File size: 4,375 Bytes
a316308
 
 
bc0284f
a316308
 
 
 
bc0284f
a316308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc0284f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a316308
 
 
 
 
 
 
bc0284f
a316308
 
bc0284f
a316308
bc0284f
17a7db3
a316308
 
 
 
 
 
 
 
 
bc0284f
a316308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17a7db3
a316308
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import os
import re
from urllib.parse import urlparse, parse_qs
import requests
import spaces
import gradio as gr
from groq import Groq

# Pull key from Hugging Face Settings -> Secret
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))

def extract_video_id(url_or_topic: str):
    parsed = urlparse(url_or_topic)
    if parsed.hostname in ("youtu.be", "www.youtu.be"):
        return parsed.path.lstrip("/")
    if parsed.hostname in ("youtube.com", "www.youtube.com"):
        if parsed.path == "/watch":
            return parse_qs(parsed.query).get("v", [None])[0]
        if parsed.path.startswith("/shorts/"):
            parts = parsed.path.split("/")
            return parts[2] if len(parts) > 2 else None
    match = re.search(r"(?:v=|\/|youtu\.be\/)([0-9A-Za-z_-]{11})", url_or_topic)
    return match.group(1) if match else None

def get_clean_transcript(video_id: str) -> str:
    """Fetches transcript via edge proxy to bypass cloud datacenter IP blocks."""
    # Attempt 1: Free Edge-cached proxy
    try:
        url = f"https://youtube-transcript.ai/transcript/{video_id}.txt"
        resp = requests.get(url, timeout=10, headers={"User-Agent": "Mozilla/5.0"})
        if resp.status_code == 200 and len(resp.text) > 100 and "Error" not in resp.text[:50]:
            # Clean markdown headers if present
            lines = [l for l in resp.text.split("\n") if not l.startswith("#")]
            return "\n".join(lines).strip()
    except Exception:
        pass

    # Attempt 2: Public Invidious mirror
    instances = ["https://inv.tux.pizza", "https://invidious.nerdvpn.de"]
    for inst in instances:
        try:
            res = requests.get(f"{inst}/api/v1/captions/{video_id}", timeout=6)
            if res.status_code == 200:
                captions = res.json().get("captions", [])
                if captions:
                    cap_url = inst + captions[0].get("url")
                    cap_res = requests.get(cap_url, timeout=6)
                    clean = re.sub(r'<[^>]+>', ' ', cap_res.text)
                    clean = re.sub(r'\s+', ' ', clean).strip()
                    if len(clean) > 100:
                        return clean
        except Exception:
            continue

    raise ValueError(
        "Could not retrieve video captions. Please test with a public video that has captions enabled."
    )

@spaces.GPU
def summarize(video_url: str):
    if not video_url.strip():
        return "Please provide a valid YouTube URL."
    
    video_id = extract_video_id(video_url)
    if not video_id:
        return "Invalid YouTube URL format. Please provide a standard watch link or shorts URL."

    try:
        transcript_text = get_clean_transcript(video_id)
    except Exception as e:
        return f"Extraction Notice: {str(e)}"

    try:
        completion = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {
                    "role": "system",
                    "content": (
                        "You are BriefTube AI, an enterprise-grade video intelligence engine. "
                        "Synthesize the provided transcript strictly and objectively from the source text. "
                        "Format cleanly into:\n"
                        "### 1. Executive Summary\n"
                        "### 2. Key Highlights & Actionable Takeaways\n"
                        "### 3. Critical Facts, Entities & Mentions"
                    )
                },
                {
                    "role": "user",
                    "content": f"Transcript:\n{transcript_text[:14000]}"
                }
            ],
            temperature=0.2
        )
        return completion.choices[0].message.content
    except Exception as e:
        return f"Groq LLM Synthesis Error: {str(e)}"

demo = gr.Interface(
    fn=summarize,
    inputs=gr.Textbox(
        label="YouTube Video URL", 
        placeholder="https://www.youtube.com/watch?v=aircAruvnKk",
        lines=1
    ),
    outputs=gr.Markdown(label="BriefTube Synthesis & Intelligence"),
    title="BriefTube AI — Video Intelligence Platform",
    description="Asynchronous video summarization pipeline powered by Meta Llama 3.3 70B via Groq LPUs.",
    examples=[
        ["https://www.youtube.com/watch?v=aircAruvnKk"]
    ]
)

if __name__ == "__main__":
    demo.launch()