Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files103 unmodified lines104105106107108109110111112108109110111112113114115116117118119120121113114115116117118119120121122123124125126127128129124125126127128129130131132130131132133134135136137138139140141135136137138139140141142143144145146147142143144145146147148149150151152153154155156157150151152158159160161162163669 unmodified lines8338348358368378388398404 unmodified lines8458468478388398408488498501 unmodified line85285385484885585685785885986086186286386486586686726 unmodified lines8948958968818828838848858868878888898908918928938948958968978988999008979029039049059068988999009019029089099109119129139149159169039049059069079089099109119129139149159169179189189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519199209219229239249259539549559569269279289299309319329339349359369589379609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100193893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697710031004100510061007100810091010101197897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861055105610571058105910601061106210871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130106411311132113310661067113411351136113711381139107010711072107311401075107610771078107910801081108210831141114211431144114511461147114811491150108511511152115311541155115637 unmodified lines119411951196112911971198119912001133120112021203120412051138120612071208120911421210121112121213114412141215121650 unmodified lines126712681269120112021203120412051206127012711272127312741275121212761277127812791280128112821283128412851286128712881289474 unmodified lines17641765176617671768176917701771177217731774177517761777177817791780178117821783276 unmodified lines2060206120621983206320642065206675 unmodified lines214221432144214521462147214820672068206920702071207220732074214921502151181 unmodified lines2333233423352262233623372264226523382339234023412342103 unmodified lines os.environ["HF_TOKEN"] = hf_key os.environ["HUGGINGFACE_API_KEY"] = hf_key
import threading
self._state_lock = threading.RLock()
def _sync_provider_env(provider: str, key: str) -> None: with self._state_lock: self.provider_keys[provider] = key if not key: return if provider == "openrouter": os.environ["OPENROUTER_API_KEY"] = key elif provider == "groq": os.environ["GROQ_API_KEY"] = key elif provider == "huggingface": os.environ["HF_TOKEN"] = key os.environ["HUGGINGFACE_API_KEY"] = key elif provider == "gemini": self.gemini_key = key os.environ["GEMINI_API_KEY"] = key os.environ["GOOGLE_API_KEY"] = key self.provider_keys[provider] = key if not key: return if provider == "openrouter": os.environ["OPENROUTER_API_KEY"] = key elif provider == "groq": os.environ["GROQ_API_KEY"] = key elif provider == "huggingface": os.environ["HF_TOKEN"] = key os.environ["HUGGINGFACE_API_KEY"] = key elif provider == "gemini": self.gemini_key = key os.environ["GEMINI_API_KEY"] = key os.environ["GOOGLE_API_KEY"] = key
def _get_api_key(model_name: str) -> str | None: with self._state_lock: provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" pool = self.provider_key_pools.get(provider) or [] idx = self._provider_key_idx.get(provider, 0) if idx < len(pool): key = pool[idx] _sync_provider_env(provider, key) return key _sync_provider_env(provider, "") return None provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" pool = self.provider_key_pools.get(provider) or [] idx = self._provider_key_idx.get(provider, 0) if idx < len(pool): key = pool[idx] _sync_provider_env(provider, key) return key _sync_provider_env(provider, "") return None
def _rotate_api_key(provider: str, permanent: bool = False) -> bool: with self._state_lock: pool = self.provider_key_pools.get(provider) or [] cur_idx = self._provider_key_idx.get(provider, 0) if permanent and 0 <= cur_idx < len(pool): pool.pop(cur_idx) next_idx = cur_idx else: next_idx = cur_idx + 1 self._provider_key_idx[provider] = next_idx if next_idx < len(pool): _sync_provider_env(provider, pool[next_idx]) return True _sync_provider_env(provider, "") return False pool = self.provider_key_pools.get(provider) or [] cur_idx = self._provider_key_idx.get(provider, 0) if permanent and 0 <= cur_idx < len(pool): pool.pop(cur_idx) next_idx = cur_idx else: next_idx = cur_idx + 1 self._provider_key_idx[provider] = next_idx if next_idx < len(pool): _sync_provider_env(provider, pool[next_idx]) return True _sync_provider_env(provider, "") return False
def _reset_key_indices() -> None: with self._state_lock: for prov, pool in self.provider_key_pools.items(): self._provider_key_idx[prov] = 0 _sync_provider_env(prov, pool[0] if pool else "") for prov, pool in self.provider_key_pools.items(): self._provider_key_idx[prov] = 0 _sync_provider_env(prov, pool[0] if pool else "")
def _tool_timeout(default_timeout: float, min_timeout: float = 4.0) -> float: import time669 unmodified lines except Exception as exc: last_err = exc err_low = str(exc).lower() if "task time budget exhausted" in err_low: raise if any( marker in err_low for marker in (4 unmodified lines "missing authentication header", "insufficient permissions", "does not have sufficient permissions", "free-models-per-day", "quota", "resource_exhausted", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(1 unmodified line ): continue break if any(marker in err_low for marker in ("429", "rate limit")): if any( marker in err_low for marker in ( "429", "rate limit", "free-models-per-day", "quota", "resource_exhausted", ) ): rate_limited_providers.add(v_provider) break break26 unmodified lines import re from html import unescape
raw = (url or "").strip() vid_match = re.search( r"(?:v=|/shorts/|/embed/|youtu\.be/)([A-Za-z0-9_-]{11})", raw, ) video_id = vid_match.group(1) if vid_match else (raw if re.fullmatch(r"[A-Za-z0-9_-]{11}", raw) else "") if not video_id: return f"Invalid YouTube URL or video ID: '{url}'"
watch_url = f"https://www.youtube.com/watch?v={video_id}" headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", "Cookie": "SOCS=CAI", } sections = [f"Video ID: {video_id}", f"URL: {watch_url}"] has_title = False has_desc = False caption_tracks = []
try: oembed_resp = requests.get( "https://www.youtube.com/oembed", params={"url": watch_url, "format": "json"}, headers=headers, timeout=15, raw = (url or "").strip() vid_match = re.search( r"(?:v=|/shorts/|/embed/|youtu\.be/)([A-Za-z0-9_-]{11})", raw, ) if oembed_resp.status_code == 200: oembed = oembed_resp.json() if oembed.get("title"): sections.append(f"Title: {oembed['title']}") has_title = True if oembed.get("author_name"): sections.append(f"Channel: {oembed['author_name']}") except Exception: pass video_id = vid_match.group(1) if vid_match else (raw if re.fullmatch(r"[A-Za-z0-9_-]{11}", raw) else "") if not video_id: return f"Invalid YouTube URL or video ID: '{url}'"
watch_url = f"https://www.youtube.com/watch?v={video_id}" headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", "Cookie": "SOCS=CAI", } sections = [f"Video ID: {video_id}", f"URL: {watch_url}"] has_title = False has_desc = False has_transcript = False caption_tracks = []
try: player_resp = requests.post( "https://www.youtube.com/youtubei/v1/player", params={"prettyPrint": "false"}, headers={ "Content-Type": "application/json", "User-Agent": "com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip", }, json={ "context": { "client": { "clientName": "ANDROID", "clientVersion": "19.09.37", "hl": "en", "gl": "US", } }, "videoId": video_id, }, timeout=20, ) if player_resp.status_code == 200: player_data = player_resp.json() v_details = player_data.get("videoDetails") or {} if not has_title and v_details.get("title"): sections.append(f"Title: {v_details['title']}") has_title = True if v_details.get("shortDescription"): sections.append(f"Description:\n{str(v_details['shortDescription'])[:2000]}") has_desc = True tracks = ( (player_data.get("captions") or {}) .get("playerCaptionsTracklistRenderer", {}) .get("captionTracks") try: oembed_resp = requests.get( "https://www.youtube.com/oembed", params={"url": watch_url, "format": "json"}, headers=headers, timeout=_tool_timeout(8.0, min_timeout=2.0), ) if isinstance(tracks, list): caption_tracks = tracks except Exception: pass if oembed_resp.status_code == 200: oembed = oembed_resp.json() if oembed.get("title"): sections.append(f"Title: {oembed['title']}") has_title = True if oembed.get("author_name"): sections.append(f"Channel: {oembed['author_name']}") except Exception as req_exc: if "task time budget exhausted" in str(req_exc).lower(): raise
if not has_desc or not caption_tracks: try: page_resp = requests.get(watch_url, headers=headers, timeout=20) if page_resp.status_code == 200: html_text = page_resp.text if not has_desc: desc_match = re.search(r'"shortDescription"\s*:\s*"((?:\\.|[^"\\])*)"', html_text) if desc_match: try: desc_val = desc_match.group(1).encode("utf-8").decode("unicode_escape") except Exception: desc_val = unescape(desc_match.group(1)) sections.append(f"Description:\n{desc_val[:2000]}") if not caption_tracks: cap_match = re.search(r'"captionTracks"\s*:\s*(\[[^\]]*\])', html_text) if cap_match: caption_tracks = json.loads(cap_match.group(1)) except Exception as e: sections.append(f"Page fetch note: {e}")
if caption_tracks: sorted_tracks = sorted( caption_tracks, key=lambda t: 0 if str(t.get("languageCode", "")).lower().startswith("en") else 1, ) for tr in sorted_tracks[:3]: base_url = tr.get("baseUrl") if not base_url: continue try: tr_resp = requests.get(unescape(base_url), headers=headers, timeout=20) if tr_resp.status_code == 200 and tr_resp.text: raw_cues = re.findall(r"(?is)<text[^>]*>(.*?)</text>", tr_resp.text) cues = [ re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", c))).strip() for c in raw_cues ] transcript = " ".join(c for c in cues if c) if transcript: lang = tr.get("languageCode", "unknown") sections.append(f"Transcript ({lang}):\n{transcript[:8000]}") break except Exception: continue player_resp = requests.post( "https://www.youtube.com/youtubei/v1/player", params={"prettyPrint": "false"}, headers={ "Content-Type": "application/json", "User-Agent": "com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip", }, json={ "context": { "client": { "clientName": "ANDROID", "clientVersion": "19.09.37", "hl": "en", "gl": "US", } }, "videoId": video_id, }, timeout=_tool_timeout(10.0, min_timeout=2.0), ) if player_resp.status_code == 200: player_data = player_resp.json() v_details = player_data.get("videoDetails") or {} if not has_title and v_details.get("title"): sections.append(f"Title: {v_details['title']}") has_title = True if v_details.get("shortDescription"): sections.append(f"Description:\n{str(v_details['shortDescription'])[:2000]}") has_desc = True tracks = ( (player_data.get("captions") or {}) .get("playerCaptionsTracklistRenderer", {}) .get("captionTracks") ) if isinstance(tracks, list): caption_tracks = tracks except Exception as req_exc: if "task time budget exhausted" in str(req_exc).lower(): raise
gemini_pool = self.provider_key_pools.get("gemini") or [] if gemini_pool: gemini_models = list( dict.fromkeys( (self.gemini_flash_models or []) + [ "gemini/gemini-2.5-flash", "gemini/gemini-flash-latest", ] if not has_desc or not caption_tracks: try: page_resp = requests.get( watch_url, headers=headers, timeout=_tool_timeout(10.0, min_timeout=2.0), ) if page_resp.status_code == 200: html_text = page_resp.text if not has_desc: desc_match = re.search(r'"shortDescription"\s*:\s*"((?:\\.|[^"\\])*)"', html_text) if desc_match: try: desc_val = desc_match.group(1).encode("utf-8").decode("unicode_escape") except Exception: desc_val = unescape(desc_match.group(1)) sections.append(f"Description:\n{desc_val[:2000]}") if not caption_tracks: cap_match = re.search(r'"captionTracks"\s*:\s*(\[[^\]]*\])', html_text) if cap_match: caption_tracks = json.loads(cap_match.group(1)) except Exception as e: if "task time budget exhausted" in str(e).lower(): raise sections.append(f"Page fetch note: {e}")
if caption_tracks: sorted_tracks = sorted( caption_tracks, key=lambda t: 0 if str(t.get("languageCode", "")).lower().startswith("en") else 1, ) for tr in sorted_tracks[:2]: base_url = tr.get("baseUrl") if not base_url: continue try: tr_resp = requests.get( unescape(base_url), headers=headers, timeout=_tool_timeout(8.0, min_timeout=2.0), ) if tr_resp.status_code == 200 and tr_resp.text: raw_cues = re.findall(r"(?is)<text[^>]*>(.*?)</text>", tr_resp.text) cues = [ re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", c))).strip() for c in raw_cues ] transcript = " ".join(c for c in cues if c) if transcript: lang = tr.get("languageCode", "unknown") sections.append(f"Transcript ({lang}):\n{transcript[:8000]}") has_transcript = True break except Exception as tr_exc: if "task time budget exhausted" in str(tr_exc).lower(): raise continue
visual_markers = ( "visual", "scene", "appear", "color", "colour", "wear", "wearing", "shirt", "count", "how many", "bird", "species", "animal", "screen", "shown", "show", "frame", "background", "sign", "logo", "action", "doing", "see", "look", "watch", ) video_analyzed = False while not video_analyzed: rate_limited_gemini = False for g_model in gemini_models: raw_model = g_model[len("gemini/"):] if g_model.startswith("gemini/") else g_model while True: g_key = self._get_api_key(g_model) if not g_key: break try: gm_resp = requests.post( f"https://generativelanguage.googleapis.com/v1beta/models/{raw_model}:generateContent", params={"key": g_key}, headers={"Content-Type": "application/json"}, json={ "contents": [ { "parts": [ {"file_data": {"mime_type": "video/mp4", "file_uri": watch_url}}, {"text": question}, ] } ], "generationConfig": {"maxOutputTokens": 2048}, }, timeout=_tool_timeout(60.0), ) if gm_resp.status_code == 200: candidates = gm_resp.json().get("candidates") or [] if candidates: parts = (candidates[0].get("content") or {}).get("parts") or [] analysis_text = "\n".join( str(p.get("text", "")).strip() for p in parts if isinstance(p, dict) and p.get("text") ).strip() if analysis_text: sections.append(f"Multimodal Video Analysis:\n{analysis_text}") video_analyzed = True break needs_video_analysis = (not has_transcript) or any( marker in (question or "").lower() for marker in visual_markers )
gemini_pool = self.provider_key_pools.get("gemini") or [] if gemini_pool and needs_video_analysis: gemini_models = list( dict.fromkeys( (self.gemini_flash_models or []) + [ "gemini/gemini-2.5-flash", "gemini/gemini-flash-latest", ] ) )[:2] video_analyzed = False while not video_analyzed: rate_limited_gemini = False for g_model in gemini_models: raw_model = g_model[len("gemini/"):] if g_model.startswith("gemini/") else g_model while True: g_key = self._get_api_key(g_model) if not g_key: break err_low = gm_resp.text.lower() if ( gm_resp.status_code in (401, 402, 403) or "quota" in err_low or "resource_exhausted" in err_low ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( "gemini", permanent=True try: gm_resp = requests.post( f"https://generativelanguage.googleapis.com/v1beta/models/{raw_model}:generateContent", params={"key": g_key}, headers={"Content-Type": "application/json"}, json={ "contents": [ { "parts": [ {"file_data": {"mime_type": "video/mp4", "file_uri": watch_url}}, {"text": question}, ] } ], "generationConfig": {"maxOutputTokens": 2048}, }, timeout=_tool_timeout(28.0, min_timeout=3.0), ) if gm_resp.status_code == 200: candidates = gm_resp.json().get("candidates") or [] if candidates: parts = (candidates[0].get("content") or {}).get("parts") or [] analysis_text = "\n".join( str(p.get("text", "")).strip() for p in parts if isinstance(p, dict) and p.get("text") ).strip() if analysis_text: sections.append(f"Multimodal Video Analysis:\n{analysis_text}") video_analyzed = True break break err_low = gm_resp.text.lower() if gm_resp.status_code in (401, 402, 403): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( "gemini", permanent=True ): continue break if ( gm_resp.status_code == 429 or "quota" in err_low or "resource_exhausted" in err_low ): continue rate_limited_gemini = True break break if gm_resp.status_code == 429: rate_limited_gemini = True except Exception as gm_exc: if "task time budget exhausted" in str(gm_exc).lower(): raise break if video_analyzed: break except Exception: break if video_analyzed: break
if ( not video_analyzed and rate_limited_gemini and hasattr(self, "_rotate_api_key") and self._provider_key_idx.get("gemini", 0) + 1 < len(gemini_pool) and self._rotate_api_key("gemini") ): continue break if ( not video_analyzed and rate_limited_gemini and hasattr(self, "_rotate_api_key") and self._provider_key_idx.get("gemini", 0) + 1 < len(gemini_pool) and self._rotate_api_key("gemini") ): continue break
return _trim_tool_output("\n\n".join(sections), max_chars=12000) return _trim_tool_output("\n\n".join(sections), max_chars=12000) except Exception as e: return f"Error inspecting YouTube '{url}': {str(e)}"
@tool def transcribe_audio(37 unmodified lines return transcript break err_body = groq_resp.text.lower() if groq_resp.status_code in (401, 402, 403) or "quota" in err_body: if groq_resp.status_code in (401, 402, 403): if hasattr(self, "_rotate_api_key") and self._rotate_api_key("groq", permanent=True): continue break if groq_resp.status_code == 429: if groq_resp.status_code == 429 or "quota" in err_body or "resource_exhausted" in err_body: groq_pool = self.provider_key_pools.get("groq") or [] if ( hasattr(self, "_rotate_api_key") and self._provider_key_idx.get("groq", 0) + 1 < len(groq_pool) and self._rotate_api_key("groq") and self._rotate_api_key("groq", permanent=False) ): continue break except Exception: except Exception as groq_exc: if "task time budget exhausted" in str(groq_exc).lower(): raise break
with open(audio_path, "rb") as f: b64_data = base64.b64encode(f.read()).decode("utf-8")
50 unmodified lines return out break err_low = gm_resp.text.lower() last_err = RuntimeError(f"HTTP {gm_resp.status_code}: {gm_resp.text[:300]}") if ( gm_resp.status_code in (401, 402, 403) or "quota" in err_low or "resource_exhausted" in err_low ): if gm_resp.status_code in (401, 402, 403): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( "gemini", permanent=True ): continue break if gm_resp.status_code == 429: if ( gm_resp.status_code == 429 or "quota" in err_low or "resource_exhausted" in err_low ): rate_limited_gemini = True break break except Exception as exc: if "task time budget exhausted" in str(exc).lower(): raise last_err = exc break
474 unmodified lines model_name = str(getattr(self, "model_id", "") or "") if api_base: self.api_base = api_base if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["api_base"] = api_base if key: self.api_key = key if isinstance(getattr(self, "kwargs", None), dict): self.kwargs["api_key"] = key if api_base: os.environ["OPENAI_API_KEY"] = key if "generativelanguage.googleapis.com" in api_base: os.environ["GEMINI_API_KEY"] = key os.environ["GOOGLE_API_KEY"] = key elif "huggingface.co" in api_base: os.environ["HF_TOKEN"] = key os.environ["HUGGINGFACE_API_KEY"] = key elif model_name.startswith("openrouter/"): os.environ["OPENROUTER_API_KEY"] = key elif model_name.startswith("groq/"):276 unmodified lines if self.model_id and self.model_id not in models_to_try: models_to_try.append(self.model_id)
deadline = time.monotonic() + 85.0 deadline = time.monotonic() + 62.0 self._local_state.deadline = deadline
try:75 unmodified lines "free-models-per-day", "quota", "resource_exhausted", "429", "rate limit exceeded", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key( provider, permanent=False ): continue blocked_models.add(model_name) rate_limited_providers.add(provider) break if any(marker in err_lower for marker in ("429", "rate limit exceeded")): rate_limited_models.add(model_name) rate_limited_providers.add(provider) break181 unmodified lines executor = ThreadPoolExecutor(max_workers=1) future = executor.submit(agent, question_text, task_id=task_id) try: submitted_answer = future.result(timeout=120) submitted_answer = future.result(timeout=80) except FutureTimeoutError: print(f"Timeout running agent on task {task_id} after 120s.") submitted_answer = "AGENT ERROR: Task timed out after 120s." print(f"Timeout running agent on task {task_id} after 80s.") submitted_answer = "AGENT ERROR: Task timed out after 80s." except Exception as e: print(f"Error running agent on task {task_id}: {e}") submitted_answer = f"AGENT ERROR: {e}"app.py+330-256