DravenBlack commited on
Commit
a712336
·
verified ·
1 Parent(s): 649c590

Upload 95 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +16 -0
  2. OmniParser/.gitignore +13 -0
  3. OmniParser/LICENSE +395 -0
  4. OmniParser/README.md +80 -0
  5. OmniParser/SECURITY.md +41 -0
  6. OmniParser/demo.ipynb +0 -0
  7. OmniParser/docs/Evaluation.md +4 -0
  8. OmniParser/eval/logs_sspro_omniv2.json +0 -0
  9. OmniParser/eval/ss_pro_gpt4o_omniv2.py +411 -0
  10. OmniParser/gradio_demo.py +98 -0
  11. OmniParser/imgs/demo_image.jpg +3 -0
  12. OmniParser/imgs/demo_image_som.jpg +3 -0
  13. OmniParser/imgs/excel.png +3 -0
  14. OmniParser/imgs/google_page.png +3 -0
  15. OmniParser/imgs/gradioicon.png +0 -0
  16. OmniParser/imgs/header_bar.png +3 -0
  17. OmniParser/imgs/header_bar_thin.png +0 -0
  18. OmniParser/imgs/ios.png +3 -0
  19. OmniParser/imgs/logo.png +0 -0
  20. OmniParser/imgs/mobile.png +3 -0
  21. OmniParser/imgs/omni3.jpg +0 -0
  22. OmniParser/imgs/omniboxicon.png +0 -0
  23. OmniParser/imgs/omniparsericon.png +0 -0
  24. OmniParser/imgs/onenote.png +3 -0
  25. OmniParser/imgs/saved_image_demo.png +3 -0
  26. OmniParser/imgs/som_overlaid_omni.png +3 -0
  27. OmniParser/imgs/teams.png +3 -0
  28. OmniParser/imgs/windows.png +3 -0
  29. OmniParser/imgs/windows_home.png +3 -0
  30. OmniParser/imgs/windows_multitab.png +3 -0
  31. OmniParser/imgs/windows_vm.png +3 -0
  32. OmniParser/imgs/word.png +3 -0
  33. OmniParser/omnitool/gradio/.gitignore +1 -0
  34. OmniParser/omnitool/gradio/__init__.py +0 -0
  35. OmniParser/omnitool/gradio/agent/anthropic_agent.py +162 -0
  36. OmniParser/omnitool/gradio/agent/llm_utils/groqclient.py +59 -0
  37. OmniParser/omnitool/gradio/agent/llm_utils/oaiclient.py +62 -0
  38. OmniParser/omnitool/gradio/agent/llm_utils/omniparserclient.py +44 -0
  39. OmniParser/omnitool/gradio/agent/llm_utils/utils.py +13 -0
  40. OmniParser/omnitool/gradio/agent/vlm_agent.py +353 -0
  41. OmniParser/omnitool/gradio/agent/vlm_agent_with_orchestrator.py +498 -0
  42. OmniParser/omnitool/gradio/app.py +426 -0
  43. OmniParser/omnitool/gradio/app_new.py +760 -0
  44. OmniParser/omnitool/gradio/app_streamlit.py +470 -0
  45. OmniParser/omnitool/gradio/executor/anthropic_executor.py +132 -0
  46. OmniParser/omnitool/gradio/loop.py +127 -0
  47. OmniParser/omnitool/gradio/tools/__init__.py +11 -0
  48. OmniParser/omnitool/gradio/tools/base.py +65 -0
  49. OmniParser/omnitool/gradio/tools/collection.py +34 -0
  50. OmniParser/omnitool/gradio/tools/computer.py +329 -0
.gitattributes CHANGED
@@ -33,3 +33,19 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ OmniParser/imgs/demo_image_som.jpg filter=lfs diff=lfs merge=lfs -text
37
+ OmniParser/imgs/demo_image.jpg filter=lfs diff=lfs merge=lfs -text
38
+ OmniParser/imgs/excel.png filter=lfs diff=lfs merge=lfs -text
39
+ OmniParser/imgs/google_page.png filter=lfs diff=lfs merge=lfs -text
40
+ OmniParser/imgs/header_bar.png filter=lfs diff=lfs merge=lfs -text
41
+ OmniParser/imgs/ios.png filter=lfs diff=lfs merge=lfs -text
42
+ OmniParser/imgs/mobile.png filter=lfs diff=lfs merge=lfs -text
43
+ OmniParser/imgs/onenote.png filter=lfs diff=lfs merge=lfs -text
44
+ OmniParser/imgs/saved_image_demo.png filter=lfs diff=lfs merge=lfs -text
45
+ OmniParser/imgs/som_overlaid_omni.png filter=lfs diff=lfs merge=lfs -text
46
+ OmniParser/imgs/teams.png filter=lfs diff=lfs merge=lfs -text
47
+ OmniParser/imgs/windows_home.png filter=lfs diff=lfs merge=lfs -text
48
+ OmniParser/imgs/windows_multitab.png filter=lfs diff=lfs merge=lfs -text
49
+ OmniParser/imgs/windows_vm.png filter=lfs diff=lfs merge=lfs -text
50
+ OmniParser/imgs/windows.png filter=lfs diff=lfs merge=lfs -text
51
+ OmniParser/imgs/word.png filter=lfs diff=lfs merge=lfs -text
OmniParser/.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ weights/icon_caption_blip2
2
+ weights/icon_caption_florence
3
+ weights/icon_detect/
4
+ weights/icon_detect_v1_5/
5
+ weights/icon_detect_v1_5_2/
6
+ .gradio
7
+ __pycache__/
8
+ debug.ipynb
9
+ util/__pycache__/
10
+ index.html?linkid=2289031
11
+ wget-log
12
+ weights/icon_caption_florence_v2/
13
+ omnitool/gradio/uploads/
OmniParser/LICENSE ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More_considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution 4.0 International Public License
58
+
59
+ By exercising the Licensed Rights (defined below), You accept and agree
60
+ to be bound by the terms and conditions of this Creative Commons
61
+ Attribution 4.0 International Public License ("Public License"). To the
62
+ extent this Public License may be interpreted as a contract, You are
63
+ granted the Licensed Rights in consideration of Your acceptance of
64
+ these terms and conditions, and the Licensor grants You such rights in
65
+ consideration of benefits the Licensor receives from making the
66
+ Licensed Material available under these terms and conditions.
67
+
68
+
69
+ Section 1 -- Definitions.
70
+
71
+ a. Adapted Material means material subject to Copyright and Similar
72
+ Rights that is derived from or based upon the Licensed Material
73
+ and in which the Licensed Material is translated, altered,
74
+ arranged, transformed, or otherwise modified in a manner requiring
75
+ permission under the Copyright and Similar Rights held by the
76
+ Licensor. For purposes of this Public License, where the Licensed
77
+ Material is a musical work, performance, or sound recording,
78
+ Adapted Material is always produced where the Licensed Material is
79
+ synched in timed relation with a moving image.
80
+
81
+ b. Adapter's License means the license You apply to Your Copyright
82
+ and Similar Rights in Your contributions to Adapted Material in
83
+ accordance with the terms and conditions of this Public License.
84
+
85
+ c. Copyright and Similar Rights means copyright and/or similar rights
86
+ closely related to copyright including, without limitation,
87
+ performance, broadcast, sound recording, and Sui Generis Database
88
+ Rights, without regard to how the rights are labeled or
89
+ categorized. For purposes of this Public License, the rights
90
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
91
+ Rights.
92
+
93
+ d. Effective Technological Measures means those measures that, in the
94
+ absence of proper authority, may not be circumvented under laws
95
+ fulfilling obligations under Article 11 of the WIPO Copyright
96
+ Treaty adopted on December 20, 1996, and/or similar international
97
+ agreements.
98
+
99
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
100
+ any other exception or limitation to Copyright and Similar Rights
101
+ that applies to Your use of the Licensed Material.
102
+
103
+ f. Licensed Material means the artistic or literary work, database,
104
+ or other material to which the Licensor applied this Public
105
+ License.
106
+
107
+ g. Licensed Rights means the rights granted to You subject to the
108
+ terms and conditions of this Public License, which are limited to
109
+ all Copyright and Similar Rights that apply to Your use of the
110
+ Licensed Material and that the Licensor has authority to license.
111
+
112
+ h. Licensor means the individual(s) or entity(ies) granting rights
113
+ under this Public License.
114
+
115
+ i. Share means to provide material to the public by any means or
116
+ process that requires permission under the Licensed Rights, such
117
+ as reproduction, public display, public performance, distribution,
118
+ dissemination, communication, or importation, and to make material
119
+ available to the public including in ways that members of the
120
+ public may access the material from a place and at a time
121
+ individually chosen by them.
122
+
123
+ j. Sui Generis Database Rights means rights other than copyright
124
+ resulting from Directive 96/9/EC of the European Parliament and of
125
+ the Council of 11 March 1996 on the legal protection of databases,
126
+ as amended and/or succeeded, as well as other essentially
127
+ equivalent rights anywhere in the world.
128
+
129
+ k. You means the individual or entity exercising the Licensed Rights
130
+ under this Public License. Your has a corresponding meaning.
131
+
132
+
133
+ Section 2 -- Scope.
134
+
135
+ a. License grant.
136
+
137
+ 1. Subject to the terms and conditions of this Public License,
138
+ the Licensor hereby grants You a worldwide, royalty-free,
139
+ non-sublicensable, non-exclusive, irrevocable license to
140
+ exercise the Licensed Rights in the Licensed Material to:
141
+
142
+ a. reproduce and Share the Licensed Material, in whole or
143
+ in part; and
144
+
145
+ b. produce, reproduce, and Share Adapted Material.
146
+
147
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
148
+ Exceptions and Limitations apply to Your use, this Public
149
+ License does not apply, and You do not need to comply with
150
+ its terms and conditions.
151
+
152
+ 3. Term. The term of this Public License is specified in Section
153
+ 6(a).
154
+
155
+ 4. Media and formats; technical modifications allowed. The
156
+ Licensor authorizes You to exercise the Licensed Rights in
157
+ all media and formats whether now known or hereafter created,
158
+ and to make technical modifications necessary to do so. The
159
+ Licensor waives and/or agrees not to assert any right or
160
+ authority to forbid You from making technical modifications
161
+ necessary to exercise the Licensed Rights, including
162
+ technical modifications necessary to circumvent Effective
163
+ Technological Measures. For purposes of this Public License,
164
+ simply making modifications authorized by this Section 2(a)
165
+ (4) never produces Adapted Material.
166
+
167
+ 5. Downstream recipients.
168
+
169
+ a. Offer from the Licensor -- Licensed Material. Every
170
+ recipient of the Licensed Material automatically
171
+ receives an offer from the Licensor to exercise the
172
+ Licensed Rights under the terms and conditions of this
173
+ Public License.
174
+
175
+ b. No downstream restrictions. You may not offer or impose
176
+ any additional or different terms or conditions on, or
177
+ apply any Effective Technological Measures to, the
178
+ Licensed Material if doing so restricts exercise of the
179
+ Licensed Rights by any recipient of the Licensed
180
+ Material.
181
+
182
+ 6. No endorsement. Nothing in this Public License constitutes or
183
+ may be construed as permission to assert or imply that You
184
+ are, or that Your use of the Licensed Material is, connected
185
+ with, or sponsored, endorsed, or granted official status by,
186
+ the Licensor or others designated to receive attribution as
187
+ provided in Section 3(a)(1)(A)(i).
188
+
189
+ b. Other rights.
190
+
191
+ 1. Moral rights, such as the right of integrity, are not
192
+ licensed under this Public License, nor are publicity,
193
+ privacy, and/or other similar personality rights; however, to
194
+ the extent possible, the Licensor waives and/or agrees not to
195
+ assert any such rights held by the Licensor to the limited
196
+ extent necessary to allow You to exercise the Licensed
197
+ Rights, but not otherwise.
198
+
199
+ 2. Patent and trademark rights are not licensed under this
200
+ Public License.
201
+
202
+ 3. To the extent possible, the Licensor waives any right to
203
+ collect royalties from You for the exercise of the Licensed
204
+ Rights, whether directly or through a collecting society
205
+ under any voluntary or waivable statutory or compulsory
206
+ licensing scheme. In all other cases the Licensor expressly
207
+ reserves any right to collect such royalties.
208
+
209
+
210
+ Section 3 -- License Conditions.
211
+
212
+ Your exercise of the Licensed Rights is expressly made subject to the
213
+ following conditions.
214
+
215
+ a. Attribution.
216
+
217
+ 1. If You Share the Licensed Material (including in modified
218
+ form), You must:
219
+
220
+ a. retain the following if it is supplied by the Licensor
221
+ with the Licensed Material:
222
+
223
+ i. identification of the creator(s) of the Licensed
224
+ Material and any others designated to receive
225
+ attribution, in any reasonable manner requested by
226
+ the Licensor (including by pseudonym if
227
+ designated);
228
+
229
+ ii. a copyright notice;
230
+
231
+ iii. a notice that refers to this Public License;
232
+
233
+ iv. a notice that refers to the disclaimer of
234
+ warranties;
235
+
236
+ v. a URI or hyperlink to the Licensed Material to the
237
+ extent reasonably practicable;
238
+
239
+ b. indicate if You modified the Licensed Material and
240
+ retain an indication of any previous modifications; and
241
+
242
+ c. indicate the Licensed Material is licensed under this
243
+ Public License, and include the text of, or the URI or
244
+ hyperlink to, this Public License.
245
+
246
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
247
+ reasonable manner based on the medium, means, and context in
248
+ which You Share the Licensed Material. For example, it may be
249
+ reasonable to satisfy the conditions by providing a URI or
250
+ hyperlink to a resource that includes the required
251
+ information.
252
+
253
+ 3. If requested by the Licensor, You must remove any of the
254
+ information required by Section 3(a)(1)(A) to the extent
255
+ reasonably practicable.
256
+
257
+ 4. If You Share Adapted Material You produce, the Adapter's
258
+ License You apply must not prevent recipients of the Adapted
259
+ Material from complying with this Public License.
260
+
261
+
262
+ Section 4 -- Sui Generis Database Rights.
263
+
264
+ Where the Licensed Rights include Sui Generis Database Rights that
265
+ apply to Your use of the Licensed Material:
266
+
267
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
268
+ to extract, reuse, reproduce, and Share all or a substantial
269
+ portion of the contents of the database;
270
+
271
+ b. if You include all or a substantial portion of the database
272
+ contents in a database in which You have Sui Generis Database
273
+ Rights, then the database in which You have Sui Generis Database
274
+ Rights (but not its individual contents) is Adapted Material; and
275
+
276
+ c. You must comply with the conditions in Section 3(a) if You Share
277
+ all or a substantial portion of the contents of the database.
278
+
279
+ For the avoidance of doubt, this Section 4 supplements and does not
280
+ replace Your obligations under this Public License where the Licensed
281
+ Rights include other Copyright and Similar Rights.
282
+
283
+
284
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
285
+
286
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
287
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
288
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
289
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
290
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
291
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
292
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
293
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
294
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
295
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
296
+
297
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
298
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
299
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
300
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
301
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
302
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
303
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
304
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
305
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
306
+
307
+ c. The disclaimer of warranties and limitation of liability provided
308
+ above shall be interpreted in a manner that, to the extent
309
+ possible, most closely approximates an absolute disclaimer and
310
+ waiver of all liability.
311
+
312
+
313
+ Section 6 -- Term and Termination.
314
+
315
+ a. This Public License applies for the term of the Copyright and
316
+ Similar Rights licensed here. However, if You fail to comply with
317
+ this Public License, then Your rights under this Public License
318
+ terminate automatically.
319
+
320
+ b. Where Your right to use the Licensed Material has terminated under
321
+ Section 6(a), it reinstates:
322
+
323
+ 1. automatically as of the date the violation is cured, provided
324
+ it is cured within 30 days of Your discovery of the
325
+ violation; or
326
+
327
+ 2. upon express reinstatement by the Licensor.
328
+
329
+ For the avoidance of doubt, this Section 6(b) does not affect any
330
+ right the Licensor may have to seek remedies for Your violations
331
+ of this Public License.
332
+
333
+ c. For the avoidance of doubt, the Licensor may also offer the
334
+ Licensed Material under separate terms or conditions or stop
335
+ distributing the Licensed Material at any time; however, doing so
336
+ will not terminate this Public License.
337
+
338
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
339
+ License.
340
+
341
+
342
+ Section 7 -- Other Terms and Conditions.
343
+
344
+ a. The Licensor shall not be bound by any additional or different
345
+ terms or conditions communicated by You unless expressly agreed.
346
+
347
+ b. Any arrangements, understandings, or agreements regarding the
348
+ Licensed Material not stated herein are separate from and
349
+ independent of the terms and conditions of this Public License.
350
+
351
+
352
+ Section 8 -- Interpretation.
353
+
354
+ a. For the avoidance of doubt, this Public License does not, and
355
+ shall not be interpreted to, reduce, limit, restrict, or impose
356
+ conditions on any use of the Licensed Material that could lawfully
357
+ be made without permission under this Public License.
358
+
359
+ b. To the extent possible, if any provision of this Public License is
360
+ deemed unenforceable, it shall be automatically reformed to the
361
+ minimum extent necessary to make it enforceable. If the provision
362
+ cannot be reformed, it shall be severed from this Public License
363
+ without affecting the enforceability of the remaining terms and
364
+ conditions.
365
+
366
+ c. No term or condition of this Public License will be waived and no
367
+ failure to comply consented to unless expressly agreed to by the
368
+ Licensor.
369
+
370
+ d. Nothing in this Public License constitutes or may be interpreted
371
+ as a limitation upon, or waiver of, any privileges and immunities
372
+ that apply to the Licensor or You, including from the legal
373
+ processes of any jurisdiction or authority.
374
+
375
+
376
+ =======================================================================
377
+
378
+ Creative Commons is not a party to its public
379
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
380
+ its public licenses to material it publishes and in those instances
381
+ will be considered the “Licensor.” The text of the Creative Commons
382
+ public licenses is dedicated to the public domain under the CC0 Public
383
+ Domain Dedication. Except for the limited purpose of indicating that
384
+ material is shared under a Creative Commons public license or as
385
+ otherwise permitted by the Creative Commons policies published at
386
+ creativecommons.org/policies, Creative Commons does not authorize the
387
+ use of the trademark "Creative Commons" or any other trademark or logo
388
+ of Creative Commons without its prior written consent including,
389
+ without limitation, in connection with any unauthorized modifications
390
+ to any of its public licenses or any other arrangements,
391
+ understandings, or agreements concerning use of licensed material. For
392
+ the avoidance of doubt, this paragraph does not form part of the
393
+ public licenses.
394
+
395
+ Creative Commons may be contacted at creativecommons.org.
OmniParser/README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OmniParser: Screen Parsing tool for Pure Vision Based GUI Agent
2
+
3
+ <p align="center">
4
+ <img src="imgs/logo.png" alt="Logo">
5
+ </p>
6
+ <!-- <a href="https://trendshift.io/repositories/12975" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12975" alt="microsoft%2FOmniParser | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a> -->
7
+
8
+ [![arXiv](https://img.shields.io/badge/Paper-green)](https://arxiv.org/abs/2408.00203)
9
+ [![License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
10
+
11
+ 📢 [[Project Page](https://microsoft.github.io/OmniParser/)] [[V2 Blog Post](https://www.microsoft.com/en-us/research/articles/omniparser-v2-turning-any-llm-into-a-computer-use-agent/)] [[Models V2](https://huggingface.co/microsoft/OmniParser-v2.0)] [[Models V1.5](https://huggingface.co/microsoft/OmniParser)] [[HuggingFace Space Demo](https://huggingface.co/spaces/microsoft/OmniParser-v2)]
12
+
13
+ **OmniParser** is a comprehensive method for parsing user interface screenshots into structured and easy-to-understand elements, which significantly enhances the ability of GPT-4V to generate actions that can be accurately grounded in the corresponding regions of the interface.
14
+
15
+ ## News
16
+ - [2025/3] We support local logging of trajecotry so that you can use OmniParser+OmniTool to build training data pipeline for your favorate agent in your domain. [Documentation WIP]
17
+ - [2025/3] We are gradually adding multi agents orchstration and improving user interface in OmniTool for better experience.
18
+ - [2025/2] We release OmniParser V2 [checkpoints](https://huggingface.co/microsoft/OmniParser-v2.0). [Watch Video](https://1drv.ms/v/c/650b027c18d5a573/EWXbVESKWo9Buu6OYCwg06wBeoM97C6EOTG6RjvWLEN1Qg?e=alnHGC)
19
+ - [2025/2] We introduce OmniTool: Control a Windows 11 VM with OmniParser + your vision model of choice. OmniTool supports out of the box the following large language models - OpenAI (4o/o1/o3-mini), DeepSeek (R1), Qwen (2.5VL) or Anthropic Computer Use. [Watch Video](https://1drv.ms/v/c/650b027c18d5a573/EehZ7RzY69ZHn-MeQHrnnR4BCj3by-cLLpUVlxMjF4O65Q?e=8LxMgX)
20
+ - [2025/1] V2 is coming. We achieve new state of the art results 39.5% on the new grounding benchmark [Screen Spot Pro](https://github.com/likaixin2000/ScreenSpot-Pro-GUI-Grounding/tree/main) with OmniParser v2 (will be released soon)! Read more details [here](https://github.com/microsoft/OmniParser/tree/master/docs/Evaluation.md).
21
+ - [2024/11] We release an updated version, OmniParser V1.5 which features 1) more fine grained/small icon detection, 2) prediction of whether each screen element is interactable or not. Examples in the demo.ipynb.
22
+ - [2024/10] OmniParser was the #1 trending model on huggingface model hub (starting 10/29/2024).
23
+ - [2024/10] Feel free to checkout our demo on [huggingface space](https://huggingface.co/spaces/microsoft/OmniParser)! (stay tuned for OmniParser + Claude Computer Use)
24
+ - [2024/10] Both Interactive Region Detection Model and Icon functional description model are released! [Hugginface models](https://huggingface.co/microsoft/OmniParser)
25
+ - [2024/09] OmniParser achieves the best performance on [Windows Agent Arena](https://microsoft.github.io/WindowsAgentArena/)!
26
+
27
+ ## Install
28
+ First clone the repo, and then install environment:
29
+ ```python
30
+ cd OmniParser
31
+ conda create -n "omni" python==3.12
32
+ conda activate omni
33
+ pip install -r requirements.txt
34
+ ```
35
+
36
+ Ensure you have the V2 weights downloaded in weights folder (ensure caption weights folder is called icon_caption_florence). If not download them with:
37
+ ```
38
+ # download the model checkpoints to local directory OmniParser/weights/
39
+ for f in icon_detect/{train_args.yaml,model.pt,model.yaml} icon_caption/{config.json,generation_config.json,model.safetensors}; do huggingface-cli download microsoft/OmniParser-v2.0 "$f" --local-dir weights; done
40
+ mv weights/icon_caption weights/icon_caption_florence
41
+ ```
42
+
43
+ <!-- ## [deprecated]
44
+ Then download the model ckpts files in: https://huggingface.co/microsoft/OmniParser, and put them under weights/, default folder structure is: weights/icon_detect, weights/icon_caption_florence, weights/icon_caption_blip2.
45
+
46
+ For v1:
47
+ convert the safetensor to .pt file.
48
+ ```python
49
+ python weights/convert_safetensor_to_pt.py
50
+
51
+ For v1.5:
52
+ download 'model_v1_5.pt' from https://huggingface.co/microsoft/OmniParser/tree/main/icon_detect_v1_5, make a new dir: weights/icon_detect_v1_5, and put it inside the folder. No weight conversion is needed.
53
+ ``` -->
54
+
55
+ ## Examples:
56
+ We put together a few simple examples in the demo.ipynb.
57
+
58
+ ## Gradio Demo
59
+ To run gradio demo, simply run:
60
+ ```python
61
+ python gradio_demo.py
62
+ ```
63
+
64
+ ## Model Weights License
65
+ For the model checkpoints on huggingface model hub, please note that icon_detect model is under AGPL license since it is a license inherited from the original yolo model. And icon_caption_blip2 & icon_caption_florence is under MIT license. Please refer to the LICENSE file in the folder of each model: https://huggingface.co/microsoft/OmniParser.
66
+
67
+ ## 📚 Citation
68
+ Our technical report can be found [here](https://arxiv.org/abs/2408.00203).
69
+ If you find our work useful, please consider citing our work:
70
+ ```
71
+ @misc{lu2024omniparserpurevisionbased,
72
+ title={OmniParser for Pure Vision Based GUI Agent},
73
+ author={Yadong Lu and Jianwei Yang and Yelong Shen and Ahmed Awadallah},
74
+ year={2024},
75
+ eprint={2408.00203},
76
+ archivePrefix={arXiv},
77
+ primaryClass={cs.CV},
78
+ url={https://arxiv.org/abs/2408.00203},
79
+ }
80
+ ```
OmniParser/SECURITY.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BEGIN MICROSOFT SECURITY.MD V0.0.9 BLOCK -->
2
+
3
+ ## Security
4
+
5
+ Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin).
6
+
7
+ If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below.
8
+
9
+ ## Reporting Security Issues
10
+
11
+ **Please do not report security vulnerabilities through public GitHub issues.**
12
+
13
+ Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report).
14
+
15
+ If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp).
16
+
17
+ You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
18
+
19
+ Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
20
+
21
+ * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
22
+ * Full paths of source file(s) related to the manifestation of the issue
23
+ * The location of the affected source code (tag/branch/commit or direct URL)
24
+ * Any special configuration required to reproduce the issue
25
+ * Step-by-step instructions to reproduce the issue
26
+ * Proof-of-concept or exploit code (if possible)
27
+ * Impact of the issue, including how an attacker might exploit the issue
28
+
29
+ This information will help us triage your report more quickly.
30
+
31
+ If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs.
32
+
33
+ ## Preferred Languages
34
+
35
+ We prefer all communications to be in English.
36
+
37
+ ## Policy
38
+
39
+ Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd).
40
+
41
+ <!-- END MICROSOFT SECURITY.MD BLOCK -->
OmniParser/demo.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
OmniParser/docs/Evaluation.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Eval setup for ScreenSpot Pro
2
+ We adapt the eval code from ScreenSpot Pro (ss pro) official [repo](https://github.com/likaixin2000/ScreenSpot-Pro-GUI-Grounding/tree/main). This folder contains the inference script/results on this benchmark. We going through legal review proces to release omniparser v2. Once it is done, we will update the file so that it can load the v2 model.
3
+ 1. eval/ss_pro_gpt4o_omniv2.py: contains the prompt we use, it can be dropped in replacement for this [file](https://github.com/likaixin2000/ScreenSpot-Pro-GUI-Grounding/blob/main/models/gpt4x.py) in the original ss pro repo.
4
+ 2. eval/logs_sspro_omniv2.json: contains the inferenced results for ss pro using GPT4o+OmniParserv2.
OmniParser/eval/logs_sspro_omniv2.json ADDED
The diff for this file is too large to render. See raw diff
 
OmniParser/eval/ss_pro_gpt4o_omniv2.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import ast
4
+ import base64
5
+ from io import BytesIO
6
+ from PIL import Image
7
+ from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
8
+
9
+ import openai
10
+ from openai import BadRequestError
11
+
12
+ model_name = "gpt-4o-2024-05-13"
13
+ OPENAI_KEY = os.environ.get("OPENAI_API_KEY")
14
+
15
+ def convert_pil_image_to_base64(image):
16
+ buffered = BytesIO()
17
+ image.save(buffered, format="PNG")
18
+ return base64.b64encode(buffered.getvalue()).decode()
19
+
20
+
21
+ from models.utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model
22
+ import torch
23
+ from ultralytics import YOLO
24
+ from PIL import Image
25
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
26
+ SOM_MODEL_PATH='...'
27
+ CAPTION_MODEL_PATH='...'
28
+ som_model = get_yolo_model(SOM_MODEL_PATH)
29
+
30
+ som_model.to(device)
31
+ print('model to {}'.format(device))
32
+
33
+ # two choices for caption model: fine-tuned blip2 or florence2
34
+ import importlib
35
+ caption_model_processor = get_caption_model_processor(model_name="florence2", model_name_or_path="CAPTION_MODEL_PATH", device=device)
36
+
37
+ def omniparser_parse(image, image_path):
38
+ box_overlay_ratio = max(image.size) / 3200
39
+ draw_bbox_config = {
40
+ 'text_scale': 0.8 * box_overlay_ratio,
41
+ 'text_thickness': max(int(2 * box_overlay_ratio), 1),
42
+ 'text_padding': max(int(3 * box_overlay_ratio), 1),
43
+ 'thickness': max(int(3 * box_overlay_ratio), 1),
44
+ }
45
+ BOX_TRESHOLD = 0.05
46
+
47
+ ocr_bbox_rslt, is_goal_filtered = check_ocr_box(image_path, display_img = False, output_bb_format='xyxy', goal_filtering=None, easyocr_args={'paragraph': False, 'text_threshold':0.5, 'canvas_size':max(image.size), 'decoder':'beamsearch', 'beamWidth':10, 'batch_size':256}, use_paddleocr=False)
48
+ text, ocr_bbox = ocr_bbox_rslt
49
+
50
+ dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(image_path, som_model, BOX_TRESHOLD = BOX_TRESHOLD, output_coord_in_ratio=True, ocr_bbox=ocr_bbox,draw_bbox_config=draw_bbox_config, caption_model_processor=caption_model_processor, ocr_text=text,use_local_semantics=True, iou_threshold=0.7, scale_img=False, batch_size=128)
51
+ return dino_labled_img, label_coordinates, parsed_content_list
52
+
53
+ def reformat_messages(parsed_content_list):
54
+ screen_info = ""
55
+ for idx, element in enumerate(parsed_content_list):
56
+ element['idx'] = idx
57
+ if element['type'] == 'text':
58
+ screen_info += f'''<p id={idx} class="text" alt="{element['content']}"> </p>\n'''
59
+ # screen_info += f'ID: {idx}, Text: {element["content"]}\n'
60
+ elif element['type'] == 'icon':
61
+ screen_info += f'''<img id={idx} class="icon" alt="{element['content']}"> </img>\n'''
62
+ # screen_info += f'ID: {idx}, Icon: {element["content"]}\n'
63
+ return screen_info
64
+
65
+ PROMPT_TEMPLATE_SEECLICK_PARSED_CONTENT = '''Please generate the next move according to the UI screenshot and task instruction. You will be presented with a screenshot image. Also you will be given each bounding box's description in a list. To complete the task, You should choose a related bbox to click based on the bbox descriptions.
66
+ Task instruction: {}.
67
+ Here is the list of all detected bounding boxes by IDs and their descriptions: {}. Keep in mind the description for Text Boxes are likely more accurate than the description for Icon Boxes.
68
+ Requirement: 1. You should first give a reasonable description of the current screenshot, and give a short analysis of how can the user task be achieved. 2. Then make an educated guess of bbox id to click in order to complete the task based on the bounding boxes descriptions. 3. Your answer should follow the following format: {{"Analysis": xxx, "Click BBox ID": "y"}}. Do not include any other info. Some examples: {}. The task is to {}. Retrieve the bbox id where its description matches the task instruction. Now start your answer:'''
69
+
70
+ # PROMPT_TEMPLATE_SEECLICK_PARSED_CONTENT_v1 = "The instruction is to {}. \nHere is the list of all detected bounding boxes by IDs and their descriptions: {}. \nKeep in mind the description for Text Boxes are likely more accurate than the description for Icon Boxes. \n Requirement: 1. You should first give a reasonable description of the current screenshot, and give a step by step analysis of how can the user task be achieved. 2. Then make an educated guess of bbox id to click in order to complete the task using both the visual information from the screenshot image and the bounding boxes descriptions. 3. Your answer should follow the following format: {{'Analysis': 'xxx', 'Click BBox ID': 'y'}}. Please do not include any other info."
71
+ PROMPT_TEMPLATE_SEECLICK_PARSED_CONTENT_v1 = "The instruction is to {}. \nHere is the list of all detected bounding boxes by IDs and their descriptions: {}. \nKeep in mind the description for Text Boxes are likely more accurate than the description for Icon Boxes. \n Requirement: 1. You should first give a reasonable description of the current screenshot, and give a some analysis of how can the user instruction be achieved by a single click. 2. Then make an educated guess of bbox id to click in order to complete the task using both the visual information from the screenshot image and the bounding boxes descriptions. REMEMBER: the task instruction must be achieved by one single click. 3. Your answer should follow the following format: {{'Analysis': 'xxx', 'Click BBox ID': 'y'}}. Please do not include any other info."
72
+
73
+
74
+ FEWSHOT_EXAMPLE = '''Example 1: Task instruction: Next page. \n{"Analysis": "Based on the screenshot and icon descriptions, I should click on the next page icon, which is labeled with box ID x in the bounding box list", "Click BBox ID": "x"}\n\n
75
+ Example 2: Task instruction: Search on google. \n{"Analysis": "Based on the screenshot and icon descriptions, I should click on the 'Search' box, which is labeled with box ID y in the bounding box list", "Click BBox ID": "y"}'''
76
+
77
+
78
+
79
+
80
+ from azure.identity import AzureCliCredential, DefaultAzureCredential, get_bearer_token_provider
81
+ from openai import AzureOpenAI
82
+ from models.utils import get_pred_phi3v, extract_dict_from_text, get_phi3v_model_dict
83
+
84
+ class GPT4XModel():
85
+ def __init__(self, model_name="gpt-4o-2024-05-13", use_managed_identity=False):
86
+ self.client = openai.OpenAI(
87
+ api_key=OPENAI_KEY,
88
+ )
89
+ self.model_name = model_name
90
+ if model_name == 'phi35v':
91
+ self.model_dict = get_phi3v_model_dict()
92
+
93
+ def load_model(self):
94
+ pass
95
+
96
+ def set_generation_config(self, **kwargs):
97
+ self.override_generation_config.update(kwargs)
98
+
99
+ def ground_only_positive_phi35v(self, instruction, image):
100
+ if isinstance(image, str):
101
+ image_path = image
102
+ assert os.path.exists(image_path) and os.path.isfile(image_path), "Invalid input image path."
103
+ image = Image.open(image_path).convert('RGB')
104
+ assert isinstance(image, Image.Image), "Invalid input image."
105
+
106
+ base64_image = convert_pil_image_to_base64(image)
107
+ dino_labled_img, label_coordinates, parsed_content_list = omniparser_parse(image, image_path)
108
+ screen_info = reformat_messages(parsed_content_list)
109
+ prompt_origin = PROMPT_TEMPLATE_SEECLICK_PARSED_CONTENT.format(instruction, screen_info, FEWSHOT_EXAMPLE, instruction)
110
+ # prompt_origin = PROMPT_TEMPLATE_SEECLICK_PARSED_CONTENT_v1.format(instruction, screen_info)
111
+
112
+ # Use the get_pred_phi3v function to get predictions
113
+ icon_id, bbox, click_point, response_text = get_pred_phi3v(prompt_origin, (base64_image, dino_labled_img), label_coordinates, id_key='Click ID', model_dict=self.model_dict)
114
+
115
+ result_dict = {
116
+ "result": "positive",
117
+ "bbox": bbox,
118
+ "point": click_point,
119
+ "raw_response": response_text,
120
+ 'dino_labled_img': dino_labled_img,
121
+ 'screen_info': screen_info,
122
+ }
123
+
124
+ return result_dict
125
+
126
+ def ground_only_positive(self, instruction, image):
127
+ if isinstance(image, str):
128
+ image_path = image
129
+ assert os.path.exists(image_path) and os.path.isfile(image_path), "Invalid input image path."
130
+ image = Image.open(image_path).convert('RGB')
131
+ assert isinstance(image, Image.Image), "Invalid input image."
132
+
133
+ base64_image = convert_pil_image_to_base64(image)
134
+ dino_labled_img, label_coordinates, parsed_content_list = omniparser_parse(image, image_path)
135
+ screen_info = reformat_messages(parsed_content_list)
136
+ # prompt_origin = PROMPT_TEMPLATE_SEECLICK_PARSED_CONTENT.format(screen_info, FEWSHOT_EXAMPLE, instruction)
137
+ prompt_origin = PROMPT_TEMPLATE_SEECLICK_PARSED_CONTENT_v1.format(instruction, screen_info)
138
+
139
+ try:
140
+ response = self.client.chat.completions.create(
141
+ model=self.model_name,
142
+ messages=[
143
+ {
144
+ "role": "system",
145
+ "content": [
146
+ # {"type": "text", "text": "You are an expert in using electronic devices and interacting with graphic interfaces. You should not call any external tools."}
147
+ {"type": "text", "text": '''You are an expert at completing instructions on GUI screens.
148
+ You will be presented with two images. The first is the original screenshot. The second is the same screenshot with some numeric tags. You will also be provided with some descriptions of the bbox, and your task is to choose the numeric bbox idx you want to click in order to complete the user instruction.'''}
149
+ ],
150
+ },
151
+ {
152
+ "role": "user",
153
+ "content": [
154
+ {
155
+ "type": "text",
156
+ "text": prompt_origin
157
+
158
+ },
159
+ {
160
+ "type": "image_url",
161
+ "image_url": {
162
+ "url": f"data:image/png;base64,{base64_image}",
163
+ }
164
+ },
165
+ {
166
+ "type": "image_url",
167
+ "image_url": {
168
+ "url": f"data:image/png;base64,{dino_labled_img}",
169
+ }
170
+ },
171
+ ],
172
+ }
173
+ ],
174
+ temperature=self.override_generation_config['temperature'],
175
+ max_tokens=2048,
176
+ )
177
+ response_text = response.choices[0].message.content
178
+ except BadRequestError as e:
179
+ print("OpenAI BadRequestError:", e)
180
+ return None
181
+
182
+ # Extract bounding box
183
+ # print("------")
184
+ # print(grounding_prompt)
185
+ print("------")
186
+ print(response_text)
187
+ # print("------")
188
+ # Try getting groundings
189
+ # bbox = extract_first_bounding_box(response_text)
190
+ # click_point = extract_first_point(response_text)
191
+
192
+ # if not click_point and bbox:
193
+ # click_point = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
194
+ response_text = response_text.replace('```json', '').replace('```', '') #TODO: fix this
195
+
196
+ try:
197
+ response_text = ast.literal_eval(response_text)
198
+
199
+ icon_id = response_text['Click BBox ID']
200
+ bbox = label_coordinates[str(icon_id)]
201
+ click_point = [bbox[0] + bbox[2]/2, bbox[1] + bbox[3]/2]
202
+ except:
203
+ print('error parsing, use regex to parse!!!')
204
+ response_text = extract_dict_from_text(response_text)
205
+ icon_id = response_text['Click BBox ID']
206
+ bbox = label_coordinates[str(icon_id)]
207
+ click_point = [bbox[0] + bbox[2]/2, bbox[1] + bbox[3]/2]
208
+
209
+ result_dict = {
210
+ "result": "positive",
211
+ "bbox": bbox,
212
+ "point": click_point,
213
+ "raw_response": response_text,
214
+ 'dino_labled_img': dino_labled_img,
215
+ 'screen_info': screen_info,
216
+ }
217
+
218
+ return result_dict
219
+
220
+ def ground_allow_negative(self, instruction, image=None):
221
+ if isinstance(image, str):
222
+ image_path = image
223
+ assert os.path.exists(image_path) and os.path.isfile(image_path), "Invalid input image path."
224
+ image = Image.open(image_path).convert('RGB')
225
+ assert isinstance(image, Image.Image), "Invalid input image."
226
+
227
+ base64_image = convert_pil_image_to_base64(image)
228
+
229
+ try:
230
+ response = self.client.chat.completions.create(
231
+ model=self.model_name,
232
+ messages=[
233
+ {
234
+ "role": "system",
235
+ "content": [
236
+ {"type": "text", "text": "You are an expert in using electronic devices and interacting with graphic interfaces. You should not call any external tools."}
237
+ ],
238
+ },
239
+ {
240
+ "role": "user",
241
+ "content": [
242
+ {
243
+ "type": "image_url",
244
+ "image_url": {
245
+ "url": f"data:image/png;base64,{base64_image}",
246
+ }
247
+ },
248
+ {
249
+ "type": "text",
250
+ "text": "You are asked to find the bounding box of an UI element in the given screenshot corresponding to a given instruction.\n"
251
+ "Don't output any analysis. Output your result in the format of [[x0,y0,x1,y1]], with x and y ranging from 0 to 1. \n"
252
+ "If such element does not exist, output only the text 'Target not existent'.\n"
253
+ "The instruction is:\n"
254
+ f"{instruction}\n"
255
+ }
256
+ ],
257
+ }
258
+ ],
259
+ temperature=self.override_generation_config['temperature'],
260
+ max_tokens=2048,
261
+ )
262
+ response_text = response.choices[0].message.content
263
+ except BadRequestError as e:
264
+ print("OpenAI BadRequestError:", e)
265
+ return {
266
+ "result": "failed"
267
+ }
268
+
269
+ # Extract bounding box
270
+ # print("------")
271
+ # print(grounding_prompt)
272
+ print("------")
273
+ print(response_text)
274
+ # print("------")
275
+
276
+ if "not existent" in response_text.lower():
277
+ return {
278
+ "result": "negative",
279
+ "bbox": None,
280
+ "point": None,
281
+ "raw_response": response_text
282
+ }
283
+
284
+ # Try getting groundings
285
+ bbox = extract_first_bounding_box(response_text)
286
+ click_point = extract_first_point(response_text)
287
+
288
+ if not click_point and bbox:
289
+ click_point = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
290
+
291
+ result_dict = {
292
+ "result": "positive" if bbox or click_point else "negative",
293
+ "bbox": bbox,
294
+ "point": click_point,
295
+ "raw_response": response_text
296
+ }
297
+
298
+ return result_dict
299
+
300
+
301
+ def ground_with_uncertainty(self, instruction, image=None):
302
+ if isinstance(image, str):
303
+ image_path = image
304
+ assert os.path.exists(image_path) and os.path.isfile(image_path), "Invalid input image path."
305
+ image = Image.open(image_path).convert('RGB')
306
+ assert isinstance(image, Image.Image), "Invalid input image."
307
+
308
+ base64_image = convert_pil_image_to_base64(image)
309
+
310
+ try:
311
+ response = self.client.chat.completions.create(
312
+ model=self.model_name,
313
+ messages=[
314
+ {
315
+ "role": "system",
316
+ "content": [
317
+ {"type": "text", "text": "You are an expert in using electronic devices and interacting with graphic interfaces. You should not call any external tools."}
318
+ ],
319
+ },
320
+ {
321
+ "role": "user",
322
+ "content": [
323
+ {
324
+ "type": "image_url",
325
+ "image_url": {
326
+ "url": f"data:image/png;base64,{base64_image}",
327
+ }
328
+ },
329
+ {
330
+ "type": "text",
331
+ "text": "You are asked to find the bounding box of an UI element in the given screenshot corresponding to a given instruction.\n"
332
+ "- If such element does not exist in the screenshot, output only the text 'Target not existent'."
333
+
334
+ "- If you are sure such element exists and you are confident in finding it, output your result in the format of [[x0,y0,x1,y1]], with x and y ranging from 0 to 1. \n"
335
+ "Please find out the bounding box of the UI element corresponding to the following instruction: \n"
336
+ "The instruction is:\n"
337
+ f"{instruction}\n"
338
+
339
+ }
340
+ ],
341
+ }
342
+ ],
343
+ temperature=self.override_generation_config['temperature'],
344
+ max_tokens=2048,
345
+ )
346
+ response_text = response.choices[0].message.content
347
+ except BadRequestError as e:
348
+ print("OpenAI BadRequestError:", e)
349
+ return {
350
+ "result": "failed"
351
+ }
352
+
353
+ # Extract bounding box
354
+ # print("------")
355
+ # print(grounding_prompt)
356
+ print("------")
357
+ print(response_text)
358
+ # print("------")
359
+
360
+ if "not found" in response_text.lower():
361
+ return {
362
+ "result": "negative",
363
+ "bbox": None,
364
+ "point": None,
365
+ "raw_response": response_text
366
+ }
367
+
368
+ # Try getting groundings
369
+ bbox = extract_first_bounding_box(response_text)
370
+ click_point = extract_first_point(response_text)
371
+
372
+ if not click_point and bbox:
373
+ click_point = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
374
+
375
+ result_dict = {
376
+ "result": "positive",
377
+ "bbox": bbox,
378
+ "point": click_point,
379
+ "raw_response": response_text
380
+ }
381
+
382
+ return result_dict
383
+
384
+ def extract_first_bounding_box(text):
385
+ # Regular expression pattern to match the first bounding box in the format [[x0,y0,x1,y1]]
386
+ # This captures the entire float value using \d for digits and optional decimal points
387
+ pattern = r"\[\[(\d+\.\d+|\d+),(\d+\.\d+|\d+),(\d+\.\d+|\d+),(\d+\.\d+|\d+)\]\]"
388
+
389
+ # Search for the first match in the text
390
+ match = re.search(pattern, text, re.DOTALL)
391
+
392
+ if match:
393
+ # Capture the bounding box coordinates as floats
394
+ bbox = [float(match.group(1)), float(match.group(2)), float(match.group(3)), float(match.group(4))]
395
+ return bbox
396
+ return None
397
+
398
+
399
+ def extract_first_point(text):
400
+ # Regular expression pattern to match the first point in the format [[x0,y0]]
401
+ # This captures the entire float value using \d for digits and optional decimal points
402
+ pattern = r"\[\[(\d+\.\d+|\d+),(\d+\.\d+|\d+)\]\]"
403
+
404
+ # Search for the first match in the text
405
+ match = re.search(pattern, text, re.DOTALL)
406
+
407
+ if match:
408
+ point = [float(match.group(1)), float(match.group(2))]
409
+ return point
410
+
411
+ return None
OmniParser/gradio_demo.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import gradio as gr
4
+ import numpy as np
5
+ import torch
6
+ from PIL import Image
7
+ import io
8
+
9
+
10
+ import base64, os
11
+ from util.utils import check_ocr_box, get_yolo_model, get_caption_model_processor, get_som_labeled_img
12
+ import torch
13
+ from PIL import Image
14
+
15
+ yolo_model = get_yolo_model(model_path='weights/icon_detect/model.pt')
16
+ caption_model_processor = get_caption_model_processor(model_name="florence2", model_name_or_path="weights/icon_caption_florence")
17
+ # caption_model_processor = get_caption_model_processor(model_name="blip2", model_name_or_path="weights/icon_caption_blip2")
18
+
19
+ MARKDOWN = """
20
+ # OmniParser for Pure Vision Based General GUI Agent 🔥
21
+ <div>
22
+ <a href="https://arxiv.org/pdf/2408.00203">
23
+ <img src="https://img.shields.io/badge/arXiv-2408.00203-b31b1b.svg" alt="Arxiv" style="display:inline-block;">
24
+ </a>
25
+ </div>
26
+
27
+ OmniParser is a screen parsing tool to convert general GUI screen to structured elements.
28
+ """
29
+
30
+ DEVICE = torch.device('cuda')
31
+
32
+ # @spaces.GPU
33
+ # @torch.inference_mode()
34
+ # @torch.autocast(device_type="cuda", dtype=torch.bfloat16)
35
+ def process(
36
+ image_input,
37
+ box_threshold,
38
+ iou_threshold,
39
+ use_paddleocr,
40
+ imgsz
41
+ ) -> Optional[Image.Image]:
42
+
43
+ box_overlay_ratio = image_input.size[0] / 3200
44
+ draw_bbox_config = {
45
+ 'text_scale': 0.8 * box_overlay_ratio,
46
+ 'text_thickness': max(int(2 * box_overlay_ratio), 1),
47
+ 'text_padding': max(int(3 * box_overlay_ratio), 1),
48
+ 'thickness': max(int(3 * box_overlay_ratio), 1),
49
+ }
50
+ # import pdb; pdb.set_trace()
51
+
52
+ ocr_bbox_rslt, is_goal_filtered = check_ocr_box(image_input, display_img = False, output_bb_format='xyxy', goal_filtering=None, easyocr_args={'paragraph': False, 'text_threshold':0.9}, use_paddleocr=use_paddleocr)
53
+ text, ocr_bbox = ocr_bbox_rslt
54
+ dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(image_input, yolo_model, BOX_TRESHOLD = box_threshold, output_coord_in_ratio=True, ocr_bbox=ocr_bbox,draw_bbox_config=draw_bbox_config, caption_model_processor=caption_model_processor, ocr_text=text,iou_threshold=iou_threshold, imgsz=imgsz,)
55
+ image = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
56
+ print('finish processing')
57
+ parsed_content_list = '\n'.join([f'icon {i}: ' + str(v) for i,v in enumerate(parsed_content_list)])
58
+ # parsed_content_list = str(parsed_content_list)
59
+ return image, str(parsed_content_list)
60
+
61
+ with gr.Blocks() as demo:
62
+ gr.Markdown(MARKDOWN)
63
+ with gr.Row():
64
+ with gr.Column():
65
+ image_input_component = gr.Image(
66
+ type='pil', label='Upload image')
67
+ # set the threshold for removing the bounding boxes with low confidence, default is 0.05
68
+ box_threshold_component = gr.Slider(
69
+ label='Box Threshold', minimum=0.01, maximum=1.0, step=0.01, value=0.05)
70
+ # set the threshold for removing the bounding boxes with large overlap, default is 0.1
71
+ iou_threshold_component = gr.Slider(
72
+ label='IOU Threshold', minimum=0.01, maximum=1.0, step=0.01, value=0.1)
73
+ use_paddleocr_component = gr.Checkbox(
74
+ label='Use PaddleOCR', value=True)
75
+ imgsz_component = gr.Slider(
76
+ label='Icon Detect Image Size', minimum=640, maximum=1920, step=32, value=640)
77
+ submit_button_component = gr.Button(
78
+ value='Submit', variant='primary')
79
+ with gr.Column():
80
+ image_output_component = gr.Image(type='pil', label='Image Output')
81
+ text_output_component = gr.Textbox(label='Parsed screen elements', placeholder='Text Output')
82
+
83
+ submit_button_component.click(
84
+ fn=process,
85
+ inputs=[
86
+ image_input_component,
87
+ box_threshold_component,
88
+ iou_threshold_component,
89
+ use_paddleocr_component,
90
+ imgsz_component
91
+ ],
92
+ outputs=[image_output_component, text_output_component]
93
+ )
94
+
95
+ #demo.launch(debug=True, show_error=True, share=True)
96
+ #demo.launch(share=True, server_port=7861, server_name='0.0.0.0')
97
+ #demo.launch(share=True, server_port=7862, server_name='127.0.0.1')
98
+ demo.launch(server_name="0.0.0.0", server_port=7860, debug=True, show_error=True, share=True)
OmniParser/imgs/demo_image.jpg ADDED

Git LFS Details

  • SHA256: 29dfbaca6024f5ca12e257f2d9499b475c78faad636609cc75c01ecfb5d3ec0f
  • Pointer size: 131 Bytes
  • Size of remote file: 573 kB
OmniParser/imgs/demo_image_som.jpg ADDED

Git LFS Details

  • SHA256: 278c8c4fdaf19cd87dde16165b7636c08e1f1f611f4124330a205f682f63bb40
  • Pointer size: 131 Bytes
  • Size of remote file: 737 kB
OmniParser/imgs/excel.png ADDED

Git LFS Details

  • SHA256: 2fa51d9c4be0e0485ae6139de8318154127fac483db12ef0b18acb866975695d
  • Pointer size: 131 Bytes
  • Size of remote file: 154 kB
OmniParser/imgs/google_page.png ADDED

Git LFS Details

  • SHA256: b49b10aea95808a8bf260632599df38c7d0d0c0e6ec8549b049323ffc3ceb3ac
  • Pointer size: 131 Bytes
  • Size of remote file: 332 kB
OmniParser/imgs/gradioicon.png ADDED
OmniParser/imgs/header_bar.png ADDED

Git LFS Details

  • SHA256: 61bf0bf90b3e0dbc80cf300a7ab7631b13b4f6f460dd796f1fb5eb91478dcec9
  • Pointer size: 131 Bytes
  • Size of remote file: 257 kB
OmniParser/imgs/header_bar_thin.png ADDED
OmniParser/imgs/ios.png ADDED

Git LFS Details

  • SHA256: 0ad1727216b6f55500084d5d2c1666ad953fcec6a0f12f646693a8264f1e44d2
  • Pointer size: 132 Bytes
  • Size of remote file: 1.93 MB
OmniParser/imgs/logo.png ADDED
OmniParser/imgs/mobile.png ADDED

Git LFS Details

  • SHA256: 14e6ef211fbb612de93f568eb7a129cc529debf4321b36f06ff2d927f391ff7a
  • Pointer size: 132 Bytes
  • Size of remote file: 3.26 MB
OmniParser/imgs/omni3.jpg ADDED
OmniParser/imgs/omniboxicon.png ADDED
OmniParser/imgs/omniparsericon.png ADDED
OmniParser/imgs/onenote.png ADDED

Git LFS Details

  • SHA256: 0d9dda4fd055b0d584a7f40eed1e890e18a092d8e01f171817f10c16bb31aa4d
  • Pointer size: 131 Bytes
  • Size of remote file: 121 kB
OmniParser/imgs/saved_image_demo.png ADDED

Git LFS Details

  • SHA256: a90160d0358f65fb0bff6693375a72c5a2be4505c51a3db32404233009216cdf
  • Pointer size: 131 Bytes
  • Size of remote file: 150 kB
OmniParser/imgs/som_overlaid_omni.png ADDED

Git LFS Details

  • SHA256: aebbb1876b50ebbf2887e193b91af41f6797bbb617748b5f88a28cd3e4f5de62
  • Pointer size: 131 Bytes
  • Size of remote file: 286 kB
OmniParser/imgs/teams.png ADDED

Git LFS Details

  • SHA256: 6061b1afa695c07a034313966bf48b1a90d0055408da848458858cadecc47936
  • Pointer size: 132 Bytes
  • Size of remote file: 1.75 MB
OmniParser/imgs/windows.png ADDED

Git LFS Details

  • SHA256: 091875eb3c285c5fc4681b257f0a00d529a2e225c17e9830b11115d2c12f9833
  • Pointer size: 132 Bytes
  • Size of remote file: 1.19 MB
OmniParser/imgs/windows_home.png ADDED

Git LFS Details

  • SHA256: 036008abc32379393876e722fedab2bd02bda9b667b957bc150c2f83c725ebac
  • Pointer size: 132 Bytes
  • Size of remote file: 6.1 MB
OmniParser/imgs/windows_multitab.png ADDED

Git LFS Details

  • SHA256: cdece5c30e3d87c63e3e99c9f6a796cc886a5e2a8a63cd4c6df0466e5a96c067
  • Pointer size: 131 Bytes
  • Size of remote file: 470 kB
OmniParser/imgs/windows_vm.png ADDED

Git LFS Details

  • SHA256: 929cbe8cecf7dfd8114ecab3cbaee2a1dea2fb1f28ba3eed309fd250bd550411
  • Pointer size: 132 Bytes
  • Size of remote file: 2.01 MB
OmniParser/imgs/word.png ADDED

Git LFS Details

  • SHA256: 634d054789643c815330cf9593127b57ff8fa22c6c8de2236035dfc8e994e367
  • Pointer size: 131 Bytes
  • Size of remote file: 189 kB
OmniParser/omnitool/gradio/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ tmp/
OmniParser/omnitool/gradio/__init__.py ADDED
File without changes
OmniParser/omnitool/gradio/agent/anthropic_agent.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Agentic sampling loop that calls the Anthropic API and local implenmentation of anthropic-defined computer use tools.
3
+ """
4
+ import asyncio
5
+ import platform
6
+ from collections.abc import Callable
7
+ from datetime import datetime
8
+ from enum import StrEnum
9
+ from typing import Any, cast
10
+
11
+ from anthropic import Anthropic, AnthropicBedrock, AnthropicVertex, APIResponse
12
+ from anthropic.types import (
13
+ ToolResultBlockParam,
14
+ )
15
+ from anthropic.types.beta import (
16
+ BetaContentBlock,
17
+ BetaContentBlockParam,
18
+ BetaImageBlockParam,
19
+ BetaMessage,
20
+ BetaMessageParam,
21
+ BetaTextBlockParam,
22
+ BetaToolResultBlockParam,
23
+ )
24
+ from anthropic.types import TextBlock
25
+ from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
26
+
27
+ from tools import ComputerTool, ToolCollection, ToolResult
28
+
29
+ from PIL import Image
30
+ from io import BytesIO
31
+ import gradio as gr
32
+ from typing import Dict
33
+
34
+ BETA_FLAG = "computer-use-2024-10-22"
35
+
36
+ class APIProvider(StrEnum):
37
+ ANTHROPIC = "anthropic"
38
+ BEDROCK = "bedrock"
39
+ VERTEX = "vertex"
40
+
41
+ SYSTEM_PROMPT = f"""<SYSTEM_CAPABILITY>
42
+ * You are utilizing a Windows system with internet access.
43
+ * The current date is {datetime.today().strftime('%A, %B %d, %Y')}.
44
+ </SYSTEM_CAPABILITY>
45
+ """
46
+
47
+ class AnthropicActor:
48
+ def __init__(
49
+ self,
50
+ model: str,
51
+ provider: APIProvider,
52
+ api_key: str,
53
+ api_response_callback: Callable[[APIResponse[BetaMessage]], None],
54
+ max_tokens: int = 4096,
55
+ only_n_most_recent_images: int | None = None,
56
+ print_usage: bool = True,
57
+ ):
58
+ self.model = model
59
+ self.provider = provider
60
+ self.api_key = api_key
61
+ self.api_response_callback = api_response_callback
62
+ self.max_tokens = max_tokens
63
+ self.only_n_most_recent_images = only_n_most_recent_images
64
+
65
+ self.tool_collection = ToolCollection(ComputerTool())
66
+
67
+ self.system = SYSTEM_PROMPT
68
+
69
+ self.total_token_usage = 0
70
+ self.total_cost = 0
71
+ self.print_usage = print_usage
72
+
73
+ # Instantiate the appropriate API client based on the provider
74
+ if provider == APIProvider.ANTHROPIC:
75
+ self.client = Anthropic(api_key=api_key)
76
+ elif provider == APIProvider.VERTEX:
77
+ self.client = AnthropicVertex()
78
+ elif provider == APIProvider.BEDROCK:
79
+ self.client = AnthropicBedrock()
80
+
81
+ def __call__(
82
+ self,
83
+ *,
84
+ messages: list[BetaMessageParam]
85
+ ):
86
+ """
87
+ Generate a response given history messages.
88
+ """
89
+ if self.only_n_most_recent_images:
90
+ _maybe_filter_to_n_most_recent_images(messages, self.only_n_most_recent_images)
91
+
92
+ # Call the API synchronously
93
+ raw_response = self.client.beta.messages.with_raw_response.create(
94
+ max_tokens=self.max_tokens,
95
+ messages=messages,
96
+ model=self.model,
97
+ system=self.system,
98
+ tools=self.tool_collection.to_params(),
99
+ betas=["computer-use-2024-10-22"],
100
+ )
101
+
102
+ self.api_response_callback(cast(APIResponse[BetaMessage], raw_response))
103
+
104
+ response = raw_response.parse()
105
+ print(f"AnthropicActor response: {response}")
106
+
107
+ self.total_token_usage += response.usage.input_tokens + response.usage.output_tokens
108
+ self.total_cost += (response.usage.input_tokens * 3 / 1000000 + response.usage.output_tokens * 15 / 1000000)
109
+
110
+ if self.print_usage:
111
+ print(f"Claude total token usage so far: {self.total_token_usage}, total cost so far: $USD{self.total_cost}")
112
+
113
+ return response
114
+
115
+
116
+ def _maybe_filter_to_n_most_recent_images(
117
+ messages: list[BetaMessageParam],
118
+ images_to_keep: int,
119
+ min_removal_threshold: int = 10,
120
+ ):
121
+ """
122
+ With the assumption that images are screenshots that are of diminishing value as
123
+ the conversation progresses, remove all but the final `images_to_keep` tool_result
124
+ images in place, with a chunk of min_removal_threshold to reduce the amount we
125
+ break the implicit prompt cache.
126
+ """
127
+ if images_to_keep is None:
128
+ return messages
129
+
130
+ tool_result_blocks = cast(
131
+ list[ToolResultBlockParam],
132
+ [
133
+ item
134
+ for message in messages
135
+ for item in (
136
+ message["content"] if isinstance(message["content"], list) else []
137
+ )
138
+ if isinstance(item, dict) and item.get("type") == "tool_result"
139
+ ],
140
+ )
141
+
142
+ total_images = sum(
143
+ 1
144
+ for tool_result in tool_result_blocks
145
+ for content in tool_result.get("content", [])
146
+ if isinstance(content, dict) and content.get("type") == "image"
147
+ )
148
+
149
+ images_to_remove = total_images - images_to_keep
150
+ # for better cache behavior, we want to remove in chunks
151
+ images_to_remove -= images_to_remove % min_removal_threshold
152
+
153
+ for tool_result in tool_result_blocks:
154
+ if isinstance(tool_result.get("content"), list):
155
+ new_content = []
156
+ for content in tool_result.get("content", []):
157
+ if isinstance(content, dict) and content.get("type") == "image":
158
+ if images_to_remove > 0:
159
+ images_to_remove -= 1
160
+ continue
161
+ new_content.append(content)
162
+ tool_result["content"] = new_content
OmniParser/omnitool/gradio/agent/llm_utils/groqclient.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from groq import Groq
2
+ import os
3
+ from .utils import is_image_path
4
+
5
+ def run_groq_interleaved(messages: list, system: str, model_name: str, api_key: str, max_tokens=256, temperature=0.6):
6
+ """
7
+ Run a chat completion through Groq's API, ignoring any images in the messages.
8
+ """
9
+ api_key = api_key or os.environ.get("GROQ_API_KEY")
10
+ if not api_key:
11
+ raise ValueError("GROQ_API_KEY is not set")
12
+
13
+ client = Groq(api_key=api_key)
14
+ # avoid using system messages for R1
15
+ final_messages = [{"role": "user", "content": system}]
16
+
17
+ if isinstance(messages, list):
18
+ for item in messages:
19
+ if isinstance(item, dict):
20
+ # For dict items, concatenate all text content, ignoring images
21
+ text_contents = []
22
+ for cnt in item["content"]:
23
+ if isinstance(cnt, str):
24
+ if not is_image_path(cnt): # Skip image paths
25
+ text_contents.append(cnt)
26
+ else:
27
+ text_contents.append(str(cnt))
28
+
29
+ if text_contents: # Only add if there's text content
30
+ message = {"role": "user", "content": " ".join(text_contents)}
31
+ final_messages.append(message)
32
+ else: # str
33
+ message = {"role": "user", "content": item}
34
+ final_messages.append(message)
35
+
36
+ elif isinstance(messages, str):
37
+ final_messages.append({"role": "user", "content": messages})
38
+
39
+ try:
40
+ completion = client.chat.completions.create(
41
+ model="deepseek-r1-distill-llama-70b",
42
+ messages=final_messages,
43
+ temperature=0.6,
44
+ max_completion_tokens=max_tokens,
45
+ top_p=0.95,
46
+ stream=False,
47
+ reasoning_format="raw"
48
+ )
49
+
50
+ response = completion.choices[0].message.content
51
+ final_answer = response.split('</think>\n')[-1] if '</think>' in response else response
52
+ final_answer = final_answer.replace("<output>", "").replace("</output>", "")
53
+ token_usage = completion.usage.total_tokens
54
+
55
+ return final_answer, token_usage
56
+ except Exception as e:
57
+ print(f"Error in interleaved Groq: {e}")
58
+
59
+ return str(e), 0
OmniParser/omnitool/gradio/agent/llm_utils/oaiclient.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import base64
4
+ import requests
5
+ from .utils import is_image_path, encode_image
6
+
7
+ def run_oai_interleaved(messages: list, system: str, model_name: str, api_key: str, max_tokens=256, temperature=0, provider_base_url: str = "https://api.openai.com/v1"):
8
+ headers = {"Content-Type": "application/json",
9
+ "Authorization": f"Bearer {api_key}"}
10
+ final_messages = [{"role": "system", "content": system}]
11
+
12
+ if type(messages) == list:
13
+ for item in messages:
14
+ contents = []
15
+ if isinstance(item, dict):
16
+ for cnt in item["content"]:
17
+ if isinstance(cnt, str):
18
+ if is_image_path(cnt) and 'o3-mini' not in model_name:
19
+ # 03 mini does not support images
20
+ base64_image = encode_image(cnt)
21
+ content = {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
22
+ else:
23
+ content = {"type": "text", "text": cnt}
24
+ else:
25
+ # in this case it is a text block from anthropic
26
+ content = {"type": "text", "text": str(cnt)}
27
+
28
+ contents.append(content)
29
+
30
+ message = {"role": 'user', "content": contents}
31
+ else: # str
32
+ contents.append({"type": "text", "text": item})
33
+ message = {"role": "user", "content": contents}
34
+
35
+ final_messages.append(message)
36
+
37
+
38
+ elif isinstance(messages, str):
39
+ final_messages = [{"role": "user", "content": messages}]
40
+
41
+ payload = {
42
+ "model": model_name,
43
+ "messages": final_messages,
44
+ }
45
+ if 'o1' in model_name or 'o3-mini' in model_name:
46
+ payload['reasoning_effort'] = 'low'
47
+ payload['max_completion_tokens'] = max_tokens
48
+ else:
49
+ payload['max_tokens'] = max_tokens
50
+
51
+ response = requests.post(
52
+ f"{provider_base_url}/chat/completions", headers=headers, json=payload
53
+ )
54
+
55
+
56
+ try:
57
+ text = response.json()['choices'][0]['message']['content']
58
+ token_usage = int(response.json()['usage']['total_tokens'])
59
+ return text, token_usage
60
+ except Exception as e:
61
+ print(f"Error in interleaved openAI: {e}. This may due to your invalid API key. Please check the response: {response.json()} ")
62
+ return response.json()
OmniParser/omnitool/gradio/agent/llm_utils/omniparserclient.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import base64
3
+ from pathlib import Path
4
+ from tools.screen_capture import get_screenshot
5
+ from agent.llm_utils.utils import encode_image
6
+
7
+ OUTPUT_DIR = "./tmp/outputs"
8
+
9
+ class OmniParserClient:
10
+ def __init__(self,
11
+ url: str) -> None:
12
+ self.url = url
13
+
14
+ def __call__(self,):
15
+ screenshot, screenshot_path = get_screenshot()
16
+ screenshot_path = str(screenshot_path)
17
+ image_base64 = encode_image(screenshot_path)
18
+ response = requests.post(self.url, json={"base64_image": image_base64})
19
+ response_json = response.json()
20
+ print('omniparser latency:', response_json['latency'])
21
+
22
+ som_image_data = base64.b64decode(response_json['som_image_base64'])
23
+ screenshot_path_uuid = Path(screenshot_path).stem.replace("screenshot_", "")
24
+ som_screenshot_path = f"{OUTPUT_DIR}/screenshot_som_{screenshot_path_uuid}.png"
25
+ with open(som_screenshot_path, "wb") as f:
26
+ f.write(som_image_data)
27
+
28
+ response_json['width'] = screenshot.size[0]
29
+ response_json['height'] = screenshot.size[1]
30
+ response_json['original_screenshot_base64'] = image_base64
31
+ response_json['screenshot_uuid'] = screenshot_path_uuid
32
+ response_json = self.reformat_messages(response_json)
33
+ return response_json
34
+
35
+ def reformat_messages(self, response_json: dict):
36
+ screen_info = ""
37
+ for idx, element in enumerate(response_json["parsed_content_list"]):
38
+ element['idx'] = idx
39
+ if element['type'] == 'text':
40
+ screen_info += f'ID: {idx}, Text: {element["content"]}\n'
41
+ elif element['type'] == 'icon':
42
+ screen_info += f'ID: {idx}, Icon: {element["content"]}\n'
43
+ response_json['screen_info'] = screen_info
44
+ return response_json
OmniParser/omnitool/gradio/agent/llm_utils/utils.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+
3
+ def is_image_path(text):
4
+ image_extensions = (".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".tif")
5
+ if text.endswith(image_extensions):
6
+ return True
7
+ else:
8
+ return False
9
+
10
+ def encode_image(image_path):
11
+ """Encode image file to base64."""
12
+ with open(image_path, "rb") as image_file:
13
+ return base64.b64encode(image_file.read()).decode("utf-8")
OmniParser/omnitool/gradio/agent/vlm_agent.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from collections.abc import Callable
3
+ from typing import cast, Callable
4
+ import uuid
5
+ from PIL import Image, ImageDraw
6
+ import base64
7
+ from io import BytesIO
8
+
9
+ from anthropic import APIResponse
10
+ from anthropic.types import ToolResultBlockParam
11
+ from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock, BetaMessageParam, BetaUsage
12
+
13
+ from agent.llm_utils.oaiclient import run_oai_interleaved
14
+ from agent.llm_utils.groqclient import run_groq_interleaved
15
+ from agent.llm_utils.utils import is_image_path
16
+ import time
17
+ import re
18
+
19
+ OUTPUT_DIR = "./tmp/outputs"
20
+
21
+ def extract_data(input_string, data_type):
22
+ # Regular expression to extract content starting from '```python' until the end if there are no closing backticks
23
+ pattern = f"```{data_type}" + r"(.*?)(```|$)"
24
+ # Extract content
25
+ # re.DOTALL allows '.' to match newlines as well
26
+ matches = re.findall(pattern, input_string, re.DOTALL)
27
+ # Return the first match if exists, trimming whitespace and ignoring potential closing backticks
28
+ return matches[0][0].strip() if matches else input_string
29
+
30
+ class VLMAgent:
31
+ def __init__(
32
+ self,
33
+ model: str,
34
+ provider: str,
35
+ api_key: str,
36
+ output_callback: Callable,
37
+ api_response_callback: Callable,
38
+ max_tokens: int = 4096,
39
+ only_n_most_recent_images: int | None = None,
40
+ print_usage: bool = True,
41
+ ):
42
+ if model == "omniparser + gpt-4o":
43
+ self.model = "gpt-4o-2024-11-20"
44
+ elif model == "omniparser + R1":
45
+ self.model = "deepseek-r1-distill-llama-70b"
46
+ elif model == "omniparser + qwen2.5vl":
47
+ self.model = "qwen2.5-vl-72b-instruct"
48
+ elif model == "omniparser + o1":
49
+ self.model = "o1"
50
+ elif model == "omniparser + o3-mini":
51
+ self.model = "o3-mini"
52
+ else:
53
+ raise ValueError(f"Model {model} not supported")
54
+
55
+
56
+ self.provider = provider
57
+ self.api_key = api_key
58
+ self.api_response_callback = api_response_callback
59
+ self.max_tokens = max_tokens
60
+ self.only_n_most_recent_images = only_n_most_recent_images
61
+ self.output_callback = output_callback
62
+
63
+ self.print_usage = print_usage
64
+ self.total_token_usage = 0
65
+ self.total_cost = 0
66
+ self.step_count = 0
67
+
68
+ self.system = ''
69
+
70
+ def __call__(self, messages: list, parsed_screen: list[str, list, dict]):
71
+ self.step_count += 1
72
+ image_base64 = parsed_screen['original_screenshot_base64']
73
+ latency_omniparser = parsed_screen['latency']
74
+ self.output_callback(f'-- Step {self.step_count}: --', sender="bot")
75
+ screen_info = str(parsed_screen['screen_info'])
76
+ screenshot_uuid = parsed_screen['screenshot_uuid']
77
+ screen_width, screen_height = parsed_screen['width'], parsed_screen['height']
78
+
79
+ boxids_and_labels = parsed_screen["screen_info"]
80
+ system = self._get_system_prompt(boxids_and_labels)
81
+
82
+ # drop looping actions msg, byte image etc
83
+ planner_messages = messages
84
+ _remove_som_images(planner_messages)
85
+ _maybe_filter_to_n_most_recent_images(planner_messages, self.only_n_most_recent_images)
86
+
87
+ if isinstance(planner_messages[-1], dict):
88
+ if not isinstance(planner_messages[-1]["content"], list):
89
+ planner_messages[-1]["content"] = [planner_messages[-1]["content"]]
90
+ planner_messages[-1]["content"].append(f"{OUTPUT_DIR}/screenshot_{screenshot_uuid}.png")
91
+ planner_messages[-1]["content"].append(f"{OUTPUT_DIR}/screenshot_som_{screenshot_uuid}.png")
92
+
93
+ start = time.time()
94
+ if "gpt" in self.model or "o1" in self.model or "o3-mini" in self.model:
95
+ vlm_response, token_usage = run_oai_interleaved(
96
+ messages=planner_messages,
97
+ system=system,
98
+ model_name=self.model,
99
+ api_key=self.api_key,
100
+ max_tokens=self.max_tokens,
101
+ provider_base_url="https://api.openai.com/v1",
102
+ temperature=0,
103
+ )
104
+ print(f"oai token usage: {token_usage}")
105
+ self.total_token_usage += token_usage
106
+ if 'gpt' in self.model:
107
+ self.total_cost += (token_usage * 2.5 / 1000000) # https://openai.com/api/pricing/
108
+ elif 'o1' in self.model:
109
+ self.total_cost += (token_usage * 15 / 1000000) # https://openai.com/api/pricing/
110
+ elif 'o3-mini' in self.model:
111
+ self.total_cost += (token_usage * 1.1 / 1000000) # https://openai.com/api/pricing/
112
+ elif "r1" in self.model:
113
+ vlm_response, token_usage = run_groq_interleaved(
114
+ messages=planner_messages,
115
+ system=system,
116
+ model_name=self.model,
117
+ api_key=self.api_key,
118
+ max_tokens=self.max_tokens,
119
+ )
120
+ print(f"groq token usage: {token_usage}")
121
+ self.total_token_usage += token_usage
122
+ self.total_cost += (token_usage * 0.99 / 1000000)
123
+ elif "qwen" in self.model:
124
+ vlm_response, token_usage = run_oai_interleaved(
125
+ messages=planner_messages,
126
+ system=system,
127
+ model_name=self.model,
128
+ api_key=self.api_key,
129
+ max_tokens=min(2048, self.max_tokens),
130
+ provider_base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
131
+ temperature=0,
132
+ )
133
+ print(f"qwen token usage: {token_usage}")
134
+ self.total_token_usage += token_usage
135
+ self.total_cost += (token_usage * 2.2 / 1000000) # https://help.aliyun.com/zh/model-studio/getting-started/models?spm=a2c4g.11186623.0.0.74b04823CGnPv7#fe96cfb1a422a
136
+ else:
137
+ raise ValueError(f"Model {self.model} not supported")
138
+ latency_vlm = time.time() - start
139
+ self.output_callback(f"LLM: {latency_vlm:.2f}s, OmniParser: {latency_omniparser:.2f}s", sender="bot")
140
+
141
+ print(f"{vlm_response}")
142
+
143
+ if self.print_usage:
144
+ print(f"Total token so far: {self.total_token_usage}. Total cost so far: $USD{self.total_cost:.5f}")
145
+
146
+ vlm_response_json = extract_data(vlm_response, "json")
147
+ vlm_response_json = json.loads(vlm_response_json)
148
+
149
+ img_to_show_base64 = parsed_screen["som_image_base64"]
150
+ if "Box ID" in vlm_response_json:
151
+ try:
152
+ bbox = parsed_screen["parsed_content_list"][int(vlm_response_json["Box ID"])]["bbox"]
153
+ vlm_response_json["box_centroid_coordinate"] = [int((bbox[0] + bbox[2]) / 2 * screen_width), int((bbox[1] + bbox[3]) / 2 * screen_height)]
154
+ img_to_show_data = base64.b64decode(img_to_show_base64)
155
+ img_to_show = Image.open(BytesIO(img_to_show_data))
156
+
157
+ draw = ImageDraw.Draw(img_to_show)
158
+ x, y = vlm_response_json["box_centroid_coordinate"]
159
+ radius = 10
160
+ draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill='red')
161
+ draw.ellipse((x - radius*3, y - radius*3, x + radius*3, y + radius*3), fill=None, outline='red', width=2)
162
+
163
+ buffered = BytesIO()
164
+ img_to_show.save(buffered, format="PNG")
165
+ img_to_show_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
166
+ except:
167
+ print(f"Error parsing: {vlm_response_json}")
168
+ pass
169
+ self.output_callback(f'<img src="data:image/png;base64,{img_to_show_base64}">', sender="bot")
170
+ self.output_callback(
171
+ f'<details>'
172
+ f' <summary>Parsed Screen elemetns by OmniParser</summary>'
173
+ f' <pre>{screen_info}</pre>'
174
+ f'</details>',
175
+ sender="bot"
176
+ )
177
+ vlm_plan_str = ""
178
+ for key, value in vlm_response_json.items():
179
+ if key == "Reasoning":
180
+ vlm_plan_str += f'{value}'
181
+ else:
182
+ vlm_plan_str += f'\n{key}: {value}'
183
+
184
+ # construct the response so that anthropicExcutor can execute the tool
185
+ response_content = [BetaTextBlock(text=vlm_plan_str, type='text')]
186
+ if 'box_centroid_coordinate' in vlm_response_json:
187
+ move_cursor_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
188
+ input={'action': 'mouse_move', 'coordinate': vlm_response_json["box_centroid_coordinate"]},
189
+ name='computer', type='tool_use')
190
+ response_content.append(move_cursor_block)
191
+
192
+ if vlm_response_json["Next Action"] == "None":
193
+ print("Task paused/completed.")
194
+ elif vlm_response_json["Next Action"] == "type":
195
+ sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
196
+ input={'action': vlm_response_json["Next Action"], 'text': vlm_response_json["value"]},
197
+ name='computer', type='tool_use')
198
+ response_content.append(sim_content_block)
199
+ else:
200
+ sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
201
+ input={'action': vlm_response_json["Next Action"]},
202
+ name='computer', type='tool_use')
203
+ response_content.append(sim_content_block)
204
+ response_message = BetaMessage(id=f'toolu_{uuid.uuid4()}', content=response_content, model='', role='assistant', type='message', stop_reason='tool_use', usage=BetaUsage(input_tokens=0, output_tokens=0))
205
+ return response_message, vlm_response_json
206
+
207
+ def _api_response_callback(self, response: APIResponse):
208
+ self.api_response_callback(response)
209
+
210
+ def _get_system_prompt(self, screen_info: str = ""):
211
+ main_section = f"""
212
+ You are using a Windows device.
213
+ You are able to use a mouse and keyboard to interact with the computer based on the given task and screenshot.
214
+ You can only interact with the desktop GUI (no terminal or application menu access).
215
+
216
+ You may be given some history plan and actions, this is the response from the previous loop.
217
+ You should carefully consider your plan base on the task, screenshot, and history actions.
218
+
219
+ Here is the list of all detected bounding boxes by IDs on the screen and their description:{screen_info}
220
+
221
+ Your available "Next Action" only include:
222
+ - type: types a string of text.
223
+ - left_click: move mouse to box id and left clicks.
224
+ - right_click: move mouse to box id and right clicks.
225
+ - double_click: move mouse to box id and double clicks.
226
+ - hover: move mouse to box id.
227
+ - scroll_up: scrolls the screen up to view previous content.
228
+ - scroll_down: scrolls the screen down, when the desired button is not visible, or you need to see more content.
229
+ - wait: waits for 1 second for the device to load or respond.
230
+
231
+ Based on the visual information from the screenshot image and the detected bounding boxes, please determine the next action, the Box ID you should operate on (if action is one of 'type', 'hover', 'scroll_up', 'scroll_down', 'wait', there should be no Box ID field), and the value (if the action is 'type') in order to complete the task.
232
+
233
+ Output format:
234
+ ```json
235
+ {{
236
+ "Reasoning": str, # describe what is in the current screen, taking into account the history, then describe your step-by-step thoughts on how to achieve the task, choose one action from available actions at a time.
237
+ "Next Action": "action_type, action description" | "None" # one action at a time, describe it in short and precisely.
238
+ "Box ID": n,
239
+ "value": "xxx" # only provide value field if the action is type, else don't include value key
240
+ }}
241
+ ```
242
+
243
+ One Example:
244
+ ```json
245
+ {{
246
+ "Reasoning": "The current screen shows google result of amazon, in previous action I have searched amazon on google. Then I need to click on the first search results to go to amazon.com.",
247
+ "Next Action": "left_click",
248
+ "Box ID": m
249
+ }}
250
+ ```
251
+
252
+ Another Example:
253
+ ```json
254
+ {{
255
+ "Reasoning": "The current screen shows the front page of amazon. There is no previous action. Therefore I need to type "Apple watch" in the search bar.",
256
+ "Next Action": "type",
257
+ "Box ID": n,
258
+ "value": "Apple watch"
259
+ }}
260
+ ```
261
+
262
+ Another Example:
263
+ ```json
264
+ {{
265
+ "Reasoning": "The current screen does not show 'submit' button, I need to scroll down to see if the button is available.",
266
+ "Next Action": "scroll_down",
267
+ }}
268
+ ```
269
+
270
+ IMPORTANT NOTES:
271
+ 1. You should only give a single action at a time.
272
+
273
+ """
274
+ thinking_model = "r1" in self.model
275
+ if not thinking_model:
276
+ main_section += """
277
+ 2. You should give an analysis to the current screen, and reflect on what has been done by looking at the history, then describe your step-by-step thoughts on how to achieve the task.
278
+
279
+ """
280
+ else:
281
+ main_section += """
282
+ 2. In <think> XML tags give an analysis to the current screen, and reflect on what has been done by looking at the history, then describe your step-by-step thoughts on how to achieve the task. In <output> XML tags put the next action prediction JSON.
283
+
284
+ """
285
+ main_section += """
286
+ 3. Attach the next action prediction in the "Next Action".
287
+ 4. You should not include other actions, such as keyboard shortcuts.
288
+ 5. When the task is completed, don't complete additional actions. You should say "Next Action": "None" in the json field.
289
+ 6. The tasks involve buying multiple products or navigating through multiple pages. You should break it into subgoals and complete each subgoal one by one in the order of the instructions.
290
+ 7. avoid choosing the same action/elements multiple times in a row, if it happens, reflect to yourself, what may have gone wrong, and predict a different action.
291
+ 8. If you are prompted with login information page or captcha page, or you think it need user's permission to do the next action, you should say "Next Action": "None" in the json field.
292
+ """
293
+
294
+ return main_section
295
+
296
+ def _remove_som_images(messages):
297
+ for msg in messages:
298
+ msg_content = msg["content"]
299
+ if isinstance(msg_content, list):
300
+ msg["content"] = [
301
+ cnt for cnt in msg_content
302
+ if not (isinstance(cnt, str) and 'som' in cnt and is_image_path(cnt))
303
+ ]
304
+
305
+
306
+ def _maybe_filter_to_n_most_recent_images(
307
+ messages: list[BetaMessageParam],
308
+ images_to_keep: int,
309
+ min_removal_threshold: int = 10,
310
+ ):
311
+ """
312
+ With the assumption that images are screenshots that are of diminishing value as
313
+ the conversation progresses, remove all but the final `images_to_keep` tool_result
314
+ images in place
315
+ """
316
+ if images_to_keep is None:
317
+ return messages
318
+
319
+ total_images = 0
320
+ for msg in messages:
321
+ for cnt in msg.get("content", []):
322
+ if isinstance(cnt, str) and is_image_path(cnt):
323
+ total_images += 1
324
+ elif isinstance(cnt, dict) and cnt.get("type") == "tool_result":
325
+ for content in cnt.get("content", []):
326
+ if isinstance(content, dict) and content.get("type") == "image":
327
+ total_images += 1
328
+
329
+ images_to_remove = total_images - images_to_keep
330
+
331
+ for msg in messages:
332
+ msg_content = msg["content"]
333
+ if isinstance(msg_content, list):
334
+ new_content = []
335
+ for cnt in msg_content:
336
+ # Remove images from SOM or screenshot as needed
337
+ if isinstance(cnt, str) and is_image_path(cnt):
338
+ if images_to_remove > 0:
339
+ images_to_remove -= 1
340
+ continue
341
+ # VLM shouldn't use anthropic screenshot tool so shouldn't have these but in case it does, remove as needed
342
+ elif isinstance(cnt, dict) and cnt.get("type") == "tool_result":
343
+ new_tool_result_content = []
344
+ for tool_result_entry in cnt.get("content", []):
345
+ if isinstance(tool_result_entry, dict) and tool_result_entry.get("type") == "image":
346
+ if images_to_remove > 0:
347
+ images_to_remove -= 1
348
+ continue
349
+ new_tool_result_content.append(tool_result_entry)
350
+ cnt["content"] = new_tool_result_content
351
+ # Append fixed content to current message's content list
352
+ new_content.append(cnt)
353
+ msg["content"] = new_content
OmniParser/omnitool/gradio/agent/vlm_agent_with_orchestrator.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from collections.abc import Callable
3
+ from typing import cast, Callable
4
+ import uuid
5
+ from PIL import Image, ImageDraw
6
+ import base64
7
+ from io import BytesIO
8
+ import copy
9
+ from pathlib import Path
10
+ from datetime import datetime
11
+ from anthropic import APIResponse
12
+ from anthropic.types import ToolResultBlockParam
13
+ from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock, BetaMessageParam, BetaUsage
14
+
15
+ from agent.llm_utils.oaiclient import run_oai_interleaved
16
+ from agent.llm_utils.groqclient import run_groq_interleaved
17
+ from agent.llm_utils.utils import is_image_path
18
+ import time
19
+ import re
20
+ import os
21
+ OUTPUT_DIR = "./tmp/outputs"
22
+ ORCHESTRATOR_LEDGER_PROMPT = """
23
+ Recall we are working on the following request:
24
+
25
+ {task}
26
+
27
+ To make progress on the request, please answer the following questions, including necessary reasoning:
28
+
29
+ - Is the request fully satisfied? (True if complete, or False if the original request has yet to be SUCCESSFULLY and FULLY addressed)
30
+ - Are we in a loop where we are repeating the same requests and / or getting the same responses as before? Loops can span multiple turns, and can include repeated actions like scrolling up or down more than a handful of times.
31
+ - Are we making forward progress? (True if just starting, or recent messages are adding value. False if recent messages show evidence of being stuck in a loop or if there is evidence of significant barriers to success such as the inability to read from a required file)
32
+ - What instruction or question would you give in order to complete the task?
33
+
34
+ Please output an answer in pure JSON format according to the following schema. The JSON object must be parsable as-is. DO NOT OUTPUT ANYTHING OTHER THAN JSON, AND DO NOT DEVIATE FROM THIS SCHEMA:
35
+
36
+ {{
37
+ "is_request_satisfied": {{
38
+ "reason": string,
39
+ "answer": boolean
40
+ }},
41
+ "is_in_loop": {{
42
+ "reason": string,
43
+ "answer": boolean
44
+ }},
45
+ "is_progress_being_made": {{
46
+ "reason": string,
47
+ "answer": boolean
48
+ }},
49
+ "instruction_or_question": {{
50
+ "reason": string,
51
+ "answer": string
52
+ }}
53
+ }}
54
+ """
55
+
56
+ def extract_data(input_string, data_type):
57
+ # Regular expression to extract content starting from '```python' until the end if there are no closing backticks
58
+ pattern = f"```{data_type}" + r"(.*?)(```|$)"
59
+ # Extract content
60
+ # re.DOTALL allows '.' to match newlines as well
61
+ matches = re.findall(pattern, input_string, re.DOTALL)
62
+ # Return the first match if exists, trimming whitespace and ignoring potential closing backticks
63
+ return matches[0][0].strip() if matches else input_string
64
+
65
+ class VLMOrchestratedAgent:
66
+ def __init__(
67
+ self,
68
+ model: str,
69
+ provider: str,
70
+ api_key: str,
71
+ output_callback: Callable,
72
+ api_response_callback: Callable,
73
+ max_tokens: int = 4096,
74
+ only_n_most_recent_images: int | None = None,
75
+ print_usage: bool = True,
76
+ save_folder: str = None,
77
+ ):
78
+ if model == "omniparser + gpt-4o" or model == "omniparser + gpt-4o-orchestrated":
79
+ self.model = "gpt-4o-2024-11-20"
80
+ elif model == "omniparser + R1" or model == "omniparser + R1-orchestrated":
81
+ self.model = "deepseek-r1-distill-llama-70b"
82
+ elif model == "omniparser + qwen2.5vl" or model == "omniparser + qwen2.5vl-orchestrated":
83
+ self.model = "qwen2.5-vl-72b-instruct"
84
+ elif model == "omniparser + o1" or model == "omniparser + o1-orchestrated":
85
+ self.model = "o1"
86
+ elif model == "omniparser + o3-mini" or model == "omniparser + o3-mini-orchestrated":
87
+ self.model = "o3-mini"
88
+ else:
89
+ raise ValueError(f"Model {model} not supported")
90
+
91
+
92
+ self.provider = provider
93
+ self.api_key = api_key
94
+ self.api_response_callback = api_response_callback
95
+ self.max_tokens = max_tokens
96
+ self.only_n_most_recent_images = only_n_most_recent_images
97
+ self.output_callback = output_callback
98
+ self.save_folder = save_folder
99
+
100
+ self.print_usage = print_usage
101
+ self.total_token_usage = 0
102
+ self.total_cost = 0
103
+ self.step_count = 0
104
+ self.plan, self.ledger = None, None
105
+
106
+ self.system = ''
107
+
108
+ def __call__(self, messages: list, parsed_screen: list[str, list, dict]):
109
+ if self.step_count == 0:
110
+ plan = self._initialize_task(messages)
111
+ self.output_callback(f'-- Plan: {plan} --', )
112
+ # update messages with the plan
113
+ messages.append({"role": "assistant", "content": plan})
114
+ else:
115
+ updated_ledger = self._update_ledger(messages)
116
+ self.output_callback(
117
+ f'<details>'
118
+ f' <summary><strong>Task Progress Ledger (click to expand)</strong></summary>'
119
+ f' <div style="padding: 10px; background-color: #f8f9fa; border-radius: 5px; margin-top: 5px;">'
120
+ f' <pre>{updated_ledger}</pre>'
121
+ f' </div>'
122
+ f'</details>',
123
+ )
124
+ # update messages with the ledger
125
+ messages.append({"role": "assistant", "content": updated_ledger})
126
+ self.ledger = updated_ledger
127
+
128
+ self.step_count += 1
129
+ # save the image to the output folder
130
+ with open(f"{self.save_folder}/screenshot_{self.step_count}.png", "wb") as f:
131
+ f.write(base64.b64decode(parsed_screen['original_screenshot_base64']))
132
+ with open(f"{self.save_folder}/som_screenshot_{self.step_count}.png", "wb") as f:
133
+ f.write(base64.b64decode(parsed_screen['som_image_base64']))
134
+
135
+ latency_omniparser = parsed_screen['latency']
136
+ screen_info = str(parsed_screen['screen_info'])
137
+ screenshot_uuid = parsed_screen['screenshot_uuid']
138
+ screen_width, screen_height = parsed_screen['width'], parsed_screen['height']
139
+
140
+ boxids_and_labels = parsed_screen["screen_info"]
141
+ system = self._get_system_prompt(boxids_and_labels)
142
+
143
+ # drop looping actions msg, byte image etc
144
+ planner_messages = messages
145
+ _remove_som_images(planner_messages)
146
+ _maybe_filter_to_n_most_recent_images(planner_messages, self.only_n_most_recent_images)
147
+
148
+ if isinstance(planner_messages[-1], dict):
149
+ if not isinstance(planner_messages[-1]["content"], list):
150
+ planner_messages[-1]["content"] = [planner_messages[-1]["content"]]
151
+ planner_messages[-1]["content"].append(f"{OUTPUT_DIR}/screenshot_{screenshot_uuid}.png")
152
+ planner_messages[-1]["content"].append(f"{OUTPUT_DIR}/screenshot_som_{screenshot_uuid}.png")
153
+
154
+ start = time.time()
155
+ if "gpt" in self.model or "o1" in self.model or "o3-mini" in self.model:
156
+ vlm_response, token_usage = run_oai_interleaved(
157
+ messages=planner_messages,
158
+ system=system,
159
+ model_name=self.model,
160
+ api_key=self.api_key,
161
+ max_tokens=self.max_tokens,
162
+ provider_base_url="https://api.openai.com/v1",
163
+ temperature=0,
164
+ )
165
+ print(f"oai token usage: {token_usage}")
166
+ self.total_token_usage += token_usage
167
+ if 'gpt' in self.model:
168
+ self.total_cost += (token_usage * 2.5 / 1000000) # https://openai.com/api/pricing/
169
+ elif 'o1' in self.model:
170
+ self.total_cost += (token_usage * 15 / 1000000) # https://openai.com/api/pricing/
171
+ elif 'o3-mini' in self.model:
172
+ self.total_cost += (token_usage * 1.1 / 1000000) # https://openai.com/api/pricing/
173
+ elif "r1" in self.model:
174
+ vlm_response, token_usage = run_groq_interleaved(
175
+ messages=planner_messages,
176
+ system=system,
177
+ model_name=self.model,
178
+ api_key=self.api_key,
179
+ max_tokens=self.max_tokens,
180
+ )
181
+ print(f"groq token usage: {token_usage}")
182
+ self.total_token_usage += token_usage
183
+ self.total_cost += (token_usage * 0.99 / 1000000)
184
+ elif "qwen" in self.model:
185
+ vlm_response, token_usage = run_oai_interleaved(
186
+ messages=planner_messages,
187
+ system=system,
188
+ model_name=self.model,
189
+ api_key=self.api_key,
190
+ max_tokens=min(2048, self.max_tokens),
191
+ provider_base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
192
+ temperature=0,
193
+ )
194
+ print(f"qwen token usage: {token_usage}")
195
+ self.total_token_usage += token_usage
196
+ self.total_cost += (token_usage * 2.2 / 1000000) # https://help.aliyun.com/zh/model-studio/getting-started/models?spm=a2c4g.11186623.0.0.74b04823CGnPv7#fe96cfb1a422a
197
+ else:
198
+ raise ValueError(f"Model {self.model} not supported")
199
+ latency_vlm = time.time() - start
200
+
201
+ # Update step counter with both latencies
202
+ self.output_callback(f'<i>Step {self.step_count} | OmniParser: {latency_omniparser:.2f}s | LLM: {latency_vlm:.2f}s</i>', )
203
+
204
+ print(f"{vlm_response}")
205
+
206
+ if self.print_usage:
207
+ print(f"Total token so far: {self.total_token_usage}. Total cost so far: $USD{self.total_cost:.5f}")
208
+
209
+ vlm_response_json = extract_data(vlm_response, "json")
210
+ vlm_response_json = json.loads(vlm_response_json)
211
+
212
+ img_to_show_base64 = parsed_screen["som_image_base64"]
213
+ if "Box ID" in vlm_response_json:
214
+ try:
215
+ bbox = parsed_screen["parsed_content_list"][int(vlm_response_json["Box ID"])]["bbox"]
216
+ vlm_response_json["box_centroid_coordinate"] = [int((bbox[0] + bbox[2]) / 2 * screen_width), int((bbox[1] + bbox[3]) / 2 * screen_height)]
217
+ img_to_show_data = base64.b64decode(img_to_show_base64)
218
+ img_to_show = Image.open(BytesIO(img_to_show_data))
219
+
220
+ draw = ImageDraw.Draw(img_to_show)
221
+ x, y = vlm_response_json["box_centroid_coordinate"]
222
+ radius = 10
223
+ draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill='red')
224
+ draw.ellipse((x - radius*3, y - radius*3, x + radius*3, y + radius*3), fill=None, outline='red', width=2)
225
+
226
+ buffered = BytesIO()
227
+ img_to_show.save(buffered, format="PNG")
228
+ img_to_show_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
229
+ except:
230
+ print(f"Error parsing: {vlm_response_json}")
231
+ pass
232
+ self.output_callback(f'<img src="data:image/png;base64,{img_to_show_base64}">', )
233
+
234
+ # Display screen info in a collapsible dropdown
235
+ self.output_callback(
236
+ f'<details>'
237
+ f' <summary><strong>Parsed Screen Elements (click to expand)</strong></summary>'
238
+ f' <div style="padding: 10px; background-color: #f8f9fa; border-radius: 5px; margin-top: 5px;">'
239
+ f' <pre>{screen_info}</pre>'
240
+ f' </div>'
241
+ f'</details>',
242
+ )
243
+
244
+ vlm_plan_str = ""
245
+ for key, value in vlm_response_json.items():
246
+ if key == "Reasoning":
247
+ vlm_plan_str += f'{value}'
248
+ else:
249
+ vlm_plan_str += f'\n{key}: {value}'
250
+
251
+ # construct the response so that anthropicExcutor can execute the tool
252
+ response_content = [BetaTextBlock(text=vlm_plan_str, type='text')]
253
+ if 'box_centroid_coordinate' in vlm_response_json:
254
+ move_cursor_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
255
+ input={'action': 'mouse_move', 'coordinate': vlm_response_json["box_centroid_coordinate"]},
256
+ name='computer', type='tool_use')
257
+ response_content.append(move_cursor_block)
258
+
259
+ if vlm_response_json["Next Action"] == "None":
260
+ print("Task paused/completed.")
261
+ elif vlm_response_json["Next Action"] == "type":
262
+ sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
263
+ input={'action': vlm_response_json["Next Action"], 'text': vlm_response_json["value"]},
264
+ name='computer', type='tool_use')
265
+ response_content.append(sim_content_block)
266
+ else:
267
+ sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
268
+ input={'action': vlm_response_json["Next Action"]},
269
+ name='computer', type='tool_use')
270
+ response_content.append(sim_content_block)
271
+ response_message = BetaMessage(id=f'toolu_{uuid.uuid4()}', content=response_content, model='', role='assistant', type='message', stop_reason='tool_use', usage=BetaUsage(input_tokens=0, output_tokens=0))
272
+
273
+ # save the intermediate step trajectory to the save folder
274
+ step_trajectory = {
275
+ "screenshot_path": f"{self.save_folder}/screenshot_{self.step_count}.png",
276
+ "som_screenshot_path": f"{self.save_folder}/som_screenshot_{self.step_count}.png",
277
+ "screen_info": screen_info,
278
+ "latency_omniparser": latency_omniparser,
279
+ "latency_vlm": latency_vlm,
280
+ "vlm_response_json": vlm_response_json,
281
+ 'ledger': self.ledger,
282
+ }
283
+ with open(f"{self.save_folder}/trajectory.json", "a") as f:
284
+ f.write(json.dumps(step_trajectory))
285
+ f.write("\n")
286
+
287
+ return response_message, vlm_response_json
288
+
289
+ def _api_response_callback(self, response: APIResponse):
290
+ self.api_response_callback(response)
291
+
292
+ def _get_system_prompt(self, screen_info: str = ""):
293
+ main_section = f"""
294
+ You are using a Windows device.
295
+ You are able to use a mouse and keyboard to interact with the computer based on the given task and screenshot.
296
+ You can only interact with the desktop GUI (no terminal or application menu access).
297
+
298
+ You may be given some history plan and actions, this is the response from the previous loop.
299
+ You should carefully consider your plan base on the task, screenshot, and history actions.
300
+
301
+ Here is the list of all detected bounding boxes by IDs on the screen and their description:{screen_info}
302
+
303
+ Your available "Next Action" only include:
304
+ - type: types a string of text.
305
+ - left_click: move mouse to box id and left clicks.
306
+ - right_click: move mouse to box id and right clicks.
307
+ - double_click: move mouse to box id and double clicks.
308
+ - hover: move mouse to box id.
309
+ - scroll_up: scrolls the screen up to view previous content.
310
+ - scroll_down: scrolls the screen down, when the desired button is not visible, or you need to see more content.
311
+ - wait: waits for 1 second for the device to load or respond.
312
+
313
+ Based on the visual information from the screenshot image and the detected bounding boxes, please determine the next action, the Box ID you should operate on (if action is one of 'type', 'hover', 'scroll_up', 'scroll_down', 'wait', there should be no Box ID field), and the value (if the action is 'type') in order to complete the task.
314
+
315
+ Output format:
316
+ ```json
317
+ {{
318
+ "Reasoning": str, # describe what is in the current screen, taking into account the history, then describe your step-by-step thoughts on how to achieve the task, choose one action from available actions at a time.
319
+ "Next Action": "action_type, action description" | "None" # one action at a time, describe it in short and precisely.
320
+ "Box ID": n,
321
+ "value": "xxx" # only provide value field if the action is type, else don't include value key
322
+ }}
323
+ ```
324
+
325
+ One Example:
326
+ ```json
327
+ {{
328
+ "Reasoning": "The current screen shows google result of amazon, in previous action I have searched amazon on google. Then I need to click on the first search results to go to amazon.com.",
329
+ "Next Action": "left_click",
330
+ "Box ID": m
331
+ }}
332
+ ```
333
+
334
+ Another Example:
335
+ ```json
336
+ {{
337
+ "Reasoning": "The current screen shows the front page of amazon. There is no previous action. Therefore I need to type "Apple watch" in the search bar.",
338
+ "Next Action": "type",
339
+ "Box ID": n,
340
+ "value": "Apple watch"
341
+ }}
342
+ ```
343
+
344
+ Another Example:
345
+ ```json
346
+ {{
347
+ "Reasoning": "The current screen does not show 'submit' button, I need to scroll down to see if the button is available.",
348
+ "Next Action": "scroll_down",
349
+ }}
350
+ ```
351
+
352
+ IMPORTANT NOTES:
353
+ 1. You should only give a single action at a time.
354
+
355
+ """
356
+ thinking_model = "r1" in self.model
357
+ if not thinking_model:
358
+ main_section += """
359
+ 2. You should give an analysis to the current screen, and reflect on what has been done by looking at the history, then describe your step-by-step thoughts on how to achieve the task.
360
+
361
+ """
362
+ else:
363
+ main_section += """
364
+ 2. In <think> XML tags give an analysis to the current screen, and reflect on what has been done by looking at the history, then describe your step-by-step thoughts on how to achieve the task. In <output> XML tags put the next action prediction JSON.
365
+
366
+ """
367
+ main_section += """
368
+ 3. Attach the next action prediction in the "Next Action".
369
+ 4. You should not include other actions, such as keyboard shortcuts.
370
+ 5. When the task is completed, don't complete additional actions. You should say "Next Action": "None" in the json field.
371
+ 6. The tasks involve buying multiple products or navigating through multiple pages. You should break it into subgoals and complete each subgoal one by one in the order of the instructions.
372
+ 7. avoid choosing the same action/elements multiple times in a row, if it happens, reflect to yourself, what may have gone wrong, and predict a different action.
373
+ 8. If you are prompted with login information page or captcha page, or you think it need user's permission to do the next action, you should say "Next Action": "None" in the json field.
374
+ """
375
+
376
+ return main_section
377
+
378
+ def _initialize_task(self, messages: list):
379
+ self._task = messages[0]["content"]
380
+ # make a plan
381
+ plan_prompt = self._get_plan_prompt(self._task)
382
+ input_message = copy.deepcopy(messages)
383
+ input_message.append({"role": "user", "content": plan_prompt})
384
+ vlm_response, token_usage = run_oai_interleaved(
385
+ messages=input_message,
386
+ system="",
387
+ model_name=self.model,
388
+ api_key=self.api_key,
389
+ max_tokens=self.max_tokens,
390
+ provider_base_url="https://api.openai.com/v1",
391
+ temperature=0,
392
+ )
393
+ plan = extract_data(vlm_response, "json")
394
+
395
+ # Create a filename with timestamp
396
+ plan_filename = f"plan.json"
397
+ plan_path = os.path.join(self.save_folder, plan_filename)
398
+
399
+ # Save the plan to a file
400
+ try:
401
+ with open(plan_path, "w") as f:
402
+ f.write(plan)
403
+ print(f"Plan successfully saved to {plan_path}")
404
+ except Exception as e:
405
+ print(f"Error saving plan to {plan_path}: {str(e)}")
406
+
407
+ return plan
408
+
409
+ def _update_ledger(self, messages):
410
+ # tobe implemented
411
+ # update the ledger with the current task and plan
412
+ # return the updated ledger
413
+ update_ledger_prompt = ORCHESTRATOR_LEDGER_PROMPT.format(task=self._task)
414
+ input_message = copy.deepcopy(messages)
415
+ input_message.append({"role": "user", "content": update_ledger_prompt})
416
+ vlm_response, token_usage = run_oai_interleaved(
417
+ messages=input_message,
418
+ system="",
419
+ model_name=self.model,
420
+ api_key=self.api_key,
421
+ max_tokens=self.max_tokens,
422
+ provider_base_url="https://api.openai.com/v1",
423
+ temperature=0,
424
+ )
425
+ updated_ledger = extract_data(vlm_response, "json")
426
+ return updated_ledger
427
+
428
+ def _get_plan_prompt(self, task):
429
+ plan_prompt = f"""
430
+ please devise a short bullet-point plan for addressing the original user task: {task}
431
+ You should write your plan in a json dict, e.g:```json
432
+ {{
433
+ 'step 1': xxx,
434
+ 'step 2': xxxx,
435
+ ...
436
+ }}```
437
+ Now start your answer directly.
438
+ """
439
+ return plan_prompt
440
+
441
+ def _remove_som_images(messages):
442
+ for msg in messages:
443
+ msg_content = msg["content"]
444
+ if isinstance(msg_content, list):
445
+ msg["content"] = [
446
+ cnt for cnt in msg_content
447
+ if not (isinstance(cnt, str) and 'som' in cnt and is_image_path(cnt))
448
+ ]
449
+
450
+
451
+ def _maybe_filter_to_n_most_recent_images(
452
+ messages: list[BetaMessageParam],
453
+ images_to_keep: int,
454
+ min_removal_threshold: int = 10,
455
+ ):
456
+ """
457
+ With the assumption that images are screenshots that are of diminishing value as
458
+ the conversation progresses, remove all but the final `images_to_keep` tool_result
459
+ images in place
460
+ """
461
+ if images_to_keep is None:
462
+ return messages
463
+
464
+ total_images = 0
465
+ for msg in messages:
466
+ for cnt in msg.get("content", []):
467
+ if isinstance(cnt, str) and is_image_path(cnt):
468
+ total_images += 1
469
+ elif isinstance(cnt, dict) and cnt.get("type") == "tool_result":
470
+ for content in cnt.get("content", []):
471
+ if isinstance(content, dict) and content.get("type") == "image":
472
+ total_images += 1
473
+
474
+ images_to_remove = total_images - images_to_keep
475
+
476
+ for msg in messages:
477
+ msg_content = msg["content"]
478
+ if isinstance(msg_content, list):
479
+ new_content = []
480
+ for cnt in msg_content:
481
+ # Remove images from SOM or screenshot as needed
482
+ if isinstance(cnt, str) and is_image_path(cnt):
483
+ if images_to_remove > 0:
484
+ images_to_remove -= 1
485
+ continue
486
+ # VLM shouldn't use anthropic screenshot tool so shouldn't have these but in case it does, remove as needed
487
+ elif isinstance(cnt, dict) and cnt.get("type") == "tool_result":
488
+ new_tool_result_content = []
489
+ for tool_result_entry in cnt.get("content", []):
490
+ if isinstance(tool_result_entry, dict) and tool_result_entry.get("type") == "image":
491
+ if images_to_remove > 0:
492
+ images_to_remove -= 1
493
+ continue
494
+ new_tool_result_content.append(tool_result_entry)
495
+ cnt["content"] = new_tool_result_content
496
+ # Append fixed content to current message's content list
497
+ new_content.append(cnt)
498
+ msg["content"] = new_content
OmniParser/omnitool/gradio/app.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ python app.py --windows_host_url localhost:8006 --omniparser_server_url localhost:8000
3
+ """
4
+
5
+ import os
6
+ from datetime import datetime
7
+ from enum import StrEnum
8
+ from functools import partial
9
+ from pathlib import Path
10
+ from typing import cast
11
+ import argparse
12
+ import gradio as gr
13
+ from anthropic import APIResponse
14
+ from anthropic.types import TextBlock
15
+ from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
16
+ from anthropic.types.tool_use_block import ToolUseBlock
17
+ from loop import (
18
+ APIProvider,
19
+ sampling_loop_sync,
20
+ )
21
+ from tools import ToolResult
22
+ import requests
23
+ from requests.exceptions import RequestException
24
+ import base64
25
+
26
+ CONFIG_DIR = Path("~/.anthropic").expanduser()
27
+ API_KEY_FILE = CONFIG_DIR / "api_key"
28
+
29
+ INTRO_TEXT = '''
30
+ OmniParser lets you turn any vision-langauge model into an AI agent. We currently support **OpenAI (4o/o1/o3-mini), DeepSeek (R1), Qwen (2.5VL) or Anthropic Computer Use (Sonnet).**
31
+
32
+ Type a message and press submit to start OmniTool. Press stop to pause, and press the trash icon in the chat to clear the message history.
33
+ '''
34
+
35
+ def parse_arguments():
36
+
37
+ parser = argparse.ArgumentParser(description="Gradio App")
38
+ parser.add_argument("--windows_host_url", type=str, default='localhost:8006')
39
+ parser.add_argument("--omniparser_server_url", type=str, default="localhost:8000")
40
+ return parser.parse_args()
41
+ args = parse_arguments()
42
+
43
+
44
+ class Sender(StrEnum):
45
+ USER = "user"
46
+ BOT = "assistant"
47
+ TOOL = "tool"
48
+
49
+
50
+ def setup_state(state):
51
+ if "messages" not in state:
52
+ state["messages"] = []
53
+ if "model" not in state:
54
+ state["model"] = "omniparser + gpt-4o"
55
+ if "provider" not in state:
56
+ state["provider"] = "openai"
57
+ if "openai_api_key" not in state: # Fetch API keys from environment variables
58
+ state["openai_api_key"] = os.getenv("OPENAI_API_KEY", "")
59
+ if "anthropic_api_key" not in state:
60
+ state["anthropic_api_key"] = os.getenv("ANTHROPIC_API_KEY", "")
61
+ if "api_key" not in state:
62
+ state["api_key"] = ""
63
+ if "auth_validated" not in state:
64
+ state["auth_validated"] = False
65
+ if "responses" not in state:
66
+ state["responses"] = {}
67
+ if "tools" not in state:
68
+ state["tools"] = {}
69
+ if "only_n_most_recent_images" not in state:
70
+ state["only_n_most_recent_images"] = 2
71
+ if 'chatbot_messages' not in state:
72
+ state['chatbot_messages'] = []
73
+ if 'stop' not in state:
74
+ state['stop'] = False
75
+
76
+ async def main(state):
77
+ """Render loop for Gradio"""
78
+ setup_state(state)
79
+ return "Setup completed"
80
+
81
+ def validate_auth(provider: APIProvider, api_key: str | None):
82
+ if provider == APIProvider.ANTHROPIC:
83
+ if not api_key:
84
+ return "Enter your Anthropic API key to continue."
85
+ if provider == APIProvider.BEDROCK:
86
+ import boto3
87
+
88
+ if not boto3.Session().get_credentials():
89
+ return "You must have AWS credentials set up to use the Bedrock API."
90
+ if provider == APIProvider.VERTEX:
91
+ import google.auth
92
+ from google.auth.exceptions import DefaultCredentialsError
93
+
94
+ if not os.environ.get("CLOUD_ML_REGION"):
95
+ return "Set the CLOUD_ML_REGION environment variable to use the Vertex API."
96
+ try:
97
+ google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
98
+ except DefaultCredentialsError:
99
+ return "Your google cloud credentials are not set up correctly."
100
+
101
+ def load_from_storage(filename: str) -> str | None:
102
+ """Load data from a file in the storage directory."""
103
+ try:
104
+ file_path = CONFIG_DIR / filename
105
+ if file_path.exists():
106
+ data = file_path.read_text().strip()
107
+ if data:
108
+ return data
109
+ except Exception as e:
110
+ print(f"Debug: Error loading {filename}: {e}")
111
+ return None
112
+
113
+ def save_to_storage(filename: str, data: str) -> None:
114
+ """Save data to a file in the storage directory."""
115
+ try:
116
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
117
+ file_path = CONFIG_DIR / filename
118
+ file_path.write_text(data)
119
+ # Ensure only user can read/write the file
120
+ file_path.chmod(0o600)
121
+ except Exception as e:
122
+ print(f"Debug: Error saving {filename}: {e}")
123
+
124
+ def _api_response_callback(response: APIResponse[BetaMessage], response_state: dict):
125
+ response_id = datetime.now().isoformat()
126
+ response_state[response_id] = response
127
+
128
+ def _tool_output_callback(tool_output: ToolResult, tool_id: str, tool_state: dict):
129
+ tool_state[tool_id] = tool_output
130
+
131
+ def chatbot_output_callback(message, chatbot_state, hide_images=False, sender="bot"):
132
+ def _render_message(message: str | BetaTextBlock | BetaToolUseBlock | ToolResult, hide_images=False):
133
+
134
+ print(f"_render_message: {str(message)[:100]}")
135
+
136
+ if isinstance(message, str):
137
+ return message
138
+
139
+ is_tool_result = not isinstance(message, str) and (
140
+ isinstance(message, ToolResult)
141
+ or message.__class__.__name__ == "ToolResult"
142
+ )
143
+ if not message or (
144
+ is_tool_result
145
+ and hide_images
146
+ and not hasattr(message, "error")
147
+ and not hasattr(message, "output")
148
+ ): # return None if hide_images is True
149
+ return
150
+ # render tool result
151
+ if is_tool_result:
152
+ message = cast(ToolResult, message)
153
+ if message.output:
154
+ return message.output
155
+ if message.error:
156
+ return f"Error: {message.error}"
157
+ if message.base64_image and not hide_images:
158
+ # somehow can't display via gr.Image
159
+ # image_data = base64.b64decode(message.base64_image)
160
+ # return gr.Image(value=Image.open(io.BytesIO(image_data)))
161
+ return f'<img src="data:image/png;base64,{message.base64_image}">'
162
+
163
+ elif isinstance(message, BetaTextBlock) or isinstance(message, TextBlock):
164
+ return f"Analysis: {message.text}"
165
+ elif isinstance(message, BetaToolUseBlock) or isinstance(message, ToolUseBlock):
166
+ # return f"Tool Use: {message.name}\nInput: {message.input}"
167
+ return f"Next I will perform the following action: {message.input}"
168
+ else:
169
+ return message
170
+
171
+ def _truncate_string(s, max_length=500):
172
+ """Truncate long strings for concise printing."""
173
+ if isinstance(s, str) and len(s) > max_length:
174
+ return s[:max_length] + "..."
175
+ return s
176
+ # processing Anthropic messages
177
+ message = _render_message(message, hide_images)
178
+
179
+ if sender == "bot":
180
+ chatbot_state.append((None, message))
181
+ else:
182
+ chatbot_state.append((message, None))
183
+
184
+ # Create a concise version of the chatbot state for printing
185
+ concise_state = [(_truncate_string(user_msg), _truncate_string(bot_msg))
186
+ for user_msg, bot_msg in chatbot_state]
187
+ # print(f"chatbot_output_callback chatbot_state: {concise_state} (truncated)")
188
+
189
+ def valid_params(user_input, state):
190
+ """Validate all requirements and return a list of error messages."""
191
+ errors = []
192
+
193
+ for server_name, url in [('Windows Host', 'localhost:5000'), ('OmniParser Server', args.omniparser_server_url)]:
194
+ try:
195
+ url = f'http://{url}/probe'
196
+ response = requests.get(url, timeout=3)
197
+ if response.status_code != 200:
198
+ errors.append(f"{server_name} is not responding")
199
+ except RequestException as e:
200
+ errors.append(f"{server_name} is not responding")
201
+
202
+ if not state["api_key"].strip():
203
+ errors.append("LLM API Key is not set")
204
+
205
+ if not user_input:
206
+ errors.append("no computer use request provided")
207
+
208
+ return errors
209
+
210
+ def process_input(user_input, state):
211
+ # Reset the stop flag
212
+ if state["stop"]:
213
+ state["stop"] = False
214
+
215
+ errors = valid_params(user_input, state)
216
+ if errors:
217
+ raise gr.Error("Validation errors: " + ", ".join(errors))
218
+
219
+ # Append the user message to state["messages"]
220
+ state["messages"].append(
221
+ {
222
+ "role": Sender.USER,
223
+ "content": [TextBlock(type="text", text=user_input)],
224
+ }
225
+ )
226
+
227
+ # Append the user's message to chatbot_messages with None for the assistant's reply
228
+ state['chatbot_messages'].append((user_input, None))
229
+ yield state['chatbot_messages'] # Yield to update the chatbot UI with the user's message
230
+
231
+ print("state")
232
+ print(state)
233
+
234
+ # Run sampling_loop_sync with the chatbot_output_callback
235
+ for loop_msg in sampling_loop_sync(
236
+ model=state["model"],
237
+ provider=state["provider"],
238
+ messages=state["messages"],
239
+ output_callback=partial(chatbot_output_callback, chatbot_state=state['chatbot_messages'], hide_images=False),
240
+ tool_output_callback=partial(_tool_output_callback, tool_state=state["tools"]),
241
+ api_response_callback=partial(_api_response_callback, response_state=state["responses"]),
242
+ api_key=state["api_key"],
243
+ only_n_most_recent_images=state["only_n_most_recent_images"],
244
+ max_tokens=16384,
245
+ omniparser_url=args.omniparser_server_url
246
+ ):
247
+ if loop_msg is None or state.get("stop"):
248
+ yield state['chatbot_messages']
249
+ print("End of task. Close the loop.")
250
+ break
251
+
252
+ yield state['chatbot_messages'] # Yield the updated chatbot_messages to update the chatbot UI
253
+
254
+ def stop_app(state):
255
+ state["stop"] = True
256
+ return "App stopped"
257
+
258
+ def get_header_image_base64():
259
+ try:
260
+ # Get the absolute path to the image relative to this script
261
+ script_dir = Path(__file__).parent
262
+ image_path = script_dir.parent.parent / "imgs" / "header_bar_thin.png"
263
+
264
+ with open(image_path, "rb") as image_file:
265
+ encoded_string = base64.b64encode(image_file.read()).decode()
266
+ return f'data:image/png;base64,{encoded_string}'
267
+ except Exception as e:
268
+ print(f"Failed to load header image: {e}")
269
+ return None
270
+
271
+ with gr.Blocks(theme=gr.themes.Default()) as demo:
272
+ gr.HTML("""
273
+ <style>
274
+ .no-padding {
275
+ padding: 0 !important;
276
+ }
277
+ .no-padding > div {
278
+ padding: 0 !important;
279
+ }
280
+ .markdown-text p {
281
+ font-size: 18px; /* Adjust the font size as needed */
282
+ }
283
+ </style>
284
+ """)
285
+ state = gr.State({})
286
+
287
+ setup_state(state.value)
288
+
289
+ header_image = get_header_image_base64()
290
+ if header_image:
291
+ gr.HTML(f'<img src="{header_image}" alt="OmniTool Header" width="100%">', elem_classes="no-padding")
292
+ gr.HTML('<h1 style="text-align: center; font-weight: normal;">Omni<span style="font-weight: bold;">Tool</span></h1>')
293
+ else:
294
+ gr.Markdown("# OmniTool")
295
+
296
+ if not os.getenv("HIDE_WARNING", False):
297
+ gr.Markdown(INTRO_TEXT, elem_classes="markdown-text")
298
+
299
+
300
+ with gr.Accordion("Settings", open=True):
301
+ with gr.Row():
302
+ with gr.Column():
303
+ model = gr.Dropdown(
304
+ label="Model",
305
+ 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"],
306
+ value="omniparser + gpt-4o",
307
+ interactive=True,
308
+ )
309
+ with gr.Column():
310
+ only_n_images = gr.Slider(
311
+ label="N most recent screenshots",
312
+ minimum=0,
313
+ maximum=10,
314
+ step=1,
315
+ value=2,
316
+ interactive=True
317
+ )
318
+ with gr.Row():
319
+ with gr.Column(1):
320
+ provider = gr.Dropdown(
321
+ label="API Provider",
322
+ choices=[option.value for option in APIProvider],
323
+ value="openai",
324
+ interactive=False,
325
+ )
326
+ with gr.Column(2):
327
+ api_key = gr.Textbox(
328
+ label="API Key",
329
+ type="password",
330
+ value=state.value.get("api_key", ""),
331
+ placeholder="Paste your API key here",
332
+ interactive=True,
333
+ )
334
+
335
+ with gr.Row():
336
+ with gr.Column(scale=8):
337
+ chat_input = gr.Textbox(show_label=False, placeholder="Type a message to send to Omniparser + X ...", container=False)
338
+ with gr.Column(scale=1, min_width=50):
339
+ submit_button = gr.Button(value="Send", variant="primary")
340
+ with gr.Column(scale=1, min_width=50):
341
+ stop_button = gr.Button(value="Stop", variant="secondary")
342
+
343
+ with gr.Row():
344
+ with gr.Column(scale=2):
345
+ chatbot = gr.Chatbot(label="Chatbot History", autoscroll=True, height=580)
346
+ with gr.Column(scale=3):
347
+ iframe = gr.HTML(
348
+ f'<iframe src="http://{args.windows_host_url}/vnc.html?view_only=1&autoconnect=1&resize=scale" width="100%" height="580" allow="fullscreen"></iframe>',
349
+ container=False,
350
+ elem_classes="no-padding"
351
+ )
352
+
353
+ def update_model(model_selection, state):
354
+ state["model"] = model_selection
355
+ print(f"Model updated to: {state['model']}")
356
+
357
+ if model_selection == "claude-3-5-sonnet-20241022":
358
+ provider_choices = [option.value for option in APIProvider if option.value != "openai"]
359
+ elif model_selection in set(["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini", "omniparser + gpt-4o-orchestrated", "omniparser + o1-orchestrated", "omniparser + o3-mini-orchestrated"]):
360
+ provider_choices = ["openai"]
361
+ elif model_selection == "omniparser + R1":
362
+ provider_choices = ["groq"]
363
+ elif model_selection == "omniparser + qwen2.5vl":
364
+ provider_choices = ["dashscope"]
365
+ else:
366
+ provider_choices = [option.value for option in APIProvider]
367
+ default_provider_value = provider_choices[0]
368
+
369
+ provider_interactive = len(provider_choices) > 1
370
+ api_key_placeholder = f"{default_provider_value.title()} API Key"
371
+
372
+ # Update state
373
+ state["provider"] = default_provider_value
374
+ state["api_key"] = state.get(f"{default_provider_value}_api_key", "")
375
+
376
+ # Calls to update other components UI
377
+ provider_update = gr.update(
378
+ choices=provider_choices,
379
+ value=default_provider_value,
380
+ interactive=provider_interactive
381
+ )
382
+ api_key_update = gr.update(
383
+ placeholder=api_key_placeholder,
384
+ value=state["api_key"]
385
+ )
386
+
387
+ return provider_update, api_key_update
388
+
389
+ def update_only_n_images(only_n_images_value, state):
390
+ state["only_n_most_recent_images"] = only_n_images_value
391
+
392
+ def update_provider(provider_value, state):
393
+ # Update state
394
+ state["provider"] = provider_value
395
+ state["api_key"] = state.get(f"{provider_value}_api_key", "")
396
+
397
+ # Calls to update other components UI
398
+ api_key_update = gr.update(
399
+ placeholder=f"{provider_value.title()} API Key",
400
+ value=state["api_key"]
401
+ )
402
+ return api_key_update
403
+
404
+ def update_api_key(api_key_value, state):
405
+ state["api_key"] = api_key_value
406
+ state[f'{state["provider"]}_api_key'] = api_key_value
407
+
408
+ def clear_chat(state):
409
+ # Reset message-related state
410
+ state["messages"] = []
411
+ state["responses"] = {}
412
+ state["tools"] = {}
413
+ state['chatbot_messages'] = []
414
+ return state['chatbot_messages']
415
+
416
+ model.change(fn=update_model, inputs=[model, state], outputs=[provider, api_key])
417
+ only_n_images.change(fn=update_only_n_images, inputs=[only_n_images, state], outputs=None)
418
+ provider.change(fn=update_provider, inputs=[provider, state], outputs=api_key)
419
+ api_key.change(fn=update_api_key, inputs=[api_key, state], outputs=None)
420
+ chatbot.clear(fn=clear_chat, inputs=[state], outputs=[chatbot])
421
+
422
+ submit_button.click(process_input, [chat_input, state], chatbot)
423
+ stop_button.click(stop_app, [state], None)
424
+
425
+ if __name__ == "__main__":
426
+ demo.launch(server_name="0.0.0.0", server_port=7888)
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="0.0.0.0", server_port=7888)
OmniParser/omnitool/gradio/app_streamlit.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Streamlit implementation of the OmniTool frontend.
3
+ Usage: streamlit run app_streamlit.py -- --windows_host_url localhost:8006 --omniparser_server_url localhost:8000
4
+ """
5
+
6
+ import os
7
+ import io
8
+ import shutil
9
+ import mimetypes
10
+ import argparse
11
+ import base64
12
+ from datetime import datetime
13
+ from pathlib import Path
14
+ from typing import cast
15
+ from enum import StrEnum
16
+ import streamlit as st
17
+ from anthropic import APIResponse
18
+ from anthropic.types import TextBlock
19
+ from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
20
+ from anthropic.types.tool_use_block import ToolUseBlock
21
+ import requests
22
+ from requests.exceptions import RequestException
23
+
24
+ from loop import (
25
+ APIProvider,
26
+ sampling_loop_sync,
27
+ )
28
+ from tools import ToolResult
29
+
30
+ # Constants and configurations
31
+ CONFIG_DIR = Path("~/.anthropic").expanduser()
32
+ API_KEY_FILE = CONFIG_DIR / "api_key"
33
+ UPLOAD_FOLDER = Path("./uploads").absolute()
34
+ UPLOAD_FOLDER.mkdir(parents=True, exist_ok=True)
35
+
36
+ class Sender(StrEnum):
37
+ USER = "user"
38
+ BOT = "assistant"
39
+ TOOL = "tool"
40
+
41
+ def parse_arguments():
42
+ parser = argparse.ArgumentParser(description="Streamlit App")
43
+ parser.add_argument("--windows_host_url", type=str, default='localhost:8006')
44
+ parser.add_argument("--omniparser_server_url", type=str, default="localhost:8000")
45
+ parser.add_argument("--upload_folder", type=str, default="./uploads")
46
+ return parser.parse_known_args()[0]
47
+
48
+ def initialize_session_state():
49
+ """Initialize session state variables"""
50
+ if "messages" not in st.session_state:
51
+ st.session_state.messages = []
52
+ if "model" not in st.session_state:
53
+ st.session_state.model = "omniparser + gpt-4o-orchestrated"
54
+ if "provider" not in st.session_state:
55
+ st.session_state.provider = "openai"
56
+ if "api_key" not in st.session_state:
57
+ st.session_state.api_key = os.getenv("OPENAI_API_KEY", "")
58
+ if "anthropic_api_key" not in st.session_state:
59
+ st.session_state.anthropic_api_key = os.getenv("ANTHROPIC_API_KEY", "")
60
+ if "only_n_most_recent_images" not in st.session_state:
61
+ st.session_state.only_n_most_recent_images = 2
62
+ if "responses" not in st.session_state:
63
+ st.session_state.responses = {}
64
+ if "tools" not in st.session_state:
65
+ st.session_state.tools = {}
66
+ if "uploaded_files" not in st.session_state:
67
+ st.session_state.uploaded_files = []
68
+ if "selected_file" not in st.session_state:
69
+ st.session_state.selected_file = "None"
70
+ if "stop" not in st.session_state:
71
+ st.session_state.stop = False
72
+
73
+ def get_file_viewer_html(file_path=None, windows_host_url=None):
74
+ """Generate HTML to view a file based on its type"""
75
+ if not file_path:
76
+ # Return the VNC viewer iframe
77
+ return f'<iframe src="http://{windows_host_url}/vnc.html?view_only=1&autoconnect=1&resize=scale" width="100%" height="580" allow="fullscreen"></iframe>'
78
+
79
+ file_path = Path(file_path)
80
+ if not file_path.exists():
81
+ return f'<div class="error-message">File not found: {file_path.name}</div>'
82
+
83
+ mime_type, _ = mimetypes.guess_type(file_path)
84
+ file_type = mime_type.split('/')[0] if mime_type else 'unknown'
85
+ file_extension = file_path.suffix.lower()
86
+
87
+ if file_type == 'image':
88
+ with open(file_path, "rb") as image_file:
89
+ encoded_string = base64.b64encode(image_file.read()).decode()
90
+ 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>'
91
+
92
+ elif file_extension in ['.txt', '.py', '.js', '.html', '.css', '.json', '.md', '.csv'] or file_type == 'text':
93
+ try:
94
+ content = file_path.read_text(errors='replace')
95
+ content = content.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
96
+ return f'<div class="file-viewer"><h3>{file_path.name}</h3><pre style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow: auto; max-height: 500px; white-space: pre-wrap;"><code>{content}</code></pre></div>'
97
+ except UnicodeDecodeError:
98
+ return f'<div class="error-message">Cannot display binary file: {file_path.name}</div>'
99
+
100
+ else:
101
+ size_kb = file_path.stat().st_size / 1024
102
+ 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>'
103
+
104
+ def handle_file_upload(uploaded_files):
105
+ """Handle file uploads and store them in the upload directory"""
106
+ if uploaded_files:
107
+ for file in uploaded_files:
108
+ file_path = UPLOAD_FOLDER / file.name
109
+ with open(file_path, "wb") as f:
110
+ f.write(file.getvalue())
111
+ if str(file_path) not in st.session_state.uploaded_files:
112
+ st.session_state.uploaded_files.append(str(file_path))
113
+
114
+ def _api_response_callback(response: APIResponse[BetaMessage]):
115
+ response_id = datetime.now().isoformat()
116
+ st.session_state.responses[response_id] = response
117
+
118
+ def _tool_output_callback(tool_output: ToolResult, tool_id: str):
119
+ st.session_state.tools[tool_id] = tool_output
120
+
121
+ def chatbot_output_callback(message, hide_images=False):
122
+ def _render_message(message: str | BetaTextBlock | BetaToolUseBlock | ToolResult, hide_images=False):
123
+ if isinstance(message, str):
124
+ return message
125
+
126
+ is_tool_result = not isinstance(message, str) and (
127
+ isinstance(message, ToolResult)
128
+ or message.__class__.__name__ == "ToolResult"
129
+ )
130
+
131
+ if is_tool_result:
132
+ message = cast(ToolResult, message)
133
+ if message.output:
134
+ return message.output
135
+ if message.error:
136
+ return f"Error: {message.error}"
137
+ if message.base64_image and not hide_images:
138
+ return f'<img src="data:image/png;base64,{message.base64_image}">'
139
+
140
+ elif isinstance(message, (BetaTextBlock, TextBlock)):
141
+ return f"Next step Reasoning: {message.text}"
142
+
143
+ elif isinstance(message, (BetaToolUseBlock, ToolUseBlock)):
144
+ return None
145
+
146
+ return message
147
+
148
+ rendered_message = _render_message(message, hide_images)
149
+ if rendered_message:
150
+ st.session_state.messages.append({"role": "assistant", "content": rendered_message})
151
+
152
+ def main():
153
+ args = parse_arguments()
154
+ initialize_session_state()
155
+
156
+ # Page configuration
157
+ st.set_page_config(
158
+ page_title="OmniTool",
159
+ page_icon="🤖",
160
+ layout="wide"
161
+ )
162
+
163
+ # Custom CSS
164
+ st.markdown("""
165
+ <style>
166
+ .stApp {
167
+ max-width: 100%;
168
+ padding: 1rem;
169
+ }
170
+ .chat-container {
171
+ height: calc(100vh - 200px);
172
+ overflow-y: auto;
173
+ position: relative;
174
+ }
175
+ .viewer-container {
176
+ height: calc(100vh - 200px);
177
+ overflow-y: auto;
178
+ }
179
+ .chat-input-container {
180
+ display: flex;
181
+ align-items: flex-end;
182
+ }
183
+ .icon-button {
184
+ border: none;
185
+ background: none;
186
+ cursor: pointer;
187
+ padding: 0.5rem;
188
+ border-radius: 50%;
189
+ transition: background-color 0.3s;
190
+ }
191
+ .icon-button:hover {
192
+ background-color: #f0f0f0;
193
+ }
194
+ .stButton button {
195
+ border-radius: 50%;
196
+ width: 40px;
197
+ height: 40px;
198
+ padding: 0;
199
+ display: flex;
200
+ align-items: center;
201
+ justify-content: center;
202
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
203
+ }
204
+ /* Custom button styles */
205
+ .send-btn {
206
+ background-color: #000 !important;
207
+ color: white !important;
208
+ }
209
+ .stop-btn {
210
+ background-color: #f8f9fa !important;
211
+ color: #d9534f !important;
212
+ border: 1px solid #d9534f !important;
213
+ }
214
+ .upload-btn {
215
+ background-color: #f8f9fa !important;
216
+ color: #0275d8 !important;
217
+ border: 1px solid #0275d8 !important;
218
+ }
219
+ /* Hide the default button styling */
220
+ div[data-testid="stHorizontalBlock"] button[kind="secondary"] {
221
+ background-color: transparent;
222
+ border: none;
223
+ }
224
+ /* Share button positioning */
225
+ .share-button-container {
226
+ position: absolute;
227
+ top: 0;
228
+ right: 0;
229
+ z-index: 100;
230
+ }
231
+ /* Chat header with title and share button */
232
+ .chat-header {
233
+ display: flex;
234
+ justify-content: space-between;
235
+ align-items: center;
236
+ margin-bottom: 10px;
237
+ }
238
+ /* Input placeholder styling */
239
+ .stTextInput input::placeholder {
240
+ color: #6c757d;
241
+ font-style: italic;
242
+ }
243
+ </style>
244
+ """, unsafe_allow_html=True)
245
+
246
+ # Header
247
+ st.title("OmniTool")
248
+
249
+ # Sidebar with settings
250
+ with st.sidebar:
251
+ st.header("Settings")
252
+
253
+ # Model selection
254
+ model = st.selectbox(
255
+ "Model",
256
+ ["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini",
257
+ "omniparser + R1", "omniparser + qwen2.5vl", "claude-3-5-sonnet-20241022",
258
+ "omniparser + gpt-4o-orchestrated", "omniparser + o1-orchestrated",
259
+ "omniparser + o3-mini-orchestrated", "omniparser + R1-orchestrated",
260
+ "omniparser + qwen2.5vl-orchestrated"],
261
+ index=6
262
+ )
263
+ st.session_state.model = model
264
+
265
+ # API settings
266
+ api_key = st.text_input("API Key", value=st.session_state.api_key, type="password")
267
+ st.session_state.api_key = api_key
268
+
269
+ # Image settings
270
+ n_images = st.slider("N most recent screenshots", 0, 10, 2)
271
+ st.session_state.only_n_most_recent_images = n_images
272
+
273
+ # File viewer selection
274
+ file_options = ["None"]
275
+ if st.session_state.uploaded_files:
276
+ file_options.extend([Path(f).name for f in st.session_state.uploaded_files])
277
+
278
+ selected_file = st.selectbox(
279
+ "View File",
280
+ options=file_options,
281
+ format_func=lambda x: x
282
+ )
283
+ st.session_state.selected_file = selected_file
284
+
285
+ view_mode = st.radio("Display Mode", ["OmniTool Computer", "File Viewer"])
286
+
287
+ # Main content area with two columns
288
+ col1, col2 = st.columns([2, 3])
289
+
290
+ # Chat interface (left column)
291
+ with col1:
292
+ # Chat header with title and share button
293
+ col_header_1, col_header_2 = st.columns([3, 1])
294
+ with col_header_1:
295
+ st.markdown("### Chat")
296
+ with col_header_2:
297
+ share_button = st.button("📤 Share", key="share_btn", help="Share conversation")
298
+ # Apply custom styling with HTML
299
+ st.markdown("""
300
+ <style>
301
+ button[data-testid="share_btn"] {
302
+ background-color: #f8f9fa !important;
303
+ color: #0275d8 !important;
304
+ border: 1px solid #0275d8 !important;
305
+ border-radius: 4px !important;
306
+ width: auto !important;
307
+ height: auto !important;
308
+ padding: 2px 8px !important;
309
+ font-size: 0.8rem !important;
310
+ }
311
+ </style>
312
+ """, unsafe_allow_html=True)
313
+
314
+ # Share functionality
315
+ if share_button:
316
+ # Create a shareable text of the conversation
317
+ conversation_text = ""
318
+ for message in st.session_state.messages:
319
+ if message["role"] == "user":
320
+ conversation_text += f"User: {message['content']}\n\n"
321
+ else:
322
+ conversation_text += f"Assistant: {message['content']}\n\n"
323
+
324
+ # Create a download link
325
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
326
+ st.download_button(
327
+ label="Download Conversation",
328
+ data=conversation_text,
329
+ file_name=f"omnitool_conversation_{timestamp}.txt",
330
+ mime="text/plain",
331
+ key="download_conversation"
332
+ )
333
+
334
+ # Display chat messages
335
+ chat_container = st.container(height=450)
336
+ with chat_container:
337
+ for message in st.session_state.messages:
338
+ if message["role"] == "user":
339
+ st.markdown(f"**You:** {message['content']}")
340
+ else:
341
+ st.markdown(f"**Assistant:** {message['content']}", unsafe_allow_html=True)
342
+
343
+ # Chat input and buttons
344
+ user_input = st.text_input(
345
+ "Type your message:",
346
+ key="user_input",
347
+ label_visibility="collapsed",
348
+ placeholder="Send message to OmniTool..."
349
+ )
350
+
351
+ # Button row with icons
352
+ col1_1, col1_2, col1_3, col1_4 = st.columns([6, 1, 1, 1])
353
+
354
+ with col1_2:
355
+ # Send button with icon - using arrow up icon
356
+ send_button = st.button("⬆️", help="Send message", key="send_btn")
357
+ # Apply custom styling with HTML
358
+ st.markdown("""
359
+ <style>
360
+ button[data-testid="send_btn"] {
361
+ background-color: black !important;
362
+ color: white !important;
363
+ }
364
+ </style>
365
+ """, unsafe_allow_html=True)
366
+
367
+ with col1_3:
368
+ # Stop button with icon
369
+ stop_button = st.button("🛑", help="Stop processing", key="stop_btn")
370
+ # Apply custom styling with HTML
371
+ st.markdown("""
372
+ <style>
373
+ button[data-testid="stop_btn"] {
374
+ background-color: #f8f9fa !important;
375
+ color: #d9534f !important;
376
+ border: 1px solid #d9534f !important;
377
+ }
378
+ </style>
379
+ """, unsafe_allow_html=True)
380
+
381
+ with col1_4:
382
+ # File upload button with icon
383
+ upload_button = st.button("📎", help="Upload files", key="upload_btn")
384
+ # Apply custom styling with HTML
385
+ st.markdown("""
386
+ <style>
387
+ button[data-testid="upload_btn"] {
388
+ background-color: #f8f9fa !important;
389
+ color: #0275d8 !important;
390
+ border: 1px solid #0275d8 !important;
391
+ }
392
+ </style>
393
+ """, unsafe_allow_html=True)
394
+
395
+ # File upload area (hidden by default, shown when upload button is clicked)
396
+ if upload_button:
397
+ uploaded_files = st.file_uploader("Upload Files", accept_multiple_files=True, label_visibility="collapsed")
398
+ if uploaded_files:
399
+ handle_file_upload(uploaded_files)
400
+ st.success(f"Uploaded {len(uploaded_files)} file(s)")
401
+ # Update file options
402
+ file_options = ["None"]
403
+ if st.session_state.uploaded_files:
404
+ file_options.extend([Path(f).name for f in st.session_state.uploaded_files])
405
+ st.rerun()
406
+
407
+ # Process send button click
408
+ if send_button and user_input:
409
+ # Add user message to state
410
+ st.session_state.messages.append({"role": "user", "content": user_input})
411
+
412
+ # Process the message through sampling_loop_sync
413
+ for loop_msg in sampling_loop_sync(
414
+ model=st.session_state.model,
415
+ provider=st.session_state.provider,
416
+ messages=[{"role": "user", "content": [TextBlock(type="text", text=msg["content"])]} for msg in st.session_state.messages],
417
+ output_callback=chatbot_output_callback,
418
+ tool_output_callback=_tool_output_callback,
419
+ api_response_callback=_api_response_callback,
420
+ api_key=st.session_state.api_key,
421
+ only_n_most_recent_images=st.session_state.only_n_most_recent_images,
422
+ max_tokens=16384,
423
+ omniparser_url=args.omniparser_server_url,
424
+ save_folder=str(UPLOAD_FOLDER)
425
+ ):
426
+ if loop_msg is None or st.session_state.stop:
427
+ break
428
+ st.rerun()
429
+
430
+ # Process stop button click
431
+ if stop_button:
432
+ st.session_state.stop = True
433
+ st.info("Processing stopped")
434
+
435
+ # Viewer interface (right column)
436
+ with col2:
437
+ st.markdown("### Display")
438
+ if view_mode == "OmniTool Computer":
439
+ viewer_html = get_file_viewer_html(windows_host_url=args.windows_host_url)
440
+ st.components.v1.html(
441
+ viewer_html,
442
+ height=600,
443
+ scrolling=True
444
+ )
445
+ else: # File Viewer mode
446
+ if st.session_state.selected_file and st.session_state.selected_file != "None":
447
+ file_path = next((f for f in st.session_state.uploaded_files
448
+ if Path(f).name == st.session_state.selected_file), None)
449
+ if file_path:
450
+ viewer_html = get_file_viewer_html(file_path=file_path)
451
+ st.components.v1.html(
452
+ viewer_html,
453
+ height=600,
454
+ scrolling=True
455
+ )
456
+ else:
457
+ st.error(f"Could not find file: {st.session_state.selected_file}")
458
+ else:
459
+ st.info("Please select a file to view from the sidebar.")
460
+
461
+ # Debug information (temporary)
462
+ with st.expander("Debug Info"):
463
+ st.write("View Mode:", view_mode)
464
+ st.write("Selected File:", st.session_state.selected_file)
465
+ st.write("Available Files:", st.session_state.uploaded_files)
466
+ if view_mode == "File Viewer" and st.session_state.selected_file != "None":
467
+ st.write("File Path:", file_path if 'file_path' in locals() else "Not found")
468
+
469
+ if __name__ == "__main__":
470
+ main()
OmniParser/omnitool/gradio/executor/anthropic_executor.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from typing import Any, Dict, cast
3
+ from collections.abc import Callable
4
+ from anthropic.types.beta import (
5
+ BetaContentBlock,
6
+ BetaContentBlockParam,
7
+ BetaImageBlockParam,
8
+ BetaMessage,
9
+ BetaMessageParam,
10
+ BetaTextBlockParam,
11
+ BetaToolResultBlockParam,
12
+ )
13
+ from anthropic.types import TextBlock
14
+ from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
15
+ from tools import ComputerTool, ToolCollection, ToolResult
16
+
17
+
18
+ class AnthropicExecutor:
19
+ def __init__(
20
+ self,
21
+ output_callback: Callable[[BetaContentBlockParam], None],
22
+ tool_output_callback: Callable[[Any, str], None],
23
+ ):
24
+ self.tool_collection = ToolCollection(
25
+ ComputerTool()
26
+ )
27
+ self.output_callback = output_callback
28
+ self.tool_output_callback = tool_output_callback
29
+
30
+ def __call__(self, response: BetaMessage, messages: list[BetaMessageParam]):
31
+ new_message = {
32
+ "role": "assistant",
33
+ "content": cast(list[BetaContentBlockParam], response.content),
34
+ }
35
+ if new_message not in messages:
36
+ messages.append(new_message)
37
+ else:
38
+ print("new_message already in messages, there are duplicates.")
39
+
40
+ tool_result_content: list[BetaToolResultBlockParam] = []
41
+ for content_block in cast(list[BetaContentBlock], response.content):
42
+ self.output_callback(content_block, sender="bot")
43
+ # Execute the tool
44
+ if content_block.type == "tool_use":
45
+ # Run the asynchronous tool execution in a synchronous context
46
+ result = asyncio.run(self.tool_collection.run(
47
+ name=content_block.name,
48
+ tool_input=cast(dict[str, Any], content_block.input),
49
+ ))
50
+
51
+ self.output_callback(result, sender="bot")
52
+
53
+ tool_result_content.append(
54
+ _make_api_tool_result(result, content_block.id)
55
+ )
56
+ # self.tool_output_callback(result, content_block.id)
57
+
58
+ # Craft messages based on the content_block
59
+ # Note: to display the messages in the gradio, you should organize the messages in the following way (user message, bot message)
60
+
61
+ display_messages = _message_display_callback(messages)
62
+ # display_messages = []
63
+
64
+ # Send the messages to the gradio
65
+ for user_msg, bot_msg in display_messages:
66
+ # yield [user_msg, bot_msg], tool_result_content
67
+ yield [None, None], tool_result_content
68
+
69
+ if not tool_result_content:
70
+ return messages
71
+
72
+ return tool_result_content
73
+
74
+ def _message_display_callback(messages):
75
+ display_messages = []
76
+ for msg in messages:
77
+ try:
78
+ if isinstance(msg["content"][0], TextBlock):
79
+ display_messages.append((msg["content"][0].text, None)) # User message
80
+ elif isinstance(msg["content"][0], BetaTextBlock):
81
+ display_messages.append((None, msg["content"][0].text)) # Bot message
82
+ elif isinstance(msg["content"][0], BetaToolUseBlock):
83
+ display_messages.append((None, f"Tool Use: {msg['content'][0].name}\nInput: {msg['content'][0].input}")) # Bot message
84
+ elif isinstance(msg["content"][0], Dict) and msg["content"][0]["content"][-1]["type"] == "image":
85
+ display_messages.append((None, f'<img src="data:image/png;base64,{msg["content"][0]["content"][-1]["source"]["data"]}">')) # Bot message
86
+ else:
87
+ print(msg["content"][0])
88
+ except Exception as e:
89
+ print("error", e)
90
+ pass
91
+ return display_messages
92
+
93
+ def _make_api_tool_result(
94
+ result: ToolResult, tool_use_id: str
95
+ ) -> BetaToolResultBlockParam:
96
+ """Convert an agent ToolResult to an API ToolResultBlockParam."""
97
+ tool_result_content: list[BetaTextBlockParam | BetaImageBlockParam] | str = []
98
+ is_error = False
99
+ if result.error:
100
+ is_error = True
101
+ tool_result_content = _maybe_prepend_system_tool_result(result, result.error)
102
+ else:
103
+ if result.output:
104
+ tool_result_content.append(
105
+ {
106
+ "type": "text",
107
+ "text": _maybe_prepend_system_tool_result(result, result.output),
108
+ }
109
+ )
110
+ if result.base64_image:
111
+ tool_result_content.append(
112
+ {
113
+ "type": "image",
114
+ "source": {
115
+ "type": "base64",
116
+ "media_type": "image/png",
117
+ "data": result.base64_image,
118
+ },
119
+ }
120
+ )
121
+ return {
122
+ "type": "tool_result",
123
+ "content": tool_result_content,
124
+ "tool_use_id": tool_use_id,
125
+ "is_error": is_error,
126
+ }
127
+
128
+
129
+ def _maybe_prepend_system_tool_result(result: ToolResult, result_text: str):
130
+ if result.system:
131
+ result_text = f"<system>{result.system}</system>\n{result_text}"
132
+ return result_text
OmniParser/omnitool/gradio/loop.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Agentic sampling loop that calls the Anthropic API and local implenmentation of anthropic-defined computer use tools.
3
+ """
4
+ from collections.abc import Callable
5
+ from enum import StrEnum
6
+
7
+ from anthropic import APIResponse
8
+ from anthropic.types import (
9
+ TextBlock,
10
+ )
11
+ from anthropic.types.beta import (
12
+ BetaContentBlock,
13
+ BetaMessage,
14
+ BetaMessageParam
15
+ )
16
+ from tools import ToolResult
17
+
18
+ from agent.llm_utils.omniparserclient import OmniParserClient
19
+ from agent.anthropic_agent import AnthropicActor
20
+ from agent.vlm_agent import VLMAgent
21
+ from agent.vlm_agent_with_orchestrator import VLMOrchestratedAgent
22
+ from executor.anthropic_executor import AnthropicExecutor
23
+
24
+ BETA_FLAG = "computer-use-2024-10-22"
25
+
26
+ class APIProvider(StrEnum):
27
+ ANTHROPIC = "anthropic"
28
+ BEDROCK = "bedrock"
29
+ VERTEX = "vertex"
30
+ OPENAI = "openai"
31
+
32
+
33
+ PROVIDER_TO_DEFAULT_MODEL_NAME: dict[APIProvider, str] = {
34
+ APIProvider.ANTHROPIC: "claude-3-5-sonnet-20241022",
35
+ APIProvider.BEDROCK: "anthropic.claude-3-5-sonnet-20241022-v2:0",
36
+ APIProvider.VERTEX: "claude-3-5-sonnet-v2@20241022",
37
+ APIProvider.OPENAI: "gpt-4o",
38
+ }
39
+
40
+ def sampling_loop_sync(
41
+ *,
42
+ model: str,
43
+ provider: APIProvider | None,
44
+ messages: list[BetaMessageParam],
45
+ output_callback: Callable[[BetaContentBlock], None],
46
+ tool_output_callback: Callable[[ToolResult, str], None],
47
+ api_response_callback: Callable[[APIResponse[BetaMessage]], None],
48
+ api_key: str,
49
+ only_n_most_recent_images: int | None = 2,
50
+ max_tokens: int = 4096,
51
+ omniparser_url: str,
52
+ save_folder: str = "./uploads"
53
+ ):
54
+ """
55
+ Synchronous agentic sampling loop for the assistant/tool interaction of computer use.
56
+ """
57
+ print('in sampling_loop_sync, model:', model)
58
+ omniparser_client = OmniParserClient(url=f"http://{omniparser_url}/parse/")
59
+ if model == "claude-3-5-sonnet-20241022":
60
+ # Register Actor and Executor
61
+ actor = AnthropicActor(
62
+ model=model,
63
+ provider=provider,
64
+ api_key=api_key,
65
+ api_response_callback=api_response_callback,
66
+ max_tokens=max_tokens,
67
+ only_n_most_recent_images=only_n_most_recent_images
68
+ )
69
+ elif model in set(["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini", "omniparser + R1", "omniparser + qwen2.5vl"]):
70
+ actor = VLMAgent(
71
+ model=model,
72
+ provider=provider,
73
+ api_key=api_key,
74
+ api_response_callback=api_response_callback,
75
+ output_callback=output_callback,
76
+ max_tokens=max_tokens,
77
+ only_n_most_recent_images=only_n_most_recent_images
78
+ )
79
+ elif model in set(["omniparser + gpt-4o-orchestrated", "omniparser + o1-orchestrated", "omniparser + o3-mini-orchestrated", "omniparser + R1-orchestrated", "omniparser + qwen2.5vl-orchestrated"]):
80
+ actor = VLMOrchestratedAgent(
81
+ model=model,
82
+ provider=provider,
83
+ api_key=api_key,
84
+ api_response_callback=api_response_callback,
85
+ output_callback=output_callback,
86
+ max_tokens=max_tokens,
87
+ only_n_most_recent_images=only_n_most_recent_images,
88
+ save_folder=save_folder
89
+ )
90
+ else:
91
+ raise ValueError(f"Model {model} not supported")
92
+ executor = AnthropicExecutor(
93
+ output_callback=output_callback,
94
+ tool_output_callback=tool_output_callback,
95
+ )
96
+ print(f"Model Inited: {model}, Provider: {provider}")
97
+
98
+ tool_result_content = None
99
+
100
+ print(f"Start the message loop. User messages: {messages}")
101
+
102
+ if model == "claude-3-5-sonnet-20241022": # Anthropic loop
103
+ while True:
104
+ parsed_screen = omniparser_client() # parsed_screen: {"som_image_base64": dino_labled_img, "parsed_content_list": parsed_content_list, "screen_info"}
105
+ screen_info_block = TextBlock(text='Below is the structured accessibility information of the current UI screen, which includes text and icons you can operate on, take these information into account when you are making the prediction for the next action. Note you will still need to take screenshot to get the image: \n' + parsed_screen['screen_info'], type='text')
106
+ screen_info_dict = {"role": "user", "content": [screen_info_block]}
107
+ messages.append(screen_info_dict)
108
+ tools_use_needed = actor(messages=messages)
109
+
110
+ for message, tool_result_content in executor(tools_use_needed, messages):
111
+ yield message
112
+
113
+ if not tool_result_content:
114
+ return messages
115
+
116
+ messages.append({"content": tool_result_content, "role": "user"})
117
+
118
+ elif model in set(["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini", "omniparser + R1", "omniparser + qwen2.5vl", "omniparser + gpt-4o-orchestrated", "omniparser + o1-orchestrated", "omniparser + o3-mini-orchestrated", "omniparser + R1-orchestrated", "omniparser + qwen2.5vl-orchestrated"]):
119
+ while True:
120
+ parsed_screen = omniparser_client()
121
+ tools_use_needed, vlm_response_json = actor(messages=messages, parsed_screen=parsed_screen)
122
+
123
+ for message, tool_result_content in executor(tools_use_needed, messages):
124
+ yield message
125
+
126
+ if not tool_result_content:
127
+ return messages
OmniParser/omnitool/gradio/tools/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base import ToolResult
2
+ from .collection import ToolCollection
3
+ from .computer import ComputerTool
4
+ from .screen_capture import get_screenshot
5
+
6
+ __ALL__ = [
7
+ ComputerTool,
8
+ ToolCollection,
9
+ ToolResult,
10
+ get_screenshot,
11
+ ]
OmniParser/omnitool/gradio/tools/base.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABCMeta, abstractmethod
2
+ from dataclasses import dataclass, fields, replace
3
+ from typing import Any
4
+
5
+ from anthropic.types.beta import BetaToolUnionParam
6
+
7
+
8
+ class BaseAnthropicTool(metaclass=ABCMeta):
9
+ """Abstract base class for Anthropic-defined tools."""
10
+
11
+ @abstractmethod
12
+ def __call__(self, **kwargs) -> Any:
13
+ """Executes the tool with the given arguments."""
14
+ ...
15
+
16
+ @abstractmethod
17
+ def to_params(
18
+ self,
19
+ ) -> BetaToolUnionParam:
20
+ raise NotImplementedError
21
+
22
+
23
+ @dataclass(kw_only=True, frozen=True)
24
+ class ToolResult:
25
+ """Represents the result of a tool execution."""
26
+
27
+ output: str | None = None
28
+ error: str | None = None
29
+ base64_image: str | None = None
30
+ system: str | None = None
31
+
32
+ def __bool__(self):
33
+ return any(getattr(self, field.name) for field in fields(self))
34
+
35
+ def __add__(self, other: "ToolResult"):
36
+ def combine_fields(
37
+ field: str | None, other_field: str | None, concatenate: bool = True
38
+ ):
39
+ if field and other_field:
40
+ if concatenate:
41
+ return field + other_field
42
+ raise ValueError("Cannot combine tool results")
43
+ return field or other_field
44
+
45
+ return ToolResult(
46
+ output=combine_fields(self.output, other.output),
47
+ error=combine_fields(self.error, other.error),
48
+ base64_image=combine_fields(self.base64_image, other.base64_image, False),
49
+ system=combine_fields(self.system, other.system),
50
+ )
51
+
52
+ def replace(self, **kwargs):
53
+ """Returns a new ToolResult with the given fields replaced."""
54
+ return replace(self, **kwargs)
55
+
56
+
57
+ class ToolFailure(ToolResult):
58
+ """A ToolResult that represents a failure."""
59
+
60
+
61
+ class ToolError(Exception):
62
+ """Raised when a tool encounters an error."""
63
+
64
+ def __init__(self, message):
65
+ self.message = message
OmniParser/omnitool/gradio/tools/collection.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Collection classes for managing multiple tools."""
2
+
3
+ from typing import Any
4
+
5
+ from anthropic.types.beta import BetaToolUnionParam
6
+
7
+ from .base import (
8
+ BaseAnthropicTool,
9
+ ToolError,
10
+ ToolFailure,
11
+ ToolResult,
12
+ )
13
+
14
+
15
+ class ToolCollection:
16
+ """A collection of anthropic-defined tools."""
17
+
18
+ def __init__(self, *tools: BaseAnthropicTool):
19
+ self.tools = tools
20
+ self.tool_map = {tool.to_params()["name"]: tool for tool in tools}
21
+
22
+ def to_params(
23
+ self,
24
+ ) -> list[BetaToolUnionParam]:
25
+ return [tool.to_params() for tool in self.tools]
26
+
27
+ async def run(self, *, name: str, tool_input: dict[str, Any]) -> ToolResult:
28
+ tool = self.tool_map.get(name)
29
+ if not tool:
30
+ return ToolFailure(error=f"Tool {name} is invalid")
31
+ try:
32
+ return await tool(**tool_input)
33
+ except ToolError as e:
34
+ return ToolFailure(error=e.message)
OmniParser/omnitool/gradio/tools/computer.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import time
3
+ from enum import StrEnum
4
+ from typing import Literal, TypedDict
5
+
6
+ from PIL import Image
7
+
8
+ from anthropic.types.beta import BetaToolComputerUse20241022Param
9
+
10
+ from .base import BaseAnthropicTool, ToolError, ToolResult
11
+ from .screen_capture import get_screenshot
12
+ import requests
13
+ import re
14
+
15
+ OUTPUT_DIR = "./tmp/outputs"
16
+
17
+ TYPING_DELAY_MS = 12
18
+ TYPING_GROUP_SIZE = 50
19
+
20
+ Action = Literal[
21
+ "key",
22
+ "type",
23
+ "mouse_move",
24
+ "left_click",
25
+ "left_click_drag",
26
+ "right_click",
27
+ "middle_click",
28
+ "double_click",
29
+ "screenshot",
30
+ "cursor_position",
31
+ "hover",
32
+ "wait"
33
+ ]
34
+
35
+
36
+ class Resolution(TypedDict):
37
+ width: int
38
+ height: int
39
+
40
+
41
+ MAX_SCALING_TARGETS: dict[str, Resolution] = {
42
+ "XGA": Resolution(width=1024, height=768), # 4:3
43
+ "WXGA": Resolution(width=1280, height=800), # 16:10
44
+ "FWXGA": Resolution(width=1366, height=768), # ~16:9
45
+ }
46
+
47
+
48
+ class ScalingSource(StrEnum):
49
+ COMPUTER = "computer"
50
+ API = "api"
51
+
52
+
53
+ class ComputerToolOptions(TypedDict):
54
+ display_height_px: int
55
+ display_width_px: int
56
+ display_number: int | None
57
+
58
+
59
+ def chunks(s: str, chunk_size: int) -> list[str]:
60
+ return [s[i : i + chunk_size] for i in range(0, len(s), chunk_size)]
61
+
62
+ class ComputerTool(BaseAnthropicTool):
63
+ """
64
+ A tool that allows the agent to interact with the screen, keyboard, and mouse of the current computer.
65
+ Adapted for Windows using 'pyautogui'.
66
+ """
67
+
68
+ name: Literal["computer"] = "computer"
69
+ api_type: Literal["computer_20241022"] = "computer_20241022"
70
+ width: int
71
+ height: int
72
+ display_num: int | None
73
+
74
+ _screenshot_delay = 2.0
75
+ _scaling_enabled = True
76
+
77
+ @property
78
+ def options(self) -> ComputerToolOptions:
79
+ width, height = self.scale_coordinates(
80
+ ScalingSource.COMPUTER, self.width, self.height
81
+ )
82
+ return {
83
+ "display_width_px": width,
84
+ "display_height_px": height,
85
+ "display_number": self.display_num,
86
+ }
87
+
88
+ def to_params(self) -> BetaToolComputerUse20241022Param:
89
+ return {"name": self.name, "type": self.api_type, **self.options}
90
+
91
+ def __init__(self, is_scaling: bool = False):
92
+ super().__init__()
93
+
94
+ # Get screen width and height using Windows command
95
+ self.display_num = None
96
+ self.offset_x = 0
97
+ self.offset_y = 0
98
+ self.is_scaling = is_scaling
99
+ self.width, self.height = self.get_screen_size()
100
+ print(f"screen size: {self.width}, {self.height}")
101
+
102
+ self.key_conversion = {"Page_Down": "pagedown",
103
+ "Page_Up": "pageup",
104
+ "Super_L": "win",
105
+ "Escape": "esc"}
106
+
107
+
108
+ async def __call__(
109
+ self,
110
+ *,
111
+ action: Action,
112
+ text: str | None = None,
113
+ coordinate: tuple[int, int] | None = None,
114
+ **kwargs,
115
+ ):
116
+ print(f"action: {action}, text: {text}, coordinate: {coordinate}, is_scaling: {self.is_scaling}")
117
+ if action in ("mouse_move", "left_click_drag"):
118
+ if coordinate is None:
119
+ raise ToolError(f"coordinate is required for {action}")
120
+ if text is not None:
121
+ raise ToolError(f"text is not accepted for {action}")
122
+ if not isinstance(coordinate, (list, tuple)) or len(coordinate) != 2:
123
+ raise ToolError(f"{coordinate} must be a tuple of length 2")
124
+ # if not all(isinstance(i, int) and i >= 0 for i in coordinate):
125
+ if not all(isinstance(i, int) for i in coordinate):
126
+ raise ToolError(f"{coordinate} must be a tuple of non-negative ints")
127
+
128
+ if self.is_scaling:
129
+ x, y = self.scale_coordinates(
130
+ ScalingSource.API, coordinate[0], coordinate[1]
131
+ )
132
+ else:
133
+ x, y = coordinate
134
+
135
+ # print(f"scaled_coordinates: {x}, {y}")
136
+ # print(f"offset: {self.offset_x}, {self.offset_y}")
137
+
138
+ # x += self.offset_x # TODO - check if this is needed
139
+ # y += self.offset_y
140
+
141
+ print(f"mouse move to {x}, {y}")
142
+
143
+ if action == "mouse_move":
144
+ self.send_to_vm(f"pyautogui.moveTo({x}, {y})")
145
+ return ToolResult(output=f"Moved mouse to ({x}, {y})")
146
+ elif action == "left_click_drag":
147
+ current_x, current_y = self.send_to_vm("pyautogui.position()")
148
+ self.send_to_vm(f"pyautogui.dragTo({x}, {y}, duration=0.5)")
149
+ return ToolResult(output=f"Dragged mouse from ({current_x}, {current_y}) to ({x}, {y})")
150
+
151
+ if action in ("key", "type"):
152
+ if text is None:
153
+ raise ToolError(f"text is required for {action}")
154
+ if coordinate is not None:
155
+ raise ToolError(f"coordinate is not accepted for {action}")
156
+ if not isinstance(text, str):
157
+ raise ToolError(output=f"{text} must be a string")
158
+
159
+ if action == "key":
160
+ # Handle key combinations
161
+ keys = text.split('+')
162
+ for key in keys:
163
+ key = self.key_conversion.get(key.strip(), key.strip())
164
+ key = key.lower()
165
+ self.send_to_vm(f"pyautogui.keyDown('{key}')") # Press down each key
166
+ for key in reversed(keys):
167
+ key = self.key_conversion.get(key.strip(), key.strip())
168
+ key = key.lower()
169
+ self.send_to_vm(f"pyautogui.keyUp('{key}')") # Release each key in reverse order
170
+ return ToolResult(output=f"Pressed keys: {text}")
171
+
172
+ elif action == "type":
173
+ # default click before type TODO: check if this is needed
174
+ self.send_to_vm("pyautogui.click()")
175
+ self.send_to_vm(f"pyautogui.typewrite('{text}', interval={TYPING_DELAY_MS / 1000})")
176
+ self.send_to_vm("pyautogui.press('enter')")
177
+ screenshot_base64 = (await self.screenshot()).base64_image
178
+ return ToolResult(output=text, base64_image=screenshot_base64)
179
+
180
+ if action in (
181
+ "left_click",
182
+ "right_click",
183
+ "double_click",
184
+ "middle_click",
185
+ "screenshot",
186
+ "cursor_position",
187
+ "left_press",
188
+ ):
189
+ if text is not None:
190
+ raise ToolError(f"text is not accepted for {action}")
191
+ if coordinate is not None:
192
+ raise ToolError(f"coordinate is not accepted for {action}")
193
+
194
+ if action == "screenshot":
195
+ return await self.screenshot()
196
+ elif action == "cursor_position":
197
+ x, y = self.send_to_vm("pyautogui.position()")
198
+ x, y = self.scale_coordinates(ScalingSource.COMPUTER, x, y)
199
+ return ToolResult(output=f"X={x},Y={y}")
200
+ else:
201
+ if action == "left_click":
202
+ self.send_to_vm("pyautogui.click()")
203
+ elif action == "right_click":
204
+ self.send_to_vm("pyautogui.rightClick()")
205
+ elif action == "middle_click":
206
+ self.send_to_vm("pyautogui.middleClick()")
207
+ elif action == "double_click":
208
+ self.send_to_vm("pyautogui.doubleClick()")
209
+ elif action == "left_press":
210
+ self.send_to_vm("pyautogui.mouseDown()")
211
+ time.sleep(1)
212
+ self.send_to_vm("pyautogui.mouseUp()")
213
+ return ToolResult(output=f"Performed {action}")
214
+ if action in ("scroll_up", "scroll_down"):
215
+ if action == "scroll_up":
216
+ self.send_to_vm("pyautogui.scroll(100)")
217
+ elif action == "scroll_down":
218
+ self.send_to_vm("pyautogui.scroll(-100)")
219
+ return ToolResult(output=f"Performed {action}")
220
+ if action == "hover":
221
+ return ToolResult(output=f"Performed {action}")
222
+ if action == "wait":
223
+ time.sleep(1)
224
+ return ToolResult(output=f"Performed {action}")
225
+ raise ToolError(f"Invalid action: {action}")
226
+
227
+ def send_to_vm(self, action: str):
228
+ """
229
+ Executes a python command on the server. Only return tuple of x,y when action is "pyautogui.position()"
230
+ """
231
+ prefix = "import pyautogui; pyautogui.FAILSAFE = False;"
232
+ command_list = ["python", "-c", f"{prefix} {action}"]
233
+ parse = action == "pyautogui.position()"
234
+ if parse:
235
+ command_list[-1] = f"{prefix} print({action})"
236
+
237
+ try:
238
+ print(f"sending to vm: {command_list}")
239
+ response = requests.post(
240
+ f"http://localhost:5000/execute",
241
+ headers={'Content-Type': 'application/json'},
242
+ json={"command": command_list},
243
+ timeout=90
244
+ )
245
+ time.sleep(0.7) # avoid async error as actions take time to complete
246
+ print(f"action executed")
247
+ if response.status_code != 200:
248
+ raise ToolError(f"Failed to execute command. Status code: {response.status_code}")
249
+ if parse:
250
+ output = response.json()['output'].strip()
251
+ match = re.search(r'Point\(x=(\d+),\s*y=(\d+)\)', output)
252
+ if not match:
253
+ raise ToolError(f"Could not parse coordinates from output: {output}")
254
+ x, y = map(int, match.groups())
255
+ return x, y
256
+ except requests.exceptions.RequestException as e:
257
+ raise ToolError(f"An error occurred while trying to execute the command: {str(e)}")
258
+
259
+ async def screenshot(self):
260
+ if not hasattr(self, 'target_dimension'):
261
+ screenshot = self.padding_image(screenshot)
262
+ self.target_dimension = MAX_SCALING_TARGETS["WXGA"]
263
+ width, height = self.target_dimension["width"], self.target_dimension["height"]
264
+ screenshot, path = get_screenshot(resize=True, target_width=width, target_height=height)
265
+ time.sleep(0.7) # avoid async error as actions take time to complete
266
+ return ToolResult(base64_image=base64.b64encode(path.read_bytes()).decode())
267
+
268
+ def padding_image(self, screenshot):
269
+ """Pad the screenshot to 16:10 aspect ratio, when the aspect ratio is not 16:10."""
270
+ _, height = screenshot.size
271
+ new_width = height * 16 // 10
272
+
273
+ padding_image = Image.new("RGB", (new_width, height), (255, 255, 255))
274
+ # padding to top left
275
+ padding_image.paste(screenshot, (0, 0))
276
+ return padding_image
277
+
278
+ def scale_coordinates(self, source: ScalingSource, x: int, y: int):
279
+ """Scale coordinates to a target maximum resolution."""
280
+ if not self._scaling_enabled:
281
+ return x, y
282
+ ratio = self.width / self.height
283
+ target_dimension = None
284
+
285
+ for target_name, dimension in MAX_SCALING_TARGETS.items():
286
+ # allow some error in the aspect ratio - not ratios are exactly 16:9
287
+ if abs(dimension["width"] / dimension["height"] - ratio) < 0.02:
288
+ if dimension["width"] < self.width:
289
+ target_dimension = dimension
290
+ self.target_dimension = target_dimension
291
+ # print(f"target_dimension: {target_dimension}")
292
+ break
293
+
294
+ if target_dimension is None:
295
+ # TODO: currently we force the target to be WXGA (16:10), when it cannot find a match
296
+ target_dimension = MAX_SCALING_TARGETS["WXGA"]
297
+ self.target_dimension = MAX_SCALING_TARGETS["WXGA"]
298
+
299
+ # should be less than 1
300
+ x_scaling_factor = target_dimension["width"] / self.width
301
+ y_scaling_factor = target_dimension["height"] / self.height
302
+ if source == ScalingSource.API:
303
+ if x > self.width or y > self.height:
304
+ raise ToolError(f"Coordinates {x}, {y} are out of bounds")
305
+ # scale up
306
+ return round(x / x_scaling_factor), round(y / y_scaling_factor)
307
+ # scale down
308
+ return round(x * x_scaling_factor), round(y * y_scaling_factor)
309
+
310
+ def get_screen_size(self):
311
+ """Return width and height of the screen"""
312
+ try:
313
+ response = requests.post(
314
+ f"http://localhost:5000/execute",
315
+ headers={'Content-Type': 'application/json'},
316
+ json={"command": ["python", "-c", "import pyautogui; print(pyautogui.size())"]},
317
+ timeout=90
318
+ )
319
+ if response.status_code != 200:
320
+ raise ToolError(f"Failed to get screen size. Status code: {response.status_code}")
321
+
322
+ output = response.json()['output'].strip()
323
+ match = re.search(r'Size\(width=(\d+),\s*height=(\d+)\)', output)
324
+ if not match:
325
+ raise ToolError(f"Could not parse screen size from output: {output}")
326
+ width, height = map(int, match.groups())
327
+ return width, height
328
+ except requests.exceptions.RequestException as e:
329
+ raise ToolError(f"An error occurred while trying to get screen size: {str(e)}")