File size: 1,319 Bytes
dd5fd0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
40
41
42
43
44
45
46
47
48
49
50
51
52
from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
import io
import base64
import requests
import os
from dotenv import load_dotenv
import multipart

load_dotenv()  # 🔒 Load .env variables

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

HF_API_URL = "https://api-inference.huggingface.co/models/OttoYu/TreeClassification"
HF_API_TOKEN = os.getenv("HF_API_TOKEN")

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    image_data = await file.read()
    base64_image = base64.b64encode(image_data).decode("utf-8")

    headers = {
        "Authorization": f"Bearer {HF_API_TOKEN}",
        "Content-Type": "application/json"
    }

    response = requests.post(
        HF_API_URL,
        headers=headers,
        json={"inputs": f"data:image/jpeg;base64,{base64_image}"}
    )

    if response.status_code != 200:
        return {"error": "Failed to get prediction from Hugging Face API", "details": response.text}

    result = response.json()
    try:
        label = result[0]["label"]
    except Exception:
        label = "ไม่สามารถจำแนกได้"

    return {"label": label}