File size: 1,796 Bytes
aa63a8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from fastapi import FastAPI, UploadFile, File
from pydantic import BaseModel
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
import uvicorn
from io import BytesIO
from PIL import Image
import pickle
import requests
import threading

app = FastAPI()

# Load the trained model
model = pickle.load(open('pneumonia_mode.sav', 'rb'))

IMAGE_SIZE = (150, 150)

def preprocess_image(image_data):
    img = Image.open(BytesIO(image_data)).convert("RGB")
    img = img.resize(IMAGE_SIZE)
    img_array = np.array(img) / 255.0  # Normalize
    img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension
    return img_array

@app.post("/predict/")
async def predict(file: UploadFile = File(...)):
    image_data = await file.read()
    img_array = preprocess_image(image_data)
    probability = model.predict(img_array)[0][0]

    label = "Pneumonia" if probability > 0.5 else "Normal"
    confidence = float(probability) if probability > 0.5 else float(1 - probability)

    return {"prediction": label, "confidence": confidence}

# Start FastAPI server in a separate thread to prevent event loop issues
def start_server():
    uvicorn.run(app, host="0.0.0.0", port=8000)

if __name__ == "__main__":
    # Run the server in a separate thread
    server_thread = threading.Thread(target=start_server, daemon=True)
    server_thread.start()

    # Wait a moment to ensure the server starts
    import time
    time.sleep(2)

    # Send a request to the API
    url = "http://127.0.0.1:8000/predict"
    file_path = "/Users/singh/Downloads/images.jpg"
    with open(file_path, "rb") as f:
        files = {"file": f}
        response = requests.post(url, files=files)

    print(response.json())