File size: 1,132 Bytes
20e43d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, UploadFile, File
import tensorflow as tf
import numpy as np
from PIL import Image
import io
import requests
import os

MODEL_URL = "https://huggingface.co/blaxx14/cat-vs-dog-inceptionv3/resolve/main/cat_dog_inception_v3.h5"
MODEL_PATH = "cat_dog_inception_v3.h5"

app = FastAPI()

def download_model():
    if not os.path.exists(MODEL_PATH):
        print("Downloading model...")
        response = requests.get(MODEL_URL)
        with open(MODEL_PATH, "wb") as f:
            f.write(response.content)
        print("Model downloaded!")

download_model()

print("Loading model...")
model = tf.keras.models.load_model(MODEL_PATH)
print("Model loaded!")

def preprocess_image(image):
    img = Image.open(io.BytesIO(image)).convert("RGB")
    img = img.resize((150, 150))  
    img = np.array(img) / 255.0   
    img = np.expand_dims(img, axis=0)  
    return img

@app.post("/predict/")
async def predict(file: UploadFile = File(...)):
    image = await file.read()
    processed_img = preprocess_image(image)
    prediction = model.predict(processed_img)
    return {"prediction": prediction.tolist()}