Ali2206 commited on
Commit
176dbe1
·
verified ·
1 Parent(s): c9b3ae0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -177
app.py CHANGED
@@ -1,53 +1,37 @@
1
- import sys
2
  import os
3
  import pandas as pd
4
  import pdfplumber
5
- import json
6
  import gradio as gr
7
- from typing import List
8
  from concurrent.futures import ThreadPoolExecutor, as_completed
9
  import hashlib
10
- import shutil
11
- import re
12
- import psutil
13
- import subprocess
14
 
15
- # Persistent directory
16
  persistent_dir = "/data/hf_cache"
17
  os.makedirs(persistent_dir, exist_ok=True)
18
-
19
- model_cache_dir = os.path.join(persistent_dir, "txagent_models")
20
- tool_cache_dir = os.path.join(persistent_dir, "tool_cache")
21
  file_cache_dir = os.path.join(persistent_dir, "cache")
22
  report_dir = os.path.join(persistent_dir, "reports")
23
- vllm_cache_dir = os.path.join(persistent_dir, "vllm_cache")
24
-
25
- for directory in [model_cache_dir, tool_cache_dir, file_cache_dir, report_dir, vllm_cache_dir]:
26
  os.makedirs(directory, exist_ok=True)
27
 
28
- os.environ["HF_HOME"] = model_cache_dir
29
- os.environ["TRANSFORMERS_CACHE"] = model_cache_dir
30
- os.environ["VLLM_CACHE_DIR"] = vllm_cache_dir
31
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
32
- os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
33
-
34
- current_dir = os.path.dirname(os.path.abspath(__file__))
35
- src_path = os.path.abspath(os.path.join(current_dir, "src"))
36
- sys.path.insert(0, src_path)
37
-
38
- from txagent.txagent import TxAgent
39
-
40
- MEDICAL_KEYWORDS = {'diagnosis', 'assessment', 'plan', 'results', 'medications',
41
- 'allergies', 'summary', 'impression', 'findings', 'recommendations'}
42
 
43
  def sanitize_utf8(text: str) -> str:
 
44
  return text.encode("utf-8", "ignore").decode("utf-8")
45
 
46
  def file_hash(path: str) -> str:
 
47
  with open(path, "rb") as f:
48
  return hashlib.md5(f.read()).hexdigest()
49
 
50
  def extract_priority_pages(file_path: str) -> str:
 
51
  try:
52
  text_chunks = []
53
  with pdfplumber.open(file_path) as pdf:
@@ -59,82 +43,112 @@ def extract_priority_pages(file_path: str) -> str:
59
  except Exception as e:
60
  return f"PDF processing error: {str(e)}"
61
 
62
- def convert_file_to_json(file_path: str, file_type: str) -> str:
 
63
  try:
64
  h = file_hash(file_path)
65
- cache_path = os.path.join(file_cache_dir, f"{h}.json")
66
  if os.path.exists(cache_path):
67
  with open(cache_path, "r", encoding="utf-8") as f:
68
  return f.read()
69
 
70
  if file_type == "pdf":
71
  text = extract_priority_pages(file_path)
72
- result = json.dumps({"filename": os.path.basename(file_path), "content": text, "status": "initial"})
73
  elif file_type == "csv":
74
  df = pd.read_csv(file_path, encoding_errors="replace", header=None, dtype=str,
75
  skip_blank_lines=False, on_bad_lines="skip")
76
- content = df.fillna("").astype(str).values.tolist()
77
- result = json.dumps({"filename": os.path.basename(file_path), "rows": content})
78
  elif file_type in ["xls", "xlsx"]:
79
  try:
80
  df = pd.read_excel(file_path, engine="openpyxl", header=None, dtype=str)
81
  except Exception:
82
  df = pd.read_excel(file_path, engine="xlrd", header=None, dtype=str)
83
- content = df.fillna("").astype(str).values.tolist()
84
- result = json.dumps({"filename": os.path.basename(file_path), "rows": content})
85
  else:
86
- result = json.dumps({"error": f"Unsupported file type: {file_type}"})
87
- with open(cache_path, "w", encoding="utf-8") as f:
88
- f.write(result)
89
- return result
90
- except Exception as e:
91
- return json.dumps({"error": f"Error processing {os.path.basename(file_path)}: {str(e)}"})
92
 
93
- def log_system_usage(tag=""):
94
- try:
95
- cpu = psutil.cpu_percent(interval=1)
96
- mem = psutil.virtual_memory()
97
- print(f"[{tag}] CPU: {cpu}% | RAM: {mem.used // (1024**2)}MB / {mem.total // (1024**2)}MB")
98
- result = subprocess.run(
99
- ["nvidia-smi", "--query-gpu=memory.used,memory.total,utilization.gpu", "--format=csv,nounits,noheader"],
100
- capture_output=True, text=True
101
- )
102
- if result.returncode == 0:
103
- used, total, util = result.stdout.strip().split(", ")
104
- print(f"[{tag}] GPU: {used}MB / {total}MB | Utilization: {util}%")
105
  except Exception as e:
106
- print(f"[{tag}] GPU/CPU monitor failed: {e}")
107
-
108
- def clean_response(text: str) -> str:
109
- text = sanitize_utf8(text)
110
- text = re.sub(r"\[TOOL_CALLS\].*", "", text, flags=re.DOTALL)
111
- text = re.sub(r"\n{3,}", "\n\n", text).strip()
112
- return text
113
-
114
- def init_agent():
115
- print("🔁 Initializing model...")
116
- log_system_usage("Before Load")
117
- default_tool_path = os.path.abspath("data/new_tool.json")
118
- target_tool_path = os.path.join(tool_cache_dir, "new_tool.json")
119
- if not os.path.exists(target_tool_path):
120
- shutil.copy(default_tool_path, target_tool_path)
121
-
122
- agent = TxAgent(
123
- model_name="mims-harvard/TxAgent-T1-Llama-3.1-8B",
124
- rag_model_name="mims-harvard/ToolRAG-T1-GTE-Qwen2-1.5B",
125
- tool_files_dict={"new_tool": target_tool_path},
126
- force_finish=True,
127
- enable_checker=True,
128
- step_rag_num=4,
129
- seed=100,
130
- additional_default_tools=[],
131
- )
132
- agent.init_model()
133
- log_system_usage("After Load")
134
- print("✅ Agent Ready")
135
- return agent
136
-
137
- def create_ui(agent):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
139
  gr.Markdown("<h1 style='text-align: center;'>🩺 Clinical Oversight Assistant</h1>")
140
  chatbot = gr.Chatbot(label="Analysis", height=600, type="messages")
@@ -144,106 +158,32 @@ def create_ui(agent):
144
  download_output = gr.File(label="Download Full Report")
145
 
146
  def analyze(message: str, history: List[dict], files: List):
 
147
  history.append({"role": "user", "content": message})
148
  history.append({"role": "assistant", "content": "⏳ Analyzing records for potential oversights..."})
149
  yield history, None
150
 
151
- extracted = ""
152
  file_hash_value = ""
153
  if files:
154
  with ThreadPoolExecutor(max_workers=6) as executor:
155
- futures = [executor.submit(convert_file_to_json, f.name, f.name.split(".")[-1].lower()) for f in files]
156
- results = [sanitize_utf8(f.result()) for f in as_completed(futures)]
157
- extracted = "\n".join(results)
158
  file_hash_value = file_hash(files[0].name) if files else ""
159
 
160
- # Split extracted text into chunks of ~6,000 characters
161
- chunk_size = 6000
162
- chunks = [extracted[i:i + chunk_size] for i in range(0, len(extracted), chunk_size)]
163
- combined_response = ""
164
-
165
- prompt_template = f"""
166
- Analyze the medical records for clinical oversights. Provide a concise, evidence-based summary under these headings:
167
- 1. **Missed Diagnoses**:
168
- - Identify inconsistencies in history, symptoms, or tests.
169
- - Consider psychiatric, neurological, infectious, autoimmune, genetic conditions, family history, trauma, and developmental factors.
170
- 2. **Medication Conflicts**:
171
- - Check for contraindications, interactions, or unjustified off-label use.
172
- - Assess if medications worsen diagnoses or cause adverse effects.
173
- 3. **Incomplete Assessments**:
174
- - Note missing or superficial cognitive, psychiatric, social, or family assessments.
175
- - Highlight gaps in medical history, substance use, or lab/imaging documentation.
176
- 4. **Urgent Follow-up**:
177
- - Flag abnormal lab results, imaging, behaviors, or legal history needing immediate reassessment or referral.
178
- Medical Records (Chunk {0} of {1}):
179
- {{chunk}}
180
- Begin analysis:
181
- """
182
-
183
  try:
184
- if history and history[-1]["content"].startswith("⏳"):
185
- history.pop()
186
-
187
- # Process each chunk and stream results in real-time
188
- for chunk_idx, chunk in enumerate(chunks, 1):
189
- # Update UI with progress
190
- history.append({"role": "assistant", "content": f"🔄 Processing Chunk {chunk_idx} of {len(chunks)}..."})
191
- yield history, None
192
-
193
- prompt = prompt_template.format(chunk_idx, len(chunks), chunk=chunk)
194
- chunk_response = ""
195
- for chunk_output in agent.run_gradio_chat(
196
- message=prompt,
197
- history=[],
198
- temperature=0.2,
199
- max_new_tokens=1024,
200
- max_token=4096,
201
- call_agent=False,
202
- conversation=[],
203
- ):
204
- if chunk_output is None:
205
- continue
206
- if isinstance(chunk_output, list):
207
- for m in chunk_output:
208
- if hasattr(m, 'content') and m.content:
209
- cleaned = clean_response(m.content)
210
- if cleaned:
211
- chunk_response += cleaned + "\n"
212
- # Update UI with partial response
213
- if history[-1]["content"].startswith("🔄"):
214
- history[-1] = {"role": "assistant", "content": f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response.strip()}"}
215
- else:
216
- history[-1]["content"] = f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response.strip()}"
217
- yield history, None
218
- elif isinstance(chunk_output, str) and chunk_output.strip():
219
- cleaned = clean_response(chunk_output)
220
- if cleaned:
221
- chunk_response += cleaned + "\n"
222
- # Update UI with partial response
223
- if history[-1]["content"].startswith("🔄"):
224
- history[-1] = {"role": "assistant", "content": f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response.strip()}"}
225
- else:
226
- history[-1]["content"] = f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response.strip()}"
227
- yield history, None
228
-
229
- # Append completed chunk response to combined response
230
- combined_response += f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response}\n"
231
-
232
- # Finalize UI with complete response
233
- if combined_response:
234
- history[-1]["content"] = combined_response.strip()
235
- else:
236
- history.append({"role": "assistant", "content": "No oversights identified."})
237
 
238
  # Generate report file
239
  report_path = os.path.join(report_dir, f"{file_hash_value}_report.txt") if file_hash_value else None
240
  if report_path:
241
  with open(report_path, "w", encoding="utf-8") as f:
242
- f.write(combined_response)
243
  yield history, report_path if report_path and os.path.exists(report_path) else None
244
-
245
  except Exception as e:
246
- print("🚨 ERROR:", e)
247
  history.append({"role": "assistant", "content": f"❌ Error occurred: {str(e)}"})
248
  yield history, None
249
 
@@ -253,12 +193,14 @@ Begin analysis:
253
 
254
  if __name__ == "__main__":
255
  print("🚀 Launching app...")
256
- agent = init_agent()
257
- demo = create_ui(agent)
258
- demo.queue(api_open=False).launch(
259
- server_name="0.0.0.0",
260
- server_port=7860,
261
- show_error=True,
262
- allowed_paths=[report_dir],
263
- share=False
264
- )
 
 
 
 
1
  import os
2
  import pandas as pd
3
  import pdfplumber
4
+ import re
5
  import gradio as gr
6
+ from typing import List, Dict
7
  from concurrent.futures import ThreadPoolExecutor, as_completed
8
  import hashlib
 
 
 
 
9
 
10
+ # Persistent directories
11
  persistent_dir = "/data/hf_cache"
12
  os.makedirs(persistent_dir, exist_ok=True)
 
 
 
13
  file_cache_dir = os.path.join(persistent_dir, "cache")
14
  report_dir = os.path.join(persistent_dir, "reports")
15
+ for directory in [file_cache_dir, report_dir]:
 
 
16
  os.makedirs(directory, exist_ok=True)
17
 
18
+ # Medical keywords for PDF extraction
19
+ MEDICAL_KEYWORDS = {
20
+ 'diagnosis', 'assessment', 'plan', 'results', 'medications',
21
+ 'allergies', 'summary', 'impression', 'findings', 'recommendations'
22
+ }
 
 
 
 
 
 
 
 
 
23
 
24
  def sanitize_utf8(text: str) -> str:
25
+ """Sanitize text to handle UTF-8 encoding issues."""
26
  return text.encode("utf-8", "ignore").decode("utf-8")
27
 
28
  def file_hash(path: str) -> str:
29
+ """Generate MD5 hash of a file."""
30
  with open(path, "rb") as f:
31
  return hashlib.md5(f.read()).hexdigest()
32
 
33
  def extract_priority_pages(file_path: str) -> str:
34
+ """Extract text from PDF pages, prioritizing those with medical keywords."""
35
  try:
36
  text_chunks = []
37
  with pdfplumber.open(file_path) as pdf:
 
43
  except Exception as e:
44
  return f"PDF processing error: {str(e)}"
45
 
46
+ def convert_file_to_text(file_path: str, file_type: str) -> str:
47
+ """Convert supported file types to text, caching results."""
48
  try:
49
  h = file_hash(file_path)
50
+ cache_path = os.path.join(file_cache_dir, f"{h}.txt")
51
  if os.path.exists(cache_path):
52
  with open(cache_path, "r", encoding="utf-8") as f:
53
  return f.read()
54
 
55
  if file_type == "pdf":
56
  text = extract_priority_pages(file_path)
 
57
  elif file_type == "csv":
58
  df = pd.read_csv(file_path, encoding_errors="replace", header=None, dtype=str,
59
  skip_blank_lines=False, on_bad_lines="skip")
60
+ text = "\n".join(df.fillna("").astype(str).agg(" ".join, axis=1))
 
61
  elif file_type in ["xls", "xlsx"]:
62
  try:
63
  df = pd.read_excel(file_path, engine="openpyxl", header=None, dtype=str)
64
  except Exception:
65
  df = pd.read_excel(file_path, engine="xlrd", header=None, dtype=str)
66
+ text = "\n".join(df.fillna("").astype(str).agg(" ".join, axis=1))
 
67
  else:
68
+ text = f"Unsupported file type: {file_type}"
 
 
 
 
 
69
 
70
+ with open(cache_path, "w", encoding="utf-8") as f:
71
+ f.write(text)
72
+ return text
 
 
 
 
 
 
 
 
 
73
  except Exception as e:
74
+ return f"Error processing {os.path.basename(file_path)}: {str(e)}"
75
+
76
+ def parse_analysis_response(raw_response: str) -> Dict[str, List[str]]:
77
+ """Parse raw analysis response into structured sections."""
78
+ sections = {
79
+ "Missed Diagnoses": [],
80
+ "Medication Conflicts": [],
81
+ "Incomplete Assessments": [],
82
+ "Urgent Follow-up": []
83
+ }
84
+ current_section = None
85
+ lines = raw_response.split("\n")
86
+
87
+ for line in lines:
88
+ line = line.strip()
89
+ if not line:
90
+ continue
91
+ if line.startswith("Missed Diagnoses"):
92
+ current_section = "Missed Diagnoses"
93
+ elif line.startswith("Medication Conflicts"):
94
+ current_section = "Medication Conflicts"
95
+ elif line.startswith("Incomplete Assessments"):
96
+ current_section = "Incomplete Assessments"
97
+ elif line.startswith("Urgent Follow-up"):
98
+ current_section = "Urgent Follow-up"
99
+ elif current_section and line.startswith("-"):
100
+ sections[current_section].append(line)
101
+
102
+ return sections
103
+
104
+ def analyze_medical_records(extracted_text: str) -> str:
105
+ """Analyze medical records for clinical oversights and return structured response."""
106
+ # Placeholder for dynamic analysis (replace with actual model or rule-based logic)
107
+ # Example response to demonstrate flexibility with varying content
108
+ raw_response = """
109
+ Missed Diagnoses:
110
+ - Undiagnosed hypertension despite elevated BP readings.
111
+ - Family history of diabetes not evaluated for prediabetes risk.
112
+
113
+ Medication Conflicts:
114
+ - Concurrent use of SSRIs and NSAIDs detected, increasing risk of gastrointestinal bleeding.
115
+ - Beta-blocker prescribed without assessing asthma history, risking bronchospasm.
116
+
117
+ Incomplete Assessments:
118
+ - No cardiac stress test despite reported chest pain.
119
+ - Social history lacks documentation of substance use or living conditions.
120
+
121
+ Urgent Follow-up:
122
+ - Abnormal ECG results require immediate cardiology referral.
123
+ - Elevated liver enzymes not addressed, needing hepatology consultation.
124
+ """
125
+
126
+ # Parse the raw response into sections
127
+ parsed = parse_analysis_response(raw_response)
128
+
129
+ # Format the response
130
+ response = ["### Clinical Oversight Analysis\n"]
131
+ has_findings = False
132
+ for section, items in parsed.items():
133
+ response.append(f"#### {section}")
134
+ if items:
135
+ response.extend(items)
136
+ has_findings = True
137
+ else:
138
+ response.append("- None identified.")
139
+ response.append("") # Add newline for readability
140
+
141
+ response.append("### Summary")
142
+ if has_findings:
143
+ summary = "The analysis identified potential oversights in diagnosis, medication management, assessments, and follow-up needs. Immediate action is recommended to address critical findings and ensure comprehensive patient care."
144
+ else:
145
+ summary = "No significant clinical oversights were identified in the provided records. Continue monitoring and ensure complete documentation."
146
+ response.append(summary)
147
+
148
+ return "\n".join(response)
149
+
150
+ def create_ui():
151
+ """Create Gradio UI for clinical oversight analysis."""
152
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
153
  gr.Markdown("<h1 style='text-align: center;'>🩺 Clinical Oversight Assistant</h1>")
154
  chatbot = gr.Chatbot(label="Analysis", height=600, type="messages")
 
158
  download_output = gr.File(label="Download Full Report")
159
 
160
  def analyze(message: str, history: List[dict], files: List):
161
+ """Handle analysis of medical records and update UI."""
162
  history.append({"role": "user", "content": message})
163
  history.append({"role": "assistant", "content": "⏳ Analyzing records for potential oversights..."})
164
  yield history, None
165
 
166
+ extracted_text = ""
167
  file_hash_value = ""
168
  if files:
169
  with ThreadPoolExecutor(max_workers=6) as executor:
170
+ futures = [executor.submit(convert_file_to_text, f.name, f.name.split(".")[-1].lower()) for f in files]
171
+ extracted_text = "\n".join(sanitize_utf8(f.result()) for f in as_completed(futures))
 
172
  file_hash_value = file_hash(files[0].name) if files else ""
173
 
174
+ # Analyze extracted text
175
+ history.pop() # Remove "Analyzing..." message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  try:
177
+ response = analyze_medical_records(extracted_text)
178
+ history.append({"role": "assistant", "content": response})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
  # Generate report file
181
  report_path = os.path.join(report_dir, f"{file_hash_value}_report.txt") if file_hash_value else None
182
  if report_path:
183
  with open(report_path, "w", encoding="utf-8") as f:
184
+ f.write(response)
185
  yield history, report_path if report_path and os.path.exists(report_path) else None
 
186
  except Exception as e:
 
187
  history.append({"role": "assistant", "content": f"❌ Error occurred: {str(e)}"})
188
  yield history, None
189
 
 
193
 
194
  if __name__ == "__main__":
195
  print("🚀 Launching app...")
196
+ try:
197
+ demo = create_ui()
198
+ demo.queue(api_open=False).launch(
199
+ server_name="0.0.0.0",
200
+ server_port=7860,
201
+ show_error=True,
202
+ allowed_paths=[report_dir],
203
+ share=False
204
+ )
205
+ except Exception as e:
206
+ print(f"Failed to launch app: {str(e)}")