├── .gitignore
├── LICENSE
├── README.md
├── SECURITY.md
├── demo.ipynb
├── docs
└── Evaluation.md
├── eval
├── logs_sspro_omniv2.json
└── ss_pro_gpt4o_omniv2.py
├── gradio_demo.py
├── imgs
├── demo_image.jpg
├── demo_image_som.jpg
├── excel.png
├── google_page.png
├── gradioicon.png
├── header_bar.png
├── header_bar_thin.png
├── ios.png
├── logo.png
├── mobile.png
├── omni3.jpg
├── omniboxicon.png
├── omniparsericon.png
├── onenote.png
├── saved_image_demo.png
├── som_overlaid_omni.png
├── teams.png
├── windows.png
├── windows_home.png
├── windows_multitab.png
├── windows_vm.png
└── word.png
├── omnitool
├── gradio
│ ├── .gitignore
│ ├── __init__.py
│ ├── agent
│ │ ├── anthropic_agent.py
│ │ ├── llm_utils
│ │ │ ├── groqclient.py
│ │ │ ├── oaiclient.py
│ │ │ ├── omniparserclient.py
│ │ │ └── utils.py
│ │ ├── vlm_agent.py
│ │ └── vlm_agent_with_orchestrator.py
│ ├── app.py
│ ├── app_new.py
│ ├── app_streamlit.py
│ ├── executor
│ │ └── anthropic_executor.py
│ ├── loop.py
│ └── tools
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── collection.py
│ │ ├── computer.py
│ │ └── screen_capture.py
├── omnibox
│ ├── .gitignore
│ ├── Dockerfile
│ ├── compose.yml
│ ├── scripts
│ │ ├── manage_vm.ps1
│ │ └── manage_vm.sh
│ └── vm
│ │ ├── buildcontainer
│ │ ├── define.sh
│ │ ├── entry.sh
│ │ ├── install.sh
│ │ ├── power.sh
│ │ └── samba.sh
│ │ ├── win11def
│ │ └── win11x64-enterprise-eval.xml
│ │ ├── win11iso
│ │ └── README.md
│ │ └── win11setup
│ │ ├── firstboot
│ │ └── install.bat
│ │ └── setupscripts
│ │ ├── on-logon.ps1
│ │ ├── server
│ │ ├── cursor.png
│ │ ├── main.py
│ │ └── requirements.txt
│ │ ├── setup-tools.psm1
│ │ ├── setup.ps1
│ │ └── tools_config.json
├── omniparserserver
│ └── omniparserserver.py
└── readme.md
├── requirements.txt
└── util
├── __init__.py
├── box_annotator.py
├── omniparser.py
└── utils.py
/.gitignore:
--------------------------------------------------------------------------------
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/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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.
396 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OmniParser: Screen Parsing tool for Pure Vision Based GUI Agent
2 |
3 |
4 |
5 |
6 |
7 |
8 | [](https://arxiv.org/abs/2408.00203)
9 | [](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 |
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 | ```
81 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 |
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 |
42 |
--------------------------------------------------------------------------------
/docs/Evaluation.md:
--------------------------------------------------------------------------------
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.
5 |
--------------------------------------------------------------------------------
/gradio_demo.py:
--------------------------------------------------------------------------------
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 |
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=False, show_error=True, share=True)
96 | demo.launch(share=True, server_port=7861, server_name='0.0.0.0')
97 |
--------------------------------------------------------------------------------
/imgs/demo_image.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/demo_image.jpg
--------------------------------------------------------------------------------
/imgs/demo_image_som.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/demo_image_som.jpg
--------------------------------------------------------------------------------
/imgs/excel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/excel.png
--------------------------------------------------------------------------------
/imgs/google_page.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/google_page.png
--------------------------------------------------------------------------------
/imgs/gradioicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/gradioicon.png
--------------------------------------------------------------------------------
/imgs/header_bar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/header_bar.png
--------------------------------------------------------------------------------
/imgs/header_bar_thin.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/header_bar_thin.png
--------------------------------------------------------------------------------
/imgs/ios.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/ios.png
--------------------------------------------------------------------------------
/imgs/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/logo.png
--------------------------------------------------------------------------------
/imgs/mobile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/mobile.png
--------------------------------------------------------------------------------
/imgs/omni3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/omni3.jpg
--------------------------------------------------------------------------------
/imgs/omniboxicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/omniboxicon.png
--------------------------------------------------------------------------------
/imgs/omniparsericon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/omniparsericon.png
--------------------------------------------------------------------------------
/imgs/onenote.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/onenote.png
--------------------------------------------------------------------------------
/imgs/saved_image_demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/saved_image_demo.png
--------------------------------------------------------------------------------
/imgs/som_overlaid_omni.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/som_overlaid_omni.png
--------------------------------------------------------------------------------
/imgs/teams.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/teams.png
--------------------------------------------------------------------------------
/imgs/windows.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/windows.png
--------------------------------------------------------------------------------
/imgs/windows_home.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/windows_home.png
--------------------------------------------------------------------------------
/imgs/windows_multitab.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/windows_multitab.png
--------------------------------------------------------------------------------
/imgs/windows_vm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/windows_vm.png
--------------------------------------------------------------------------------
/imgs/word.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/imgs/word.png
--------------------------------------------------------------------------------
/omnitool/gradio/.gitignore:
--------------------------------------------------------------------------------
1 | tmp/
--------------------------------------------------------------------------------
/omnitool/gradio/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/OmniParser/5171b092483ab3e74ca50b9357e225f9f3571f18/omnitool/gradio/__init__.py
--------------------------------------------------------------------------------
/omnitool/gradio/agent/anthropic_agent.py:
--------------------------------------------------------------------------------
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"""
42 | * You are utilizing a Windows system with internet access.
43 | * The current date is {datetime.today().strftime('%A, %B %d, %Y')}.
44 |
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
--------------------------------------------------------------------------------
/omnitool/gradio/agent/llm_utils/groqclient.py:
--------------------------------------------------------------------------------
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('\n')[-1] if '' in response else response
52 | final_answer = final_answer.replace("", "")
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
--------------------------------------------------------------------------------
/omnitool/gradio/agent/llm_utils/oaiclient.py:
--------------------------------------------------------------------------------
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()
--------------------------------------------------------------------------------
/omnitool/gradio/agent/llm_utils/omniparserclient.py:
--------------------------------------------------------------------------------
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
--------------------------------------------------------------------------------
/omnitool/gradio/agent/llm_utils/utils.py:
--------------------------------------------------------------------------------
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")
--------------------------------------------------------------------------------
/omnitool/gradio/agent/vlm_agent.py:
--------------------------------------------------------------------------------
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'
', sender="bot")
170 | self.output_callback(
171 | f''
172 | f' Parsed Screen elemetns by OmniParser
'
173 | f' {screen_info}
'
174 | f' ',
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 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