Commit 2dbd1f90 authored by Vidanapathirana V.D's avatar Vidanapathirana V.D

Merge branch 'IT20144708' into 'master'

It20144708

See merge request !6
parents c22823f2 252627c4
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+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l8VUCjZcejk/q0AYPEz7QmRlP1ia2xl5g9aJ\n3Yr3MT3i2GgRx3g7zfB1FQTL\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"
}
This diff is collapsed.
This diff is collapsed.
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"id": "72ba86ae",
"metadata": {},
"outputs": [
{
"ename": "OSError",
"evalue": "cannot write mode RGBA as JPEG",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)",
"File \u001b[1;32m~\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\PIL\\JpegImagePlugin.py:643\u001b[0m, in \u001b[0;36m_save\u001b[1;34m(im, fp, filename)\u001b[0m\n\u001b[0;32m 642\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m--> 643\u001b[0m rawmode \u001b[38;5;241m=\u001b[39m \u001b[43mRAWMODE\u001b[49m\u001b[43m[\u001b[49m\u001b[43mim\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmode\u001b[49m\u001b[43m]\u001b[49m\n\u001b[0;32m 644\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mKeyError\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n",
"\u001b[1;31mKeyError\u001b[0m: 'RGBA'",
"\nThe above exception was the direct cause of the following exception:\n",
"\u001b[1;31mOSError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn [2], line 32\u001b[0m\n\u001b[0;32m 30\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i, transformed_image \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(transformed_images):\n\u001b[0;32m 31\u001b[0m transformed_image_path \u001b[38;5;241m=\u001b[39m os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39mjoin(new_folder_path, \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mfilename\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m_transformed_\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mi\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m.jpg\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m---> 32\u001b[0m \u001b[43mtransformed_image\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msave\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtransformed_image_path\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 34\u001b[0m \u001b[38;5;66;03m# Increment the number of processed images and check if we've processed 400 images\u001b[39;00m\n\u001b[0;32m 35\u001b[0m processed_images \u001b[38;5;241m+\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n",
"File \u001b[1;32m~\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\PIL\\Image.py:2431\u001b[0m, in \u001b[0;36mImage.save\u001b[1;34m(self, fp, format, **params)\u001b[0m\n\u001b[0;32m 2428\u001b[0m fp \u001b[38;5;241m=\u001b[39m builtins\u001b[38;5;241m.\u001b[39mopen(filename, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mw+b\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 2430\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m-> 2431\u001b[0m \u001b[43msave_handler\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mfp\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mfilename\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 2432\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m:\n\u001b[0;32m 2433\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m open_fp:\n",
"File \u001b[1;32m~\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\PIL\\JpegImagePlugin.py:646\u001b[0m, in \u001b[0;36m_save\u001b[1;34m(im, fp, filename)\u001b[0m\n\u001b[0;32m 644\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mKeyError\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[0;32m 645\u001b[0m msg \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcannot write mode \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mim\u001b[38;5;241m.\u001b[39mmode\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m as JPEG\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m--> 646\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mOSError\u001b[39;00m(msg) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01me\u001b[39;00m\n\u001b[0;32m 648\u001b[0m info \u001b[38;5;241m=\u001b[39m im\u001b[38;5;241m.\u001b[39mencoderinfo\n\u001b[0;32m 650\u001b[0m dpi \u001b[38;5;241m=\u001b[39m [\u001b[38;5;28mround\u001b[39m(x) \u001b[38;5;28;01mfor\u001b[39;00m x \u001b[38;5;129;01min\u001b[39;00m info\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mdpi\u001b[39m\u001b[38;5;124m\"\u001b[39m, (\u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m0\u001b[39m))]\n",
"\u001b[1;31mOSError\u001b[0m: cannot write mode RGBA as JPEG"
]
}
],
"source": [
"from PIL import Image\n",
"import os\n",
"\n",
"# Path to the existing folder with image files\n",
"existing_folder_path = r\"C:\\Users\\asus\\Desktop\\New folder\"\n",
"\n",
"# Create a new folder to store the transformed images\n",
"new_folder_path =r\"C:\\Users\\asus\\Desktop\\New folder (2)\"\n",
"if not os.path.exists(new_folder_path):\n",
" os.makedirs(new_folder_path)\n",
"\n",
"# Loop through all image files in the existing folder\n",
"processed_images = 0\n",
"for filename in os.listdir(existing_folder_path):\n",
" # Check if the file is an image file\n",
" if filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n",
" # Open the existing image\n",
" existing_image_path = os.path.join(existing_folder_path, filename)\n",
" existing_image = Image.open(existing_image_path)\n",
"\n",
" # Apply some transformations to the image\n",
" transformed_images = []\n",
" for i in range(5):\n",
" # Example transformations - you can modify these to fit your needs\n",
" transformed_image = existing_image.rotate(90*i)\n",
" transformed_image = transformed_image.transpose(Image.FLIP_LEFT_RIGHT)\n",
" transformed_images.append(transformed_image)\n",
"\n",
" # Save the transformed images to the new folder\n",
" for i, transformed_image in enumerate(transformed_images):\n",
" transformed_image_path = os.path.join(new_folder_path, f\"{filename}_transformed_{i}.jpg\")\n",
" transformed_image.save(transformed_image_path)\n",
"\n",
" # Increment the number of processed images and check if we've processed 400 images\n",
" processed_images += 1\n",
" if processed_images == 400:\n",
" break\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3026991e",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "e4e351af",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
This diff is collapsed.
xcfdgfdv
\ No newline at end of file
Disease
\ No newline at end of file
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