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'(?