Update app.py
Browse files
app.py
CHANGED
@@ -35,23 +35,35 @@ def file_hash(path: str) -> str:
|
|
35 |
return hashlib.md5(f.read()).hexdigest()
|
36 |
|
37 |
def clean_response(text: str) -> str:
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
text = re.sub(r"\[.*?\]|\bNone\b", "", text, flags=re.DOTALL)
|
40 |
text = re.sub(r"\n{3,}", "\n\n", text)
|
41 |
text = re.sub(r"[^\n#\-\*\w\s\.,:\(\)]+", "", text)
|
42 |
return text.strip()
|
43 |
|
44 |
def parse_excel_to_prompts(file_path: str) -> List[str]:
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
for
|
52 |
-
records
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
55 |
Patient Booking Number: {booking}
|
56 |
|
57 |
Instructions:
|
@@ -72,84 +84,181 @@ Data:
|
|
72 |
### Urgent Follow-up
|
73 |
- ...
|
74 |
"""
|
75 |
-
|
76 |
-
|
|
|
|
|
77 |
|
78 |
def init_agent():
|
79 |
default_tool_path = os.path.abspath("data/new_tool.json")
|
80 |
target_tool_path = os.path.join(tool_cache_dir, "new_tool.json")
|
|
|
81 |
if not os.path.exists(target_tool_path):
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
|
96 |
def create_ui(agent):
|
97 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
98 |
-
gr.Markdown("
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
def analyze(message: str, history: List[dict], file) -> tuple:
|
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 |
return demo
|
145 |
|
146 |
if __name__ == "__main__":
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
return hashlib.md5(f.read()).hexdigest()
|
36 |
|
37 |
def clean_response(text: str) -> str:
|
38 |
+
try:
|
39 |
+
# First try to encode/decode to handle any surrogate pairs
|
40 |
+
text = text.encode('utf-8', 'surrogatepass').decode('utf-8')
|
41 |
+
except UnicodeEncodeError:
|
42 |
+
# Fallback to replace strategy if there are invalid characters
|
43 |
+
text = text.encode('utf-8', 'replace').decode('utf-8')
|
44 |
+
|
45 |
+
# Additional cleaning
|
46 |
text = re.sub(r"\[.*?\]|\bNone\b", "", text, flags=re.DOTALL)
|
47 |
text = re.sub(r"\n{3,}", "\n\n", text)
|
48 |
text = re.sub(r"[^\n#\-\*\w\s\.,:\(\)]+", "", text)
|
49 |
return text.strip()
|
50 |
|
51 |
def parse_excel_to_prompts(file_path: str) -> List[str]:
|
52 |
+
try:
|
53 |
+
xl = pd.ExcelFile(file_path)
|
54 |
+
df = xl.parse(xl.sheet_names[0], header=0).fillna("")
|
55 |
+
groups = df.groupby("Booking Number")
|
56 |
+
prompts = []
|
57 |
+
|
58 |
+
for booking, group in groups:
|
59 |
+
records = []
|
60 |
+
for _, row in group.iterrows():
|
61 |
+
record = f"- {row['Form Name']}: {row['Form Item']} = {row['Item Response']} ({row['Interview Date']} by {row['Interviewer']})\n{row['Description']}"
|
62 |
+
# Clean each record to prevent encoding issues
|
63 |
+
records.append(clean_response(record))
|
64 |
+
|
65 |
+
record_text = "\n".join(records)
|
66 |
+
prompt = f"""
|
67 |
Patient Booking Number: {booking}
|
68 |
|
69 |
Instructions:
|
|
|
84 |
### Urgent Follow-up
|
85 |
- ...
|
86 |
"""
|
87 |
+
prompts.append(prompt)
|
88 |
+
return prompts
|
89 |
+
except Exception as e:
|
90 |
+
raise ValueError(f"Error parsing Excel file: {str(e)}")
|
91 |
|
92 |
def init_agent():
|
93 |
default_tool_path = os.path.abspath("data/new_tool.json")
|
94 |
target_tool_path = os.path.join(tool_cache_dir, "new_tool.json")
|
95 |
+
|
96 |
if not os.path.exists(target_tool_path):
|
97 |
+
try:
|
98 |
+
shutil.copy(default_tool_path, target_tool_path)
|
99 |
+
except Exception as e:
|
100 |
+
raise RuntimeError(f"Failed to copy tool file: {str(e)}")
|
101 |
+
|
102 |
+
try:
|
103 |
+
agent = TxAgent(
|
104 |
+
model_name="mims-harvard/TxAgent-T1-Llama-3.1-8B",
|
105 |
+
rag_model_name="mims-harvard/ToolRAG-T1-GTE-Qwen2-1.5B",
|
106 |
+
tool_files_dict={"new_tool": target_tool_path},
|
107 |
+
force_finish=True,
|
108 |
+
enable_checker=True,
|
109 |
+
step_rag_num=4,
|
110 |
+
seed=100,
|
111 |
+
additional_default_tools=[],
|
112 |
+
)
|
113 |
+
agent.init_model()
|
114 |
+
return agent
|
115 |
+
except Exception as e:
|
116 |
+
raise RuntimeError(f"Failed to initialize agent: {str(e)}")
|
117 |
|
118 |
def create_ui(agent):
|
119 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
120 |
+
gr.Markdown("# 🏥 Clinical Oversight Assistant (Excel Optimized)")
|
121 |
+
|
122 |
+
with gr.Row():
|
123 |
+
with gr.Column(scale=1):
|
124 |
+
file_upload = gr.File(
|
125 |
+
label="Upload Excel File",
|
126 |
+
file_types=[".xlsx"],
|
127 |
+
file_count="single",
|
128 |
+
interactive=True
|
129 |
+
)
|
130 |
+
msg_input = gr.Textbox(
|
131 |
+
label="Additional Instructions",
|
132 |
+
placeholder="Add any specific analysis requests...",
|
133 |
+
lines=3
|
134 |
+
)
|
135 |
+
send_btn = gr.Button("Analyze", variant="primary")
|
136 |
+
|
137 |
+
with gr.Column(scale=2):
|
138 |
+
chatbot = gr.Chatbot(
|
139 |
+
label="Analysis Results",
|
140 |
+
height=600,
|
141 |
+
bubble_full_width=False,
|
142 |
+
show_copy_button=True
|
143 |
+
)
|
144 |
+
download_output = gr.File(
|
145 |
+
label="Download Full Report",
|
146 |
+
interactive=False
|
147 |
+
)
|
148 |
+
|
149 |
def analyze(message: str, history: List[dict], file) -> tuple:
|
150 |
+
if not file:
|
151 |
+
raise gr.Error("Please upload an Excel file first")
|
152 |
+
|
153 |
+
try:
|
154 |
+
# Initial processing message
|
155 |
+
history.append({"role": "user", "content": message})
|
156 |
+
history.append({"role": "assistant", "content": "⏳ Processing Excel data..."})
|
157 |
+
yield history, None
|
158 |
+
|
159 |
+
# Parse Excel file
|
160 |
+
prompts = parse_excel_to_prompts(file.name)
|
161 |
+
full_output = ""
|
162 |
+
|
163 |
+
# Process each booking
|
164 |
+
for idx, prompt in enumerate(prompts, 1):
|
165 |
+
chunk_output = ""
|
166 |
+
try:
|
167 |
+
for result in agent.run_gradio_chat(
|
168 |
+
message=prompt,
|
169 |
+
history=[],
|
170 |
+
temperature=0.2,
|
171 |
+
max_new_tokens=1024,
|
172 |
+
max_token=4096,
|
173 |
+
call_agent=False,
|
174 |
+
conversation=[],
|
175 |
+
):
|
176 |
+
if isinstance(result, list):
|
177 |
+
for r in result:
|
178 |
+
if hasattr(r, 'content') and r.content:
|
179 |
+
cleaned = clean_response(r.content)
|
180 |
+
chunk_output += cleaned + "\n"
|
181 |
+
elif isinstance(result, str):
|
182 |
+
cleaned = clean_response(result)
|
183 |
+
chunk_output += cleaned + "\n"
|
184 |
+
|
185 |
+
# Yield intermediate results
|
186 |
+
if chunk_output:
|
187 |
+
output = f"--- Booking {idx} ---\n{chunk_output.strip()}\n"
|
188 |
+
history[-1] = {"role": "assistant", "content": output}
|
189 |
+
yield history, None
|
190 |
+
|
191 |
+
except Exception as e:
|
192 |
+
error_msg = f"⚠️ Error processing booking {idx}: {str(e)}"
|
193 |
+
history.append({"role": "assistant", "content": error_msg})
|
194 |
+
yield history, None
|
195 |
+
continue
|
196 |
+
|
197 |
+
if chunk_output:
|
198 |
+
output = f"--- Booking {idx} ---\n{chunk_output.strip()}\n"
|
199 |
+
history.append({"role": "assistant", "content": output})
|
200 |
+
full_output += output + "\n"
|
201 |
+
yield history, None
|
202 |
+
|
203 |
+
# Save report
|
204 |
+
file_hash_value = file_hash(file.name)
|
205 |
+
report_path = os.path.join(report_dir, f"{file_hash_value}_report.txt")
|
206 |
+
with open(report_path, "w", encoding="utf-8") as f:
|
207 |
+
f.write(full_output)
|
208 |
+
|
209 |
+
yield history, report_path if os.path.exists(report_path) else None
|
210 |
+
|
211 |
+
except Exception as e:
|
212 |
+
history.append({"role": "assistant", "content": f"❌ Error: {str(e)}"})
|
213 |
+
yield history, None
|
214 |
+
raise gr.Error(f"Analysis failed: {str(e)}")
|
215 |
+
|
216 |
+
# Event handlers
|
217 |
+
send_btn.click(
|
218 |
+
analyze,
|
219 |
+
inputs=[msg_input, gr.State([]), file_upload],
|
220 |
+
outputs=[chatbot, download_output],
|
221 |
+
api_name="analyze"
|
222 |
+
)
|
223 |
+
|
224 |
+
msg_input.submit(
|
225 |
+
analyze,
|
226 |
+
inputs=[msg_input, gr.State([]), file_upload],
|
227 |
+
outputs=[chatbot, download_output]
|
228 |
+
)
|
229 |
+
|
230 |
+
# Additional UI elements
|
231 |
+
with gr.Accordion("Instructions", open=False):
|
232 |
+
gr.Markdown("""
|
233 |
+
**How to use:**
|
234 |
+
1. Upload an Excel file containing patient records
|
235 |
+
2. Optionally add specific analysis instructions
|
236 |
+
3. Click 'Analyze' to process the data
|
237 |
+
4. Review results and download the full report
|
238 |
+
|
239 |
+
**Excel Format Requirements:**
|
240 |
+
- Must contain columns: Booking Number, Form Name, Form Item, Item Response, Interview Date, Interviewer, Description
|
241 |
+
- Each row represents one patient record item
|
242 |
+
""")
|
243 |
+
|
244 |
return demo
|
245 |
|
246 |
if __name__ == "__main__":
|
247 |
+
try:
|
248 |
+
agent = init_agent()
|
249 |
+
demo = create_ui(agent)
|
250 |
+
|
251 |
+
# Launch with error handling
|
252 |
+
demo.queue(
|
253 |
+
api_open=False,
|
254 |
+
max_size=20
|
255 |
+
).launch(
|
256 |
+
server_name="0.0.0.0",
|
257 |
+
server_port=7860,
|
258 |
+
show_error=True,
|
259 |
+
allowed_paths=[report_dir],
|
260 |
+
share=False # Changed to False to avoid the warning
|
261 |
+
)
|
262 |
+
except Exception as e:
|
263 |
+
print(f"Failed to launch application: {str(e)}")
|
264 |
+
sys.exit(1)
|