Smart_Agro_AI / src /streamlit_app.py
BasitAliii's picture
Create src/streamlit_app.py
ff4b124 verified
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}&current_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)