import os import streamlit as st from youtube_transcript_api import YouTubeTranscriptApi import requests from langchain_openai import ChatOpenAI from langchain.schema import HumanMessage, SystemMessage from langchain.callbacks.base import BaseCallbackHandler from dotenv import load_dotenv import time # Load environment variables load_dotenv() # Page configuration st.set_page_config( page_title="YouTube Video Chat", page_icon="🎥", layout="wide" ) # Define supported languages languages = [ "English", "Hindi", "Gujarati", "Bengali", "Tamil", "Telugu", "Kannada", "Malayalam", "Punjabi", "Marathi", "Urdu", "Assamese", "Odia", "Sanskrit", "Korean", "Japanese", "Arabic", "French", "German", "Spanish", "Portuguese", "Russian", "Chinese", "Vietnamese", "Thai", "Indonesian", "Turkish", "Polish", "Ukrainian", "Dutch", "Italian", "Greek", "Hebrew", "Persian", "Swedish", "Norwegian", "Danish", "Finnish", "Czech", "Hungarian", "Romanian", "Bulgarian", "Croatian", "Serbian", "Slovak", "Slovenian", "Estonian", "Latvian", "Lithuanian", "Malay", "Tagalog", "Swahili" ] # YouTube transcript configuration def extract_video_id(url): """Extract video ID from YouTube URL""" import re patterns = [ r'(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&\n?#]+)', r'youtube\.com\/v\/([^&\n?#]+)', r'youtube\.com\/watch\?.*v=([^&\n?#]+)' ] for pattern in patterns: match = re.search(pattern, url) if match: return match.group(1) return None # Streaming callback handler class StreamHandler(BaseCallbackHandler): def __init__(self, container, initial_text=""): self.container = container self.text = initial_text self.run_id_ignore_token = None def on_llm_new_token(self, token: str, **kwargs): self.text += token self.container.markdown(self.text) # Initialize the ChatOpenAI model - base instance for caching @st.cache_resource def get_base_chat_model(api_key): return ChatOpenAI( api_key=api_key, base_url="https://api.two.ai/v2", model="sutra-v2", temperature=0.7, ) # Create a streaming version of the model with callback handler def get_streaming_chat_model(api_key, callback_handler=None): return ChatOpenAI( api_key=api_key, base_url="https://api.two.ai/v2", model="sutra-v2", temperature=0.7, streaming=True, callbacks=[callback_handler] if callback_handler else None ) # Function to get YouTube transcript with fallback options @st.cache_data def get_youtube_transcript(url): try: # Extract video ID from URL video_id = extract_video_id(url) if not video_id: raise Exception("Invalid YouTube URL. Please check the URL format.") # Try different methods to get transcript transcript_text = "" try: # Method 1: Try with default settings transcript_list = YouTubeTranscriptApi.get_transcript(video_id) for segment in transcript_list: transcript_text += segment['text'] + " " except Exception as e1: try: # Method 2: Try with different language codes transcript_list = YouTubeTranscriptApi.get_transcript(video_id, languages=['en', 'en-US', 'en-GB']) for segment in transcript_list: transcript_text += segment['text'] + " " except Exception as e2: try: # Method 3: Try to get available transcripts transcript_list = YouTubeTranscriptApi.list_transcripts(video_id) # Get the first available transcript transcript = transcript_list.find_transcript(['en']) transcript_data = transcript.fetch() for segment in transcript_data: transcript_text += segment.text + " " except Exception as e3: # If all methods fail, provide helpful error message error_msg = str(e1) if "IP" in error_msg or "blocked" in error_msg.lower(): raise Exception("YouTube is blocking requests from this server. This is common on cloud platforms. Please try again later or use a different video.") elif "No transcript available" in error_msg: raise Exception("This video doesn't have captions/transcripts available.") elif "Video unavailable" in error_msg: raise Exception("This video is unavailable or private.") else: raise Exception(f"Failed to get transcript: {error_msg}") return transcript_text.strip() except Exception as e: st.error(f"Error getting transcript: {str(e)}") raise # Sidebar configuration st.sidebar.image("https://framerusercontent.com/images/3Ca34Pogzn9I3a7uTsNSlfs9Bdk.png", use_container_width=True) with st.sidebar: st.markdown("### 🎥 YouTube Video Chat") # API Keys section in expander with st.expander("🔑 API Keys", expanded=False): st.markdown("Get your free API key from:") st.markdown("- [SUTRA API](https://www.two.ai/sutra/api)") sutra_api_key = st.text_input("SUTRA API Key:", type="password") # Language selector selected_language = st.selectbox("🌐 Chat Language:", languages) # YouTube URL input st.markdown("### 📺 Video Input") youtube_url = st.text_input("YouTube URL:") # Note about deployment limitations with st.expander("ℹ️ Deployment Note", expanded=False): st.info(""" **Note:** When deployed on cloud platforms, YouTube may block transcript requests due to IP restrictions. This is a limitation of the YouTube Transcript API, not the app itself. If you encounter blocking errors, try: - Using a different video - Waiting a few minutes before retrying - Testing locally where this limitation doesn't apply """) # Get Transcript button if youtube_url: if st.button("🎬 Get Video Transcript", use_container_width=True): st.session_state.transcription_status = "processing" try: # Get transcript directly transcript_text = get_youtube_transcript(youtube_url) st.session_state.transcript = transcript_text st.session_state.transcription_status = "completed" st.success("Transcript retrieved successfully!") st.rerun() except Exception as e: error_msg = str(e) if "blocking" in error_msg.lower() or "ip" in error_msg.lower(): st.error("⚠️ YouTube is blocking requests from this server (common on cloud platforms).") st.info("💡 **Solutions:**") st.info("• Try again in a few minutes") st.info("• Use a different YouTube video") st.info("• Try from a local environment") else: st.error(f"Error: {error_msg}") st.session_state.transcription_status = "error" st.rerun() st.divider() st.markdown(f"**Current Language:** {selected_language}") # Main content st.markdown( f'