BasitAliii commited on
Commit
ff4b124
Β·
verified Β·
1 Parent(s): 3aeb9d1

Create src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +299 -0
src/streamlit_app.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import os
4
+ import datetime
5
+ from openai import OpenAI
6
+
7
+ # =============================
8
+ # CONFIG
9
+ # =============================
10
+ st.set_page_config(
11
+ page_title="🌾 Smart Agro AI",
12
+ layout="wide",
13
+ initial_sidebar_state="collapsed"
14
+ )
15
+
16
+ # Groq Client
17
+ client = OpenAI(
18
+ api_key=os.environ.get("GROQ_API_KEY"),
19
+ base_url="https://api.groq.com/openai/v1"
20
+ )
21
+
22
+ # =============================
23
+ # HEADER
24
+ # =============================
25
+ st.title("🌾 Smart Agro AI")
26
+ st.caption("An intelligent farming system that uses Artificial Intelligence to help farmers make better decisions.")
27
+
28
+ # =============================
29
+ # MENU
30
+ # =============================
31
+ menu = st.radio(
32
+ "",
33
+ ["🌦 Weather",
34
+ "🌾 Crop Estimator",
35
+ "πŸ“ˆ Market & Profit",
36
+ "πŸ§ͺ Fertilizer AI",
37
+ "πŸ“… Crop Calendar",
38
+ "πŸ€– Smart Advisory",
39
+ "πŸ’¬ Chatbot"],
40
+ horizontal=True
41
+ )
42
+
43
+ # =============================
44
+ # WEATHER
45
+ # =============================
46
+ if menu == "🌦 Weather":
47
+
48
+ st.subheader("🌦 Live Weather")
49
+ city = st.text_input("Enter City Name")
50
+
51
+ def get_coordinates(city):
52
+ geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}"
53
+ geo_data = requests.get(geo_url).json()
54
+
55
+ if "results" in geo_data:
56
+ return geo_data["results"][0]["latitude"], geo_data["results"][0]["longitude"]
57
+ return None, None
58
+
59
+ if st.button("Get Weather"):
60
+ with st.spinner("Fetching weather..."):
61
+ lat, lon = get_coordinates(city)
62
+
63
+ if lat:
64
+ weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current_weather=true"
65
+ data = requests.get(weather_url).json()
66
+
67
+ temp = data["current_weather"]["temperature"]
68
+ wind = data["current_weather"]["windspeed"]
69
+
70
+ st.success(f"🌑 Temperature in {city}: {temp}°C")
71
+ st.info(f"πŸ’¨ Wind Speed: {wind} km/h")
72
+
73
+ if wind > 25:
74
+ st.warning("πŸ’¨ Strong wind detected β€” avoid spraying.")
75
+ elif wind > 15:
76
+ st.info("πŸ’¨ Moderate wind β€” safe activities.")
77
+ else:
78
+ st.success("πŸ’¨ Calm wind β€” ideal conditions.")
79
+ else:
80
+ st.error("City not found.")
81
+
82
+ # =============================
83
+ # CROP ESTIMATOR
84
+ # =============================
85
+ elif menu == "🌾 Crop Estimator":
86
+
87
+ st.subheader("🌾 Crop Cost & Yield Estimator")
88
+
89
+ crops = {
90
+ "Wheat": {"cost": 50000, "yield": 30},
91
+ "Rice": {"cost": 60000, "yield": 35},
92
+ "Maize": {"cost": 45000, "yield": 28},
93
+ "Sugarcane": {"cost": 80000, "yield": 60},
94
+ "Cotton": {"cost": 70000, "yield": 25}
95
+ }
96
+
97
+ crop = st.selectbox("Select Crop", list(crops.keys()))
98
+ area = st.number_input("Enter land area (acres)", min_value=1)
99
+
100
+ if st.button("Calculate"):
101
+ total_cost = crops[crop]["cost"] * area
102
+ total_yield = crops[crop]["yield"] * area
103
+
104
+ st.success(f"πŸ’° Estimated Cost: Rs {total_cost}")
105
+ st.info(f"🌾 Expected Yield: {total_yield} maunds")
106
+
107
+ # =============================
108
+ # MARKET & PROFIT
109
+ # =============================
110
+ elif menu == "πŸ“ˆ Market & Profit":
111
+
112
+ st.subheader("πŸ“ˆ Market Price & Profit Predictor")
113
+
114
+ prices = {
115
+ "Wheat": 3900,
116
+ "Rice": 4500,
117
+ "Maize": 3500,
118
+ "Sugarcane": 3000,
119
+ "Cotton": 8500
120
+ }
121
+
122
+ crop = st.selectbox("Select Crop", list(prices.keys()))
123
+ area = st.number_input("Enter land area (acres)", min_value=1)
124
+
125
+ if st.button("Predict Profit"):
126
+ avg_yield = 30
127
+ revenue = avg_yield * area * prices[crop]
128
+ cost = 50000 * area
129
+ profit = revenue - cost
130
+
131
+ st.success(f"πŸ’° Revenue: Rs {revenue}")
132
+ st.warning(f"πŸ“‰ Cost: Rs {cost}")
133
+ st.info(f"πŸ† Profit: Rs {profit}")
134
+
135
+ # =============================
136
+ # FERTILIZER AI
137
+ # =============================
138
+ elif menu == "πŸ§ͺ Fertilizer AI":
139
+
140
+ st.subheader("πŸ§ͺ Smart Fertilizer Recommendation")
141
+
142
+ crop = st.text_input("Enter crop name")
143
+
144
+ if st.button("Get Recommendation"):
145
+ if crop.lower() == "wheat":
146
+ rec = "Use Urea + DAP. Apply Nitrogen in split doses."
147
+ elif crop.lower() == "rice":
148
+ rec = "Apply NPK 20-20-20 and maintain flooded field."
149
+ else:
150
+ rec = "Use balanced NPK fertilizer with organic compost."
151
+
152
+ st.success(rec)
153
+
154
+ # =============================
155
+ # CROP CALENDAR
156
+ # =============================
157
+ # =============================
158
+ # πŸ“… ADVANCED CROP CALENDAR
159
+ # =============================
160
+ elif menu == "πŸ“… Crop Calendar":
161
+
162
+ st.subheader("πŸ“… Seasonal Crop Calendar (Pakistan)")
163
+
164
+ # Crop Data
165
+ crops_data = {
166
+ "Wheat": {
167
+ "sowing": ["November", "December"],
168
+ "harvest": ["April", "May"],
169
+ "use": "Staple food crop (flour, roti, bread)"
170
+ },
171
+ "Rice": {
172
+ "sowing": ["June", "July"],
173
+ "harvest": ["October", "November"],
174
+ "use": "Staple food crop (boiled rice, export)"
175
+ },
176
+ "Maize": {
177
+ "sowing": ["February", "March", "July", "August"],
178
+ "harvest": ["June", "November"],
179
+ "use": "Food, poultry feed, industrial use"
180
+ },
181
+ "Cotton": {
182
+ "sowing": ["April", "May"],
183
+ "harvest": ["September", "October"],
184
+ "use": "Textile industry"
185
+ },
186
+ "Sugarcane": {
187
+ "sowing": ["February", "March", "September", "October"],
188
+ "harvest": ["November", "December", "January", "February", "March"],
189
+ "use": "Sugar production"
190
+ },
191
+ "Mustard": {
192
+ "sowing": ["October", "November"],
193
+ "harvest": ["February", "March"],
194
+ "use": "Cooking oil"
195
+ },
196
+ "Gram (Chickpea)": {
197
+ "sowing": ["October", "November"],
198
+ "harvest": ["March", "April"],
199
+ "use": "Pulse / protein food"
200
+ },
201
+ "Sunflower": {
202
+ "sowing": ["January", "February", "June"],
203
+ "harvest": ["May", "June", "October"],
204
+ "use": "Cooking oil"
205
+ }
206
+ }
207
+
208
+ # User selects month
209
+ selected_month = st.selectbox(
210
+ "Select Month",
211
+ ["January","February","March","April","May","June",
212
+ "July","August","September","October","November","December"]
213
+ )
214
+
215
+ st.info(f"πŸ“† Selected Month: {selected_month}")
216
+
217
+ sowing_crops = []
218
+ harvest_crops = []
219
+
220
+ for crop, details in crops_data.items():
221
+ if selected_month in details["sowing"]:
222
+ sowing_crops.append((crop, details["use"]))
223
+ if selected_month in details["harvest"]:
224
+ harvest_crops.append((crop, details["use"]))
225
+
226
+ st.markdown("### 🌱 Crops to Sow")
227
+
228
+ if sowing_crops:
229
+ for crop, use in sowing_crops:
230
+ st.success(f"🌾 {crop} β€” Use: {use}")
231
+ else:
232
+ st.write("No major sowing crop this month.")
233
+
234
+ st.markdown("### 🌾 Crops to Harvest")
235
+
236
+ if harvest_crops:
237
+ for crop, use in harvest_crops:
238
+ st.warning(f"🌾 {crop} β€” Use: {use}")
239
+ else:
240
+ st.write("No major harvesting crop this month.")
241
+ # =============================
242
+ # SMART ADVISORY
243
+ # =============================
244
+ elif menu == "πŸ€– Smart Advisory":
245
+
246
+ st.subheader("πŸ€– AI Farming Advisory")
247
+
248
+ advisory_crop = st.text_input("Crop")
249
+ advisory_soil = st.selectbox("Soil Type", ["Sandy", "Clay", "Loamy"])
250
+ advisory_season = st.selectbox("Season", ["Summer", "Winter", "Monsoon", "Spring"])
251
+
252
+ if st.button("Generate Advisory"):
253
+ with st.spinner("Generating..."):
254
+ prompt = f"""
255
+ You are an expert agricultural advisor.
256
+ Crop: {advisory_crop}
257
+ Soil: {advisory_soil}
258
+ Season: {advisory_season}
259
+ Provide fertilizer, irrigation, disease prevention, yield and market advice.
260
+ """
261
+
262
+ try:
263
+ response = client.responses.create(
264
+ model="openai/gpt-oss-20b",
265
+ input=prompt
266
+ )
267
+ st.success("βœ… Advisory Generated")
268
+ st.write(response.output_text)
269
+ except Exception as e:
270
+ st.error(str(e))
271
+
272
+ # =============================
273
+ # CHATBOT
274
+ # =============================
275
+ elif menu == "πŸ’¬ Chatbot":
276
+
277
+ st.subheader("πŸ’¬ Farming Assistant Chatbot")
278
+
279
+ if "messages" not in st.session_state:
280
+ st.session_state.messages = []
281
+
282
+ for msg in st.session_state.messages:
283
+ st.chat_message(msg["role"]).write(msg["content"])
284
+
285
+ if prompt := st.chat_input("Ask farming question..."):
286
+ st.session_state.messages.append({"role": "user", "content": prompt})
287
+ st.chat_message("user").write(prompt)
288
+
289
+ try:
290
+ response = client.responses.create(
291
+ model="openai/gpt-oss-20b",
292
+ input=prompt
293
+ )
294
+ reply = response.output_text
295
+ except Exception as e:
296
+ reply = str(e)
297
+
298
+ st.session_state.messages.append({"role": "assistant", "content": reply})
299
+ st.chat_message("assistant").write(reply)