File size: 21,083 Bytes
dcae033
 
 
94f1582
dcae033
94f1582
27ff090
94f1582
 
 
dcae033
94f1582
dcae033
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94f1582
dcae033
 
 
 
 
94f1582
dcae033
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94f1582
 
 
 
 
 
 
 
 
 
73aff18
94f1582
 
 
 
73aff18
 
 
dcae033
94f1582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcae033
94f1582
 
 
dcae033
 
94f1582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcae033
 
94f1582
 
dcae033
 
 
 
 
94f1582
dcae033
 
 
 
94f1582
 
 
dcae033
 
94f1582
dcae033
94f1582
 
dcae033
94f1582
 
dcae033
94f1582
 
 
dcae033
 
 
 
94f1582
dcae033
 
94f1582
dcae033
 
 
 
 
 
 
 
94f1582
 
 
 
 
 
 
 
 
dcae033
 
94f1582
dcae033
 
 
 
 
 
 
94f1582
dcae033
 
 
 
 
 
 
94f1582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcae033
 
 
 
 
 
 
94f1582
dcae033
94f1582
dcae033
 
94f1582
dcae033
 
94f1582
dcae033
94f1582
dcae033
94f1582
dcae033
 
94f1582
dcae033
 
 
94f1582
dcae033
 
 
 
 
 
 
 
94f1582
 
 
 
dcae033
94f1582
dcae033
94f1582
dcae033
 
 
94f1582
 
 
 
 
 
 
 
dcae033
 
94f1582
dcae033
94f1582
dcae033
94f1582
 
 
 
 
 
 
dcae033
94f1582
 
 
 
 
 
 
 
 
 
 
 
 
 
dcae033
 
94f1582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcae033
94f1582
 
 
 
 
 
 
 
 
 
 
 
dcae033
94f1582
 
 
dcae033
94f1582
 
 
 
dcae033
 
 
 
94f1582
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
import os
import gradio as gr
import requests
import openai

# πŸ” Load API keys from environment variables (set these in Hugging Face Secrets)
weather_api_key = os.getenv("openweather")
groq_api_key = os.getenv("GROQ_API_KEY")
openai.api_key = os.getenv("OPENAI_API_KEY")
serper_api_key = os.getenv("SERPER_API_KEY")

# 🌀️ Weather Fetch
def get_weather(city_name):
    if not city_name.strip():
        city_name = "Dubai"
    try:
        url = f"https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={weather_api_key}&units=metric"
        data = requests.get(url).json()

        if data["cod"] == 200:
            rain = data.get("rain", {}).get("1h", 0)
            condition = data["weather"][0]["main"]
            emoji_map = {
                "Clear": "β˜€οΈ", "Clouds": "☁️", "Rain": "🌧️",
                "Snow": "❄️", "Thunderstorm": "β›ˆοΈ", "Drizzle": "🌦️",
                "Mist": "🌫️", "Haze": "🌁", "Fog": "🌫️"
            }
            emoji = emoji_map.get(condition, "🌈")

            return {
                "city": data["name"],
                "country": data["sys"]["country"],
                "temperature": int(data["main"]["temp"]),
                "feels_like": int(data["main"]["feels_like"]),
                "humidity": data["main"]["humidity"],
                "pressure": data["main"]["pressure"],
                "description": f"{data['weather'][0]['description'].title()} {emoji}",
                "wind_speed": data["wind"]["speed"],
                "visibility": data.get("visibility", 10000) // 1000,
                "rain_chance": f"{rain} mm"
            }
        else:
            return None
    except:
        return None

# πŸ–ΌοΈ Format Weather Display
def format_weather_display(data):
    if not data:
        return "<div style='text-align:center; color: #e74c3c; font-size: 18px; padding: 40px;'>❌ City not found. Please try again.</div>"

    font_color = "#2d3436"
    card_bg = "#e8f5e9"
    main_bg = "#ffffff"

    return f"""
    <div style="background: {main_bg}; border-radius: 16px; padding: 25px; box-shadow: 0 10px 30px rgba(0,0,0,0.1);">
        <div style="text-align: center; margin-bottom: 25px;">
            <h2 style="margin: 0; color: {font_color}; font-size: 24px; font-weight: 600;">πŸ“ {data['city']}, {data['country']}</h2>
            <h1 style="margin: 10px 0; font-size: 64px; color: {font_color}; font-weight: 300;">{data['temperature']}Β°C</h1>
            <p style="margin: 5px 0; color: {font_color}; font-size: 18px; font-weight: 500;">{data['description']}</p>
        </div>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-top: 25px;">
            <div style="background: {card_bg}; border-radius: 12px; padding: 16px; text-align: center; color: {font_color};">
                <div style="font-size: 24px; margin-bottom: 8px;">πŸ’§</div>
                <strong style="font-size: 16px; display: block;">{data['rain_chance']}</strong>
                <span style="font-size: 12px; opacity: 0.8;">Precipitation</span>
            </div>
            <div style="background: {card_bg}; border-radius: 12px; padding: 16px; text-align: center; color: {font_color};">
                <div style="font-size: 24px; margin-bottom: 8px;">πŸ“Š</div>
                <strong style="font-size: 16px; display: block;">{data['pressure']} mb</strong>
                <span style="font-size: 12px; opacity: 0.8;">Pressure</span>
            </div>
            <div style="background: {card_bg}; border-radius: 12px; padding: 16px; text-align: center; color: {font_color};">
                <div style="font-size: 24px; margin-bottom: 8px;">πŸ’¨</div>
                <strong style="font-size: 16px; display: block;">{data['wind_speed']} km/h</strong>
                <span style="font-size: 12px; opacity: 0.8;">Wind Speed</span>
            </div>
            <div style="background: {card_bg}; border-radius: 12px; padding: 16px; text-align: center; color: {font_color};">
                <div style="font-size: 24px; margin-bottom: 8px;">🌑️</div>
                <strong style="font-size: 16px; display: block;">{data['feels_like']}Β°C</strong>
                <span style="font-size: 12px; opacity: 0.8;">Feels Like</span>
            </div>
            <div style="background: {card_bg}; border-radius: 12px; padding: 16px; text-align: center; color: {font_color};">
                <div style="font-size: 24px; margin-bottom: 8px;">πŸ‘οΈ</div>
                <strong style="font-size: 16px; display: block;">{data['visibility']} km</strong>
                <span style="font-size: 12px; opacity: 0.8;">Visibility</span>
            </div>
            <div style="background: {card_bg}; border-radius: 12px; padding: 16px; text-align: center; color: {font_color};">
                <div style="font-size: 24px; margin-bottom: 8px;">πŸ’¦</div>
                <strong style="font-size: 16px; display: block;">{data['humidity']}%</strong>
                <span style="font-size: 12px; opacity: 0.8;">Humidity</span>
            </div>
        </div>
    </div>
    """

# 🌾 Farming Assistant Chatbot (Groq API)
def agri_chat(msg, history):
    prompt = f"You're a smart farming assistant. Help the farmer clearly and briefly.\nUser: {msg}\nAssistant:"
    url = "https://api.groq.com/openai/v1/chat/completions"
    headers = {"Authorization": f"Bearer {groq_api_key}", "Content-Type": "application/json"}
    body = {
        "model": "llama3-8b-8192",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7
    }
    try:
        res = requests.post(url, headers=headers, json=body).json()
        reply = res["choices"][0]["message"]["content"]
    except:
        reply = "⚠️ Unable to get response. Try again."
    history.append({"role": "user", "content": msg})
    history.append({"role": "assistant", "content": reply})
    return history, history

# 🌱 Crop Search (OpenAI)
def search_crop(crop_name):
    try:
        messages = [
            {
                "role": "system",
                "content": (
                    "You are an expert agronomist. When asked about a crop, provide the following in well-structured HTML:\n\n"
                    "1. A short paragraph (3–5 sentences) about the crop, including where it's commonly grown and its basic growing needs.\n"
                    "2. A bullet list of 3–5 benefits of growing or consuming the crop.\n"
                    "3. A numbered list (5–7 steps) explaining how to grow this crop from seed to harvest.\n\n"
                    "Use proper HTML structure with <h3>, <p>, <ul>, <ol>, <li> tags."
                )
            },
            {
                "role": "user",
                "content": f"Tell me about {crop_name}. Include a short paragraph, key benefits, and growing steps."
            }
        ]

        response = openai.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages
        )

        return response.choices[0].message.content.strip()

    except Exception as e:
        return f"<div style='color:red;'>⚠️ Error fetching crop info: {str(e)}</div>"


# 🌱 Fetch best crops based on region using OpenAI
def get_best_crops_for_region(city, country, temp, humidity, description):
    try:
        messages = [
            {
                "role": "system",
                "content": (
                    "You are an expert agronomist. Based on the region, temperature, humidity, and weather condition, "
                    "suggest 6 to 9 crops that grow best in this region. Return each crop as a Python tuple like:\n"
                    "(\"Tomato\", \"Needs warm weather, full sun, and well-drained soil.\")"
                )
            },
            {
                "role": "user",
                "content": (
                    f"Suggest best crops for {city}, {country} where the average temperature is {temp}Β°C, "
                    f"humidity is {humidity}%, and the weather condition is '{description.lower()}'. "
                    "Output the results as Python tuples."
                )
            }
        ]

        response = openai.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages
        )

        content = response.choices[0].message.content.strip()

        crops = []
        for line in content.split('\n'):
            line = line.strip().rstrip(',')
            if line.startswith('(') and line.endswith(')'):
                try:
                    crop_tuple = eval(line)
                    if isinstance(crop_tuple, tuple) and len(crop_tuple) == 2:
                        crops.append(crop_tuple)
                except:
                    continue
        return crops if crops else [("⚠️ No Crops Found", "Try a different city or adjust your weather input.")]

    except Exception as e:
        return [("⚠️ Error", f"Could not fetch crops: {str(e)}")]

# 🎨 Format each crop card for the grid layout
def format_crop_card(name, details):
    return f"""
    <div class='crop-card'>
        <div class='crop-name'>{name.title()}</div>
        <div class='crop-description'>{details}</div>
    </div>
    """


# Launch UI with layout from old code + crop cards and search
custom_css = """
body, .gradio-container {
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%) !important;
    font-family: 'Segoe UI', 'Roboto', sans-serif;
    min-height: 100vh;
}
#main-title {
    text-align: center;
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 10px;
    color: #2e7d32;
    text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}
#subtitle {
    text-align: center;
    font-size: 1.1rem;
    color: #666;
    margin-bottom: 30px;
    font-weight: 400;
}
.section-header {
    background: linear-gradient(135deg, #43a047 0%, #388e3c 100%);
    color: white;
    padding: 12px 20px;
    border-radius: 12px 12px 0 0;
    margin: 0;
    font-size: 1.2rem;
    font-weight: 600;
    text-align: center;
    box-shadow: 0 4px 15px rgba(67, 160, 71, 0.3);
}
.content-box {
    background-color: #ffffff;
    border-radius: 0 0 16px 16px;
    padding: 25px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    min-height: 520px;
    border-top: 3px solid #43a047;
}
.weather-controls {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    border: 1px solid #e9ecef;
}
.footer {
    background: linear-gradient(135deg, #2e7d32 0%, #1b5e20 100%);
    color: white;
    padding: 30px;
    border-radius: 16px;
    margin-top: 30px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}
.footer h3 {
    margin: 0 0 15px 0;
    font-size: 1.3rem;
    font-weight: 600;
    color: #ffffff;
}
.footer-content {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 25px;
    margin-bottom: 20px;
}
.footer-section {
    background: rgba(255, 255, 255, 0.1);
    padding: 20px;
    border-radius: 12px;
    backdrop-filter: blur(10px);
}
.footer-section h4 {
    margin: 0 0 10px 0;
    color: #a8e6cf;
    font-size: 1.1rem;
}
.footer-section ul {
    list-style: none;
    padding: 0;
    margin: 0;
}
.footer-section li {
    margin: 8px 0;
    padding-left: 20px;
    position: relative;
}
.footer-section li:before {
    content: "βœ“";
    position: absolute;
    left: 0;
    color: #a8e6cf;
    font-weight: bold;
}
button {
    background: linear-gradient(135deg, #43a047 0%, #388e3c 100%) !important;
    color: white !important;
    border-radius: 10px !important;
    border: none !important;
    padding: 12px 24px !important;
    font-weight: 600 !important;
    transition: all 0.3s ease !important;
    box-shadow: 0 4px 15px rgba(67, 160, 71, 0.3) !important;
}
button:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 6px 20px rgba(67, 160, 71, 0.4) !important;
}
.gradio-textbox input {
    border-radius: 10px !important;
    border: 2px solid #e9ecef !important;
    padding: 12px 16px !important;
    font-size: 16px !important;
    transition: all 0.3s ease !important;
}
.gradio-textbox input:focus {
    border-color: #43a047 !important;
    box-shadow: 0 0 0 3px rgba(67, 160, 71, 0.1) !important;
}
.card-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 18px;
    margin-top: 25px;
}
.crop-card {
    background: #ffffff;
    border: 1px solid #c8e6c9;
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(67, 160, 71, 0.1);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.crop-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 20px rgba(67, 160, 71, 0.2);
}
.crop-name {
    font-size: 20px;
    font-weight: 600;
    color: #2e7d32;
    margin-bottom: 12px;
    text-align: center;
}
.crop-description {
    font-size: 15px;
    color: #444;
    line-height: 1.5;
    text-align: center;
}
"""

def launch_ui():
    with gr.Blocks(css=custom_css, title="Shafaq's AgriWeather") as demo:
        # Header Section
        gr.Markdown("<div id='main-title'>🌿 Shafaq's AgriWeather Hub</div>")
        gr.Markdown("<div id='subtitle'>Real-time Weather Data & Smart Farming Assistant</div>")

        # Main Content
        with gr.Row(equal_height=True):
            # Weather Section
            with gr.Column(scale=1):
                gr.Markdown("<div class='section-header'>🌀️ Weather Dashboard</div>")
                with gr.Group(elem_classes="content-box"):
                    with gr.Group(elem_classes="weather-controls"):
                        city_input = gr.Textbox(
                            label="πŸ™οΈ City Name",
                            value="Dubai",
                            placeholder="Enter city name (e.g., Dubai, London, Tokyo)",
                            info="Get real-time weather data for any city worldwide"
                        )
                        update_btn = gr.Button("πŸ“ Get Weather Data", variant="primary")
                    weather_html = gr.HTML()

            # Chat Section
            with gr.Column(scale=1):
                gr.Markdown("<div class='section-header'>🌾 AgriBot Assistant</div>")
                with gr.Group(elem_classes="content-box"):
                    chat = gr.Chatbot(
                        height=350,
                        type="messages",
                        show_label=False,
                        bubble_full_width=False,
                        avatar_images=("πŸ‘¨β€πŸŒΎ", "πŸ€–")
                    )
                    with gr.Row():
                        message = gr.Textbox(
                            placeholder="Ask about crops, weather impact, farming tips...",
                            show_label=False,
                            scale=4
                        )
                        ask_btn = gr.Button("Send", variant="primary", scale=1)
                    # Quick suggestions
                    gr.Markdown("""
                    **πŸ’‘ Quick Questions:**
                    - "What crops grow best in hot weather?"
                    - "How does humidity affect plant growth?"
                    - "Best irrigation practices for dry season?"
                    """)

                    state = gr.State([])

        # --- Dynamic Crop Cards Section ---
        gr.Markdown("<div class='section-header'>🌿 Crops That Grow Best in Your Region</div>")
        crop_cards_html = gr.HTML()

        def generate_crop_cards(city):
            weather = get_weather(city)
            if not weather:
                return "<div style='padding:20px; color:red;'>⚠️ Couldn't fetch crops due to missing weather data.</div>"

            crops = get_best_crops_for_region(
                city=weather["city"],
                country=weather["country"],
                temp=weather["temperature"],
                humidity=weather["humidity"],
                description=weather["description"]
            )
            return "<div class='card-grid'>" + "".join(format_crop_card(name, details) for name, details in crops) + "</div>"


        # --- Crop search section ---
        gr.Markdown("<div class='section-header'>πŸ”Ž Search for Crop Growing Conditions</div>")
        with gr.Group(elem_classes="content-box"):
            with gr.Row():
                crop_search_input = gr.Textbox(
                    placeholder="Type a crop name (e.g., Tomato, Wheat)...",
                    show_label=False,
                    scale=5
                )
                crop_search_btn = gr.Button("πŸ” Search", variant="primary", scale=1)
            crop_search_output = gr.HTML()


        # --- Coming Soon Plant Doc Feature Section ---
        gr.Markdown("<div class='section-header'>🌿 Coming Soon: Plant Doctor Feature</div>")
        with gr.Group(elem_classes="content-box"):
            gr.HTML("""
                <div style="text-align: center; padding: 50px; color: #555; font-size: 1.2rem;">
                    <h3>Future Feature: Diagnose Plant Diseases!</h3>
                    <p>Upload an image of your plant, and our AI-powered Plant Doctor will identify potential diseases and suggest treatments. Stay tuned!</p>
                    <div style="margin-top: 30px;">
                        <span style="font-size: 60px;">🌱</span>
                        <span style="font-size: 60px; margin-left: 20px;">πŸ”¬</span>
                        <span style="font-size: 60px; margin-left: 20px;">πŸ’‘</span>
                    </div>
                </div>
            """)

        
        # Footer Section (fixed)
        gr.HTML("""
        <div class='footer'>
            <h3>🌱 About Shafaq's AgriWeather Hub</h3>
            <div class='footer-content'>
                <div class='footer-section'>
                    <h4>🌀️ Weather Features</h4>
                    <ul>
                        <li>Real-time weather updates for any city</li>
                        <li>Detailed forecasts: temperature, wind, humidity, etc.</li>
                        <li>Smart visual indicators with icons</li>
                        <li>Location-based crop recommendations</li>
                    </ul>
                </div>
                <div class='footer-section'>
                    <h4>πŸ€– AgriBot Capabilities</h4>
                    <ul>
                        <li>Ask farming-related questions interactively</li>
                        <li>Get irrigation, soil & seasonal guidance</li>
                        <li>Pest, disease & crop management tips</li>
                        <li>Uses advanced AI (Groq + OpenAI)</li>
                    </ul>
                </div>
                <div class='footer-section'>
                    <h4>πŸ”Ž Crop Search Intelligence</h4>
                    <ul>
                        <li>Search growing conditions for any crop</li>
                        <li>Uses trusted sources via Serper API</li>
                        <li>Clean layout with links to learn more</li>
                        <li>Get contextual crop care information</li>
                    </ul>
                </div>
                <div class='footer-section'>
                    <h4>πŸš€ Quick Usage Tips</h4>
                    <ul>
                        <li>Start by entering a city to get crop advice</li>
                        <li>Ask specific crop or weather questions</li>
                        <li>Use the crop search for deeper research</li>
                        <li>Combine data for informed decisions</li>
                    </ul>
                </div>
            </div>
            <div style='text-align: center; margin-top: 20px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.2); color: rgba(255,255,255,0.85); font-size: 14px;'>
                <p>πŸ’š Built by Shafaq Mandha | Powered by OpenWeather, Groq, OpenAI, and Serper APIs | All rights reserved Β© 2025</p>
            </div>
        </div>
        """)


        # Event bindings
        update_btn.click(
            fn=lambda city: (format_weather_display(get_weather(city)), generate_crop_cards(city)),
            inputs=city_input,
            outputs=[weather_html, crop_cards_html]
        )

        city_input.submit(
            fn=lambda city: (format_weather_display(get_weather(city)), generate_crop_cards(city)),
            inputs=city_input,
            outputs=[weather_html, crop_cards_html]
        )

        ask_btn.click(fn=agri_chat, inputs=[message, state], outputs=[chat, state])
        message.submit(fn=agri_chat, inputs=[message, state], outputs=[chat, state])
        crop_search_btn.click(fn=search_crop, inputs=crop_search_input, outputs=crop_search_output)

        # Load initial weather on launch
        demo.load(fn=lambda: (format_weather_display(get_weather("Dubai")), generate_crop_cards("Dubai")),
                  inputs=None,
                  outputs=[weather_html, crop_cards_html])


    demo.launch()

launch_ui()