Spaces:
Sleeping
Sleeping
| # β 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") | |