import gradio as gr import os import json import traceback from data_service import DataAssessmentService from sheets_integration import SheetsLogger from datetime import datetime # Initialize services with error handling try: print("Initializing services...") service = DataAssessmentService(api_key=os.environ.get("OPENAI_API_KEY")) sheets_logger = SheetsLogger() print("Services initialized successfully") except Exception as e: print(f"Error initializing services: {str(e)}") print(traceback.format_exc()) raise # Constants DEPARTMENTS = { "Executive Management": "Executive Administration", "Education Support": "Education Support", "Medicine": "Medicine", "Cardiology": "Cardiology", "Gastroenterology": "Gastroenterology", "Medical Oncology": "Medical Oncology", "Hematology": "Hematology", "Operating Room": "Operating Room", "Surgery": "Surgery", "Orthopedics": "Orthopedics", "Obstetrics and Gynecology": "Obstetrics and Gynecology", "Ophthalmology": "Ophthalmology", "Ear, Nose, and Throat": "ENT", "Anesthesiology": "Anesthesiology", "Emergency Medicine & EMS": "Emergency Medicine", "Pediatrics": "Pediatrics", "Family Medicine & Preventive Medicine": "Family Medicine", "Psychiatry": "Psychiatry", "Physical Medicine & Rehabilitation": "PM&R", "Pathology": "Pathology", "Radiology": "Radiology", "Other": "Other" } FREQUENCIES = ["One-time request", "Weekly", "Monthly"] URGENCY = ["Within a week", "Within a month", "Within a year"] # Example requests for reference EXAMPLE_REQUESTS = """ ### Example 1: Clinical Data Request I need OPD patient statistics for the Cardiology department from January to June 2024, including daily patient volume, types of cardiac conditions (ICD-10 codes), average waiting times, and number of follow-up vs. new cases. This data will be used for department capacity planning and resource allocation. ### Example 2: Quality Improvement Request Requesting waiting time analysis for all OPD clinics for Q1 2024, including: - Registration to first nurse contact time - Nurse station to doctor examination time - Doctor examination duration - Time at pharmacy - Total visit duration Break down by day of week and time slots (morning/afternoon). This data will help identify service bottlenecks. ### Example 3: Department Performance Analysis Need Emergency Department performance data for March 2024: - Daily patient volume by triage level - Door-to-doctor times - Length of stay in ED - Admission rates - Transfer rates to other departments Purpose: Monthly performance review and staff allocation planning. """ # Function to format user-friendly summaries def format_user_summary(analysis_result): """Format analysis result into user-friendly summary""" available = [ report['report_type'] for report in analysis_result.get("required_reports", []) if report['category'] == "OPD" # Example: assuming OPD reports are in Web Data System ] data_lake = [ report['report_type'] for report in analysis_result.get("required_reports", []) if report['category'] != "OPD" # Example: assuming other categories require Data Lake queries ] unavailable = analysis_result.get("unavailable_data", []) interpretation = analysis_result.get("interpretation", "No interpretation available.") summary = [ "### Data Request Summary", f"**Request Analysis**: \n{interpretation}\n", "\n**Data Availability**:\n" ] if available: summary.append("✅ **Available in Web Data System**: ") for report in available: summary.append(f"- {report}") summary.append(f"\nEstimated processing time: **3 working days**\n") if data_lake: summary.append("🔄 **Requires Additional Database Query**: ") for report in data_lake: summary.append(f"- {report}") summary.append(f"\nEstimated processing time: **2–4 weeks**\n") if unavailable: summary.append("❌ **Not Currently Available**: ") for item in unavailable: summary.append(f"- {item}") summary.append("\nAction required: Schedule a meeting to discuss alternative data sources or solutions. We will follow up via email.\n") # Return formatted summary return "\n".join(summary) def process_request(name, employee_id, email, department, other_dept, request_details, frequency, urgency): print("=== Debug: Received Inputs ===") print(f"Name: {name}, Employee ID: {employee_id}, Email: {email}, Department: {department}, Request Details: {request_details}, Frequency: {frequency}, Urgency: {urgency}") if not all([name, employee_id, email, request_details, department, frequency, urgency]): return "Please fill in all required fields.", None final_department = other_dept if department == "Other" else department try: # Analyze request print("Calling GPT service...") result = service.assess_request(request_details) print(f"GPT response received: {result}") # Format summary user_summary = format_user_summary(result) print(f"User Summary: {user_summary}") # Log request sheet_data = { "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "name": name, "employee_id": employee_id, "email": email, "department": final_department, "request_details": request_details, "frequency": frequency, "urgency": urgency, "user_summary": user_summary, "system_analysis": json.dumps(result, ensure_ascii=False) } sheets_logger.log_request(sheet_data) return user_summary, result except Exception as e: return f"Error processing request: {str(e)}", None # Create Gradio interface with gr.Blocks() as demo: gr.Markdown("# Hospital Data Request System") gr.Markdown("Please fill in the following information to request data access.") with gr.Row(): with gr.Column(): name = gr.Textbox( label="Full Name*", placeholder="Enter your full name" ) employee_id = gr.Textbox( label="Employee ID*", placeholder="Enter your employee ID" ) email = gr.Textbox( label="Email*", placeholder="Enter your email for contact" ) with gr.Row(): with gr.Column(): department = gr.Dropdown( choices=list(DEPARTMENTS.keys()), label="Department*", info="Select your department", value=list(DEPARTMENTS.keys())[0] # Set default value ) other_dept = gr.Textbox( label="Other Department", placeholder="Specify your department if not in the list", visible=False ) def update_other_dept_visibility(dept): return gr.update(visible=(dept == "Other")) department.change( fn=update_other_dept_visibility, inputs=department, outputs=other_dept ) # Example requests section with gr.Accordion("📝 Click here to see example requests", open=False): gr.Markdown(EXAMPLE_REQUESTS) with gr.Row(): request_details = gr.Textbox( label="Request Details*", placeholder="Please describe in detail what data you need, including time period, specific parameters, etc.", lines=5 ) with gr.Row(): with gr.Column(): frequency = gr.Dropdown( choices=FREQUENCIES, label="Request Frequency*" ) urgency = gr.Dropdown( choices=URGENCY, label="Urgency Level*" ) submit_btn = gr.Button("Submit Request", variant="primary") user_output = gr.Markdown("", label="Request Summary") tech_output = gr.JSON(label="Technical Analysis (For Data Team)") submit_btn.click( fn=process_request, inputs=[ name, employee_id, email, department, other_dept, request_details, frequency, urgency ], outputs=[user_output, tech_output] ) gr.Markdown( """ ### Notes: - Fields marked with * are required - Provide detailed information about the data you need - Include specific time periods and parameters - Clearly state the purpose of your request - All communications will be sent to the provided email """ ) if __name__ == "__main__": demo.launch()