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)