elanuk commited on
Commit
5aba7dd
Β·
verified Β·
1 Parent(s): f036d24

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -77
app.py CHANGED
@@ -1,56 +1,67 @@
1
  import gradio as gr
 
 
 
2
  import requests
3
  import json
4
  from datetime import datetime
5
  import os
6
- import subprocess
7
- import threading
8
- import time
9
 
10
- # Configuration - for HuggingFace Spaces
11
- MCP_SERVER_URL = "https://elanuk-mcp-hf.hf.space/" # Local server URL
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  def start_mcp_server():
14
  """Start the MCP server in background"""
15
  try:
16
- # Start mcp_server.py as subprocess
 
 
 
 
17
  process = subprocess.Popen(
18
  ["python", "mcp_server.py"],
19
  stdout=subprocess.PIPE,
20
- stderr=subprocess.PIPE
 
 
21
  )
22
 
23
- # Wait a bit for server to start
24
- time.sleep(10)
 
 
 
 
 
 
 
 
 
 
 
 
25
  return process
 
26
  except Exception as e:
27
- print(f"Failed to start MCP server: {e}")
28
  return None
29
 
30
- # Start server in background thread
31
- def start_server_thread():
32
- start_mcp_server()
33
-
34
- server_thread = threading.Thread(target=start_server_thread, daemon=True)
35
- server_thread.start()
36
-
37
- # Bihar districts list
38
- BIHAR_DISTRICTS = [
39
- "Patna", "Gaya", "Bhagalpur", "Muzaffarpur", "Darbhanga", "Siwan",
40
- "Begusarai", "Katihar", "Nalanda", "Rohtas", "Saran", "Samastipur",
41
- "Madhubani", "Purnia", "Araria", "Kishanganj", "Supaul", "Madhepura",
42
- "Saharsa", "Khagaria", "Munger", "Lakhisarai", "Sheikhpura", "Nawada",
43
- "Jamui", "Jehanabad", "Aurangabad", "Arwal", "Kaimur", "Buxar",
44
- "Bhojpur", "Saran", "Siwan", "Gopalganj", "East Champaran", "West Champaran",
45
- "Sitamarhi", "Sheohar", "Vaishali"
46
- ]
47
-
48
  def format_workflow_output(raw_output):
49
  """Format the workflow output for better display"""
50
  if not raw_output:
51
  return "❌ No output received"
52
 
53
- # Split into lines and format
54
  lines = raw_output.split('\n')
55
  formatted_lines = []
56
 
@@ -60,11 +71,10 @@ def format_workflow_output(raw_output):
60
  formatted_lines.append("")
61
  continue
62
 
63
- # Format headers
64
  if line.startswith('🌾') and 'Workflow' in line:
65
  formatted_lines.append(f"## {line}")
66
  elif line.startswith('=') or line.startswith('-'):
67
- continue # Skip separator lines
68
  elif line.startswith('🌀️') or line.startswith('βœ… Workflow'):
69
  formatted_lines.append(f"### {line}")
70
  elif line.startswith('πŸ“±') or line.startswith('πŸ“ž') or line.startswith('πŸŽ™οΈ') or line.startswith('πŸ€–'):
@@ -120,7 +130,6 @@ def test_mcp_workflow(district):
120
  return "❌ Please select a district", "", ""
121
 
122
  try:
123
- # Make request to MCP server
124
  payload = {
125
  "state": "bihar",
126
  "district": district.lower()
@@ -129,17 +138,14 @@ def test_mcp_workflow(district):
129
  response = requests.post(
130
  f"{MCP_SERVER_URL}/api/run-workflow",
131
  json=payload,
132
- timeout=30
133
  )
134
 
135
  if response.status_code == 200:
136
  result = response.json()
137
 
138
- # Format outputs
139
  workflow_output = format_workflow_output(result.get('message', ''))
140
  alert_summary = format_alert_summary(result.get('raw_data', {}))
141
-
142
- # Create CSV download content
143
  csv_content = result.get('csv', '')
144
 
145
  return workflow_output, alert_summary, csv_content
@@ -151,7 +157,7 @@ def test_mcp_workflow(district):
151
  except requests.exceptions.Timeout:
152
  return "⏰ Request timed out. The server might be processing...", "", ""
153
  except requests.exceptions.ConnectionError:
154
- return f"πŸ”Œ Connection Error: Cannot reach MCP server at {MCP_SERVER_URL}", "", ""
155
  except Exception as e:
156
  return f"❌ Error: {str(e)}", "", ""
157
 
@@ -164,8 +170,19 @@ def check_server_health():
164
  return f"βœ… Server Online | OpenAI: {'βœ…' if data.get('openai_available') else '❌'} | Time: {data.get('timestamp', 'N/A')}"
165
  else:
166
  return f"⚠️ Server responded with status {response.status_code}"
167
- except:
168
- return f"❌ Server Offline or Unreachable ({MCP_SERVER_URL})"
 
 
 
 
 
 
 
 
 
 
 
169
 
170
  # Create Gradio interface
171
  with gr.Blocks(
@@ -176,11 +193,6 @@ with gr.Blocks(
176
  max-width: 1200px;
177
  margin: auto;
178
  }
179
- .status-box {
180
- padding: 10px;
181
- border-radius: 5px;
182
- margin: 10px 0;
183
- }
184
  """
185
  ) as demo:
186
 
@@ -189,32 +201,32 @@ with gr.Blocks(
189
 
190
  **AI-Powered Weather Alerts for Bihar Farmers**
191
 
192
- This interface tests the MCP (Model Context Protocol) server that generates personalized weather alerts for agricultural activities in Bihar districts.
193
 
194
  ## πŸ“‹ How to Use:
195
- 1. **Select District**: Choose a Bihar district from the dropdown
196
- 2. **Run Workflow**: Click the button to generate weather alerts
197
- 3. **View Results**: See formatted workflow output and alert summary
198
- 4. **Download Data**: Get CSV export of the alert data
 
199
 
200
- The system will:
201
  - Select a random village in the district
202
- - Choose appropriate crops based on season and region
203
  - Generate weather-based agricultural alerts
204
- - Create messages for multiple communication channels (SMS, WhatsApp, etc.)
205
  """)
206
 
207
  # Server status
208
  with gr.Row():
209
  server_status = gr.Textbox(
210
  label="πŸ”§ Server Status",
211
- value=check_server_health(),
212
  interactive=False,
213
  container=True
214
  )
215
 
216
- refresh_btn = gr.Button("πŸ”„ Refresh Status", size="sm")
217
- refresh_btn.click(check_server_health, outputs=server_status)
218
 
219
  # Main interface
220
  with gr.Row():
@@ -234,11 +246,11 @@ with gr.Blocks(
234
 
235
  gr.Markdown("""
236
  ### πŸ’‘ What happens next?
237
- - Weather data collection
238
- - Crop stage estimation
239
  - AI-powered alert generation
240
- - Multi-channel message creation
241
- - CSV data export
242
  """)
243
 
244
  # Results section
@@ -246,13 +258,13 @@ with gr.Blocks(
246
  with gr.Column(scale=2):
247
  workflow_output = gr.Markdown(
248
  label="πŸ“‹ Workflow Output",
249
- value="Click 'Generate Weather Alert' to see results..."
250
  )
251
 
252
  with gr.Column(scale=1):
253
  alert_summary = gr.Markdown(
254
- label="πŸ“Š Alert Summary",
255
- value="Alert details will appear here..."
256
  )
257
 
258
  # CSV export
@@ -266,46 +278,46 @@ with gr.Blocks(
266
  def run_workflow_with_csv(district):
267
  workflow, summary, csv_content = test_mcp_workflow(district)
268
 
269
- # Create temporary CSV file if content exists
270
- if csv_content:
271
  filename = f"bihar_alert_{district.lower()}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
272
- with open(filename, 'w') as f:
273
  f.write(csv_content)
274
  return workflow, summary, gr.File(value=filename, visible=True)
275
  else:
276
  return workflow, summary, gr.File(visible=False)
277
 
 
 
278
  run_btn.click(
279
  run_workflow_with_csv,
280
- inputs=[district_input],
281
  outputs=[workflow_output, alert_summary, csv_output]
282
  )
283
 
 
 
 
 
 
 
 
284
  # Footer
285
  gr.Markdown("""
286
  ---
287
 
288
  ### πŸ”— System Information:
289
- - **State Coverage**: Bihar (38 districts)
290
  - **Crops Supported**: Rice, Wheat, Maize, Sugarcane, Mustard, and more
291
  - **Weather Sources**: Open-Meteo API with AI enhancement
292
  - **Communication Channels**: SMS, WhatsApp, USSD, IVR, Telegram
293
 
294
- ### πŸ“ž Agent Outputs:
295
- The system generates formatted messages for:
296
- - **πŸ“± SMS**: Short text alerts for basic phones
297
- - **πŸ“± WhatsApp**: Rich media messages with emojis
298
- - **πŸ“ž USSD**: Interactive menu systems
299
- - **πŸŽ™οΈ IVR**: Voice script for phone calls
300
- - **πŸ€– Telegram**: Bot-friendly formatted messages
301
-
302
  *Built with MCP (Model Context Protocol) for agricultural intelligence*
303
  """)
304
 
305
- # Launch configuration for HuggingFace Spaces
306
  if __name__ == "__main__":
 
307
  demo.launch(
308
- share=True,
309
  server_name="0.0.0.0",
310
  server_port=7860,
311
  show_error=True
 
1
  import gradio as gr
2
+ import subprocess
3
+ import threading
4
+ import time
5
  import requests
6
  import json
7
  from datetime import datetime
8
  import os
 
 
 
9
 
10
+ # Configuration
11
+ MCP_SERVER_URL = "https://elanuk-mcp-hf.hf.space/"
12
+
13
+ # Bihar districts list
14
+ BIHAR_DISTRICTS = [
15
+ "Patna", "Gaya", "Bhagalpur", "Muzaffarpur", "Darbhanga", "Siwan",
16
+ "Begusarai", "Katihar", "Nalanda", "Rohtas", "Saran", "Samastipur",
17
+ "Madhubani", "Purnia", "Araria", "Kishanganj", "Supaul", "Madhepura",
18
+ "Saharsa", "Khagaria", "Munger", "Lakhisarai", "Sheikhpura", "Nawada",
19
+ "Jamui", "Jehanabad", "Aurangabad", "Arwal", "Kaimur", "Buxar",
20
+ "Bhojpur", "Saran", "Siwan", "Gopalganj", "East Champaran", "West Champaran",
21
+ "Sitamarhi", "Sheohar", "Vaishali"
22
+ ]
23
 
24
  def start_mcp_server():
25
  """Start the MCP server in background"""
26
  try:
27
+ print("πŸš€ Starting MCP Server...")
28
+ # Set environment variable for the server port
29
+ env = os.environ.copy()
30
+ env["PORT"] = str(MCP_SERVER_PORT)
31
+
32
  process = subprocess.Popen(
33
  ["python", "mcp_server.py"],
34
  stdout=subprocess.PIPE,
35
+ stderr=subprocess.PIPE,
36
+ env=env,
37
+ text=True
38
  )
39
 
40
+ # Wait for server to start
41
+ print("⏳ Waiting for server to start...")
42
+ time.sleep(15)
43
+
44
+ # Check if server is running
45
+ try:
46
+ response = requests.get(f"{MCP_SERVER_URL}/api/health", timeout=5)
47
+ if response.status_code == 200:
48
+ print("βœ… MCP Server started successfully!")
49
+ return process
50
+ except:
51
+ pass
52
+
53
+ print("⚠️ Server may still be starting...")
54
  return process
55
+
56
  except Exception as e:
57
+ print(f"❌ Failed to start MCP server: {e}")
58
  return None
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def format_workflow_output(raw_output):
61
  """Format the workflow output for better display"""
62
  if not raw_output:
63
  return "❌ No output received"
64
 
 
65
  lines = raw_output.split('\n')
66
  formatted_lines = []
67
 
 
71
  formatted_lines.append("")
72
  continue
73
 
 
74
  if line.startswith('🌾') and 'Workflow' in line:
75
  formatted_lines.append(f"## {line}")
76
  elif line.startswith('=') or line.startswith('-'):
77
+ continue
78
  elif line.startswith('🌀️') or line.startswith('βœ… Workflow'):
79
  formatted_lines.append(f"### {line}")
80
  elif line.startswith('πŸ“±') or line.startswith('πŸ“ž') or line.startswith('πŸŽ™οΈ') or line.startswith('πŸ€–'):
 
130
  return "❌ Please select a district", "", ""
131
 
132
  try:
 
133
  payload = {
134
  "state": "bihar",
135
  "district": district.lower()
 
138
  response = requests.post(
139
  f"{MCP_SERVER_URL}/api/run-workflow",
140
  json=payload,
141
+ timeout=60 # Increased timeout
142
  )
143
 
144
  if response.status_code == 200:
145
  result = response.json()
146
 
 
147
  workflow_output = format_workflow_output(result.get('message', ''))
148
  alert_summary = format_alert_summary(result.get('raw_data', {}))
 
 
149
  csv_content = result.get('csv', '')
150
 
151
  return workflow_output, alert_summary, csv_content
 
157
  except requests.exceptions.Timeout:
158
  return "⏰ Request timed out. The server might be processing...", "", ""
159
  except requests.exceptions.ConnectionError:
160
+ return f"πŸ”Œ Connection Error: Cannot reach MCP server. Is it running?", "", ""
161
  except Exception as e:
162
  return f"❌ Error: {str(e)}", "", ""
163
 
 
170
  return f"βœ… Server Online | OpenAI: {'βœ…' if data.get('openai_available') else '❌'} | Time: {data.get('timestamp', 'N/A')}"
171
  else:
172
  return f"⚠️ Server responded with status {response.status_code}"
173
+ except Exception as e:
174
+ return f"❌ Server Offline: {str(e)}"
175
+
176
+ # Start server in background thread
177
+ print("πŸ”§ Initializing BIHAR AgMCP...")
178
+ server_process = None
179
+
180
+ def start_server_thread():
181
+ global server_process
182
+ server_process = start_mcp_server()
183
+
184
+ server_thread = threading.Thread(target=start_server_thread, daemon=True)
185
+ server_thread.start()
186
 
187
  # Create Gradio interface
188
  with gr.Blocks(
 
193
  max-width: 1200px;
194
  margin: auto;
195
  }
 
 
 
 
 
196
  """
197
  ) as demo:
198
 
 
201
 
202
  **AI-Powered Weather Alerts for Bihar Farmers**
203
 
204
+ This system generates personalized weather alerts for agricultural activities in Bihar districts.
205
 
206
  ## πŸ“‹ How to Use:
207
+ 1. **Wait for Server**: Ensure server status shows "Online" below
208
+ 2. **Select District**: Choose a Bihar district from the dropdown
209
+ 3. **Run Workflow**: Click the button to generate weather alerts
210
+ 4. **View Results**: See formatted workflow output and alert summary
211
+ 5. **Download Data**: Get CSV export of the alert data
212
 
213
+ The system will automatically:
214
  - Select a random village in the district
215
+ - Choose appropriate crops based on season and region
216
  - Generate weather-based agricultural alerts
217
+ - Create messages for multiple communication channels
218
  """)
219
 
220
  # Server status
221
  with gr.Row():
222
  server_status = gr.Textbox(
223
  label="πŸ”§ Server Status",
224
+ value="πŸ”„ Starting server...",
225
  interactive=False,
226
  container=True
227
  )
228
 
229
+ refresh_btn = gr.Button("πŸ”„ Check Status", size="sm")
 
230
 
231
  # Main interface
232
  with gr.Row():
 
246
 
247
  gr.Markdown("""
248
  ### πŸ’‘ What happens next?
249
+ - Weather data collection from multiple sources
250
+ - Intelligent crop stage estimation
251
  - AI-powered alert generation
252
+ - Multi-channel message creation (SMS, WhatsApp, etc.)
253
+ - Comprehensive CSV data export
254
  """)
255
 
256
  # Results section
 
258
  with gr.Column(scale=2):
259
  workflow_output = gr.Markdown(
260
  label="πŸ“‹ Workflow Output",
261
+ value="Server is starting... Please wait and check server status above."
262
  )
263
 
264
  with gr.Column(scale=1):
265
  alert_summary = gr.Markdown(
266
+ label="πŸ“Š Alert Summary",
267
+ value="Alert details will appear here after running workflow..."
268
  )
269
 
270
  # CSV export
 
278
  def run_workflow_with_csv(district):
279
  workflow, summary, csv_content = test_mcp_workflow(district)
280
 
281
+ if csv_content and not csv_content.startswith("Error"):
 
282
  filename = f"bihar_alert_{district.lower()}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
283
+ with open(filename, 'w', encoding='utf-8') as f:
284
  f.write(csv_content)
285
  return workflow, summary, gr.File(value=filename, visible=True)
286
  else:
287
  return workflow, summary, gr.File(visible=False)
288
 
289
+ # Connect events
290
+ refresh_btn.click(check_server_health, outputs=server_status)
291
  run_btn.click(
292
  run_workflow_with_csv,
293
+ inputs=[district_input],
294
  outputs=[workflow_output, alert_summary, csv_output]
295
  )
296
 
297
+ # Auto-refresh server status after a delay
298
+ def auto_check_status():
299
+ time.sleep(20) # Wait 20 seconds
300
+ return check_server_health()
301
+
302
+ demo.load(auto_check_status, outputs=server_status)
303
+
304
  # Footer
305
  gr.Markdown("""
306
  ---
307
 
308
  ### πŸ”— System Information:
309
+ - **State Coverage**: Bihar (38+ districts)
310
  - **Crops Supported**: Rice, Wheat, Maize, Sugarcane, Mustard, and more
311
  - **Weather Sources**: Open-Meteo API with AI enhancement
312
  - **Communication Channels**: SMS, WhatsApp, USSD, IVR, Telegram
313
 
 
 
 
 
 
 
 
 
314
  *Built with MCP (Model Context Protocol) for agricultural intelligence*
315
  """)
316
 
317
+ # Launch the interface
318
  if __name__ == "__main__":
319
+ print("🌾 Launching BIHAR AgMCP Interface...")
320
  demo.launch(
 
321
  server_name="0.0.0.0",
322
  server_port=7860,
323
  show_error=True