Update server.py
Browse files
server.py
CHANGED
@@ -821,8 +821,9 @@ BIHAR_DISTRICTS = [
|
|
821 |
"Sitamarhi", "Sheohar", "Vaishali"
|
822 |
]
|
823 |
|
824 |
-
|
825 |
-
|
|
|
826 |
if not raw_output:
|
827 |
return "β No output received"
|
828 |
|
@@ -842,7 +843,36 @@ def format_workflow_output(raw_output):
|
|
842 |
elif line.startswith('π€οΈ') or line.startswith('β
Workflow'):
|
843 |
formatted_lines.append(f"### {line}")
|
844 |
elif line.startswith('π±') or line.startswith('π') or line.startswith('ποΈ') or line.startswith('π€'):
|
845 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
846 |
elif line.startswith('β
') or line.startswith('β'):
|
847 |
formatted_lines.append(f"- {line}")
|
848 |
else:
|
@@ -850,6 +880,44 @@ def format_workflow_output(raw_output):
|
|
850 |
|
851 |
return '\n'.join(formatted_lines)
|
852 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
853 |
def format_alert_summary(raw_data):
|
854 |
"""Format alert summary"""
|
855 |
if not raw_data or 'alert_data' not in raw_data:
|
@@ -889,10 +957,10 @@ def format_alert_summary(raw_data):
|
|
889 |
def run_workflow_ui(district):
|
890 |
"""Run workflow directly using internal functions"""
|
891 |
if not district:
|
892 |
-
return "β Please select a district", "", ""
|
893 |
|
894 |
try:
|
895 |
-
# Call the workflow function directly
|
896 |
request_obj = WorkflowRequest(state="bihar", district=district.lower())
|
897 |
|
898 |
# Use asyncio to run the async function
|
@@ -905,9 +973,14 @@ def run_workflow_ui(district):
|
|
905 |
|
906 |
result = loop.run_until_complete(run_workflow(request_obj))
|
907 |
|
908 |
-
#
|
909 |
-
|
910 |
-
|
|
|
|
|
|
|
|
|
|
|
911 |
csv_content = result.get('csv', '')
|
912 |
|
913 |
# Create CSV file if content exists
|
@@ -923,72 +996,81 @@ def run_workflow_ui(district):
|
|
923 |
# Create a proper filename for download
|
924 |
display_name = f"bihar_alert_{district.lower()}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
|
925 |
|
926 |
-
return workflow_output, alert_summary, gr.File(value=temp_filename, visible=True, label=display_name)
|
927 |
else:
|
928 |
-
return workflow_output, alert_summary, gr.File(visible=False)
|
929 |
|
930 |
except Exception as e:
|
931 |
error_msg = f"β Error: {str(e)}"
|
932 |
logger.exception(f"UI workflow error: {e}")
|
933 |
-
return error_msg, "", gr.File(visible=False)
|
934 |
|
935 |
# Create Gradio interface
|
936 |
-
|
937 |
-
|
938 |
-
|
939 |
-
)
|
940 |
-
|
941 |
-
|
942 |
-
|
943 |
-
|
944 |
-
|
945 |
-
|
946 |
-
|
947 |
-
|
948 |
-
|
949 |
-
|
950 |
-
|
951 |
-
|
952 |
-
|
953 |
-
|
954 |
-
|
955 |
-
with gr.
|
956 |
-
|
957 |
-
|
958 |
-
|
959 |
-
|
960 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
961 |
|
962 |
-
|
963 |
-
|
964 |
-
|
965 |
-
|
966 |
-
|
967 |
-
|
968 |
-
with gr.Row():
|
969 |
-
with gr.Column(scale=2):
|
970 |
-
workflow_output = gr.Markdown(
|
971 |
-
label="π Workflow Output",
|
972 |
-
value="Select a district and click the button to generate alerts..."
|
973 |
-
)
|
974 |
|
975 |
-
with gr.
|
976 |
-
|
977 |
-
label="
|
978 |
-
value="
|
979 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
980 |
|
981 |
-
|
982 |
-
label="π Download CSV Data",
|
983 |
-
visible=False
|
984 |
-
)
|
985 |
-
|
986 |
-
# Connect the button
|
987 |
-
run_btn.click(
|
988 |
-
run_workflow_ui,
|
989 |
-
inputs=[district_input],
|
990 |
-
outputs=[workflow_output, alert_summary, csv_output]
|
991 |
-
)
|
992 |
|
993 |
def run_fastapi():
|
994 |
"""Run FastAPI server"""
|
@@ -1013,6 +1095,7 @@ if __name__ == "__main__":
|
|
1013 |
time.sleep(3)
|
1014 |
|
1015 |
# Launch Gradio interface
|
|
|
1016 |
demo.launch(
|
1017 |
server_name="0.0.0.0",
|
1018 |
server_port=7860,
|
|
|
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 |
|
|
|
843 |
elif line.startswith('π€οΈ') or line.startswith('β
Workflow'):
|
844 |
formatted_lines.append(f"### {line}")
|
845 |
elif line.startswith('π±') or line.startswith('π') or line.startswith('ποΈ') or line.startswith('π€'):
|
846 |
+
# This is an agent section - add the actual response
|
847 |
+
agent_name = line
|
848 |
+
formatted_lines.append(f"#### {agent_name}")
|
849 |
+
|
850 |
+
# Find the corresponding agent response
|
851 |
+
if agent_responses:
|
852 |
+
clean_name = agent_name.replace("π± ", "").replace("π ", "").replace("ποΈ ", "").replace("π€ ", "")
|
853 |
+
if clean_name in agent_responses:
|
854 |
+
response = agent_responses[clean_name]
|
855 |
+
formatted_lines.append("**Generated Message:**")
|
856 |
+
formatted_lines.append("```")
|
857 |
+
if isinstance(response, dict):
|
858 |
+
# Format dictionary responses nicely
|
859 |
+
for key, value in response.items():
|
860 |
+
if isinstance(value, str) and len(value) > 200:
|
861 |
+
formatted_lines.append(f"{key}: {value[:200]}...")
|
862 |
+
else:
|
863 |
+
formatted_lines.append(f"{key}: {value}")
|
864 |
+
else:
|
865 |
+
# Format string responses
|
866 |
+
response_str = str(response)
|
867 |
+
if len(response_str) > 500:
|
868 |
+
formatted_lines.append(f"{response_str[:500]}...")
|
869 |
+
else:
|
870 |
+
formatted_lines.append(response_str)
|
871 |
+
formatted_lines.append("```")
|
872 |
+
formatted_lines.append("")
|
873 |
+
else:
|
874 |
+
formatted_lines.append("*No response data available*")
|
875 |
+
formatted_lines.append("")
|
876 |
elif line.startswith('β
') or line.startswith('β'):
|
877 |
formatted_lines.append(f"- {line}")
|
878 |
else:
|
|
|
880 |
|
881 |
return '\n'.join(formatted_lines)
|
882 |
|
883 |
+
|
884 |
+
def format_agent_responses(agent_responses):
|
885 |
+
"""Create a dedicated section for agent responses"""
|
886 |
+
if not agent_responses:
|
887 |
+
return "No agent responses available"
|
888 |
+
|
889 |
+
formatted = ["## π± Agent Responses", ""]
|
890 |
+
|
891 |
+
for agent_name, response in agent_responses.items():
|
892 |
+
clean_name = agent_name.replace("π± ", "").replace("π ", "").replace("ποΈ ", "").replace("π€ ", "")
|
893 |
+
|
894 |
+
if str(response).startswith('Error:'):
|
895 |
+
formatted.append(f"### β {clean_name}")
|
896 |
+
formatted.append(f"**Error:** {response}")
|
897 |
+
else:
|
898 |
+
formatted.append(f"### β
{clean_name}")
|
899 |
+
|
900 |
+
if isinstance(response, dict):
|
901 |
+
for key, value in response.items():
|
902 |
+
formatted.append(f"**{key.title()}:**")
|
903 |
+
if isinstance(value, str) and len(value) > 300:
|
904 |
+
formatted.append(f"```\n{value[:300]}...\n```")
|
905 |
+
elif isinstance(value, list):
|
906 |
+
formatted.append(f"```\n{chr(10).join(value)}\n```")
|
907 |
+
else:
|
908 |
+
formatted.append(f"```\n{value}\n```")
|
909 |
+
else:
|
910 |
+
response_str = str(response)
|
911 |
+
if len(response_str) > 300:
|
912 |
+
formatted.append(f"```\n{response_str[:300]}...\n```")
|
913 |
+
else:
|
914 |
+
formatted.append(f"```\n{response_str}\n```")
|
915 |
+
|
916 |
+
formatted.append("")
|
917 |
+
|
918 |
+
return '\n'.join(formatted)
|
919 |
+
|
920 |
+
|
921 |
def format_alert_summary(raw_data):
|
922 |
"""Format alert summary"""
|
923 |
if not raw_data or 'alert_data' not in raw_data:
|
|
|
957 |
def run_workflow_ui(district):
|
958 |
"""Run workflow directly using internal functions"""
|
959 |
if not district:
|
960 |
+
return "β Please select a district", "", "", gr.File(visible=False)
|
961 |
|
962 |
try:
|
963 |
+
# Call the workflow function directly
|
964 |
request_obj = WorkflowRequest(state="bihar", district=district.lower())
|
965 |
|
966 |
# Use asyncio to run the async function
|
|
|
973 |
|
974 |
result = loop.run_until_complete(run_workflow(request_obj))
|
975 |
|
976 |
+
# Extract data
|
977 |
+
raw_data = result.get('raw_data', {})
|
978 |
+
agent_responses = raw_data.get('agent_responses', {})
|
979 |
+
|
980 |
+
# Format outputs with agent responses
|
981 |
+
workflow_output = format_workflow_output(result.get('message', ''), agent_responses)
|
982 |
+
alert_summary = format_alert_summary(raw_data)
|
983 |
+
agent_details = format_agent_responses(agent_responses)
|
984 |
csv_content = result.get('csv', '')
|
985 |
|
986 |
# Create CSV file if content exists
|
|
|
996 |
# Create a proper filename for download
|
997 |
display_name = f"bihar_alert_{district.lower()}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
|
998 |
|
999 |
+
return workflow_output, alert_summary, agent_details, gr.File(value=temp_filename, visible=True, label=display_name)
|
1000 |
else:
|
1001 |
+
return workflow_output, alert_summary, agent_details, gr.File(visible=False)
|
1002 |
|
1003 |
except Exception as e:
|
1004 |
error_msg = f"β Error: {str(e)}"
|
1005 |
logger.exception(f"UI workflow error: {e}")
|
1006 |
+
return error_msg, "", "", gr.File(visible=False)
|
1007 |
|
1008 |
# Create Gradio interface
|
1009 |
+
def create_gradio_interface():
|
1010 |
+
with gr.Blocks(
|
1011 |
+
title="BIHAR AgMCP - Agricultural Weather Alerts",
|
1012 |
+
theme=gr.themes.Soft()
|
1013 |
+
) as demo:
|
1014 |
+
|
1015 |
+
gr.Markdown("""
|
1016 |
+
# πΎ BIHAR AgMCP - Agricultural Weather Alert System
|
1017 |
+
|
1018 |
+
**AI-Powered Weather Alerts for Bihar Farmers**
|
1019 |
+
|
1020 |
+
Generate personalized weather alerts for agricultural activities in Bihar districts.
|
1021 |
+
|
1022 |
+
## How to Use:
|
1023 |
+
1. Select a Bihar district from the dropdown
|
1024 |
+
2. Click "Generate Weather Alert"
|
1025 |
+
3. View the formatted results and download CSV data
|
1026 |
+
""")
|
1027 |
+
|
1028 |
+
with gr.Row():
|
1029 |
+
with gr.Column(scale=1):
|
1030 |
+
district_input = gr.Dropdown(
|
1031 |
+
choices=BIHAR_DISTRICTS,
|
1032 |
+
label="π Select Bihar District",
|
1033 |
+
value="Patna"
|
1034 |
+
)
|
1035 |
+
|
1036 |
+
run_btn = gr.Button(
|
1037 |
+
"π Generate Weather Alert",
|
1038 |
+
variant="primary",
|
1039 |
+
size="lg"
|
1040 |
+
)
|
1041 |
+
|
1042 |
+
with gr.Row():
|
1043 |
+
with gr.Column(scale=1):
|
1044 |
+
workflow_output = gr.Markdown(
|
1045 |
+
label="π Workflow Output",
|
1046 |
+
value="Select a district and click the button to generate alerts..."
|
1047 |
+
)
|
1048 |
|
1049 |
+
with gr.Column(scale=1):
|
1050 |
+
alert_summary = gr.Markdown(
|
1051 |
+
label="π Alert Summary",
|
1052 |
+
value="Alert details will appear here..."
|
1053 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1054 |
|
1055 |
+
with gr.Row():
|
1056 |
+
agent_responses = gr.Markdown(
|
1057 |
+
label="π± Agent Messages",
|
1058 |
+
value="Agent responses will appear here..."
|
1059 |
)
|
1060 |
+
|
1061 |
+
csv_output = gr.File(
|
1062 |
+
label="π Download CSV Data",
|
1063 |
+
visible=False
|
1064 |
+
)
|
1065 |
+
|
1066 |
+
# Connect the button - now with 4 outputs
|
1067 |
+
run_btn.click(
|
1068 |
+
run_workflow_ui,
|
1069 |
+
inputs=[district_input],
|
1070 |
+
outputs=[workflow_output, alert_summary, agent_responses, csv_output]
|
1071 |
+
)
|
1072 |
|
1073 |
+
return demo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1074 |
|
1075 |
def run_fastapi():
|
1076 |
"""Run FastAPI server"""
|
|
|
1095 |
time.sleep(3)
|
1096 |
|
1097 |
# Launch Gradio interface
|
1098 |
+
demo = create_gradio_interface()
|
1099 |
demo.launch(
|
1100 |
server_name="0.0.0.0",
|
1101 |
server_port=7860,
|