Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import requests | |
| import os | |
| import datetime | |
| from openai import OpenAI | |
| # ============================= | |
| # CONFIG | |
| # ============================= | |
| st.set_page_config( | |
| page_title="πΎ Smart Agro AI", | |
| layout="wide", | |
| initial_sidebar_state="collapsed" | |
| ) | |
| # Groq Client | |
| client = OpenAI( | |
| api_key=os.environ.get("GROQ_API_KEY"), | |
| base_url="https://api.groq.com/openai/v1" | |
| ) | |
| # ============================= | |
| # HEADER | |
| # ============================= | |
| st.title("πΎ Smart Agro AI") | |
| st.caption("An intelligent farming system that uses Artificial Intelligence to help farmers make better decisions.") | |
| # ============================= | |
| # MENU | |
| # ============================= | |
| menu = st.radio( | |
| "", | |
| ["π¦ Weather", | |
| "πΎ Crop Estimator", | |
| "π Market & Profit", | |
| "π§ͺ Fertilizer AI", | |
| "π Crop Calendar", | |
| "π€ Smart Advisory", | |
| "π¬ Chatbot"], | |
| horizontal=True | |
| ) | |
| # ============================= | |
| # WEATHER | |
| # ============================= | |
| if menu == "π¦ Weather": | |
| st.subheader("π¦ Live Weather") | |
| city = st.text_input("Enter City Name") | |
| def get_coordinates(city): | |
| geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}" | |
| geo_data = requests.get(geo_url).json() | |
| if "results" in geo_data: | |
| return geo_data["results"][0]["latitude"], geo_data["results"][0]["longitude"] | |
| return None, None | |
| if st.button("Get Weather"): | |
| with st.spinner("Fetching weather..."): | |
| lat, lon = get_coordinates(city) | |
| if lat: | |
| weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true" | |
| data = requests.get(weather_url).json() | |
| temp = data["current_weather"]["temperature"] | |
| wind = data["current_weather"]["windspeed"] | |
| st.success(f"π‘ Temperature in {city}: {temp}Β°C") | |
| st.info(f"π¨ Wind Speed: {wind} km/h") | |
| if wind > 25: | |
| st.warning("π¨ Strong wind detected β avoid spraying.") | |
| elif wind > 15: | |
| st.info("π¨ Moderate wind β safe activities.") | |
| else: | |
| st.success("π¨ Calm wind β ideal conditions.") | |
| else: | |
| st.error("City not found.") | |
| # ============================= | |
| # CROP ESTIMATOR | |
| # ============================= | |
| elif menu == "πΎ Crop Estimator": | |
| st.subheader("πΎ Crop Cost & Yield Estimator") | |
| crops = { | |
| "Wheat": {"cost": 50000, "yield": 30}, | |
| "Rice": {"cost": 60000, "yield": 35}, | |
| "Maize": {"cost": 45000, "yield": 28}, | |
| "Sugarcane": {"cost": 80000, "yield": 60}, | |
| "Cotton": {"cost": 70000, "yield": 25} | |
| } | |
| crop = st.selectbox("Select Crop", list(crops.keys())) | |
| area = st.number_input("Enter land area (acres)", min_value=1) | |
| if st.button("Calculate"): | |
| total_cost = crops[crop]["cost"] * area | |
| total_yield = crops[crop]["yield"] * area | |
| st.success(f"π° Estimated Cost: Rs {total_cost}") | |
| st.info(f"πΎ Expected Yield: {total_yield} maunds") | |
| # ============================= | |
| # MARKET & PROFIT | |
| # ============================= | |
| elif menu == "π Market & Profit": | |
| st.subheader("π Market Price & Profit Predictor") | |
| prices = { | |
| "Wheat": 3900, | |
| "Rice": 4500, | |
| "Maize": 3500, | |
| "Sugarcane": 3000, | |
| "Cotton": 8500 | |
| } | |
| crop = st.selectbox("Select Crop", list(prices.keys())) | |
| area = st.number_input("Enter land area (acres)", min_value=1) | |
| if st.button("Predict Profit"): | |
| avg_yield = 30 | |
| revenue = avg_yield * area * prices[crop] | |
| cost = 50000 * area | |
| profit = revenue - cost | |
| st.success(f"π° Revenue: Rs {revenue}") | |
| st.warning(f"π Cost: Rs {cost}") | |
| st.info(f"π Profit: Rs {profit}") | |
| # ============================= | |
| # FERTILIZER AI | |
| # ============================= | |
| elif menu == "π§ͺ Fertilizer AI": | |
| st.subheader("π§ͺ Smart Fertilizer Recommendation") | |
| crop = st.text_input("Enter crop name") | |
| if st.button("Get Recommendation"): | |
| if crop.lower() == "wheat": | |
| rec = "Use Urea + DAP. Apply Nitrogen in split doses." | |
| elif crop.lower() == "rice": | |
| rec = "Apply NPK 20-20-20 and maintain flooded field." | |
| else: | |
| rec = "Use balanced NPK fertilizer with organic compost." | |
| st.success(rec) | |
| # ============================= | |
| # CROP CALENDAR | |
| # ============================= | |
| # ============================= | |
| # π ADVANCED CROP CALENDAR | |
| # ============================= | |
| elif menu == "π Crop Calendar": | |
| st.subheader("π Seasonal Crop Calendar (Pakistan)") | |
| # Crop Data | |
| crops_data = { | |
| "Wheat": { | |
| "sowing": ["November", "December"], | |
| "harvest": ["April", "May"], | |
| "use": "Staple food crop (flour, roti, bread)" | |
| }, | |
| "Rice": { | |
| "sowing": ["June", "July"], | |
| "harvest": ["October", "November"], | |
| "use": "Staple food crop (boiled rice, export)" | |
| }, | |
| "Maize": { | |
| "sowing": ["February", "March", "July", "August"], | |
| "harvest": ["June", "November"], | |
| "use": "Food, poultry feed, industrial use" | |
| }, | |
| "Cotton": { | |
| "sowing": ["April", "May"], | |
| "harvest": ["September", "October"], | |
| "use": "Textile industry" | |
| }, | |
| "Sugarcane": { | |
| "sowing": ["February", "March", "September", "October"], | |
| "harvest": ["November", "December", "January", "February", "March"], | |
| "use": "Sugar production" | |
| }, | |
| "Mustard": { | |
| "sowing": ["October", "November"], | |
| "harvest": ["February", "March"], | |
| "use": "Cooking oil" | |
| }, | |
| "Gram (Chickpea)": { | |
| "sowing": ["October", "November"], | |
| "harvest": ["March", "April"], | |
| "use": "Pulse / protein food" | |
| }, | |
| "Sunflower": { | |
| "sowing": ["January", "February", "June"], | |
| "harvest": ["May", "June", "October"], | |
| "use": "Cooking oil" | |
| } | |
| } | |
| # User selects month | |
| selected_month = st.selectbox( | |
| "Select Month", | |
| ["January","February","March","April","May","June", | |
| "July","August","September","October","November","December"] | |
| ) | |
| st.info(f"π Selected Month: {selected_month}") | |
| sowing_crops = [] | |
| harvest_crops = [] | |
| for crop, details in crops_data.items(): | |
| if selected_month in details["sowing"]: | |
| sowing_crops.append((crop, details["use"])) | |
| if selected_month in details["harvest"]: | |
| harvest_crops.append((crop, details["use"])) | |
| st.markdown("### π± Crops to Sow") | |
| if sowing_crops: | |
| for crop, use in sowing_crops: | |
| st.success(f"πΎ {crop} β Use: {use}") | |
| else: | |
| st.write("No major sowing crop this month.") | |
| st.markdown("### πΎ Crops to Harvest") | |
| if harvest_crops: | |
| for crop, use in harvest_crops: | |
| st.warning(f"πΎ {crop} β Use: {use}") | |
| else: | |
| st.write("No major harvesting crop this month.") | |
| # ============================= | |
| # SMART ADVISORY | |
| # ============================= | |
| elif menu == "π€ Smart Advisory": | |
| st.subheader("π€ AI Farming Advisory") | |
| advisory_crop = st.text_input("Crop") | |
| advisory_soil = st.selectbox("Soil Type", ["Sandy", "Clay", "Loamy"]) | |
| advisory_season = st.selectbox("Season", ["Summer", "Winter", "Monsoon", "Spring"]) | |
| if st.button("Generate Advisory"): | |
| with st.spinner("Generating..."): | |
| prompt = f""" | |
| You are an expert agricultural advisor. | |
| Crop: {advisory_crop} | |
| Soil: {advisory_soil} | |
| Season: {advisory_season} | |
| Provide fertilizer, irrigation, disease prevention, yield and market advice. | |
| """ | |
| try: | |
| response = client.responses.create( | |
| model="openai/gpt-oss-20b", | |
| input=prompt | |
| ) | |
| st.success("β Advisory Generated") | |
| st.write(response.output_text) | |
| except Exception as e: | |
| st.error(str(e)) | |
| # ============================= | |
| # CHATBOT | |
| # ============================= | |
| elif menu == "π¬ Chatbot": | |
| st.subheader("π¬ Farming Assistant Chatbot") | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| for msg in st.session_state.messages: | |
| st.chat_message(msg["role"]).write(msg["content"]) | |
| if prompt := st.chat_input("Ask farming question..."): | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| st.chat_message("user").write(prompt) | |
| try: | |
| response = client.responses.create( | |
| model="openai/gpt-oss-20b", | |
| input=prompt | |
| ) | |
| reply = response.output_text | |
| except Exception as e: | |
| reply = str(e) | |
| st.session_state.messages.append({"role": "assistant", "content": reply}) | |
| st.chat_message("assistant").write(reply) |