File size: 8,289 Bytes
5925eac
 
 
 
842fce5
dc5209b
5925eac
842fce5
5925eac
842fce5
5925eac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f169455
dc5209b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5925eac
 
dc5209b
 
 
 
5925eac
 
 
dc5209b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5925eac
 
 
 
 
 
 
 
dc5209b
f169455
 
dc5209b
 
f169455
 
dc5209b
 
f169455
 
dc5209b
5925eac
 
 
 
dc5209b
f169455
 
5925eac
 
 
 
 
 
 
f169455
 
 
 
 
 
c0d20a2
 
 
5925eac
 
f169455
5925eac
f169455
5925eac
 
 
 
 
 
f169455
5925eac
 
 
f169455
5925eac
 
 
dc5209b
 
f169455
dc5209b
 
f169455
5925eac
 
 
 
 
dc5209b
5925eac
 
 
 
f169455
5925eac
c0d20a2
 
5925eac
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import gradio as gr
import os
import json
from data_service import DataAssessmentService
from sheets_integration import SheetsLogger
from datetime import datetime

# Initialize services
service = DataAssessmentService(api_key=os.environ.get("OPENAI_API_KEY"))
sheets_logger = SheetsLogger()

# Department mapping from abbreviations to full names
DEPARTMENTS = {
    "Executive Management": "บริหาร ผอ รอง ผู้ช่วย",
    "Education Support": "สนับสนุนการศึกษา",
    "Medicine": "MED",
    "Cardiology": "Cardio",
    "Gastroenterology": "GI",
    "Medical Oncology": "Onco MED",
    "Hematology": "Hematology",
    "Operating Room": "OR",
    "Surgery": "Sx",
    "Orthopedics": "Ortho",
    "Obstetrics and Gynecology": "OBgyne",
    "Ophthalmology": "Oph",
    "Ear, Nose, and Throat": "ENT",
    "Anesthesiology": "Anes",
    "Emergency Medicine & EMS": "ER and EMS",
    "Pediatrics": "PED",
    "Family Medicine & Preventive Medicine": "GP Fammed preventive med",
    "Psychiatry": "Psych",
    "Physical Medicine & Rehabilitation": "PM&R Physiotherapy",
    "Pathology": "Patho",
    "Radiology": "Xray",
    "Radiation Oncology": "Onco radiology",
    "Cyclotron": "Cyclotron",
    "Inpatient Department": "IPD",
    "Outpatient Department": "OPD",
    "Pharmacy": "Pharmacy",
    "Dentistry": "dentistry",
    "Nutrition": "Nutrition",
    "Medical Records": "เวชระเบียน",
    "Finance": "การเงิน",
    "Other": "Other"
}

# Frequency options
FREQUENCIES = ["One-time request", "Weekly", "Monthly"]

# Urgency options
URGENCY = ["Within a week", "Within a month", "Within a year"]

# Example requests
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 format_user_summary(analysis_result):
    """Format analysis result into user-friendly summary"""
    available = analysis_result.get("data_availability", {}).get("available_reports", [])
    data_lake = analysis_result.get("data_lake_requirements", {}).get("reports_needed", [])
    unavailable = analysis_result.get("unavailable_data", [])
    
    interpretation = analysis_result.get("request_analysis", {}).get("interpretation", "")
    
    summary = [
        "### Summary of Your Request",
        f"**What you need**: {interpretation}\n",
        "\n**Data Availability Status:**\n"
    ]
    
    if available:
        summary.append("✅ **Available in Web Data System:**")
        for report in available:
            summary.append(f"- {report['name']}")
        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['report_type']}")
        summary.append(f"\nEstimated processing time: 2 weeks\n")
    
    if unavailable:
        summary.append("❌ **Data Not Currently Available:**")
        for item in unavailable:
            summary.append(f"- {item['report_type']}")
        summary.append("\nRecommendation: Schedule a meeting to discuss alternative data sources or solutions\n")
    
    return "\n".join(summary)

def process_request(name, employee_id, email, department, other_dept, request_details, frequency, urgency):
    # Validate inputs
    if not all([name, employee_id, email, request_details]):
        return "Please fill in all required fields.", None
        
    # Combine department info
    final_department = other_dept if department == "Other" else department
    
    try:
        # Process the request through GPT
        result = service.assess_request(request_details)
        
        # Create user-friendly summary
        user_summary = format_user_summary(result)
        
        # Prepare data for logging
        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)
        }
        
        # Log to Google Sheets
        sheets_logger.log_request(sheet_data)
        
        return user_summary, result
        
    except Exception as e:
        error_message = f"Error processing request: {str(e)}"
        return error_message, 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"
            )
            other_dept = gr.Textbox(
                label="Other Department",
                placeholder="Specify your department if not in the list",
                visible=False
            )
    
    department.change(
        fn=lambda x: gr.update(visible=x=="Other"),
        inputs=[department],
        outputs=[other_dept]
    )
    
    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")
    
    with gr.Row():
        user_output = gr.Markdown(label="Request Summary")
    
    with gr.Accordion("Technical Analysis (For Data Team)", open=False):
        tech_output = gr.JSON()
    
    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()