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}&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)