File size: 1,737 Bytes
7ad8ad8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse

# ตั้งค่า API URLs
PREDICTION_API_URL = "https://thiophai-foodai-llmmodel.hf.space/predict"
FOOD_GENERATOR_API_URL = "https://thiophai-foodai-llmmodel.hf.space/predict"

app = FastAPI()

@app.post("/predict-food")
async def predict_food(file: UploadFile = File(...)):
    """
    API ตัวกลางสำหรับรับไฟล์ภาพ ส่งไปยัง Prediction API เพื่อทำนายชื่อเมนู
    และส่งชื่อเมนูไปยัง Food Generator API เพื่อดึงข้อมูลโภชนาการ
    """
    # ส่งภาพไปที่ Prediction API
    files = {"file": (file.filename, await file.read(), file.content_type)}
    response = requests.post(PREDICTION_API_URL, files=files)

    if response.status_code != 200:
        return JSONResponse(content={"error": "Failed to predict food"}, status_code=500)

    prediction_result = response.json()

    # ตรวจสอบผลลัพธ์จาก Prediction API
    if "prediction" not in prediction_result or prediction_result["prediction"] == "Not food":
        return JSONResponse(content={"error": "The uploaded image does not contain food"}, status_code=400)

    food_name = prediction_result["prediction"]

    # ส่งชื่อเมนูไปยัง Food Generator API
    response = requests.post(FOOD_GENERATOR_API_URL, params={"menu_name": food_name})

    if response.status_code != 200:
        return JSONResponse(content={"error": "Failed to generate food details"}, status_code=500)

    return response.json()