File size: 6,397 Bytes
524df2c
 
 
1526954
fa33eaa
 
5aba7dd
 
 
 
 
 
 
 
 
 
 
06cdcc5
524df2c
f55d428
524df2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aba7dd
524df2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f55d428
 
524df2c
 
 
 
 
 
 
 
 
fa33eaa
524df2c
fa33eaa
524df2c
d83dcb2
524df2c
 
 
 
 
 
 
 
 
f55d428
 
 
 
 
 
 
 
 
524df2c
f55d428
 
524df2c
 
f55d428
 
524df2c
 
 
 
f55d428
524df2c
 
 
 
 
 
 
f55d428
524df2c
f55d428
 
 
 
524df2c
 
 
 
 
 
 
f55d428
524df2c
 
 
 
 
 
 
 
 
 
 
 
f55d428
524df2c
 
 
 
f55d428
 
524df2c
 
f55d428
 
 
 
d83dcb2
f55d428
524df2c
f55d428
 
524df2c
 
 
 
 
 
f55d428
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
import gradio as gr
import requests
from datetime import datetime

# Use your deployed server instead of localhost
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 format_workflow_output(raw_output):
    """Format the workflow output for 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}")
        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 run_workflow(district):
    """Run the workflow and return results"""
    if not district:
        return "❌ Please select a district", "", ""
    
    try:
        payload = {
            "state": "bihar",
            "district": district.lower()
        }
        
        # Call your existing deployed server
        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', '')
            
            # Create CSV file if content exists
            if csv_content:
                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_output, alert_summary, gr.File(value=filename, visible=True)
            else:
                return workflow_output, alert_summary, gr.File(visible=False)
                
        else:
            error_msg = f"❌ Server Error ({response.status_code})"
            return error_msg, "", gr.File(visible=False)
            
    except Exception as e:
        error_msg = f"❌ Error: {str(e)}"
        return error_msg, "", gr.File(visible=False)

# Create Gradio interface
with gr.Blocks(
    title="BIHAR AgMCP - Agricultural Weather Alerts",
    theme=gr.themes.Soft()
) as demo:
    
    gr.Markdown("""
    # 🌾 BIHAR AgMCP - Agricultural Weather Alert System
    
    **AI-Powered Weather Alerts for Bihar Farmers**
    
    Generate personalized weather alerts for agricultural activities in Bihar districts.
    
    ## How to Use:
    1. Select a Bihar district from the dropdown
    2. Click "Generate Weather Alert" 
    3. View the formatted results and download CSV data
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            district_input = gr.Dropdown(
                choices=BIHAR_DISTRICTS,
                label="πŸ“ Select Bihar District",
                value="Patna"
            )
            
            run_btn = gr.Button(
                "πŸš€ Generate Weather Alert", 
                variant="primary",
                size="lg"
            )
    
    with gr.Row():
        with gr.Column(scale=2):
            workflow_output = gr.Markdown(
                label="πŸ“‹ Workflow Output",
                value="Select a district and click the button to generate alerts..."
            )
        
        with gr.Column(scale=1):
            alert_summary = gr.Markdown(
                label="πŸ“Š Alert Summary",
                value="Alert details will appear here..."
            )
    
    csv_output = gr.File(
        label="πŸ“ Download CSV Data",
        visible=False
    )
    
    # Connect the button
    run_btn.click(
        run_workflow,
        inputs=[district_input],
        outputs=[workflow_output, alert_summary, csv_output]
    )

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860
    )