Commit b7d4c69c authored by asus's avatar asus

Add Backend

parent 189a05e4
from fastapi import FastAPI, File, UploadFile
import firebase_admin
from firebase_admin import credentials, storage
import uvicorn
import numpy as np
from PIL import Image
import requests
from io import BytesIO
import tensorflow as tf
from urllib.parse import unquote
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred, {"storageBucket": "rp-project-d2045.appspot.com"})
bucket = storage.bucket()
def upload_to_firebase(file: UploadFile) -> str:
# Read the uploaded image
image_bytes = file.file.read()
# Resize the image to 256x256
image = Image.open(BytesIO(image_bytes))
image = image.resize((256, 256))
# Convert the image back to bytes
image_bytes_resized = BytesIO()
image.save(image_bytes_resized, format="JPEG")
image_bytes_resized = image_bytes_resized.getvalue()
# Set the path and upload the resized image to Firebase
image_path = f"images/{file.filename}"
blob = bucket.blob(image_path)
blob.upload_from_string(image_bytes_resized, content_type=file.content_type)
image_url = blob.public_url
return image_url
def read_file_as_image(url) -> np.ndarray:
response = requests.get(url)
try:
image = Image.open(BytesIO(response.content))
except Exception as e:
print(f"Error while opening image: {e}")
return None
return np.array(image)
MODEL_PATH_1 = "Models/1/VGG16.h5" # Update with the correct model path
MODEL_PATH_2 = "Models/2/VGG19.h5" # Update with the correct model path for model 2
CLASS_NAMES_1 = ['Diseases','Helthy','undefined' ]
CLASS_NAMES_2 = ['Anthracnose', 'Bacterial Blight', 'Cercospora Leaf Spot']
model_1 = tf.keras.models.load_model(MODEL_PATH_1)
model_2 = tf.keras.models.load_model(MODEL_PATH_2)
@app.get("/")
async def ping():
return {"message": "Ping successful"}
@app.post("/predict")
async def predict_disease(
file: UploadFile = File(...)
):
image_url = upload_to_firebase(file)
image = read_file_as_image(unquote(image_url))
if image is None:
return {"error": "Failed to load image"}
img_batch = np.expand_dims(image, 0)
predictions_1 = model_1.predict(img_batch)
predicted_class_1 = CLASS_NAMES_1[np.argmax(predictions_1[0])]
confidence_1 = np.max(predictions_1[0])
if predicted_class_1 == "Diseases":
predictions_2 = model_2.predict(img_batch)
predicted_class_2 = CLASS_NAMES_2[np.argmax(predictions_2[0])]
confidence_2 = np.max(predictions_2[0])
return {
'class_model_1': predicted_class_1,
'confidence_model_1': float(confidence_1),
'class_model_2': predicted_class_2,
'confidence_model_2': float(confidence_2)
}
else:
return {
'class_model_1': predicted_class_1,
'confidence_model_1': float(confidence_1)
}
# CORS middleware configuration
origins = [
"http://localhost:8081",
"http://localhost:3000",
"http://localhost:8088", # Replace this with your frontend's domain
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
if __name__ == "__main__":
uvicorn.run(app, host='192.168.140.107', port=8000)
\ No newline at end of file
{
"type": "service_account",
"project_id": "rp-project-d2045",
"private_key_id": "1afcdfd65ccfbfad05701b64473f28d58ffbb67b",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDkWOGO4YLY589G\nlfopPyEYMmchwqmzl+FHafUMCPznZajx7VIOSvH93vbfL/J/7sXDqtkN4iThhgj/\nfUXU9cHEVuqAW1r3ppWWb9xG6CORManJXHVhpXqym3OueOOTvBkkRVruL/FEU/EC\nNTlDSLiu+qN81QRm7kID6spFPyRT6IPe9OhfyjP2nrmLaWKdA/AknLG1LSEcYFm1\nfw9obD9EenT+lJOUU71oMuX7AxUL5pOc+nirnujGkaObCo5/a67GsVzgDqJRrqpm\nnq3wa51OySDSp1SZ8B9HZtM6K6XxSp9D263TtF/COe6/8Me/JePOxEp6loz+Fycv\nepJtwLAbAgMBAAECggEAHYrYPRLfnwNioC21dzz5IaHHu6jtKVSMK0qXOaQ3YBKZ\ncxnyj0cn8WHgIPZEPUPy0cKaoVQG1HycURLv2Wz60YAzMkG0zlcpgZSISaOCkn17\n4MF1rZk/ULiRlLAu3+//yrRZtCN/ZzPQTv+myxXZ+vK8pbZY2EjuloYmVCN7+4ov\nZv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gRx3g7zfB1FQTL\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-nz7m9@rp-project-d2045.iam.gserviceaccount.com",
"client_id": "113165482898063166799",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-nz7m9%40rp-project-d2045.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment