Spaces:
Runtime error
Runtime error
Commit ·
dd5fd0f
1
Parent(s): 442a8dc
Add application file
Browse files- Dockerfile +11 -0
- app.py +51 -0
- requirements.txt +7 -0
Dockerfile
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt ./
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY . .
|
| 9 |
+
|
| 10 |
+
EXPOSE 8000
|
| 11 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
|
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import io
|
| 5 |
+
import base64
|
| 6 |
+
import requests
|
| 7 |
+
import os
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
import multipart
|
| 10 |
+
|
| 11 |
+
load_dotenv() # 🔒 Load .env variables
|
| 12 |
+
|
| 13 |
+
app = FastAPI()
|
| 14 |
+
|
| 15 |
+
app.add_middleware(
|
| 16 |
+
CORSMiddleware,
|
| 17 |
+
allow_origins=["*"],
|
| 18 |
+
allow_credentials=True,
|
| 19 |
+
allow_methods=["*"],
|
| 20 |
+
allow_headers=["*"],
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
HF_API_URL = "https://api-inference.huggingface.co/models/OttoYu/TreeClassification"
|
| 24 |
+
HF_API_TOKEN = os.getenv("HF_API_TOKEN")
|
| 25 |
+
|
| 26 |
+
@app.post("/predict")
|
| 27 |
+
async def predict(file: UploadFile = File(...)):
|
| 28 |
+
image_data = await file.read()
|
| 29 |
+
base64_image = base64.b64encode(image_data).decode("utf-8")
|
| 30 |
+
|
| 31 |
+
headers = {
|
| 32 |
+
"Authorization": f"Bearer {HF_API_TOKEN}",
|
| 33 |
+
"Content-Type": "application/json"
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
response = requests.post(
|
| 37 |
+
HF_API_URL,
|
| 38 |
+
headers=headers,
|
| 39 |
+
json={"inputs": f"data:image/jpeg;base64,{base64_image}"}
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
if response.status_code != 200:
|
| 43 |
+
return {"error": "Failed to get prediction from Hugging Face API", "details": response.text}
|
| 44 |
+
|
| 45 |
+
result = response.json()
|
| 46 |
+
try:
|
| 47 |
+
label = result[0]["label"]
|
| 48 |
+
except Exception:
|
| 49 |
+
label = "ไม่สามารถจำแนกได้"
|
| 50 |
+
|
| 51 |
+
return {"label": label}
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
transformers
|
| 4 |
+
torch
|
| 5 |
+
pillow
|
| 6 |
+
python-dotenv
|
| 7 |
+
python-multipart
|