File size: 6,514 Bytes
176aef3
3158848
 
d62c6dc
 
 
713f90d
 
 
 
3158848
713f90d
3158848
 
 
ae5277d
d62c6dc
3158848
722fe6d
647f2f0
 
3158848
 
d62c6dc
 
 
 
0a9e522
3aadc6e
d62c6dc
 
 
 
 
 
 
3aadc6e
 
 
0a9e522
3aadc6e
 
 
a76b3fd
3aadc6e
d62c6dc
3aadc6e
d62c6dc
 
bb198cb
713f90d
 
 
 
 
 
 
 
 
8f100ae
 
 
 
 
 
 
d1b3f36
 
 
 
 
 
 
713f90d
 
 
3158848
713f90d
 
 
 
 
 
 
d1b3f36
713f90d
bb198cb
713f90d
 
3158848
0a62fe9
176aef3
 
3158848
 
 
 
176aef3
3158848
 
 
 
 
628990b
 
 
 
 
 
 
3158848
 
d62c6dc
 
 
 
 
0a9e522
d62c6dc
0a9e522
 
d62c6dc
0a9e522
d62c6dc
0a9e522
 
d62c6dc
3158848
dead369
3158848
 
 
713f90d
 
 
8f100ae
 
bb198cb
d1b3f36
bb198cb
 
 
 
 
 
 
 
 
 
 
713f90d
 
 
b38b8e7
d1b3f36
 
 
 
3158848
6a3bc8b
0409a4b
6a3bc8b
0409a4b
 
 
 
 
3158848
 
 
 
 
 
176aef3
 
cbfbd40
d1b3f36
 
 
 
176aef3
713f90d
 
bb198cb
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.responses import JSONResponse
from fastapi import Header
import google.auth.transport.requests
from google.oauth2 import service_account
import whisper
import tempfile
import requests
import subprocess
import os
import uuid
import json
import re

os.environ["XDG_CACHE_HOME"] = "/tmp"
gemini_api_key = os.environ["GEMINI_API_KEY"]
app = FastAPI()
model = whisper.load_model("tiny")


class AnalyzeRequest(BaseModel):
    audio_url: str
    language_code: str = "en-US"  # Default English

def validate_app_check_token(app_check_token: str) -> bool:
    try:
        print("[AppCheck] Validating App Check token...")

        service_account_info = json.loads(os.environ["FIREBASE_SERVICE_ACCOUNT_JSON"])
        credentials = service_account.Credentials.from_service_account_info(
            service_account_info,
            scopes=["https://www.googleapis.com/auth/firebase"]
        )
        authed_session = google.auth.transport.requests.AuthorizedSession(credentials)

        url = "https://firebaseappcheck.googleapis.com/v1beta/projects/{project_id}:verifyAppCheckToken".format(
            project_id=service_account_info["project_id"]
        )

        response = authed_session.post(url, json={"appCheckToken": app_check_token})
        print(f"[AppCheck] Status: {response.status_code}")
        print(f"[AppCheck] Body: {response.text}")

        return response.status_code == 200
    except Exception as e:
        print(f"[AppCheck] πŸ”₯ Exception while validating token: {e}")
        return False

def download_video_audio_and_metadata(url: str) -> tuple[str, str, str]:
    temp_filename = f"/tmp/{uuid.uuid4()}.mp3"
    try:
        description = subprocess.check_output([
            "yt-dlp",
            "--skip-download",
            "--print", "%(description)s",
            url
        ], text=True).strip()

        thumbnail = subprocess.check_output([
            "yt-dlp",
            "--skip-download",
            "--print", "%(thumbnail)s",
            url
        ], text=True).strip()

        uploader = subprocess.check_output([
            "yt-dlp",
            "--skip-download",
            "--print", "%(uploader)s",
            url
        ], text=True).strip()

        command = [
            "yt-dlp",
            "-x", "--audio-format", "mp3",
            "-o", f"{temp_filename}",
            url
        ]
        subprocess.run(command, check=True)

        if not os.path.exists(temp_filename):
            raise Exception("Audio file was not created.")

        return temp_filename, description, thumbnail, uploader
    except Exception as e:
        raise Exception(f"Failed to download video: {e}")


def call_gemini(prompt: str, api_key: str) -> str:
    endpoint = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={api_key}"
    headers = {"Content-Type": "application/json"}
    data = { "contents": [{ "parts": [{"text": prompt }] }] }

    response = requests.post(endpoint, headers=headers, json=data)
    if response.status_code != 200:
        raise Exception(f"Error calling Gemini: {response.status_code} - {response.text}")
    return response.json()["candidates"][0]["content"]["parts"][0]["text"]


def clean_gemini_response(text: str) -> str:
    pattern = r"```json\s*(\{.*?\})\s*```"
    match = re.search(pattern, text, re.DOTALL)
    raw = match.group(1) if match else text

    cleaned = re.sub(r'"\s*null\s*"', 'null', raw)  # "null" β†’ null
    cleaned = re.sub(r':\s*None\b', ': null', cleaned)  # Python None β†’ null
    cleaned = re.sub(r'(?<!["\w])NaN(?!["\w])', 'null', cleaned)  # NaN β†’ null
    return cleaned


@app.post("/analyze")
async def analyze(
    request: AnalyzeRequest,
    x_firebase_appcheck: str = Header(None)
):
    if not x_firebase_appcheck:
        print("[/analyze] ❌ Missing App Check token")
        return JSONResponse(status_code=403, content={"error": "Missing Firebase App Check token"})

    print("[/analyze] App Check token received")
    if not validate_app_check_token(x_firebase_appcheck):
        print("[/analyze] ❌ Invalid App Check token")
        return JSONResponse(status_code=403, content={"error": "Invalid App Check token"})

    print("[/analyze] βœ… App Check token validated")
        
    audio_url = request.audio_url
    language_code = request.language_code or "en-US"

    if not audio_url or not gemini_api_key:
        return JSONResponse(status_code=400, content={"error": "Missing audio_url or gemini_api_key"})

    try:
        description = None
        thumbnail = None

        try:
            temp_path, description, thumbnail, author = download_video_audio_and_metadata(audio_url)
        except Exception:
            if audio_url.endswith(".mp3"):
                response = requests.get(audio_url)
                response.raise_for_status()
                with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f:
                    f.write(response.content)
                    temp_path = f.name
                description = None
                thumbnail = None
            else:
                raise

        result = model.transcribe(temp_path)
        os.remove(temp_path)

        if description:
            text_to_process = f"Description:\n{description}\n\nTranscription:\n{result['text']}"
        else:
            text_to_process = result["text"]

        prompt_template = os.environ.get("PROMPT_TEMPLATE")
        if not prompt_template:
            raise Exception("Missing PROMPT_TEMPLATE environment variable")

        prompt = prompt_template.format(
            language_code=language_code,
            text_to_process=text_to_process
        )

        structured_response = call_gemini(prompt, gemini_api_key)
        try:
            cleaned = clean_gemini_response(structured_response)
            structured_json = json.loads(cleaned)
        except json.JSONDecodeError:
            return JSONResponse(status_code=500, content={"error": "Invalid JSON from Gemini", "raw": structured_response})

        structured_json["video_transcription"] = result["text"]
        structured_json["video_description"] = description
        structured_json["video_url"] = audio_url
        structured_json["thumbnail_url"] = thumbnail
        structured_json["author"] = author
        return structured_json

    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})