Update app.py
Browse files12345610 unmodified lines171819202122237 unmodified lines313233343536373839404150 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301319 unmodified lines1411421431441451461471481491501511521531541551561571584 unmodified lines16316416516616716816917020 unmodified lines1911921931941951961971981992002012026 unmodified lines209210211212213214215import ioimport torchfrom transformers import WhisperProcessor, WhisperForConditionalGeneration, AutoTokenizer, AutoModelForCausalLMimport requestsfrom bs4 import BeautifulSoupimport tempfile10 unmodified linesimport numpy as np# Set up logginglogging.basicConfig(level=logging.DEBUG)logger = logging.getLogger(__name__)print("Script started")7 unmodified lineswhisper_processor = WhisperProcessor.from_pretrained(whisper_model_name)whisper_model = WhisperForConditionalGeneration.from_pretrained(whisper_model_name).to(device)# Load the Qwen model and tokenizerqwen_model_name = "Qwen/Qwen2.5-1.5B-Instruct"qwen_tokenizer = AutoTokenizer.from_pretrained(qwen_model_name, trust_remote_code=True)qwen_model = AutoModelForCausalLM.from_pretrained(qwen_model_name, trust_remote_code=True).to(device)def download_audio_from_url(url):try:if "youtube.com" in url or "youtu.be" in url:50 unmodified linesfull_transcription = " ".join(transcriptions)logger.info(f"Transcription complete. Full transcription length: {len(full_transcription)} characters")logger.info("Applying speaker separation using Qwen...")separated_transcript = separate_speakers(full_transcription)return separated_transcriptexcept Exception as e:logger.error(f"Error in transcribe_audio: {str(e)}")raisedef separate_speakers(transcription):logger.info("Starting speaker separation...")prompt = f"""Analyze the following transcribed text and separate it into different speakers. Identify potential speaker changes based on context, content shifts, or dialogue patterns. Format the output as follows:1. Label speakers as "Speaker 1", "Speaker 2", etc.2. Start each speaker's text on a new line beginning with their label.3. Separate different speakers' contributions with a blank line.4. If the same speaker continues, do not insert a blank line or repeat the speaker label.5. Do not include any additional explanations or metadata.Now, please process the following transcribed text:{transcription}"""inputs = qwen_tokenizer(prompt, return_tensors="pt").to(device)with torch.no_grad():outputs = qwen_model.generate(**inputs, max_new_tokens=4000)result = qwen_tokenizer.decode(outputs[0], skip_special_tokens=True)# Extract only the processed text (remove the instruction part)processed_text = result.split("Now, please process the following transcribed text:")[-1].strip()logger.info("Speaker separation complete.")return processed_textdef transcribe_video(url):try:logger.info(f"Attempting to download audio from URL: {url}")9 unmodified linesif len(transcript) < 10:raise ValueError("Transcription too short, possibly failed")logger.info("Separating speakers...")try:diarized_transcript = separate_speakers(transcript)logger.info(f"Speaker separation complete. Result length: {len(diarized_transcript)} characters")if len(diarized_transcript) < 10:logger.warning("Speaker separation result too short, using original transcript")return transcriptreturn diarized_transcriptexcept Exception as e:logger.error(f"Error during speaker separation: {str(e)}")logger.info("Returning original transcript without speaker separation")return transcriptexcept Exception as e:error_message = f"An error occurred: {str(e)}"logger.error(error_message)4 unmodified linesapp.layout = dbc.Container([dbc.Row([dbc.Col([html.H1("Video Transcription with Speaker Separation", className="text-center mb-4"),html.Div("If you can see this, the app is working!", className="text-center mb-4"), # Debug elementdbc.Card([dbc.CardBody([dbc.Input(id="video-url", type="text", placeholder="Enter video URL"),20 unmodified linesif not url:raise PreventUpdatetranscript = transcribe_video(url)if transcript and not transcript.startswith("An error occurred"):return dbc.Card([dbc.CardBody([html.H5("Transcription Result with Speaker Separation"),html.Pre(transcript, style={"white-space": "pre-wrap", "word-wrap": "break-word"})])]), {'display': 'block'}6 unmodified linesState("transcription-output", "children"),prevent_initial_call=True)def download_transcript(n_clicks, transcription_output):if not transcription_output:raise PreventUpdate12345610 unmodified lines171819202122237 unmodified lines31323334353650 unmodified lines87888990919293949596979 unmodified lines1071081091101111121134 unmodified lines11811912012112212312412520 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721736 unmodified lines180181182183184185import ioimport torchfrom transformers import WhisperProcessor, WhisperForConditionalGenerationimport requestsfrom bs4 import BeautifulSoupimport tempfile10 unmodified linesimport numpy as np# Set up logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)print("Script started")7 unmodified lineswhisper_processor = WhisperProcessor.from_pretrained(whisper_model_name)whisper_model = WhisperForConditionalGeneration.from_pretrained(whisper_model_name).to(device)def download_audio_from_url(url):try:if "youtube.com" in url or "youtu.be" in url:50 unmodified linesfull_transcription = " ".join(transcriptions)logger.info(f"Transcription complete. Full transcription length: {len(full_transcription)} characters")return full_transcriptionexcept Exception as e:logger.error(f"Error in transcribe_audio: {str(e)}")raisedef transcribe_video(url):try:logger.info(f"Attempting to download audio from URL: {url}")9 unmodified linesif len(transcript) < 10:raise ValueError("Transcription too short, possibly failed")return transcriptexcept Exception as e:error_message = f"An error occurred: {str(e)}"logger.error(error_message)4 unmodified linesapp.layout = dbc.Container([dbc.Row([dbc.Col([html.H1("Video Transcription", className="text-center mb-4"),html.Div("If you can see this, the app is working!", className="text-center mb-4"),dbc.Card([dbc.CardBody([dbc.Input(id="video-url", type="text", placeholder="Enter video URL"),20 unmodified linesif not url:raise PreventUpdatedef transcribe():try:transcript = transcribe_video(url)return transcriptexcept Exception as e:logger.exception("Error in transcription:")return f"An error occurred: {str(e)}"# Run transcription in a separate threadthread = threading.Thread(target=transcribe)thread.start()thread.join(timeout=600) # 10 minutes timeoutif thread.is_alive():return "Transcription timed out after 10 minutes", {'display': 'none'}transcript = getattr(thread, 'result', "Transcription failed")if transcript and not transcript.startswith("An error occurred"):return dbc.Card([dbc.CardBody([html.H5("Transcription Result"),html.Pre(transcript, style={"white-space": "pre-wrap", "word-wrap": "break-word"})])]), {'display': 'block'}6 unmodified linesState("transcription-output", "children"),prevent_initial_call=True)def download_transcript(n_clicks, transcription_output):if not transcription_output:raise PreventUpdate
app.py+24-54