AgriWeather_Hub / app.py
Shafaq25's picture
Update app.py
94f1582 verified
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()