import os import re import time import uuid from pathlib import Path import gradio as gr import spaces import torch import subprocess from transformers import pipeline MODEL_NAME = "NbAiLab/nb-whisper-large" MAX_AUDIO_LENGTH_SECONDS = 30 * 60 CHUNK_LENGTH_SECONDS = 28 STRIDE_LENGTH_SECONDS = 4 BATCH_SIZE = 12 SHARE = os.environ.get("SHARE", "False")[0].lower() in "ty1" AUTH_TOKEN = os.environ.get("AUTH_TOKEN") or True DEVICE_ID = 0 if torch.cuda.is_available() else -1 DEVICE_NAME = "cuda:0" if torch.cuda.is_available() else "cpu" TORCH_DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32 try: import flash_attn # noqa: F401 FLASH_ATTENTION = True except ImportError: FLASH_ATTENTION = False ATTN_IMPLEMENTATION = "flash_attention_2" if FLASH_ATTENTION else "sdpa" print(f"Bruker enhet: {DEVICE_NAME}") print(f"Attention implementation: {ATTN_IMPLEMENTATION}") def load_asr_pipeline(): return pipeline( task="automatic-speech-recognition", model=MODEL_NAME, chunk_length_s=CHUNK_LENGTH_SECONDS, stride_length_s=[STRIDE_LENGTH_SECONDS, STRIDE_LENGTH_SECONDS], device=DEVICE_ID, token=AUTH_TOKEN, torch_dtype=TORCH_DTYPE, model_kwargs={"attn_implementation": ATTN_IMPLEMENTATION}, ) ASR = load_asr_pipeline() def format_output(text: str) -> str: return re.sub(r"(\.{3,}|[.!:?])", lambda m: m.group() + "
", text) def format_timestamp(seconds) -> str: if seconds is None: return "??:??:??" return time.strftime("%H:%M:%S", time.gmtime(seconds)) def format_chunks(chunks: list[dict]) -> str: lines = [] for chunk in chunks: start, end = chunk.get("timestamp", (None, None)) start_time = format_timestamp(start) end_time = format_timestamp(end) text = chunk.get("text", "").strip() lines.append(f"[{start_time} -> {end_time}] {text}") return "
".join(lines) @spaces.GPU(duration=60 * 2) def run_asr(file_path: str, return_timestamps: bool = False, lang: str = "no") -> dict: ASR.model.config.forced_decoder_ids = ASR.tokenizer.get_decoder_prompt_ids( language=lang, task="transcribe", no_timestamps=not return_timestamps, ) return ASR( file_path, return_timestamps=return_timestamps, batch_size=BATCH_SIZE, generate_kwargs={ "task": "transcribe", "language": lang, "num_beams": 5, }, ) def get_audio_duration_seconds(file_path: str) -> float: result = subprocess.run( [ "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file_path, ], check=True, capture_output=True, text=True, ) return float(result.stdout.strip()) def truncate_audio_if_needed(file_path: str) -> tuple[str, bool, str | None]: audio_duration = get_audio_duration_seconds(file_path) if audio_duration <= MAX_AUDIO_LENGTH_SECONDS: return file_path, False, None warning_message = ( "⚠️ Advarsel: " "Lydfilen er lengre enn 30 minutter. Kun de første 30 minuttene vil bli transkribert." ) truncated_file = f"truncated_audio_{uuid.uuid4().hex}.wav" subprocess.run( [ "ffmpeg", "-y", "-i", file_path, "-t", str(MAX_AUDIO_LENGTH_SECONDS), "-ac", "1", "-ar", "16000", truncated_file, ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) return truncated_file, True, warning_message def write_transcription_file(formatted_text: str) -> str: output_file = f"transcription_{uuid.uuid4().hex}.txt" plain_text = re.sub(r"", "\n", formatted_text) plain_text = re.sub(r"<[^>]+>", "", plain_text) with open(output_file, "w", encoding="utf-8") as f: f.write(plain_text) return output_file def transcribe(file: str, return_timestamps: bool = False, lang_nn: bool = False): if not file: return None, "Ingen lydfil valgt.", None lang = "nn" if lang_nn else "no" file_to_transcribe, truncated, warning_message = truncate_audio_if_needed(file) result = run_asr( file_to_transcribe, return_timestamps=return_timestamps, lang=lang, ) if return_timestamps: formatted_text = format_chunks(result.get("chunks", [])) else: formatted_text = format_output(result.get("text", "")) if truncated: link = "https://github.com/NbAiLab/nostram/blob/main/leverandorer.md" disclaimer = ( "Dette er en demo. Det er ikke tillatt å bruke denne teksten i profesjonell sammenheng. " "Vi anbefaler at hvis du trenger å transkribere lengre opptak, så kjører du enten modellen lokalt " "eller sjekker denne siden for å se hvem som leverer løsninger basert på NB-Whisper: " f"denne siden." ) formatted_text += f"

{disclaimer}" formatted_text += "

Transkribert med NB-Whisper demo" output_file = write_transcription_file(formatted_text) if truncated and file_to_transcribe != file: Path(file_to_transcribe).unlink(missing_ok=True) return warning_message, formatted_text, output_file demo = gr.Blocks( theme=gr.themes.Default( primary_hue=gr.themes.colors.green, secondary_hue=gr.themes.colors.red, ) ) with demo: with gr.Column(): gr.HTML("") gr.Markdown("

NB-Whisper Demo

") gr.Interface( fn=transcribe, inputs=[ gr.Audio(sources=["upload", "microphone"], type="filepath"), gr.Checkbox(label="Inkluder tidskoder"), gr.Checkbox(label="Nynorsk"), ], outputs=[ gr.HTML(label="Varsel"), gr.HTML(label="Tekst"), gr.File(label="Last ned transkripsjon"), ], description=( "Demoen bruker " f"modellen [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) " "til å transkribere lydfiler opp til 30 minutter." ), allow_flagging="never", ) demo.queue().launch( server_name="0.0.0.0", server_port=7860, share=False, show_api=False, allowed_paths=["Logonew.png"], )