Tbaberca commited on
Commit
8396721
·
verified ·
1 Parent(s): 69afb83

Update Gradio_UI.py

Browse files
Files changed (1) hide show
  1. Gradio_UI.py +47 -129
Gradio_UI.py CHANGED
@@ -1,133 +1,51 @@
1
- #!/usr/bin/env python
2
- # coding=utf-8
3
- # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
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
17
- import os
18
- import re
19
- import shutil
20
- from typing import Optional
21
-
22
- from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
23
- from smolagents.agents import ActionStep, MultiStepAgent
24
- from smolagents.memory import MemoryStep
25
- from smolagents.utils import _is_package_available
26
-
27
-
28
- def pull_messages_from_step(
29
- step_log: MemoryStep,
30
  ):
31
- """Extract ChatMessage objects from agent steps with proper nesting"""
 
 
32
  import gradio as gr
33
 
34
- if isinstance(step_log, ActionStep):
35
- # Output the step number
36
- step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
37
- yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
38
-
39
- # First yield the thought/reasoning from the LLM
40
- if hasattr(step_log, "model_output") and step_log.model_output is not None:
41
- # Clean up the LLM output
42
- model_output = step_log.model_output.strip()
43
- # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
44
- model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
45
- model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
46
- model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
47
- model_output = model_output.strip()
48
- yield gr.ChatMessage(role="assistant", content=model_output)
49
-
50
- # For tool calls, create a parent message
51
- if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
52
- first_tool_call = step_log.tool_calls[0]
53
- used_code = first_tool_call.name == "python_interpreter"
54
- parent_id = f"call_{len(step_log.tool_calls)}"
55
-
56
- # Tool call becomes the parent message with timing info
57
- # First we will handle arguments based on type
58
- args = first_tool_call.arguments
59
- if isinstance(args, dict):
60
- content = str(args.get("answer", str(args)))
61
- else:
62
- content = str(args).strip()
63
-
64
- if used_code:
65
- # Clean up the content by removing any end code tags
66
- content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
67
- content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
68
- content = content.strip()
69
- if not content.startswith("```python"):
70
- content = f"```python\n{content}\n```"
71
-
72
- parent_message_tool = gr.ChatMessage(
73
- role="assistant",
74
- content=content,
75
- metadata={
76
- "title": f"🛠️ Used tool {first_tool_call.name}",
77
- "id": parent_id,
78
- "status": "pending",
79
- },
80
- )
81
- yield parent_message_tool
82
-
83
- # Nesting execution logs under the tool call if they exist
84
- if hasattr(step_log, "observations") and (
85
- step_log.observations is not None and step_log.observations.strip()
86
- ): # Only yield execution logs if there's actual content
87
- log_content = step_log.observations.strip()
88
- if log_content:
89
- log_content = re.sub(r"^Execution logs:\s*", "", log_content)
90
- yield gr.ChatMessage(
91
- role="assistant",
92
- content=f"{log_content}",
93
- metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
94
- )
95
-
96
- # Nesting any errors under the tool call
97
- if hasattr(step_log, "error") and step_log.error is not None:
98
- yield gr.ChatMessage(
99
- role="assistant",
100
- content=str(step_log.error),
101
- metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
102
- )
103
-
104
- # Update parent message metadata to done status without yielding a new message
105
- parent_message_tool.metadata["status"] = "done"
106
-
107
- # Handle standalone errors but not from tool calls
108
- elif hasattr(step_log, "error") and step_log.error is not None:
109
- yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
110
-
111
- # Calculate duration and token information
112
- step_footnote = f"{step_number}"
113
- if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
114
- token_str = (
115
- f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
116
- )
117
- step_footnote += token_str
118
- if hasattr(step_log, "duration"):
119
- step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
120
- step_footnote += step_duration
121
- step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
122
- yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
123
- yield gr.ChatMessage(role="assistant", content="-----")
124
-
125
-
126
- def stream_to_gradio(
127
- agent,
128
- task: str,
129
- reset_agent_memory: bool = False,
130
- additional_args: Optional[dict] = None,
131
- ):
132
- """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
133
 
 
1
+ def upload_file(
2
+ self,
3
+ file,
4
+ file_uploads_log,
5
+ allowed_file_types=[
6
+ "application/pdf",
7
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
8
+ "text/plain",
9
+ ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  ):
11
+ """
12
+ Handle file uploads, default allowed types are .pdf, .docx, and .txt
13
+ """
14
  import gradio as gr
15
 
16
+ if file is None:
17
+ return gr.Textbox("No file uploaded", visible=True), file_uploads_log
18
+
19
+ try:
20
+ mime_type, _ = mimetypes.guess_type(file.name)
21
+ except Exception as e:
22
+ return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
23
+
24
+ if mime_type not in allowed_file_types:
25
+ return gr.Textbox("File type disallowed", visible=True), file_uploads_log
26
+
27
+ # Sanitize file name
28
+ original_name = os.path.basename(file.name)
29
+ sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)
30
+
31
+ # Map mime type to extension
32
+ type_to_ext = {}
33
+ for ext, t in mimetypes.types_map.items():
34
+ if t not in type_to_ext:
35
+ type_to_ext[t] = ext
36
+
37
+ name_without_ext = ".".join(sanitized_name.split(".")[:-1])
38
+ ext = type_to_ext.get(mime_type, "")
39
+ if not ext.startswith("."):
40
+ ext = "." + ext if ext else ""
41
+ sanitized_name = f"{name_without_ext}{ext}"
42
+
43
+ # Save file
44
+ file_path = os.path.join(self.file_upload_folder, sanitized_name)
45
+ with open(file_path, "wb") as f:
46
+ f.write(file.read())
47
+
48
+ # Update log or return success message
49
+ file_uploads_log.append(file_path)
50
+ return gr.Textbox(f"File uploaded: {sanitized_name}", visible=True), file_uploads_log
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51