makeitfr commited on
Commit
102a042
·
verified ·
1 Parent(s): af90918

Upload OmniParser/omnitool/gradio/app_new.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. OmniParser/omnitool/gradio/app_new.py +760 -0
OmniParser/omnitool/gradio/app_new.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The app contains:
3
+ - a new UI for the OmniParser AI Agent.
4
+ -
5
+ python app_new.py --windows_host_url localhost:8006 --omniparser_server_url localhost:8000
6
+ """
7
+
8
+ import os
9
+ import io
10
+ import shutil
11
+ import mimetypes
12
+ from datetime import datetime
13
+ from enum import StrEnum
14
+ from functools import partial
15
+ from pathlib import Path
16
+ from typing import cast, List, Optional
17
+ import argparse
18
+ import gradio as gr
19
+ from anthropic import APIResponse
20
+ from anthropic.types import TextBlock
21
+ from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
22
+ from anthropic.types.tool_use_block import ToolUseBlock
23
+ from loop import (
24
+ APIProvider,
25
+ sampling_loop_sync,
26
+ )
27
+ from tools import ToolResult
28
+ import requests
29
+ from requests.exceptions import RequestException
30
+ import base64
31
+
32
+ CONFIG_DIR = Path("~/.anthropic").expanduser()
33
+ API_KEY_FILE = CONFIG_DIR / "api_key"
34
+
35
+ INTRO_TEXT = '''
36
+ <div style="text-align: center; margin-bottom: 10px;">
37
+ <h2>OmniParser AI Agent</h2>
38
+ <p>Turn any vision-language model into an AI agent. We currently support <b>OpenAI (4o/o1/o3-mini), DeepSeek (R1), Qwen (2.5VL) or Anthropic Computer Use (Sonnet)</b>.</p>
39
+ <p>Type a message and press send to start OmniTool. Press stop to pause, and press the trash icon in the chat to clear the message history.</p>
40
+ <p>You can also upload files for analysis using the file upload section.</p>
41
+ </div>
42
+ '''
43
+
44
+ def parse_arguments():
45
+ parser = argparse.ArgumentParser(description="Gradio App")
46
+ parser.add_argument("--windows_host_url", type=str, default='localhost:8006')
47
+ parser.add_argument("--omniparser_server_url", type=str, default="localhost:8000")
48
+ parser.add_argument("--run_folder", type=str, default="./tmp/outputs")
49
+ return parser.parse_args()
50
+ args = parse_arguments()
51
+
52
+ # Update upload folder from args if provided
53
+ RUN_FOLDER = Path(os.path.join(args.run_folder, datetime.now().strftime('%Y%m%d_%H%M')))
54
+ RUN_FOLDER.mkdir(parents=True, exist_ok=True)
55
+
56
+ class Sender(StrEnum):
57
+ USER = "user"
58
+ BOT = "assistant"
59
+ TOOL = "tool"
60
+
61
+
62
+ def load_existing_files():
63
+ """Load all existing files from the uploads folder"""
64
+ files = []
65
+ if RUN_FOLDER.exists():
66
+ for file_path in RUN_FOLDER.iterdir():
67
+ if file_path.is_file():
68
+ files.append(str(file_path))
69
+ return files
70
+
71
+ def setup_state(state):
72
+ if "messages" not in state:
73
+ state["messages"] = []
74
+ if "model" not in state:
75
+ state["model"] = "omniparser + gpt-4o-orchestrated"
76
+ if "provider" not in state:
77
+ state["provider"] = "openai"
78
+ if "openai_api_key" not in state: # Fetch API keys from environment variables
79
+ state["openai_api_key"] = os.getenv("OPENAI_API_KEY", "")
80
+ if "anthropic_api_key" not in state:
81
+ state["anthropic_api_key"] = os.getenv("ANTHROPIC_API_KEY", "")
82
+ if "api_key" not in state:
83
+ state["api_key"] = ""
84
+ if "auth_validated" not in state:
85
+ state["auth_validated"] = False
86
+ if "responses" not in state:
87
+ state["responses"] = {}
88
+ if "tools" not in state:
89
+ state["tools"] = {}
90
+ if "only_n_most_recent_images" not in state:
91
+ state["only_n_most_recent_images"] = 2
92
+ if 'chatbot_messages' not in state:
93
+ state['chatbot_messages'] = []
94
+ if 'stop' not in state:
95
+ state['stop'] = False
96
+ if 'uploaded_files' not in state:
97
+ state['uploaded_files'] = [] # Start with an empty list instead of loading existing files
98
+
99
+ async def main(state):
100
+ """Render loop for Gradio"""
101
+ setup_state(state)
102
+ return "Setup completed"
103
+
104
+ def validate_auth(provider: APIProvider, api_key: str | None):
105
+ if provider == APIProvider.ANTHROPIC:
106
+ if not api_key:
107
+ return "Enter your Anthropic API key to continue."
108
+ if provider == APIProvider.BEDROCK:
109
+ import boto3
110
+
111
+ if not boto3.Session().get_credentials():
112
+ return "You must have AWS credentials set up to use the Bedrock API."
113
+ if provider == APIProvider.VERTEX:
114
+ import google.auth
115
+ from google.auth.exceptions import DefaultCredentialsError
116
+
117
+ if not os.environ.get("CLOUD_ML_REGION"):
118
+ return "Set the CLOUD_ML_REGION environment variable to use the Vertex API."
119
+ try:
120
+ google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
121
+ except DefaultCredentialsError:
122
+ return "Your google cloud credentials are not set up correctly."
123
+
124
+ def load_from_storage(filename: str) -> str | None:
125
+ """Load data from a file in the storage directory."""
126
+ try:
127
+ file_path = CONFIG_DIR / filename
128
+ if file_path.exists():
129
+ data = file_path.read_text().strip()
130
+ if data:
131
+ return data
132
+ except Exception as e:
133
+ print(f"Debug: Error loading {filename}: {e}")
134
+ return None
135
+
136
+ def save_to_storage(filename: str, data: str) -> None:
137
+ """Save data to a file in the storage directory."""
138
+ try:
139
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
140
+ file_path = CONFIG_DIR / filename
141
+ file_path.write_text(data)
142
+ # Ensure only user can read/write the file
143
+ file_path.chmod(0o600)
144
+ except Exception as e:
145
+ print(f"Debug: Error saving {filename}: {e}")
146
+
147
+ def _api_response_callback(response: APIResponse[BetaMessage], response_state: dict):
148
+ response_id = datetime.now().isoformat()
149
+ response_state[response_id] = response
150
+
151
+ def _tool_output_callback(tool_output: ToolResult, tool_id: str, tool_state: dict):
152
+ tool_state[tool_id] = tool_output
153
+
154
+ def chatbot_output_callback(message, chatbot_state, hide_images=False, sender="bot"):
155
+ def _render_message(message: str | BetaTextBlock | BetaToolUseBlock | ToolResult, hide_images=False):
156
+
157
+ print(f"_render_message: {str(message)[:100]}")
158
+
159
+ if isinstance(message, str):
160
+ return message
161
+
162
+ is_tool_result = not isinstance(message, str) and (
163
+ isinstance(message, ToolResult)
164
+ or message.__class__.__name__ == "ToolResult"
165
+ )
166
+ if not message or (
167
+ is_tool_result
168
+ and hide_images
169
+ and not hasattr(message, "error")
170
+ and not hasattr(message, "output")
171
+ ): # return None if hide_images is True
172
+ return
173
+ # render tool result
174
+ if is_tool_result:
175
+ message = cast(ToolResult, message)
176
+ if message.output:
177
+ return message.output
178
+ if message.error:
179
+ return f"Error: {message.error}"
180
+ if message.base64_image and not hide_images:
181
+ # somehow can't display via gr.Image
182
+ # image_data = base64.b64decode(message.base64_image)
183
+ # return gr.Image(value=Image.open(io.BytesIO(image_data)))
184
+ return f'<img src="data:image/png;base64,{message.base64_image}">'
185
+
186
+ elif isinstance(message, BetaTextBlock) or isinstance(message, TextBlock):
187
+ # Format reasoning text in a collapsible dropdown
188
+ return f"Next step Reasoning: {message.text}"
189
+ # reasoning_text = message.text
190
+ # return f'''
191
+ # <details>
192
+ # <summary><Current Step Reasoning (click to expand):</summary>
193
+ # <div style="padding: 10px; background-color: #f8f9fa; border-radius: 5px; margin-top: 5px;">
194
+ # <pre>{reasoning_text}</pre>
195
+ # </div>
196
+ # </details>
197
+ # '''
198
+ elif isinstance(message, BetaToolUseBlock) or isinstance(message, ToolUseBlock):
199
+ # return f"Next I will perform the following action: {message.input}"
200
+ return None
201
+ else:
202
+ return message
203
+
204
+ def _truncate_string(s, max_length=500):
205
+ """Truncate long strings for concise printing."""
206
+ if isinstance(s, str) and len(s) > max_length:
207
+ return s[:max_length] + "..."
208
+ return s
209
+ # processing Anthropic messages
210
+ message = _render_message(message, hide_images)
211
+
212
+ if sender == "bot":
213
+ chatbot_state.append((None, message))
214
+ else:
215
+ chatbot_state.append((message, None))
216
+
217
+ # Create a concise version of the chatbot state for printing
218
+ concise_state = [(_truncate_string(user_msg), _truncate_string(bot_msg))
219
+ for user_msg, bot_msg in chatbot_state]
220
+ # print(f"chatbot_output_callback chatbot_state: {concise_state} (truncated)")
221
+
222
+ def valid_params(user_input, state):
223
+ """Validate all requirements and return a list of error messages."""
224
+ errors = []
225
+
226
+ for server_name, url in [('Windows Host', 'localhost:5000'), ('OmniParser Server', args.omniparser_server_url)]:
227
+ try:
228
+ url = f'http://{url}/probe'
229
+ response = requests.get(url, timeout=3)
230
+ if response.status_code != 200:
231
+ errors.append(f"{server_name} is not responding")
232
+ except RequestException as e:
233
+ errors.append(f"{server_name} is not responding")
234
+
235
+ if not state["api_key"].strip():
236
+ errors.append("LLM API Key is not set")
237
+
238
+ if not user_input:
239
+ errors.append("no computer use request provided")
240
+
241
+ return errors
242
+
243
+ def process_input(user_input, state):
244
+ # Reset the stop flag
245
+ if state["stop"]:
246
+ state["stop"] = False
247
+
248
+ errors = valid_params(user_input, state)
249
+ if errors:
250
+ raise gr.Error("Validation errors: " + ", ".join(errors))
251
+
252
+ # Append the user message to state["messages"]
253
+ state["messages"].append(
254
+ {
255
+ "role": Sender.USER,
256
+ "content": [TextBlock(type="text", text=user_input)],
257
+ }
258
+ )
259
+
260
+ # Append the user's message to chatbot_messages with None for the assistant's reply
261
+ state['chatbot_messages'].append((user_input, None))
262
+ yield state['chatbot_messages'], gr.update() # Yield to update the chatbot UI with the user's message
263
+
264
+ print("state")
265
+ print(state)
266
+
267
+ # Run sampling_loop_sync with the chatbot_output_callback
268
+ for loop_msg in sampling_loop_sync(
269
+ model=state["model"],
270
+ provider=state["provider"],
271
+ messages=state["messages"],
272
+ output_callback=partial(chatbot_output_callback, chatbot_state=state['chatbot_messages'], hide_images=False),
273
+ tool_output_callback=partial(_tool_output_callback, tool_state=state["tools"]),
274
+ api_response_callback=partial(_api_response_callback, response_state=state["responses"]),
275
+ api_key=state["api_key"],
276
+ only_n_most_recent_images=state["only_n_most_recent_images"],
277
+ max_tokens=16384,
278
+ omniparser_url=args.omniparser_server_url,
279
+ save_folder=str(RUN_FOLDER)
280
+ ):
281
+ if loop_msg is None or state.get("stop"):
282
+ # Detect and add new files to the state
283
+ file_choices_update = detect_new_files(state)
284
+ yield state['chatbot_messages'], file_choices_update
285
+ print("End of task. Close the loop.")
286
+ break
287
+
288
+ yield state['chatbot_messages'], gr.update() # Yield the updated chatbot_messages to update the chatbot UI
289
+
290
+ # Final detection of new files
291
+ file_choices_update = detect_new_files(state)
292
+ yield state['chatbot_messages'], file_choices_update
293
+
294
+ def stop_app(state):
295
+ state["stop"] = True
296
+ return "App stopped"
297
+
298
+ def get_header_image_base64():
299
+ try:
300
+ # Get the absolute path to the image relative to this script
301
+ script_dir = Path(__file__).parent
302
+ image_path = script_dir.parent.parent / "imgs" / "header_bar_thin.png"
303
+
304
+ with open(image_path, "rb") as image_file:
305
+ encoded_string = base64.b64encode(image_file.read()).decode()
306
+ return f'data:image/png;base64,{encoded_string}'
307
+ except Exception as e:
308
+ print(f"Failed to load header image: {e}")
309
+ return None
310
+
311
+ def get_file_viewer_html(file_path=None):
312
+ """Generate HTML to view a file based on its type"""
313
+ if not file_path:
314
+ # Return the VNC viewer iframe
315
+ return f'<iframe src="http://{args.windows_host_url}/vnc.html?view_only=1&autoconnect=1&resize=scale" width="100%" height="580" allow="fullscreen"></iframe>'
316
+
317
+ file_path = Path(file_path)
318
+ if not file_path.exists():
319
+ return f'<div class="error-message">File not found: {file_path.name}</div>'
320
+
321
+ # Determine the file type
322
+ mime_type, _ = mimetypes.guess_type(file_path)
323
+ file_type = mime_type.split('/')[0] if mime_type else 'unknown'
324
+ file_extension = file_path.suffix.lower()
325
+
326
+ # Handle different file types
327
+ if file_type == 'image':
328
+ # For images, display them directly
329
+ with open(file_path, "rb") as image_file:
330
+ encoded_string = base64.b64encode(image_file.read()).decode()
331
+ return f'<div class="file-viewer"><h3>{file_path.name}</h3><img src="data:{mime_type};base64,{encoded_string}" style="max-width:100%; max-height:500px;"></div>'
332
+
333
+ elif file_extension in ['.txt', '.py', '.js', '.html', '.css', '.json', '.md', '.csv'] or file_type == 'text':
334
+ # For text files, display the content with syntax highlighting for code
335
+ try:
336
+ content = file_path.read_text(errors='replace') # Use 'replace' to handle encoding issues
337
+ # Escape HTML characters
338
+ content = content.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
339
+
340
+ # Add syntax highlighting class based on file extension
341
+ highlight_class = ""
342
+ if file_extension == '.py':
343
+ highlight_class = "language-python"
344
+ elif file_extension == '.js':
345
+ highlight_class = "language-javascript"
346
+ elif file_extension == '.html':
347
+ highlight_class = "language-html"
348
+ elif file_extension == '.css':
349
+ highlight_class = "language-css"
350
+ elif file_extension == '.json':
351
+ highlight_class = "language-json"
352
+
353
+ return f'''
354
+ <div class="file-viewer">
355
+ <h3>{file_path.name}</h3>
356
+ <pre class="{highlight_class}" style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow: auto; max-height: 500px; white-space: pre-wrap;"><code>{content}</code></pre>
357
+ <script>
358
+ // Add basic syntax highlighting with CSS
359
+ if (document.querySelector('.language-python')) {{
360
+ const keywords = ['def', 'class', 'import', 'from', 'return', 'if', 'else', 'elif', 'for', 'while', 'try', 'except', 'with', 'as', 'in', 'not', 'and', 'or', 'True', 'False', 'None'];
361
+ const code = document.querySelector('.language-python code');
362
+ let html = code.innerHTML;
363
+ keywords.forEach(keyword => {{
364
+ const regex = new RegExp('\\\\b' + keyword + '\\\\b', 'g');
365
+ html = html.replace(regex, `<span style="color: #0000FF; font-weight: bold;">$&</span>`);
366
+ }});
367
+ // Highlight strings
368
+ html = html.replace(/(["'])(?:(?=(\\\\?))\2.)*?\1/g, '<span style="color: #008000;">$&</span>');
369
+ // Highlight comments
370
+ html = html.replace(/(#.*)$/gm, '<span style="color: #808080;">$1</span>');
371
+ code.innerHTML = html;
372
+ }}
373
+ </script>
374
+ </div>
375
+ '''
376
+ except UnicodeDecodeError:
377
+ return f'<div class="error-message">Cannot display binary file: {file_path.name}</div>'
378
+
379
+ elif file_type == 'video':
380
+ # For videos, use video tag
381
+ with open(file_path, "rb") as video_file:
382
+ encoded_string = base64.b64encode(video_file.read()).decode()
383
+ return f'''
384
+ <div class="file-viewer">
385
+ <h3>{file_path.name}</h3>
386
+ <video controls style="max-width:100%; max-height:500px;">
387
+ <source src="data:{mime_type};base64,{encoded_string}" type="{mime_type}">
388
+ Your browser does not support the video tag.
389
+ </video>
390
+ </div>
391
+ '''
392
+
393
+ elif file_type == 'audio':
394
+ # For audio, use audio tag
395
+ with open(file_path, "rb") as audio_file:
396
+ encoded_string = base64.b64encode(audio_file.read()).decode()
397
+ return f'''
398
+ <div class="file-viewer">
399
+ <h3>{file_path.name}</h3>
400
+ <audio controls>
401
+ <source src="data:{mime_type};base64,{encoded_string}" type="{mime_type}">
402
+ Your browser does not support the audio tag.
403
+ </audio>
404
+ </div>
405
+ '''
406
+
407
+ elif file_extension == '.pdf':
408
+ # For PDFs, embed them using an iframe with base64 data
409
+ try:
410
+ with open(file_path, "rb") as pdf_file:
411
+ encoded_string = base64.b64encode(pdf_file.read()).decode()
412
+ return f'''
413
+ <div class="file-viewer">
414
+ <h3>{file_path.name}</h3>
415
+ <iframe src="data:application/pdf;base64,{encoded_string}" width="100%" height="500px" style="border: none;"></iframe>
416
+ </div>
417
+ '''
418
+ except Exception as e:
419
+ return f'<div class="error-message">Error displaying PDF: {str(e)}</div>'
420
+
421
+ else:
422
+ # For other file types, show info but can't display
423
+ size_kb = file_path.stat().st_size / 1024
424
+ return f'<div class="file-viewer"><h3>{file_path.name}</h3><p>File type: {mime_type or "Unknown"}</p><p>Size: {size_kb:.2f} KB</p><p>This file type cannot be displayed in the browser.</p></div>'
425
+
426
+ def handle_file_upload(files, state):
427
+ """Handle file uploads and store them in the upload directory"""
428
+ if not files:
429
+ return gr.update(choices=[])
430
+
431
+ file_choices = []
432
+
433
+ for file in files:
434
+ # Get the file name and create a path in the upload directory
435
+ file_name = Path(file.name).name
436
+ file_path = RUN_FOLDER / file_name
437
+
438
+ # Save the file
439
+ shutil.copy(file.name, file_path)
440
+
441
+ # Add to the list of uploaded files
442
+ file_path_str = str(file_path)
443
+ file_choices.append((file_name, file_path_str))
444
+
445
+ # Add to state
446
+ if file_path_str not in state['uploaded_files']:
447
+ state['uploaded_files'].append(file_path_str)
448
+
449
+ # Update the view file dropdown with all uploaded files
450
+ all_file_choices = [(Path(path).name, path) for path in state['uploaded_files']]
451
+
452
+ return gr.update(choices=all_file_choices)
453
+
454
+ def toggle_view(view_mode, file_path=None, state=None):
455
+ """Toggle between OmniTool Computer view and file viewer"""
456
+ # If switching to File Viewer mode, detect and add new files to the state
457
+ file_choices_update = gr.update()
458
+ if view_mode == "File Viewer" and state is not None:
459
+ file_choices_update = detect_new_files(state)
460
+
461
+ # Return the appropriate view
462
+ if view_mode == "OmniTool Computer":
463
+ return get_file_viewer_html(), file_choices_update # This returns the VNC iframe
464
+ else: # File Viewer mode
465
+ if file_path:
466
+ return get_file_viewer_html(file_path), file_choices_update
467
+ else:
468
+ return get_file_viewer_html(), file_choices_update # Default to VNC if no file selected
469
+
470
+ def detect_new_files(state):
471
+ """Detect new files in the uploads folder and add them to the state"""
472
+ new_files_count = 0
473
+ if RUN_FOLDER.exists():
474
+ current_files = set(state['uploaded_files'])
475
+ for file_path in RUN_FOLDER.iterdir():
476
+ if file_path.is_file():
477
+ file_path_str = str(file_path)
478
+ if file_path_str not in current_files:
479
+ # This is a new file not yet in the state
480
+ state['uploaded_files'].append(file_path_str)
481
+ new_files_count += 1
482
+ print(f"Added new file to state: {file_path_str}")
483
+
484
+ # Return updated file choices
485
+ file_choices = [(Path(path).name, path) for path in state['uploaded_files']]
486
+ print(f"Detected {new_files_count} new files. Total files in state: {len(state['uploaded_files'])}")
487
+ return gr.update(choices=file_choices)
488
+
489
+ def refresh_files(state):
490
+ """Refresh the list of files from the current session and detect new files"""
491
+ return detect_new_files(state)
492
+
493
+ def auto_refresh_files(state):
494
+ """Automatically refresh the list of files from the current session and detect new files"""
495
+ return detect_new_files(state)
496
+
497
+ with gr.Blocks(theme=gr.themes.Default()) as demo:
498
+ gr.HTML("""
499
+ <style>
500
+ .no-padding {
501
+ padding: 0 !important;
502
+ }
503
+ .no-padding > div {
504
+ padding: 0 !important;
505
+ }
506
+ .markdown-text p {
507
+ font-size: 18px; /* Adjust the font size as needed */
508
+ }
509
+ </style>
510
+ """)
511
+ state = gr.State({})
512
+
513
+ setup_state(state.value)
514
+
515
+ header_image = get_header_image_base64()
516
+ if header_image:
517
+ gr.HTML(f'<img src="{header_image}" alt="OmniTool Header" width="100%">', elem_classes="no-padding")
518
+ gr.HTML('<h1 style="text-align: center; font-weight: normal; margin-bottom: 20px;">Omni<span style="font-weight: bold;">Tool</span></h1>')
519
+ else:
520
+ gr.Markdown("# OmniTool", elem_classes="text-center")
521
+
522
+ if not os.getenv("HIDE_WARNING", False):
523
+ gr.HTML(INTRO_TEXT, elem_classes="markdown-text")
524
+
525
+ with gr.Accordion("Settings", open=True, elem_classes="accordion-header"):
526
+ with gr.Row():
527
+ with gr.Column():
528
+ model = gr.Dropdown(
529
+ label="Model",
530
+ choices=["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini", "omniparser + R1", "omniparser + qwen2.5vl", "claude-3-5-sonnet-20241022", "omniparser + gpt-4o-orchestrated", "omniparser + o1-orchestrated", "omniparser + o3-mini-orchestrated", "omniparser + R1-orchestrated", "omniparser + qwen2.5vl-orchestrated"],
531
+ value="omniparser + gpt-4o-orchestrated",
532
+ interactive=True,
533
+ container=True
534
+ )
535
+ with gr.Column():
536
+ only_n_images = gr.Slider(
537
+ label="N most recent screenshots",
538
+ minimum=0,
539
+ maximum=10,
540
+ step=1,
541
+ value=2,
542
+ interactive=True
543
+ )
544
+ with gr.Row():
545
+ with gr.Column(1):
546
+ provider = gr.Dropdown(
547
+ label="API Provider",
548
+ choices=[option.value for option in APIProvider],
549
+ value="openai",
550
+ interactive=False,
551
+ container=True
552
+ )
553
+ with gr.Column(2):
554
+ api_key = gr.Textbox(
555
+ label="API Key",
556
+ type="password",
557
+ value=state.value.get("api_key", ""),
558
+ placeholder="Paste your API key here",
559
+ interactive=True,
560
+ container=True
561
+ )
562
+
563
+ # File Upload Section
564
+ with gr.Accordion("File Upload & Management", open=True, elem_classes="accordion-header"):
565
+ with gr.Row():
566
+ with gr.Column():
567
+ file_upload = gr.File(
568
+ label="Upload Files",
569
+ file_count="multiple",
570
+ type="filepath",
571
+ elem_classes="file-upload-area"
572
+ )
573
+ with gr.Column():
574
+ with gr.Row():
575
+ upload_button = gr.Button("Upload Files", variant="primary", elem_classes="primary-button")
576
+ refresh_button = gr.Button("Refresh Files", variant="secondary", elem_classes="secondary-button")
577
+
578
+ with gr.Row():
579
+ # Initialize file choices as an empty list
580
+ view_file_dropdown = gr.Dropdown(
581
+ label="View File",
582
+ choices=[],
583
+ interactive=True,
584
+ container=True
585
+ )
586
+ view_toggle = gr.Radio(
587
+ label="Display Mode",
588
+ choices=["OmniTool Computer", "File Viewer"],
589
+ value="OmniTool Computer",
590
+ interactive=True
591
+ )
592
+
593
+ with gr.Row():
594
+ with gr.Column(scale=8):
595
+ chat_input = gr.Textbox(
596
+ show_label=False,
597
+ placeholder="Type a message to send to Omniparser + X ...",
598
+ container=False
599
+ )
600
+ with gr.Column(scale=1, min_width=50):
601
+ submit_button = gr.Button(value="Send", variant="primary", elem_classes="primary-button")
602
+ with gr.Column(scale=1, min_width=50):
603
+ stop_button = gr.Button(value="Stop", variant="secondary", elem_classes="secondary-button")
604
+
605
+ with gr.Row():
606
+ with gr.Column(scale=2):
607
+ chatbot = gr.Chatbot(
608
+ label="Chatbot History",
609
+ autoscroll=True,
610
+ height=580,
611
+ avatar_images=("👤", "🤖")
612
+ )
613
+ with gr.Column(scale=3):
614
+ display_area = gr.HTML(
615
+ get_file_viewer_html(),
616
+ elem_classes="no-padding"
617
+ )
618
+
619
+ def update_model(model_selection, state):
620
+ state["model"] = model_selection
621
+ print(f"Model updated to: {state['model']}")
622
+
623
+ if model_selection == "claude-3-5-sonnet-20241022":
624
+ provider_choices = [option.value for option in APIProvider if option.value != "openai"]
625
+ elif model_selection in set(["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini", "omniparser + gpt-4o-orchestrated", "omniparser + o1-orchestrated", "omniparser + o3-mini-orchestrated"]):
626
+ provider_choices = ["openai"]
627
+ elif model_selection == "omniparser + R1":
628
+ provider_choices = ["groq"]
629
+ elif model_selection == "omniparser + qwen2.5vl":
630
+ provider_choices = ["dashscope"]
631
+ else:
632
+ provider_choices = [option.value for option in APIProvider]
633
+ default_provider_value = provider_choices[0]
634
+
635
+ provider_interactive = len(provider_choices) > 1
636
+ api_key_placeholder = f"{default_provider_value.title()} API Key"
637
+
638
+ # Update state
639
+ state["provider"] = default_provider_value
640
+ state["api_key"] = state.get(f"{default_provider_value}_api_key", "")
641
+
642
+ # Calls to update other components UI
643
+ provider_update = gr.update(
644
+ choices=provider_choices,
645
+ value=default_provider_value,
646
+ interactive=provider_interactive
647
+ )
648
+ api_key_update = gr.update(
649
+ placeholder=api_key_placeholder,
650
+ value=state["api_key"]
651
+ )
652
+
653
+ return provider_update, api_key_update
654
+
655
+ def update_only_n_images(only_n_images_value, state):
656
+ state["only_n_most_recent_images"] = only_n_images_value
657
+
658
+ def update_provider(provider_value, state):
659
+ # Update state
660
+ state["provider"] = provider_value
661
+ state["api_key"] = state.get(f"{provider_value}_api_key", "")
662
+
663
+ # Calls to update other components UI
664
+ api_key_update = gr.update(
665
+ placeholder=f"{provider_value.title()} API Key",
666
+ value=state["api_key"]
667
+ )
668
+ return api_key_update
669
+
670
+ def update_api_key(api_key_value, state):
671
+ state["api_key"] = api_key_value
672
+ state[f'{state["provider"]}_api_key'] = api_key_value
673
+
674
+ def clear_chat(state):
675
+ # Reset message-related state
676
+ state["messages"] = []
677
+ state["responses"] = {}
678
+ state["tools"] = {}
679
+ state['chatbot_messages'] = []
680
+ return state['chatbot_messages']
681
+
682
+ def view_file(file_path, view_mode):
683
+ """Generate HTML to view the selected file if in File Viewer mode"""
684
+ if view_mode == "File Viewer" and file_path:
685
+ return get_file_viewer_html(file_path)
686
+ elif view_mode == "OmniTool Computer":
687
+ return get_file_viewer_html() # Return VNC viewer
688
+ else:
689
+ return display_area.value # Keep current display
690
+
691
+ def update_view_file_dropdown(uploaded_files):
692
+ """Update the view file dropdown when uploaded files change"""
693
+ if not uploaded_files:
694
+ return gr.update(choices=[])
695
+
696
+ file_choices = [(Path(path).name, path) for path in uploaded_files]
697
+ return gr.update(choices=file_choices)
698
+
699
+ def reset_view():
700
+ """Reset the view to the VNC viewer"""
701
+ return get_file_viewer_html()
702
+
703
+ model.change(fn=update_model, inputs=[model, state], outputs=[provider, api_key])
704
+ only_n_images.change(fn=update_only_n_images, inputs=[only_n_images, state], outputs=None)
705
+ provider.change(fn=update_provider, inputs=[provider, state], outputs=api_key)
706
+ api_key.change(fn=update_api_key, inputs=[api_key, state], outputs=None)
707
+ chatbot.clear(fn=clear_chat, inputs=[state], outputs=[chatbot])
708
+
709
+ # File upload event handlers
710
+ upload_button.click(
711
+ fn=handle_file_upload,
712
+ inputs=[file_upload, state],
713
+ outputs=[view_file_dropdown]
714
+ )
715
+
716
+ # File viewing handlers
717
+ view_file_dropdown.change(
718
+ fn=view_file,
719
+ inputs=[view_file_dropdown, view_toggle],
720
+ outputs=[display_area]
721
+ )
722
+
723
+ submit_button.click(process_input, [chat_input, state], [chatbot, view_file_dropdown])
724
+ stop_button.click(stop_app, [state], None)
725
+
726
+ # Toggle view handler
727
+ view_toggle.change(
728
+ fn=toggle_view,
729
+ inputs=[view_toggle, view_file_dropdown, state],
730
+ outputs=[display_area, view_file_dropdown]
731
+ )
732
+
733
+ # Refresh files handler
734
+ refresh_button.click(fn=refresh_files, inputs=[state], outputs=[view_file_dropdown])
735
+
736
+ # Add JavaScript for auto-refresh instead of using demo.load()
737
+ js_refresh = """
738
+ function() {
739
+ // Auto-refresh files every 5 seconds
740
+ const refreshInterval = setInterval(function() {
741
+ // Find and click the refresh button
742
+ const refreshButtons = document.querySelectorAll('button');
743
+ for (const button of refreshButtons) {
744
+ if (button.textContent.includes('Refresh Files')) {
745
+ button.click();
746
+ break;
747
+ }
748
+ }
749
+ }, 5000);
750
+
751
+ // Return a cleanup function
752
+ return () => clearInterval(refreshInterval);
753
+ }
754
+ """
755
+
756
+ # Add the JavaScript to the page
757
+ gr.HTML("<script>(" + js_refresh + ")();</script>")
758
+
759
+ if __name__ == "__main__":
760
+ demo.launch(server_name="127.0.0.1", server_port=7888)