Spaces:
Sleeping
Sleeping
Update appbackup.py
Browse files- appbackup.py +227 -52
appbackup.py
CHANGED
@@ -1,73 +1,248 @@
|
|
1 |
-
# app.py
|
2 |
import gradio as gr
|
3 |
import os
|
4 |
-
from data_service import DataAssessmentService
|
5 |
import json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
-
|
8 |
-
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
12 |
try:
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
except Exception as e:
|
16 |
-
return
|
17 |
-
"status": "error",
|
18 |
-
"message": str(e)
|
19 |
-
}, indent=2)
|
20 |
-
|
21 |
-
demo_text = """Example requests:
|
22 |
-
1. "Show me OPD patients from January 2024, including their diagnoses and waiting times"
|
23 |
-
2. "Get all emergency surgeries from last month with their durations and costs"
|
24 |
-
3. "List top 100 diagnoses from pediatric clinic in 2023"
|
25 |
-
"""
|
26 |
|
27 |
# Create Gradio interface
|
28 |
with gr.Blocks() as demo:
|
29 |
-
gr.Markdown("# Hospital Data
|
30 |
-
gr.Markdown("
|
31 |
-
|
32 |
with gr.Row():
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
with gr.Row():
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
|
|
|
|
|
|
|
|
|
|
43 |
with gr.Row():
|
44 |
-
|
45 |
-
label="
|
46 |
-
|
47 |
-
|
48 |
)
|
49 |
-
|
50 |
-
with gr.
|
51 |
-
gr.
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
submit_btn.click(
|
54 |
fn=process_request,
|
55 |
-
inputs=[
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
fn=lambda: (None, None),
|
61 |
-
inputs=[],
|
62 |
-
outputs=[request_input, output]
|
63 |
)
|
64 |
|
65 |
-
gr.Markdown(
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
|
|
|
|
|
|
|
|
71 |
|
72 |
if __name__ == "__main__":
|
73 |
-
demo.launch()
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import os
|
|
|
3 |
import json
|
4 |
+
import traceback
|
5 |
+
from data_service import DataAssessmentService
|
6 |
+
from sheets_integration import SheetsLogger
|
7 |
+
from datetime import datetime
|
8 |
+
|
9 |
+
# Initialize services with error handling
|
10 |
+
try:
|
11 |
+
print("Initializing services...")
|
12 |
+
service = DataAssessmentService(api_key=os.environ.get("OPENAI_API_KEY"))
|
13 |
+
sheets_logger = SheetsLogger()
|
14 |
+
print("Services initialized successfully")
|
15 |
+
except Exception as e:
|
16 |
+
print(f"Error initializing services: {str(e)}")
|
17 |
+
print(traceback.format_exc())
|
18 |
+
raise
|
19 |
+
|
20 |
+
# Constants
|
21 |
+
DEPARTMENTS = {
|
22 |
+
"Executive Management": "Executive Administration",
|
23 |
+
"Education Support": "Education Support",
|
24 |
+
"Medicine": "Medicine",
|
25 |
+
"Cardiology": "Cardiology",
|
26 |
+
"Gastroenterology": "Gastroenterology",
|
27 |
+
"Medical Oncology": "Medical Oncology",
|
28 |
+
"Hematology": "Hematology",
|
29 |
+
"Operating Room": "Operating Room",
|
30 |
+
"Surgery": "Surgery",
|
31 |
+
"Orthopedics": "Orthopedics",
|
32 |
+
"Obstetrics and Gynecology": "Obstetrics and Gynecology",
|
33 |
+
"Ophthalmology": "Ophthalmology",
|
34 |
+
"Ear, Nose, and Throat": "ENT",
|
35 |
+
"Anesthesiology": "Anesthesiology",
|
36 |
+
"Emergency Medicine & EMS": "Emergency Medicine",
|
37 |
+
"Pediatrics": "Pediatrics",
|
38 |
+
"Family Medicine & Preventive Medicine": "Family Medicine",
|
39 |
+
"Psychiatry": "Psychiatry",
|
40 |
+
"Physical Medicine & Rehabilitation": "PM&R",
|
41 |
+
"Pathology": "Pathology",
|
42 |
+
"Radiology": "Radiology",
|
43 |
+
"Other": "Other"
|
44 |
+
}
|
45 |
+
|
46 |
+
FREQUENCIES = ["One-time request", "Weekly", "Monthly"]
|
47 |
+
URGENCY = ["Within a week", "Within a month", "Within a year"]
|
48 |
+
|
49 |
+
# Example requests for reference
|
50 |
+
EXAMPLE_REQUESTS = """
|
51 |
+
### Example 1: Clinical Data Request
|
52 |
+
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.
|
53 |
+
|
54 |
+
### Example 2: Quality Improvement Request
|
55 |
+
Requesting waiting time analysis for all OPD clinics for Q1 2024, including:
|
56 |
+
- Registration to first nurse contact time
|
57 |
+
- Nurse station to doctor examination time
|
58 |
+
- Doctor examination duration
|
59 |
+
- Time at pharmacy
|
60 |
+
- Total visit duration
|
61 |
+
Break down by day of week and time slots (morning/afternoon). This data will help identify service bottlenecks.
|
62 |
+
|
63 |
+
### Example 3: Department Performance Analysis
|
64 |
+
Need Emergency Department performance data for March 2024:
|
65 |
+
- Daily patient volume by triage level
|
66 |
+
- Door-to-doctor times
|
67 |
+
- Length of stay in ED
|
68 |
+
- Admission rates
|
69 |
+
- Transfer rates to other departments
|
70 |
+
Purpose: Monthly performance review and staff allocation planning.
|
71 |
+
"""
|
72 |
+
# Function to format user-friendly summaries
|
73 |
+
def format_user_summary(analysis_result):
|
74 |
+
"""Format analysis result into user-friendly summary"""
|
75 |
+
available = [
|
76 |
+
report['report_type']
|
77 |
+
for report in analysis_result.get("required_reports", [])
|
78 |
+
if report['category'] == "OPD" # Example: assuming OPD reports are in Web Data System
|
79 |
+
]
|
80 |
+
data_lake = [
|
81 |
+
report['report_type']
|
82 |
+
for report in analysis_result.get("required_reports", [])
|
83 |
+
if report['category'] != "OPD" # Example: assuming other categories require Data Lake queries
|
84 |
+
]
|
85 |
+
unavailable = analysis_result.get("unavailable_data", [])
|
86 |
+
|
87 |
+
interpretation = analysis_result.get("interpretation", "No interpretation available.")
|
88 |
+
|
89 |
+
summary = [
|
90 |
+
"### Data Request Summary",
|
91 |
+
f"**Request Analysis**: \n{interpretation}\n",
|
92 |
+
"\n**Data Availability**:\n"
|
93 |
+
]
|
94 |
+
|
95 |
+
if available:
|
96 |
+
summary.append("β
**Available in Web Data System**: ")
|
97 |
+
for report in available:
|
98 |
+
summary.append(f"- {report}")
|
99 |
+
summary.append(f"\nEstimated processing time: **3 working days**\n")
|
100 |
+
|
101 |
+
if data_lake:
|
102 |
+
summary.append("π **Requires Additional Database Query**: ")
|
103 |
+
for report in data_lake:
|
104 |
+
summary.append(f"- {report}")
|
105 |
+
summary.append(f"\nEstimated processing time: **2β4 weeks**\n")
|
106 |
+
|
107 |
+
if unavailable:
|
108 |
+
summary.append("β **Not Currently Available**: ")
|
109 |
+
for item in unavailable:
|
110 |
+
summary.append(f"- {item}")
|
111 |
+
summary.append("\nAction required: Schedule a meeting to discuss alternative data sources or solutions. We will follow up via email.\n")
|
112 |
+
|
113 |
+
# Return formatted summary
|
114 |
+
return "\n".join(summary)
|
115 |
|
116 |
+
|
117 |
+
def process_request(name, employee_id, email, department, other_dept, request_details, frequency, urgency):
|
118 |
+
print("=== Debug: Received Inputs ===")
|
119 |
+
print(f"Name: {name}, Employee ID: {employee_id}, Email: {email}, Department: {department}, Request Details: {request_details}, Frequency: {frequency}, Urgency: {urgency}")
|
120 |
|
121 |
+
if not all([name, employee_id, email, request_details, department, frequency, urgency]):
|
122 |
+
return "Please fill in all required fields.", None
|
123 |
+
|
124 |
+
final_department = other_dept if department == "Other" else department
|
125 |
+
|
126 |
try:
|
127 |
+
# Analyze request
|
128 |
+
print("Calling GPT service...")
|
129 |
+
result = service.assess_request(request_details)
|
130 |
+
print(f"GPT response received: {result}")
|
131 |
+
|
132 |
+
# Format summary
|
133 |
+
user_summary = format_user_summary(result)
|
134 |
+
print(f"User Summary: {user_summary}")
|
135 |
+
|
136 |
+
# Log request
|
137 |
+
sheet_data = {
|
138 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
139 |
+
"name": name,
|
140 |
+
"employee_id": employee_id,
|
141 |
+
"email": email,
|
142 |
+
"department": final_department,
|
143 |
+
"request_details": request_details,
|
144 |
+
"frequency": frequency,
|
145 |
+
"urgency": urgency,
|
146 |
+
"user_summary": user_summary,
|
147 |
+
"system_analysis": json.dumps(result, ensure_ascii=False)
|
148 |
+
}
|
149 |
+
sheets_logger.log_request(sheet_data)
|
150 |
+
|
151 |
+
return user_summary, result
|
152 |
except Exception as e:
|
153 |
+
return f"Error processing request: {str(e)}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
|
155 |
# Create Gradio interface
|
156 |
with gr.Blocks() as demo:
|
157 |
+
gr.Markdown("# Hospital Data Request System")
|
158 |
+
gr.Markdown("Please fill in the following information to request data access.")
|
159 |
+
|
160 |
with gr.Row():
|
161 |
+
with gr.Column():
|
162 |
+
name = gr.Textbox(
|
163 |
+
label="Full Name*",
|
164 |
+
placeholder="Enter your full name"
|
165 |
+
)
|
166 |
+
employee_id = gr.Textbox(
|
167 |
+
label="Employee ID*",
|
168 |
+
placeholder="Enter your employee ID"
|
169 |
+
)
|
170 |
+
email = gr.Textbox(
|
171 |
+
label="Email*",
|
172 |
+
placeholder="Enter your email for contact"
|
173 |
+
)
|
174 |
+
|
175 |
with gr.Row():
|
176 |
+
with gr.Column():
|
177 |
+
department = gr.Dropdown(
|
178 |
+
choices=list(DEPARTMENTS.keys()),
|
179 |
+
label="Department*",
|
180 |
+
info="Select your department",
|
181 |
+
value=list(DEPARTMENTS.keys())[0] # Set default value
|
182 |
+
)
|
183 |
+
other_dept = gr.Textbox(
|
184 |
+
label="Other Department",
|
185 |
+
placeholder="Specify your department if not in the list",
|
186 |
+
visible=False
|
187 |
+
)
|
188 |
+
|
189 |
+
def update_other_dept_visibility(dept):
|
190 |
+
return gr.update(visible=(dept == "Other"))
|
191 |
+
|
192 |
+
department.change(
|
193 |
+
fn=update_other_dept_visibility,
|
194 |
+
inputs=department,
|
195 |
+
outputs=other_dept
|
196 |
+
)
|
197 |
|
198 |
+
# Example requests section
|
199 |
+
with gr.Accordion("π Click here to see example requests", open=False):
|
200 |
+
gr.Markdown(EXAMPLE_REQUESTS)
|
201 |
+
|
202 |
+
|
203 |
with gr.Row():
|
204 |
+
request_details = gr.Textbox(
|
205 |
+
label="Request Details*",
|
206 |
+
placeholder="Please describe in detail what data you need, including time period, specific parameters, etc.",
|
207 |
+
lines=5
|
208 |
)
|
209 |
+
|
210 |
+
with gr.Row():
|
211 |
+
with gr.Column():
|
212 |
+
frequency = gr.Dropdown(
|
213 |
+
choices=FREQUENCIES,
|
214 |
+
label="Request Frequency*"
|
215 |
+
)
|
216 |
+
urgency = gr.Dropdown(
|
217 |
+
choices=URGENCY,
|
218 |
+
label="Urgency Level*"
|
219 |
+
)
|
220 |
+
|
221 |
+
submit_btn = gr.Button("Submit Request", variant="primary")
|
222 |
+
|
223 |
+
user_output = gr.Markdown("", label="Request Summary")
|
224 |
+
tech_output = gr.JSON(label="Technical Analysis (For Data Team)")
|
225 |
+
|
226 |
submit_btn.click(
|
227 |
fn=process_request,
|
228 |
+
inputs=[
|
229 |
+
name, employee_id, email, department, other_dept,
|
230 |
+
request_details, frequency, urgency
|
231 |
+
],
|
232 |
+
outputs=[user_output, tech_output]
|
|
|
|
|
|
|
233 |
)
|
234 |
|
235 |
+
gr.Markdown(
|
236 |
+
"""
|
237 |
+
### Notes:
|
238 |
+
- Fields marked with * are required
|
239 |
+
- Provide detailed information about the data you need
|
240 |
+
- Include specific time periods and parameters
|
241 |
+
- Clearly state the purpose of your request
|
242 |
+
- All communications will be sent to the provided email
|
243 |
+
"""
|
244 |
+
)
|
245 |
|
246 |
if __name__ == "__main__":
|
247 |
+
demo.launch()
|
248 |
+
|