httpsAkayush commited on
Commit
3d8dd57
·
1 Parent(s): 8e2dc8a
Files changed (2) hide show
  1. app.py +56 -26
  2. requirements.txt +3 -1
app.py CHANGED
@@ -1,15 +1,29 @@
1
- import tempfile
 
2
  import tensorflow as tf
3
  import numpy as np
4
  from PIL import Image
5
- import gradio as gr
6
- import requests
7
- from io import BytesIO
8
  import cv2
9
 
10
- # Load your model (you'll need to upload trained_modela.keras to your space)
 
 
 
 
 
 
 
 
 
 
 
 
11
  model = tf.keras.models.load_model('trained_modela.keras')
12
 
 
13
  class_name = ['Apple___Apple_scab',
14
  'Apple___Black_rot',
15
  'Apple___Cedar_apple_rust',
@@ -50,22 +64,35 @@ class_name = ['Apple___Apple_scab',
50
  'Tomato___healthy']
51
 
52
 
 
 
 
53
 
54
- def predict_disease(image):
 
55
  """
56
- Predict plant disease from uploaded image using same preprocessing as your working cv2 method
57
  """
58
  try:
 
 
 
 
 
 
59
  with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
60
  temp_path = tmp.name
61
- image.save(temp_path)
62
-
 
 
63
  img = cv2.imread(temp_path)
 
 
64
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
65
- # Convert PIL image to array like load_img method
66
- #image = image.convert("RGB") # Ensure 3 channels
67
  image = tf.keras.preprocessing.image.load_img(temp_path,target_size=(128, 128))
68
- #image = image.resize((128, 128)) # Resize
69
  input_arr = tf.keras.preprocessing.image.img_to_array(image)
70
  input_arr = np.array([input_arr]) # Convert single image to batch
71
 
@@ -75,22 +102,25 @@ def predict_disease(image):
75
  confidence = prediction[0][result_index]
76
  disease_name = class_name[result_index]
77
 
78
- return f"Disease: {disease_name}\nConfidence: {confidence:.2%}"
 
 
 
 
79
 
 
 
80
  except Exception as e:
81
- return f"Error: {str(e)}"
82
 
83
- # Create Gradio interface
84
- iface = gr.Interface(
85
- fn=predict_disease,
86
- inputs=gr.Image(type="pil", label="Upload Plant Image"),
87
- outputs=gr.Textbox(label="Prediction Result"),
88
- title="Plant Disease Detection API",
89
- description="Upload an image of a plant leaf to detect diseases",
90
- examples=[
91
- # You can add example images here
92
- ]
93
- )
94
 
95
  if __name__ == "__main__":
96
- iface.launch()
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
  import tensorflow as tf
4
  import numpy as np
5
  from PIL import Image
6
+ import io
7
+ import uvicorn
8
+ import tempfile
9
  import cv2
10
 
11
+ # Initialize FastAPI app
12
+ app = FastAPI(title="Plant Disease Detection API", version="1.0.0")
13
+
14
+ # Add CORS middleware to allow requests from your frontend
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"], # In production, replace with your frontend URL
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
+
23
+ # Load your model
24
  model = tf.keras.models.load_model('trained_modela.keras')
25
 
26
+ # Define your class names (update with your actual classes)
27
  class_name = ['Apple___Apple_scab',
28
  'Apple___Black_rot',
29
  'Apple___Cedar_apple_rust',
 
64
  'Tomato___healthy']
65
 
66
 
67
+ @app.get("/")
68
+ async def root():
69
+ return {"message": "Plant Disease Detection API", "version": "1.0.0"}
70
 
71
+ @app.post("/predict")
72
+ async def predict_disease(file: UploadFile = File(...)):
73
  """
74
+ Predict plant disease from uploaded image
75
  """
76
  try:
77
+ # Validate file type
78
+ # Validate file type
79
+ if not file.content_type.startswith('image/'):
80
+ raise HTTPException(status_code=400, detail="File must be an image")
81
+
82
+ # Save uploaded file temporarily
83
  with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
84
  temp_path = tmp.name
85
+ contents = await file.read()
86
+ tmp.write(contents)
87
+
88
+ # Read image using OpenCV
89
  img = cv2.imread(temp_path)
90
+ if img is None:
91
+ raise HTTPException(status_code=400, detail="Invalid image file")
92
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
93
+
 
94
  image = tf.keras.preprocessing.image.load_img(temp_path,target_size=(128, 128))
95
+
96
  input_arr = tf.keras.preprocessing.image.img_to_array(image)
97
  input_arr = np.array([input_arr]) # Convert single image to batch
98
 
 
102
  confidence = prediction[0][result_index]
103
  disease_name = class_name[result_index]
104
 
105
+ return {
106
+ "success": True,
107
+ "disease": disease_name,
108
+ "confidence": confidence
109
+ }
110
 
111
+ except HTTPException as he:
112
+ raise he
113
  except Exception as e:
114
+ raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")
115
 
116
+ @app.get("/health")
117
+ async def health_check():
118
+ return {"status": "healthy"}
119
+
120
+ @app.get("/classes")
121
+ async def get_classes():
122
+ """Get all available disease classes"""
123
+ return {"classes": class_name}
 
 
 
124
 
125
  if __name__ == "__main__":
126
+ uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt CHANGED
@@ -3,4 +3,6 @@ numpy>=1.26.0,<2.2.0
3
  gradio == 5.44.1
4
  pillow == 10.4.0
5
  requests == 2.32.3
6
- opencv-python-headless == 4.12.0.88
 
 
 
3
  gradio == 5.44.1
4
  pillow == 10.4.0
5
  requests == 2.32.3
6
+ opencv-python-headless == 4.12.0.88
7
+ fastapi==0.116.1
8
+ uvicorn==0.35.0