SamarthPujari commited on
Commit
7c1adae
·
verified ·
1 Parent(s): 37316fa

Update Gradio_UI.py

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