Ali2206 commited on
Commit
e4d9325
·
verified ·
1 Parent(s): 870dc53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -215
app.py CHANGED
@@ -1,251 +1,228 @@
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:
54
- for i, page in enumerate(pdf.pages):
55
  page_text = page.extract_text() or ""
56
- if i < 3 or any(re.search(rf'\b{kw}\b', page_text.lower()) for kw in MEDICAL_KEYWORDS):
57
- text_chunks.append(f"=== Page {i+1} ===\n{page_text.strip()}")
58
- return "\n\n".join(text_chunks)
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")
141
  file_upload = gr.File(file_types=[".pdf", ".csv", ".xls", ".xlsx"], file_count="multiple")
142
  msg_input = gr.Textbox(placeholder="Ask about potential oversights...", show_label=False)
143
  send_btn = gr.Button("Analyze", variant="primary")
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
 
250
  send_btn.click(analyze, inputs=[msg_input, gr.State([]), file_upload], outputs=[chatbot, download_output])
251
  msg_input.submit(analyze, inputs=[msg_input, gr.State([]), file_upload], outputs=[chatbot, download_output])
@@ -253,12 +230,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
8
  import hashlib
9
+ import multiprocessing
10
+ from functools import partial
11
+ import logging
12
+
13
+ # Suppress pdfplumber CropBox warnings
14
+ logging.getLogger("pdfplumber").setLevel(logging.ERROR)
15
 
16
+ # Persistent directories
17
  persistent_dir = "/data/hf_cache"
18
  os.makedirs(persistent_dir, exist_ok=True)
 
 
 
19
  file_cache_dir = os.path.join(persistent_dir, "cache")
20
  report_dir = os.path.join(persistent_dir, "reports")
21
+ for directory in [file_cache_dir, report_dir]:
 
 
22
  os.makedirs(directory, exist_ok=True)
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_page_range(file_path: str, start_page: int, end_page: int) -> str:
34
+ """Extract text from a range of PDF pages."""
35
  try:
36
  text_chunks = []
37
  with pdfplumber.open(file_path) as pdf:
38
+ for page in pdf.pages[start_page:end_page]:
39
  page_text = page.extract_text() or ""
40
+ text_chunks.append(page_text.strip())
41
+ return "\n".join(text_chunks)
42
+ except Exception:
43
+ return ""
 
44
 
45
+ def extract_all_pages(file_path: str) -> str:
46
+ """Extract text from all pages of a PDF using parallel processing."""
47
+ try:
48
+ with pdfplumber.open(file_path) as pdf:
49
+ total_pages = len(pdf.pages)
50
+
51
+ if total_pages == 0:
52
+ return ""
53
+
54
+ # Use 4 processes (adjust based on CPU cores)
55
+ num_processes = min(4, multiprocessing.cpu_count())
56
+ pages_per_process = max(1, total_pages // num_processes)
57
+
58
+ # Create page ranges for parallel processing
59
+ ranges = [(i * pages_per_process, min((i + 1) * pages_per_process, total_pages))
60
+ for i in range(num_processes)]
61
+ if ranges[-1][1] != total_pages:
62
+ ranges[-1] = (ranges[-1][0], total_pages)
63
+
64
+ # Process page ranges in parallel
65
+ with multiprocessing.Pool(processes=num_processes) as pool:
66
+ extract_func = partial(extract_page_range, file_path)
67
+ results = pool.starmap(extract_func, ranges)
68
+
69
+ return "\n".join(filter(None, results))
70
+ except Exception:
71
+ return ""
72
+
73
+ def convert_file_to_text(file_path: str, file_type: str) -> str:
74
+ """Convert supported file types to text, caching results."""
75
  try:
76
  h = file_hash(file_path)
77
+ cache_path = os.path.join(file_cache_dir, f"{h}.txt")
78
  if os.path.exists(cache_path):
79
  with open(cache_path, "r", encoding="utf-8") as f:
80
  return f.read()
81
 
82
  if file_type == "pdf":
83
+ text = extract_all_pages(file_path)
 
84
  elif file_type == "csv":
85
  df = pd.read_csv(file_path, encoding_errors="replace", header=None, dtype=str,
86
+ skip_blank_lines=True, on_bad_lines="skip")
87
+ text = " ".join(df.fillna("").astype(str).agg(" ".join, axis=1))
 
88
  elif file_type in ["xls", "xlsx"]:
89
+ df = pd.read_excel(file_path, engine="openpyxl", header=None, dtype=str)
90
+ text = " ".join(df.fillna("").astype(str).agg(" ".join, axis=1))
 
 
 
 
91
  else:
92
+ text = ""
93
+
94
+ if text:
95
+ # Compress text by removing redundant whitespace
96
+ text = re.sub(r'\s+', ' ', text).strip()
97
+ with open(cache_path, "w", encoding="utf-8") as f:
98
+ f.write(text)
99
+ return text
100
+ except Exception:
101
+ return ""
102
+
103
+ def parse_analysis_response(raw_response: str) -> Dict[str, List[str]]:
104
+ """Parse raw analysis response into structured sections using regex."""
105
+ sections = {
106
+ "Missed Diagnoses": [],
107
+ "Medication Conflicts": [],
108
+ "Incomplete Assessments": [],
109
+ "Urgent Follow-up": []
110
+ }
111
+ current_section = None
112
+ section_pattern = re.compile(r"^(Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up):$", re.MULTILINE)
113
+ item_pattern = re.compile(r"^- .+$", re.MULTILINE)
114
+
115
+ for line in raw_response.splitlines():
116
+ line = line.strip()
117
+ if not line:
118
+ continue
119
+ if section_pattern.match(line):
120
+ current_section = line[:-1]
121
+ elif current_section and item_pattern.match(line):
122
+ sections[current_section].append(line)
123
+
124
+ return sections
125
+
126
+ def analyze_medical_records(extracted_text: str) -> str:
127
+ """Analyze medical records and return structured response."""
128
+ # Split text into chunks to handle large inputs
129
+ chunk_size = 10000
130
+ chunks = [extracted_text[i:i + chunk_size] for i in range(0, len(extracted_text), chunk_size)]
131
+
132
+ # Placeholder for analysis (replace with model or rule-based logic)
133
+ raw_response_template = """
134
+ Missed Diagnoses:
135
+ - Undiagnosed hypertension despite elevated BP readings.
136
+ - Family history of diabetes not evaluated for prediabetes risk.
137
+
138
+ Medication Conflicts:
139
+ - SSRIs and NSAIDs detected, increasing GI bleeding risk.
140
+
141
+ Incomplete Assessments:
142
+ - No cardiac stress test despite chest pain.
143
+
144
+ Urgent Follow-up:
145
+ - Abnormal ECG requires cardiology referral.
146
+ """
147
+
148
+ # Aggregate findings across chunks
149
+ all_sections = {
150
+ "Missed Diagnoses": set(),
151
+ "Medication Conflicts": set(),
152
+ "Incomplete Assessments": set(),
153
+ "Urgent Follow-up": set()
154
+ }
155
+
156
+ for chunk_idx, chunk in enumerate(chunks, 1):
157
+ # Simulate analysis per chunk (replace with real logic)
158
+ raw_response = raw_response_template
159
+ parsed = parse_analysis_response(raw_response)
160
+ for section, items in parsed.items():
161
+ all_sections[section].update(items)
162
+
163
+ # Format final response
164
+ response = ["### Clinical Oversight Analysis\n"]
165
+ has_findings = False
166
+ for section, items in all_sections.items():
167
+ response.append(f"#### {section}")
168
+ if items:
169
+ response.extend(sorted(items))
170
+ has_findings = True
171
+ else:
172
+ response.append("- None identified.")
173
+ response.append("")
174
+
175
+ response.append("### Summary")
176
+ summary = ("The analysis identified potential oversights in diagnosis, medication management, "
177
+ "assessments, and follow-up needs. Immediate action is recommended.") if has_findings else \
178
+ "No significant oversights identified. Continue monitoring."
179
+ response.append(summary)
180
+
181
+ return "\n".join(response)
182
+
183
+ def create_ui():
184
+ """Create Gradio UI for clinical oversight analysis."""
185
+ def analyze(message: str, history: List[dict], files: List):
186
+ """Handle analysis and return results."""
187
+ history.append({"role": "user", "content": message})
188
+ history.append({"role": "assistant", "content": "⏳ Extracting text from files..."})
189
+ yield history, None
190
+
191
+ extracted_text = ""
192
+ file_hash_value = ""
193
+ if files:
194
+ with ThreadPoolExecutor(max_workers=4) as executor:
195
+ futures = [executor.submit(convert_file_to_text, f.name, f.name.split(".")[-1].lower()) for f in files]
196
+ results = [f.result() for f in futures]
197
+ extracted_text = "\n".join(sanitize_utf8(r) for r in results if r)
198
+ file_hash_value = file_hash(files[0].name) if files else ""
199
+
200
+ history.pop() # Remove "Extracting..."
201
+ history.append({"role": "assistant", "content": "⏳ Analyzing medical records..."})
202
+ yield history, None
203
+
204
+ report_path = os.path.join(report_dir, f"{file_hash_value}_report.txt") if file_hash_value else None
205
+
206
+ try:
207
+ response = analyze_medical_records(extracted_text)
208
+ history.pop() # Remove "Analyzing..."
209
+ history.append({"role": "assistant", "content": response})
210
+ if report_path:
211
+ with open(report_path, "w", encoding="utf-8") as f:
212
+ f.write(response)
213
+ yield history, report_path if report_path and os.path.exists(report_path) else None
214
+ except Exception as e:
215
+ history.pop() # Remove "Analyzing..."
216
+ history.append({"role": "assistant", "content": f"❌ Error: {str(e)}"})
217
+ yield history, None
218
 
 
219
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
220
  gr.Markdown("<h1 style='text-align: center;'>🩺 Clinical Oversight Assistant</h1>")
221
  chatbot = gr.Chatbot(label="Analysis", height=600, type="messages")
222
  file_upload = gr.File(file_types=[".pdf", ".csv", ".xls", ".xlsx"], file_count="multiple")
223
  msg_input = gr.Textbox(placeholder="Ask about potential oversights...", show_label=False)
224
  send_btn = gr.Button("Analyze", variant="primary")
225
+ download_output = gr.File(label="Download Report")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
227
  send_btn.click(analyze, inputs=[msg_input, gr.State([]), file_upload], outputs=[chatbot, download_output])
228
  msg_input.submit(analyze, inputs=[msg_input, gr.State([]), file_upload], outputs=[chatbot, download_output])
 
230
 
231
  if __name__ == "__main__":
232
  print("🚀 Launching app...")
233
+ try:
234
+ demo = create_ui()
235
+ demo.launch(
236
+ server_name="0.0.0.0",
237
+ server_port=7860,
238
+ show_error=True,
239
+ allowed_paths=[report_dir],
240
+ share=False
241
+ )
242
+ except Exception as e:
243
+ print(f"Failed to launch app: {str(e)}")