Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import streamlit as stfrom youtube_transcript_api import YouTubeTranscriptApifrom youtube_transcript_api.formatters import SRTFormatter# Function to get captions using youtube-transcript-apidef get_youtube_captions(youtube_url):"""Retrieves YouTube video captions using youtube-transcript-api.Parameters:- youtube_url: The URL of the YouTube video.Returns:- The captions of the video in SRT format, or a message if captions are not available."""# Extract video ID from YouTube URL (for both regular videos and Shorts)if "si=" in youtube_url:# For YouTube Shorts or URLs with "si=", extract the video ID after "si="video_id = youtube_url.split("si=")[-1].split("?")[0]else:# For regular YouTube videos, extract the video ID after "v="video_id = youtube_url.split("v=")[-1].split("&")[0]# Print extracted video ID for debuggingprint(f"Extracted Video ID: {video_id}")try:# Fetch transcript for the videotranscript = YouTubeTranscriptApi.get_transcript(video_id)# Format the transcript in SRT formatformatter = SRTFormatter()formatted_transcript = formatter.format_transcript(transcript)return formatted_transcriptexcept Exception as e:return f"Error: {str(e)}"# YouTube video URL inputyoutube_url = st.text_input("Enter the YouTube video link",placeholder="Paste the YouTube video URL here",help="Provide the link to the YouTube video you want to summarize.")if youtube_url:# Clean URL before passing to the function (remove extra parts)youtube_url_cleaned = youtube_url.split("?")[0] # Remove URL parameterstry:with st.spinner("Fetching and processing the YouTube video..."):# Get captions using youtube-transcript-apicaptions = get_youtube_captions(youtube_url_cleaned)# Check if captions are availableif "Error" not in captions:# Display captionsst.subheader("Video Captions:")st.text(captions)else:st.error(captions)except Exception as e:st.error(f"An error occurred: {e}")else:st.info("Enter a YouTube video link to begin analysis.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import streamlit as stfrom phi.agent import Agentfrom phi.model.google import Geminifrom phi.tools.duckduckgo import DuckDuckGofrom google.generativeai import upload_file, get_fileimport google.generativeai as genaiimport timefrom pathlib import Pathimport tempfilefrom dotenv import load_dotenvimport osfrom pytube import YouTube # Import pytube for downloading YouTube videosload_dotenv()API_KEY = os.getenv("GOOGLE_API_KEY")if API_KEY:genai.configure(api_key=API_KEY)# Page configurationst.set_page_config(page_title="Multimodal AI Agent- Video Summarizer",page_icon="🎥",layout="wide")st.title("Phidata Video AI Summarizer Agent 🎥🎤🖬")st.header("Powered by Gemini 2.0 Flash Exp")@st.cache_resourcedef initialize_agent():return Agent(name="Video AI Summarizer",model=Gemini(id="gemini-2.0-flash-exp"),tools=[DuckDuckGo()],markdown=True,)# Initialize the agentmultimodal_Agent = initialize_agent()# YouTube video URL inputvideo_url = st.text_input("Enter a YouTube video URL",help="Paste a YouTube video link for AI analysis")if video_url:try:# Download the YouTube videoyt = YouTube(video_url)video_stream = yt.streams.filter(progressive=True, file_extension='mp4').first()# Create a temporary file to save the videowith tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as temp_video:video_stream.download(output_path=temp_video.name)video_path = temp_video.namest.video(video_path, format="video/mp4", start_time=0)user_query = st.text_area("What insights are you seeking from the video?",placeholder="Ask anything about the video content. The AI agent will analyze and gather additional context if needed.",help="Provide specific questions or insights you want from the video.")if st.button("🔍 Analyze Video", key="analyze_video_button"):if not user_query:st.warning("Please enter a question or insight to analyze the video.")else:try:with st.spinner("Processing video and gathering insights..."):# Upload and process the video fileprocessed_video = upload_file(video_path)while processed_video.state.name == "PROCESSING":time.sleep(1)processed_video = get_file(processed_video.name)# Prompt generation for analysisanalysis_prompt = (f"""Analyze the uploaded video for content and context.Respond to the following query using video insights and supplementary web research:{user_query}Provide a detailed, user-friendly, and actionable response.""")# AI agent processingresponse = multimodal_Agent.run(analysis_prompt, videos=[processed_video])# Display the resultst.subheader("Analysis Result")st.markdown(response.content)except Exception as error:st.error(f"An error occurred during analysis: {error}")finally:# Clean up temporary video filePath(video_path).unlink(missing_ok=True)except Exception as e:st.error(f"Error downloading YouTube video: {e}")else:st.info("Paste a YouTube video URL to begin analysis.")
app.py+92-53