-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
129 lines (107 loc) · 4.36 KB
/
Copy pathapp.py
File metadata and controls
129 lines (107 loc) · 4.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import os
import numpy as np
from flask import Flask, request, render_template, Response
from werkzeug.utils import secure_filename
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from tensorflow.keras.models import load_model
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
import requests
from requests.auth import HTTPBasicAuth
# Initialize Flask app
app = Flask(__name__)
# --------------------------
# 1️⃣ Load Trained Model
# --------------------------
model = load_model('model_name.h5')
print('✅ Model loaded successfully!')
labels = {0: 'Healthy', 1: 'Powdery', 2: 'Rust'}
precautions = {
"Rust": "🌿 Precaution for Rust: Remove infected leaves, avoid overhead watering, and apply a fungicide if necessary.",
"Powdery": "🌿 Precaution for Powdery Mildew: Improve air circulation, avoid wetting leaves, and use sulfur-based fungicide if needed.",
"Healthy": "✅ Your leaf looks healthy! Keep monitoring regularly and maintain good farm hygiene."
}
# --------------------------
# 2️⃣ Twilio Setup
# --------------------------
ACCOUNT_SID = 'sid token'
AUTH_TOKEN = 'auth token' # Replace with your Twilio Auth Token
FROM_WHATSAPP = "whatsapp:no" # Twilio sandbox number
client = Client(ACCOUNT_SID, AUTH_TOKEN)
# --------------------------
# 3️⃣ Helper: Prediction
# --------------------------
def getResult(image_path):
img = load_img(image_path, target_size=(225, 225))
x = img_to_array(img)
x = x.astype('float32') / 255.
x = np.expand_dims(x, axis=0)
predictions = model.predict(x)[0]
predicted_label = labels[np.argmax(predictions)]
return predicted_label
# --------------------------
# 4️⃣ Web Interface Route
# --------------------------
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
f = request.files['file']
basepath = os.path.dirname(__file__)
upload_dir = os.path.join(basepath, 'uploads')
os.makedirs(upload_dir, exist_ok=True)
file_path = os.path.join(upload_dir, secure_filename(f.filename))
f.save(file_path)
predicted_label = getResult(file_path)
return str(predicted_label)
return None
# --------------------------
# 5️⃣ WhatsApp Integration Route
# --------------------------
@app.route("/whatsapp", methods=["POST"])
def whatsapp_reply():
"""
Handles incoming WhatsApp messages from Twilio.
Farmers can send leaf images and get predictions instantly.
"""
# Log incoming Twilio data for debugging
print("Incoming Twilio data:", request.form)
media_url = request.form.get('MediaUrl0')
resp = MessagingResponse()
reply = resp.message()
if media_url:
try:
# Ensure uploads folder exists
os.makedirs("uploads", exist_ok=True)
img_path = os.path.join("uploads", "whatsapp_leaf.jpg")
# Download media with Twilio authentication
img_data = requests.get(media_url, auth=HTTPBasicAuth(ACCOUNT_SID, AUTH_TOKEN)).content
with open(img_path, "wb") as f:
f.write(img_data)
# Predict leaf disease
predicted_label = getResult(img_path)
precaution_text = precautions.get(predicted_label, "")
reply.body(f"🍃 Prediction: {predicted_label}\n{precaution_text}")
except Exception as e:
print("Error processing image:", e)
reply.body("⚠️ Error processing the image. Please try again.")
else:
reply.body("Please send a *leaf image* of apple tree to detect disease 🌿")
# Return proper TwiML response with Content-Type
return Response(str(resp), mimetype="text/xml")
# --------------------------
# 6️⃣ Optional: Send proactive WhatsApp message from Flask
# --------------------------
def send_whatsapp_message(to_number, message_text):
client.messages.create(
from_=FROM_WHATSAPP,
body=message_text,
to=f"whatsapp:{to_number}"
)
# --------------------------
# 7️⃣ Run Flask App
# --------------------------
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)