Update app.py
Browse files2 unmodified lines3456787 unmodified lines16171819202122232425264 unmodified lines313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979843 unmodified lines1421431441451461471 unmodified line1491501511521531541551561571581591 unmodified line16116216316416516610 unmodified lines1771781791801811822 unmodified linesimport tempfileimport threadingimport base64from urllib.parse import urlparseimport dash7 unmodified linesimport google.generativeai as genaifrom moviepy.editor import VideoFileClip# Initialize the Dash appapp = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])# Retrieve the Google API key from Hugging Face SpacesGOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")genai.configure(api_key=GOOGLE_API_KEY)# Initialize Gemini model4 unmodified linesresult = urlparse(url)return all([result.scheme, result.netloc])except ValueError:return Falsedef download_media(url):if "youtube.com" in url or "youtu.be" in url:yt = YouTube(url)stream = yt.streams.filter(progressive=True, file_extension='mp4').first()with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_file:stream.download(output_path=os.path.dirname(temp_file.name), filename=temp_file.name)return temp_file.nameelse:response = requests.get(url)content_type = response.headers.get('content-type', '')if 'video' in content_type:suffix = '.mp4'elif 'audio' in content_type:suffix = '.mp3'else:suffix = ''with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:temp_file.write(response.content)return temp_file.namedef extract_audio(file_path):video = VideoFileClip(file_path)audio = video.audioaudio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")audio.write_audiofile(audio_file.name)video.close()audio.close()return audio_file.namedef transcribe_audio(file_path):with open(file_path, "rb") as audio_file:audio_data = audio_file.read()response = model.generate_content(audio_data)return response.textdef process_media(contents, filename, url):if contents:content_type, content_string = contents.split(',')decoded = base64.b64decode(content_string)suffix = os.path.splitext(filename)[1]with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:temp_file.write(decoded)temp_file_path = temp_file.nameelif url:temp_file_path = download_media(url)else:raise ValueError("No input provided")try:if temp_file_path.lower().endswith(('.mp4', '.avi', '.mov', '.flv', '.wmv')):audio_file_path = extract_audio(temp_file_path)transcript = transcribe_audio(audio_file_path)os.unlink(audio_file_path)else:transcript = transcribe_audio(temp_file_path)finally:os.unlink(temp_file_path)return transcriptapp.layout = dbc.Container([html.H1("Audio/Video Transcription App", className="text-center my-4"),43 unmodified linestry:return process_media(contents, filename, url)except Exception as e:return f"An error occurred: {str(e)}"thread = threading.Thread(target=transcribe)1 unmodified linethread.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"),1 unmodified line])]), {'display': 'block'}else:return transcript, {'display': 'none'}@app.callback(10 unmodified linesreturn dict(content=transcript, filename="transcript.txt")if __name__ == '__main__':print("Starting the Dash application...")app.run(debug=True, host='0.0.0.0', port=7860)print("Dash application has finished running.")2 unmodified lines34567897 unmodified lines171819202122232425262728293031323334354 unmodified lines40414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313443 unmodified lines1781791801811821831841 unmodified line1861871881891901911921931941951961971981 unmodified line20020120220320420520610 unmodified lines2172182192202212222 unmodified linesimport tempfileimport threadingimport base64import loggingfrom urllib.parse import urlparseimport dash7 unmodified linesimport google.generativeai as genaifrom moviepy.editor import VideoFileClip# Set up logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# Initialize the Dash appapp = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])# Retrieve the Google API key from Hugging Face SpacesGOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")if not GOOGLE_API_KEY:logger.error("GOOGLE_API_KEY not found in environment variables")raise ValueError("GOOGLE_API_KEY not set")genai.configure(api_key=GOOGLE_API_KEY)# Initialize Gemini model4 unmodified linesresult = urlparse(url)return all([result.scheme, result.netloc])except ValueError:logger.error(f"Invalid URL: {url}")return Falsedef download_media(url):logger.info(f"Attempting to download media from URL: {url}")try:if "youtube.com" in url or "youtu.be" in url:yt = YouTube(url)stream = yt.streams.filter(progressive=True, file_extension='mp4').first()with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_file:stream.download(output_path=os.path.dirname(temp_file.name), filename=temp_file.name)logger.info(f"YouTube video downloaded: {temp_file.name}")return temp_file.nameelse:response = requests.get(url)content_type = response.headers.get('content-type', '')if 'video' in content_type:suffix = '.mp4'elif 'audio' in content_type:suffix = '.mp3'else:suffix = ''with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:temp_file.write(response.content)logger.info(f"Media downloaded: {temp_file.name}")return temp_file.nameexcept Exception as e:logger.error(f"Error downloading media: {str(e)}")raisedef extract_audio(file_path):logger.info(f"Extracting audio from video: {file_path}")try:video = VideoFileClip(file_path)audio = video.audioaudio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")audio.write_audiofile(audio_file.name)video.close()audio.close()logger.info(f"Audio extracted: {audio_file.name}")return audio_file.nameexcept Exception as e:logger.error(f"Error extracting audio: {str(e)}")raisedef transcribe_audio(file_path):logger.info(f"Transcribing audio: {file_path}")try:with open(file_path, "rb") as audio_file:audio_data = audio_file.read()response = model.generate_content(audio_data)logger.info("Transcription completed successfully")return response.textexcept Exception as e:logger.error(f"Error during transcription: {str(e)}")raisedef process_media(contents, filename, url):logger.info("Starting media processing")try:if contents:content_type, content_string = contents.split(',')decoded = base64.b64decode(content_string)suffix = os.path.splitext(filename)[1]with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:temp_file.write(decoded)temp_file_path = temp_file.namelogger.info(f"File uploaded: {temp_file_path}")elif url:temp_file_path = download_media(url)else:logger.error("No input provided")raise ValueError("No input provided")if temp_file_path.lower().endswith(('.mp4', '.avi', '.mov', '.flv', '.wmv')):logger.info("Video file detected, extracting audio")audio_file_path = extract_audio(temp_file_path)transcript = transcribe_audio(audio_file_path)os.unlink(audio_file_path)else:logger.info("Audio file detected, transcribing directly")transcript = transcribe_audio(temp_file_path)os.unlink(temp_file_path)return transcriptexcept Exception as e:logger.error(f"Error in process_media: {str(e)}")raiseapp.layout = dbc.Container([html.H1("Audio/Video Transcription App", className="text-center my-4"),43 unmodified linestry:return process_media(contents, filename, url)except Exception as e:logger.error(f"Transcription failed: {str(e)}")return f"An error occurred: {str(e)}"thread = threading.Thread(target=transcribe)1 unmodified linethread.join(timeout=600) # 10 minutes timeoutif thread.is_alive():logger.warning("Transcription timed out after 10 minutes")return "Transcription timed out after 10 minutes", {'display': 'none'}transcript = getattr(thread, 'result', "Transcription failed")if transcript and not transcript.startswith("An error occurred"):logger.info("Transcription successful")return dbc.Card([dbc.CardBody([html.H5("Transcription Result"),1 unmodified line])]), {'display': 'block'}else:logger.error(f"Transcription failed: {transcript}")return transcript, {'display': 'none'}@app.callback(10 unmodified linesreturn dict(content=transcript, filename="transcript.txt")if __name__ == '__main__':logger.info("Starting the Dash application...")app.run(debug=True, host='0.0.0.0', port=7860)logger.info("Dash application has finished running.")
app.py+86-46