Update app.py
Browse files123456789101112131415161718192021228 unmodified lines313233343536373827 unmodified lines6667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615731 unmodified lines18919019119219319419519619719819920020116 unmodified lines218219220221222223224import ioimport reimport torchfrom transformers import WhisperProcessor, WhisperForConditionalGenerationimport requestsfrom bs4 import BeautifulSoupimport tempfileimport osimport soundfile as sffrom spellchecker import SpellCheckerfrom pydub import AudioSegmentimport librosaimport numpy as npfrom pyannote.audio import Pipelineimport dashfrom dash import dcc, html, Input, Output, Stateimport dash_bootstrap_components as dbcfrom dash.exceptions import PreventUpdateimport base64import threadingfrom pytube import YouTube8 unmodified linesprocessor = WhisperProcessor.from_pretrained(model_name)model = WhisperForConditionalGeneration.from_pretrained(model_name).to(device)spell = SpellChecker()def download_audio_from_url(url):try:if "youtube.com" in url or "youtu.be" in url:27 unmodified linesprint(f"Error in download_audio_from_url: {str(e)}")raisedef correct_spelling(text):words = text.split()corrected_words = [spell.correction(word) or word for word in words]return ' '.join(corrected_words)def format_transcript_with_speakers(transcript, diarization):formatted_transcript = []current_speaker = Nonefor segment, _, speaker in diarization.itertracks(yield_label=True):start = segment.startend = segment.endif speaker != current_speaker:if current_speaker is not None:formatted_transcript.append("\n") # Add a blank line between speakersformatted_transcript.append(f"Speaker {speaker}:\n")current_speaker = speakersegment_text = transcript[start:end].strip()if segment_text:formatted_transcript.append(f"{segment_text}\n")return "".join(formatted_transcript)def transcribe_audio(audio_file, pipeline):try:if pipeline is None:raise ValueError("Speaker diarization pipeline is not initialized")print("Loading audio file...")audio_input, sr = librosa.load(audio_file, sr=16000)audio_input = audio_input.astype(np.float32)print(f"Audio duration: {len(audio_input) / sr:.2f} seconds")# Apply speaker diarizationprint("Applying speaker diarization...")diarization = pipeline(audio_file)print("Speaker diarization complete.")chunk_length = 30 * sroverlap = 5 * srtranscriptions = []print("Starting transcription...")for i in range(0, len(audio_input), chunk_length - overlap):chunk = audio_input[i:i+chunk_length]input_features = processor(chunk, sampling_rate=16000, return_tensors="pt").input_features.to(device)predicted_ids = model.generate(input_features)transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)transcriptions.extend(transcription)print(f"Processed {i / sr:.2f} to {(i + chunk_length) / sr:.2f} seconds")full_transcription = " ".join(transcriptions)print(f"Transcription complete. Full transcription length: {len(full_transcription)} characters")print("Applying formatting with speaker diarization...")formatted_transcription = format_transcript_with_speakers(full_transcription, diarization)return formatted_transcriptionexcept Exception as e:print(f"Error in transcribe_audio: {str(e)}")raisedef transcribe_video(url, pipeline):try:print(f"Attempting to download audio from URL: {url}")audio_bytes = download_audio_from_url(url)print(f"Successfully downloaded {len(audio_bytes)} bytes of audio data")# Convert audio bytes to AudioSegmentaudio = AudioSegment.from_file(io.BytesIO(audio_bytes))print(f"Audio duration: {len(audio) / 1000} seconds")# Save as WAV filewith tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:audio.export(temp_audio.name, format="wav")temp_audio_path = temp_audio.nameprint("Starting audio transcription...")transcript = transcribe_audio(temp_audio_path, pipeline)print(f"Transcription completed. Transcript length: {len(transcript)} characters")# Clean up the temporary fileos.unlink(temp_audio_path)# Apply spelling correctiontranscript = correct_spelling(transcript)return transcriptexcept Exception as e:error_message = f"An error occurred: {str(e)}"31 unmodified linesdef transcribe():try:# Initialize the speaker diarization pipeline without tokenpipeline = Pipeline.from_pretrained("collinbarnwell/pyannote-speaker-diarization-31")if pipeline is None:raise ValueError("Failed to initialize the speaker diarization pipeline")print("Speaker diarization pipeline initialized successfully")transcript = transcribe_video(url, pipeline)return transcriptexcept Exception as e:return f"An error occurred: {str(e)}"16 unmodified lines]), download_dataelse:return transcript, Noneif __name__ == '__main__':print("Starting the Dash application...")app.run(debug=True, host='0.0.0.0', port=7860)1234567891011121314158 unmodified lines24252627282927 unmodified lines575859606162636465666768697071727374757677787980818283848586878889909131 unmodified lines12312412512612712812916 unmodified lines146147148149150151152153154import ioimport torchfrom transformers import WhisperProcessor, WhisperForConditionalGenerationimport requestsfrom bs4 import BeautifulSoupimport tempfileimport osfrom pydub import AudioSegmentimport dashfrom dash import dcc, html, Input, Output, Stateimport dash_bootstrap_components as dbcfrom dash.exceptions import PreventUpdateimport threadingfrom pytube import YouTube8 unmodified linesprocessor = WhisperProcessor.from_pretrained(model_name)model = WhisperForConditionalGeneration.from_pretrained(model_name).to(device)def download_audio_from_url(url):try:if "youtube.com" in url or "youtu.be" in url:27 unmodified linesprint(f"Error in download_audio_from_url: {str(e)}")raisedef transcribe_audio(audio_file):try:print("Loading audio file...")audio = AudioSegment.from_file(audio_file)audio = audio.set_channels(1).set_frame_rate(16000)audio_array = audio.get_array_of_samples()print("Starting transcription...")input_features = processor(audio_array, sampling_rate=16000, return_tensors="pt").input_features.to(device)predicted_ids = model.generate(input_features)transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)print(f"Transcription complete. Length: {len(transcription[0])} characters")return transcription[0]except Exception as e:print(f"Error in transcribe_audio: {str(e)}")raisedef transcribe_video(url):try:print(f"Attempting to download audio from URL: {url}")audio_bytes = download_audio_from_url(url)print(f"Successfully downloaded {len(audio_bytes)} bytes of audio data")with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:AudioSegment.from_file(io.BytesIO(audio_bytes)).export(temp_audio.name, format="wav")transcript = transcribe_audio(temp_audio.name)os.unlink(temp_audio.name)return transcriptexcept Exception as e:error_message = f"An error occurred: {str(e)}"31 unmodified linesdef transcribe():try:transcript = transcribe_video(url)return transcriptexcept Exception as e:return f"An error occurred: {str(e)}"16 unmodified lines]), download_dataelse:return transcript, Noneprint("Reached end of script definitions")if __name__ == '__main__':print("Starting the Dash application...")app.run(debug=True, host='0.0.0.0', port=7860)
app.py+18-88