Update app.py
Browse files123417 unmodified lines2223242526272820 unmodified lines4950515253545556575859606162636465666768697071727374757677787980816 unmodified lines888990919293945 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160from fastapi import FastAPI, Requestfrom pydantic import BaseModelfrom fastapi.responses import JSONResponseimport whisper17 unmodified linesdef 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 linesdef 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}")result_json = response.json()return result_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 text@app.post("/analyze")6 unmodified linestry:description = Noneif "tiktok.com" in audio_url:temp_path, description = download_audio_from_tiktok(audio_url)else:5 unmodified linesresult = 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.Return ONLY valid JSON in this exact format:{{"title": "Recipe title here","ingredients": {{"sauce": [{{ "quantity": 2, "unit": "tbsp", "name": "olive oil" }},{{ "quantity": 1, "unit": "tsp", "name": "paprika" }}],"chicken": [{{ "quantity": 500, "unit": "g", "name": "chicken breast" }}]}},"steps": ["Step 1 ...","Step 2 ...",...]}}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"),}except Exception as e:return JSONResponse(status_code=500, content={"error": str(e)})123417 unmodified lines22232425262720 unmodified lines484950515253545556575859606162636465666 unmodified lines7374757677785 unmodified lines84858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142from fastapi import FastAPIfrom pydantic import BaseModelfrom fastapi.responses import JSONResponseimport whisper17 unmodified linesdef 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 linesdef 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)return match.group(1) if match else text@app.post("/analyze")6 unmodified linestry:description = Noneif "tiktok.com" in audio_url:temp_path, description = download_audio_from_tiktok(audio_url)else:5 unmodified linesresult = 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 AI. You will receive the text or transcript of a recipe from a video.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": {{"elaboration_title_here": [{{"quantity": 1.5,"unit": "tsp","name": "salt","icon": "🧂"}},{{"quantity": 750,"unit": "g","name": "chicken breast","icon": "🍗"}}]}},"steps": ["Step 1 ...","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:return JSONResponse(status_code=500, content={"error": "Invalid JSON from Gemini", "raw": structured_response})return structured_jsonexcept Exception as e:return JSONResponse(status_code=500, content={"error": str(e)})
app.py+33-51