Update app.py
Browse files21 unmodified lines22232425262728293031323335 unmodified lines6970717273747576773 unmodified lines8182838485867 unmodified lines94959697989910010110210310410528 unmodified lines1341351361371381391402 unmodified lines1431441451461471481497 unmodified lines15715815916016116216316416516616716816917017117217317417517617717817918018118218318421 unmodified lines# Load the Whisper model and processorwhisper_model_name = "openai/whisper-small"whisper_processor = WhisperProcessor.from_pretrained(whisper_model_name)whisper_model = WhisperForConditionalGeneration.from_pretrained(whisper_model_name, torch_dtype=torch.float16).to(device)# Load the Qwen model and tokenizerqwen_model_name = "Qwen/Qwen2.5-3B-Instruct"qwen_tokenizer = AutoTokenizer.from_pretrained(qwen_model_name)qwen_model = AutoModelForCausalLM.from_pretrained(qwen_model_name, torch_dtype=torch.float16).to(device)def download_audio_from_url(url):try:35 unmodified linesaudio = audio.set_channels(1).set_frame_rate(16000)audio_array = torch.tensor(audio.get_array_of_samples()).float()print("Starting transcription...")input_features = whisper_processor(audio_array, sampling_rate=16000, return_tensors="pt").input_features.to(device).to(torch.float16)predicted_ids = whisper_model.generate(input_features, language='en', task='translate')transcription = whisper_processor.batch_decode(predicted_ids, skip_special_tokens=True)print(f"Transcription complete. Length: {len(transcription[0])} characters")3 unmodified linesraisedef separate_speakers(transcription):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.7 unmodified lines"""inputs = qwen_tokenizer(prompt, return_tensors="pt").to(device)outputs = qwen_model.generate(**inputs, max_new_tokens=1000)result = qwen_tokenizer.decode(outputs[0], skip_special_tokens=True)# Extract the processed text (remove the instruction part)processed_text = result.split("Now, please process the following transcribed text:")[-1].strip()return processed_textdef transcribe_video(url):28 unmodified linesdbc.Input(id="video-url", type="text", placeholder="Enter video URL"),dbc.Button("Transcribe", id="transcribe-button", color="primary", className="mt-3"),dbc.Spinner(html.Div(id="transcription-output", className="mt-3")),dcc.Download(id="download-transcript")])])], width=12)2 unmodified lines@app.callback(Output("transcription-output", "children"),Output("download-transcript", "data"),Input("transcribe-button", "n_clicks"),State("video-url", "value"),prevent_initial_call=True7 unmodified linestranscript = transcribe_video(url)return transcriptexcept Exception as e:return f"An error occurred: {str(e)}"# Run transcription in a separate threadthread = threading.Thread(target=transcribe)thread.start()thread.join()transcript = thread.result if hasattr(thread, 'result') else "Transcription failed"if transcript and not transcript.startswith("An error occurred"):download_data = dict(content=transcript, filename="transcript.txt")return dbc.Card([dbc.CardBody([html.H5("Transcription Result with Speaker Separation"),html.Pre(transcript, style={"white-space": "pre-wrap", "word-wrap": "break-word"}),dbc.Button("Download Transcript", id="btn-download", color="secondary", className="mt-3")])]), download_dataelse:return transcript, Noneprint("Reached end of script definitions")if __name__ == '__main__':print("Starting the Dash application...")21 unmodified lines22232425262728293031323335 unmodified lines697071727374757677783 unmodified lines828384858687887 unmodified lines9697989910010110210310410510610710810928 unmodified lines1381391401411421431441451461472 unmodified lines1501511521531541551567 unmodified lines16416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320421 unmodified lines# Load the Whisper model and processorwhisper_model_name = "openai/whisper-small"whisper_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-3B-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:35 unmodified linesaudio = audio.set_channels(1).set_frame_rate(16000)audio_array = torch.tensor(audio.get_array_of_samples()).float()print(f"Audio duration: {len(audio) / 1000:.2f} seconds")print("Starting transcription...")input_features = whisper_processor(audio_array, sampling_rate=16000, return_tensors="pt").input_features.to(device)predicted_ids = whisper_model.generate(input_features)transcription = whisper_processor.batch_decode(predicted_ids, skip_special_tokens=True)print(f"Transcription complete. Length: {len(transcription[0])} characters")3 unmodified linesraisedef separate_speakers(transcription):print("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.7 unmodified lines"""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 the processed text (remove the instruction part)processed_text = result.split("Now, please process the following transcribed text:")[-1].strip()print("Speaker separation complete.")return processed_textdef transcribe_video(url):28 unmodified linesdbc.Input(id="video-url", type="text", placeholder="Enter video URL"),dbc.Button("Transcribe", id="transcribe-button", color="primary", className="mt-3"),dbc.Spinner(html.Div(id="transcription-output", className="mt-3")),html.Div([dbc.Button("Download Transcript", id="download-button", color="secondary", className="mt-3", style={'display': 'none'}),dcc.Download(id="download-transcript")])])])], width=12)2 unmodified lines@app.callback(Output("transcription-output", "children"),Output("download-button", "style"),Input("transcribe-button", "n_clicks"),State("video-url", "value"),prevent_initial_call=True7 unmodified linestranscript = transcribe_video(url)return transcriptexcept Exception as e:import tracebackreturn f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"# 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 = thread.result if hasattr(thread, 'result') else "Transcription failed"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'}else:return transcript, {'display': 'none'}@app.callback(Output("download-transcript", "data"),Input("download-button", "n_clicks"),State("transcription-output", "children"),prevent_initial_call=True)def download_transcript(n_clicks, transcription_output):if not transcription_output:raise PreventUpdatetranscript = transcription_output['props']['children'][0]['props']['children'][1]['props']['children']return dict(content=transcript, filename="transcript.txt")if __name__ == '__main__':print("Starting the Dash application...")
app.py+36-16