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

Update Gradio_UI.py

Browse files
Files changed (1) hide show
  1. Gradio_UI.py +18 -65
Gradio_UI.py CHANGED
@@ -1,57 +1,36 @@
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
- # Clean up the uploaded file after processing (optional but good practice)
35
- # import os
36
- # if os.path.exists(pdf_file.name):
37
- # os.remove(pdf_file.name)
38
  return response
39
 
40
  except IndexError:
41
  return "Error: Document Q&A tool not found at the expected index (4). Check agent tool setup in app.py."
42
  except Exception as e:
43
  print(f"Error during Document Q&A tool execution: {e}")
44
- # Clean up the uploaded file on error too
45
- # import os
46
- # if os.path.exists(pdf_file.name):
47
- # os.remove(pdf_file.name)
48
  return f"An error occurred during Document Q&A: {str(e)}"
49
 
50
- # If no PDF file, or query is empty when file is present, handle as a general agent query
51
  elif query and query.strip():
52
  print(f"No PDF file or query is for general task. Processing with agent.run(): {query}")
53
  try:
54
- # --- Call the agent's run method for general queries ---
55
  response = self.agent.run(query)
56
  print("Agent.run finished for general query.")
57
  return response
@@ -59,12 +38,7 @@ class GradioUI:
59
  print(f"Error during agent.run: {e}")
60
  return f"An error occurred while processing your request: {str(e)}"
61
 
62
- # Handle cases where only a PDF is uploaded without a question, or no input at all
63
  elif pdf_file is not None:
64
- # Clean up the uploaded file if no question was provided
65
- # import os
66
- # if os.path.exists(pdf_file.name):
67
- # os.remove(pdf_file.name)
68
  return "Please enter a question in the textbox to ask about the uploaded PDF."
69
  else:
70
  return "Please enter a request or upload a document for analysis."
@@ -72,9 +46,11 @@ class GradioUI:
72
 
73
  def launch(self):
74
  """
75
- Launches the Gradio user interface with layout adjustments.
76
  """
77
- with gr.Blocks() as demo:
 
 
78
  gr.Markdown("# Multi-Tool AI Agent with Document Upload")
79
  gr.Markdown(
80
  "Enter your request and optionally upload a PDF document. "
@@ -82,59 +58,36 @@ class GradioUI:
82
  "Otherwise, use the text box for general requests (weather, search, etc.)."
83
  )
84
 
85
- # Use a gr.Row to place input components side-by-side (or stacked on small screens)
86
  with gr.Row():
87
- # Text input for the user's query or question
88
- # Give it more space (e.g., scale=3) compared to the file upload
89
  query_input = gr.Textbox(
90
  label="Enter your request or question:",
91
  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.",
92
  lines=3,
93
  interactive=True,
94
- scale=3 # This component will take 3 parts of the available width in the row
95
  )
96
 
97
- # File upload component for PDF documents
98
- # Give it less space (e.g., scale=1 or scale=0)
99
  pdf_upload = gr.File(
100
- label="Upload PDF (Optional)", # Can also shorten the label
101
- file_types=[".pdf"], # Restrict file types to PDF
102
- interactive=True, # User can upload files
103
- scale=1 # This component will take 1 part of the available width in the row
104
- # Using scale=0 would make it take the minimum possible space
105
  )
106
 
107
- # Single output field to display the agent's final response
108
  agent_output = gr.Textbox(
109
  label="Agent's Response:",
110
- interactive=False, # User cannot type in the output box
111
- lines=10, # Provides more space to display potentially long responses
112
  autoscroll=True
113
  )
114
 
115
- # Button to trigger the processing function
116
  submit_btn = gr.Button("Submit")
117
 
118
- # Link the button click to the process_input function
119
- # Pass both query_input (text) and pdf_upload (file) as inputs
120
  submit_btn.click(
121
  fn=self.process_input,
122
- inputs=[query_input, pdf_upload], # This list specifies all inputs
123
- outputs=agent_output # This specifies the output where the return value goes
124
  )
125
 
126
- # Optional examples - adjust these based on your tools and whether you have default files
127
- # examples = [
128
- # ["What is the time in Berlin?"],
129
- # ["Generate an image of a robot cooking pasta."],
130
- # # Example for document Q&A - requires a default file path accessible by the tool
131
- # # For file examples, you need to provide the path to the example file(s)
132
- # # ["Summarize the introduction section", "path/to/your/sample_document.pdf"]
133
- # ]
134
- # gr.Examples(examples=examples, inputs=[query_input, pdf_upload]) # Examples take same inputs as function
135
-
136
-
137
  # Launch the Gradio interface
138
- # Setting share=True creates a public URL (useful for demos, be mindful of security/costs)
139
- # Setting inline=False opens the app in a new browser tab
140
  demo.launch(share=False, inline=False)
 
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
  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
 
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
  "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,
80
+ lines=10,
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)