mohammedelfeky-ai commited on
Commit
d9e8945
·
verified ·
1 Parent(s): 839bdd7

Update Gradio_UI.py

Browse files
Files changed (1) hide show
  1. Gradio_UI.py +20 -27
Gradio_UI.py CHANGED
@@ -167,15 +167,14 @@ def stream_to_gradio(
167
 
168
 
169
  class GradioUI:
170
- def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None): # Parameter kept for consistency
171
  if not _is_package_available("gradio"):
172
  raise ModuleNotFoundError("Install 'gradio': `pip install 'smolagents[gradio]'`")
173
  self.agent = agent
174
- self.file_upload_folder = None # Effectively disabling file uploads from UI side
175
  self._latest_file_path_for_download = None
176
 
177
- def _get_created_document_path(self): # Renamed for clarity
178
- """Checks agent logs for a path from create_document and returns it if valid, else None."""
179
  if hasattr(self.agent, 'interaction_logs') and self.agent.interaction_logs:
180
  print(f"DEBUG Gradio UI: Checking {len(self.agent.interaction_logs)} interaction log entries for created document paths.")
181
  for log_entry in reversed(self.agent.interaction_logs):
@@ -186,7 +185,8 @@ class GradioUI:
186
  is_python_interpreter_step = any(tc.name == "python_interpreter" for tc in tool_calls)
187
 
188
  if is_python_interpreter_step and observations and isinstance(observations, str):
189
- print(f"DEBUG Gradio UI (_get_created_document_path): Python Interpreter Observations: '''{observations[:500]}...'''")
 
190
 
191
  match = re.search(
192
  r"(?:Document created \((?:docx|pdf|txt)\):|Document converted to PDF:)\s*(/tmp/[a-zA-Z0-9_]+/generated_document\.(?:docx|pdf|txt))",
@@ -200,49 +200,46 @@ class GradioUI:
200
  normalized_path = os.path.normpath(extracted_path)
201
  if os.path.exists(normalized_path):
202
  print(f"DEBUG Gradio UI: Validated path for download: {normalized_path}")
203
- return normalized_path # Return the path
204
  else:
205
  print(f"DEBUG Gradio UI: Path from create_document output ('{normalized_path}') does not exist.")
206
  print("DEBUG Gradio UI: No valid generated document path found in agent logs.")
207
- return None # Return None if no valid path found
208
 
209
  def interact_with_agent(self, prompt_text: str, current_chat_history: list):
210
  print(f"DEBUG Gradio: interact_with_agent called with prompt: '{prompt_text}'")
211
 
212
  updated_chat_history = current_chat_history + [{"role": "user", "content": prompt_text}]
213
 
214
- # Initial yield: show user message, keep file_download_display_component hidden
215
- yield updated_chat_history, gr.update(value=None, visible=False)
216
 
217
  agent_responses_for_history = []
218
  for msg_dict in stream_to_gradio(self.agent, task=prompt_text, reset_agent_memory=False):
219
  agent_responses_for_history.append(msg_dict)
220
- # Yield progressively to update chat, keep file_download_display_component hidden
221
- yield updated_chat_history + agent_responses_for_history, gr.update(value=None, visible=False)
222
 
223
  final_chat_display_content = updated_chat_history + agent_responses_for_history
224
 
225
- # After all agent messages are processed, check for a created document path
226
  document_path_to_display = self._get_created_document_path()
227
 
228
  if document_path_to_display:
229
  print(f"DEBUG Gradio: Document found for display: {document_path_to_display}")
230
- # Update chat and make the file component visible with the path
231
- yield final_chat_display_content, gr.File.update(value=document_path_to_display,
232
  label=os.path.basename(document_path_to_display),
233
  visible=True)
234
  else:
235
- # Update chat, keep file component hidden
236
  print(f"DEBUG Gradio: No document found for display.")
237
- yield final_chat_display_content, gr.File.update(value=None, visible=False)
 
238
 
239
 
240
- def log_user_message(self, text_input_value: str): # File uploads removed
241
  full_prompt = text_input_value
242
  print(f"DEBUG Gradio: Prepared prompt for agent: {full_prompt[:300]}...")
243
  return full_prompt, ""
244
 
245
- # prepare_and_show_download_file and download_action_button are removed as we try direct display
246
 
247
  def launch(self, **kwargs):
248
  with gr.Blocks(fill_height=True, theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue)) as demo:
@@ -267,13 +264,12 @@ class GradioUI:
267
  )
268
 
269
  with gr.Column(scale=1):
270
- # --- "Generated File" section now directly shows the gr.File component ---
271
- # No separate "Download" button, file appears if created.
272
- gr.Markdown("### Generated Document") # Renamed title for clarity
273
  file_download_display_component = gr.File(
274
  label="Downloadable Document",
275
- visible=False, # Initially hidden
276
- interactive=False # User cannot upload to this
277
  )
278
 
279
  text_message_input.submit(
@@ -283,11 +279,8 @@ class GradioUI:
283
  ).then(
284
  self.interact_with_agent,
285
  [prepared_prompt_for_agent, chatbot_display],
286
- # Outputs: chatbot, and the file_download_display_component
287
- [chatbot_display, file_download_display_component]
288
  )
289
-
290
- # No explicit download_action_button.click event needed anymore
291
 
292
  demo.launch(debug=True, share=kwargs.get("share", False), **kwargs)
293
 
 
167
 
168
 
169
  class GradioUI:
170
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
171
  if not _is_package_available("gradio"):
172
  raise ModuleNotFoundError("Install 'gradio': `pip install 'smolagents[gradio]'`")
173
  self.agent = agent
174
+ self.file_upload_folder = None
175
  self._latest_file_path_for_download = None
176
 
177
+ def _get_created_document_path(self):
 
178
  if hasattr(self.agent, 'interaction_logs') and self.agent.interaction_logs:
179
  print(f"DEBUG Gradio UI: Checking {len(self.agent.interaction_logs)} interaction log entries for created document paths.")
180
  for log_entry in reversed(self.agent.interaction_logs):
 
185
  is_python_interpreter_step = any(tc.name == "python_interpreter" for tc in tool_calls)
186
 
187
  if is_python_interpreter_step and observations and isinstance(observations, str):
188
+ # CRITICAL DEBUG LINE: Print the exact observations string
189
+ print(f"DEBUG Gradio UI (_get_created_document_path): Python Interpreter Observations: '''{observations}'''")
190
 
191
  match = re.search(
192
  r"(?:Document created \((?:docx|pdf|txt)\):|Document converted to PDF:)\s*(/tmp/[a-zA-Z0-9_]+/generated_document\.(?:docx|pdf|txt))",
 
200
  normalized_path = os.path.normpath(extracted_path)
201
  if os.path.exists(normalized_path):
202
  print(f"DEBUG Gradio UI: Validated path for download: {normalized_path}")
203
+ return normalized_path
204
  else:
205
  print(f"DEBUG Gradio UI: Path from create_document output ('{normalized_path}') does not exist.")
206
  print("DEBUG Gradio UI: No valid generated document path found in agent logs.")
207
+ return None
208
 
209
  def interact_with_agent(self, prompt_text: str, current_chat_history: list):
210
  print(f"DEBUG Gradio: interact_with_agent called with prompt: '{prompt_text}'")
211
 
212
  updated_chat_history = current_chat_history + [{"role": "user", "content": prompt_text}]
213
 
214
+ yield updated_chat_history, gr.update(value=None, visible=False) # For file_download_display_component
 
215
 
216
  agent_responses_for_history = []
217
  for msg_dict in stream_to_gradio(self.agent, task=prompt_text, reset_agent_memory=False):
218
  agent_responses_for_history.append(msg_dict)
219
+ yield updated_chat_history + agent_responses_for_history, gr.update(value=None, visible=False) # For file_download_display_component
 
220
 
221
  final_chat_display_content = updated_chat_history + agent_responses_for_history
222
 
 
223
  document_path_to_display = self._get_created_document_path()
224
 
225
  if document_path_to_display:
226
  print(f"DEBUG Gradio: Document found for display: {document_path_to_display}")
227
+ # CORRECTED: Use gr.update() for the File component
228
+ yield final_chat_display_content, gr.update(value=document_path_to_display,
229
  label=os.path.basename(document_path_to_display),
230
  visible=True)
231
  else:
 
232
  print(f"DEBUG Gradio: No document found for display.")
233
+ # CORRECTED: Use gr.update() for the File component
234
+ yield final_chat_display_content, gr.update(value=None, visible=False)
235
 
236
 
237
+ def log_user_message(self, text_input_value: str):
238
  full_prompt = text_input_value
239
  print(f"DEBUG Gradio: Prepared prompt for agent: {full_prompt[:300]}...")
240
  return full_prompt, ""
241
 
242
+ # prepare_and_show_download_file is not needed if we directly update the gr.File component
243
 
244
  def launch(self, **kwargs):
245
  with gr.Blocks(fill_height=True, theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue)) as demo:
 
264
  )
265
 
266
  with gr.Column(scale=1):
267
+ # "Generated File" section directly shows the gr.File component
268
+ gr.Markdown("### Generated Document")
 
269
  file_download_display_component = gr.File(
270
  label="Downloadable Document",
271
+ visible=False,
272
+ interactive=False
273
  )
274
 
275
  text_message_input.submit(
 
279
  ).then(
280
  self.interact_with_agent,
281
  [prepared_prompt_for_agent, chatbot_display],
282
+ [chatbot_display, file_download_display_component] # Outputs update chatbot and file component
 
283
  )
 
 
284
 
285
  demo.launch(debug=True, share=kwargs.get("share", False), **kwargs)
286