from fastai.vision.all import *
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from PIL import Image
import io
import base64

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

def get_x(i):
    # Convert NumPy array to a single-channel PIL image with inverted colors
    return PILImageBW.create(all_noise[i])

def get_y(i):
    return all_thresh[i].astype(np.float32)

def get_items(_):
    return range(len(all_noise))

# Load the model
#learn = load_learner('model.pkl')
learn = load_learner('model2.pkl')

@app.get("/")
def read_root():
    html_content = "<p>This is a model inference point for the <a href='https://huggingface.co/spaces/vishalbakshi/isitadigit' target='_blank'>isitadigit</a> space</p>"
    return HTMLResponse(content=html_content)

class ImageData(BaseModel):
    image: str

def predict_image(img):
    img = img.convert("L")
    img = img.resize((28, 28))
    img = np.array(img)
    pred = np.clip(learn.predict(img)[0][0], 0.0, 1.0)
    return f"{pred:.2f}"

@app.post("/predict")
async def predict(data: ImageData):
    try:
        image_data = base64.b64decode(data.image)
        img = Image.open(io.BytesIO(image_data))
        probability = predict_image(img)
        return {"probability": probability}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
    
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)