Spaces:
Configuration error
Configuration error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
+
import tensorflow as tf
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# Load the TFLite model
|
| 11 |
+
interpreter = tf.lite.Interpreter(model_path="best_float32.tflite")
|
| 12 |
+
interpreter.allocate_tensors()
|
| 13 |
+
input_details = interpreter.get_input_details()
|
| 14 |
+
output_details = interpreter.get_output_details()
|
| 15 |
+
|
| 16 |
+
def preprocess(image: Image.Image):
|
| 17 |
+
image = image.resize((640, 640))
|
| 18 |
+
image = np.array(image, dtype=np.float32) / 255.0
|
| 19 |
+
image = np.expand_dims(image, axis=0)
|
| 20 |
+
return image
|
| 21 |
+
|
| 22 |
+
@app.get("/")
|
| 23 |
+
async def root():
|
| 24 |
+
return {"message": "Fake Logo Detection API is running 💡"}
|
| 25 |
+
|
| 26 |
+
@app.post("/predict")
|
| 27 |
+
async def predict(file: UploadFile = File(...)):
|
| 28 |
+
try:
|
| 29 |
+
contents = await file.read()
|
| 30 |
+
image = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 31 |
+
input_data = preprocess(image)
|
| 32 |
+
|
| 33 |
+
interpreter.set_tensor(input_details[0]['index'], input_data)
|
| 34 |
+
interpreter.invoke()
|
| 35 |
+
output_data = interpreter.get_tensor(output_details[0]['index'])
|
| 36 |
+
|
| 37 |
+
result = output_data.tolist()
|
| 38 |
+
return JSONResponse(content={"predictions": result})
|
| 39 |
+
|
| 40 |
+
except Exception as e:
|
| 41 |
+
return JSONResponse(status_code=500, content={"error": str(e)})
|