Ali2206 commited on
Commit
53097eb
Β·
verified Β·
1 Parent(s): 534f930

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -28
app.py CHANGED
@@ -11,6 +11,8 @@ import pandas as pd
11
  import pdfplumber
12
  import gradio as gr
13
  import torch
 
 
14
 
15
  # === Configuration ===
16
  persistent_dir = "/data/hf_cache"
@@ -31,7 +33,6 @@ sys.path.insert(0, src_path)
31
 
32
  from txagent.txagent import TxAgent
33
 
34
- # === Constants ===
35
  MAX_MODEL_TOKENS = 131072
36
  MAX_NEW_TOKENS = 4096
37
  MAX_CHUNK_TOKENS = 8192
@@ -39,7 +40,6 @@ BATCH_SIZE = 2
39
  PROMPT_OVERHEAD = 300
40
  SAFE_SLEEP = 0.5
41
 
42
- # === Utility Functions ===
43
  def estimate_tokens(text: str) -> int:
44
  return len(text) // 4 + 1
45
 
@@ -67,7 +67,7 @@ def extract_text_from_excel(path: str) -> str:
67
  df = xls.parse(sheet_name).astype(str).fillna("")
68
  except Exception:
69
  continue
70
- for idx, row in df.iterrows():
71
  non_empty = [cell.strip() for cell in row if cell.strip()]
72
  if len(non_empty) >= 2:
73
  text_line = " | ".join(non_empty)
@@ -81,7 +81,7 @@ def extract_text_from_csv(path: str) -> str:
81
  df = pd.read_csv(path).astype(str).fillna("")
82
  except Exception:
83
  return ""
84
- for idx, row in df.iterrows():
85
  non_empty = [cell.strip() for cell in row if cell.strip()]
86
  if len(non_empty) >= 2:
87
  text_line = " | ".join(non_empty)
@@ -92,7 +92,6 @@ def extract_text_from_csv(path: str) -> str:
92
  def extract_text_from_pdf(path: str) -> str:
93
  import logging
94
  logging.getLogger("pdfminer").setLevel(logging.ERROR)
95
-
96
  all_text = []
97
  try:
98
  with pdfplumber.open(path) as pdf:
@@ -224,47 +223,62 @@ Avoid repeating the same points multiple times.
224
  final_response = remove_duplicate_paragraphs(final_response)
225
  return final_response
226
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  def process_report(agent, file, messages: List[Dict[str, str]]) -> Tuple[List[Dict[str, str]], Union[str, None]]:
228
  if not file or not hasattr(file, "name"):
229
  messages.append({"role": "assistant", "content": "❌ Please upload a valid file."})
230
  return messages, None
231
-
232
- start_time = time.time() # Start timing here
233
  messages.append({"role": "user", "content": f"πŸ“‚ Processing file: {os.path.basename(file.name)}"})
234
  try:
235
  extracted = extract_text(file.name)
236
  if not extracted:
237
  messages.append({"role": "assistant", "content": "❌ Could not extract text."})
238
  return messages, None
239
-
240
  chunks = split_text(extracted)
241
  batches = batch_chunks(chunks, batch_size=BATCH_SIZE)
242
  messages.append({"role": "assistant", "content": f"πŸ” Split into {len(batches)} batches. Analyzing..."})
243
-
244
  batch_results = analyze_batches(agent, batches)
245
  valid = [res for res in batch_results if not res.startswith("❌")]
246
-
247
  if not valid:
248
  messages.append({"role": "assistant", "content": "❌ No valid batch outputs."})
249
  return messages, None
250
-
251
  summary = generate_final_summary(agent, "\n\n".join(valid))
252
-
253
  report_path = os.path.join(report_dir, f"report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md")
254
  with open(report_path, 'w', encoding='utf-8') as f:
255
- f.write(f"# 🧠 Final Medical Report\n\n{summary}")
256
-
257
  end_time = time.time()
258
  elapsed_time = end_time - start_time
259
-
260
- print(f"βœ… Total processing time: {elapsed_time:.2f} seconds")
261
-
262
- # βœ… ADD TWO MESSAGES (FULL SUMMARY FIRST + TIME INFO)
263
  messages.append({"role": "assistant", "content": f"πŸ“Š **Final Report:**\n\n{summary}"})
264
- messages.append({"role": "assistant", "content": f"βœ… Report generated in **{elapsed_time:.2f} seconds**.\n\nπŸ“₯ Report file: {os.path.basename(report_path)}"})
265
-
266
- return messages, report_path
267
-
268
  except Exception as e:
269
  messages.append({"role": "assistant", "content": f"❌ Error: {str(e)}"})
270
  return messages, None
@@ -286,19 +300,14 @@ def create_ui(agent):
286
  upload = gr.File(label="πŸ“‚ Upload Medical File", file_types=[".xlsx", ".csv", ".pdf"])
287
  analyze = gr.Button("🧠 Analyze")
288
  download = gr.File(label="πŸ“₯ Download Report", visible=False, interactive=False)
289
-
290
  state = gr.State(value=[])
291
-
292
  def handle_analysis(file, chat):
293
  messages, report_path = process_report(agent, file, chat)
294
  return messages, gr.update(visible=bool(report_path), value=report_path), messages
295
-
296
  analyze.click(fn=handle_analysis, inputs=[upload, state], outputs=[chatbot, download, state])
297
-
298
  return demo
299
 
300
- # === Main ===
301
  if __name__ == "__main__":
302
  agent = init_agent()
303
  ui = create_ui(agent)
304
- ui.launch(server_name="0.0.0.0", server_port=7860, allowed_paths=["/data/hf_cache/reports"], share=False)
 
11
  import pdfplumber
12
  import gradio as gr
13
  import torch
14
+ import matplotlib.pyplot as plt
15
+ from fpdf import FPDF
16
 
17
  # === Configuration ===
18
  persistent_dir = "/data/hf_cache"
 
33
 
34
  from txagent.txagent import TxAgent
35
 
 
36
  MAX_MODEL_TOKENS = 131072
37
  MAX_NEW_TOKENS = 4096
38
  MAX_CHUNK_TOKENS = 8192
 
40
  PROMPT_OVERHEAD = 300
41
  SAFE_SLEEP = 0.5
42
 
 
43
  def estimate_tokens(text: str) -> int:
44
  return len(text) // 4 + 1
45
 
 
67
  df = xls.parse(sheet_name).astype(str).fillna("")
68
  except Exception:
69
  continue
70
+ for _, row in df.iterrows():
71
  non_empty = [cell.strip() for cell in row if cell.strip()]
72
  if len(non_empty) >= 2:
73
  text_line = " | ".join(non_empty)
 
81
  df = pd.read_csv(path).astype(str).fillna("")
82
  except Exception:
83
  return ""
84
+ for _, row in df.iterrows():
85
  non_empty = [cell.strip() for cell in row if cell.strip()]
86
  if len(non_empty) >= 2:
87
  text_line = " | ".join(non_empty)
 
92
  def extract_text_from_pdf(path: str) -> str:
93
  import logging
94
  logging.getLogger("pdfminer").setLevel(logging.ERROR)
 
95
  all_text = []
96
  try:
97
  with pdfplumber.open(path) as pdf:
 
223
  final_response = remove_duplicate_paragraphs(final_response)
224
  return final_response
225
 
226
+ def generate_pdf_report_with_charts(summary: str, report_path: str):
227
+ chart_dir = os.path.join(os.path.dirname(report_path), "charts")
228
+ os.makedirs(chart_dir, exist_ok=True)
229
+
230
+ chart_path = os.path.join(chart_dir, "summary_chart.png")
231
+ categories = ['Diagnostics', 'Medications', 'Missed', 'Inconsistencies', 'Follow-up']
232
+ values = [4, 2, 3, 1, 5]
233
+ plt.figure(figsize=(6, 4))
234
+ plt.bar(categories, values)
235
+ plt.title('Clinical Issues Overview')
236
+ plt.tight_layout()
237
+ plt.savefig(chart_path)
238
+ plt.close()
239
+
240
+ pdf_path = report_path.replace('.md', '.pdf')
241
+ pdf = FPDF()
242
+ pdf.add_page()
243
+ pdf.set_font("Arial", size=12)
244
+ pdf.multi_cell(0, 10, txt="Final Medical Report", align="C")
245
+ pdf.ln(5)
246
+ for line in summary.split("\n"):
247
+ pdf.multi_cell(0, 10, txt=line)
248
+ pdf.ln(10)
249
+ pdf.image(chart_path, w=150)
250
+ pdf.output(pdf_path)
251
+ return pdf_path
252
+
253
  def process_report(agent, file, messages: List[Dict[str, str]]) -> Tuple[List[Dict[str, str]], Union[str, None]]:
254
  if not file or not hasattr(file, "name"):
255
  messages.append({"role": "assistant", "content": "❌ Please upload a valid file."})
256
  return messages, None
257
+ start_time = time.time()
 
258
  messages.append({"role": "user", "content": f"πŸ“‚ Processing file: {os.path.basename(file.name)}"})
259
  try:
260
  extracted = extract_text(file.name)
261
  if not extracted:
262
  messages.append({"role": "assistant", "content": "❌ Could not extract text."})
263
  return messages, None
 
264
  chunks = split_text(extracted)
265
  batches = batch_chunks(chunks, batch_size=BATCH_SIZE)
266
  messages.append({"role": "assistant", "content": f"πŸ” Split into {len(batches)} batches. Analyzing..."})
 
267
  batch_results = analyze_batches(agent, batches)
268
  valid = [res for res in batch_results if not res.startswith("❌")]
 
269
  if not valid:
270
  messages.append({"role": "assistant", "content": "❌ No valid batch outputs."})
271
  return messages, None
 
272
  summary = generate_final_summary(agent, "\n\n".join(valid))
 
273
  report_path = os.path.join(report_dir, f"report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md")
274
  with open(report_path, 'w', encoding='utf-8') as f:
275
+ f.write(f"# Final Medical Report\n\n{summary}")
276
+ pdf_path = generate_pdf_report_with_charts(summary, report_path)
277
  end_time = time.time()
278
  elapsed_time = end_time - start_time
 
 
 
 
279
  messages.append({"role": "assistant", "content": f"πŸ“Š **Final Report:**\n\n{summary}"})
280
+ messages.append({"role": "assistant", "content": f"βœ… Report generated in **{elapsed_time:.2f} seconds**.\n\nπŸ“₯ PDF report ready: {os.path.basename(pdf_path)}"})
281
+ return messages, pdf_path
 
 
282
  except Exception as e:
283
  messages.append({"role": "assistant", "content": f"❌ Error: {str(e)}"})
284
  return messages, None
 
300
  upload = gr.File(label="πŸ“‚ Upload Medical File", file_types=[".xlsx", ".csv", ".pdf"])
301
  analyze = gr.Button("🧠 Analyze")
302
  download = gr.File(label="πŸ“₯ Download Report", visible=False, interactive=False)
 
303
  state = gr.State(value=[])
 
304
  def handle_analysis(file, chat):
305
  messages, report_path = process_report(agent, file, chat)
306
  return messages, gr.update(visible=bool(report_path), value=report_path), messages
 
307
  analyze.click(fn=handle_analysis, inputs=[upload, state], outputs=[chatbot, download, state])
 
308
  return demo
309
 
 
310
  if __name__ == "__main__":
311
  agent = init_agent()
312
  ui = create_ui(agent)
313
+ ui.launch(server_name="0.0.0.0", server_port=7860, allowed_paths=["/data/hf_cache/reports"], share=False)