File size: 14,176 Bytes
524df2c 5aba7dd 524df2c 5aba7dd d83dcb2 5aba7dd 06cdcc5 5aba7dd 06cdcc5 5aba7dd 06cdcc5 5aba7dd 06cdcc5 5aba7dd 06cdcc5 5aba7dd 06cdcc5 524df2c 5aba7dd 524df2c d83dcb2 524df2c d83dcb2 524df2c d83dcb2 524df2c d83dcb2 524df2c d83dcb2 524df2c d83dcb2 524df2c d83dcb2 524df2c d83dcb2 524df2c d83dcb2 5aba7dd d83dcb2 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c d83dcb2 524df2c d83dcb2 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd d83dcb2 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c 5aba7dd 524df2c |
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 |
import gradio as gr
import subprocess
import threading
import time
import requests
import json
from datetime import datetime
import os
# Configuration
MCP_SERVER_PORT = 8001
MCP_SERVER_URL = "https://elanuk-mcp-hf.hf.space/"
# Bihar districts list
BIHAR_DISTRICTS = [
"Patna", "Gaya", "Bhagalpur", "Muzaffarpur", "Darbhanga", "Siwan",
"Begusarai", "Katihar", "Nalanda", "Rohtas", "Saran", "Samastipur",
"Madhubani", "Purnia", "Araria", "Kishanganj", "Supaul", "Madhepura",
"Saharsa", "Khagaria", "Munger", "Lakhisarai", "Sheikhpura", "Nawada",
"Jamui", "Jehanabad", "Aurangabad", "Arwal", "Kaimur", "Buxar",
"Bhojpur", "Saran", "Siwan", "Gopalganj", "East Champaran", "West Champaran",
"Sitamarhi", "Sheohar", "Vaishali"
]
def start_mcp_server():
"""Start the MCP server in background"""
try:
print("π Starting MCP Server...")
# Set environment variable for the server port
env = os.environ.copy()
env["PORT"] = str(MCP_SERVER_PORT)
process = subprocess.Popen(
["python", "mcp_server.py"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
text=True
)
# Wait for server to start
print("β³ Waiting for server to start...")
time.sleep(15)
# Check if server is running
try:
response = requests.get(f"{MCP_SERVER_URL}/api/health", timeout=5)
if response.status_code == 200:
print("β
MCP Server started successfully!")
return process
except:
pass
print("β οΈ Server may still be starting...")
return process
except Exception as e:
print(f"β Failed to start MCP server: {e}")
return None
def format_workflow_output(raw_output):
"""Format the workflow output for better display"""
if not raw_output:
return "β No output received"
lines = raw_output.split('\n')
formatted_lines = []
for line in lines:
line = line.strip()
if not line:
formatted_lines.append("")
continue
if line.startswith('πΎ') and 'Workflow' in line:
formatted_lines.append(f"## {line}")
elif line.startswith('=') or line.startswith('-'):
continue
elif line.startswith('π€οΈ') or line.startswith('β
Workflow'):
formatted_lines.append(f"### {line}")
elif line.startswith('π±') or line.startswith('π') or line.startswith('ποΈ') or line.startswith('π€'):
formatted_lines.append(f"#### {line}")
elif line.startswith('β
') or line.startswith('β'):
formatted_lines.append(f"- {line}")
elif line.startswith(' '):
formatted_lines.append(f" {line.strip()}")
else:
formatted_lines.append(line)
return '\n'.join(formatted_lines)
def format_alert_summary(raw_data):
"""Create a formatted summary of the alert data"""
if not raw_data or 'alert_data' not in raw_data:
return "No alert data available"
alert_data = raw_data['alert_data']
summary = f"""
## π¨ Alert Summary
**π Location:** {alert_data['location']['village']}, {alert_data['location']['district']}, {alert_data['location']['state']}
**πΎ Crop Information:**
- **Crop:** {alert_data['crop']['name'].title()}
- **Growth Stage:** {alert_data['crop']['stage']}
- **Season:** {alert_data['crop']['season'].title()}
**π€οΈ Weather Conditions:**
- **Temperature:** {alert_data['weather']['temperature']}
- **Expected Rainfall:** {alert_data['weather']['expected_rainfall']}
- **Wind Speed:** {alert_data['weather']['wind_speed']}
- **Rain Probability:** {alert_data['weather']['rain_probability']}%
**β οΈ Alert Details:**
- **Type:** {alert_data['alert']['type'].replace('_', ' ').title()}
- **Urgency:** {alert_data['alert']['urgency'].upper()}
- **AI Enhanced:** {'β
Yes' if alert_data['alert']['ai_generated'] else 'β No'}
**π¨ Alert Message:**
{alert_data['alert']['message']}
**π― Action Items:**
{chr(10).join([f"- {item.replace('_', ' ').title()}" for item in alert_data['alert']['action_items']])}
"""
return summary
def test_mcp_workflow(district):
"""Test the MCP workflow for a given district"""
if not district:
return "β Please select a district", "", ""
try:
payload = {
"state": "bihar",
"district": district.lower()
}
# First check if server is responding
try:
health_check = requests.get(f"{MCP_SERVER_URL}/", timeout=5)
if health_check.status_code != 200:
return f"β MCP Server not responding properly (status: {health_check.status_code})", "", ""
except:
return "β MCP Server is not running. Please check server status above.", "", ""
# Try the workflow endpoint
response = requests.post(
f"{MCP_SERVER_URL}/api/run-workflow",
json=payload,
timeout=60
)
if response.status_code == 200:
result = response.json()
workflow_output = format_workflow_output(result.get('message', ''))
alert_summary = format_alert_summary(result.get('raw_data', {}))
csv_content = result.get('csv', '')
return workflow_output, alert_summary, csv_content
elif response.status_code == 404:
return "β Workflow endpoint not found. The server may not be fully started or may be missing the workflow functionality.", "", ""
else:
error_msg = f"β Server Error ({response.status_code}): {response.text[:500]}"
return error_msg, "", ""
except requests.exceptions.Timeout:
return "β° Request timed out. The workflow is taking longer than expected...", "", ""
except requests.exceptions.ConnectionError:
return f"π Connection Error: Cannot reach MCP server at {MCP_SERVER_URL}", "", ""
except Exception as e:
return f"β Error: {str(e)}", "", ""
def check_server_health():
"""Check if the MCP server is running"""
try:
# Try the health endpoint first
response = requests.get(f"{MCP_SERVER_URL}/api/health", timeout=10)
if response.status_code == 200:
data = response.json()
return f"β
Server Online | OpenAI: {'β
' if data.get('openai_available') else 'β'} | Time: {data.get('timestamp', 'N/A')}"
elif response.status_code == 404:
# Try the root endpoint as fallback
try:
root_response = requests.get(f"{MCP_SERVER_URL}/", timeout=5)
if root_response.status_code == 200:
root_data = root_response.json()
if "MCP Weather Server" in str(root_data):
return f"β οΈ Server Running (health endpoint missing) | Status: {root_data.get('status', 'unknown')}"
return f"β οΈ Server responded with status {response.status_code} (health endpoint not found)"
except:
return f"β οΈ Server responded with status {response.status_code} (health endpoint not found)"
else:
return f"β οΈ Server responded with status {response.status_code}"
except requests.exceptions.ConnectionError:
return f"β Cannot connect to server at {MCP_SERVER_URL}"
except requests.exceptions.Timeout:
return f"β° Server connection timeout"
except Exception as e:
return f"β Server check failed: {str(e)}"
# Start server in background thread
print("π§ Initializing BIHAR AgMCP...")
server_process = None
def start_server_thread():
global server_process
server_process = start_mcp_server()
server_thread = threading.Thread(target=start_server_thread, daemon=True)
server_thread.start()
# Create Gradio interface
with gr.Blocks(
title="BIHAR AgMCP - Agricultural Weather Alerts",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 1200px;
margin: auto;
}
"""
) as demo:
gr.Markdown("""
# πΎ BIHAR AgMCP - Agricultural Weather Alert System
**AI-Powered Weather Alerts for Bihar Farmers**
This system generates personalized weather alerts for agricultural activities in Bihar districts.
## π How to Use:
1. **Wait for Server**: Ensure server status shows "Online" below
2. **Select District**: Choose a Bihar district from the dropdown
3. **Run Workflow**: Click the button to generate weather alerts
4. **View Results**: See formatted workflow output and alert summary
5. **Download Data**: Get CSV export of the alert data
The system will automatically:
- Select a random village in the district
- Choose appropriate crops based on season and region
- Generate weather-based agricultural alerts
- Create messages for multiple communication channels
""")
# Server status
with gr.Row():
with gr.Column(scale=3):
server_status = gr.Textbox(
label="π§ Server Status",
value="π Starting server...",
interactive=False,
container=True
)
with gr.Column(scale=1):
refresh_btn = gr.Button("π Check Status", size="sm")
debug_btn = gr.Button("π Debug Info", size="sm", variant="secondary")
# Main interface
with gr.Row():
with gr.Column(scale=1):
district_input = gr.Dropdown(
choices=BIHAR_DISTRICTS,
label="π Select Bihar District",
value="Patna",
info="Choose a district to generate weather alerts"
)
run_btn = gr.Button(
"π Generate Weather Alert",
variant="primary",
size="lg"
)
gr.Markdown("""
### π‘ What happens next?
- Weather data collection from multiple sources
- Intelligent crop stage estimation
- AI-powered alert generation
- Multi-channel message creation (SMS, WhatsApp, etc.)
- Comprehensive CSV data export
""")
# Results section
with gr.Row():
with gr.Column(scale=2):
workflow_output = gr.Markdown(
label="π Workflow Output",
value="Server is starting... Please wait and check server status above."
)
with gr.Column(scale=1):
alert_summary = gr.Markdown(
label="π Alert Summary",
value="Alert details will appear here after running workflow..."
)
# CSV export
with gr.Row():
csv_output = gr.File(
label="π Download CSV Data",
visible=False
)
# Event handling
def run_workflow_with_csv(district):
workflow, summary, csv_content = test_mcp_workflow(district)
if csv_content and not csv_content.startswith("Error"):
filename = f"bihar_alert_{district.lower()}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
with open(filename, 'w', encoding='utf-8') as f:
f.write(csv_content)
return workflow, summary, gr.File(value=filename, visible=True)
else:
return workflow, summary, gr.File(visible=False)
# Connect events
refresh_btn.click(check_server_health, outputs=server_status)
def debug_server():
"""Debug server endpoints"""
try:
debug_info = []
# Test root endpoint
try:
root_resp = requests.get(f"{MCP_SERVER_URL}/", timeout=5)
debug_info.append(f"β
Root endpoint: {root_resp.status_code} - {root_resp.text[:100]}")
except Exception as e:
debug_info.append(f"β Root endpoint failed: {str(e)}")
# Test health endpoint
try:
health_resp = requests.get(f"{MCP_SERVER_URL}/api/health", timeout=5)
debug_info.append(f"β
Health endpoint: {health_resp.status_code} - {health_resp.text[:100]}")
except Exception as e:
debug_info.append(f"β Health endpoint failed: {str(e)}")
# List what we're trying to connect to
debug_info.append(f"π Trying to connect to: {MCP_SERVER_URL}")
debug_info.append(f"π³ Container environment: {os.getenv('SPACE_ID', 'Not in HF Spaces')}")
return "π **Debug Information:**\n\n" + "\n".join(debug_info)
except Exception as e:
return f"β Debug failed: {str(e)}"
debug_btn.click(debug_server, outputs=workflow_output)
run_btn.click(
run_workflow_with_csv,
inputs=[district_input],
outputs=[workflow_output, alert_summary, csv_output]
)
# Auto-refresh server status after a delay
def auto_check_status():
time.sleep(20) # Wait 20 seconds
return check_server_health()
demo.load(auto_check_status, outputs=server_status)
# Footer
gr.Markdown("""
---
### π System Information:
- **State Coverage**: Bihar (38+ districts)
- **Crops Supported**: Rice, Wheat, Maize, Sugarcane, Mustard, and more
- **Weather Sources**: Open-Meteo API with AI enhancement
- **Communication Channels**: SMS, WhatsApp, USSD, IVR, Telegram
*Built with MCP (Model Context Protocol) for agricultural intelligence*
""")
# Launch the interface
if __name__ == "__main__":
print("πΎ Launching BIHAR AgMCP Interface...")
demo.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True
) |