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. """ def process_request(name, employee_id, email, department, other_dept, request_details, frequency, urgency): """Process the data request and return both user and technical responses""" print("=== Debug: Received Inputs ===") print("\nProcessing new request:") print(f"Name: {name}") print(f"Employee ID: {employee_id}") print(f"Email: {email}") print(f"Department: {department}") print(f"Other Dept: {other_dept}") print(f"Request Details: {request_details}") print(f"Frequency: {frequency}") print(f"Urgency: {urgency}") # Validate inputs if not all([name, employee_id, email, request_details, department, frequency, urgency]): print("Validation failed - missing required fields") return "Please fill in all required fields.", None try: # Process the request through GPT print("Calling GPT service...") result = service.assess_request(request_details) print(f"GPT service response received: {result}") if "error" in result: return f"Error analyzing request: {result['error']}", None # Create user-friendly summary user_summary = f""" ### Data Request Summary **From:** {name} ({department}) **Request Type:** {frequency} | Urgency: {urgency} **Analysis:** {result.get('request_analysis', {}).get('interpretation', 'No interpretation available')} **Data Availability:** """ # Add available reports available = result.get('data_availability', {}).get('available_reports', []) if available: user_summary += "\nāœ… **Available in Web Data:**\n" for report in available: user_summary += f"- {report['name']}\n" user_summary += "\nEstimated processing time: 3 working days\n" # Add data lake requirements data_lake = result.get('data_lake_requirements', {}).get('reports_needed', []) if data_lake: user_summary += "\nšŸ”„ **Requires Additional Database Query:**\n" for report in data_lake: user_summary += f"- {report['report_type']}\n" user_summary += "\nEstimated processing time: 2 weeks\n" # Add unavailable data unavailable = result.get('unavailable_data', []) if unavailable: user_summary += "\nāŒ **Data Not Currently Available:**\n" for item in unavailable: user_summary += f"- {item['report_type']}\n" user_summary += "\nRecommendation: Schedule a meeting to discuss alternatives\n" # Log to sheets print("Logging to Google Sheets...") sheet_data = { "name": name, "employee_id": employee_id, "email": email, "department": other_dept if department == "Other" else 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) print("Request logged successfully") return user_summary, result except Exception as e: error_msg = f"Error processing request: {str(e)}" print(error_msg) print(traceback.format_exc()) return error_msg, 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", value="" ) employee_id = gr.Textbox( label="Employee ID*", placeholder="Enter your employee ID", value="" ) email = gr.Textbox( label="Email*", placeholder="Enter your email for contact", value="" ) with gr.Row(): with gr.Column(): department = gr.Dropdown( choices=list(DEPARTMENTS.keys()), label="Department*", info="Select your department", value=list(DEPARTMENTS.keys())[0] ) other_dept = gr.Textbox( label="Other Department", placeholder="Specify your department if not in the list", visible=False, value="" ) # Handle department change department.change( fn=lambda x: gr.update(visible=(x == "Other")), 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, value="" ) with gr.Row(): with gr.Column(): frequency = gr.Dropdown( choices=FREQUENCIES, label="Request Frequency*", value=FREQUENCIES[0] ) urgency = gr.Dropdown( choices=URGENCY, label="Urgency Level*", value=URGENCY[0] ) # Submit button submit_btn = gr.Button("Submit Request") # Output sections with gr.Row(): user_output = gr.Markdown(label="Request Summary") with gr.Accordion("Technical Analysis (For Data Team)", open=False): tech_output = gr.JSON() # Connect the submit button to the process function 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 - Please 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()