CoolFace
Apppublic

Risheeth/APT-models

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
api.py160 linesDownload Raw Back to root
1from flask import Flask, request, jsonify
2from flask_cors import CORS
3import numpy as np
4import pickle
5import os
6import cv2
7from tensorflow.keras.preprocessing.image import load_img, img_to_array
8from tensorflow.keras.models import load_model
9
10app = Flask(__name__)
11CORS(app)  # Allow cross-origin requests from Next.js
12
13# Allow handling of potentially large images/models
14app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB limit
15
16# Load models safely using relative paths if possible, but fallback to absolute
17base_dir = os.path.dirname(os.path.abspath(__file__))
18
19crop_model_path = os.path.join(base_dir, "Crop_recommendation_model_01.pkl")
20encoder_path = os.path.join(base_dir, "Crop_enc_new.pkl")
21disease_model_path = os.path.join(base_dir, "Plant_disease_prediction_model.keras")
22
23try:
24    with open(crop_model_path, "rb") as f:
25        crop_model = pickle.load(f)
26    with open(encoder_path, "rb") as f:
27        crop_encoder = pickle.load(f)
28    print("Crop Suggestion Models loaded.")
29except Exception as e:
30    print(f"Warning: Could not load Crop Model. Make sure {crop_model_path} exists. Error: {e}")
31    crop_model, crop_encoder = None, None
32
33try:
34    disease_model = load_model(disease_model_path)
35    print("Disease Detection Model loaded.")
36except Exception as e:
37    print(f"Warning: Could not load Disease Model. Make sure {disease_model_path} exists. Error: {e}")
38    disease_model = None
39
40
41# Disease Classes Dictionary
42disease_classes = {
43    0: ("Apple - Apple Scab", "Apply fungicides like Mancozeb or Captan during early leaf development. Remove infected leaves and fruits."),
44    1: ("Apple - Black Rot", "Prune infected branches and apply copper-based fungicides. Remove fallen leaves and fruit."),  
45    2: ("Apple - Cedar Apple Rust", "Use resistant varieties and apply fungicides like myclobutanil. Remove nearby cedar trees."),  
46    3: ("Apple - Healthy", "No disease detected. Maintain proper pruning and watering."),  
47    4: ("Blueberry - Healthy", "No disease detected. Ensure proper irrigation and pH-balanced soil."),  
48    5: ("Cherry - Powdery Mildew", "Apply sulfur-based fungicides and remove infected parts. Avoid excessive nitrogen."),  
49    6: ("Cherry - Healthy", "No disease detected. Provide well-drained soil and proper sunlight."),  
50    7: ("Corn - Cercospora Leaf Spot", "Use strobilurin or triazole fungicides. Rotate crops and remove debris."),  
51    8: ("Corn - Common Rust", "Apply propiconazole or tebuconazole. Plant rust-resistant varieties."),  
52    9: ("Corn - Northern Leaf Blight", "Use azoxystrobin and practice crop rotation. Maintain plant nutrition."),  
53    10: ("Corn - Healthy", "No disease detected. Ensure soil fertility with NPK fertilizers."),  
54    11: ("Grape - Black Rot", "Remove mummified berries. Apply Mancozeb or Captan. Ensure good air circulation."),  
55    12: ("Grape - Esca", "Prune affected vines early. Apply fungicides. Avoid excessive irrigation."),  
56    13: ("Grape - Leaf Blight", "Use Bordeaux mixture or copper fungicides. Improve drainage."),  
57    14: ("Grape - Healthy", "No disease detected. Maintain proper pruning and sunlight."),  
58    15: ("Orange - Citrus Greening", "Remove infected trees. Use insecticides for psyllids. Apply balanced fertilizers."),  
59    16: ("Peach - Bacterial Spot", "Apply copper bactericides. Avoid overhead irrigation. Remove infected parts."),  
60    17: ("Peach - Healthy", "No disease detected. Ensure proper air circulation."),  
61    18: ("Pepper - Bacterial Spot", "Use copper sprays. Remove infected leaves. Rotate crops annually."),  
62    19: ("Pepper - Healthy", "No disease detected. Ensure proper sunlight and well-drained soil."),  
63    20: ("Potato - Early Blight", "Apply Chlorothalonil. Use crop rotation. Avoid overwatering."),  
64    21: ("Potato - Late Blight", "Use Mancozeb. Plant resistant varieties. Avoid wet conditions."),  
65    22: ("Potato - Healthy", "No disease detected. Maintain soil fertility using compost."),  
66    23: ("Raspberry - Healthy", "No disease detected. Prune properly and use mulch."),  
67    24: ("Soybean - Healthy", "No disease detected. Use balanced fertilizers and ensure drainage."),  
68    25: ("Squash - Powdery Mildew", "Apply sulfur-based fungicides or neem oil. Avoid overhead watering."),  
69    26: ("Strawberry - Leaf Scorch", "Apply copper hydroxide. Ensure spacing and water at the base."),  
70    27: ("Strawberry - Healthy", "No disease detected. Keep soil well-drained. Remove dead leaves."),  
71    28: ("Tomato - Bacterial Spot", "Use copper sprays. Practice crop rotation. Avoid working when plants are wet."),  
72    29: ("Tomato - Early Blight", "Apply Chlorothalonil. Space plants properly for airflow."),  
73    30: ("Tomato - Late Blight", "Apply copper sprays. Improve air circulation by pruning."),  
74    31: ("Tomato - Leaf Mold", "Ensure airflow. Use copper-based sprays. Avoid high humidity."),  
75    32: ("Tomato - Septoria Leaf Spot", "Apply Chlorothalonil. Remove infected leaves. Avoid overhead watering."),  
76    33: ("Tomato - Spider Mites", "Use neem oil or insecticidal soap. Introduce natural predators like ladybugs."),  
77    34: ("Tomato - Target Spot", "Use Mancozeb or Chlorothalonil. Avoid wetting leaves. Maintain spacing."),  
78    35: ("Tomato - Yellow Leaf Curl Virus", "Control whiteflies. Remove infected plants. Use resistant varieties."),  
79    36: ("Tomato - Tomato Mosaic Virus", "Remove infected plants. Disinfect gardening tools. Wash hands after handling."),  
80    37: ("Tomato - Healthy", "No disease detected. Maintain proper soil nutrition and irrigation.")  
81}
82
83@app.route("/api/ping", methods=["GET"])
84def ping():
85    return jsonify({"status": "ok", "message": "ML Service is running"})
86
87@app.route("/api/predict-crop", methods=["POST"])
88def predict_crop():
89    if not crop_model or not crop_encoder:
90        return jsonify({"error": "Crop Model not loaded on server."}), 500
91
92    data = request.json
93    try:
94        # Extract features
95        N = float(data.get("N", 0))
96        P = float(data.get("P", 0))
97        K = float(data.get("K", 0))
98        pH = float(data.get("pH", 0))
99        rainfall = float(data.get("rainfall", 0))
100        temperature = float(data.get("temperature", 0))
101
102        input_data = np.array([[N, P, K, pH, rainfall, temperature]])
103        
104        predicted_label = int(crop_model.predict(input_data)[0])
105        prediction = crop_encoder.inverse_transform([predicted_label])[0]
106        
107        return jsonify({
108            "success": True,
109            "crop": prediction.capitalize()
110        })
111    except Exception as e:
112        return jsonify({"success": False, "error": str(e)}), 400
113
114@app.route("/api/predict-disease", methods=["POST"])
115def predict_disease():
116    if not disease_model:
117        return jsonify({"error": "Disease Model not loaded on server."}), 500
118
119    if 'image' not in request.files:
120        return jsonify({"error": "No image file provided in the request."}), 400
121    
122    file = request.files['image']
123    if file.filename == '':
124        return jsonify({"error": "No selected file."}), 400
125
126    try:
127        # Save temporarily to process
128        temp_path = os.path.join(base_dir, "temp_upload.jpg")
129        file.save(temp_path)
130
131        # Process Image for model
132        image = load_img(temp_path, target_size=(224, 224))
133        image = img_to_array(image) / 255.0
134        image = np.expand_dims(image, axis=0)
135
136        # Predict
137        result = disease_model.predict(image)
138        pred_class = np.argmax(result)
139        
140        disease, remedy = disease_classes.get(pred_class, ("Unknown Disease", "No remedy available."))
141        
142        # Cleanup
143        if os.path.exists(temp_path):
144            os.remove(temp_path)
145
146        return jsonify({
147            "success": True,
148            "disease": disease,
149            "remedy": remedy
150        })
151    except Exception as e:
152        if os.path.exists(temp_path):
153            os.remove(temp_path)
154        return jsonify({"success": False, "error": str(e)}), 500
155
156if __name__ == "__main__":
157    # Get port from environment variable for Hugging Face compatibility
158    port = int(os.environ.get("PORT", 7860))
159    app.run(host="0.0.0.0", port=port)
160