Update main.py
Browse files
main.py
CHANGED
|
@@ -1,48 +1,53 @@
|
|
| 1 |
-
|
| 2 |
-
from fastapi
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
tf.keras.layers.
|
| 27 |
-
tf.keras.layers.
|
| 28 |
-
tf.keras.layers.
|
| 29 |
-
tf.keras.layers.
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
image =
|
| 38 |
-
image = np.
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# main.py
|
| 2 |
+
from fastapi import FastAPI, File, UploadFile
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
import numpy as np
|
| 6 |
+
from vit_keras import vit
|
| 7 |
+
import tensorflow_addons as tfa
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
app = FastAPI()
|
| 12 |
+
|
| 13 |
+
# CORS configuration
|
| 14 |
+
app.add_middleware(
|
| 15 |
+
CORSMiddleware,
|
| 16 |
+
allow_origins=["*"], # Adjust this according to your security needs
|
| 17 |
+
allow_credentials=True,
|
| 18 |
+
allow_methods=["*"],
|
| 19 |
+
allow_headers=["*"],
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# Load the model
|
| 23 |
+
vit_model = vit.vit_b16(image_size=224, activation='softmax', pretrained=True, include_top=False, pretrained_top=False, classes=7)
|
| 24 |
+
model1 = tf.keras.Sequential([
|
| 25 |
+
vit_model,
|
| 26 |
+
tf.keras.layers.Flatten(),
|
| 27 |
+
tf.keras.layers.BatchNormalization(),
|
| 28 |
+
tf.keras.layers.Dense(11, activation=tfa.activations.gelu),
|
| 29 |
+
tf.keras.layers.BatchNormalization(),
|
| 30 |
+
tf.keras.layers.Dense(7, activation='softmax')
|
| 31 |
+
])
|
| 32 |
+
model1.load_weights('vit_model_weights.h5')
|
| 33 |
+
|
| 34 |
+
labels = ['akiec', 'bcc', 'bkl', 'df', 'mel', 'nv', 'vasc']
|
| 35 |
+
|
| 36 |
+
def preprocess_image(image: Image.Image):
|
| 37 |
+
image = image.resize((224, 224))
|
| 38 |
+
image = np.array(image) / 255.0
|
| 39 |
+
image = np.expand_dims(image, axis=0)
|
| 40 |
+
return image
|
| 41 |
+
|
| 42 |
+
@app.post("/predict/")
|
| 43 |
+
async def predict(file: UploadFile = File(...)):
|
| 44 |
+
image = Image.open(BytesIO(await file.read()))
|
| 45 |
+
processed_image = preprocess_image(image)
|
| 46 |
+
predictions = model1.predict(processed_image)
|
| 47 |
+
predicted_class = labels[np.argmax(predictions)]
|
| 48 |
+
confidence = np.max(predictions)
|
| 49 |
+
return {"predicted_class": predicted_class, "confidence": float(confidence)}
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
import uvicorn
|
| 53 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|