Ali2206 commited on
Commit
728def5
·
verified ·
1 Parent(s): f469559

Update ui/ui_core.py

Browse files
Files changed (1) hide show
  1. ui/ui_core.py +28 -13
ui/ui_core.py CHANGED
@@ -1,46 +1,57 @@
1
  import sys
2
  import os
 
 
 
3
 
4
  # ✅ Add src to Python path
5
  sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src")))
6
-
7
  from txagent.txagent import TxAgent
8
- import pandas as pd
9
- import pdfplumber
10
- import gradio as gr
11
 
12
- def extract_all_text_from_csv(file_path):
 
13
  try:
14
- df = pd.read_csv(file_path)
 
 
15
  return df.to_string(index=False)
16
  except Exception as e:
17
  return f"Error parsing CSV: {e}"
18
 
19
- def extract_all_text_from_pdf(file_path):
 
20
  extracted = []
21
  try:
22
  with pdfplumber.open(file_path) as pdf:
23
- for page in pdf.pages:
 
24
  tables = page.extract_tables()
25
  for table in tables:
26
  for row in table:
27
  if any(row):
28
  extracted.append("\t".join([cell or "" for cell in row]))
 
 
29
  return "\n".join(extracted)
30
  except Exception as e:
31
  return f"Error parsing PDF: {e}"
32
 
 
33
  def create_ui(agent: TxAgent):
34
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
35
  gr.Markdown("<h1 style='text-align: center;'>💊 TxAgent: Therapeutic Reasoning</h1>")
36
  chatbot = gr.Chatbot(label="TxAgent", height=600, type="messages")
37
 
38
- file_upload = gr.File(label="Upload Medical File", file_types=[".pdf", ".txt", ".docx", ".jpg", ".png", ".csv"], file_count="multiple")
 
 
 
 
39
  message_input = gr.Textbox(placeholder="Ask a biomedical question or just upload the files...", show_label=False)
40
  send_button = gr.Button("Send", variant="primary")
41
  conversation_state = gr.State([])
42
 
43
- def handle_chat(message, history, conversation, uploaded_files):
44
  context = (
45
  "You are a clinical AI reviewing medical interview or form data. "
46
  "Analyze the extracted content and reason step-by-step about what the doctor could have missed. "
@@ -49,14 +60,18 @@ def create_ui(agent: TxAgent):
49
 
50
  if uploaded_files:
51
  extracted_text = ""
52
- for file in uploaded_files:
 
 
53
  path = file.name
54
  if path.endswith(".csv"):
55
- extracted_text += extract_all_text_from_csv(path) + "\n"
56
  elif path.endswith(".pdf"):
57
- extracted_text += extract_all_text_from_pdf(path) + "\n"
58
  else:
59
  extracted_text += f"(Uploaded file: {os.path.basename(path)})\n"
 
 
60
 
61
  message = f"{context}\n\n---\n{extracted_text.strip()}\n---\n\nNow reason what the doctor might have missed."
62
 
 
1
  import sys
2
  import os
3
+ import pandas as pd
4
+ import pdfplumber
5
+ import gradio as gr
6
 
7
  # ✅ Add src to Python path
8
  sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src")))
 
9
  from txagent.txagent import TxAgent
 
 
 
10
 
11
+
12
+ def extract_all_text_from_csv(file_path, progress=None, index=0, total=1):
13
  try:
14
+ df = pd.read_csv(file_path, low_memory=False)
15
+ if progress:
16
+ progress((index + 1) / total, desc=f"Processed CSV: {os.path.basename(file_path)}")
17
  return df.to_string(index=False)
18
  except Exception as e:
19
  return f"Error parsing CSV: {e}"
20
 
21
+
22
+ def extract_all_text_from_pdf(file_path, progress=None, index=0, total=1):
23
  extracted = []
24
  try:
25
  with pdfplumber.open(file_path) as pdf:
26
+ num_pages = len(pdf.pages)
27
+ for i, page in enumerate(pdf.pages):
28
  tables = page.extract_tables()
29
  for table in tables:
30
  for row in table:
31
  if any(row):
32
  extracted.append("\t".join([cell or "" for cell in row]))
33
+ if progress:
34
+ progress((index + i / num_pages) / total, desc=f"Parsing PDF: {os.path.basename(file_path)} ({i+1}/{num_pages})")
35
  return "\n".join(extracted)
36
  except Exception as e:
37
  return f"Error parsing PDF: {e}"
38
 
39
+
40
  def create_ui(agent: TxAgent):
41
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
42
  gr.Markdown("<h1 style='text-align: center;'>💊 TxAgent: Therapeutic Reasoning</h1>")
43
  chatbot = gr.Chatbot(label="TxAgent", height=600, type="messages")
44
 
45
+ file_upload = gr.File(
46
+ label="Upload Medical File",
47
+ file_types=[".pdf", ".txt", ".docx", ".jpg", ".png", ".csv"],
48
+ file_count="multiple"
49
+ )
50
  message_input = gr.Textbox(placeholder="Ask a biomedical question or just upload the files...", show_label=False)
51
  send_button = gr.Button("Send", variant="primary")
52
  conversation_state = gr.State([])
53
 
54
+ def handle_chat(message, history, conversation, uploaded_files, progress=gr.Progress()):
55
  context = (
56
  "You are a clinical AI reviewing medical interview or form data. "
57
  "Analyze the extracted content and reason step-by-step about what the doctor could have missed. "
 
60
 
61
  if uploaded_files:
62
  extracted_text = ""
63
+ total_files = len(uploaded_files)
64
+
65
+ for index, file in enumerate(uploaded_files):
66
  path = file.name
67
  if path.endswith(".csv"):
68
+ extracted_text += extract_all_text_from_csv(path, progress, index, total_files) + "\n"
69
  elif path.endswith(".pdf"):
70
+ extracted_text += extract_all_text_from_pdf(path, progress, index, total_files) + "\n"
71
  else:
72
  extracted_text += f"(Uploaded file: {os.path.basename(path)})\n"
73
+ if progress:
74
+ progress((index + 1) / total_files, desc=f"Skipping unsupported file: {os.path.basename(path)}")
75
 
76
  message = f"{context}\n\n---\n{extracted_text.strip()}\n---\n\nNow reason what the doctor might have missed."
77