Spaces:
Sleeping
Sleeping
File size: 9,267 Bytes
ff4b124 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | 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) |