ace7s/mpoxscanccs6
0
1from fastapi import FastAPI, File, UploadFile2from fastapi.responses import JSONResponse3from modelpipeline import model_pipeline4from PIL import Image5import io6from fastapi.middleware.cors import CORSMiddleware7import firebase_admin8from firebase_admin import credentials, firestore9 10# Initialize Firebase11cred = credentials.Certificate('firebaseKey.json') # Replace with your actual path12firebase_admin.initialize_app(cred)13 14# Initialize Firestore15db = firestore.client()16 17app = FastAPI()18app.add_middleware(19 CORSMiddleware,20 allow_origins=["*"], # Replace '*' with specific domains for better security21 allow_credentials=True,22 allow_methods=["*"],23 allow_headers=["*"],24)25 26@app.get("/")27def read_root():28 return {"message": "Welcome to the MobileNetV3 API"}29 30@app.post("/ask")31async def predict(file: UploadFile = File(...)):32 # Read the uploaded file33 content = await file.read()34 print("Received file of size:", len(content)) # Debugging step35 image = Image.open(io.BytesIO(content))36 37 # Run the model pipeline on the uploaded file38 final_predicted_class, final_confidence, img_str = model_pipeline(image)39 40 # Determine confidence level41 confidence_level = "low"42 if final_confidence > 0.8:43 confidence_level = "high"44 elif final_confidence > 0.6:45 confidence_level = "medium"46 47 # Convert final_confidence to percentage and round to 2 decimal places48 final_confidence_percentage = round(final_confidence * 100, 2)49 50 # Create the JSON response51 response_content = {52 "prediction": final_predicted_class,53 "confidence": final_confidence_percentage,54 "confidence level": confidence_level,55 "image": img_str56 }57 58 # Save the JSON response to Firestore59 doc_ref = db.collection('responses').add(response_content)60 print(f'Successfully saved JSON response with ID: {doc_ref[1].id}')61 62 return JSONResponse(content=response_content)