Manasa1 commited on
Commit
e1c36f1
Β·
verified Β·
1 Parent(s): 0ce9a88

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -53
app.py CHANGED
@@ -1,66 +1,105 @@
1
  import streamlit as st
2
- from youtube_transcript_api import YouTubeTranscriptApi
3
- from youtube_transcript_api.formatters import SRTFormatter
 
 
 
 
 
 
 
 
 
4
 
5
- # Function to get captions using youtube-transcript-api
6
- def get_youtube_captions(youtube_url):
7
- """
8
- Retrieves YouTube video captions using youtube-transcript-api.
9
-
10
- Parameters:
11
- - youtube_url: The URL of the YouTube video.
12
-
13
- Returns:
14
- - The captions of the video in SRT format, or a message if captions are not available.
15
- """
16
- # Extract video ID from YouTube URL (for both regular videos and Shorts)
17
- if "si=" in youtube_url:
18
- # For YouTube Shorts or URLs with "si=", extract the video ID after "si="
19
- video_id = youtube_url.split("si=")[-1].split("?")[0]
20
- else:
21
- # For regular YouTube videos, extract the video ID after "v="
22
- video_id = youtube_url.split("v=")[-1].split("&")[0]
23
-
24
- # Print extracted video ID for debugging
25
- print(f"Extracted Video ID: {video_id}")
26
 
27
- try:
28
- # Fetch transcript for the video
29
- transcript = YouTubeTranscriptApi.get_transcript(video_id)
30
-
31
- # Format the transcript in SRT format
32
- formatter = SRTFormatter()
33
- formatted_transcript = formatter.format_transcript(transcript)
34
- return formatted_transcript
35
-
36
- except Exception as e:
37
- return f"Error: {str(e)}"
 
38
 
39
  # YouTube video URL input
40
- youtube_url = st.text_input(
41
- "Enter the YouTube video link",
42
- placeholder="Paste the YouTube video URL here",
43
- help="Provide the link to the YouTube video you want to summarize."
44
  )
45
 
46
- if youtube_url:
47
- # Clean URL before passing to the function (remove extra parts)
48
- youtube_url_cleaned = youtube_url.split("?")[0] # Remove URL parameters
49
-
50
  try:
51
- with st.spinner("Fetching and processing the YouTube video..."):
52
- # Get captions using youtube-transcript-api
53
- captions = get_youtube_captions(youtube_url_cleaned)
 
 
 
 
 
 
 
54
 
55
- # Check if captions are available
56
- if "Error" not in captions:
57
- # Display captions
58
- st.subheader("Video Captions:")
59
- st.text(captions)
 
 
 
 
60
  else:
61
- st.error(captions)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
 
 
 
 
 
63
  except Exception as e:
64
- st.error(f"An error occurred: {e}")
65
  else:
66
- st.info("Enter a YouTube video link to begin analysis.")
 
1
  import streamlit as st
2
+ from phi.agent import Agent
3
+ from phi.model.google import Gemini
4
+ from phi.tools.duckduckgo import DuckDuckGo
5
+ from google.generativeai import upload_file, get_file
6
+ import google.generativeai as genai
7
+ import time
8
+ from pathlib import Path
9
+ import tempfile
10
+ from dotenv import load_dotenv
11
+ import os
12
+ from pytube import YouTube # Import pytube for downloading YouTube videos
13
 
14
+ load_dotenv()
15
+
16
+ API_KEY = os.getenv("GOOGLE_API_KEY")
17
+ if API_KEY:
18
+ genai.configure(api_key=API_KEY)
19
+
20
+ # Page configuration
21
+ st.set_page_config(
22
+ page_title="Multimodal AI Agent- Video Summarizer",
23
+ page_icon="πŸŽ₯",
24
+ layout="wide"
25
+ )
26
+
27
+ st.title("Phidata Video AI Summarizer Agent πŸŽ₯πŸŽ€πŸ–¬")
28
+ st.header("Powered by Gemini 2.0 Flash Exp")
 
 
 
 
 
 
29
 
30
+
31
+ @st.cache_resource
32
+ def initialize_agent():
33
+ return Agent(
34
+ name="Video AI Summarizer",
35
+ model=Gemini(id="gemini-2.0-flash-exp"),
36
+ tools=[DuckDuckGo()],
37
+ markdown=True,
38
+ )
39
+
40
+ # Initialize the agent
41
+ multimodal_Agent = initialize_agent()
42
 
43
  # YouTube video URL input
44
+ video_url = st.text_input(
45
+ "Enter a YouTube video URL",
46
+ help="Paste a YouTube video link for AI analysis"
 
47
  )
48
 
49
+ if video_url:
 
 
 
50
  try:
51
+ # Download the YouTube video
52
+ yt = YouTube(video_url)
53
+ video_stream = yt.streams.filter(progressive=True, file_extension='mp4').first()
54
+
55
+ # Create a temporary file to save the video
56
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as temp_video:
57
+ video_stream.download(output_path=temp_video.name)
58
+ video_path = temp_video.name
59
+
60
+ st.video(video_path, format="video/mp4", start_time=0)
61
 
62
+ user_query = st.text_area(
63
+ "What insights are you seeking from the video?",
64
+ placeholder="Ask anything about the video content. The AI agent will analyze and gather additional context if needed.",
65
+ help="Provide specific questions or insights you want from the video."
66
+ )
67
+
68
+ if st.button("πŸ” Analyze Video", key="analyze_video_button"):
69
+ if not user_query:
70
+ st.warning("Please enter a question or insight to analyze the video.")
71
  else:
72
+ try:
73
+ with st.spinner("Processing video and gathering insights..."):
74
+ # Upload and process the video file
75
+ processed_video = upload_file(video_path)
76
+ while processed_video.state.name == "PROCESSING":
77
+ time.sleep(1)
78
+ processed_video = get_file(processed_video.name)
79
+
80
+ # Prompt generation for analysis
81
+ analysis_prompt = (
82
+ f"""
83
+ Analyze the uploaded video for content and context.
84
+ Respond to the following query using video insights and supplementary web research:
85
+ {user_query}
86
+ Provide a detailed, user-friendly, and actionable response.
87
+ """
88
+ )
89
+
90
+ # AI agent processing
91
+ response = multimodal_Agent.run(analysis_prompt, videos=[processed_video])
92
+
93
+ # Display the result
94
+ st.subheader("Analysis Result")
95
+ st.markdown(response.content)
96
 
97
+ except Exception as error:
98
+ st.error(f"An error occurred during analysis: {error}")
99
+ finally:
100
+ # Clean up temporary video file
101
+ Path(video_path).unlink(missing_ok=True)
102
  except Exception as e:
103
+ st.error(f"Error downloading YouTube video: {e}")
104
  else:
105
+ st.info("Paste a YouTube video URL to begin analysis.")