httpsAkayush commited on
Commit
db33294
·
1 Parent(s): 438af47

Add application file

Browse files
Files changed (3) hide show
  1. Dockerfile +16 -0
  2. app.py +126 -0
  3. requirements.txt +8 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
2
+ # you will also find guides on how best to write your Dockerfile
3
+
4
+ FROM python:3.9
5
+
6
+ RUN useradd -m -u 1000 user
7
+ USER user
8
+ ENV PATH="/home/user/.local/bin:$PATH"
9
+
10
+ WORKDIR /app
11
+
12
+ COPY --chown=user ./requirements.txt requirements.txt
13
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
14
+
15
+ COPY --chown=user . /app
16
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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',
30
+ 'Apple___healthy',
31
+ 'Blueberry___healthy',
32
+ 'Cherry_(including_sour)___Powdery_mildew',
33
+ 'Cherry_(including_sour)___healthy',
34
+ 'Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot',
35
+ 'Corn_(maize)___Common_rust_',
36
+ 'Corn_(maize)___Northern_Leaf_Blight',
37
+ 'Corn_(maize)___healthy',
38
+ 'Grape___Black_rot',
39
+ 'Grape___Esca_(Black_Measles)',
40
+ 'Grape___Leaf_blight_(Isariopsis_Leaf_Spot)',
41
+ 'Grape___healthy',
42
+ 'Orange___Haunglongbing_(Citrus_greening)',
43
+ 'Peach___Bacterial_spot',
44
+ 'Peach___healthy',
45
+ 'Pepper,_bell___Bacterial_spot',
46
+ 'Pepper,_bell___healthy',
47
+ 'Potato___Early_blight',
48
+ 'Potato___Late_blight',
49
+ 'Potato___healthy',
50
+ 'Raspberry___healthy',
51
+ 'Soybean___healthy',
52
+ 'Squash___Powdery_mildew',
53
+ 'Strawberry___Leaf_scorch',
54
+ 'Strawberry___healthy',
55
+ 'Tomato___Bacterial_spot',
56
+ 'Tomato___Early_blight',
57
+ 'Tomato___Late_blight',
58
+ 'Tomato___Leaf_Mold',
59
+ 'Tomato___Septoria_leaf_spot',
60
+ 'Tomato___Spider_mites Two-spotted_spider_mite',
61
+ 'Tomato___Target_Spot',
62
+ 'Tomato___Tomato_Yellow_Leaf_Curl_Virus',
63
+ 'Tomato___Tomato_mosaic_virus',
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
+
99
+ # Predict
100
+ prediction = model.predict(input_arr)
101
+ result_index = np.argmax(prediction)
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=7860)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ tensorFlow == 2.19.0
2
+ 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
7
+ fastapi==0.116.1
8
+ uvicorn==0.35.0