Sharad9084's picture
Update app.py
b487304 verified
# βœ… SMART AGRICULTURE SYSTEM FULL CODE
# Includes: Streamlit App + Crop Recommendation + Disease Detection + Smart Irrigation + Symptom-based NLP + Weather API + Image Detection + City Auto-detect
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
import requests
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import json
# -------------------------------
# πŸ“Œ Load Crop Recommendation Model
# -------------------------------
# df = pd.read_csv("crop-recommendation-dataset/Crop_recommendation.csv")
# X = df.drop('label', axis=1)
# y = df['label']
# model_crop = RandomForestClassifier(n_estimators=100, random_state=42)
# model_crop.fit(X, y)
import pickle
with open('crop_model.pkl', 'rb') as file:
model_crop = pickle.load(file)
# -------------------------------
# πŸ’§ Crop Water Requirements
# -------------------------------
crop_water_needs = {
'rice': 6.0, 'wheat': 4.0, 'maize': 4.5, 'cotton': 5.0, 'sugarcane': 8.0,
'banana': 7.0, 'millet': 3.5, 'ground nut': 4.2, 'barley': 3.8
}
# -------------------------------
# 🌀️ Weather API Function
# -------------------------------
def get_weather(city, api_key):
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
res = requests.get(url)
if res.status_code != 200:
return None
data = res.json()
return data['main']['temp'], data['main']['humidity'], data.get('rain', {}).get('1h', 0)
# -------------------------------
# 🌍 Auto-Detect City from IP
# -------------------------------
def detect_city_from_ip():
try:
response = requests.get("https://ipinfo.io")
if response.status_code == 200:
return response.json().get("city")
except:
return None
# -------------------------------
# πŸ’Š Symptom-Based Disease Checker
# -------------------------------
def diagnose_disease(text):
text = text.lower()
if all(x in text for x in ["yellow", "leaf", "spot"]):
return "Early Blight or Nutrient Deficiency"
elif all(x in text for x in ["brown", "spot"]):
return "Leaf Spot Disease"
elif "white powder" in text:
return "Powdery Mildew"
elif "wilting" in text:
return "Bacterial Wilt"
elif all(x in text for x in ["black", "patch", "stem"]):
return "Stem Rot or Anthracnose"
else:
return "No clear match found"
# -------------------------------
# 🌱 Recommend Crop
# -------------------------------
def recommend_crop(N, P, K, temp, humidity, ph, rainfall):
data = [[N, P, K, temp, humidity, ph, rainfall]]
return model_crop.predict(data)[0]
# -------------------------------
# πŸ’§ Irrigation Suggestion
# -------------------------------
def suggest_irrigation(crop, temp, humidity, rainfall):
crop = crop.lower()
if crop not in crop_water_needs:
return "No irrigation data"
water = crop_water_needs[crop]
if humidity > 80: water *= 0.8
elif humidity < 40: water *= 1.2
net = water - (rainfall / 7)
return f"{round(net, 2)} mm needed" if net > 0 else "No irrigation needed"
# -------------------------------
# πŸ“· Image-Based Disease Detection
# -------------------------------
try:
model_disease = load_model("model_disease.h5")
with open("labels.json", "r") as f:
class_indices = json.load(f)
labels_map = {v: k for k, v in class_indices.items()}
disease_model_loaded = True
except:
disease_model_loaded = False
# -------------------------------
# 🌐 Streamlit App Layout
# -------------------------------
st.set_page_config(page_title="Smart Agriculture System", layout="centered")
st.title("🌿 Smart Agriculture Assistant")
menu = st.sidebar.selectbox("Choose Service", [
"Crop Recommendation",
"Irrigation Advisor",
"Disease Checker (Text)",
"Disease Checker (Image)",
"Weather Status"])
if menu == "Crop Recommendation":
st.subheader("πŸ§ͺ Enter Soil & Weather Data")
N = st.number_input("Nitrogen (N)", 0, 140)
P = st.number_input("Phosphorus (P)", 0, 140)
K = st.number_input("Potassium (K)", 0, 200)
temp = st.number_input("Temperature (Β°C)", 0.0, 60.0)
humidity = st.number_input("Humidity (%)", 0.0, 100.0)
ph = st.number_input("Soil pH", 0.0, 14.0)
rainfall = st.number_input("Rainfall (mm)", 0.0, 300.0)
if st.button("🌱 Recommend Crop"):
crop = recommend_crop(N, P, K, temp, humidity, ph, rainfall)
st.success(f"βœ… Best Crop to Grow: **{crop.upper()}**")
elif menu == "Irrigation Advisor":
st.subheader("πŸ’§ Check Irrigation Need")
crop = st.text_input("Enter Crop Name")
temp = st.number_input("Temperature (Β°C)", 0.0, 60.0)
humidity = st.number_input("Humidity (%)", 0.0, 100.0)
rainfall = st.number_input("Rainfall (mm)", 0.0, 300.0)
if st.button("Suggest Irrigation"):
st.info(suggest_irrigation(crop, temp, humidity, rainfall))
elif menu == "Disease Checker (Text)":
st.subheader("πŸ’Š Describe Plant Symptoms")
user_input = st.text_area("Example: Leaves are yellow and have brown spots")
if st.button("Diagnose Disease"):
st.warning(diagnose_disease(user_input))
elif menu == "Disease Checker (Image)":
st.subheader("πŸ“· Upload Plant Image for Disease Detection")
if not disease_model_loaded:
st.error("❌ Image model not found. Upload 'model_disease.h5' and 'labels.json'")
else:
img_file = st.file_uploader("Choose image", type=["jpg", "png", "jpeg"])
if img_file:
img = image.load_img(img_file, target_size=(128, 128))
img_array = image.img_to_array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
prediction = model_disease.predict(img_array)
predicted_class = labels_map[np.argmax(prediction)]
st.success(f"🦠 Predicted Disease: **{predicted_class}**")
elif menu == "Weather Status":
st.subheader("🌀️ Real-time Weather")
if st.button("πŸ“ Detect My City"):
city = detect_city_from_ip()
if city:
st.success(f"City: {city}")
else:
st.error("❌ Could not detect city")
city = st.text_input("Or Enter City Name")
if st.button("Get Weather"):
API_KEY = "9d3d7ca8fc96b4e392d890de1a4c78b9"
result = get_weather(city, API_KEY)
if result:
temp, humid, rain = result
st.write(f"🌑️ Temperature: {temp} °C")
st.write(f"πŸ’§ Humidity: {humid}%")
st.write(f"🌧️ Rainfall: {rain} mm")
else:
st.error("City not found or API error")