SamarthPujari commited on
Commit
ecac0c6
·
verified ·
1 Parent(s): 30f4e01

Update Gradio_UI.py

Browse files
Files changed (1) hide show
  1. Gradio_UI.py +82 -28
Gradio_UI.py CHANGED
@@ -1,36 +1,65 @@
1
  import gradio as gr
2
  import os
3
- # Import the themes module
4
- import gradio.themes as themes
5
 
6
  class GradioUI:
7
  def __init__(self, agent):
8
  self.agent = agent
9
 
10
- # Keep the process_input method as is
11
  def process_input(self, query: str, pdf_file: gr.File = None):
12
  """
13
- Processes user input...
 
 
 
 
 
 
 
 
 
14
  """
15
- # ... (your existing process_input code)
16
  if pdf_file is not None and query and query.strip():
17
  print(f"PDF file uploaded: {pdf_file.name}")
18
  print(f"Query (assumed question for PDF): {query}")
19
  try:
 
 
 
 
20
  print("Detected PDF upload and query. Calling document_qna_tool...")
 
21
  response = self.agent.tools[4](pdf_file.name, query)
22
  print("Document Q&A tool finished.")
 
 
 
 
 
 
 
 
23
  return response
24
 
25
  except IndexError:
26
  return "Error: Document Q&A tool not found at the expected index (4). Check agent tool setup in app.py."
27
  except Exception as e:
28
  print(f"Error during Document Q&A tool execution: {e}")
 
 
 
 
 
 
 
 
29
  return f"An error occurred during Document Q&A: {str(e)}"
30
 
 
31
  elif query and query.strip():
32
  print(f"No PDF file or query is for general task. Processing with agent.run(): {query}")
33
  try:
 
34
  response = self.agent.run(query)
35
  print("Agent.run finished for general query.")
36
  return response
@@ -38,7 +67,16 @@ class GradioUI:
38
  print(f"Error during agent.run: {e}")
39
  return f"An error occurred while processing your request: {str(e)}"
40
 
 
41
  elif pdf_file is not None:
 
 
 
 
 
 
 
 
42
  return "Please enter a question in the textbox to ask about the uploaded PDF."
43
  else:
44
  return "Please enter a request or upload a document for analysis."
@@ -46,11 +84,9 @@ class GradioUI:
46
 
47
  def launch(self):
48
  """
49
- Launches the Gradio user interface with a theme.
50
  """
51
- # Apply a theme here using the 'theme' argument
52
- # You can try different themes like themes.Soft(), themes.Glass(), themes.Monochrome()
53
- with gr.Blocks(theme=themes.Soft()) as demo: # <--- Added theme argument here
54
  gr.Markdown("# Multi-Tool AI Agent with Document Upload")
55
  gr.Markdown(
56
  "Enter your request and optionally upload a PDF document. "
@@ -58,22 +94,27 @@ class GradioUI:
58
  "Otherwise, use the text box for general requests (weather, search, etc.)."
59
  )
60
 
61
- with gr.Row():
62
- query_input = gr.Textbox(
63
- label="Enter your request or question:",
64
- placeholder="e.g., What is the weather in London? Search for the latest news about AI. What does this document say about [topic]? Summarize the document.",
65
- lines=3,
66
- interactive=True,
67
- scale=3
68
- )
69
-
70
- pdf_upload = gr.File(
71
- label="Upload PDF (Optional)",
72
- file_types=[".pdf"],
73
- interactive=True,
74
- scale=1
75
- )
 
76
 
 
 
 
 
77
  agent_output = gr.Textbox(
78
  label="Agent's Response:",
79
  interactive=False,
@@ -81,13 +122,26 @@ class GradioUI:
81
  autoscroll=True
82
  )
83
 
84
- submit_btn = gr.Button("Submit")
85
-
86
  submit_btn.click(
87
  fn=self.process_input,
88
- inputs=[query_input, pdf_upload],
89
- outputs=agent_output
90
  )
91
 
 
 
 
 
 
 
 
 
 
 
 
92
  # Launch the Gradio interface
 
 
93
  demo.launch(share=False, inline=False)
 
1
  import gradio as gr
2
  import os
 
 
3
 
4
  class GradioUI:
5
  def __init__(self, agent):
6
  self.agent = agent
7
 
 
8
  def process_input(self, query: str, pdf_file: gr.File = None):
9
  """
10
+ Processes user input, which can include a text query and optionally a PDF file.
11
+ If a PDF is uploaded, it assumes the query is a question about it and calls
12
+ the Document Q&A tool directly. Otherwise, it sends the query to the agent.run() method.
13
+
14
+ Args:
15
+ query (str): The text query from the user.
16
+ pdf_file (gr.File, optional): The uploaded PDF file object provided by Gradio. Defaults to None.
17
+
18
+ Returns:
19
+ str: The response from the agent or tool.
20
  """
21
+ # Check if a PDF file is uploaded AND there is a text query (assumed to be the question)
22
  if pdf_file is not None and query and query.strip():
23
  print(f"PDF file uploaded: {pdf_file.name}")
24
  print(f"Query (assumed question for PDF): {query}")
25
  try:
26
+ # --- Call the Document Q&A tool directly ---
27
+ # We assume the document_qna_tool is at index 4 as per your app.py initialization
28
+ # Gradio's gr.File object has a .name attribute which is the file path
29
+ # The document_qna_tool expects a file path string.
30
  print("Detected PDF upload and query. Calling document_qna_tool...")
31
+ # The tool signature is document_qna_tool(pdf_path: str, question: str)
32
  response = self.agent.tools[4](pdf_file.name, query)
33
  print("Document Q&A tool finished.")
34
+ # Optional: Clean up the uploaded file after processing
35
+ # import os
36
+ # try:
37
+ # if os.path.exists(pdf_file.name):
38
+ # os.remove(pdf_file.name)
39
+ # print(f"Cleaned up file: {pdf_file.name}")
40
+ # except Exception as e:
41
+ # print(f"Error cleaning up file {pdf_file.name}: {e}")
42
  return response
43
 
44
  except IndexError:
45
  return "Error: Document Q&A tool not found at the expected index (4). Check agent tool setup in app.py."
46
  except Exception as e:
47
  print(f"Error during Document Q&A tool execution: {e}")
48
+ # Optional: Clean up the uploaded file on error too
49
+ # import os
50
+ # try:
51
+ # if os.path.exists(pdf_file.name):
52
+ # os.remove(pdf_file.name)
53
+ # print(f"Cleaned up file on error: {pdf_file.name}")
54
+ # except Exception as e:
55
+ # print(f"Error cleaning up file {pdf_file.name} on error: {e}")
56
  return f"An error occurred during Document Q&A: {str(e)}"
57
 
58
+ # If no PDF file, or query is empty when file is present, handle as a general agent query
59
  elif query and query.strip():
60
  print(f"No PDF file or query is for general task. Processing with agent.run(): {query}")
61
  try:
62
+ # --- Call the agent's run method for general queries ---
63
  response = self.agent.run(query)
64
  print("Agent.run finished for general query.")
65
  return response
 
67
  print(f"Error during agent.run: {e}")
68
  return f"An error occurred while processing your request: {str(e)}"
69
 
70
+ # Handle cases where only a PDF is uploaded without a question, or no input at all
71
  elif pdf_file is not None:
72
+ # Optional: Clean up the uploaded file if no question was provided
73
+ # import os
74
+ # try:
75
+ # if os.path.exists(pdf_file.name):
76
+ # os.remove(pdf_file.name)
77
+ # print(f"Cleaned up file: {pdf_file.name}")
78
+ # except Exception as e:
79
+ # print(f"Error cleaning up file {pdf_file.name}: {e}")
80
  return "Please enter a question in the textbox to ask about the uploaded PDF."
81
  else:
82
  return "Please enter a request or upload a document for analysis."
 
84
 
85
  def launch(self):
86
  """
87
+ Launches the Gradio user interface with input components stacked vertically.
88
  """
89
+ with gr.Blocks() as demo:
 
 
90
  gr.Markdown("# Multi-Tool AI Agent with Document Upload")
91
  gr.Markdown(
92
  "Enter your request and optionally upload a PDF document. "
 
94
  "Otherwise, use the text box for general requests (weather, search, etc.)."
95
  )
96
 
97
+ # Stack components vertically by default within gr.Blocks
98
+ # Text input for the user's query or question
99
+ query_input = gr.Textbox(
100
+ label="Enter your request or question:",
101
+ placeholder="e.g., What is the weather in London? Search for the latest news about AI. What does this document say about [topic]? Summarize the document.",
102
+ lines=3, # Gives height to the textbox
103
+ interactive=True
104
+ )
105
+
106
+ # File upload component for PDF documents - placed below the textbox
107
+ pdf_upload = gr.File(
108
+ label="Upload PDF (Optional - for Document Q&A)",
109
+ file_types=[".pdf"], # Restrict file types to PDF
110
+ interactive=True,
111
+ # The vertical size of this component is somewhat fixed by Gradio
112
+ )
113
 
114
+ # Button to trigger the processing function - placed below the file upload
115
+ submit_btn = gr.Button("Submit")
116
+
117
+ # Output field below the button
118
  agent_output = gr.Textbox(
119
  label="Agent's Response:",
120
  interactive=False,
 
122
  autoscroll=True
123
  )
124
 
125
+ # Link the button click to the process_input function
126
+ # Pass both query_input (text) and pdf_upload (file) as inputs
127
  submit_btn.click(
128
  fn=self.process_input,
129
+ inputs=[query_input, pdf_upload], # This list specifies all inputs
130
+ outputs=agent_output # This specifies the output where the return value goes
131
  )
132
 
133
+ # Optional examples - adjust these based on your tools and whether you have default files
134
+ # examples = [
135
+ # ["What is the time in Berlin?", None], # Example with only text
136
+ # ["Generate an image of a robot cooking pasta.", None], # Example with only text
137
+ # # Example for document Q&A - requires a default file path accessible by the tool
138
+ # # and needs to be in the same directory or accessible path
139
+ # # ["Summarize the introduction section", "sample_document.pdf"] # Example with text and file
140
+ # ]
141
+ # gr.Examples(examples=examples, inputs=[query_input, pdf_upload]) # Examples take same inputs as function
142
+
143
+
144
  # Launch the Gradio interface
145
+ # Setting share=True creates a public URL (useful for demos, be mindful of security/costs)
146
+ # Setting inline=False opens the app in a new browser tab
147
  demo.launch(share=False, inline=False)