Update Gradio_UI.py
Browse files- Gradio_UI.py +45 -48
Gradio_UI.py
CHANGED
|
@@ -13,10 +13,8 @@
|
|
| 13 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
# See the License for the specific language governing permissions and
|
| 15 |
# limitations under the License.
|
| 16 |
-
# import mimetypes # No longer needed if file upload is removed
|
| 17 |
import os
|
| 18 |
import re
|
| 19 |
-
# import shutil # No longer needed if file upload is removed
|
| 20 |
from typing import Optional
|
| 21 |
import tempfile
|
| 22 |
from PIL import Image as PILImage
|
|
@@ -169,17 +167,17 @@ def stream_to_gradio(
|
|
| 169 |
|
| 170 |
|
| 171 |
class GradioUI:
|
| 172 |
-
def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
|
| 173 |
if not _is_package_available("gradio"):
|
| 174 |
raise ModuleNotFoundError("Install 'gradio': `pip install 'smolagents[gradio]'`")
|
| 175 |
self.agent = agent
|
| 176 |
-
self.file_upload_folder = None #
|
| 177 |
self._latest_file_path_for_download = None
|
| 178 |
|
| 179 |
-
def
|
| 180 |
-
|
| 181 |
if hasattr(self.agent, 'interaction_logs') and self.agent.interaction_logs:
|
| 182 |
-
print(f"DEBUG Gradio UI: Checking {len(self.agent.interaction_logs)} interaction log entries for created
|
| 183 |
for log_entry in reversed(self.agent.interaction_logs):
|
| 184 |
if isinstance(log_entry, ActionStep):
|
| 185 |
observations = getattr(log_entry, 'observations', None)
|
|
@@ -188,8 +186,7 @@ class GradioUI:
|
|
| 188 |
is_python_interpreter_step = any(tc.name == "python_interpreter" for tc in tool_calls)
|
| 189 |
|
| 190 |
if is_python_interpreter_step and observations and isinstance(observations, str):
|
| 191 |
-
|
| 192 |
-
print(f"DEBUG Gradio UI (_check_for_file): Python Interpreter Observations: '''{observations}'''")
|
| 193 |
|
| 194 |
match = re.search(
|
| 195 |
r"(?:Document created \((?:docx|pdf|txt)\):|Document converted to PDF:)\s*(/tmp/[a-zA-Z0-9_]+/generated_document\.(?:docx|pdf|txt))",
|
|
@@ -198,52 +195,54 @@ class GradioUI:
|
|
| 198 |
)
|
| 199 |
|
| 200 |
if match:
|
| 201 |
-
extracted_path = match.group(1)
|
| 202 |
print(f"DEBUG Gradio UI: Regex matched. Extracted path: '{extracted_path}'")
|
| 203 |
normalized_path = os.path.normpath(extracted_path)
|
| 204 |
if os.path.exists(normalized_path):
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
return True
|
| 208 |
else:
|
| 209 |
print(f"DEBUG Gradio UI: Path from create_document output ('{normalized_path}') does not exist.")
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
print("DEBUG Gradio UI: No valid generated file path (from create_document) found for download button.")
|
| 213 |
-
return False
|
| 214 |
|
| 215 |
def interact_with_agent(self, prompt_text: str, current_chat_history: list):
|
| 216 |
print(f"DEBUG Gradio: interact_with_agent called with prompt: '{prompt_text}'")
|
| 217 |
|
| 218 |
updated_chat_history = current_chat_history + [{"role": "user", "content": prompt_text}]
|
| 219 |
|
| 220 |
-
yield
|
|
|
|
| 221 |
|
| 222 |
agent_responses_for_history = []
|
| 223 |
for msg_dict in stream_to_gradio(self.agent, task=prompt_text, reset_agent_memory=False):
|
| 224 |
agent_responses_for_history.append(msg_dict)
|
| 225 |
-
|
|
|
|
| 226 |
|
| 227 |
-
file_found_for_download = self._check_for_created_file()
|
| 228 |
-
|
| 229 |
final_chat_display_content = updated_chat_history + agent_responses_for_history
|
| 230 |
-
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
-
def log_user_message(self, text_input_value: str):
|
| 234 |
full_prompt = text_input_value
|
| 235 |
print(f"DEBUG Gradio: Prepared prompt for agent: {full_prompt[:300]}...")
|
| 236 |
return full_prompt, ""
|
| 237 |
|
| 238 |
-
|
| 239 |
-
if self._latest_file_path_for_download and os.path.exists(self._latest_file_path_for_download):
|
| 240 |
-
print(f"DEBUG Gradio UI: Preparing download for UI component: {self._latest_file_path_for_download}")
|
| 241 |
-
return gr.File.update(value=self._latest_file_path_for_download,
|
| 242 |
-
label=os.path.basename(self._latest_file_path_for_download),
|
| 243 |
-
visible=True)
|
| 244 |
-
else:
|
| 245 |
-
print("DEBUG Gradio UI: No valid file path to prepare for download component.")
|
| 246 |
-
return gr.File.update(visible=False, value=None)
|
| 247 |
|
| 248 |
def launch(self, **kwargs):
|
| 249 |
with gr.Blocks(fill_height=True, theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue)) as demo:
|
|
@@ -268,30 +267,28 @@ class GradioUI:
|
|
| 268 |
)
|
| 269 |
|
| 270 |
with gr.Column(scale=1):
|
| 271 |
-
# File
|
| 272 |
-
#
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
|
| 280 |
text_message_input.submit(
|
| 281 |
self.log_user_message,
|
| 282 |
-
[text_message_input],
|
| 283 |
[prepared_prompt_for_agent, text_message_input]
|
| 284 |
).then(
|
| 285 |
self.interact_with_agent,
|
| 286 |
[prepared_prompt_for_agent, chatbot_display],
|
| 287 |
-
|
|
|
|
| 288 |
)
|
| 289 |
|
| 290 |
-
download_action_button.click
|
| 291 |
-
|
| 292 |
-
[],
|
| 293 |
-
[file_download_display_component]
|
| 294 |
-
)
|
| 295 |
demo.launch(debug=True, share=kwargs.get("share", False), **kwargs)
|
| 296 |
|
| 297 |
__all__ = ["stream_to_gradio", "GradioUI"]
|
|
|
|
| 13 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
# See the License for the specific language governing permissions and
|
| 15 |
# limitations under the License.
|
|
|
|
| 16 |
import os
|
| 17 |
import re
|
|
|
|
| 18 |
from typing import Optional
|
| 19 |
import tempfile
|
| 20 |
from PIL import Image as PILImage
|
|
|
|
| 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):
|
| 182 |
if isinstance(log_entry, ActionStep):
|
| 183 |
observations = getattr(log_entry, 'observations', None)
|
|
|
|
| 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))",
|
|
|
|
| 195 |
)
|
| 196 |
|
| 197 |
if match:
|
| 198 |
+
extracted_path = match.group(1)
|
| 199 |
print(f"DEBUG Gradio UI: Regex matched. Extracted path: '{extracted_path}'")
|
| 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 |
)
|
| 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(
|
| 280 |
self.log_user_message,
|
| 281 |
+
[text_message_input],
|
| 282 |
[prepared_prompt_for_agent, text_message_input]
|
| 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 |
|
| 294 |
__all__ = ["stream_to_gradio", "GradioUI"]
|