Download app.py from magikdevelopments/transcript-video-audio-flask: direct link, hf CLI and curl.
- Browser
- Download file 6.51 kB
-
https://huggingface.co/spaces/magikdevelopments/transcript-video-audio-flask/resolve/main/app.py
- Command line
-
hf download hf://spaces/magikdevelopments/transcript-video-audio-flask/app.py
-
curl -L -o app.py https://huggingface.co/spaces/magikdevelopments/transcript-video-audio-flask/resolve/main/app.py
6.51 kB
| 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 | |
| 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)}) |