elanuk commited on
Commit
c2c6d34
Β·
verified Β·
1 Parent(s): 0b8bf8f

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +88 -52
server.py CHANGED
@@ -821,71 +821,109 @@ BIHAR_DISTRICTS = [
821
  "Sitamarhi", "Sheohar", "Vaishali"
822
  ]
823
 
824
-
825
  def format_workflow_output(raw_output, agent_responses=None):
826
- """Format workflow output for display with actual agent responses"""
827
  if not raw_output:
828
  return "❌ No output received"
829
 
830
- # Ensure raw_output is a string
831
  if not isinstance(raw_output, str):
832
  raw_output = str(raw_output)
833
 
834
  lines = raw_output.split('\n')
835
  formatted_lines = []
836
 
 
 
837
  for line in lines:
838
  line = str(line).strip() # Ensure line is string
839
  if not line:
840
- formatted_lines.append("")
 
841
  continue
842
-
843
- if line.startswith('🌾') and 'Workflow' in line:
844
- formatted_lines.append(f"## {line}")
845
- elif line.startswith('=') or line.startswith('-'):
846
- continue
847
- elif line.startswith('🌀️') or line.startswith('βœ… Workflow'):
848
  formatted_lines.append(f"### {line}")
849
- elif line.startswith('πŸ“±') or line.startswith('πŸ“ž') or line.startswith('πŸŽ™οΈ') or line.startswith('πŸ€–'):
850
- # This is an agent section - add the actual response
851
- agent_name = line
852
- formatted_lines.append(f"#### {agent_name}")
853
 
854
- # Find the corresponding agent response
855
- if agent_responses:
856
- clean_name = agent_name.replace("πŸ“± ", "").replace("πŸ“ž ", "").replace("πŸŽ™οΈ ", "").replace("πŸ€– ", "")
857
- if clean_name in agent_responses:
858
- response = agent_responses[clean_name]
859
- formatted_lines.append("**Generated Message:**")
860
- formatted_lines.append("```")
861
- if isinstance(response, dict):
862
- # Format dictionary responses nicely
863
- for key, value in response.items():
864
- key_str = str(key)
865
- value_str = str(value)
866
- if len(value_str) > 200:
867
- formatted_lines.append(f"{key_str}: {value_str[:200]}...")
868
- else:
869
- formatted_lines.append(f"{key_str}: {value_str}")
870
- else:
871
- # Format string responses
872
- response_str = str(response)
873
- if len(response_str) > 500:
874
- formatted_lines.append(f"{response_str[:500]}...")
875
- else:
876
- formatted_lines.append(response_str)
877
- formatted_lines.append("```")
878
- formatted_lines.append("")
879
- else:
880
- formatted_lines.append("*No response data available*")
881
- formatted_lines.append("")
882
- elif line.startswith('βœ…') or line.startswith('❌'):
883
  formatted_lines.append(f"- {line}")
884
  else:
885
  formatted_lines.append(line)
 
 
 
886
 
887
  return '\n'.join(formatted_lines)
888
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
889
  def format_agent_responses(agent_responses):
890
  """Create a dedicated section for agent responses"""
891
  if not agent_responses:
@@ -932,6 +970,7 @@ def format_agent_responses(agent_responses):
932
  formatted = [str(item) for item in formatted]
933
  return '\n'.join(formatted)
934
 
 
935
  def format_alert_summary(raw_data):
936
  """Format alert summary"""
937
  if not raw_data or 'alert_data' not in raw_data:
@@ -964,15 +1003,13 @@ def format_alert_summary(raw_data):
964
 
965
 
966
  def run_workflow_ui(district):
967
- """Run workflow directly using internal functions"""
968
  if not district:
969
  return "❌ Please select a district", "", "", gr.File(visible=False)
970
 
971
  try:
972
- # Call the workflow function directly
973
  request_obj = WorkflowRequest(state="bihar", district=district.lower())
974
 
975
- # Use asyncio to run the async function
976
  import asyncio
977
  try:
978
  loop = asyncio.get_event_loop()
@@ -980,14 +1017,13 @@ def run_workflow_ui(district):
980
  loop = asyncio.new_event_loop()
981
  asyncio.set_event_loop(loop)
982
 
983
- result = loop.run_until_complete(run_workflow(request_obj))
984
 
985
  # Extract data
986
  raw_data = result.get('raw_data', {})
987
  agent_responses = raw_data.get('agent_responses', {})
988
 
989
- # Format outputs with agent responses
990
- workflow_output = format_workflow_output(result.get('message', ''), agent_responses)
991
  alert_summary = format_alert_summary(raw_data)
992
  agent_details = format_agent_responses(agent_responses)
993
  csv_content = result.get('csv', '')
@@ -997,12 +1033,10 @@ def run_workflow_ui(district):
997
  import tempfile
998
  import os
999
 
1000
- # Create temporary file
1001
  with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as temp_file:
1002
  temp_file.write(csv_content)
1003
  temp_filename = temp_file.name
1004
 
1005
- # Create a proper filename for download
1006
  display_name = f"bihar_alert_{district.lower()}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
1007
 
1008
  return workflow_output, alert_summary, agent_details, gr.File(value=temp_filename, visible=True, label=display_name)
@@ -1014,7 +1048,9 @@ def run_workflow_ui(district):
1014
  logger.exception(f"UI workflow error: {e}")
1015
  return error_msg, "", "", gr.File(visible=False)
1016
 
1017
- # Updated Gradio interface
 
 
1018
  def create_gradio_interface():
1019
  with gr.Blocks(
1020
  title="BIHAR AgMCP - Agricultural Weather Alerts",
 
821
  "Sitamarhi", "Sheohar", "Vaishali"
822
  ]
823
 
 
824
  def format_workflow_output(raw_output, agent_responses=None):
825
+ """Format workflow output for display with actual agent responses - skip detailed workflow steps"""
826
  if not raw_output:
827
  return "❌ No output received"
828
 
 
829
  if not isinstance(raw_output, str):
830
  raw_output = str(raw_output)
831
 
832
  lines = raw_output.split('\n')
833
  formatted_lines = []
834
 
835
+ capture_content = False
836
+
837
  for line in lines:
838
  line = str(line).strip() # Ensure line is string
839
  if not line:
840
+ if capture_content:
841
+ formatted_lines.append("")
842
  continue
843
+
844
+ if line.startswith('βœ… Workflow Summary'):
845
+ capture_content = True
 
 
 
846
  formatted_lines.append(f"### {line}")
847
+ continue
848
+
849
+ if not capture_content:
850
+ continue
851
 
852
+ if line.startswith('=') or line.startswith('-'):
853
+ continue
854
+ elif line.startswith('🎯') or line.startswith('πŸ“Š') or line.startswith('πŸ€–') or line.startswith('⏰') or line.startswith('πŸ“±'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
855
  formatted_lines.append(f"- {line}")
856
  else:
857
  formatted_lines.append(line)
858
+
859
+ if not capture_content or not formatted_lines:
860
+ return "βœ… Alert generated successfully - check other tabs for details"
861
 
862
  return '\n'.join(formatted_lines)
863
 
864
+
865
+ async def run_workflow_clean(request: WorkflowRequest):
866
+ logger.info(f"Received workflow request: {request.state}, {request.district}")
867
+
868
+ try:
869
+ # Generate dynamic alert
870
+ sample_alert = await generate_dynamic_alert(request.district, request.state)
871
+
872
+ # Generate agent responses
873
+ agents = [
874
+ ("πŸ“± WhatsApp Agent", whatsapp_agent.create_whatsapp_message),
875
+ ("πŸ“± SMS Agent", sms_agent.create_sms_message),
876
+ ("πŸ“ž USSD Agent", ussd_agent.create_ussd_menu),
877
+ ("πŸŽ™οΈ IVR Agent", ivr_agent.create_ivr_script),
878
+ ("πŸ€– Telegram Agent", telegram_agent.create_telegram_message)
879
+ ]
880
+
881
+ agent_responses = {}
882
+ successful_agents = 0
883
+
884
+ for agent_name, agent_func in agents:
885
+ try:
886
+ response = agent_func(sample_alert)
887
+ agent_responses[agent_name] = response
888
+ successful_agents += 1
889
+ except Exception as e:
890
+ agent_responses[agent_name] = f"Error: {str(e)}"
891
+
892
+ summary_message = f"""### βœ… Workflow Summary
893
+
894
+ 🎯 Successfully generated alerts for {sample_alert['location']['village']}, {request.district.title()}
895
+ πŸ“Š Data Sources: {sample_alert['data_source']}
896
+ πŸ€– AI Enhanced: {'Yes' if sample_alert['alert']['ai_generated'] else 'No'}
897
+ ⏰ Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}
898
+ πŸ“± Agents Processed: {successful_agents}/{len(agents)}"""
899
+
900
+ # Generate CSV
901
+ csv_content = generate_csv_export(sample_alert, agent_responses)
902
+
903
+ return {
904
+ "message": summary_message,
905
+ "status": "success",
906
+ "csv": csv_content,
907
+ "raw_data": {
908
+ "state": request.state,
909
+ "district": request.district,
910
+ "alert_data": sample_alert,
911
+ "agent_responses": agent_responses
912
+ }
913
+ }
914
+
915
+ except Exception as e:
916
+ error_msg = f"❌ Workflow failed: {str(e)}"
917
+ logger.exception(f"Workflow error for {request.district}, {request.state}")
918
+
919
+ return {
920
+ "message": error_msg,
921
+ "status": "error",
922
+ "csv": "",
923
+ "error": str(e)
924
+ }
925
+
926
+
927
  def format_agent_responses(agent_responses):
928
  """Create a dedicated section for agent responses"""
929
  if not agent_responses:
 
970
  formatted = [str(item) for item in formatted]
971
  return '\n'.join(formatted)
972
 
973
+
974
  def format_alert_summary(raw_data):
975
  """Format alert summary"""
976
  if not raw_data or 'alert_data' not in raw_data:
 
1003
 
1004
 
1005
  def run_workflow_ui(district):
1006
+ """Run workflow directly using internal functions with clean output"""
1007
  if not district:
1008
  return "❌ Please select a district", "", "", gr.File(visible=False)
1009
 
1010
  try:
 
1011
  request_obj = WorkflowRequest(state="bihar", district=district.lower())
1012
 
 
1013
  import asyncio
1014
  try:
1015
  loop = asyncio.get_event_loop()
 
1017
  loop = asyncio.new_event_loop()
1018
  asyncio.set_event_loop(loop)
1019
 
1020
+ result = loop.run_until_complete(run_workflow_clean(request_obj))
1021
 
1022
  # Extract data
1023
  raw_data = result.get('raw_data', {})
1024
  agent_responses = raw_data.get('agent_responses', {})
1025
 
1026
+ workflow_output = result.get('message', '')
 
1027
  alert_summary = format_alert_summary(raw_data)
1028
  agent_details = format_agent_responses(agent_responses)
1029
  csv_content = result.get('csv', '')
 
1033
  import tempfile
1034
  import os
1035
 
 
1036
  with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as temp_file:
1037
  temp_file.write(csv_content)
1038
  temp_filename = temp_file.name
1039
 
 
1040
  display_name = f"bihar_alert_{district.lower()}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
1041
 
1042
  return workflow_output, alert_summary, agent_details, gr.File(value=temp_filename, visible=True, label=display_name)
 
1048
  logger.exception(f"UI workflow error: {e}")
1049
  return error_msg, "", "", gr.File(visible=False)
1050
 
1051
+
1052
+
1053
+ # Gradio interface
1054
  def create_gradio_interface():
1055
  with gr.Blocks(
1056
  title="BIHAR AgMCP - Agricultural Weather Alerts",