Ali2206 commited on
Commit
3800ddf
·
verified ·
1 Parent(s): bfa497f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -17
app.py CHANGED
@@ -139,25 +139,37 @@ def log_system_usage(tag=""):
139
  print(f"[{tag}] GPU/CPU monitor failed: {e}")
140
 
141
  def clean_response(text: str) -> str:
142
- """Clean TxAgent response to remove tool calls, reasoning, and non-markdown content."""
143
  text = sanitize_utf8(text)
144
  # Remove tool call artifacts, None, and reasoning
145
  text = re.sub(r"\[.*?\]|\bNone\b|To analyze the patient record excerpt.*?medications\.|Since the previous attempts.*?\.|I need to.*?medications\.|Retrieving tools.*?\.", "", text, flags=re.DOTALL)
146
  # Remove extra whitespace and non-markdown content
147
  text = re.sub(r"\n{3,}", "\n\n", text)
148
  text = re.sub(r"[^\n#\-\*\w\s\.\,\:\(\)]+", "", text) # Keep markdown-relevant characters
149
- # Extract only markdown sections
150
- markdown_pattern = r"(###\s*(?:Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up).*?(?=\n###|\Z))|(-.*?)(?=\n-|\n###|\Z)"
151
- matches = re.findall(markdown_pattern, text, re.DOTALL | re.MULTILINE)
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  cleaned = []
153
- for match in matches:
154
- section = match[0].strip() or match[1].strip()
155
- if section:
156
- cleaned.append(section)
157
- text = "\n".join(cleaned).strip()
158
- # Ensure consistent markdown formatting
159
- if not text.startswith("###"):
160
- text = "### Missed Diagnoses\n- No issues identified.\n\n### Medication Conflicts\n- No issues identified.\n\n### Incomplete Assessments\n- No issues identified.\n\n### Urgent Follow-up\n- No issues identified."
161
  return text
162
 
163
  def init_agent():
@@ -285,7 +297,7 @@ Patient Record Excerpt (Chunk {0} of {1}):
285
  if hasattr(m, 'content') and m.content:
286
  cleaned = clean_response(m.content)
287
  if cleaned and re.search(r"###\s*(Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up)", cleaned):
288
- chunk_response += cleaned + "\n"
289
  # Update UI with partial response
290
  if history[-1]["content"].startswith("Analyzing"):
291
  history[-1] = {"role": "assistant", "content": f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response.strip()}"}
@@ -295,7 +307,7 @@ Patient Record Excerpt (Chunk {0} of {1}):
295
  elif isinstance(chunk_output, str) and chunk_output.strip():
296
  cleaned = clean_response(chunk_output)
297
  if cleaned and re.search(r"###\s*(Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up)", cleaned):
298
- chunk_response += cleaned + "\n"
299
  # Update UI with partial response
300
  if history[-1]["content"].startswith("Analyzing"):
301
  history[-1] = {"role": "assistant", "content": f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response.strip()}"}
@@ -307,13 +319,13 @@ Patient Record Excerpt (Chunk {0} of {1}):
307
  if chunk_response:
308
  combined_response += f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response}\n"
309
  else:
310
- combined_response += f"--- Analysis for Chunk {chunk_idx} ---\n### Missed Diagnoses\n- No issues identified.\n\n### Medication Conflicts\n- No issues identified.\n\n### Incomplete Assessments\n- No issues identified.\n\n### Urgent Follow-up\n- No issues identified.\n\n"
311
 
312
  # Finalize UI with complete response
313
- if combined_response:
314
  history[-1]["content"] = combined_response.strip()
315
  else:
316
- history.append({"role": "assistant", "content": "No oversights identified."})
317
 
318
  # Generate report file
319
  report_path = os.path.join(report_dir, f"{file_hash_value}_report.txt") if file_hash_value else None
 
139
  print(f"[{tag}] GPU/CPU monitor failed: {e}")
140
 
141
  def clean_response(text: str) -> str:
142
+ """Clean TxAgent response to keep only markdown sections with valid findings."""
143
  text = sanitize_utf8(text)
144
  # Remove tool call artifacts, None, and reasoning
145
  text = re.sub(r"\[.*?\]|\bNone\b|To analyze the patient record excerpt.*?medications\.|Since the previous attempts.*?\.|I need to.*?medications\.|Retrieving tools.*?\.", "", text, flags=re.DOTALL)
146
  # Remove extra whitespace and non-markdown content
147
  text = re.sub(r"\n{3,}", "\n\n", text)
148
  text = re.sub(r"[^\n#\-\*\w\s\.\,\:\(\)]+", "", text) # Keep markdown-relevant characters
149
+
150
+ # Extract markdown sections with valid findings
151
+ sections = []
152
+ current_section = None
153
+ lines = text.splitlines()
154
+ for line in lines:
155
+ line = line.strip()
156
+ if not line:
157
+ continue
158
+ if re.match(r"###\s*(Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up)", line):
159
+ current_section = line
160
+ sections.append([current_section])
161
+ elif current_section and re.match(r"-\s*.+", line) and not re.match(r"-\s*No issues identified", line):
162
+ sections[-1].append(line)
163
+
164
+ # Combine only non-empty sections
165
  cleaned = []
166
+ for section in sections:
167
+ if len(section) > 1: # Section has at least one finding
168
+ cleaned.append("\n".join(section))
169
+
170
+ text = "\n\n".join(cleaned).strip()
171
+ if not text:
172
+ text = "" # Return empty string if no valid findings
 
173
  return text
174
 
175
  def init_agent():
 
297
  if hasattr(m, 'content') and m.content:
298
  cleaned = clean_response(m.content)
299
  if cleaned and re.search(r"###\s*(Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up)", cleaned):
300
+ chunk_response += cleaned + "\n\n"
301
  # Update UI with partial response
302
  if history[-1]["content"].startswith("Analyzing"):
303
  history[-1] = {"role": "assistant", "content": f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response.strip()}"}
 
307
  elif isinstance(chunk_output, str) and chunk_output.strip():
308
  cleaned = clean_response(chunk_output)
309
  if cleaned and re.search(r"###\s*(Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up)", cleaned):
310
+ chunk_response += cleaned + "\n\n"
311
  # Update UI with partial response
312
  if history[-1]["content"].startswith("Analyzing"):
313
  history[-1] = {"role": "assistant", "content": f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response.strip()}"}
 
319
  if chunk_response:
320
  combined_response += f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response}\n"
321
  else:
322
+ combined_response += f"--- Analysis for Chunk {chunk_idx} ---\nNo oversights identified for this chunk.\n\n"
323
 
324
  # Finalize UI with complete response
325
+ if combined_response.strip() and not all("No oversights identified" in chunk for chunk in combined_response.split("--- Analysis for Chunk")):
326
  history[-1]["content"] = combined_response.strip()
327
  else:
328
+ history.append({"role": "assistant", "content": "No oversights identified in the provided records."})
329
 
330
  # Generate report file
331
  report_path = os.path.join(report_dir, f"{file_hash_value}_report.txt") if file_hash_value else None