Update app.py
Browse files
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
|
11 |
-
MCP_SERVER_URL = "https://elanuk-mcp-hf.hf.space/"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
def start_mcp_server():
|
14 |
"""Start the MCP server in background"""
|
15 |
try:
|
16 |
-
|
|
|
|
|
|
|
|
|
17 |
process = subprocess.Popen(
|
18 |
["python", "mcp_server.py"],
|
19 |
stdout=subprocess.PIPE,
|
20 |
-
stderr=subprocess.PIPE
|
|
|
|
|
21 |
)
|
22 |
|
23 |
-
# Wait
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
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=
|
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
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
193 |
|
194 |
## π How to Use:
|
195 |
-
1. **
|
196 |
-
2. **
|
197 |
-
3. **
|
198 |
-
4. **
|
|
|
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
|
205 |
""")
|
206 |
|
207 |
# Server status
|
208 |
with gr.Row():
|
209 |
server_status = gr.Textbox(
|
210 |
label="π§ Server Status",
|
211 |
-
value=
|
212 |
interactive=False,
|
213 |
container=True
|
214 |
)
|
215 |
|
216 |
-
refresh_btn = gr.Button("π
|
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 |
-
-
|
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="
|
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 |
-
|
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
|
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
|