Update app.py
Browse files
app.py
CHANGED
@@ -38,7 +38,6 @@ os.environ.update({
|
|
38 |
|
39 |
from txagent.txagent import TxAgent
|
40 |
|
41 |
-
# Medical keywords for priority detection
|
42 |
MEDICAL_KEYWORDS = {
|
43 |
'diagnosis', 'assessment', 'plan', 'results', 'medications',
|
44 |
'allergies', 'summary', 'impression', 'findings', 'recommendations'
|
@@ -59,7 +58,7 @@ def extract_priority_pages(file_path: str, max_pages: int = 20) -> str:
|
|
59 |
text_chunks.append(f"=== Page {i+1} ===\n{(page.extract_text() or '').strip()}")
|
60 |
for i, page in enumerate(pdf.pages[3:max_pages], start=4):
|
61 |
page_text = page.extract_text() or ""
|
62 |
-
if any(re.search(rf'
|
63 |
text_chunks.append(f"=== Page {i} ===\n{page_text.strip()}")
|
64 |
return "\n\n".join(text_chunks)
|
65 |
except Exception as e:
|
@@ -69,7 +68,6 @@ def convert_file_to_json(file_path: str, file_type: str) -> str:
|
|
69 |
try:
|
70 |
h = file_hash(file_path)
|
71 |
cache_path = os.path.join(file_cache_dir, f"{h}.json")
|
72 |
-
|
73 |
if os.path.exists(cache_path):
|
74 |
return open(cache_path, "r", encoding="utf-8").read()
|
75 |
|
@@ -151,11 +149,7 @@ def create_ui(agent: TxAgent):
|
|
151 |
gr.Markdown("<h3 style='text-align: center;'>Identify potential oversights in patient care</h3>")
|
152 |
|
153 |
chatbot = gr.Chatbot(label="Analysis", height=600, type="messages")
|
154 |
-
file_upload = gr.File(
|
155 |
-
label="Upload Medical Records",
|
156 |
-
file_types=[".pdf", ".csv", ".xls", ".xlsx"],
|
157 |
-
file_count="multiple"
|
158 |
-
)
|
159 |
msg_input = gr.Textbox(placeholder="Ask about potential oversights...", show_label=False)
|
160 |
send_btn = gr.Button("Analyze", variant="primary")
|
161 |
conversation_state = gr.State([])
|
@@ -163,7 +157,8 @@ def create_ui(agent: TxAgent):
|
|
163 |
def analyze_potential_oversights(message: str, history: list, conversation: list, files: list):
|
164 |
start_time = time.time()
|
165 |
try:
|
166 |
-
history.append(
|
|
|
167 |
yield history
|
168 |
|
169 |
extracted_data = ""
|
@@ -172,21 +167,21 @@ def create_ui(agent: TxAgent):
|
|
172 |
futures = [executor.submit(convert_file_to_json, f.name, f.name.split(".")[-1].lower()) for f in files if hasattr(f, 'name')]
|
173 |
extracted_data = "\n".join([sanitize_utf8(f.result()) for f in as_completed(futures)])
|
174 |
|
175 |
-
analysis_prompt = """Review these medical records and identify EXACTLY what might have been missed:
|
176 |
1. List potential missed diagnoses
|
177 |
2. Flag any medication conflicts
|
178 |
3. Note incomplete assessments
|
179 |
4. Highlight abnormal results needing follow-up
|
180 |
|
181 |
Medical Records:
|
182 |
-
{
|
183 |
|
184 |
Provide ONLY the potential oversights in this format:
|
185 |
|
186 |
### Potential Oversights:
|
187 |
1. [Missed diagnosis] - [Evidence from records]
|
188 |
2. [Medication issue] - [Supporting data]
|
189 |
-
3. [Assessment gap] - [Relevant findings]"""
|
190 |
|
191 |
response = []
|
192 |
for chunk in agent.run_gradio_chat(
|
@@ -202,9 +197,8 @@ Provide ONLY the potential oversights in this format:
|
|
202 |
response.append(chunk)
|
203 |
elif isinstance(chunk, list):
|
204 |
response.extend([c.content for c in chunk if hasattr(c, 'content')])
|
205 |
-
|
206 |
if len(response) % 3 == 0:
|
207 |
-
history[-1] =
|
208 |
yield history
|
209 |
|
210 |
final_output = "".join(response).strip()
|
@@ -214,12 +208,12 @@ Provide ONLY the potential oversights in this format:
|
|
214 |
if not final_output.startswith(("1.", "-", "*", "#")):
|
215 |
final_output = "• " + final_output.replace("\n", "\n• ")
|
216 |
|
217 |
-
history[-1] =
|
218 |
print(f"Analysis completed in {time.time()-start_time:.2f}s")
|
219 |
yield history
|
220 |
|
221 |
except Exception as e:
|
222 |
-
history.append(
|
223 |
yield history
|
224 |
|
225 |
inputs = [msg_input, chatbot, conversation_state, file_upload]
|
|
|
38 |
|
39 |
from txagent.txagent import TxAgent
|
40 |
|
|
|
41 |
MEDICAL_KEYWORDS = {
|
42 |
'diagnosis', 'assessment', 'plan', 'results', 'medications',
|
43 |
'allergies', 'summary', 'impression', 'findings', 'recommendations'
|
|
|
58 |
text_chunks.append(f"=== Page {i+1} ===\n{(page.extract_text() or '').strip()}")
|
59 |
for i, page in enumerate(pdf.pages[3:max_pages], start=4):
|
60 |
page_text = page.extract_text() or ""
|
61 |
+
if any(re.search(rf'\\b{kw}\\b', page_text.lower()) for kw in MEDICAL_KEYWORDS):
|
62 |
text_chunks.append(f"=== Page {i} ===\n{page_text.strip()}")
|
63 |
return "\n\n".join(text_chunks)
|
64 |
except Exception as e:
|
|
|
68 |
try:
|
69 |
h = file_hash(file_path)
|
70 |
cache_path = os.path.join(file_cache_dir, f"{h}.json")
|
|
|
71 |
if os.path.exists(cache_path):
|
72 |
return open(cache_path, "r", encoding="utf-8").read()
|
73 |
|
|
|
149 |
gr.Markdown("<h3 style='text-align: center;'>Identify potential oversights in patient care</h3>")
|
150 |
|
151 |
chatbot = gr.Chatbot(label="Analysis", height=600, type="messages")
|
152 |
+
file_upload = gr.File(label="Upload Medical Records", file_types=[".pdf", ".csv", ".xls", ".xlsx"], file_count="multiple")
|
|
|
|
|
|
|
|
|
153 |
msg_input = gr.Textbox(placeholder="Ask about potential oversights...", show_label=False)
|
154 |
send_btn = gr.Button("Analyze", variant="primary")
|
155 |
conversation_state = gr.State([])
|
|
|
157 |
def analyze_potential_oversights(message: str, history: list, conversation: list, files: list):
|
158 |
start_time = time.time()
|
159 |
try:
|
160 |
+
history.append({"role": "user", "content": message})
|
161 |
+
history.append({"role": "assistant", "content": "Analyzing records for potential oversights..."})
|
162 |
yield history
|
163 |
|
164 |
extracted_data = ""
|
|
|
167 |
futures = [executor.submit(convert_file_to_json, f.name, f.name.split(".")[-1].lower()) for f in files if hasattr(f, 'name')]
|
168 |
extracted_data = "\n".join([sanitize_utf8(f.result()) for f in as_completed(futures)])
|
169 |
|
170 |
+
analysis_prompt = f"""Review these medical records and identify EXACTLY what might have been missed:
|
171 |
1. List potential missed diagnoses
|
172 |
2. Flag any medication conflicts
|
173 |
3. Note incomplete assessments
|
174 |
4. Highlight abnormal results needing follow-up
|
175 |
|
176 |
Medical Records:
|
177 |
+
{extracted_data[:15000]}
|
178 |
|
179 |
Provide ONLY the potential oversights in this format:
|
180 |
|
181 |
### Potential Oversights:
|
182 |
1. [Missed diagnosis] - [Evidence from records]
|
183 |
2. [Medication issue] - [Supporting data]
|
184 |
+
3. [Assessment gap] - [Relevant findings]"""
|
185 |
|
186 |
response = []
|
187 |
for chunk in agent.run_gradio_chat(
|
|
|
197 |
response.append(chunk)
|
198 |
elif isinstance(chunk, list):
|
199 |
response.extend([c.content for c in chunk if hasattr(c, 'content')])
|
|
|
200 |
if len(response) % 3 == 0:
|
201 |
+
history[-1] = {"role": "assistant", "content": "".join(response).strip()}
|
202 |
yield history
|
203 |
|
204 |
final_output = "".join(response).strip()
|
|
|
208 |
if not final_output.startswith(("1.", "-", "*", "#")):
|
209 |
final_output = "• " + final_output.replace("\n", "\n• ")
|
210 |
|
211 |
+
history[-1] = {"role": "assistant", "content": f"### Potential Clinical Oversights:\n{final_output}"}
|
212 |
print(f"Analysis completed in {time.time()-start_time:.2f}s")
|
213 |
yield history
|
214 |
|
215 |
except Exception as e:
|
216 |
+
history.append({"role": "assistant", "content": f"❌ Analysis failed: {str(e)}"})
|
217 |
yield history
|
218 |
|
219 |
inputs = [msg_input, chatbot, conversation_state, file_upload]
|