Update app.py
Browse files1123417 unmodified lines2223242525262720 unmodified lines484950525354555657585960616263515253545556686970575859606162767763786465666 unmodified lines737475917677785 unmodified lines84858610387888910710810911011111211311411511690911189293949596979899100101102103123124125126127128104105106107108109110111112113114115116117118119120133134121122123124125126127128129130131132144133134135136149150151152153154155156157137138139140141142from fastapi import FastAPI, Requestfrom fastapi import FastAPIfrom pydantic import BaseModelfrom fastapi.responses import JSONResponseimport whisper17 unmodified lines
def download_audio_from_tiktok(url: str) -> tuple[str, str]: temp_filename = f"/tmp/{uuid.uuid4()}.mp3"
try: description = subprocess.check_output([ "yt-dlp",20 unmodified lines
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}] } ] } 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}")
result_json = response.json() return result_json["candidates"][0]["content"]["parts"][0]["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) if match: return match.group(1) return match.group(1) if match else text return text
@app.post("/analyze")6 unmodified lines
try: description = None
if "tiktok.com" in audio_url: temp_path, description = download_audio_from_tiktok(audio_url) else:5 unmodified lines
result = model.transcribe(temp_path) os.remove(temp_path)
text_to_process = description if description else result["text"]
prompt = f"""You are an expert cooking assistant. You receive a recipe description or text.Your task is to extract and return a valid JSON with three keys: "title", "ingredients", and "steps".
- "title" should be a short, descriptive name for the recipe.- "ingredients" must be a dictionary grouped by preparation parts (e.g. chicken, sauce, side dish, etc.). Each ingredient should be represented as an object with: - "quantity": the numeric amount (use float if needed, or null if not specified), - "unit": the measurement unit (e.g. g, ml, tsp, tbsp, cup, etc., or null if not applicable), - "name": the name of the ingredient.- "steps" should be an ordered list of step-by-step instructions to prepare the recipe.You are an expert cooking assistant AI. You will receive the text or transcript of a recipe from a video.
Return ONLY valid JSON in this exact format:Return ONLY valid JSON with the following structure:
{{ "title": "Recipe title here", "video_description": "Text from the original video if provided", "author": "If known or mentioned", "video_url": "{audio_url}", "duration_minutes": 25, "kcal": 600, "difficulty": "easy", "servings": 2, "ingredients": {{ "sauce": [ {{ "quantity": 2, "unit": "tbsp", "name": "olive oil" }}, {{ "quantity": 1, "unit": "tsp", "name": "paprika" }} ], "chicken": [ {{ "quantity": 500, "unit": "g", "name": "chicken breast" }} "elaboration_title_here": [ {{ "quantity": 1.5, "unit": "tsp", "name": "salt", "icon": "🧂" }}, {{ "quantity": 750, "unit": "g", "name": "chicken breast", "icon": "🍗" }} ] }}, "steps": [ "Step 1 ...", "Step 2 ...", ... "Step 2 ..." ]}}
Infer all missing values if not explicitly stated, using the video text.
Here is the text to analyze:
\"\"\"{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: structured_json = {"raw_response": structured_response}
return { "title": structured_json.get("title"), "transcription_text": result["text"], "description": description, "ingredients": structured_json.get("ingredients"), "steps": structured_json.get("steps"), } return JSONResponse(status_code=500, content={"error": "Invalid JSON from Gemini", "raw": structured_response})
return structured_json
except Exception as e: return JSONResponse(status_code=500, content={"error": str(e)})app.py+33-51