Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296# main.pyimport streamlit as stimport osimport tempfileimport whisperimport yt_dlpfrom dotenv import load_dotenvfrom config import Configfrom transcript_utils import extract_video_id, fetch_transcriptfrom vector_utils import build_vector_store, get_retrieverfrom qa_pipeline import run_qafrom youtube_transcript_api import YouTubeTranscriptApifrom youtube_transcript_api._errors import TranscriptsDisabled, NoTranscriptFound, VideoUnavailable# Load environment variablesload_dotenv()st.set_page_config(page_title="YouTube Video Chat-QA", layout="centered")st.title("π₯ YouTube Video Chat-QA App")# Initialize session stateif 'ready' not in st.session_state:st.session_state.ready = Falseif 'messages' not in st.session_state:st.session_state.messages = []if 'transcript_method' not in st.session_state:st.session_state.transcript_method = None@st.cache_resourcedef load_whisper_model():"""Load Whisper model with caching for better performance"""try:return whisper.load_model("base")except Exception as e:st.error(f"Failed to load Whisper model: {str(e)}")return Nonedef download_audio_from_youtube(video_id):"""Download audio from YouTube video using yt-dlp with better error handling"""try:# Create temporary directorytemp_dir = tempfile.mkdtemp()output_path = os.path.join(temp_dir, f"{video_id}.%(ext)s")ydl_opts = {'format': 'bestaudio/best','outtmpl': output_path,'extractaudio': True,'audioformat': 'mp3','noplaylist': True,'no_warnings': True,'quiet': True,# Add user agent to avoid bot detection'http_headers': {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'},# Add retries for network issues'retries': 3,'socket_timeout': 30,}with yt_dlp.YoutubeDL(ydl_opts) as ydl:url = f"https://www.youtube.com/watch?v={video_id}"info = ydl.extract_info(url, download=True)# Find the downloaded filefor file in os.listdir(temp_dir):if file.startswith(video_id):return os.path.join(temp_dir, file)return Noneexcept Exception as e:st.error(f"Audio download failed: {str(e)}")return Nonedef transcribe_with_whisper(video_id):"""Fallback transcription using Whisper when YouTube transcript fails"""try:# Load Whisper modelmodel = load_whisper_model()if not model:return None# Download audioaudio_file = download_audio_from_youtube(video_id)if not audio_file:return None# Transcribe using Whisperwith st.spinner("π€ Transcribing audio using AI (this may take a few minutes)..."):result = model.transcribe(audio_file)# Clean up audio filetry:os.remove(audio_file)os.rmdir(os.path.dirname(audio_file))except:pass# Convert to transcript format compatible with your existing codeif result and result.get("text"):transcript = [{"text": result["text"],"start": 0,"duration": len(result["text"].split()) * 0.5}]return transcriptreturn Noneexcept Exception as e:st.error(f"Whisper transcription failed: {str(e)}")return Nonedef enhanced_fetch_transcript(video_id, languages=None):"""Enhanced transcript fetching with multiple fallback methods"""transcript = Nonemethod_used = None# Method 1: Try YouTube Transcript API first (CORRECTED)try:# CORRECT: Call static method directly, not as instancetranscript = YouTubeTranscriptApi.get_transcript(video_id,languages=languages or ['en', 'hi', 'auto-generated'])method_used = "YouTube API"st.success("β Transcript fetched from YouTube")except (TranscriptsDisabled, NoTranscriptFound, VideoUnavailable) as e:st.warning("β οΈ YouTube transcript not available. Trying alternative method...")# Method 2: Try with different language codestry:transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en'])method_used = "YouTube API (English only)"st.success("β English transcript found")except:passexcept Exception as e:st.warning(f"β οΈ YouTube API error: {str(e)}")# Method 3: Fallback to Whisper transcription (only if network allows)if not transcript:st.info("π Attempting AI transcription as fallback...")transcript = transcribe_with_whisper(video_id)if transcript:method_used = "Whisper AI"st.success("β Transcript generated using AI")return transcript, method_used# Setup section for video linkwith st.expander("π Setup Video", expanded=not st.session_state.ready):st.markdown("Enter a YouTube video URL to start chatting about its content:")url = st.text_input("YouTube Video Link", key='input_url', placeholder="https://www.youtube.com/watch?v=...")col1, col2 = st.columns(2)with col1:if st.button("π Submit Link", type="primary"):if not url:st.error("Please enter a YouTube URL")else:vid = extract_video_id(url)if not vid:st.error("β Invalid YouTube URL. Please check and try again.")else:st.session_state.video_id = vidst.session_state.ready = Truest.session_state.messages = []st.rerun()with col2:if st.button("π Reset"):for key in ['ready', 'video_id', 'messages', 'input_url', 'transcript_method']:if key in st.session_state:del st.session_state[key]st.rerun()# Chat interface after video is readydef chat_interface():st.markdown("---")# Display videotry:st.video(f"https://www.youtube.com/watch?v={st.session_state.video_id}")except Exception as e:st.error(f"Error displaying video: {str(e)}")# Show transcript method if availableif st.session_state.get('transcript_method'):st.info(f"π Transcript source: {st.session_state.transcript_method}")# Display chat history firstfor msg in st.session_state.messages:with st.chat_message(msg['role']):st.write(msg['content'])# Input new messagenew_q = st.chat_input("π¬ Ask a question about this video...")if new_q:# Add user messagest.session_state.messages.append({'role': 'user', 'content': new_q})# Display user message immediatelywith st.chat_message("user"):st.write(new_q)# Process the questionwith st.chat_message("assistant"):with st.spinner("π Analyzing video content..."):# Get transcript using enhanced methodtranscript, method_used = enhanced_fetch_transcript(st.session_state.video_id,languages=["en", "hi"])# Store the method usedif method_used:st.session_state.transcript_method = method_usedif not transcript:error_msg = """β **Unable to obtain transcript for this video.**This could be due to:- Network connectivity issues in the deployment environment- YouTube's restrictions on cloud platforms (common on Hugging Face Spaces)- Video has no available transcripts/captions- The video is private or restricted**Suggestions:**- Try a different video with verified captions- Use videos from educational channels (usually have transcripts)- Test locally if possible"""st.markdown(error_msg)st.session_state.messages.append({'role': 'assistant','content': error_msg})else:try:# Build vector store and get answervector_store = build_vector_store(transcript, None, Config.EMBEDDING_MODEL)retriever = get_retriever(vector_store)answer = run_qa(retriever, new_q)# Display answerst.write(answer)st.session_state.messages.append({'role': 'assistant', 'content': answer})except Exception as e:error_msg = f"β Error processing your question: {str(e)}"st.error(error_msg)st.session_state.messages.append({'role': 'assistant','content': error_msg})# Main app logicif st.session_state.ready:chat_interface()else:# Welcome messagest.markdown("""### π Welcome to YouTube Video Chat-QA!This app allows you to:- πΊ Load any YouTube video- π¬ Ask questions about the video content- π€ Get AI-powered answers based on the video transcript**β οΈ Note for Hugging Face Spaces users:**Due to network restrictions, some features may be limited. The app works best with:- Educational videos with clear captions- Popular videos from established channels- Videos with manual (not auto-generated) transcripts""")# Sidebar with informationwith st.sidebar:st.markdown("### βΉοΈ App Status")st.markdown("""**Network Status:**- β οΈ Limited connectivity (Cloud environment)- β YouTube Transcript API (when available)- β Whisper AI (Network restricted)""")if st.session_state.ready:st.markdown(f"**Current Video ID:** `{st.session_state.video_id}`")if st.session_state.get('transcript_method'):st.markdown(f"**Transcript Method:** {st.session_state.transcript_method}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# main.pyimport streamlit as stfrom dotenv import load_dotenvfrom config import Configfrom transcript_utils import extract_video_id, fetch_transcriptfrom vector_utils import build_vector_store, get_retrieverfrom qa_pipeline import run_qa# Load environment variablesload_dotenv()st.set_page_config(page_title="YouTube Video Chat-QA", layout="centered")st.title("YouTube Video Chat-QA App")# Initialize session stateif 'ready' not in st.session_state:st.session_state.ready = Falseif 'messages' not in st.session_state:st.session_state.messages = []# Setup section for video linkwith st.expander("Setup Video", expanded=not st.session_state.ready):url = st.text_input("YouTube Video Link", key='input_url')if st.button("Submit Link"):vid = extract_video_id(url)if not vid:st.error("Invalid YouTube URL.")else:st.session_state.video_id = vidst.session_state.ready = True# Chat interface after video is readydef chat_interface():st.video(f"https://www.youtube.com/watch?v={st.session_state.video_id}")# Input new messagenew_q = st.chat_input("Ask a question about this video...")if new_q:st.session_state.messages.append({'role': 'user', 'content': new_q})transcript = fetch_transcript(st.session_state.video_id, languages=["en", "hi"])if not transcript:st.session_state.messages.append({'role': 'assistant', 'content': "Transcript not available."})else:vector_store = build_vector_store(transcript, None, Config.EMBEDDING_MODEL)retriever = get_retriever(vector_store)answer = run_qa(retriever, new_q)st.session_state.messages.append({'role': 'assistant', 'content': answer})# Display chat historyfor msg in st.session_state.messages:st.chat_message(msg['role']).write(msg['content'])if st.button("Exit Chat"):for key in ['ready', 'video_id', 'messages', 'input_url']:if key in st.session_state:del st.session_state[key]if st.session_state.ready:chat_interface()
app.py+30-268