Update app.py
Browse files1234567891011121314153 unmodified lines1920212223242526272829303132333 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import 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()3 unmodified lines# 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(3 unmodified linesmarkdown=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.")1234567891011121314153 unmodified lines1920212223242526272829303132333 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import streamlit as stimport reimport requestsfrom youtube_transcript_api import YouTubeTranscriptApifrom 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 dotenv import load_dotenvimport osload_dotenv()3 unmodified lines# Page configurationst.set_page_config(page_title="Video Summarizer with Transcript Extraction",page_icon="π₯",layout="wide")st.title("Video AI Summarizer with Transcript π₯π€π¬")st.header("Powered by Gemini 2.0 Flash Exp")# Initialize the agent@st.cache_resourcedef initialize_agent():return Agent(3 unmodified linesmarkdown=True,)multimodal_Agent = initialize_agent()# YouTube URL inputvideo_url = st.text_input("Enter a YouTube video URL",help="Paste a YouTube video link to extract the transcript and generate a summary")# Function to extract YouTube video ID from URLdef extract_video_id(url):match = re.search(r"v=([a-zA-Z0-9_-]+)", url)if match:return match.group(1)else:raise ValueError("Invalid YouTube URL")# Function to get the transcript using the YouTubeTranscriptApidef get_transcript(video_id):transcript_raw = YouTubeTranscriptApi.get_transcript(video_id, languages=['en', 'es', 'ko'])transcript_full = ' '.join([i['text'] for i in transcript_raw])return transcript_full# Process the YouTube URLif video_url:try:# Extract video ID from the URLvideo_id = extract_video_id(video_url)# Get the transcript for the videotranscript = get_transcript(video_id)# Display the transcriptst.subheader("Video Transcript")st.text_area("Transcript", transcript, height=200)user_query = st.text_area("What insights or summary would you like from the transcript?",placeholder="Ask anything about the transcript or request a summary.",help="Provide specific questions or insights you want from the transcript.")if st.button("π Generate Summary", key="generate_summary_button"):if not user_query:st.warning("Please enter a query or request a summary of the transcript.")else:try:with st.spinner("Processing transcript and generating summary..."):# Prompt generation for analysisanalysis_prompt = (f"""Here is the transcript of the video:{transcript}The user has requested the following insight/summary:{user_query}Please provide a detailed, user-friendly, and actionable summary based on the provided transcript.""")# AI agent processingresponse = multimodal_Agent.run(analysis_prompt)# Display the resultst.subheader("Summary Result")st.markdown(response.content)except Exception as error:st.error(f"An error occurred during analysis: {error}")except Exception as e:st.error(f"Error processing the YouTube video: {e}")else:st.info("Paste a YouTube video URL to begin transcript extraction and analysis.")
app.py+49-42