Realistvik0 commited on
Commit
72641b8
·
verified ·
1 Parent(s): d22ad00

Create youtube_video_analysis

Browse files
Files changed (1) hide show
  1. tools/youtube_video_analysis +192 -0
tools/youtube_video_analysis ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ YouTube video analysis tool for smolagents.
3
+
4
+ Uses Google's Gemini API directly because Gemini supports public YouTube
5
+ URLs as native video inputs.
6
+
7
+ Requirements:
8
+ pip install google-genai smolagents
9
+
10
+ Environment:
11
+ GEMINI_API_KEY=your_api_key
12
+ """
13
+
14
+ import os
15
+ import re
16
+ from typing import Any
17
+
18
+ from smolagents import Tool
19
+ from google import genai
20
+
21
+
22
+ class YouTubeVideoAnalysisTool(Tool):
23
+ name = "youtube_video_analysis"
24
+
25
+ description = """
26
+ Analyze a public YouTube video using Gemini's native video understanding.
27
+
28
+ Use this tool when a question requires actually watching or visually
29
+ inspecting a YouTube video, especially questions about:
30
+ - objects or people visible in the video
31
+ - animals or species visible
32
+ - events happening at particular times
33
+ - counts of objects/people/species on screen
34
+ - visual comparisons
35
+ - what appears simultaneously on camera
36
+ - visual details that cannot be reliably answered from a transcript
37
+
38
+ This tool accepts a public YouTube URL and a natural-language question.
39
+ Gemini analyzes the video and returns a detailed answer with timestamps
40
+ when possible.
41
+ """
42
+
43
+ inputs = {
44
+ "url": {
45
+ "type": "string",
46
+ "description": "Public YouTube video URL.",
47
+ },
48
+ "question": {
49
+ "type": "string",
50
+ "description": "The specific question to answer from the video.",
51
+ },
52
+ }
53
+
54
+ output_type = "string"
55
+
56
+ def __init__(
57
+ self,
58
+ model: str = "gemini-2.5-flash",
59
+ **kwargs,
60
+ ):
61
+ super().__init__(**kwargs)
62
+
63
+ api_key = os.getenv("GEMINI_API_KEY")
64
+
65
+ if not api_key:
66
+ raise RuntimeError(
67
+ "GEMINI_API_KEY environment variable is not set."
68
+ )
69
+
70
+ self.model = model
71
+ self.client = genai.Client(api_key=api_key)
72
+
73
+ def forward(self, url: str, question: str) -> str:
74
+ """
75
+ Analyze a YouTube video and answer the supplied question.
76
+ """
77
+
78
+ # Basic URL validation.
79
+ if not self._is_youtube_url(url):
80
+ return (
81
+ "ERROR: The supplied URL does not appear to be a valid "
82
+ "YouTube URL."
83
+ )
84
+
85
+ if not question.strip():
86
+ return "ERROR: The question cannot be empty."
87
+
88
+ prompt = f"""
89
+ You are analyzing a YouTube video to answer a factual research question.
90
+
91
+ VIDEO:
92
+ {url}
93
+
94
+ QUESTION:
95
+ {question}
96
+
97
+ Instructions:
98
+
99
+ 1. Actually inspect the video content.
100
+ 2. Do not rely solely on the title, description, comments, or external
101
+ webpages.
102
+ 3. For questions involving things visible on camera, inspect the visual
103
+ content carefully.
104
+ 4. If the question asks for a maximum or minimum, examine the relevant
105
+ portions of the video rather than giving an estimate.
106
+ 5. Distinguish different species, people, objects, etc. when the question
107
+ requires it.
108
+ 6. When useful, provide timestamps showing the evidence.
109
+ 7. Give the final answer clearly at the end.
110
+ 8. If something cannot be determined reliably, explicitly say so rather
111
+ than guessing.
112
+
113
+ Return a concise but evidence-based answer.
114
+ """
115
+
116
+ try:
117
+ response = self.client.interactions.create(
118
+ model=self.model,
119
+ input=[
120
+ {
121
+ "type": "text",
122
+ "text": prompt,
123
+ },
124
+ {
125
+ "type": "video",
126
+ "uri": url,
127
+ },
128
+ ],
129
+ )
130
+
131
+ answer = getattr(response, "output_text", None)
132
+
133
+ if answer:
134
+ return answer.strip()
135
+
136
+ # Fallback for SDK versions where output_text is unavailable.
137
+ return self._extract_output(response)
138
+
139
+ except Exception as exc:
140
+ return (
141
+ "VIDEO_ANALYSIS_ERROR: "
142
+ f"{type(exc).__name__}: {exc}"
143
+ )
144
+
145
+ @staticmethod
146
+ def _is_youtube_url(url: str) -> bool:
147
+ """Check whether the URL is a normal YouTube URL."""
148
+
149
+ pattern = re.compile(
150
+ r"^https?://"
151
+ r"(www\.)?"
152
+ r"(youtube\.com/watch\?v=|youtu\.be/)"
153
+ r"[A-Za-z0-9_-]+",
154
+ re.IGNORECASE,
155
+ )
156
+
157
+ return bool(pattern.search(url.strip()))
158
+
159
+ @staticmethod
160
+ def _extract_output(response: Any) -> str:
161
+ """
162
+ Fallback response extraction.
163
+
164
+ Different google-genai versions can expose interaction output
165
+ slightly differently, so this attempts several common forms.
166
+ """
167
+
168
+ # Try dictionary-style response.
169
+ if isinstance(response, dict):
170
+ if response.get("output_text"):
171
+ return str(response["output_text"]).strip()
172
+
173
+ output = response.get("output")
174
+
175
+ if output:
176
+ return str(output).strip()
177
+
178
+ # Try normal object attributes.
179
+ output_text = getattr(response, "output_text", None)
180
+
181
+ if output_text:
182
+ return str(output_text).strip()
183
+
184
+ output = getattr(response, "output", None)
185
+
186
+ if output:
187
+ return str(output).strip()
188
+
189
+ return (
190
+ "VIDEO_ANALYSIS_ERROR: Gemini returned a response, "
191
+ "but no text output could be extracted."
192
+ )