Skip to content

100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.

Add earnings call analyst agent

Shubhamsaboo854f52118608
diff --git a/README.md b/README.md
index d78e0179..1c8523cf 100644
--- a/README.md
+++ b/README.md
@@ -92,6 +92,7 @@ streamlit run travel_agent.py
| Template | What it does | Stack |
|---|---|---|
+| [πŸ“ˆ Earnings Call Analyst Agent](advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/) | YouTube earnings calls become quote-synced analyst cards with ADK, Gemini, filings, and grounded market news | ADK + Gemini |
| [πŸ›‘οΈ Insurance Claim Live Agent Team](voice_ai_agents/insurance_claim_live_agent_team/) | Real-time voice claim intake with Gemini Live and ADK | Voice + ADK |
| [🏠 Home Renovation Agent](advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent) | Photo β†’ AI redesign with Nano Banana Pro | Vision + Multi-agent |
| [♾️ Self-Improving Agent Skills](awesome_agent_skills/self-improving-agent-skills/) | Automatically optimize agent skills using Gemini and ADK | Agent Skills + ADK |
@@ -150,6 +151,7 @@ streamlit run travel_agent.py
* [πŸ’° AI Financial Coach Agent](advanced_ai_agents/multi_agent_apps/ai_financial_coach_agent/)
* [🎬 AI Movie Production Agent](advanced_ai_agents/single_agent_apps/ai_movie_production_agent/)
* [πŸ“ˆ AI Investment Agent](advanced_ai_agents/single_agent_apps/ai_investment_agent/)
+* [πŸ“ˆ Earnings Call Analyst Agent](advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/)
* [πŸ‹οΈβ€β™‚οΈ AI Health & Fitness Agent](advanced_ai_agents/single_agent_apps/ai_health_fitness_agent/)
* [πŸš€ AI Product Launch Intelligence Agent](advanced_ai_agents/multi_agent_apps/product_launch_intelligence_agent)
* [πŸ” AI Fraud Investigation Agent](advanced_ai_agents/single_agent_apps/ai_fraud_investigation_agent/)
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/.env.example b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/.env.example
new file mode 100644
index 00000000..18b77b04
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/.env.example
@@ -0,0 +1,14 @@
+# Option 1: Vertex AI / Google Cloud
+GOOGLE_GENAI_USE_VERTEXAI=True
+GOOGLE_CLOUD_PROJECT=your-google-cloud-project-id
+GOOGLE_CLOUD_LOCATION=global
+
+# Option 2: Gemini API key
+# GOOGLE_GENAI_USE_VERTEXAI=False
+# GOOGLE_API_KEY=your-google-api-key
+
+EARNINGS_GEMINI_MODEL=gemini-3-flash-preview
+EARNINGS_SEARCH_GEMINI_MODEL=gemini-2.5-flash
+EARNINGS_TRANSCRIPT_MODEL=gemini-3-flash-preview
+EARNINGS_AUDIO_CHUNK_SECONDS=300
+EARNINGS_USER_AGENT="earnings-call-analyst-agent [email protected]"
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/.gitignore b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/.gitignore
new file mode 100644
index 00000000..762b8d72
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/.gitignore
@@ -0,0 +1,4 @@
+.env
+.venv/
+__pycache__/
+.pytest_cache/
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/README.md b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/README.md
new file mode 100644
index 00000000..87c48bb3
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/README.md
@@ -0,0 +1,91 @@
+# πŸ“ˆ Earnings Call Analyst Agent
+
+An investor-grade earnings call companion that turns any YouTube earnings call into a playback-synced analyst workspace. Paste a call URL, watch the video, and let ADK agents surface the numbers, tone shifts, filing context, and market-moving surprises that are easy to miss in a live call.
+
+This is built for the real earnings workflow: instead of reading a transcript after the fact, you can follow management commentary with an agentic research layer that keeps every insight tied to the quote that triggered it.
+
+![Earnings Call Analyst Agent architecture](assets/earnings-call-analyst-agent-architecture.png)
+
+## Features
+
+### Agentic Call Research
+
+- Identifies the company, ticker, fiscal period, and peer set from the YouTube metadata and transcript opening
+- Builds a research pack with SEC filings and current market context
+- Uses an ADK news agent with Google Search grounding before falling back to finance feeds
+- Hides unresolved context instead of showing empty research panels
+
+### Quote-Anchored Signal Detection
+
+- Creates analyst cards only when the transcript contains a real investor signal
+- Anchors every card to the exact quote and timestamp that triggered it
+- Filters out greetings, safe-harbor boilerplate, and generic upbeat commentary
+- Reveals cards as playback reaches the relevant moment in the call
+
+### Earnings Intelligence Cards
+
+- Flags financial metrics, margin pressure, guidance language, demand commentary, pricing, cash flow, and capex signals
+- Separates company-specific statements from peer or sector context when evidence is available
+- Calls out CFO hedging, confidence shifts, defensiveness, and unusually specific language
+- Adds compact tables or chart summaries only when they clarify the finding
+
+### Caption + Audio Resilience
+
+- Uses YouTube captions when available for precise timestamps
+- Falls back to ADK-powered audio transcription for captionless videos
+- Realigns generated cards to the closest caption segment so the video and quote stay in sync
+- Keeps a local heuristic fallback for basic metric and tone flags when Gemini is unavailable
+
+## How to get Started?
+
+This agent lives in `advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent`.
+
+1. Clone the GitHub repository
+
+```bash
+git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
+cd advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent
+```
+
+2. Install the required dependencies:
+
+```bash
+python3 -m venv .venv
+source .venv/bin/activate
+pip install -r requirements.txt
+```
+
+3. Configure Vertex AI or Gemini API key:
+
+```bash
+cp .env.example .env
+```
+
+For Vertex AI / Google Cloud auth:
+
+```bash
+GOOGLE_GENAI_USE_VERTEXAI=True
+GOOGLE_CLOUD_PROJECT=your-google-cloud-project-id
+GOOGLE_CLOUD_LOCATION=global
+```
+
+For Gemini API key auth:
+
+```bash
+GOOGLE_GENAI_USE_VERTEXAI=False
+GOOGLE_API_KEY=your-google-api-key
+```
+
+4. Run the FastAPI app:
+
+```bash
+PYTHONPATH=.. python -m uvicorn earnings_call_analyst_agent.live_demo.server:app --host 127.0.0.1 --port 4188
+```
+
+5. Open the app:
+
+```text
+http://127.0.0.1:4188
+```
+
+Paste a YouTube earnings call URL. The app builds the research pack first, then reveals analyst cards as the video reaches each quote.
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/__init__.py b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/__init__.py
new file mode 100644
index 00000000..be58b768
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/__init__.py
@@ -0,0 +1 @@
+"""Earnings Call Analyst Agent package."""
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/adk_runtime.py b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/adk_runtime.py
new file mode 100644
index 00000000..50caeda9
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/adk_runtime.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+import asyncio
+import inspect
+import os
+import uuid
+
+from google.genai import types
+
+
+APP_NAME = "earnings_call_analyst_agent"
+USER_ID = "local_demo_user"
+
+
+async def run_adk_agent_text_async(agent: object, prompt: str, state: dict | None = None) -> str:
+ """Run an ADK agent once and return the final text it emits."""
+ message = types.Content(role="user", parts=[types.Part(text=prompt)])
+ return await run_adk_agent_content_async(agent, message, state=state)
+
+
+async def run_adk_agent_content_async(
+ agent: object, message: types.Content, state: dict | None = None
+) -> str:
+ """Run an ADK agent once with a prepared Content payload."""
+ _ensure_google_api_key_alias()
+ from google.adk.runners import Runner
+ from google.adk.sessions import InMemorySessionService
+
+ session_service = InMemorySessionService()
+ session = await session_service.create_session(
+ app_name=APP_NAME,
+ user_id=USER_ID,
+ session_id=uuid.uuid4().hex,
+ state=state or {},
+ )
+ runner = Runner(
+ app_name=APP_NAME,
+ agent=agent,
+ session_service=session_service,
+ )
+ final_text = ""
+ try:
+ async for event in runner.run_async(
+ user_id=session.user_id,
+ session_id=session.id,
+ new_message=message,
+ ):
+ if not event.content or not event.content.parts:
+ continue
+ text = "".join(part.text or "" for part in event.content.parts)
+ if text:
+ final_text = text
+ if event.is_final_response() and text:
+ final_text = text
+ finally:
+ close = getattr(runner, "close", None)
+ if close:
+ result = close()
+ if inspect.isawaitable(result):
+ await result
+ return final_text
+
+
+def run_adk_agent_text(agent: object, prompt: str, state: dict | None = None) -> str:
+ return asyncio.run(run_adk_agent_text_async(agent, prompt, state=state))
+
+
+def run_adk_agent_content(
+ agent: object, message: types.Content, state: dict | None = None
+) -> str:
+ return asyncio.run(run_adk_agent_content_async(agent, message, state=state))
+
+
+def _ensure_google_api_key_alias() -> None:
+ if os.getenv("GEMINI_API_KEY") and not os.getenv("GOOGLE_API_KEY"):
+ os.environ["GOOGLE_API_KEY"] = os.environ["GEMINI_API_KEY"]
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/agent.py b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/agent.py
new file mode 100644
index 00000000..fa980cfc
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/agent.py
@@ -0,0 +1,390 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+from typing import Any
+
+from .adk_runtime import run_adk_agent_text
+from .schemas import (
+ Citation,
+ InsightEvent,
+ MiniVisualization,
+ ResearchPack,
+ TranscriptChunk,
+ TranscriptSegment,
+ VideoMetadata,
+)
+
+MODEL = os.getenv("EARNINGS_GEMINI_MODEL", "gemini-3-flash-preview")
+
+
+try:
+ from google.adk.agents import LlmAgent
+
+ root_agent = LlmAgent(
+ name="earnings_call_analyst_agent",
+ model=MODEL,
+ description="Creates playback-synced investor insight cards from an earnings-call transcript and research pack.",
+ instruction=(
+ "Act like a skeptical public-equities analyst. Read timestamped transcript chunks and research context. "
+ "Create only high-signal investor cards. Use the agent field to classify the card as "
+ "numbers_reconciler, cfo_tone, peer_context, surprise_detector, filing_grounder, or market_narrator. "
+ "Return strict JSON only. Never invent filings, peers, consensus, or quote text."
+ ),
+ )
+except Exception:
+ root_agent = None
+
+
+def generate_insights(
+ metadata: VideoMetadata,
+ research: ResearchPack,
+ chunks: list[TranscriptChunk],
+ max_chunks: int = 64,
+) -> list[InsightEvent]:
+ selected = select_signal_chunks(chunks, limit=max_chunks)
+ if _has_gemini_key() and root_agent is not None:
+ insights = _generate_with_adk(metadata, research, selected)
+ if insights:
+ return sorted(_realign_event_times(insights, selected))
+ return sorted(_realign_event_times(_generate_local_insights(research, selected), selected))
+
+
+def select_signal_chunks(chunks: list[TranscriptChunk], limit: int = 64) -> list[TranscriptChunk]:
+ scored = []
+ for index, chunk in enumerate(chunks):
+ score = _chunk_signal_score(chunk.text)
+ if index < 4:
+ score += 3
+ scored.append((score, index, chunk))
+ chosen = sorted(scored, key=lambda item: (-item[0], item[1]))[:limit]
+ return [chunk for _, _, chunk in sorted(chosen, key=lambda item: item[1])]
+
+
+def _generate_with_adk(
+ metadata: VideoMetadata, research: ResearchPack, chunks: list[TranscriptChunk]
+) -> list[InsightEvent]:
+ if root_agent is None:
+ return []
+
+ context = _research_context(research)
+ chunk_payload = [
+ {"start": round(chunk.start, 2), "end": round(chunk.end, 2), "text": chunk.text[:1600]}
+ for chunk in chunks
+ ]
+ prompt = f"""
+You are powering a playback-synced analyst cockpit for a YouTube earnings call.
+Act like a skeptical public-equities analyst, not a generic summarizer.
+Return strict JSON only, with this shape:
+{{"insights":[{{"start_time": number, "end_time": number, "agent": one of
+["numbers_reconciler","cfo_tone","peer_context","surprise_detector","filing_grounder","market_narrator"],
+"severity": "high"|"medium"|"low", "headline": string, "quote": exact transcript quote,
+"confidence": number 0-1, "explanation": string,
+"mini_viz": {{"type": string, "title": string, "rows": [[string,string]], "points": [number], "labels": [string]}},
+"citations": [{{"label": string, "source": string, "url": string}}]}}]}}
+
+Rules:
+- Create at most 24 insights.
+- Every insight must be anchored to a supplied transcript chunk time.
+- Use quote text copied from the transcript chunk.
+- Do not invent filings, peers, or consensus data. If research context is thin, say so.
+- Prefer high-signal cards: guidance changes, margins, capex, cash flow, demand, backlog, pricing, churn, macro, AI, layoffs, litigation, CFO hedging, and contradictions against prior context.
+- Do not create cards for generic greetings, boilerplate safe-harbor language, or vague upbeat statements unless they reveal a concrete investor signal.
+- Numbers Reconciler cards must identify the metric, current value, and baseline if available. If no baseline exists, say "baseline not found" in mini_viz rows.
+- CFO Tone cards must cite the exact words that indicate confidence, caution, hedging, defensiveness, or unusual emphasis.
+- Peer Context cards must distinguish "sector-wide" vs "company-specific" and name the evidence source when available.
+- Surprise Detector cards must explain why the statement is novel, contradictory, unusually specific, or likely market-moving.
+- The explanation field must answer "why this matters to an investor" in one concise sentence.
+- Make mini_viz compact and useful. Use rows for direct comparisons. Use points only for a real time series, and include matching labels and a title with the unit, such as "Monthly Token Volume (Quadrillions)".
+- If a finding is weak, omit it.
+- If the transcript does not appear to be an earnings call, return at most one low-severity market_narrator card saying the source does not look like an earnings call.
+
+Video: {metadata.title}
+Research context:
+{context}
+
+Transcript chunks:
+{json.dumps(chunk_payload)}
+"""
+ try:
+ payload = _parse_json_object(run_adk_agent_text(root_agent, prompt))
+ except Exception:
+ return []
+
+ raw_insights = payload.get("insights", [])
+ if not isinstance(raw_insights, list):
+ return []
+
+ events: list[InsightEvent] = []
+ for raw in raw_insights:
+ if not isinstance(raw, dict):
+ continue
+ try:
+ event_id = raw.get("id") or _event_id(raw)
+ mini_raw = raw.get("mini_viz") if isinstance(raw.get("mini_viz"), dict) else {}
+ citations_raw = raw.get("citations") if isinstance(raw.get("citations"), list) else []
+ events.append(
+ InsightEvent(
+ id=event_id,
+ start_time=float(raw.get("start_time", 0)),
+ end_time=float(raw.get("end_time", raw.get("start_time", 0))),
+ agent=str(raw.get("agent", "market_narrator")),
+ severity=raw.get("severity", "low"),
+ headline=str(raw.get("headline", "")).strip()[:180],
+ quote=str(raw.get("quote", "")).strip()[:500],
+ confidence=float(raw.get("confidence", 0.5)),
+ explanation=str(raw.get("explanation", "")).strip()[:600],
+ mini_viz=MiniVisualization(**mini_raw),
+ citations=[Citation(**item) for item in citations_raw if isinstance(item, dict)],
+ )
+ )
+ except Exception:
+ continue
+ return _dedupe_events([event for event in events if event.headline and event.quote])
+
+
+def _generate_local_insights(
+ research: ResearchPack, chunks: list[TranscriptChunk]
+) -> list[InsightEvent]:
+ events: list[InsightEvent] = []
+ tone_points: list[float] = []
+ for chunk in chunks[:80]:
+ text = chunk.text
+ lower = text.lower()
+ numbers = re.findall(r"(?:\$?\d+(?:\.\d+)?\s*(?:%|percent|million|billion|basis points|bps)?)", text)
+ if numbers and any(term in lower for term in ["revenue", "margin", "guidance", "cash", "eps", "growth"]):
+ quote = _quote(text, numbers[0])
+ events.append(
+ InsightEvent(
+ id=_stable_id("numbers", chunk.start, quote),
+ start_time=chunk.start,
+ end_time=chunk.end,
+ agent="numbers_reconciler",
+ severity="medium",
+ headline=f"Numeric claim detected: {numbers[0]}",
+ quote=quote,
+ confidence=0.62,
+ explanation="Gemini analysis was unavailable, so this local pass flagged a financial metric for review.",
+ mini_viz=MiniVisualization(
+ type="metric_table",
+ title="Detected metric",
+ rows=[["Metric", numbers[0]], ["Context", _compact_context(lower)]],
+ ),
+ citations=_default_citations(research),
+ )
+ )
+ hedge_count = sum(lower.count(term) for term in ["uncertain", "challenging", "headwind", "pressure", "cautious", "volatile"])
+ confident_count = sum(lower.count(term) for term in ["confident", "strong", "record", "accelerat", "robust"])
+ tone = max(0, min(100, 50 + confident_count * 10 - hedge_count * 12))
+ tone_points.append(tone)
+ if hedge_count >= 2:
+ quote = _quote(text, "headwind" if "headwind" in lower else text.split()[0])
+ events.append(
+ InsightEvent(
+ id=_stable_id("tone", chunk.start, quote),
+ start_time=chunk.start,
+ end_time=chunk.end,
+ agent="cfo_tone",
+ severity="low",
+ headline="Tone shifted toward caution",
+ quote=quote,
+ confidence=0.58,
+ explanation="Local tone scan found clustered caution language in this segment.",
+ mini_viz=MiniVisualization(
+ type="tone_sparkline",
+ title="Tone score",
+ points=tone_points[-12:],
+ ),
+ citations=[Citation(label="Transcript segment", source="YouTube captions")],
+ )
+ )
+ return _dedupe_events(events)[:30]
+
+
+def _chunk_signal_score(text: str) -> int:
+ lower = text.lower()
+ terms = [
+ "revenue",
+ "guidance",
+ "margin",
+ "eps",
+ "earnings",
+ "cash flow",
+ "free cash",
+ "capex",
+ "demand",
+ "backlog",
+ "pricing",
+ "churn",
+ "headwind",
+ "tailwind",
+ "uncertain",
+ "confident",
+ "ai",
+ "layoff",
+ "restructuring",
+ "litigation",
+ ]
+ score = sum(lower.count(term) for term in terms)
+ score += min(6, len(re.findall(r"\d", text)) // 8)
+ return score
+
+
+def _research_context(research: ResearchPack) -> str:
+ docs = "\n".join(
+ f"- {doc.kind}: {doc.title} {doc.url}" for doc in research.documents[:5]
+ )
+ news = "\n".join(f"- {item.title}: {item.summary}" for item in research.news[:8])
+ peers = ", ".join(research.peers) or "Not resolved"
+ notes = "; ".join(research.notes)
+ return (
+ f"Company: {research.company}\nTicker: {research.ticker}\n"
+ f"Fiscal period: {research.fiscal_period}\nPeers: {peers}\n"
+ f"Documents:\n{docs or '- None'}\nRecent news:\n{news or '- None'}\nNotes: {notes}"
+ )
+
+
+def _parse_json_object(text: str) -> dict[str, Any]:
+ cleaned = text.strip()
+ cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", cleaned, flags=re.I | re.S)
+ start = cleaned.find("{")
+ end = cleaned.rfind("}")
+ if start == -1 or end == -1:
+ return {}
+ try:
+ data = json.loads(cleaned[start : end + 1])
+ except json.JSONDecodeError:
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _dedupe_events(events: list[InsightEvent]) -> list[InsightEvent]:
+ seen: set[tuple[str, int, str]] = set()
+ deduped: list[InsightEvent] = []
+ for event in sorted(events):
+ key = (str(event.agent), round(event.start_time), event.headline.lower())
+ if key in seen:
+ continue
+ seen.add(key)
+ deduped.append(event)
+ return deduped
+
+
+def _event_id(raw: dict[str, Any]) -> str:
+ return _stable_id(
+ str(raw.get("agent", "")),
+ raw.get("start_time", ""),
+ str(raw.get("headline", "")),
+ )
+
+
+def _stable_id(*parts: object) -> str:
+ digest = hashlib.sha1("|".join(str(part) for part in parts).encode()).hexdigest()
+ return digest[:12]
+
+
+def _has_gemini_key() -> bool:
+ if os.getenv("GEMINI_API_KEY") and not os.getenv("GOOGLE_API_KEY"):
+ os.environ["GOOGLE_API_KEY"] = os.environ["GEMINI_API_KEY"]
+ return bool(os.getenv("GOOGLE_API_KEY"))
+
+
+def _quote(text: str, needle: str) -> str:
+ sentences = re.split(r"(?<=[.!?])\s+", text)
+ for sentence in sentences:
+ if needle.lower() in sentence.lower():
+ return sentence.strip()[:420]
+ return text.strip()[:420]
+
+
+def _compact_context(text: str) -> str:
+ for term in ["revenue", "margin", "guidance", "cash", "eps", "growth"]:
+ if term in text:
+ return term
+ return "financial statement"
+
+
+def _default_citations(research: ResearchPack) -> list[Citation]:
+ citations = [Citation(label="Transcript segment", source="YouTube captions")]
+ if research.documents:
+ doc = research.documents[0]
+ citations.append(Citation(label=doc.kind, source=doc.title, url=doc.url))
+ return citations
+
+
+def _realign_event_times(
+ events: list[InsightEvent], chunks: list[TranscriptChunk]
+) -> list[InsightEvent]:
+ segments = [
+ segment
+ for chunk in chunks
+ for segment in chunk.segments
+ if segment.text.strip()
+ ]
+ if not segments:
+ return events
+
+ realigned: list[InsightEvent] = []
+ for event in events:
+ segment = _best_quote_segment(event.quote, event.start_time, segments)
+ if not segment:
+ realigned.append(event)
+ continue
+ realigned.append(
+ event.model_copy(
+ update={
+ "start_time": max(0, segment.start - 0.35),
+ "end_time": max(segment.end, segment.start + 0.75),
+ }
+ )
+ )
+ return realigned
+
+
+def _best_quote_segment(
+ quote: str, fallback_time: float, segments: list[TranscriptSegment]
+) -> TranscriptSegment | None:
+ quote_tokens = _token_set(quote)
+ if not quote_tokens:
+ return min(segments, key=lambda segment: abs(segment.start - fallback_time), default=None)
+
+ best: tuple[float, TranscriptSegment] | None = None
+ normalized_quote = _normalize_text(quote)
+ ordered_quote_tokens = [
+ token
+ for token in re.findall(r"[a-z0-9]+", quote.lower())
+ if len(token) > 2
+ ]
+ prefix_tokens = set(ordered_quote_tokens[: min(6, len(ordered_quote_tokens))])
+ first_token = ordered_quote_tokens[0] if ordered_quote_tokens else ""
+ second_token = ordered_quote_tokens[1] if len(ordered_quote_tokens) > 1 else ""
+ for segment in segments:
+ normalized_segment = _normalize_text(segment.text)
+ segment_tokens = _token_set(segment.text)
+ overlap = len(quote_tokens & segment_tokens) / max(1, len(quote_tokens))
+ prefix_overlap = len(prefix_tokens & segment_tokens) / max(1, len(prefix_tokens))
+ substring_bonus = 0.75 if normalized_quote and normalized_quote in normalized_segment else 0
+ start_bonus = 0.9 if first_token and first_token in segment_tokens else 0
+ start_bonus += 0.45 if second_token and second_token in segment_tokens else 0
+ time_penalty = min(0.35, abs(segment.start - fallback_time) / 900)
+ score = overlap + (prefix_overlap * 0.8) + substring_bonus + start_bonus - time_penalty
+ if best is None or score > best[0]:
+ best = (score, segment)
+
+ if not best or best[0] < 0.22:
+ return min(segments, key=lambda segment: abs(segment.start - fallback_time), default=None)
+ return best[1]
+
+
+def _token_set(text: str) -> set[str]:
+ return {
+ token
+ for token in re.findall(r"[a-z0-9]+", text.lower())
+ if len(token) > 2
+ }
+
+
+def _normalize_text(text: str) -> str:
+ return " ".join(re.findall(r"[a-z0-9]+", text.lower()))
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/assets/earnings-call-analyst-agent-architecture.png b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/assets/earnings-call-analyst-agent-architecture.png
new file mode 100644
index 00000000..3d381a19
Binary files /dev/null and b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/assets/earnings-call-analyst-agent-architecture.png differ
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/app.js b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/app.js
new file mode 100644
index 00000000..844885a3
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/app.js
@@ -0,0 +1,612 @@
+const SIGNALS = {
+ numbers_reconciler: {
+ label: "Financial metric",
+ shortLabel: "Metric",
+ color: "#ffad9b",
+ threshold: "Numbers that change the investment picture",
+ },
+ cfo_tone: {
+ label: "Tone shift",
+ shortLabel: "Tone",
+ color: "#8cf5c2",
+ threshold: "Confidence, caution, hedging, or defensiveness",
+ },
+ peer_context: {
+ label: "Peer context",
+ shortLabel: "Peers",
+ color: "#6f96ff",
+ threshold: "Company-specific versus sector-wide read-through",
+ },
+ surprise_detector: {
+ label: "Surprise",
+ shortLabel: "Surprise",
+ color: "#ff7759",
+ threshold: "New, contradictory, or market-moving statements",
+ },
+ filing_grounder: {
+ label: "Filing check",
+ shortLabel: "Filings",
+ color: "#d9d9dd",
+ threshold: "Transcript claim tied back to filings",
+ },
+ market_narrator: {
+ label: "Context",
+ shortLabel: "Context",
+ color: "#93939f",
+ threshold: "Source validation or call-level framing",
+ },
+};
+
+let player = null;
+let playerApiReady = false;
+let activeSessionId = "";
+let sessionData = null;
+let pollTimer = null;
+let playbackTimer = null;
+const revealed = new Set();
+
+const form = document.getElementById("urlForm");
+const input = document.getElementById("youtubeUrl");
+const analyzeButton = document.getElementById("analyzeButton");
+const healthLine = document.getElementById("healthLine");
+const statusText = document.getElementById("statusText");
+const progressBar = document.getElementById("progressBar");
+const statusSteps = Array.from(document.querySelectorAll(".status-steps span"));
+const companyBadge = document.getElementById("companyBadge");
+const researchGrid = document.getElementById("researchGrid");
+const timecode = document.getElementById("timecode");
+const watchState = document.getElementById("watchState");
+const timelineFeed = document.getElementById("timelineFeed");
+const timelineStatus = document.getElementById("timelineStatus");
+const streamSummary = document.getElementById("streamSummary");
+const revealNextButton = document.getElementById("revealNextButton");
+const showAllButton = document.getElementById("showAllButton");
+const videoPanel = document.querySelector(".video-panel");
+
+window.onYouTubeIframeAPIReady = () => {
+ playerApiReady = true;
+};
+if (window.YT && window.YT.Player) {
+ playerApiReady = true;
+}
+
+form.addEventListener("submit", async (event) => {
+ event.preventDefault();
+ const youtubeUrl = input.value.trim();
+ if (!youtubeUrl) return;
+
+ resetWorkspace();
+ analyzeButton.disabled = true;
+ setStatus(4, "Creating analysis session");
+
+ try {
+ const response = await fetch("/api/sessions", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ youtube_url: youtubeUrl }),
+ });
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.detail || "Could not create session.");
+ }
+ const payload = await response.json();
+ activeSessionId = payload.session_id;
+ pollSession();
+ pollTimer = window.setInterval(pollSession, 1500);
+ } catch (error) {
+ analyzeButton.disabled = false;
+ setStatus(100, error.message);
+ }
+});
+
+revealNextButton.addEventListener("click", () => revealNextInsight());
+showAllButton.addEventListener("click", () => revealAllInsights());
+
+async function pollSession() {
+ if (!activeSessionId) return;
+ let payload;
+ try {
+ const response = await fetch(`/api/sessions/${activeSessionId}`);
+ if (!response.ok) throw new Error("Backend session lookup failed.");
+ payload = await response.json();
+ } catch (error) {
+ setStatus(100, error.message || "Backend connection dropped.");
+ window.clearInterval(pollTimer);
+ analyzeButton.disabled = false;
+ return;
+ }
+ setStatus(payload.progress || 0, payload.message || payload.status);
+
+ if (payload.status === "error") {
+ window.clearInterval(pollTimer);
+ analyzeButton.disabled = false;
+ setStatus(100, payload.error || "Analysis failed.");
+ return;
+ }
+
+ if (payload.data) {
+ sessionData = payload.data;
+ renderSession(sessionData);
+ }
+
+ if (payload.status === "ready") {
+ window.clearInterval(pollTimer);
+ analyzeButton.disabled = false;
+ }
+}
+
+async function checkHealth() {
+ try {
+ const response = await fetch("/health");
+ const health = await response.json();
+ healthLine.textContent = health.has_google_key
+ ? "Gemini key detected"
+ : "No Gemini key detected; local fallback available";
+ } catch {
+ healthLine.textContent = "Backend unavailable";
+ }
+}
+
+function renderSession(data) {
+ const videoId = data.video.video_id;
+ if (!player) {
+ mountPlayer(videoId);
+ } else if (player.getVideoData && player.getVideoData().video_id !== videoId) {
+ player.loadVideoById(videoId);
+ }
+
+ renderResearch(data.research);
+ renderInsightDesk(data);
+ renderAnalystTimeline(data.insights);
+ watchState.textContent = data.insights.length
+ ? "Analyst cards are synced to playback"
+ : "Research loaded; no high-signal cards found";
+
+ if (!playbackTimer) {
+ playbackTimer = window.setInterval(syncPlayback, 500);
+ }
+}
+
+function renderInsightDesk(data) {
+ const total = data.insights.length;
+ const locked = Math.max(0, total - revealed.size);
+ if (total) {
+ streamSummary.textContent = `${revealed.size} of ${total} analyst signals visible. Future signals stay collapsed until playback reaches them.`;
+ } else {
+ streamSummary.textContent = "The transcript and research loaded, but no strong investor signal was detected.";
+ }
+ revealNextButton.disabled = locked === 0;
+ showAllButton.disabled = locked === 0;
+}
+
+function mountPlayer(videoId) {
+ const mount = () => {
+ player = new YT.Player("player", {
+ videoId,
+ playerVars: {
+ rel: 0,
+ modestbranding: 1,
+ playsinline: 1,
+ },
+ events: {
+ onReady: syncPlayback,
+ },
+ });
+ };
+
+ if (playerApiReady && window.YT && window.YT.Player) {
+ mount();
+ } else {
+ const wait = window.setInterval(() => {
+ if (playerApiReady && window.YT && window.YT.Player) {
+ window.clearInterval(wait);
+ mount();
+ }
+ }, 120);
+ }
+}
+
+function renderResearch(research) {
+ companyBadge.textContent = research.ticker
+ ? `${research.company} Β· ${research.ticker}`
+ : research.company;
+
+ const docs = research.documents || [];
+ const news = research.news || [];
+
+ const peerText = research.peers && research.peers.length
+ ? research.peers.map((peer) => `<span>${escapeHtml(peer)}</span>`).join("")
+ : "<em>Unresolved</em>";
+
+ const newsCard = news.length
+ ? `
+ <article class="research-card research-news">
+ <span>News</span>
+ <strong>Latest external context</strong>
+ ${renderResearchLinks(news.slice(0, 4), "")}
+ </article>
+ `
+ : "";
+
+ researchGrid.innerHTML = `
+ <article class="research-card research-primary">
+ <span>Company</span>
+ <strong>${escapeHtml(research.ticker || research.company)}</strong>
+ <p>${escapeHtml(research.fiscal_period || "Period unresolved")}</p>
+ <div class="research-chips">${peerText}</div>
+ </article>
+ <article class="research-card">
+ <span>Filings</span>
+ <strong>${docs.length ? "Primary source links" : "No SEC filing linked"}</strong>
+ ${renderResearchLinks(docs.slice(0, 3), "Agent will cite transcript-first.")}
+ </article>
+ ${newsCard}
+ `;
+}
+
+function syncPlayback() {
+ if (!sessionData || !player || typeof player.getCurrentTime !== "function") return;
+ const current = player.getCurrentTime();
+ timecode.textContent = formatTime(current);
+ revealDueInsights(current);
+ updateTimelinePlayback(current);
+}
+
+function revealDueInsights(currentTime) {
+ const due = sessionData.insights
+ .filter((insight) => insight.start_time <= currentTime && !revealed.has(insight.id))
+ .sort((a, b) => a.start_time - b.start_time);
+
+ if (!due.length) return;
+ due.forEach((insight) => revealed.add(insight.id));
+ updateRevealState({ scrollToId: due[due.length - 1].id });
+}
+
+function revealNextInsight() {
+ if (!sessionData) return;
+ const next = sessionData.insights.find((insight) => !revealed.has(insight.id));
+ if (next) {
+ revealed.add(next.id);
+ seekTo(next.start_time, { reveal: false });
+ updateRevealState({ scrollToId: next.id });
+ }
+}
+
+function revealAllInsights() {
+ if (!sessionData) return;
+ sessionData.insights.forEach((insight) => revealed.add(insight.id));
+ updateRevealState();
+}
+
+function revealInsightById(id) {
+ if (!sessionData || !id) return;
+ const insight = sessionData.insights.find((item) => item.id === id);
+ if (!insight) return;
+ revealed.add(insight.id);
+ seekTo(insight.start_time, { reveal: false });
+ updateRevealState({ scrollToId: insight.id });
+}
+
+function updateRevealState(options = {}) {
+ if (sessionData) {
+ renderInsightDesk(sessionData);
+ renderAnalystTimeline(sessionData.insights);
+ if (options.scrollToId) scrollTimelineTo(options.scrollToId);
+ }
+}
+
+function renderAnalystTimeline(insights) {
+ if (!insights.length) {
+ timelineStatus.textContent = "Quiet";
+ timelineFeed.innerHTML = '<div class="empty-feed">No high-signal analyst cards were emitted for this source.</div>';
+ return;
+ }
+
+ const current = getCurrentPlaybackTime();
+ const next = insights.find((insight) => !revealed.has(insight.id));
+ timelineStatus.textContent = next ? `Next ${formatTime(next.start_time)}` : "All visible";
+ timelineFeed.innerHTML = insights.map((insight) => renderTimelineItem(insight, current)).join("");
+ timelineFeed.querySelectorAll("[data-action='jump']").forEach((button) => {
+ button.addEventListener("click", () => {
+ revealInsightById(button.dataset.id);
+ });
+ });
+}
+
+function renderTimelineItem(insight, current) {
+ const meta = SIGNALS[insight.agent] || SIGNALS.market_narrator;
+ const state = revealed.has(insight.id)
+ ? "revealed"
+ : current >= insight.start_time
+ ? "current"
+ : "upcoming";
+ const stateLabel = state === "revealed" ? "Seen" : state === "current" ? "Now" : "Upcoming";
+ if (state === "upcoming") {
+ return `
+ <article class="timeline-card upcoming" style="--agent-color: ${meta.color}" data-id="${escapeHtml(insight.id)}">
+ <div class="time-rail">
+ <span>${formatTime(insight.start_time)}</span>
+ </div>
+ <div class="card-body">
+ <div class="card-top">
+ <span class="agent-tag">${escapeHtml(meta.label)}</span>
+ <span class="severity">${stateLabel}</span>
+ </div>
+ <h3>Signal queued</h3>
+ <p class="quote preview">${escapeHtml(meta.threshold)}</p>
+ <div class="card-foot">
+ <button type="button" data-action="jump" data-id="${escapeHtml(insight.id)}">Jump and reveal</button>
+ <div class="citations">Unlocks at ${formatTime(insight.start_time)}</div>
+ </div>
+ </div>
+ </article>
+ `;
+ }
+ return `
+ <article class="timeline-card ${state}" style="--agent-color: ${meta.color}" data-id="${escapeHtml(insight.id)}">
+ <div class="time-rail">
+ <span>${formatTime(insight.start_time)}</span>
+ </div>
+ <div class="card-body">
+ <div class="card-top">
+ <span class="agent-tag">${escapeHtml(meta.label)}</span>
+ <span class="severity">${stateLabel}</span>
+ </div>
+ <h3>${escapeHtml(insight.headline)}</h3>
+ <p class="quote">${escapeHtml(stripOuterQuotes(insight.quote))}</p>
+ ${insight.explanation ? `<p class="why">${escapeHtml(insight.explanation)}</p>` : ""}
+ ${renderMiniViz(insight.mini_viz)}
+ <div class="card-foot">
+ <button type="button" data-action="jump" data-id="${escapeHtml(insight.id)}">Jump to quote</button>
+ <div class="citations">${renderCitations(insight.citations)}</div>
+ </div>
+ </div>
+ </article>
+ `;
+}
+
+function updateTimelinePlayback(current) {
+ if (!sessionData || !timelineFeed) return;
+ timelineFeed.querySelectorAll(".timeline-card").forEach((card) => {
+ const insight = sessionData.insights.find((item) => item.id === card.dataset.id);
+ if (!insight) return;
+ const state = revealed.has(insight.id)
+ ? "revealed"
+ : current >= insight.start_time
+ ? "current"
+ : "upcoming";
+ card.classList.toggle("revealed", state === "revealed");
+ card.classList.toggle("current", state === "current");
+ card.classList.toggle("upcoming", state === "upcoming");
+ });
+}
+
+function scrollTimelineTo(id) {
+ const card = timelineFeed.querySelector(`[data-id="${CSS.escape(id)}"]`);
+ if (!card) return;
+ card.scrollIntoView({ block: "nearest", behavior: "smooth" });
+}
+
+function getCurrentPlaybackTime() {
+ if (player && typeof player.getCurrentTime === "function") {
+ try {
+ return player.getCurrentTime();
+ } catch {
+ return 0;
+ }
+ }
+ return 0;
+}
+
+function renderMiniViz(viz) {
+ if (!viz) return "";
+ const title = viz.title || viz.type || "Signal";
+ if (viz.points && viz.points.length > 1) {
+ return renderPointViz(viz, title);
+ }
+ const rows = (viz.rows || [])
+ .filter((row) => row && (String(row[0] || "").trim() || String(row[1] || "").trim()))
+ .slice(0, 5)
+ .map((row) => `<div class="viz-row"><span>${escapeHtml(row[0] || "")}</span><strong>${escapeHtml(row[1] || "")}</strong></div>`)
+ .join("");
+ if (!rows) return "";
+ return `<div class="mini-viz"><div class="viz-title">${escapeHtml(title)}</div>${rows}</div>`;
+}
+
+function renderPointViz(viz, title) {
+ const rawPoints = (viz.points || [])
+ .map((point) => Number(point))
+ .filter((point) => Number.isFinite(point));
+ if (rawPoints.length < 2) return "";
+
+ const points = rawPoints.slice(-10);
+ const sourceLabels = Array.isArray(viz.labels) ? viz.labels.slice(-10) : [];
+ const labels = points.map((_, index) => {
+ const label = sourceLabels[index];
+ return label && String(label).trim() ? String(label).trim() : `Point ${index + 1}`;
+ });
+ const min = Math.min(...points);
+ const max = Math.max(...points);
+ const spread = max - min || 1;
+ const latest = points[points.length - 1];
+ const previous = points[points.length - 2];
+ const change = latest - previous;
+ const coordinates = points.map((point, index) => {
+ const x = points.length === 1 ? 50 : 6 + (index / (points.length - 1)) * 88;
+ const y = 40 - ((point - min) / spread) * 30;
+ return { x, y, point, label: labels[index] };
+ });
+ const line = coordinates.map((point) => `${point.x.toFixed(2)},${point.y.toFixed(2)}`).join(" ");
+ const pointButtons = coordinates
+ .map((coord) => {
+ const tooltip = `${coord.label}: ${formatVizNumber(coord.point)}`;
+ return `
+ <button
+ type="button"
+ class="chart-point"
+ style="left: ${coord.x}%; top: ${(coord.y / 46) * 100}%"
+ title="${escapeHtml(tooltip)}"
+ aria-label="${escapeHtml(tooltip)}"
+ data-tooltip="${escapeHtml(tooltip)}"
+ ></button>
+ `;
+ })
+ .join("");
+ const axisLabels = [coordinates[0], coordinates[coordinates.length - 1]]
+ .filter(Boolean)
+ .map((coord) => `<span style="left: ${coord.x}%">${escapeHtml(coord.label)}</span>`)
+ .join("");
+
+ return `
+ <div class="mini-viz metric-viz">
+ <div class="viz-title">${escapeHtml(title)}</div>
+ <div class="viz-summary">
+ <span><b>Latest</b>${formatVizNumber(latest)}</span>
+ <span><b>Change</b>${change >= 0 ? "+" : ""}${formatVizNumber(change)}</span>
+ <span><b>Range</b>${formatVizNumber(min)} - ${formatVizNumber(max)}</span>
+ </div>
+ <div class="metric-chart" role="img" aria-label="${escapeHtml(title)} values from ${escapeHtml(labels[0])} to ${escapeHtml(labels[labels.length - 1])}">
+ <svg viewBox="0 0 100 46" preserveAspectRatio="none" aria-hidden="true">
+ <line x1="0" y1="10" x2="100" y2="10"></line>
+ <line x1="0" y1="25" x2="100" y2="25"></line>
+ <line x1="0" y1="40" x2="100" y2="40"></line>
+ <polyline points="${line}"></polyline>
+ </svg>
+ ${pointButtons}
+ </div>
+ <div class="chart-axis">${axisLabels}</div>
+ </div>
+ `;
+}
+
+function renderCitations(citations) {
+ if (!citations || !citations.length) return "Transcript anchored";
+ return citations
+ .slice(0, 2)
+ .map((citation) => {
+ const label = escapeHtml(citation.label || citation.source || "Source");
+ return citation.url ? `<a href="${escapeHtml(citation.url)}" target="_blank" rel="noreferrer">${label}</a>` : label;
+ })
+ .join("<br>");
+}
+
+function renderResearchLinks(items, fallback) {
+ if (!items || !items.length) return `<p>${escapeHtml(fallback)}</p>`;
+ return `
+ <div class="research-links">
+ ${items
+ .map((item) => {
+ const label = item.kind && item.kind !== "news" ? item.kind : item.title;
+ return item.url
+ ? `<a href="${escapeHtml(item.url)}" target="_blank" rel="noreferrer">${escapeHtml(label)}</a>`
+ : `<span>${escapeHtml(label)}</span>`;
+ })
+ .join("")}
+ </div>
+ `;
+}
+
+function seekTo(seconds, options = { reveal: true }) {
+ if (player && typeof player.seekTo === "function") {
+ player.seekTo(seconds, true);
+ player.playVideo();
+ }
+ if (options.reveal !== false) {
+ revealDueInsights(seconds);
+ }
+ timecode.textContent = formatTime(seconds);
+}
+
+function resetWorkspace() {
+ window.clearInterval(pollTimer);
+ pollTimer = null;
+ if (player && typeof player.destroy === "function") {
+ player.destroy();
+ }
+ player = null;
+ setPlayerPlaceholder("Analyzing", "Building research and high-signal analyst cards");
+ sessionData = null;
+ activeSessionId = "";
+ revealed.clear();
+ timelineFeed.innerHTML = '<div class="empty-feed">Timestamped analyst cards will appear here.</div>';
+ researchGrid.innerHTML = "";
+ companyBadge.textContent = "No company loaded";
+ timelineStatus.textContent = "Waiting";
+ streamSummary.textContent = "Paste a URL to build a playback-synced analyst overlay.";
+ timecode.textContent = "00:00";
+ watchState.textContent = "Preparing analysis";
+ revealNextButton.disabled = true;
+ showAllButton.disabled = true;
+}
+
+function setStatus(progress, text) {
+ progressBar.style.width = `${Math.max(0, Math.min(100, progress))}%`;
+ statusText.textContent = text;
+ updateStage(progress);
+}
+
+function updateStage(progress) {
+ const ordered = [
+ ["metadata", 10],
+ ["transcript", 25],
+ ["research", 45],
+ ["analysis", 70],
+ ["ready", 100],
+ ];
+ const active = [...ordered].reverse().find(([, threshold]) => progress >= threshold)?.[0] || "";
+ statusSteps.forEach((step) => {
+ const stage = step.dataset.stage;
+ const threshold = ordered.find(([name]) => name === stage)?.[1] || 0;
+ step.classList.toggle("done", progress >= threshold);
+ step.classList.toggle("active", stage === active && progress < 100);
+ });
+}
+
+function setPlayerPlaceholder(label, headline) {
+ if (!videoPanel) return;
+ videoPanel.innerHTML = `
+ <div id="player" class="player-empty">
+ <div class="empty-state">
+ <span>${escapeHtml(label)}</span>
+ <strong>${escapeHtml(headline)}</strong>
+ </div>
+ </div>
+ `;
+}
+
+function formatTime(seconds) {
+ const total = Math.max(0, Math.floor(seconds));
+ const mins = Math.floor(total / 60);
+ const secs = total % 60;
+ const hours = Math.floor(mins / 60);
+ if (hours) {
+ return `${hours}:${String(mins % 60).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
+ }
+ return `${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
+}
+
+function stripOuterQuotes(value) {
+ const text = String(value ?? "").trim();
+ return text.replace(/^["'β€œβ€β€˜β€™]+|["'β€œβ€β€˜β€™]+$/g, "");
+}
+
+function formatVizNumber(value) {
+ const number = Number(value);
+ if (!Number.isFinite(number)) return "";
+ const abs = Math.abs(number);
+ if (abs >= 1000) return number.toLocaleString(undefined, { maximumFractionDigits: 1 });
+ if (abs >= 100) return number.toLocaleString(undefined, { maximumFractionDigits: 1 });
+ if (abs >= 10) return number.toLocaleString(undefined, { maximumFractionDigits: 2 });
+ return number.toLocaleString(undefined, { maximumFractionDigits: 3 });
+}
+
+function escapeHtml(value) {
+ return String(value ?? "")
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;")
+ .replaceAll('"', "&quot;")
+ .replaceAll("'", "&#039;");
+}
+
+checkHealth();
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/index.html b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/index.html
new file mode 100644
index 00000000..ea69898d
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/index.html
@@ -0,0 +1,93 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Earnings Call Analyst Agent</title>
+ <link rel="icon" href="data:," />
+ <link rel="stylesheet" href="/static/styles.css?v=20260506-robust-audit" />
+ </head>
+ <body>
+ <main class="shell">
+ <header class="topbar">
+ <div class="brand">
+ <span class="mark">EC</span>
+ <div>
+ <h1>Earnings Call Analyst Agent</h1>
+ <p id="healthLine">Connecting backend</p>
+ </div>
+ </div>
+ <form id="urlForm" class="url-form">
+ <input
+ id="youtubeUrl"
+ name="youtubeUrl"
+ type="url"
+ placeholder="Paste a YouTube earnings-call URL"
+ autocomplete="off"
+ required
+ />
+ <button id="analyzeButton" type="submit">Analyze</button>
+ </form>
+ </header>
+
+ <section class="status-strip">
+ <div class="progress-track"><span id="progressBar"></span></div>
+ <div id="statusText">Waiting for a YouTube URL</div>
+ <div class="status-steps" aria-label="Analysis pipeline">
+ <span data-stage="metadata">Video</span>
+ <span data-stage="transcript">Transcript</span>
+ <span data-stage="research">Research</span>
+ <span data-stage="analysis">Signals</span>
+ <span data-stage="ready">Ready</span>
+ </div>
+ </section>
+
+ <section class="workspace">
+ <section class="watch-column">
+ <div class="video-panel">
+ <div id="player" class="player-empty">
+ <div class="empty-state">
+ <span>Paste URL</span>
+ <strong>Playback-synced analyst cockpit</strong>
+ </div>
+ </div>
+ </div>
+ <div class="watch-status">
+ <span id="timecode">00:00</span>
+ <strong id="watchState">Waiting for a YouTube URL</strong>
+ </div>
+
+ <div class="research-panel">
+ <div class="panel-heading">
+ <h2>Research Pack</h2>
+ <span id="companyBadge">No company loaded</span>
+ </div>
+ <div id="researchGrid" class="research-grid"></div>
+ </div>
+ </section>
+
+ <aside class="insight-column">
+ <div class="feed-panel timeline-workbench">
+ <div class="stream-header">
+ <div>
+ <h2>Analyst Stream</h2>
+ <p id="streamSummary">Paste a URL to build a playback-synced analyst overlay.</p>
+ </div>
+ <span id="timelineStatus">Waiting</span>
+ </div>
+ <div class="stream-controls">
+ <button id="revealNextButton" type="button" disabled>Reveal next signal</button>
+ <button id="showAllButton" type="button" disabled>Show all</button>
+ </div>
+ <div id="timelineFeed" class="analyst-timeline">
+ <div class="empty-feed">Timestamped analyst cards will appear here.</div>
+ </div>
+ </div>
+ </aside>
+ </section>
+ </main>
+
+ <script src="https://www.youtube.com/iframe_api"></script>
+ <script src="/static/app.js?v=20260506-robust-audit"></script>
+ </body>
+</html>
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/server.py b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/server.py
new file mode 100644
index 00000000..1e790594
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/server.py
@@ -0,0 +1,205 @@
+from __future__ import annotations
+
+import asyncio
+import os
+import sys
+import uuid
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Literal
+
+from fastapi import BackgroundTasks, FastAPI, HTTPException
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import FileResponse
+from fastapi.staticfiles import StaticFiles
+from pydantic import BaseModel
+
+APP_DIR = Path(__file__).resolve().parents[1]
+DEMO_DIR = Path(__file__).resolve().parent
+APP_PARENT_DIR = APP_DIR.parent
+if str(APP_PARENT_DIR) not in sys.path:
+ sys.path.insert(0, str(APP_PARENT_DIR))
+
+
+def _load_env() -> None:
+ env_path = APP_DIR / ".env"
+ if not env_path.exists():
+ return
+ for line in env_path.read_text().splitlines():
+ line = line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, value = line.split("=", 1)
+ os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
+
+
+_load_env()
+if os.getenv("GEMINI_API_KEY") and not os.getenv("GOOGLE_API_KEY"):
+ os.environ["GOOGLE_API_KEY"] = os.environ["GEMINI_API_KEY"]
+
+from earnings_call_analyst_agent.agent import generate_insights # noqa: E402
+from earnings_call_analyst_agent.research import build_research_pack # noqa: E402
+from earnings_call_analyst_agent.schemas import AnalysisSession # noqa: E402
+from earnings_call_analyst_agent.youtube_ingest import ( # noqa: E402
+ chunk_transcript,
+ extract_video_id,
+ fetch_transcript,
+ fetch_video_metadata,
+ transcribe_audio_with_adk,
+)
+
+
+class SessionRequest(BaseModel):
+ youtube_url: str
+
+
+class SessionCreated(BaseModel):
+ session_id: str
+
+
+@dataclass
+class RuntimeSession:
+ session_id: str
+ youtube_url: str
+ status: Literal["queued", "metadata", "transcript", "research", "analysis", "ready", "error"] = "queued"
+ progress: int = 0
+ message: str = "Queued"
+ data: AnalysisSession | None = None
+ error: str = ""
+ diagnostics: dict[str, Any] = field(default_factory=dict)
+
+
+sessions: dict[str, RuntimeSession] = {}
+session_lock = asyncio.Lock()
+
+app = FastAPI(title="Earnings Call Analyst Agent")
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["http://127.0.0.1:4188", "http://localhost:4188"],
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+app.mount("/static", StaticFiles(directory=DEMO_DIR), name="static")
+
+
+def index() -> FileResponse:
+ return FileResponse(DEMO_DIR / "index.html")
+
+
+def health() -> dict[str, Any]:
+ return {
+ "ok": True,
+ "has_google_key": bool(os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY")),
+ }
+
+
[email protected]("/api/sessions", response_model=SessionCreated)
+async def create_session(request: SessionRequest, background_tasks: BackgroundTasks) -> SessionCreated:
+ try:
+ extract_video_id(request.youtube_url)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ session_id = uuid.uuid4().hex[:12]
+ runtime = RuntimeSession(session_id=session_id, youtube_url=request.youtube_url)
+ async with session_lock:
+ sessions[session_id] = runtime
+ background_tasks.add_task(_run_session, session_id)
+ return SessionCreated(session_id=session_id)
+
+
[email protected]("/api/sessions/{session_id}")
+async def get_session(session_id: str) -> dict[str, Any]:
+ runtime = sessions.get(session_id)
+ if not runtime:
+ raise HTTPException(status_code=404, detail="Unknown analysis session.")
+ payload: dict[str, Any] = {
+ "session_id": runtime.session_id,
+ "status": runtime.status,
+ "progress": runtime.progress,
+ "message": runtime.message,
+ "error": runtime.error,
+ "diagnostics": runtime.diagnostics,
+ }
+ if runtime.data:
+ payload["data"] = runtime.data.model_dump()
+ return payload
+
+
+async def _run_session(session_id: str) -> None:
+ runtime = sessions[session_id]
+ try:
+ await _set_status(runtime, "metadata", 10, "Resolving YouTube video")
+ video_id = extract_video_id(runtime.youtube_url)
+ metadata = await asyncio.to_thread(fetch_video_metadata, runtime.youtube_url, video_id)
+
+ await _set_status(runtime, "transcript", 25, "Loading YouTube captions")
+ try:
+ transcript = await asyncio.to_thread(fetch_transcript, video_id)
+ transcript_source = "youtube_captions"
+ except Exception:
+ await _set_status(
+ runtime,
+ "transcript",
+ 32,
+ "Captions unavailable; transcribing audio with ADK",
+ )
+ transcript = await asyncio.to_thread(
+ transcribe_audio_with_adk,
+ video_id,
+ lambda progress, message: _set_status_from_thread(runtime, progress, message),
+ )
+ transcript_source = "adk_audio"
+ if not transcript:
+ raise RuntimeError("This video did not return usable transcript segments.")
+ chunks = chunk_transcript(transcript, window_seconds=42)
+
+ await _set_status(runtime, "research", 45, "Building company research pack")
+ research = await asyncio.to_thread(build_research_pack, metadata, transcript)
+
+ await _set_status(runtime, "analysis", 70, "Curating high-signal analyst cards")
+ insights = await asyncio.to_thread(generate_insights, metadata, research, chunks)
+
+ runtime.data = AnalysisSession(
+ session_id=session_id,
+ video=metadata,
+ transcript=transcript,
+ chunks=chunks,
+ research=research,
+ insights=insights,
+ status="ready" if insights else "partial",
+ message="Ready" if insights else "Ready with transcript and research; no high-signal insights were emitted.",
+ diagnostics={
+ "transcript_segments": len(transcript),
+ "transcript_source": transcript_source,
+ "chunks": len(chunks),
+ "insights": len(insights),
+ "analysis_engine": "adk" if os.getenv("GOOGLE_API_KEY") else "local_fallback",
+ },
+ )
+ await _set_status(runtime, "ready", 100, runtime.data.message)
+ except Exception as exc:
+ runtime.status = "error"
+ runtime.progress = 100
+ runtime.error = str(exc)
+ runtime.message = "Analysis failed"
+
+
+async def _set_status(
+ runtime: RuntimeSession,
+ status: Literal["queued", "metadata", "transcript", "research", "analysis", "ready", "error"],
+ progress: int,
+ message: str,
+) -> None:
+ runtime.status = status
+ runtime.progress = progress
+ runtime.message = message
+ await asyncio.sleep(0)
+
+
+def _set_status_from_thread(runtime: RuntimeSession, progress: int, message: str) -> None:
+ runtime.status = "transcript"
+ runtime.progress = progress
+ runtime.message = message
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/styles.css b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/styles.css
new file mode 100644
index 00000000..a8bb74ec
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/live_demo/styles.css
@@ -0,0 +1,1030 @@
+:root {
+ color-scheme: dark;
+ --canvas: #020504;
+ --green-field: #003c33;
+ --navy-field: #071829;
+ --surface: #0a1110;
+ --surface-2: #11191a;
+ --surface-3: #17171c;
+ --ink: #ffffff;
+ --body: #e7ebe8;
+ --muted: #93939f;
+ --slate: #75758a;
+ --hairline: rgba(217, 217, 221, 0.18);
+ --hairline-strong: rgba(229, 231, 235, 0.28);
+ --blue: #4c6ee6;
+ --link-blue: #6f96ff;
+ --coral: #ff7759;
+ --soft-coral: #ffad9b;
+ --green: #8cf5c2;
+ --radius-sm: 8px;
+ --radius-md: 16px;
+ --radius-lg: 22px;
+ --radius-pill: 9999px;
+ --display-font: "Space Grotesk", Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ --body-font: Inter, Arial, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ --mono-font: "SFMono-Regular", "CohereMono", ui-monospace, Menlo, Monaco, Consolas, monospace;
+ font-family: var(--body-font);
+}
+
+* {
+ box-sizing: border-box;
+}
+
+body {
+ margin: 0;
+ min-height: 100vh;
+ overflow: hidden;
+ background: var(--canvas);
+ color: var(--body);
+}
+
+button,
+input {
+ font: inherit;
+}
+
+button {
+ transition:
+ border-color 160ms ease,
+ color 160ms ease,
+ background 160ms ease,
+ opacity 160ms ease;
+}
+
+button:focus-visible,
+input:focus-visible,
+a:focus-visible {
+ outline: 2px solid var(--blue);
+ outline-offset: 2px;
+}
+
+.shell {
+ display: grid;
+ grid-template-rows: auto auto minmax(0, 1fr);
+ height: 100vh;
+ padding: 18px;
+ background: var(--canvas);
+}
+
+.topbar {
+ display: grid;
+ grid-template-columns: minmax(320px, 0.86fr) minmax(420px, 1.14fr);
+ gap: 24px;
+ align-items: center;
+ margin-bottom: 16px;
+}
+
+.brand {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ min-width: 0;
+}
+
+.mark {
+ display: grid;
+ width: 48px;
+ height: 48px;
+ flex: 0 0 auto;
+ place-items: center;
+ border: 1px solid var(--hairline-strong);
+ border-radius: var(--radius-sm);
+ background: #000000;
+ color: var(--ink);
+ font-family: var(--mono-font);
+ font-size: 13px;
+ font-weight: 500;
+ letter-spacing: 0.04em;
+}
+
+h1,
+h2,
+p {
+ margin: 0;
+}
+
+h1 {
+ color: var(--ink);
+ font-family: var(--display-font);
+ font-size: clamp(24px, 2.8vw, 38px);
+ font-weight: 400;
+ letter-spacing: -0.035em;
+ line-height: 0.98;
+}
+
+.brand p,
+.panel-heading span,
+.status-strip,
+.empty-feed {
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.url-form {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ gap: 10px;
+ padding: 6px;
+ border: 1px solid var(--hairline);
+ border-radius: var(--radius-lg);
+ background: rgba(10, 17, 16, 0.86);
+}
+
+.url-form input {
+ min-width: 0;
+ height: 44px;
+ padding: 0 16px;
+ border: 1px solid transparent;
+ border-radius: var(--radius-md);
+ background: transparent;
+ color: var(--ink);
+ outline: none;
+}
+
+.url-form input::placeholder {
+ color: var(--slate);
+}
+
+.url-form input:focus {
+ border-color: rgba(155, 96, 170, 0.72);
+ background: rgba(255, 255, 255, 0.025);
+}
+
+.url-form button,
+.stream-controls button,
+.card-foot button {
+ border-radius: var(--radius-pill);
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 1.7;
+}
+
+.url-form button {
+ height: 44px;
+ padding: 0 24px;
+ border: 1px solid #ffffff;
+ background: #ffffff;
+ color: #17171c;
+ cursor: pointer;
+}
+
+.url-form button:hover {
+ background: transparent;
+ color: var(--ink);
+}
+
+.url-form button:disabled {
+ border-color: var(--hairline);
+ background: transparent;
+ color: var(--muted);
+ cursor: wait;
+ opacity: 0.5;
+}
+
+.status-strip {
+ display: grid;
+ grid-template-columns: 220px minmax(160px, 1fr) auto;
+ gap: 14px;
+ align-items: center;
+ min-height: 38px;
+ margin-bottom: 16px;
+ padding: 0 2px;
+ font-family: var(--mono-font);
+ letter-spacing: 0.02em;
+}
+
+.progress-track {
+ height: 2px;
+ overflow: hidden;
+ border-radius: var(--radius-pill);
+ background: rgba(217, 217, 221, 0.18);
+}
+
+.progress-track span {
+ display: block;
+ width: 0%;
+ height: 100%;
+ border-radius: inherit;
+ background: var(--soft-coral);
+ transition: width 260ms ease;
+}
+
+.status-steps {
+ display: flex;
+ gap: 8px;
+ justify-content: flex-end;
+}
+
+.status-steps span {
+ display: inline-flex;
+ min-height: 28px;
+ align-items: center;
+ padding: 4px 11px;
+ border: 1px solid var(--hairline);
+ border-radius: var(--radius-pill);
+ color: var(--slate);
+ font-family: var(--mono-font);
+ font-size: 10px;
+ font-weight: 400;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ white-space: nowrap;
+}
+
+.status-steps span.active {
+ border-color: rgba(255, 173, 155, 0.74);
+ color: var(--soft-coral);
+ background: rgba(255, 119, 89, 0.08);
+}
+
+.status-steps span.done {
+ border-color: rgba(140, 245, 194, 0.48);
+ color: var(--green);
+}
+
+.workspace {
+ display: grid;
+ grid-template-columns: minmax(520px, 1.22fr) minmax(420px, 0.78fr);
+ gap: 16px;
+ min-height: 0;
+ align-items: stretch;
+}
+
+.watch-column,
+.insight-column {
+ display: grid;
+ min-height: 0;
+ gap: 16px;
+}
+
+.watch-column {
+ grid-template-rows: minmax(220px, 1fr) auto minmax(132px, 0.72fr);
+ overflow: hidden;
+}
+
+.insight-column {
+ grid-template-rows: minmax(0, 1fr);
+ overflow: hidden;
+}
+
+.video-panel,
+.research-panel,
+.feed-panel {
+ border: 1px solid var(--hairline);
+ border-radius: var(--radius-lg);
+ background: rgba(10, 17, 16, 0.94);
+}
+
+.video-panel {
+ overflow: hidden;
+ min-height: 0;
+ background: #000000;
+}
+
+.research-panel {
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr);
+ min-height: 0;
+ overflow: hidden;
+}
+
+.watch-status {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ align-items: center;
+ padding: 10px 14px;
+ border: 1px solid var(--hairline);
+ border-radius: var(--radius-pill);
+ background: rgba(0, 0, 0, 0.28);
+}
+
+.watch-status span {
+ color: var(--soft-coral);
+ font-family: var(--mono-font);
+ font-size: 12px;
+ font-weight: 400;
+ font-variant-numeric: tabular-nums;
+}
+
+.watch-status strong {
+ min-width: 0;
+ color: var(--muted);
+ font-size: 13px;
+ font-weight: 400;
+ line-height: 1.35;
+ text-align: right;
+}
+
+#player,
+.player-empty,
+iframe {
+ width: 100%;
+ height: 100%;
+}
+
+.empty-state {
+ display: grid;
+ height: 100%;
+ place-items: center;
+ align-content: center;
+ gap: 12px;
+ background: #071829;
+ text-align: center;
+}
+
+.empty-state span {
+ color: var(--soft-coral);
+ font-family: var(--mono-font);
+ font-size: 12px;
+ font-weight: 400;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+}
+
+.empty-state strong {
+ width: min(520px, 82%);
+ color: var(--ink);
+ font-family: var(--display-font);
+ font-size: clamp(30px, 4vw, 56px);
+ font-weight: 400;
+ letter-spacing: -0.035em;
+ line-height: 0.98;
+}
+
+.panel-heading {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ align-items: center;
+ padding: 18px 18px 12px;
+ border-bottom: 1px solid rgba(217, 217, 221, 0.08);
+}
+
+.panel-heading h2 {
+ color: var(--ink);
+ font-family: var(--mono-font);
+ font-size: 12px;
+ font-weight: 400;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+}
+
+.research-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ align-content: start;
+ min-height: 0;
+ overflow: auto;
+ padding: 0 18px 18px;
+}
+
+.research-card {
+ min-height: 116px;
+ padding: 15px 14px;
+ border-top: 1px solid var(--hairline);
+ background: transparent;
+}
+
+.research-card:nth-child(odd) {
+ border-right: 1px solid var(--hairline);
+}
+
+.research-news {
+ grid-column: 1 / -1;
+ border-right: 0;
+}
+
+.research-card span {
+ display: block;
+ margin-bottom: 10px;
+ color: var(--muted);
+ font-family: var(--mono-font);
+ font-size: 11px;
+ font-weight: 400;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.research-card strong {
+ display: block;
+ color: var(--ink);
+ font-size: 18px;
+ font-weight: 400;
+ letter-spacing: -0.01em;
+ line-height: 1.22;
+}
+
+.research-card p {
+ margin-top: 9px;
+ color: var(--muted);
+ font-size: 14px;
+ line-height: 1.42;
+}
+
+.research-primary {
+ background: rgba(0, 60, 51, 0.18);
+}
+
+.research-links,
+.research-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 7px;
+ margin-top: 12px;
+}
+
+.research-links a,
+.research-links span,
+.research-chips span,
+.research-chips em {
+ display: inline-flex;
+ max-width: 100%;
+ min-height: 28px;
+ align-items: center;
+ padding: 4px 11px;
+ border: 1px solid rgba(255, 173, 155, 0.46);
+ border-radius: var(--radius-pill);
+ color: var(--body);
+ font-size: 12px;
+ font-style: normal;
+ line-height: 1.25;
+ text-decoration: none;
+}
+
+.research-links a {
+ border-color: rgba(111, 150, 255, 0.48);
+ color: var(--link-blue);
+}
+
+.research-links a:hover {
+ border-color: var(--link-blue);
+}
+
+.timeline-workbench {
+ display: grid;
+ grid-template-rows: auto auto minmax(0, 1fr);
+ min-height: 0;
+ overflow: hidden;
+ background: var(--surface);
+}
+
+.stream-header {
+ display: flex;
+ justify-content: space-between;
+ gap: 18px;
+ align-items: flex-start;
+ padding: 22px 22px 16px;
+ border-bottom: 1px solid rgba(217, 217, 221, 0.1);
+}
+
+.stream-header h2 {
+ color: var(--ink);
+ font-family: var(--display-font);
+ font-size: clamp(28px, 2.7vw, 42px);
+ font-weight: 400;
+ letter-spacing: -0.035em;
+ line-height: 0.98;
+}
+
+.stream-header p {
+ max-width: 430px;
+ margin-top: 10px;
+ color: var(--muted);
+ font-size: 15px;
+ line-height: 1.42;
+}
+
+.stream-header span {
+ flex: 0 0 auto;
+ min-height: 30px;
+ padding: 6px 12px;
+ border: 1px solid rgba(255, 173, 155, 0.46);
+ border-radius: var(--radius-pill);
+ background: rgba(255, 119, 89, 0.08);
+ color: var(--soft-coral);
+ font-family: var(--mono-font);
+ font-size: 11px;
+ font-weight: 400;
+ letter-spacing: 0.05em;
+ white-space: nowrap;
+}
+
+.stream-controls {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 10px;
+ padding: 0 22px 18px;
+}
+
+.stream-controls button {
+ min-width: 84px;
+ min-height: 42px;
+ border: 1px solid var(--hairline-strong);
+ background: transparent;
+ color: var(--body);
+ cursor: pointer;
+}
+
+.stream-controls button:first-child {
+ border-color: #ffffff;
+ background: #ffffff;
+ color: #17171c;
+}
+
+.stream-controls button:first-child:hover {
+ background: transparent;
+ color: var(--ink);
+}
+
+.stream-controls button:not(:first-child):hover {
+ border-color: rgba(255, 255, 255, 0.74);
+}
+
+.stream-controls button:disabled {
+ border-color: var(--hairline);
+ background: transparent;
+ color: var(--muted);
+ cursor: not-allowed;
+ opacity: 0.62;
+}
+
+.empty-feed {
+ padding: 28px;
+ border: 1px dashed var(--hairline);
+ border-radius: var(--radius-md);
+ text-align: center;
+}
+
+.analyst-timeline {
+ display: grid;
+ align-content: start;
+ gap: 14px;
+ min-height: 0;
+ overflow: auto;
+ padding: 0 22px 22px;
+ scrollbar-color: rgba(255, 173, 155, 0.48) transparent;
+}
+
+.timeline-card {
+ display: grid;
+ grid-template-columns: 64px minmax(0, 1fr);
+ gap: 12px;
+ animation: enter 220ms ease both;
+}
+
+.time-rail {
+ position: relative;
+ display: flex;
+ justify-content: center;
+ padding-top: 14px;
+}
+
+.time-rail::before {
+ content: "";
+ position: absolute;
+ top: 0;
+ bottom: -24px;
+ left: 50%;
+ width: 1px;
+ background: var(--hairline);
+}
+
+.time-rail span {
+ position: relative;
+ z-index: 1;
+ display: inline-grid;
+ width: 58px;
+ height: 30px;
+ place-items: center;
+ border: 1px solid color-mix(in srgb, var(--agent-color) 42%, var(--hairline-strong));
+ border-radius: var(--radius-pill);
+ background: var(--surface);
+ color: var(--agent-color);
+ font-family: var(--mono-font);
+ font-size: 11px;
+ font-weight: 400;
+ font-variant-numeric: tabular-nums;
+}
+
+.card-body {
+ border: 1px solid color-mix(in srgb, var(--agent-color) 36%, var(--hairline));
+ border-radius: var(--radius-md);
+ background: rgba(23, 23, 28, 0.86);
+}
+
+.timeline-card.upcoming .card-body {
+ border-color: var(--hairline);
+ background: rgba(10, 17, 16, 0.72);
+}
+
+.timeline-card.upcoming .time-rail span {
+ border-color: var(--hairline);
+ color: var(--muted);
+}
+
+.timeline-card.current .card-body {
+ border-color: color-mix(in srgb, var(--agent-color) 58%, var(--hairline-strong));
+}
+
+@keyframes enter {
+ from {
+ opacity: 0;
+ transform: translateY(-6px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+.card-top {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 16px 16px 0;
+}
+
+.agent-tag {
+ color: var(--agent-color);
+ font-family: var(--mono-font);
+ font-size: 11px;
+ font-weight: 400;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+}
+
+.severity {
+ color: var(--muted);
+ font-family: var(--mono-font);
+ font-size: 11px;
+ font-weight: 400;
+}
+
+.timeline-card h3 {
+ margin: 10px 16px 10px;
+ color: var(--ink);
+ font-family: var(--display-font);
+ font-size: 24px;
+ font-weight: 400;
+ letter-spacing: -0.025em;
+ line-height: 1.12;
+}
+
+.quote {
+ margin: 0 16px;
+ padding-left: 12px;
+ border-left: 2px solid var(--agent-color);
+ color: var(--body);
+ font-size: 14px;
+ line-height: 1.45;
+}
+
+.quote.preview {
+ border-left-color: var(--hairline-strong);
+ color: var(--muted);
+}
+
+.why {
+ margin: 12px 16px 0;
+ color: var(--muted);
+ font-size: 14px;
+ line-height: 1.48;
+}
+
+.mini-viz {
+ margin: 16px;
+ padding: 14px;
+ border: 1px solid var(--hairline);
+ border-radius: var(--radius-sm);
+ background: rgba(0, 0, 0, 0.2);
+}
+
+.viz-title {
+ margin-bottom: 10px;
+ color: var(--muted);
+ font-family: var(--mono-font);
+ font-size: 11px;
+ font-weight: 400;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+}
+
+.viz-row {
+ display: grid;
+ grid-template-columns: minmax(92px, 0.8fr) 1fr;
+ gap: 12px;
+ padding: 8px 0;
+ border-top: 1px solid var(--hairline);
+ font-size: 14px;
+}
+
+.viz-row span,
+.viz-summary b,
+.chart-axis,
+.citations {
+ color: var(--muted);
+}
+
+.viz-row strong {
+ color: var(--ink);
+ font-weight: 500;
+}
+
+.metric-viz {
+ display: grid;
+ gap: 12px;
+}
+
+.viz-summary {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.viz-summary span {
+ min-width: 0;
+ padding: 9px;
+ border-top: 1px solid var(--hairline);
+ color: var(--ink);
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 1.2;
+}
+
+.viz-summary b {
+ display: block;
+ margin-bottom: 4px;
+ font-family: var(--mono-font);
+ font-size: 10px;
+ font-weight: 400;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.metric-chart {
+ position: relative;
+ height: 92px;
+ border: 1px solid var(--hairline);
+ border-radius: var(--radius-sm);
+ background: #060a0a;
+}
+
+.metric-chart svg {
+ position: absolute;
+ inset: 10px 10px 18px;
+ width: calc(100% - 20px);
+ height: calc(100% - 28px);
+ overflow: visible;
+}
+
+.metric-chart line {
+ stroke: rgba(217, 217, 221, 0.16);
+ stroke-width: 0.6;
+}
+
+.metric-chart polyline {
+ fill: none;
+ stroke: var(--agent-color);
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ stroke-width: 2;
+ vector-effect: non-scaling-stroke;
+}
+
+.chart-point {
+ position: absolute;
+ width: 13px;
+ height: 13px;
+ border: 2px solid var(--surface-3);
+ border-radius: var(--radius-pill);
+ background: var(--agent-color);
+ transform: translate(-50%, -50%);
+ cursor: help;
+}
+
+.chart-point:hover,
+.chart-point:focus-visible {
+ outline: none;
+ box-shadow:
+ 0 0 0 2px var(--surface-3),
+ 0 0 0 4px var(--agent-color);
+ z-index: 2;
+}
+
+.chart-point:hover::after,
+.chart-point:focus-visible::after {
+ content: attr(data-tooltip);
+ position: absolute;
+ left: 50%;
+ bottom: calc(100% + 8px);
+ width: max-content;
+ max-width: 210px;
+ padding: 7px 9px;
+ border: 1px solid var(--hairline-strong);
+ border-radius: var(--radius-sm);
+ background: #000000;
+ color: var(--ink);
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 1.25;
+ transform: translateX(-50%);
+ white-space: normal;
+}
+
+.chart-axis {
+ position: relative;
+ min-height: 14px;
+ font-size: 11px;
+}
+
+.chart-axis span {
+ position: absolute;
+ max-width: 46%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ transform: translateX(-50%);
+ white-space: nowrap;
+}
+
+.card-foot {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ align-items: center;
+ padding: 0 16px 16px;
+}
+
+.card-foot button {
+ padding: 7px 13px;
+ border: 1px solid var(--hairline-strong);
+ background: transparent;
+ color: var(--ink);
+ cursor: pointer;
+}
+
+.card-foot button:hover {
+ border-color: #ffffff;
+}
+
+.citations {
+ font-size: 12px;
+ line-height: 1.35;
+ text-align: right;
+}
+
+.citations a {
+ color: var(--link-blue);
+}
+
+@media (max-width: 1080px) {
+ .shell {
+ height: 100vh;
+ min-height: 0;
+ padding: 10px;
+ }
+
+ .topbar,
+ .workspace {
+ grid-template-columns: 1fr;
+ }
+
+ .topbar {
+ gap: 10px;
+ margin-bottom: 8px;
+ align-items: stretch;
+ }
+
+ .url-form {
+ grid-template-columns: minmax(0, 1fr) minmax(96px, 116px);
+ padding: 0;
+ border-radius: var(--radius-sm);
+ background: transparent;
+ }
+
+ .url-form input,
+ .url-form button {
+ height: 44px;
+ border-radius: var(--radius-sm);
+ }
+
+ .url-form button {
+ width: 100%;
+ padding: 0 14px;
+ }
+
+ .status-strip {
+ grid-template-columns: 1fr;
+ gap: 8px;
+ min-height: 0;
+ margin-bottom: 8px;
+ border-radius: var(--radius-sm);
+ }
+
+ .status-steps {
+ justify-content: start;
+ overflow-x: auto;
+ padding-bottom: 2px;
+ }
+
+ .workspace {
+ grid-template-rows: minmax(220px, 0.58fr) minmax(260px, 0.42fr);
+ gap: 10px;
+ }
+
+ .watch-column {
+ grid-template-rows: minmax(0, 1fr) auto;
+ gap: 10px;
+ min-height: 0;
+ }
+
+ .video-panel {
+ height: 100%;
+ border-radius: var(--radius-sm);
+ }
+
+ .research-panel {
+ display: none;
+ }
+
+ .insight-column {
+ overflow: hidden;
+ padding-right: 0;
+ }
+
+ .timeline-workbench {
+ max-height: none;
+ border-radius: var(--radius-sm);
+ }
+
+ .stream-header {
+ padding: 16px 16px 12px;
+ }
+
+ .stream-header h2 {
+ font-size: 24px;
+ }
+
+ .stream-controls,
+ .analyst-timeline {
+ padding-right: 16px;
+ padding-left: 16px;
+ }
+}
+
+@media (min-width: 1081px) and (max-height: 760px) {
+ .watch-column {
+ grid-template-rows: minmax(0, 1fr) auto;
+ }
+
+ .research-panel {
+ display: none;
+ }
+}
+
+@media (max-width: 680px) {
+ h1 {
+ font-size: 22px;
+ }
+
+ .mark {
+ width: 44px;
+ height: 44px;
+ }
+
+ .url-form,
+ .research-grid {
+ grid-template-columns: 1fr;
+ }
+
+ .stream-header {
+ align-items: flex-start;
+ }
+
+ .stream-header p {
+ font-size: 14px;
+ }
+
+ .stream-controls {
+ grid-template-columns: 1fr 1fr;
+ gap: 8px;
+ }
+
+ .timeline-card {
+ grid-template-columns: 54px minmax(0, 1fr);
+ gap: 8px;
+ }
+
+ .time-rail span {
+ width: 50px;
+ }
+
+ .timeline-card h3 {
+ font-size: 20px;
+ }
+
+ .viz-summary {
+ grid-template-columns: 1fr;
+ }
+}
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/pyproject.toml b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/pyproject.toml
new file mode 100644
index 00000000..faeb3f23
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/pyproject.toml
@@ -0,0 +1,3 @@
+[tool.pytest.ini_options]
+pythonpath = [".."]
+testpaths = ["tests"]
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/requirements.txt b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/requirements.txt
new file mode 100644
index 00000000..d7c17879
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/requirements.txt
@@ -0,0 +1,9 @@
+fastapi>=0.115.0
+uvicorn[standard]>=0.30.0
+pydantic>=2.7.0
+requests>=2.31.0
+youtube-transcript-api>=0.6.2
+yt-dlp>=2025.12.8
+google-genai>=1.0.0
+google-adk>=1.0.0
+pytest>=8.0.0
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/research.py b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/research.py
new file mode 100644
index 00000000..eae99b37
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/research.py
@@ -0,0 +1,380 @@
+from __future__ import annotations
+
+import json
+import os
+import re
+import xml.etree.ElementTree as ET
+from functools import lru_cache
+from typing import Any
+
+import requests
+
+from .adk_runtime import run_adk_agent_text
+from .schemas import ResearchDocument, ResearchPack, TranscriptSegment, VideoMetadata
+
+
+SEC_TICKERS_URL = "https://www.sec.gov/files/company_tickers.json"
+SEC_SUBMISSIONS_URL = "https://data.sec.gov/submissions/CIK{cik}.json"
+YAHOO_NEWS_RSS = "https://feeds.finance.yahoo.com/rss/2.0/headline"
+GOOGLE_NEWS_RSS = "https://news.google.com/rss/search"
+MODEL = os.getenv("EARNINGS_GEMINI_MODEL", "gemini-3-flash-preview")
+SEARCH_MODEL = os.getenv("EARNINGS_SEARCH_GEMINI_MODEL", "gemini-2.5-flash")
+
+
+try:
+ from google.adk.agents import Agent
+ from google.adk.tools import google_search
+
+ identity_agent = Agent(
+ name="earnings_identity_agent",
+ model=MODEL,
+ description="Identifies the company, ticker, fiscal period, and peer set for an earnings-call video.",
+ instruction=(
+ "Identify public-company context from YouTube metadata and transcript openings. "
+ "Return strict JSON only with keys: company, ticker, fiscal_period, peers, confidence. "
+ "Use a ticker only when evidence is strong. Peers must be ticker symbols."
+ ),
+ )
+ market_news_agent = Agent(
+ name="earnings_market_news_agent",
+ model=SEARCH_MODEL,
+ description="Uses Google Search to find current investor-relevant news for a public company.",
+ instruction=(
+ "Use Google Search for current market news. Return strict JSON only with key items. "
+ "Each item must have title, source, url, and summary. Include only real URLs from credible sources. "
+ "Exclude forums, social posts, promotional pages, and duplicates."
+ ),
+ tools=[google_search],
+ )
+except Exception:
+ identity_agent = None
+ market_news_agent = None
+
+
+def build_research_pack(
+ metadata: VideoMetadata, transcript: list[TranscriptSegment], max_news: int = 8
+) -> ResearchPack:
+ sample = " ".join(segment.text for segment in transcript[:24])
+ identity = infer_company_identity(metadata.title, metadata.author_name, sample)
+ ticker = str(identity.get("ticker") or "").upper().strip()
+ company = str(identity.get("company") or "").strip() or _clean_company_name(metadata)
+
+ documents: list[ResearchDocument] = []
+ notes: list[str] = []
+
+ if ticker:
+ sec_docs, sec_notes = fetch_sec_documents(ticker)
+ documents.extend(sec_docs)
+ notes.extend(sec_notes)
+
+ news = fetch_market_news(ticker, company, max_news=max_news) if ticker else []
+ peers = identity.get("peers", [])
+ if not isinstance(peers, list):
+ peers = []
+
+ if not documents:
+ notes.append("No SEC filing links were resolved automatically.")
+ if not news:
+ notes.append("No recent market headlines were resolved automatically.")
+
+ return ResearchPack(
+ company=company,
+ ticker=ticker,
+ fiscal_period=str(identity.get("fiscal_period") or ""),
+ confidence=float(identity.get("confidence", 0.35)),
+ documents=documents,
+ peers=[str(peer).upper().strip() for peer in peers if str(peer).strip()][:8],
+ news=news,
+ notes=notes,
+ )
+
+
+def infer_company_identity(title: str, channel: str, transcript_sample: str) -> dict[str, Any]:
+ heuristic = _infer_identity_heuristically(title, channel, transcript_sample)
+ if not _has_gemini_key() or identity_agent is None:
+ return heuristic
+
+ prompt = f"""
+Identify the public company and context for this earnings-call video.
+Return strict JSON with keys: company, ticker, fiscal_period, peers, confidence.
+Use a stock ticker only when you have strong evidence. Peers should be ticker symbols.
+
+Title: {title}
+Channel: {channel}
+Transcript opening:
+{transcript_sample[:4000]}
+"""
+ try:
+ parsed = _parse_json_object(run_adk_agent_text(identity_agent, prompt))
+ if parsed.get("company") or parsed.get("ticker"):
+ return {**heuristic, **parsed}
+ except Exception:
+ return heuristic
+
+ return heuristic
+
+
+def fetch_sec_documents(ticker: str) -> tuple[list[ResearchDocument], list[str]]:
+ notes: list[str] = []
+ cik = ticker_to_cik(ticker)
+ if not cik:
+ return [], [f"SEC CIK lookup did not find ticker {ticker}."]
+
+ headers = {"User-Agent": os.getenv("EARNINGS_USER_AGENT", "earnings-call-analyst-agent")}
+ try:
+ response = requests.get(
+ SEC_SUBMISSIONS_URL.format(cik=cik), headers=headers, timeout=10
+ )
+ response.raise_for_status()
+ data = response.json()
+ except Exception as exc:
+ return [], [f"SEC submissions request failed for {ticker}: {exc}"]
+
+ filings = data.get("filings", {}).get("recent", {})
+ forms = filings.get("form", [])
+ accession_numbers = filings.get("accessionNumber", [])
+ primary_docs = filings.get("primaryDocument", [])
+ filing_dates = filings.get("filingDate", [])
+
+ docs: list[ResearchDocument] = []
+ seen_forms: set[str] = set()
+ for form, accession, primary_doc, filing_date in zip(
+ forms, accession_numbers, primary_docs, filing_dates
+ ):
+ if form not in {"10-K", "10-Q", "8-K"} or form in seen_forms:
+ continue
+ accession_path = str(accession).replace("-", "")
+ url = (
+ f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/"
+ f"{accession_path}/{primary_doc}"
+ )
+ docs.append(
+ ResearchDocument(
+ title=f"{ticker} {form} filed {filing_date}",
+ kind=form,
+ url=url,
+ summary="Latest SEC filing resolved from company submissions.",
+ )
+ )
+ seen_forms.add(form)
+ if len(docs) >= 3:
+ break
+
+ return docs, notes
+
+
+def fetch_market_news(ticker: str, company: str = "", max_news: int = 8) -> list[ResearchDocument]:
+ grounded_items = fetch_adk_grounded_news(ticker, company, max_news=max_news)
+ if grounded_items:
+ return grounded_items
+ yahoo_items = fetch_yahoo_news(ticker, max_news=max_news)
+ if yahoo_items:
+ return yahoo_items
+ return fetch_google_news(ticker, company, max_news=max_news)
+
+
+def fetch_adk_grounded_news(
+ ticker: str, company: str = "", max_news: int = 8
+) -> list[ResearchDocument]:
+ if not _has_gemini_key() or market_news_agent is None:
+ return []
+
+ company_label = company or ticker
+ prompt = f"""
+Use Google Search to find the latest market-moving news about {company_label} ({ticker}) stock.
+Focus on investor-relevant headlines from the last 7 days: earnings, guidance, deliveries,
+analyst actions, regulation, major product/business updates, executive news, or stock-moving events.
+
+Return only strict JSON. No markdown.
+Schema:
+{{
+ "items": [
+ {{
+ "title": "headline",
+ "source": "publisher",
+ "url": "https://...",
+ "summary": "one sentence explaining why this matters to investors"
+ }}
+ ]
+}}
+
+Rules:
+- Return at most {max_news} items.
+- Include only items with a real public URL.
+- Exclude forums, social posts, promotional pages, and duplicate headlines.
+"""
+ try:
+ text = run_adk_agent_text(market_news_agent, prompt)
+ except Exception:
+ return []
+
+ parsed = _parse_json_object(text)
+ raw_items = parsed.get("items", [])
+ if not isinstance(raw_items, list):
+ return []
+
+ items: list[ResearchDocument] = []
+ seen_urls: set[str] = set()
+ for raw in raw_items:
+ if not isinstance(raw, dict):
+ continue
+ title = " ".join(str(raw.get("title") or "").split())
+ source = " ".join(str(raw.get("source") or "").split())
+ url = str(raw.get("url") or "").strip()
+ summary = " ".join(str(raw.get("summary") or "").split())[:260]
+ if not title or not url.startswith(("http://", "https://")):
+ continue
+ if url in seen_urls or _is_low_quality_news_title(title):
+ continue
+ label = f"{title} - {source}" if source and not title.endswith(f" - {source}") else title
+ items.append(
+ ResearchDocument(
+ title=label,
+ kind="news",
+ url=url,
+ summary=summary or "Latest market context resolved with Gemini Google Search grounding.",
+ )
+ )
+ seen_urls.add(url)
+ if len(items) >= max_news:
+ break
+ return items
+
+
+def fetch_yahoo_news(ticker: str, max_news: int = 8) -> list[ResearchDocument]:
+ try:
+ response = requests.get(
+ YAHOO_NEWS_RSS,
+ params={"s": ticker, "region": "US", "lang": "en-US"},
+ timeout=8,
+ )
+ response.raise_for_status()
+ root = ET.fromstring(response.text)
+ except Exception:
+ return []
+
+ items: list[ResearchDocument] = []
+ for item in root.findall(".//item")[:max_news]:
+ title = item.findtext("title") or ""
+ link = item.findtext("link") or ""
+ description = re.sub("<[^>]+>", "", item.findtext("description") or "")
+ if title:
+ items.append(
+ ResearchDocument(
+ title=title,
+ kind="news",
+ url=link,
+ summary=" ".join(description.split())[:260],
+ )
+ )
+ return items
+
+
+def fetch_google_news(ticker: str, company: str = "", max_news: int = 8) -> list[ResearchDocument]:
+ query = " ".join(part for part in [company, ticker, "stock", "when:7d"] if part).strip()
+ headers = {"User-Agent": os.getenv("EARNINGS_USER_AGENT", "earnings-call-analyst-agent")}
+ try:
+ response = requests.get(
+ GOOGLE_NEWS_RSS,
+ params={"q": query, "hl": "en-US", "gl": "US", "ceid": "US:en"},
+ headers=headers,
+ timeout=8,
+ )
+ response.raise_for_status()
+ root = ET.fromstring(response.text)
+ except Exception:
+ return []
+
+ items: list[ResearchDocument] = []
+ for item in root.findall(".//item"):
+ title = " ".join((item.findtext("title") or "").split())
+ link = item.findtext("link") or ""
+ description = re.sub("<[^>]+>", "", item.findtext("description") or "")
+ if not title or not link or _is_low_quality_news_title(title):
+ continue
+ items.append(
+ ResearchDocument(
+ title=title,
+ kind="news",
+ url=link,
+ summary=" ".join(description.split())[:260],
+ )
+ )
+ if len(items) >= max_news:
+ break
+ return items
+
+
+def _is_low_quality_news_title(title: str) -> bool:
+ low_quality_sources = {"moomoo", "reddit", "stocktwits"}
+ source = title.rsplit(" - ", 1)[-1].strip().lower() if " - " in title else ""
+ return source in low_quality_sources
+
+
+@lru_cache(maxsize=1)
+def _sec_ticker_map() -> dict[str, str]:
+ headers = {"User-Agent": os.getenv("EARNINGS_USER_AGENT", "earnings-call-analyst-agent")}
+ response = requests.get(SEC_TICKERS_URL, headers=headers, timeout=10)
+ response.raise_for_status()
+ data = response.json()
+ return {
+ str(row.get("ticker", "")).upper(): str(row.get("cik_str", "")).zfill(10)
+ for row in data.values()
+ if row.get("ticker") and row.get("cik_str")
+ }
+
+
+def ticker_to_cik(ticker: str) -> str:
+ try:
+ return _sec_ticker_map().get(ticker.upper(), "")
+ except Exception:
+ return ""
+
+
+def _infer_identity_heuristically(title: str, channel: str, transcript_sample: str) -> dict[str, Any]:
+ text = f"{title} {channel} {transcript_sample[:1200]}"
+ ticker = ""
+ ticker_match = re.search(r"\(([A-Z]{1,5})\)|\bNYSE:\s*([A-Z]{1,5})\b|\bNASDAQ:\s*([A-Z]{1,5})\b", text)
+ if ticker_match:
+ ticker = next(group for group in ticker_match.groups() if group)
+
+ company = _clean_company_name(VideoMetadata(video_id="", title=title, author_name=channel))
+ quarter = ""
+ quarter_match = re.search(r"\b(Q[1-4]\s*(?:FY)?\s*20\d{2}|20\d{2}\s*Q[1-4])\b", text, re.I)
+ if quarter_match:
+ quarter = quarter_match.group(1).upper()
+
+ return {
+ "company": company,
+ "ticker": ticker,
+ "fiscal_period": quarter,
+ "peers": [],
+ "confidence": 0.45 if ticker else 0.25,
+ }
+
+
+def _clean_company_name(metadata: VideoMetadata) -> str:
+ title = metadata.title
+ title = re.sub(r"\b(Q[1-4]|FY|20\d{2}|earnings|call|results|conference|webcast|transcript)\b", "", title, flags=re.I)
+ title = re.sub(r"\([^)]*\)", "", title)
+ title = re.sub(r"[-|:]+", " ", title)
+ words = [word for word in title.split() if word.strip()]
+ return " ".join(words[:5]) or metadata.author_name or "Unknown company"
+
+
+def _has_gemini_key() -> bool:
+ return bool(os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY"))
+
+
+def _parse_json_object(text: str) -> dict[str, Any]:
+ cleaned = text.strip()
+ cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", cleaned, flags=re.I | re.S)
+ start = cleaned.find("{")
+ end = cleaned.rfind("}")
+ if start == -1 or end == -1:
+ return {}
+ try:
+ data = json.loads(cleaned[start : end + 1])
+ except json.JSONDecodeError:
+ return {}
+ return data if isinstance(data, dict) else {}
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/schemas.py b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/schemas.py
new file mode 100644
index 00000000..b87911be
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/schemas.py
@@ -0,0 +1,115 @@
+from __future__ import annotations
+
+from functools import total_ordering
+from typing import Any, Literal, Union
+
+from pydantic import BaseModel, Field
+
+
+Severity = Literal["high", "medium", "low"]
+AgentName = Literal[
+ "numbers_reconciler",
+ "cfo_tone",
+ "peer_context",
+ "surprise_detector",
+ "filing_grounder",
+ "market_narrator",
+]
+
+
+class TranscriptSegment(BaseModel):
+ start: float
+ duration: float = 0
+ text: str
+
+ @property
+ def end(self) -> float:
+ return self.start + self.duration
+
+
+class TranscriptChunk(BaseModel):
+ start: float
+ end: float
+ text: str
+ segments: list[TranscriptSegment] = Field(default_factory=list)
+
+
+class MiniVisualization(BaseModel):
+ type: str = "note"
+ title: str = ""
+ rows: list[list[str]] = Field(default_factory=list)
+ points: list[float] = Field(default_factory=list)
+ labels: list[str] = Field(default_factory=list)
+
+
+class Citation(BaseModel):
+ label: str
+ source: str = ""
+ url: str = ""
+
+
+@total_ordering
+class InsightEvent(BaseModel):
+ id: str
+ start_time: float
+ end_time: float
+ agent: Union[AgentName, str]
+ severity: Severity
+ headline: str
+ quote: str
+ confidence: float = Field(ge=0, le=1)
+ explanation: str = ""
+ mini_viz: MiniVisualization = Field(default_factory=MiniVisualization)
+ citations: list[Citation] = Field(default_factory=list)
+
+ def __lt__(self, other: object) -> bool:
+ if not isinstance(other, InsightEvent):
+ return NotImplemented
+ severity_rank = {"high": 0, "medium": 1, "low": 2}
+ return (
+ self.start_time,
+ severity_rank.get(self.severity, 9),
+ self.id,
+ ) < (
+ other.start_time,
+ severity_rank.get(other.severity, 9),
+ other.id,
+ )
+
+
+class VideoMetadata(BaseModel):
+ video_id: str
+ title: str = "Untitled earnings call"
+ author_name: str = ""
+ thumbnail_url: str = ""
+ source_url: str = ""
+
+
+class ResearchDocument(BaseModel):
+ title: str
+ kind: str
+ url: str = ""
+ summary: str = ""
+
+
+class ResearchPack(BaseModel):
+ company: str = "Unknown company"
+ ticker: str = ""
+ fiscal_period: str = ""
+ confidence: float = 0
+ documents: list[ResearchDocument] = Field(default_factory=list)
+ peers: list[str] = Field(default_factory=list)
+ news: list[ResearchDocument] = Field(default_factory=list)
+ notes: list[str] = Field(default_factory=list)
+
+
+class AnalysisSession(BaseModel):
+ session_id: str
+ video: VideoMetadata
+ transcript: list[TranscriptSegment]
+ chunks: list[TranscriptChunk]
+ research: ResearchPack
+ insights: list[InsightEvent]
+ status: Literal["ready", "partial", "error"]
+ message: str = ""
+ diagnostics: dict[str, Any] = Field(default_factory=dict)
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/tests/test_core_contracts.py b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/tests/test_core_contracts.py
new file mode 100644
index 00000000..60d02a41
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/tests/test_core_contracts.py
@@ -0,0 +1,233 @@
+import pytest
+
+from earnings_call_analyst_agent.schemas import InsightEvent, ResearchDocument, TranscriptSegment
+from earnings_call_analyst_agent.adk_runtime import _ensure_google_api_key_alias
+from earnings_call_analyst_agent.agent import _realign_event_times
+from earnings_call_analyst_agent.research import build_research_pack, fetch_market_news
+from earnings_call_analyst_agent.youtube_ingest import (
+ chunk_transcript,
+ extract_video_id,
+ load_transcript,
+ parse_transcribed_segments,
+)
+
+
+ ("url", "video_id"),
+ [
+ ("https://www.youtube.com/watch?v=abcDEF12345", "abcDEF12345"),
+ ("https://youtu.be/abcDEF12345?t=120", "abcDEF12345"),
+ ("https://www.youtube.com/live/abcDEF12345?si=x", "abcDEF12345"),
+ ("abcDEF12345", "abcDEF12345"),
+ ],
+)
+def test_extract_video_id_handles_common_youtube_urls(url, video_id):
+ assert extract_video_id(url) == video_id
+
+
+def test_extract_video_id_rejects_invalid_values():
+ with pytest.raises(ValueError):
+ extract_video_id("https://example.com/not-youtube")
+
+
+def test_chunk_transcript_combines_segments_until_window_limit():
+ segments = [
+ TranscriptSegment(start=0, duration=3, text="Good afternoon everyone."),
+ TranscriptSegment(start=3, duration=3, text="Revenue grew twelve percent."),
+ TranscriptSegment(start=9, duration=3, text="Margins expanded by 80 basis points."),
+ ]
+
+ chunks = chunk_transcript(segments, window_seconds=7)
+
+ assert len(chunks) == 2
+ assert chunks[0].start == 0
+ assert chunks[0].end == 6
+ assert "Revenue grew" in chunks[0].text
+ assert chunks[1].start == 9
+ assert chunks[1].end == 12
+
+
+def test_insight_event_reveal_order_uses_start_time_then_severity():
+ events = [
+ InsightEvent(
+ id="later",
+ start_time=20,
+ end_time=25,
+ agent="cfo_tone",
+ severity="low",
+ headline="Later",
+ quote="Later quote",
+ confidence=0.6,
+ ),
+ InsightEvent(
+ id="high",
+ start_time=10,
+ end_time=13,
+ agent="surprise_detector",
+ severity="high",
+ headline="High",
+ quote="High quote",
+ confidence=0.9,
+ ),
+ InsightEvent(
+ id="medium",
+ start_time=10,
+ end_time=14,
+ agent="numbers_reconciler",
+ severity="medium",
+ headline="Medium",
+ quote="Medium quote",
+ confidence=0.8,
+ ),
+ ]
+
+ assert [event.id for event in sorted(events)] == ["high", "medium", "later"]
+
+
+def test_realign_event_times_snaps_quote_to_caption_segment():
+ chunks = chunk_transcript(
+ [
+ TranscriptSegment(start=0, duration=4, text="Welcome to the earnings call."),
+ TranscriptSegment(start=12, duration=5, text="Revenue grew twelve percent in the quarter."),
+ TranscriptSegment(start=21, duration=4, text="Operating margin also improved."),
+ ],
+ window_seconds=60,
+ )
+ event = InsightEvent(
+ id="metric",
+ start_time=0,
+ end_time=4,
+ agent="numbers_reconciler",
+ severity="medium",
+ headline="Revenue growth called out",
+ quote="Revenue grew twelve percent",
+ confidence=0.8,
+ )
+
+ [realigned] = _realign_event_times([event], chunks)
+
+ assert realigned.start_time == pytest.approx(11.65)
+ assert realigned.end_time == 17
+
+
+def test_realign_event_times_prefers_where_quote_begins_for_spanning_quotes():
+ chunks = chunk_transcript(
+ [
+ TranscriptSegment(start=18, duration=4, text="We're no strangers to love."),
+ TranscriptSegment(start=22, duration=4, text="You know the rules and so do I."),
+ ],
+ window_seconds=60,
+ )
+ event = InsightEvent(
+ id="context",
+ start_time=22,
+ end_time=26,
+ agent="market_narrator",
+ severity="low",
+ headline="Not an earnings call",
+ quote="We're no strangers to love You know the rules and so do I",
+ confidence=0.8,
+ )
+
+ [realigned] = _realign_event_times([event], chunks)
+
+ assert realigned.start_time == pytest.approx(17.65)
+
+
+def test_research_pack_handles_null_ticker_from_identity(monkeypatch):
+ monkeypatch.setattr(
+ "earnings_call_analyst_agent.research.infer_company_identity",
+ lambda *_: {
+ "company": "Example Co",
+ "ticker": None,
+ "fiscal_period": None,
+ "peers": None,
+ "confidence": 0.2,
+ },
+ )
+
+ pack = build_research_pack(
+ metadata=type(
+ "Metadata",
+ (),
+ {"title": "Example Q4 earnings call", "author_name": "Example IR"},
+ )(),
+ transcript=[TranscriptSegment(start=0, duration=1, text="Welcome to the call.")],
+ )
+
+ assert pack.company == "Example Co"
+ assert pack.ticker == ""
+ assert pack.peers == []
+
+
+def test_load_transcript_falls_back_to_audio_transcription(monkeypatch):
+ def captions_fail(_video_id):
+ raise RuntimeError("Subtitles are disabled for this video")
+
+ monkeypatch.setattr("earnings_call_analyst_agent.youtube_ingest.fetch_transcript", captions_fail)
+ monkeypatch.setattr(
+ "earnings_call_analyst_agent.youtube_ingest.transcribe_audio_with_adk",
+ lambda video_id: [TranscriptSegment(start=0, duration=5, text="Fallback transcript")],
+ )
+
+ segments, source = load_transcript("abcDEF12345")
+
+ assert source == "adk_audio"
+ assert segments[0].text == "Fallback transcript"
+
+
+def test_fetch_market_news_prefers_adk_grounded_search(monkeypatch):
+ grounded = [
+ ResearchDocument(
+ title="Tesla shares rise after delivery update - Reuters",
+ kind="news",
+ url="https://www.reuters.com/example",
+ )
+ ]
+ monkeypatch.setattr("earnings_call_analyst_agent.research.fetch_adk_grounded_news", lambda *_args, **_kwargs: grounded)
+ monkeypatch.setattr("earnings_call_analyst_agent.research.fetch_yahoo_news", lambda *_args, **_kwargs: pytest.fail("Yahoo fallback should not run when ADK search resolves news"))
+
+ assert fetch_market_news("TSLA", "Tesla") == grounded
+
+
+def test_fetch_market_news_falls_back_when_adk_search_is_empty(monkeypatch):
+ fallback = [
+ ResearchDocument(
+ title="Tesla stock update - MarketWatch",
+ kind="news",
+ url="https://www.marketwatch.com/example",
+ )
+ ]
+ monkeypatch.setattr("earnings_call_analyst_agent.research.fetch_adk_grounded_news", lambda *_args, **_kwargs: [])
+ monkeypatch.setattr("earnings_call_analyst_agent.research.fetch_yahoo_news", lambda *_args, **_kwargs: [])
+ monkeypatch.setattr("earnings_call_analyst_agent.research.fetch_google_news", lambda *_args, **_kwargs: fallback)
+
+ assert fetch_market_news("TSLA", "Tesla") == fallback
+
+
+def test_gemini_key_is_aliased_for_adk(monkeypatch):
+ monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
+ monkeypatch.setenv("GEMINI_API_KEY", "test-key")
+
+ _ensure_google_api_key_alias()
+
+ assert __import__("os").environ["GOOGLE_API_KEY"] == "test-key"
+
+
+def test_parse_transcribed_segments_accepts_json_with_code_fences():
+ text = """
+ ```json
+ {"segments": [
+ {"start": 0, "duration": 4.5, "text": "Welcome to the call."},
+ {"start": 4.5, "end": 9, "text": "Revenue grew this quarter."}
+ ]}
+ ```
+ """
+
+ segments = parse_transcribed_segments(text)
+
+ assert [segment.text for segment in segments] == [
+ "Welcome to the call.",
+ "Revenue grew this quarter.",
+ ]
+ assert segments[1].duration == 4.5
diff --git a/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/youtube_ingest.py b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/youtube_ingest.py
new file mode 100644
index 00000000..d3135eb9
--- /dev/null
+++ b/advanced_ai_agents/single_agent_apps/earnings_call_analyst_agent/youtube_ingest.py
@@ -0,0 +1,352 @@
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Callable, Optional
+from urllib.parse import parse_qs, urlparse
+
+import requests
+
+from .adk_runtime import run_adk_agent_content
+from .schemas import TranscriptChunk, TranscriptSegment, VideoMetadata
+
+
+VIDEO_ID_RE = re.compile(r"^[A-Za-z0-9_-]{11}$")
+
+
+def _int_env(name: str, default: int, minimum: int, maximum: int) -> int:
+ try:
+ value = int(os.getenv(name, str(default)) or str(default))
+ except ValueError:
+ value = default
+ return max(minimum, min(maximum, value))
+
+
+AUDIO_CHUNK_SECONDS = _int_env("EARNINGS_AUDIO_CHUNK_SECONDS", 300, minimum=60, maximum=900)
+
+
+try:
+ from google.adk.agents import Agent
+
+ transcription_agent = Agent(
+ name="earnings_audio_transcription_agent",
+ model=os.getenv(
+ "EARNINGS_TRANSCRIPT_MODEL",
+ os.getenv("EARNINGS_GEMINI_MODEL", "gemini-3-flash-preview"),
+ ),
+ description="Transcribes earnings-call audio into timestamped transcript segments.",
+ instruction=(
+ "Transcribe supplied audio into timestamped English transcript segments. "
+ "Return strict JSON only with key segments. Preserve financial numbers, speaker names, "
+ "tickers, and guidance language exactly."
+ ),
+ )
+except Exception:
+ transcription_agent = None
+
+
+def extract_video_id(value: str) -> str:
+ raw = (value or "").strip()
+ if VIDEO_ID_RE.match(raw):
+ return raw
+
+ parsed = urlparse(raw)
+ host = parsed.netloc.lower()
+ path_parts = [part for part in parsed.path.split("/") if part]
+
+ if host.endswith("youtube.com") or host.endswith("youtube-nocookie.com"):
+ query_id = parse_qs(parsed.query).get("v", [""])[0]
+ if VIDEO_ID_RE.match(query_id):
+ return query_id
+ if path_parts and path_parts[0] in {"live", "embed", "shorts"}:
+ candidate = path_parts[1] if len(path_parts) > 1 else ""
+ if VIDEO_ID_RE.match(candidate):
+ return candidate
+
+ if host == "youtu.be" and path_parts and VIDEO_ID_RE.match(path_parts[0]):
+ return path_parts[0]
+
+ raise ValueError("Enter a valid YouTube URL or 11-character video id.")
+
+
+def fetch_video_metadata(url: str, video_id: str) -> VideoMetadata:
+ endpoint = "https://www.youtube.com/oembed"
+ try:
+ response = requests.get(
+ endpoint,
+ params={"url": f"https://www.youtube.com/watch?v={video_id}", "format": "json"},
+ timeout=8,
+ )
+ response.raise_for_status()
+ data = response.json()
+ except Exception:
+ data = {}
+
+ return VideoMetadata(
+ video_id=video_id,
+ title=data.get("title") or "Untitled earnings call",
+ author_name=data.get("author_name") or "",
+ thumbnail_url=data.get("thumbnail_url") or "",
+ source_url=url,
+ )
+
+
+def fetch_transcript(video_id: str) -> list[TranscriptSegment]:
+ try:
+ from youtube_transcript_api import YouTubeTranscriptApi
+ except ImportError as exc:
+ raise RuntimeError(
+ "Missing youtube-transcript-api. Install requirements.txt before running the app."
+ ) from exc
+
+ try:
+ items = YouTubeTranscriptApi.get_transcript(video_id, languages=["en", "en-US"])
+ except AttributeError:
+ api = YouTubeTranscriptApi()
+ fetched = api.fetch(video_id, languages=["en", "en-US"])
+ items = [
+ {
+ "start": snippet.start,
+ "duration": snippet.duration,
+ "text": snippet.text,
+ }
+ for snippet in fetched
+ ]
+ except Exception as exc:
+ raise RuntimeError(
+ "Could not load captions for this video. Try a YouTube earnings call with English captions."
+ ) from exc
+
+ return [
+ TranscriptSegment(
+ start=float(item.get("start", 0)),
+ duration=float(item.get("duration", 0)),
+ text=" ".join(str(item.get("text", "")).replace("\n", " ").split()),
+ )
+ for item in items
+ if str(item.get("text", "")).strip()
+ ]
+
+
+def load_transcript(video_id: str) -> tuple[list[TranscriptSegment], str]:
+ try:
+ return fetch_transcript(video_id), "youtube_captions"
+ except Exception as captions_error:
+ try:
+ return transcribe_audio_with_adk(video_id), "adk_audio"
+ except Exception as audio_error:
+ raise RuntimeError(
+ "Could not load captions and ADK audio transcription fallback failed. "
+ f"Captions error: {captions_error}. Audio fallback error: {audio_error}"
+ ) from audio_error
+
+
+def transcribe_audio_with_adk(
+ video_id: str, on_progress: Optional[Callable[[int, str], None]] = None
+) -> list[TranscriptSegment]:
+ if os.getenv("GEMINI_API_KEY") and not os.getenv("GOOGLE_API_KEY"):
+ os.environ["GOOGLE_API_KEY"] = os.environ["GEMINI_API_KEY"]
+ if not os.getenv("GOOGLE_API_KEY"):
+ raise RuntimeError("GOOGLE_API_KEY is required for audio transcription fallback.")
+
+ try:
+ from google.genai import types
+ from yt_dlp import YoutubeDL
+ except ImportError as exc:
+ raise RuntimeError(
+ "Audio fallback requires google-genai and yt-dlp. Run pip install -r requirements.txt."
+ ) from exc
+
+ with tempfile.TemporaryDirectory(prefix="earnings-audio-") as temp_dir:
+ if on_progress:
+ on_progress(34, "Downloading low-bitrate audio for ADK transcription")
+ output_template = str(Path(temp_dir) / "audio.%(ext)s")
+ ydl_opts = {
+ "format": "worstaudio[ext=m4a]/worstaudio[ext=webm]/worstaudio/bestaudio",
+ "outtmpl": output_template,
+ "noplaylist": True,
+ "quiet": True,
+ "no_warnings": True,
+ "noprogress": True,
+ }
+ with YoutubeDL(ydl_opts) as ydl:
+ ydl.extract_info(f"https://www.youtube.com/watch?v={video_id}", download=True)
+
+ audio_files = [path for path in Path(temp_dir).iterdir() if path.is_file()]
+ if not audio_files:
+ raise RuntimeError("yt-dlp did not produce an audio file.")
+
+ audio_path = max(audio_files, key=lambda path: path.stat().st_size)
+ audio_chunks = _prepare_audio_chunks(audio_path, Path(temp_dir))
+ if not audio_chunks:
+ audio_chunks = [audio_path]
+
+ segments: list[TranscriptSegment] = []
+ for index, chunk_path in enumerate(audio_chunks):
+ if on_progress:
+ chunk_progress = 38 + int((index / max(1, len(audio_chunks))) * 22)
+ on_progress(
+ chunk_progress,
+ f"Transcribing audio chunk {index + 1} of {len(audio_chunks)} with ADK",
+ )
+ chunk_offset = index * AUDIO_CHUNK_SECONDS
+ mime_type = _audio_mime_type(chunk_path)
+ prompt = f"""
+Transcribe this earnings-call audio into timestamped English segments.
+Return strict JSON only:
+{{"segments":[{{"start":0,"duration":8.5,"text":"..."}}]}}
+
+ Rules:
+- Use seconds from the beginning of this audio chunk, not the full original video.
+- Keep segments between 5 and 20 seconds when possible.
+- Preserve financial numbers, speaker names, tickers, and guidance language exactly.
+- If audio is not an earnings call, still transcribe accurately.
+Chunk starts at {chunk_offset} seconds in the original video.
+"""
+ if transcription_agent is None:
+ raise RuntimeError("ADK transcription agent is unavailable.")
+ message = types.Content(
+ role="user",
+ parts=[
+ types.Part.from_bytes(data=chunk_path.read_bytes(), mime_type=mime_type),
+ types.Part.from_text(text=prompt),
+ ],
+ )
+ chunk_segments = parse_transcribed_segments(
+ run_adk_agent_content(transcription_agent, message)
+ )
+ for segment in chunk_segments:
+ segments.append(
+ TranscriptSegment(
+ start=segment.start + chunk_offset,
+ duration=segment.duration,
+ text=segment.text,
+ )
+ )
+ if on_progress:
+ on_progress(62, "Audio transcription complete; preparing transcript")
+ if not segments:
+ raise RuntimeError("ADK transcription returned no transcript segments from audio.")
+ return sorted(segments, key=lambda segment: segment.start)
+
+def parse_transcribed_segments(text: str) -> list[TranscriptSegment]:
+ data = _parse_json_object(text)
+ raw_segments = data.get("segments", [])
+ if not isinstance(raw_segments, list):
+ return []
+
+ segments: list[TranscriptSegment] = []
+ for raw in raw_segments:
+ if not isinstance(raw, dict):
+ continue
+ clean_text = " ".join(str(raw.get("text", "")).replace("\n", " ").split())
+ if not clean_text:
+ continue
+ try:
+ start = float(raw.get("start", 0))
+ if "duration" in raw:
+ duration = float(raw.get("duration", 0))
+ else:
+ duration = max(0, float(raw.get("end", start)) - start)
+ except (TypeError, ValueError):
+ continue
+ segments.append(TranscriptSegment(start=start, duration=duration, text=clean_text))
+ return sorted(segments, key=lambda segment: segment.start)
+
+
+def chunk_transcript(
+ segments: list[TranscriptSegment], window_seconds: int = 45
+) -> list[TranscriptChunk]:
+ chunks: list[TranscriptChunk] = []
+ current: list[TranscriptSegment] = []
+ window_start: Optional[float] = None
+
+ for segment in segments:
+ if window_start is None:
+ window_start = segment.start
+ if current and segment.end - window_start > window_seconds:
+ chunks.append(_build_chunk(current))
+ current = []
+ window_start = segment.start
+ current.append(segment)
+
+ if current:
+ chunks.append(_build_chunk(current))
+
+ return chunks
+
+
+def _build_chunk(segments: list[TranscriptSegment]) -> TranscriptChunk:
+ return TranscriptChunk(
+ start=segments[0].start,
+ end=max(segment.end for segment in segments),
+ text=" ".join(segment.text for segment in segments),
+ segments=segments,
+ )
+
+
+def _audio_mime_type(path: Path) -> str:
+ suffix = path.suffix.lower()
+ if suffix in {".m4a", ".mp4"}:
+ return "audio/mp4"
+ if suffix == ".mp3":
+ return "audio/mpeg"
+ if suffix == ".wav":
+ return "audio/wav"
+ if suffix == ".ogg":
+ return "audio/ogg"
+ if suffix == ".webm":
+ return "audio/webm"
+ return "application/octet-stream"
+
+
+def _prepare_audio_chunks(audio_path: Path, temp_dir: Path) -> list[Path]:
+ if not shutil.which("ffmpeg"):
+ return [audio_path]
+
+ output_pattern = temp_dir / "chunk_%03d.mp3"
+ command = [
+ "ffmpeg",
+ "-y",
+ "-i",
+ str(audio_path),
+ "-vn",
+ "-ac",
+ "1",
+ "-ar",
+ "16000",
+ "-b:a",
+ "32k",
+ "-f",
+ "segment",
+ "-segment_time",
+ str(AUDIO_CHUNK_SECONDS),
+ "-reset_timestamps",
+ "1",
+ str(output_pattern),
+ ]
+ result = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ if result.returncode != 0:
+ return [audio_path]
+
+ chunks = sorted(temp_dir.glob("chunk_*.mp3"))
+ return [chunk for chunk in chunks if chunk.stat().st_size > 0]
+
+
+def _parse_json_object(text: str) -> dict:
+ cleaned = text.strip()
+ cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", cleaned, flags=re.I | re.S)
+ start = cleaned.find("{")
+ end = cleaned.rfind("}")
+ if start == -1 or end == -1:
+ return {}
+ try:
+ data = json.loads(cleaned[start : end + 1])
+ except json.JSONDecodeError:
+ return {}
+ return data if isinstance(data, dict) else {}