elanuk commited on
Commit
87eae33
Β·
verified Β·
1 Parent(s): b4dcc60

Rename mcp_server.py to server.py

Browse files
Files changed (1) hide show
  1. mcp_server.py β†’ server.py +206 -4
mcp_server.py β†’ server.py RENAMED
@@ -800,12 +800,214 @@ async def general_exception_handler(request, exc):
800
  "timestamp": datetime.now().isoformat()
801
  }
802
 
803
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
804
  import uvicorn
805
- logger.info("Starting MCP Weather Server...")
806
  uvicorn.run(
807
  app,
808
  host="0.0.0.0",
809
- port=int(os.getenv("PORT", 8000)),
810
  log_level=LOG_LEVEL.lower()
811
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
800
  "timestamp": datetime.now().isoformat()
801
  }
802
 
803
+
804
+
805
+ import gradio as gr
806
+ import threading
807
+ import time
808
+
809
+ # Bihar districts list
810
+ BIHAR_DISTRICTS = [
811
+ "Patna", "Gaya", "Bhagalpur", "Muzaffarpur", "Darbhanga", "Siwan",
812
+ "Begusarai", "Katihar", "Nalanda", "Rohtas", "Saran", "Samastipur",
813
+ "Madhubani", "Purnia", "Araria", "Kishanganj", "Supaul", "Madhepura",
814
+ "Saharsa", "Khagaria", "Munger", "Lakhisarai", "Sheikhpura", "Nawada",
815
+ "Jamui", "Jehanabad", "Aurangabad", "Arwal", "Kaimur", "Buxar",
816
+ "Bhojpur", "Saran", "Siwan", "Gopalganj", "East Champaran", "West Champaran",
817
+ "Sitamarhi", "Sheohar", "Vaishali"
818
+ ]
819
+
820
+ def format_workflow_output(raw_output):
821
+ """Format workflow output for display"""
822
+ if not raw_output:
823
+ return "❌ No output received"
824
+
825
+ lines = raw_output.split('\n')
826
+ formatted_lines = []
827
+
828
+ for line in lines:
829
+ line = line.strip()
830
+ if not line:
831
+ formatted_lines.append("")
832
+ continue
833
+
834
+ if line.startswith('🌾') and 'Workflow' in line:
835
+ formatted_lines.append(f"## {line}")
836
+ elif line.startswith('=') or line.startswith('-'):
837
+ continue
838
+ elif line.startswith('🌀️') or line.startswith('βœ… Workflow'):
839
+ formatted_lines.append(f"### {line}")
840
+ elif line.startswith('πŸ“±') or line.startswith('πŸ“ž') or line.startswith('πŸŽ™οΈ') or line.startswith('πŸ€–'):
841
+ formatted_lines.append(f"#### {line}")
842
+ elif line.startswith('βœ…') or line.startswith('❌'):
843
+ formatted_lines.append(f"- {line}")
844
+ else:
845
+ formatted_lines.append(line)
846
+
847
+ return '\n'.join(formatted_lines)
848
+
849
+ def format_alert_summary(raw_data):
850
+ """Format alert summary"""
851
+ if not raw_data or 'alert_data' not in raw_data:
852
+ return "No alert data available"
853
+
854
+ alert_data = raw_data['alert_data']
855
+
856
+ summary = f"""
857
+ ## 🚨 Alert Summary
858
+
859
+ **πŸ“ Location:** {alert_data['location']['village']}, {alert_data['location']['district']}, {alert_data['location']['state']}
860
+
861
+ **🌾 Crop Information:**
862
+ - **Crop:** {alert_data['crop']['name'].title()}
863
+ - **Growth Stage:** {alert_data['crop']['stage']}
864
+ - **Season:** {alert_data['crop']['season'].title()}
865
+
866
+ **🌀️ Weather Conditions:**
867
+ - **Temperature:** {alert_data['weather']['temperature']}
868
+ - **Expected Rainfall:** {alert_data['weather']['expected_rainfall']}
869
+ - **Wind Speed:** {alert_data['weather']['wind_speed']}
870
+ - **Rain Probability:** {alert_data['weather']['rain_probability']}%
871
+
872
+ **⚠️ Alert Details:**
873
+ - **Type:** {alert_data['alert']['type'].replace('_', ' ').title()}
874
+ - **Urgency:** {alert_data['alert']['urgency'].upper()}
875
+ - **AI Enhanced:** {'βœ… Yes' if alert_data['alert']['ai_generated'] else '❌ No'}
876
+
877
+ **πŸ“¨ Alert Message:**
878
+ {alert_data['alert']['message']}
879
+
880
+ **🎯 Action Items:**
881
+ {chr(10).join([f"- {item.replace('_', ' ').title()}" for item in alert_data['alert']['action_items']])}
882
+ """
883
+ return summary
884
+
885
+ def run_workflow_ui(district):
886
+ """Run workflow directly using internal functions"""
887
+ if not district:
888
+ return "❌ Please select a district", "", ""
889
+
890
+ try:
891
+ # Call the workflow function directly (no HTTP request needed!)
892
+ request_obj = WorkflowRequest(state="bihar", district=district.lower())
893
+
894
+ # Use asyncio to run the async function
895
+ import asyncio
896
+ try:
897
+ loop = asyncio.get_event_loop()
898
+ except RuntimeError:
899
+ loop = asyncio.new_event_loop()
900
+ asyncio.set_event_loop(loop)
901
+
902
+ result = loop.run_until_complete(run_workflow(request_obj))
903
+
904
+ # Format outputs
905
+ workflow_output = format_workflow_output(result.get('message', ''))
906
+ alert_summary = format_alert_summary(result.get('raw_data', {}))
907
+ csv_content = result.get('csv', '')
908
+
909
+ # Create CSV file if content exists
910
+ if csv_content:
911
+ filename = f"bihar_alert_{district.lower()}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
912
+ with open(filename, 'w', encoding='utf-8') as f:
913
+ f.write(csv_content)
914
+ return workflow_output, alert_summary, gr.File(value=filename, visible=True)
915
+ else:
916
+ return workflow_output, alert_summary, gr.File(visible=False)
917
+
918
+ except Exception as e:
919
+ error_msg = f"❌ Error: {str(e)}"
920
+ logger.exception(f"UI workflow error: {e}")
921
+ return error_msg, "", gr.File(visible=False)
922
+
923
+ # Create Gradio interface
924
+ with gr.Blocks(
925
+ title="BIHAR AgMCP - Agricultural Weather Alerts",
926
+ theme=gr.themes.Soft()
927
+ ) as demo:
928
+
929
+ gr.Markdown("""
930
+ # 🌾 BIHAR AgMCP - Agricultural Weather Alert System
931
+
932
+ **AI-Powered Weather Alerts for Bihar Farmers**
933
+
934
+ Generate personalized weather alerts for agricultural activities in Bihar districts.
935
+
936
+ ## How to Use:
937
+ 1. Select a Bihar district from the dropdown
938
+ 2. Click "Generate Weather Alert"
939
+ 3. View the formatted results and download CSV data
940
+ """)
941
+
942
+ with gr.Row():
943
+ with gr.Column(scale=1):
944
+ district_input = gr.Dropdown(
945
+ choices=BIHAR_DISTRICTS,
946
+ label="πŸ“ Select Bihar District",
947
+ value="Patna"
948
+ )
949
+
950
+ run_btn = gr.Button(
951
+ "πŸš€ Generate Weather Alert",
952
+ variant="primary",
953
+ size="lg"
954
+ )
955
+
956
+ with gr.Row():
957
+ with gr.Column(scale=2):
958
+ workflow_output = gr.Markdown(
959
+ label="πŸ“‹ Workflow Output",
960
+ value="Select a district and click the button to generate alerts..."
961
+ )
962
+
963
+ with gr.Column(scale=1):
964
+ alert_summary = gr.Markdown(
965
+ label="πŸ“Š Alert Summary",
966
+ value="Alert details will appear here..."
967
+ )
968
+
969
+ csv_output = gr.File(
970
+ label="πŸ“ Download CSV Data",
971
+ visible=False
972
+ )
973
+
974
+ # Connect the button
975
+ run_btn.click(
976
+ run_workflow_ui,
977
+ inputs=[district_input],
978
+ outputs=[workflow_output, alert_summary, csv_output]
979
+ )
980
+
981
+ def run_fastapi():
982
+ """Run FastAPI server"""
983
  import uvicorn
 
984
  uvicorn.run(
985
  app,
986
  host="0.0.0.0",
987
+ port=8000,
988
  log_level=LOG_LEVEL.lower()
989
+ )
990
+
991
+ if __name__ == "__main__":
992
+ # Check if we should show UI (HuggingFace Spaces) or just API
993
+ if os.getenv("SPACE_ID") or os.getenv("GRADIO_SERVER_NAME"):
994
+ # HuggingFace Spaces - start FastAPI in background, Gradio in foreground
995
+ logger.info("Starting in HuggingFace Spaces mode with UI...")
996
+
997
+ # Start FastAPI in background
998
+ fastapi_thread = threading.Thread(target=run_fastapi, daemon=True)
999
+ fastapi_thread.start()
1000
+
1001
+ # Wait for FastAPI to start
1002
+ time.sleep(3)
1003
+
1004
+ # Launch Gradio interface
1005
+ demo.launch(
1006
+ server_name="0.0.0.0",
1007
+ server_port=7860,
1008
+ show_error=True
1009
+ )
1010
+ else:
1011
+ # Local development - just run FastAPI
1012
+ logger.info("Starting MCP Weather Server (API only)...")
1013
+ run_fastapi()