Rathapoom commited on
Commit
dc5209b
·
verified ·
1 Parent(s): 21f7901

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -60
app.py CHANGED
@@ -1,40 +1,14 @@
1
  import gradio as gr
2
  import os
3
  import json
4
- import pandas as pd
5
  from data_service import DataAssessmentService
6
- from datetime import datetime
7
- import gspread
8
- from oauth2client.service_account import ServiceAccountCredentials
9
  from sheets_integration import SheetsLogger
 
10
 
11
  # Initialize services
12
  service = DataAssessmentService(api_key=os.environ.get("OPENAI_API_KEY"))
13
  sheets_logger = SheetsLogger()
14
 
15
- EXAMPLE_REQUESTS = """
16
- ### Example 1: Clinical Data Request
17
- 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.
18
-
19
- ### Example 2: Quality Improvement Request
20
- Requesting waiting time analysis for all OPD clinics for Q1 2024, including:
21
- - Registration to first nurse contact time
22
- - Nurse station to doctor examination time
23
- - Doctor examination duration
24
- - Time at pharmacy
25
- - Total visit duration
26
- Break down by day of week and time slots (morning/afternoon). This data will help identify service bottlenecks.
27
-
28
- ### Example 3: Department Performance Analysis
29
- Need Emergency Department performance data for March 2024:
30
- - Daily patient volume by triage level
31
- - Door-to-doctor times
32
- - Length of stay in ED
33
- - Admission rates
34
- - Transfer rates to other departments
35
- Purpose: Monthly performance review and staff allocation planning.
36
- """
37
-
38
  # Department mapping from abbreviations to full names
39
  DEPARTMENTS = {
40
  "Executive Management": "บริหาร ผอ รอง ผู้ช่วย",
@@ -76,34 +50,102 @@ FREQUENCIES = ["One-time request", "Weekly", "Monthly"]
76
  # Urgency options
77
  URGENCY = ["Within a week", "Within a month", "Within a year"]
78
 
79
- def save_to_sheet(data):
80
- """Save request data to Google Sheet"""
81
- # TODO: Implement Google Sheets integration
82
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  def process_request(name, employee_id, email, department, other_dept, request_details, frequency, urgency):
 
 
 
 
 
85
  # Combine department info
86
  final_department = other_dept if department == "Other" else department
87
 
88
- # Process the request through GPT
89
- result = service.assess_request(request_details)
90
-
91
- # Prepare data for logging
92
- request_data = {
93
- "name": name,
94
- "employee_id": employee_id,
95
- "email": email,
96
- "department": final_department,
97
- "request_details": request_details,
98
- "frequency": frequency,
99
- "urgency": urgency,
100
- "system_response": json.dumps(result, ensure_ascii=False)
101
- }
102
-
103
- # Log to Google Sheets
104
- sheets_logger.log_request(request_data)
105
-
106
- return result
 
 
 
 
 
 
 
 
 
 
107
 
108
  # Create Gradio interface
109
  with gr.Blocks() as demo:
@@ -112,16 +154,29 @@ with gr.Blocks() as demo:
112
 
113
  with gr.Row():
114
  with gr.Column():
115
- name = gr.Textbox(label="Full Name", placeholder="Enter your full name")
116
- employee_id = gr.Textbox(label="Employee ID", placeholder="Enter your employee ID")
117
- email = gr.Textbox(label="Email", placeholder="Enter your email for contact")
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  with gr.Row():
120
  with gr.Column():
121
  department = gr.Dropdown(
122
- choices=list(DEPARTMENTS.keys()) + ["Other"],
123
  label="Department",
124
- info="Select your department"
 
125
  )
126
  other_dept = gr.Textbox(
127
  label="Other Department",
@@ -143,7 +198,8 @@ with gr.Blocks() as demo:
143
  request_details = gr.Textbox(
144
  label="Request Details",
145
  placeholder="Please describe in detail what data you need, including time period, specific parameters, etc.",
146
- lines=5
 
147
  )
148
 
149
  with gr.Row():
@@ -151,22 +207,35 @@ with gr.Blocks() as demo:
151
  frequency = gr.Dropdown(
152
  choices=FREQUENCIES,
153
  label="Request Frequency",
154
- info="How often do you need this data?"
 
155
  )
156
  urgency = gr.Dropdown(
157
  choices=URGENCY,
158
  label="Urgency Level",
159
- info="How urgent is your request?"
 
160
  )
161
 
162
  submit_btn = gr.Button("Submit Request")
163
- output = gr.JSON(label="Analysis Result")
 
 
 
 
 
 
 
 
 
 
 
164
 
165
  submit_btn.click(
166
  fn=process_request,
167
  inputs=[name, employee_id, email, department, other_dept,
168
  request_details, frequency, urgency],
169
- outputs=[output]
170
  )
171
 
172
  gr.Markdown("""
 
1
  import gradio as gr
2
  import os
3
  import json
 
4
  from data_service import DataAssessmentService
 
 
 
5
  from sheets_integration import SheetsLogger
6
+ from datetime import datetime
7
 
8
  # Initialize services
9
  service = DataAssessmentService(api_key=os.environ.get("OPENAI_API_KEY"))
10
  sheets_logger = SheetsLogger()
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  # Department mapping from abbreviations to full names
13
  DEPARTMENTS = {
14
  "Executive Management": "บริหาร ผอ รอง ผู้ช่วย",
 
50
  # Urgency options
51
  URGENCY = ["Within a week", "Within a month", "Within a year"]
52
 
53
+ # Example requests for reference
54
+ EXAMPLE_REQUESTS = """
55
+ ### Example 1: Clinical Data Request
56
+ 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.
57
+
58
+ ### Example 2: Quality Improvement Request
59
+ Requesting waiting time analysis for all OPD clinics for Q1 2024, including:
60
+ - Registration to first nurse contact time
61
+ - Nurse station to doctor examination time
62
+ - Doctor examination duration
63
+ - Time at pharmacy
64
+ - Total visit duration
65
+ Break down by day of week and time slots (morning/afternoon). This data will help identify service bottlenecks.
66
+
67
+ ### Example 3: Department Performance Analysis
68
+ Need Emergency Department performance data for March 2024:
69
+ - Daily patient volume by triage level
70
+ - Door-to-doctor times
71
+ - Length of stay in ED
72
+ - Admission rates
73
+ - Transfer rates to other departments
74
+ Purpose: Monthly performance review and staff allocation planning.
75
+ """
76
+
77
+ def format_user_summary(analysis_result):
78
+ """Format analysis result into user-friendly summary"""
79
+ available = analysis_result.get("data_availability", {}).get("available_reports", [])
80
+ data_lake = analysis_result.get("data_lake_requirements", {}).get("reports_needed", [])
81
+ unavailable = analysis_result.get("unavailable_data", [])
82
+
83
+ interpretation = analysis_result.get("request_analysis", {}).get("interpretation", "")
84
+
85
+ summary = [
86
+ "### Summary of Your Request",
87
+ f"**What you need**: {interpretation}\n",
88
+ "\n**Data Availability Status:**\n"
89
+ ]
90
+
91
+ if available:
92
+ summary.append("✅ **Available in Web Data System:**")
93
+ for report in available:
94
+ summary.append(f"- {report['name']}")
95
+ summary.append(f"\nEstimated processing time: 3 working days\n")
96
+
97
+ if data_lake:
98
+ summary.append("🔄 **Requires Additional Database Query:**")
99
+ for report in data_lake:
100
+ summary.append(f"- {report['report_type']}")
101
+ summary.append(f"\nEstimated processing time: 2 weeks\n")
102
+
103
+ if unavailable:
104
+ summary.append("❌ **Data Not Currently Available:**")
105
+ for item in unavailable:
106
+ summary.append(f"- {item['report_type']}")
107
+ summary.append("\nRecommendation: Schedule a meeting to discuss alternative data sources or solutions\n")
108
+
109
+ return "\n".join(summary)
110
 
111
  def process_request(name, employee_id, email, department, other_dept, request_details, frequency, urgency):
112
+ """Process the data request and return both user and technical responses"""
113
+ # Validate inputs
114
+ if not all([name, employee_id, email, request_details]):
115
+ return "Please fill in all required fields.", None
116
+
117
  # Combine department info
118
  final_department = other_dept if department == "Other" else department
119
 
120
+ try:
121
+ # Process the request through GPT
122
+ result = service.assess_request(request_details)
123
+
124
+ # Create user-friendly summary
125
+ user_summary = format_user_summary(result)
126
+
127
+ # Prepare data for logging
128
+ sheet_data = {
129
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
130
+ "name": name,
131
+ "employee_id": employee_id,
132
+ "email": email,
133
+ "department": final_department,
134
+ "request_details": request_details,
135
+ "frequency": frequency,
136
+ "urgency": urgency,
137
+ "user_summary": user_summary,
138
+ "system_analysis": json.dumps(result, ensure_ascii=False)
139
+ }
140
+
141
+ # Log to Google Sheets
142
+ sheets_logger.log_request(sheet_data)
143
+
144
+ return user_summary, result
145
+
146
+ except Exception as e:
147
+ error_message = f"Error processing request: {str(e)}"
148
+ return error_message, None
149
 
150
  # Create Gradio interface
151
  with gr.Blocks() as demo:
 
154
 
155
  with gr.Row():
156
  with gr.Column():
157
+ name = gr.Textbox(
158
+ label="Full Name",
159
+ placeholder="Enter your full name",
160
+ required=True
161
+ )
162
+ employee_id = gr.Textbox(
163
+ label="Employee ID",
164
+ placeholder="Enter your employee ID",
165
+ required=True
166
+ )
167
+ email = gr.Textbox(
168
+ label="Email",
169
+ placeholder="Enter your email for contact",
170
+ required=True
171
+ )
172
 
173
  with gr.Row():
174
  with gr.Column():
175
  department = gr.Dropdown(
176
+ choices=list(DEPARTMENTS.keys()),
177
  label="Department",
178
+ info="Select your department",
179
+ required=True
180
  )
181
  other_dept = gr.Textbox(
182
  label="Other Department",
 
198
  request_details = gr.Textbox(
199
  label="Request Details",
200
  placeholder="Please describe in detail what data you need, including time period, specific parameters, etc.",
201
+ lines=5,
202
+ required=True
203
  )
204
 
205
  with gr.Row():
 
207
  frequency = gr.Dropdown(
208
  choices=FREQUENCIES,
209
  label="Request Frequency",
210
+ info="How often do you need this data?",
211
+ required=True
212
  )
213
  urgency = gr.Dropdown(
214
  choices=URGENCY,
215
  label="Urgency Level",
216
+ info="How urgent is your request?",
217
+ required=True
218
  )
219
 
220
  submit_btn = gr.Button("Submit Request")
221
+
222
+ # Add user-friendly summary output
223
+ with gr.Row():
224
+ user_output = gr.Markdown(
225
+ label="Request Summary",
226
+ value="Your request summary will appear here...",
227
+ show_label=True
228
+ )
229
+
230
+ # Technical analysis output (for data team)
231
+ with gr.Accordion("Technical Analysis (For Data Team)", open=False):
232
+ tech_output = gr.JSON(label="Detailed Analysis")
233
 
234
  submit_btn.click(
235
  fn=process_request,
236
  inputs=[name, employee_id, email, department, other_dept,
237
  request_details, frequency, urgency],
238
+ outputs=[user_output, tech_output]
239
  )
240
 
241
  gr.Markdown("""