Spaces:
Runtime error
Runtime error
Commit ·
8b19fd0
1
Parent(s): 4d079c5
chore: change app.py to main.py
Browse files- app.py → main.py +98 -98
app.py → main.py
RENAMED
|
@@ -1,98 +1,98 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import os
|
| 4 |
-
from contextlib import asynccontextmanager
|
| 5 |
-
|
| 6 |
-
import uvicorn
|
| 7 |
-
from fastapi import FastAPI, File, HTTPException, UploadFile
|
| 8 |
-
from fastapi.concurrency import run_in_threadpool
|
| 9 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
-
from pydantic import BaseModel
|
| 11 |
-
|
| 12 |
-
from inference import get_model_path, load_model, predict_image_bytes
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
class ProbabilityResponse(BaseModel):
|
| 16 |
-
negative: float
|
| 17 |
-
neutral: float
|
| 18 |
-
positive: float
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
class PredictionResponse(BaseModel):
|
| 22 |
-
label: str
|
| 23 |
-
fis_score: float
|
| 24 |
-
cnn_prediction_name: str
|
| 25 |
-
probabilities: ProbabilityResponse
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def get_allowed_origins() -> list[str]:
|
| 29 |
-
configured_origins = os.getenv("AI_ENGINE_ALLOWED_ORIGINS", "")
|
| 30 |
-
if configured_origins.strip():
|
| 31 |
-
return [origin.strip() for origin in configured_origins.split(",") if origin.strip()]
|
| 32 |
-
|
| 33 |
-
return [
|
| 34 |
-
"http://localhost:3000",
|
| 35 |
-
"http://127.0.0.1:3000",
|
| 36 |
-
]
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
@asynccontextmanager
|
| 40 |
-
async def lifespan(_: FastAPI):
|
| 41 |
-
yield
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
app = FastAPI(
|
| 45 |
-
title="Soft Computing AI Engine",
|
| 46 |
-
description="FastAPI service for CNN + FIS image sentiment inference.",
|
| 47 |
-
version="0.1.0",
|
| 48 |
-
lifespan=lifespan,
|
| 49 |
-
)
|
| 50 |
-
|
| 51 |
-
app.add_middleware(
|
| 52 |
-
CORSMiddleware,
|
| 53 |
-
allow_origins=get_allowed_origins(),
|
| 54 |
-
allow_credentials=False,
|
| 55 |
-
allow_methods=["*"],
|
| 56 |
-
allow_headers=["*"],
|
| 57 |
-
)
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
@app.get("/health")
|
| 61 |
-
def health():
|
| 62 |
-
model_path = get_model_path()
|
| 63 |
-
return {
|
| 64 |
-
"status": "ok",
|
| 65 |
-
"model_exists": model_path.exists(),
|
| 66 |
-
"model_loaded": load_model.cache_info().currsize > 0,
|
| 67 |
-
"model_path": str(model_path),
|
| 68 |
-
}
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
@app.post("/predict", response_model=PredictionResponse)
|
| 72 |
-
async def predict(file: UploadFile = File(...)):
|
| 73 |
-
if not file.content_type or not file.content_type.startswith("image/"):
|
| 74 |
-
raise HTTPException(status_code=400, detail="Upload harus berupa file gambar.")
|
| 75 |
-
|
| 76 |
-
image_bytes = await file.read()
|
| 77 |
-
await file.close()
|
| 78 |
-
|
| 79 |
-
if not image_bytes:
|
| 80 |
-
raise HTTPException(status_code=400, detail="File gambar kosong.")
|
| 81 |
-
|
| 82 |
-
try:
|
| 83 |
-
prediction = await run_in_threadpool(predict_image_bytes, image_bytes)
|
| 84 |
-
except FileNotFoundError as error:
|
| 85 |
-
raise HTTPException(status_code=500, detail=str(error)) from error
|
| 86 |
-
except ValueError as error:
|
| 87 |
-
raise HTTPException(status_code=400, detail=str(error)) from error
|
| 88 |
-
except Exception as error:
|
| 89 |
-
raise HTTPException(
|
| 90 |
-
status_code=500,
|
| 91 |
-
detail=f"Prediksi gagal dijalankan: {error}",
|
| 92 |
-
) from error
|
| 93 |
-
|
| 94 |
-
return PredictionResponse.model_validate(prediction)
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
if __name__ == "__main__":
|
| 98 |
-
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from contextlib import asynccontextmanager
|
| 5 |
+
|
| 6 |
+
import uvicorn
|
| 7 |
+
from fastapi import FastAPI, File, HTTPException, UploadFile
|
| 8 |
+
from fastapi.concurrency import run_in_threadpool
|
| 9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
+
from pydantic import BaseModel
|
| 11 |
+
|
| 12 |
+
from inference import get_model_path, load_model, predict_image_bytes
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ProbabilityResponse(BaseModel):
|
| 16 |
+
negative: float
|
| 17 |
+
neutral: float
|
| 18 |
+
positive: float
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class PredictionResponse(BaseModel):
|
| 22 |
+
label: str
|
| 23 |
+
fis_score: float
|
| 24 |
+
cnn_prediction_name: str
|
| 25 |
+
probabilities: ProbabilityResponse
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def get_allowed_origins() -> list[str]:
|
| 29 |
+
configured_origins = os.getenv("AI_ENGINE_ALLOWED_ORIGINS", "")
|
| 30 |
+
if configured_origins.strip():
|
| 31 |
+
return [origin.strip() for origin in configured_origins.split(",") if origin.strip()]
|
| 32 |
+
|
| 33 |
+
return [
|
| 34 |
+
"http://localhost:3000",
|
| 35 |
+
"http://127.0.0.1:3000",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@asynccontextmanager
|
| 40 |
+
async def lifespan(_: FastAPI):
|
| 41 |
+
yield
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
app = FastAPI(
|
| 45 |
+
title="Soft Computing AI Engine",
|
| 46 |
+
description="FastAPI service for CNN + FIS image sentiment inference.",
|
| 47 |
+
version="0.1.0",
|
| 48 |
+
lifespan=lifespan,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
app.add_middleware(
|
| 52 |
+
CORSMiddleware,
|
| 53 |
+
allow_origins=get_allowed_origins(),
|
| 54 |
+
allow_credentials=False,
|
| 55 |
+
allow_methods=["*"],
|
| 56 |
+
allow_headers=["*"],
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@app.get("/health")
|
| 61 |
+
def health():
|
| 62 |
+
model_path = get_model_path()
|
| 63 |
+
return {
|
| 64 |
+
"status": "ok",
|
| 65 |
+
"model_exists": model_path.exists(),
|
| 66 |
+
"model_loaded": load_model.cache_info().currsize > 0,
|
| 67 |
+
"model_path": str(model_path),
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@app.post("/predict", response_model=PredictionResponse)
|
| 72 |
+
async def predict(file: UploadFile = File(...)):
|
| 73 |
+
if not file.content_type or not file.content_type.startswith("image/"):
|
| 74 |
+
raise HTTPException(status_code=400, detail="Upload harus berupa file gambar.")
|
| 75 |
+
|
| 76 |
+
image_bytes = await file.read()
|
| 77 |
+
await file.close()
|
| 78 |
+
|
| 79 |
+
if not image_bytes:
|
| 80 |
+
raise HTTPException(status_code=400, detail="File gambar kosong.")
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
prediction = await run_in_threadpool(predict_image_bytes, image_bytes)
|
| 84 |
+
except FileNotFoundError as error:
|
| 85 |
+
raise HTTPException(status_code=500, detail=str(error)) from error
|
| 86 |
+
except ValueError as error:
|
| 87 |
+
raise HTTPException(status_code=400, detail=str(error)) from error
|
| 88 |
+
except Exception as error:
|
| 89 |
+
raise HTTPException(
|
| 90 |
+
status_code=500,
|
| 91 |
+
detail=f"Prediksi gagal dijalankan: {error}",
|
| 92 |
+
) from error
|
| 93 |
+
|
| 94 |
+
return PredictionResponse.model_validate(prediction)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|