Spaces:
Sleeping
Sleeping
File size: 1,109 Bytes
6e77308 b5d99a8 6e77308 b5d99a8 cc33eed b5d99a8 6e77308 b5d99a8 cc33eed b5d99a8 6e77308 b5d99a8 6e77308 cc33eed 6e77308 b5d99a8 cc33eed b5d99a8 |
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 |
from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
import numpy as np
from PIL import Image
import tensorflow as tf
# Load model and classes
model = tf.keras.models.load_model("hf_keras_model.keras")
class_names = ['buildings', 'forest', 'glacier', 'mountain', 'sea', 'street']
# Initialize app
app = FastAPI()
# Allow all CORS (for frontend/test requests)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def root():
return {"message": "API is working!"}
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
# Load image
image = Image.open(file.file).convert("RGB").resize((150, 150))
img_array = np.array(image) / 255.0
img_array = np.expand_dims(img_array, axis=0)
# Predict
predictions = model.predict(img_array)[0]
results = {class_names[i]: float(predictions[i]) for i in range(len(class_names))}
top_class = class_names[np.argmax(predictions)]
return {"top_prediction": top_class, "all_predictions": results}
|