Ali2206 commited on
Commit
ac93cad
Β·
verified Β·
1 Parent(s): 888250d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -30
app.py CHANGED
@@ -1,4 +1,7 @@
1
-
 
 
 
2
  import json
3
  import gradio as gr
4
  from typing import List
@@ -9,9 +12,7 @@ import re
9
  import psutil
10
  import subprocess
11
 
12
- # ---------------------------------------------------------------------------------------
13
- # Persistent directory setup
14
- # ---------------------------------------------------------------------------------------
15
  persistent_dir = "/data/hf_cache"
16
  os.makedirs(persistent_dir, exist_ok=True)
17
 
@@ -36,13 +37,8 @@ sys.path.insert(0, src_path)
36
 
37
  from txagent.txagent import TxAgent
38
 
39
- # ---------------------------------------------------------------------------------------
40
- # Utilities
41
- # ---------------------------------------------------------------------------------------
42
- MEDICAL_KEYWORDS = {
43
- 'diagnosis', 'assessment', 'plan', 'results', 'medications',
44
- 'allergies', 'summary', 'impression', 'findings', 'recommendations'
45
- }
46
 
47
  def sanitize_utf8(text: str) -> str:
48
  return text.encode("utf-8", "ignore").decode("utf-8")
@@ -60,7 +56,7 @@ def extract_priority_pages(file_path: str, max_pages: int = 20) -> str:
60
  text_chunks.append(f"=== Page {i+1} ===\n{text.strip()}")
61
  for i, page in enumerate(pdf.pages[3:max_pages], start=4):
62
  page_text = page.extract_text() or ""
63
- if any(re.search(rf'\b{kw}\b', page_text.lower()) for kw in MEDICAL_KEYWORDS):
64
  text_chunks.append(f"=== Page {i} ===\n{page_text.strip()}")
65
  return "\n\n".join(text_chunks)
66
  except Exception as e:
@@ -78,7 +74,7 @@ def convert_file_to_json(file_path: str, file_type: str) -> str:
78
  text = extract_priority_pages(file_path)
79
  result = json.dumps({"filename": os.path.basename(file_path), "content": text, "status": "initial"})
80
  elif file_type == "csv":
81
- df = pd.read_csv(file_path, encoding_errors="replace", header=None, dtype=str,
82
  skip_blank_lines=False, on_bad_lines="skip")
83
  content = df.fillna("").astype(str).values.tolist()
84
  result = json.dumps({"filename": os.path.basename(file_path), "rows": content})
@@ -110,12 +106,11 @@ def log_system_usage(tag=""):
110
  used, total, util = result.stdout.strip().split(", ")
111
  print(f"[{tag}] GPU: {used}MB / {total}MB | Utilization: {util}%")
112
  except Exception as e:
113
- print(f"[{tag}] ⚠️ GPU/CPU monitor failed: {e}")
114
 
115
  def init_agent():
116
  print("πŸ” Initializing model...")
117
  log_system_usage("Before Load")
118
-
119
  default_tool_path = os.path.abspath("data/new_tool.json")
120
  target_tool_path = os.path.join(tool_cache_dir, "new_tool.json")
121
  if not os.path.exists(target_tool_path):
@@ -134,12 +129,8 @@ def init_agent():
134
  agent.init_model()
135
  log_system_usage("After Load")
136
  print("βœ… Agent Ready")
137
-
138
  return agent
139
 
140
- # ---------------------------------------------------------------------------------------
141
- # Gradio UI
142
- # ---------------------------------------------------------------------------------------
143
  def create_ui(agent):
144
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
145
  gr.Markdown("<h1 style='text-align: center;'>🩺 Clinical Oversight Assistant</h1>")
@@ -174,7 +165,7 @@ Medical Records:
174
 
175
  ### Potential Oversights:
176
  """
177
- response = ""
178
  try:
179
  for chunk in agent.run_gradio_chat(
180
  message=prompt,
@@ -185,21 +176,23 @@ Medical Records:
185
  call_agent=False,
186
  conversation=[]
187
  ):
188
- if chunk is None: continue
 
189
  if isinstance(chunk, str):
190
- response += chunk
191
  elif isinstance(chunk, list):
192
- response += "".join([c.content for c in chunk if hasattr(c, 'content')])
193
- cleaned = response.strip()
194
- cleaned = re.sub(r"\[TOOL_CALLS\].*?$", "", cleaned, flags=re.DOTALL).strip()
195
- history[-1] = {"role": "assistant", "content": cleaned or "⏳ Processing..."}
196
  yield history, None
197
  except Exception as e:
198
  history[-1] = {"role": "assistant", "content": f"❌ Error: {str(e)}"}
199
  yield history, None
200
  return
201
 
202
- final_output = re.sub(r"\[TOOL_CALLS\].*?$", "", response, flags=re.DOTALL).strip()
 
203
  if not final_output:
204
  final_output = "No clear oversights identified. Recommend comprehensive review."
205
  history[-1] = {"role": "assistant", "content": final_output}
@@ -211,9 +204,6 @@ Medical Records:
211
  msg_input.submit(analyze, inputs=[msg_input, gr.State([]), file_upload], outputs=[chatbot, download_output])
212
  return demo
213
 
214
- # ---------------------------------------------------------------------------------------
215
- # Launch
216
- # ---------------------------------------------------------------------------------------
217
  if __name__ == "__main__":
218
  print("πŸš€ Launching app...")
219
  agent = init_agent()
 
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
 
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
 
 
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")
 
56
  text_chunks.append(f"=== Page {i+1} ===\n{text.strip()}")
57
  for i, page in enumerate(pdf.pages[3:max_pages], start=4):
58
  page_text = page.extract_text() or ""
59
+ if any(re.search(rf'\\b{kw}\\b', page_text.lower()) for kw in MEDICAL_KEYWORDS):
60
  text_chunks.append(f"=== Page {i} ===\n{page_text.strip()}")
61
  return "\n\n".join(text_chunks)
62
  except Exception as e:
 
74
  text = extract_priority_pages(file_path)
75
  result = json.dumps({"filename": os.path.basename(file_path), "content": text, "status": "initial"})
76
  elif file_type == "csv":
77
+ df = pd.read_csv(file_path, encoding_errors="replace", header=None, dtype=str,
78
  skip_blank_lines=False, on_bad_lines="skip")
79
  content = df.fillna("").astype(str).values.tolist()
80
  result = json.dumps({"filename": os.path.basename(file_path), "rows": content})
 
106
  used, total, util = result.stdout.strip().split(", ")
107
  print(f"[{tag}] GPU: {used}MB / {total}MB | Utilization: {util}%")
108
  except Exception as e:
109
+ print(f"[{tag}] GPU/CPU monitor failed: {e}")
110
 
111
  def init_agent():
112
  print("πŸ” Initializing model...")
113
  log_system_usage("Before Load")
 
114
  default_tool_path = os.path.abspath("data/new_tool.json")
115
  target_tool_path = os.path.join(tool_cache_dir, "new_tool.json")
116
  if not os.path.exists(target_tool_path):
 
129
  agent.init_model()
130
  log_system_usage("After Load")
131
  print("βœ… Agent Ready")
 
132
  return agent
133
 
 
 
 
134
  def create_ui(agent):
135
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
136
  gr.Markdown("<h1 style='text-align: center;'>🩺 Clinical Oversight Assistant</h1>")
 
165
 
166
  ### Potential Oversights:
167
  """
168
+ response_chunks = []
169
  try:
170
  for chunk in agent.run_gradio_chat(
171
  message=prompt,
 
176
  call_agent=False,
177
  conversation=[]
178
  ):
179
+ if not chunk:
180
+ continue
181
  if isinstance(chunk, str):
182
+ response_chunks.append(chunk)
183
  elif isinstance(chunk, list):
184
+ response_chunks.extend([c.content for c in chunk if hasattr(c, 'content')])
185
+ partial_response = "".join(response_chunks)
186
+ cleaned_partial = partial_response.split("[TOOL_CALLS]")[0].strip()
187
+ history[-1] = {"role": "assistant", "content": cleaned_partial or "⏳ Working..."}
188
  yield history, None
189
  except Exception as e:
190
  history[-1] = {"role": "assistant", "content": f"❌ Error: {str(e)}"}
191
  yield history, None
192
  return
193
 
194
+ full_response = "".join(response_chunks)
195
+ final_output = full_response.split("[TOOL_CALLS]")[0].strip()
196
  if not final_output:
197
  final_output = "No clear oversights identified. Recommend comprehensive review."
198
  history[-1] = {"role": "assistant", "content": final_output}
 
204
  msg_input.submit(analyze, inputs=[msg_input, gr.State([]), file_upload], outputs=[chatbot, download_output])
205
  return demo
206
 
 
 
 
207
  if __name__ == "__main__":
208
  print("πŸš€ Launching app...")
209
  agent = init_agent()