Ali2206 commited on
Commit
dfe34bb
·
verified ·
1 Parent(s): 1ab3cf4

Update ui/ui_core.py

Browse files
Files changed (1) hide show
  1. ui/ui_core.py +64 -43
ui/ui_core.py CHANGED
@@ -1,47 +1,70 @@
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from PyPDF2 import PdfReader
3
- import docx
4
-
5
- def extract_text_from_uploaded_file(file_path):
6
- if file_path.endswith(".pdf"):
7
- try:
8
- reader = PdfReader(file_path)
9
- return "\n".join(page.extract_text() or "" for page in reader.pages)
10
- except Exception as e:
11
- return f"[Error extracting PDF text: {e}]"
12
- elif file_path.endswith(".txt"):
13
- try:
14
- with open(file_path, "r", encoding="utf-8") as f:
15
- return f.read()
16
- except Exception as e:
17
- return f"[Error reading text file: {e}]"
18
- elif file_path.endswith(".docx"):
19
- try:
20
- doc = docx.Document(file_path)
21
- return "\n".join([p.text for p in doc.paragraphs])
22
- except Exception as e:
23
- return f"[Error reading DOCX: {e}]"
24
- else:
25
- return "[Unsupported file type for text extraction]"
26
-
27
- def create_ui(agent):
 
 
 
 
 
28
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
29
- gr.Markdown("<h1 style='text-align: center;'>💊 TxAgent: Therapeutic Reasoning</h1>")
30
  chatbot = gr.Chatbot(label="TxAgent", height=600, type="messages")
31
 
32
- file_upload = gr.File(label="Upload Medical File", file_types=[".pdf", ".txt", ".docx"])
33
- message_input = gr.Textbox(placeholder="Ask a biomedical question...", show_label=False)
34
  send_button = gr.Button("Send", variant="primary")
35
  conversation_state = gr.State([])
36
 
37
- def handle_chat(message, history, conversation, uploaded_file):
38
- file_text = ""
39
- if uploaded_file:
40
- file_text = extract_text_from_uploaded_file(uploaded_file.name)
 
 
41
 
42
- # Append file text to the question
43
- if file_text:
44
- message += f"\n\n[Document Content Extracted from Upload]:\n{file_text}"
 
 
 
 
 
 
45
 
46
  generator = agent.run_gradio_chat(
47
  message=message,
@@ -51,6 +74,7 @@ def create_ui(agent):
51
  max_token=8192,
52
  call_agent=False,
53
  conversation=conversation,
 
54
  max_round=30
55
  )
56
  for update in generator:
@@ -60,11 +84,8 @@ def create_ui(agent):
60
  send_button.click(fn=handle_chat, inputs=inputs, outputs=chatbot)
61
  message_input.submit(fn=handle_chat, inputs=inputs, outputs=chatbot)
62
 
63
- gr.Examples(
64
- examples=[
65
- ["Upload the files"],
66
- ],
67
- inputs=message_input,
68
- )
69
 
70
- return demo
 
1
+
2
+ import sys
3
+ import os
4
+
5
+ # ✅ Add src to Python path
6
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src")))
7
+
8
+ from txagent.txagent import TxAgent # ✅ Now this will work
9
+ import pandas as pd
10
+ import pdfplumber
11
  import gradio as gr
12
+
13
+
14
+ def extract_structured_text_from_csv(file_path):
15
+ try:
16
+ df = pd.read_csv(file_path)
17
+ relevant_columns = [
18
+ "Booking Number", "Form Name", "Form Item",
19
+ "Item Response", "Interviewer", "Interview Date"
20
+ ]
21
+ df = df[[col for col in relevant_columns if col in df.columns]]
22
+ return df.to_string(index=False)
23
+ except Exception as e:
24
+ return f"Error parsing CSV: {e}"
25
+
26
+
27
+ def extract_structured_text_from_pdf(file_path):
28
+ extracted = []
29
+ try:
30
+ with pdfplumber.open(file_path) as pdf:
31
+ for page in pdf.pages:
32
+ tables = page.extract_tables()
33
+ for table in tables:
34
+ for row in table:
35
+ if any(row):
36
+ extracted.append("\t".join([cell or "" for cell in row]))
37
+ return "\n".join(extracted)
38
+ except Exception as e:
39
+ return f"Error parsing PDF: {e}"
40
+
41
+
42
+ def create_ui(agent: TxAgent):
43
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
44
+ gr.Markdown("<h1 style='text-align: center;'>\ud83d\udc8a TxAgent: Therapeutic Reasoning</h1>")
45
  chatbot = gr.Chatbot(label="TxAgent", height=600, type="messages")
46
 
47
+ file_upload = gr.File(label="Upload Medical File", file_types=[".pdf", ".txt", ".docx", ".jpg", ".png", ".csv"], file_count="multiple")
48
+ message_input = gr.Textbox(placeholder="Ask a biomedical question or just upload the files...", show_label=False)
49
  send_button = gr.Button("Send", variant="primary")
50
  conversation_state = gr.State([])
51
 
52
+ def handle_chat(message, history, conversation, uploaded_files):
53
+ context = (
54
+ "You are a clinical AI reviewing patient form data from interviews. "
55
+ "Your task is to analyze the responses, dates, and items, and reason step-by-step about "
56
+ "what the doctor might have overlooked. Do not summarize or answer yet — just reason step-by-step first."
57
+ )
58
 
59
+ if uploaded_files:
60
+ extracted_text = ""
61
+ for file in uploaded_files:
62
+ path = file.name
63
+ if path.endswith(".csv"):
64
+ extracted_text += extract_structured_text_from_csv(path) + "\n"
65
+ elif path.endswith(".pdf"):
66
+ extracted_text += extract_structured_text_from_pdf(path) + "\n"
67
+ message = f"{context}\n\n---\n{extracted_text.strip()}\n---\n\nNow reason what the doctor might have missed."
68
 
69
  generator = agent.run_gradio_chat(
70
  message=message,
 
74
  max_token=8192,
75
  call_agent=False,
76
  conversation=conversation,
77
+ uploaded_files=uploaded_files,
78
  max_round=30
79
  )
80
  for update in generator:
 
84
  send_button.click(fn=handle_chat, inputs=inputs, outputs=chatbot)
85
  message_input.submit(fn=handle_chat, inputs=inputs, outputs=chatbot)
86
 
87
+ gr.Examples([
88
+ ["Upload the files"],
89
+ ], inputs=message_input)
 
 
 
90
 
91
+ return demo