omniparse-mcp: standalone OmniParser V2 parsing service + MCP shim

Self-contained: vendored util/ (CC BY 4.0, fixes noted in NOTICE), portable
setup.sh (venv + weights + Pascal lane), start.sh with real-parse readiness
gate, FastAPI service (bearer, serial GPU queue, LRU cache, OOM->503), MCP
stdio shim (MCPServer 2.x, token strip), hardware-honest README.
This commit is contained in:
plean committed 2026-11-18 02:29:08 +00:00
commit 2a4b1101e6
16 files changed
+2113

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
weights/
.venv/
__pycache__/
*.pyc
/config/
token
*.log
+25
View File
@@ -0,0 +1,25 @@
MIT License
Copyright (c) 2026 plean
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
NOTE: This license covers ONLY the files listed as "MIT (this project)" in
NOTICE. Files listed as "Vendored from microsoft/OmniParser" are licensed
under CC BY 4.0 - see LICENSE.upstream - and are subject to their own terms.
+395
View File
@@ -0,0 +1,395 @@
Attribution 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
+35
View File
@@ -0,0 +1,35 @@
omniparse-mcp — licensing overview
==================================
MIT (this project) — LICENSE:
omni_api/server.py
omni_api/engine.py
omni_api/mcp_server.py
setup.sh
start.sh
requirements.txt
Vendored from microsoft/OmniParser (https://github.com/microsoft/OmniParser)
— CC BY 4.0 (LICENSE.upstream), with modifications:
util/utils.py modified: lazy OCR-engine initialization; textless-
frame fixes (ocr_bbox None -> [] in
get_som_labeled_img; remove_overlap_new appended a
raw bbox list instead of the element dict on the
no-OCR branch)
util/box_annotator.py unmodified
util/yolov9.py unmodified (YOLOv9-E inference for the icon detector)
util/__init__.py unmodified
Attribution, as required by CC BY 4.0:
This product includes files derived from OmniParser by Microsoft
Corporation (Lu, Yang, Shen, Awadallah; arXiv:2408.00203), licensed under
CC BY 4.0. The modifications above are by plean and are offered under the
same CC BY 4.0 terms.
Model weights (downloaded by setup.sh, not part of this repository):
icon_detect_v3/model.pt MIT-based (built on the MIT-licensed YOLOv9
implementation)
icon_caption_florence/* MIT (Florence-2 caption model)
See the microsoft/OmniParser-v2.0 HuggingFace model card for details.
Note: util/box_annotator.py derives from supervision (MIT). The optional
ultralytics fallback path (non-default, AGPL) is not used by this service.
+149
View File
@@ -0,0 +1,149 @@
# omniparse-mcp
**Screenshot → structured, numbered, clickable elements — as a self-hosted HTTP
service with an MCP tool wrapper.** Point it at any GUI screenshot and get back
every interactable element with a caption, bounding box, and click coordinates
(pixels and normalized). Built on [OmniParser V2](https://github.com/microsoft/OmniParser)
(pure-vision pipeline: OCR + YOLOv9-E icon detection + Florence-2 captioning —
no accessibility trees, works on any screen including video and remote desktops).
The point: give a vision LLM agent *eyes with coordinates*. Instead of sending
a 1920×1080 image and hoping GPT-4V-class grounding lands, the agent gets a
compact token-cheap list:
```
id=22 center=(1008,402) caption="Notepad"
id=57 center=(84,48) caption="File"
```
## Architecture
```mermaid
graph LR
A[agent / script] -->|MCP stdio| B[mcp_server.py<br/>tiny shim]
A2[any HTTP client] -->|POST /parse| C
B -->|REST + bearer token| C[server.py<br/>FastAPI, queue, LRU cache]
C --> D[engine.py<br/>EasyOCR → YOLOv9-E → Florence-2]
D --> E[(one GPU)]
```
One process owns the GPU (serial worker + bounded queue → `429` on overflow,
no VRAM thrash). The MCP shim is a ~50-line stdio↔REST forwarder: restart your
agent harness freely, the service (and its model load + warm cache) survives.
Identical screenshots (same bytes + params) answer from cache in ~5 ms — the
agent re-sending a screenshot across thinking turns is free.
## Requirements
- Linux, Python ≥ 3.10
- **GPU: ≥ 6 GB VRAM** usable (models ~2.5 GB resident; OCR detection peak
needs headroom — the service returns a clean `503` if the card is shared
and full, never a corrupt partial parse). CPU works, painfully.
- Pascal/Maxwell/Volta (GTX 900/10, TITAN X/P, V100): use `./setup.sh --pascal`
— recent torch CUDA ≥ 12.8 wheels dropped these architectures.
- ~1.8 GB of model weights (downloaded, not committed).
## Quick start
```bash
git clone https://git.plean.rip/plean/omniparse-mcp.git && cd omniparse-mcp
./setup.sh # venv + deps + weights (add --pascal for GTX 9/10 cards)
./start.sh # starts, waits for models, smoke-tests a real parse
curl -s http://127.0.0.1:8898/healthz
```
`start.sh` readiness = an actual parse round-trip, not just "models loaded"
(OCR loads lazily and its detection peak is where VRAM pressure bites).
Parse something:
```bash
TOKEN=$(cat ~/.config/omniparse_token)
python -c "import base64,json,urllib.request as u
b = base64.b64encode(open('shot.png','rb').read()).decode()
req = u.Request('http://127.0.0.1:8898/parse', data=json.dumps(
{'image_b64': b, 'format': 'view'}).encode(),
headers={'Authorization': f'Bearer $TOKEN'})
print(json.loads(u.urlopen(req).read())['view'])"
```
## REST API
Bearer auth on everything except `/healthz`. OpenAPI at `/docs`.
| Endpoint | Notes |
|---|---|
| `POST /parse` | `{image_b64, format: "view"\|"full", include_som?, box_thr?, iou_thr?, imgsz?, batch?, engine?}` |
| `POST /parse_upload` | same params as fields, screenshot as multipart file |
| `GET /healthz` | device, VRAM, queue depth, parse/cache counters |
Response fields: `elements[]` (`id, type, content, bbox_px, center_px,
center_norm, source`), `view` (one line per element, ~12 tokens each), `image_size`,
`timings`, `cache_hit`, optional `som_image_b64` (set-image overlay PNG).
Tunables (env): `OMNI_CUDA_DEVICE` (card; `-1` = CPU), `OMNI_API_PORT`,
`OMNI_TOKEN_FILE`, `OMNI_MAX_QUEUE`, `OMNI_CACHE_MAX`, `OMNI_PYTHON`.
## MCP registration
Start the service first. Then any MCP harness — omp (`~/.omp/agent/mcp.json`):
```json
{ "mcpServers": { "omniparse": {
"command": "/path/to/omniparse-mcp/.venv/bin/python",
"args": ["-m", "omni_api.mcp_server"],
"cwd": "/path/to/omniparse-mcp",
"timeout": 120000,
"env": { "OMNI_API_URL": "http://127.0.0.1:8898",
"OMNI_API_TOKEN": "!cat ~/.config/omniparse_token" } } } }
```
The shim registers one tool, `omniparse(image_path | image_b64, format,
include_som)`. In omp: `/mcp reload`, then `/mcp test omniparse`. The same
entry works in Claude Desktop / Cursor-class harnesses; where `!cmd` env
indirection isn't supported, inline the token string (and keep the file out of
sync deliberately, or patch `OMNI_TOKEN_FILE`).
Remote agents: serve it on a LAN box — set `OMNI_API_URL` to
`http://that.host:8898`, keep the token file client-side; only the shim
speaks HTTP, agents never need GPU access.
## Measured performance
GTX 1070 Ti (8 GB, Pascal) / GTX 1080 Ti, torch 2.6+cu124, fp32 OCR + fp16
Florence, 1920×1080 screenshots:
| Workload | Warm latency |
|---|---|
| Dense desktop (137 elements) | ~5 s (OCR ~4 s dominates) |
| Simple app window (56 elements) | ~1.3 s |
| Repeat of same screenshot | ~5 ms (cache) |
| MCP round-trip incl. shim startup | +0.5–1 s over REST |
OCR-recognition-bound: 1080 Ti ≈ 1070 Ti here. Any sm_70+ card with more
memory scales with batch size instead.
## Troubleshooting
- **`503 GPU out of memory (another process on the card?)`** — something else
(a Jupyter kernel!) holds VRAM. Free it or move the service via
`OMNI_CUDA_DEVICE`. Check `/healthz`.
- **`429`** — queue full (default 8 waiters); service is serial by design.
- **Slow first parse after boot (~10 s extra)** — lazy EasyOCR load, then warm.
- **Silent 401s from MCP** — your harness doesn't expand `!cat …`; inline the token.
- **`InvalidHeader` on first MCP call** — token env value carries a newline;
this repo's shim strips it, but check your harness passes it cleanly.
## License
- This repo's service/shim/setup code (`omni_api/`, `start.sh`, `setup.sh`,
`requirements.txt`): **MIT** (LICENSE).
- `util/` is vendored from [microsoft/OmniParser](https://github.com/microsoft/OmniParser)
under **CC BY 4.0** (LICENSE.upstream) with modifications noted in NOTICE —
commercial use permitted with attribution.
- Model weights (not committed; fetched by `setup.sh`): MIT / MIT-based,
see NOTICE.
- If you swap the icon detector to the ultralytics path, that component is AGPL.
Cite upstream: Lu et al., *OmniParser for Pure Vision Based GUI Agent*,
arXiv:2408.00203.
View File
Whitespace-only changes.
+118
View File
@@ -0,0 +1,118 @@
"""Shared OmniParser engine - THE single parse implementation (mirrors
omni_playground.ipynb's parse(); keep behavior in sync there, not by copy).
Loads YOLOv9-E + Florence-2 captioner + EasyOCR once; parse() runs the full
pipeline on a PIL image. All GPU work lands on the single visible device
(the start script sets CUDA_VISIBLE_DEVICES so the service owns one card -
default 1070 Ti - and never contends with the notebook on the 1080 Ti).
"""
import base64
import io
import os
import time
import torch
from PIL import Image
REPO_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from util.utils import (check_ocr_box, get_yolo_model, # noqa: E402
get_som_labeled_img)
DEFAULTS = {'box_thr': 0.05, 'iou_thr': 0.1, 'imgsz': 640, 'batch': 128,
'engine': 'EasyOCR'}
class ParseEngine:
def __init__(self, device='cuda', dtype=torch.float32,
florence_dir=None, verbose=True):
self.device, self.dtype = device, dtype
self.verbose = verbose
t0 = time.perf_counter()
self.yolo = get_yolo_model(device=device)
from transformers import AutoModelForCausalLM, AutoProcessor
proc = AutoProcessor.from_pretrained('microsoft/Florence-2-base',
trust_remote_code=True)
weights = florence_dir or os.path.join(REPO_DIR, 'weights',
'icon_caption_florence')
model = AutoModelForCausalLM.from_pretrained(
weights, torch_dtype=dtype, trust_remote_code=True).to(device)
self.caption = {'model': model, 'processor': proc}
self.load_s = round(time.perf_counter() - t0, 1)
@torch.inference_mode()
def parse(self, image, box_thr=None, iou_thr=None, imgsz=None, batch=None,
engine=None):
"""Full pipeline. Returns dict ready to serialize (som excluded)."""
p = dict(DEFAULTS)
p.update({k: v for k, v in dict(box_thr=box_thr, iou_thr=iou_thr,
imgsz=imgsz, batch=batch, engine=engine).items()
if v is not None})
if not isinstance(image, Image.Image):
image = Image.open(image).convert('RGB')
image = image.convert('RGB')
ratio = image.size[0] / 3200
draw_bbox_config = {'text_scale': 0.8 * ratio,
'text_thickness': max(int(2 * ratio), 1),
'text_padding': max(int(3 * ratio), 1),
'thickness': max(int(3 * ratio), 1)}
t0 = time.perf_counter()
(text, ocr_bbox), _ = check_ocr_box(
image, display_img=False, output_bb_format='xyxy', goal_filtering=None,
easyocr_args={'paragraph': False, 'text_threshold': 0.9,
'batch_size': 64}, # matches notebook: batched recognition
use_paddleocr=(p['engine'] == 'PaddleOCR'))
t_ocr = time.perf_counter() - t0
t0 = time.perf_counter()
b64, coords, elements = get_som_labeled_img(
image, self.yolo, BOX_TRESHOLD=p['box_thr'], output_coord_in_ratio=True,
ocr_bbox=ocr_bbox, draw_bbox_config=draw_bbox_config,
caption_model_processor=self.caption, ocr_text=text,
iou_threshold=p['iou_thr'], imgsz=p['imgsz'], batch_size=p['batch'])
t_net = time.perf_counter() - t0
pw, ph = image.size
out_elements = []
for i, e in enumerate(elements):
m = coords.get(str(i))
if m:
cx, cy = m[0] + m[2] / 2, m[1] + m[3] / 2
else:
cx, cy = (e['bbox'][0] + e['bbox'][2]) / 2, (e['bbox'][1] + e['bbox'][3]) / 2
out_elements.append({
'id': i, 'type': e['type'], 'content': str(e['content']),
'center_norm': [round(float(cx), 4), round(float(cy), 4)],
'center_px': [round(float(cx) * pw), round(float(cy) * ph)],
'bbox_norm': [round(float(v), 4) for v in e['bbox']],
'interactivity': e.get('interactivity'),
'source': e.get('source', 'icon_detect'),
})
return {'elements': out_elements,
'som_png_b64': b64,
'image_size': [pw, ph],
'timings': {'ocr_s': round(t_ocr, 2),
'detect_caption_s': round(t_net, 2),
'total_s': round(t_ocr + t_net, 2)}}
@staticmethod
def view(res):
"""Token-cheap LLM-facing rendering (same shape as the notebook's
agent_screen_view)."""
lines = []
for e in res['elements']:
if e['type'] == 'icon':
lines.append(f"id={e['id']} center={tuple(e['center_px'])} "
f"caption=\"{e['content']}\"")
else:
lines.append(f"id={e['id']} text=\"{e['content']}\"")
return '\n'.join(lines)
def vram(self):
return [{'index': i,
'name': torch.cuda.get_device_name(i),
'allocated_mib': round(torch.cuda.memory_allocated(i) / 2**20),
'reserved_mib': round(torch.cuda.memory_reserved(i) / 2**20)}
for i in range(torch.cuda.device_count())]
+71
View File
@@ -0,0 +1,71 @@
"""MCP (Model Context Protocol) stdio shim for the omniparse REST service.
Registers one tool, `omniparse`, that forwards to POST /parse on the HTTP
service, so MCP-capable harnesses (omp /mcp.json, Claude Desktop, Cursor...)
get the parser as a first-class tool without custom plugin code.
Register in your harness's MCP config - e.g. ~/.omp/agent/mcp.json (stdio):
"omniparse": {
"command": "<repo>/.venv/bin/python",
"args": ["-m", "omni_api.mcp_server"],
"cwd": "<repo>",
"timeout": 120000,
"env": { "OMNI_API_URL": "http://127.0.0.1:8898",
"OMNI_API_TOKEN": "!cat ~/.config/omniparse_token" }
}
(!cmd values are executed by omp at connect time - a bare env name copies
the launching shell's variable or, when unset, ships the literal string.)
"""
import base64
import os
import requests
from mcp.server.mcpserver import MCPServer
API = os.environ.get('OMNI_API_URL', 'http://127.0.0.1:8898').rstrip('/')
def _token() -> str:
# strip both branches: omp !cmd env values may arrive with the file's
# trailing newline, and a \n in a Bearer header trips httpx validation
return (os.environ.get('OMNI_API_TOKEN') or
open(os.path.expanduser(os.environ.get(
'OMNI_TOKEN_FILE', '~/.config/omniparse_token'))).read()).strip()
mcp = MCPServer('omniparse')
@mcp.tool()
def omniparse(image_path: str = '', image_b64: str = '', format: str = 'view',
include_som: bool = False) -> dict:
"""Parse a GUI screenshot into numbered, captioned interactable elements.
Give the screenshot as image_path (local file the agent can read, e.g. a
captured VM/desktop screenshot) OR image_b64 (base64 PNG/JPEG). Returns
elements: compact 'view' lines (id + pixel center + caption - the primary
LLM-facing form), and/or 'full' per-element JSON with normalized bbox and
center. Set include_som=true only when a vision model or a human must see
the annotated Set-of-Mark rendering. Click targets use center_px scaled to
the ACTUAL screen (image_size tells you the parsed resolution)."""
if image_path:
b64 = base64.b64encode(open(image_path, 'rb').read()).decode()
elif image_b64:
b64 = image_b64
else:
return {'error': 'provide image_path or image_b64'}
r = requests.post(f'{API}/parse',
json={'image_b64': b64, 'format': format,
'include_som': include_som},
headers={'Authorization': f'Bearer {_token()}'}, timeout=300)
if r.status_code != 200:
return {'error': f'{r.status_code}: {r.text[:200]}'}
d = r.json()
d.pop('som_png_b64', None) if not include_som else None
return d
if __name__ == '__main__':
mcp.run(transport='stdio')
+183
View File
@@ -0,0 +1,183 @@
"""OmniParser-as-a-tool HTTP service.
POST /parse (bearer auth): screenshot in (base64 JSON or multipart),
labeled elements out (+ compact view, optional SOM image).
GET /healthz (open): model state, device/VRAM, queue depth.
One GPU worker (serial pipeline) behind a bounded queue; overflow gets 429.
LRU cache on (image bytes + params) so agents re-sending the same screenshot
across thinking turns get millisecond answers.
Run: start.sh (sets CUDA_VISIBLE_DEVICES for the service's card,
token from $OMNI_API_TOKEN or $OMNI_TOKEN_FILE
[default ~/.config/omniparse_token], uvicorn on :$OMNI_API_PORT)
"""
import asyncio
import base64
import hashlib
import os
import sys
import time
from collections import OrderedDict
from contextlib import asynccontextmanager
import torch
from fastapi import FastAPI, Header, HTTPException, Request, UploadFile
from pydantic import BaseModel, Field
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from omni_api.engine import ParseEngine # noqa: E402
MAX_QUEUE = int(os.environ.get('OMNI_MAX_QUEUE', '8'))
MAX_IMAGE_BYTES = 16 * 2**20
CACHE_MAX = int(os.environ.get('OMNI_CACHE_MAX', '16'))
STATE = {'engine': None, 'ready': False, 'started': time.time(), 'queue': None,
'waiters': 0, 'cache': OrderedDict(), 'hits': 0, 'parses': 0}
def _token() -> str:
tok = os.environ.get('OMNI_API_TOKEN')
if not tok:
path = os.path.expanduser(os.environ.get(
'OMNI_TOKEN_FILE', '~/.config/omniparse_token'))
try:
with open(path) as fh:
tok = fh.read().strip()
except OSError:
tok = ''
if not tok:
raise HTTPException(500, 'server has no API token configured')
return tok
@asynccontextmanager
async def lifespan(app: FastAPI):
STATE['queue'] = asyncio.Semaphore(1)
import threading
def _load():
try:
STATE['engine'] = ParseEngine()
STATE['ready'] = True
except Exception as e: # surface in /healthz, retry via restart
STATE['engine'] = e
threading.Thread(target=_load, daemon=True).start()
yield
app = FastAPI(title='omniparse', version='1.0', lifespan=lifespan)
def _auth(authorization: str | None):
import hmac
if not authorization or not hmac.compare_digest(
authorization, f'Bearer {_token()}'):
raise HTTPException(401, 'missing/invalid bearer token')
class ParseReq(BaseModel):
image_b64: str = Field(..., description='PNG/JPEG screenshot, base64 (data-URL prefix ok)')
format: str = Field('view', pattern='^(full|view|both)$',
description="view=compact LLM lines, full=element JSON, both")
include_som: bool = Field(False, description='return Set-of-Mark annotated PNG (base64)')
box_thr: float | None = None
iou_thr: float | None = None
imgsz: int | None = None
batch: int | None = None
engine: str | None = Field(None, pattern='^(EasyOCR|PaddleOCR)$')
def _cache_key(raw: bytes, req) -> str:
h = hashlib.sha1(raw)
h.update(f'{req.box_thr},{req.iou_thr},{req.imgsz},{req.batch},{req.engine}'.encode())
return h.hexdigest()
def _run_cached(key: str, raw: bytes, req) -> dict:
eng: ParseEngine = STATE['engine']
cached = STATE['cache'].get(key)
hit = cached is not None
if hit:
STATE['hits'] += 1
res = dict(cached)
else:
from PIL import Image
import io
img = Image.open(io.BytesIO(raw)).convert('RGB')
try:
res = eng.parse(img, box_thr=req.box_thr, iou_thr=req.iou_thr,
imgsz=req.imgsz, batch=req.batch, engine=req.engine)
except torch.OutOfMemoryError as e:
torch.cuda.empty_cache()
raise HTTPException(503, f'GPU out of memory (another process on the '
f'card?): {e}'.split('\n')[0])
STATE['parses'] += 1
STATE['cache'][key] = res
STATE['cache'].move_to_end(key)
while len(STATE['cache']) > CACHE_MAX:
STATE['cache'].popitem(last=False)
res = dict(res)
out = {'image_size': res['image_size'], 'n_elements': len(res['elements']),
'timings': res['timings'], 'cache_hit': hit}
if req.format in ('full', 'both'):
out['elements'] = res['elements']
if req.format in ('view', 'both'):
out['view'] = eng.view(res)
if req.include_som:
out['som_png_b64'] = res['som_png_b64']
return out
@app.post('/parse')
async def parse(req: ParseReq, authorization: str | None = Header(None)):
_auth(authorization)
if not STATE['ready']:
raise HTTPException(503, 'models still loading - see /healthz')
if isinstance(STATE['engine'], Exception):
raise HTTPException(500, f'model load failed: {STATE["engine"]}')
raw = req.image_b64.split(',', 1)[-1]
try:
raw_bytes = base64.b64decode(raw, validate=False)
except Exception:
raise HTTPException(422, 'image_b64 is not valid base64')
if len(raw_bytes) > MAX_IMAGE_BYTES:
raise HTTPException(413, f'image exceeds {MAX_IMAGE_BYTES} bytes')
if STATE['queue'].locked():
if STATE['waiters'] >= MAX_QUEUE:
raise HTTPException(429, 'parse queue full', headers={'Retry-After': '5'})
STATE['waiters'] += 1
try:
async with STATE['queue']:
return await asyncio.to_thread(_run_cached, _cache_key(raw_bytes, req),
raw_bytes, req)
finally:
STATE['waiters'] -= 1
async with STATE['queue']:
return await asyncio.to_thread(_run_cached, _cache_key(raw_bytes, req),
raw_bytes, req)
@app.post('/parse_upload')
async def parse_upload(file: UploadFile, format: str = 'view', include_som: bool = False,
authorization: str | None = Header(None)):
raw_bytes = await file.read()
if len(raw_bytes) > MAX_IMAGE_BYTES:
raise HTTPException(413, 'image too large')
req = ParseReq(image_b64=base64.b64encode(raw_bytes).decode(),
format=format, include_som=include_som)
return await parse(req, authorization)
@app.get('/healthz')
async def healthz():
eng = STATE['engine']
return {
'status': ('ready' if STATE['ready'] else
'failed' if isinstance(eng, Exception) else 'loading'),
'uptime_s': round(time.time() - STATE['started']),
'parses': STATE['parses'], 'cache_hits': STATE['hits'],
'queue_waiters': STATE['waiters'],
'device': (eng.vram() if STATE['ready'] else None),
'error': (str(eng) if isinstance(eng, Exception) else None),
}
+24
View File
@@ -0,0 +1,24 @@
# Install order matters only for torch on old GPUs - see setup.sh --pascal.
# torch / torchvision come from setup.sh (CUDA-wheel choice is hardware-specific).
numpy==1.26.4 # torch/opencv ecosystem pin from upstream
opencv-python-headless
pillow
matplotlib
requests
tqdm
supervision==0.18.0
ultralytics==8.3.70 # fallback detector path only; default is vendored YOLOv9-E
transformers>=4.45,<4.50
accelerate
timm
einops==0.8.0 # florence-2 remote code
easyocr # default OCR engine
paddleocr==2.10.0 # optional OCR engine (paddlepaddle 3.x dropped use_gpu kwarg upstream uses)
paddlepaddle==3.0.0
huggingface_hub
# serving
fastapi
uvicorn[standard]
# MCP stdio shim (>=2.x: mcp.server.mcpserver.MCPServer; 1.x path was
# mcp.server.fastmcp.FastMCP - adjust import if you pin lower)
mcp>=2.0.0
Executable
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env bash
# One-command setup: venv + deps + model weights (~1.8 GB from HuggingFace).
# ./setup.sh modern GPU (sm_70+, CUDA 12.x) or CPU
# ./setup.sh --pascal Pascal/Maxwell/Volta cards (GTX 9/10, TITAN, V100):
# pins torch 2.6.0+cu124, the last wheels shipping
# sm_61 kernels
# ./setup.sh --skip-weights keep existing weights/
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
PASCAL=0; SKIP_WEIGHTS=0
for a in "$@"; do
case "$a" in
--pascal) PASCAL=1 ;;
--skip-weights) SKIP_WEIGHTS=1 ;;
*) echo "unknown flag: $a"; exit 1 ;;
esac
done
command -v python3 >/dev/null || { echo "python3 required (3.10+)"; exit 1; }
python3 -c 'import sys; assert sys.version_info >= (3, 10)' || { echo "python >= 3.10 required"; exit 1; }
echo "== venv"
[[ -d .venv ]] || python3 -m venv .venv
.venv/bin/pip install -q --upgrade pip
echo "== torch"
if [[ $PASCAL == 1 ]]; then
.venv/bin/pip install -q torch==2.6.0 torchvision==0.21.0 \
--index-url https://download.pytorch.org/whl/cu124
else
.venv/bin/pip install -q torch torchvision
fi
echo "== rest of requirements (a few minutes)"
.venv/bin/pip install -q -r requirements.txt
if [[ $SKIP_WEIGHTS == 0 ]]; then
echo "== weights (~1.8 GB from huggingface.co/microsoft/OmniParser-v2.0)"
mkdir -p weights/icon_caption_florence weights/icon_detect_v3
base=https://huggingface.co/microsoft/OmniParser-v2.0/resolve/main
curl -fSL --retry 3 -o weights/icon_caption_florence/config.json "$base/icon_caption/config.json"
curl -fSL --retry 3 -o weights/icon_caption_florence/generation_config.json "$base/icon_caption/generation_config.json"
curl -fSL --retry 3 -o weights/icon_caption_florence/model.safetensors "$base/icon_caption/model.safetensors"
# YOLOv9-E icon detector (upstream recommends the icon_detect_v3 revision)
curl -fSL --retry 3 -o weights/icon_detect_v3/model.pt \
"https://huggingface.co/microsoft/OmniParser-v2.0/resolve/refs%2Fpr%2F37/icon_detect_v3/model.pt"
fi
.venv/bin/python - <<'EOF'
import torch
print(f"torch {torch.__version__} cuda={torch.cuda.is_available()}"
+ (f" device={torch.cuda.get_device_name(0)} arch={torch.cuda.get_device_capability(0)}"
if torch.cuda.is_available() else " (CPU only - parses will be slow)"))
EOF
echo
echo "done. next:"
echo " ./start.sh # start the service (health-checked, self-tested)"
echo " then register the MCP tool in your harness (README: 'MCP registration')"
Executable
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
# Start (or health-probe) the omniparse parsing service. Idempotent: if a
# healthy service answers on the port, reports it and exits 0.
#
# OMNI_CUDA_DEVICE=0 GPU index for the service (default 0; -1 = CPU)
# OMNI_API_PORT=8898 listen port
# OMNI_TOKEN_FILE token file (default ~/.config/omniparse_token;
# created with a random token if missing)
# OMNI_PYTHON python interpreter (default .venv/bin/python,
# else python3 from PATH)
set -u
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PORT="${OMNI_API_PORT:-8898}"
LOG="${OMNI_LOG_FILE:-/tmp/omniparse.log}"
TOKEN_FILE="${OMNI_TOKEN_FILE:-$HOME/.config/omniparse_token}"
if [[ -x "$REPO/.venv/bin/uvicorn" ]]; then
ENVBIN="$REPO/.venv/bin"
else
ENVBIN="" # bare install: uvicorn/python must be on PATH
fi
PY="${OMNI_PYTHON:-${ENVBIN:+$ENVBIN/}python3}"
if curl -sf --max-time 2 "http://127.0.0.1:$PORT/healthz" >/dev/null 2>&1; then
echo "already up: $(curl -s --max-time 5 "http://127.0.0.1:$PORT/healthz")"
exit 0
fi
umask 077
[[ -f "$TOKEN_FILE" ]] || { mkdir -p "$(dirname "$TOKEN_FILE")"
"$PY" -c 'import secrets; print(secrets.token_hex(16))' | tee "$TOKEN_FILE"; }
TOKEN="$(cat "$TOKEN_FILE")"
cd "$REPO"
export OMNI_API_TOKEN="$TOKEN" PYTHONPATH="$REPO"
if [[ "${OMNI_CUDA_DEVICE:-0}" == "-1" ]]; then
export CUDA_VISIBLE_DEVICES=""
else
export CUDA_VISIBLE_DEVICES="${OMNI_CUDA_DEVICE:-0}"
fi
nohup "${ENVBIN:+$ENVBIN/}uvicorn" omni_api.server:app --host "${OMNI_API_HOST:-0.0.0.0}" \
--port "$PORT" --log-level warning >>"$LOG" 2>&1 &
echo "started (pid $!) port $PORT card ${OMNI_CUDA_DEVICE:-0}; first parse pays a ~10 s lazy OCR load; log: $LOG"
for _ in $(seq 1 120); do
sleep 2
S="$(curl -sf --max-time 3 "http://127.0.0.1:$PORT/healthz" 2>/dev/null)"
[[ "$S" == *'"ready"'* ]] && break
done
[[ "$S" == *'"ready"'* ]] || { echo "FAILED: models never loaded; see $LOG"; exit 1; }
# Readiness = an actual parse, not just loaded models: OCR loads lazily and its
# detection peak is what OOMs when another process shares the card.
IMG_B64="$("$PY" -c 'import base64, io
from PIL import Image
img = Image.new("RGB", (64, 64), (90, 120, 200))
buf = io.BytesIO(); img.save(buf, "PNG")
print(base64.b64encode(buf.getvalue()).decode())')"
SMOKE="$(curl -s --max-time 120 -X POST "http://127.0.0.1:$PORT/parse" \
-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d "{\"image_b64\": \"$IMG_B64\", \"format\": \"view\"}")"
if [[ "$SMOKE" == *'"n_elements"'* ]]; then
echo "READY (warm smoke parse ok)"
else
echo "WARNING: models loaded but smoke parse failed: ${SMOKE:0:200}"; exit 1
fi
IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
echo "url: http://${IP:-127.0.0.1}:$PORT (docs at /docs)"
View File
Whitespace-only changes.
+262
View File
@@ -0,0 +1,262 @@
from typing import List, Optional, Union, Tuple
import cv2
import numpy as np
from supervision.detection.core import Detections
from supervision.draw.color import Color, ColorPalette
class BoxAnnotator:
"""
A class for drawing bounding boxes on an image using detections provided.
Attributes:
color (Union[Color, ColorPalette]): The color to draw the bounding box,
can be a single color or a color palette
thickness (int): The thickness of the bounding box lines, default is 2
text_color (Color): The color of the text on the bounding box, default is white
text_scale (float): The scale of the text on the bounding box, default is 0.5
text_thickness (int): The thickness of the text on the bounding box,
default is 1
text_padding (int): The padding around the text on the bounding box,
default is 5
"""
def __init__(
self,
color: Union[Color, ColorPalette] = ColorPalette.DEFAULT,
thickness: int = 3, # 1 for seeclick 2 for mind2web and 3 for demo
text_color: Color = Color.BLACK,
text_scale: float = 0.5, # 0.8 for mobile/web, 0.3 for desktop # 0.4 for mind2web
text_thickness: int = 2, #1, # 2 for demo
text_padding: int = 10,
avoid_overlap: bool = True,
):
self.color: Union[Color, ColorPalette] = color
self.thickness: int = thickness
self.text_color: Color = text_color
self.text_scale: float = text_scale
self.text_thickness: int = text_thickness
self.text_padding: int = text_padding
self.avoid_overlap: bool = avoid_overlap
def annotate(
self,
scene: np.ndarray,
detections: Detections,
labels: Optional[List[str]] = None,
skip_label: bool = False,
image_size: Optional[Tuple[int, int]] = None,
) -> np.ndarray:
"""
Draws bounding boxes on the frame using the detections provided.
Args:
scene (np.ndarray): The image on which the bounding boxes will be drawn
detections (Detections): The detections for which the
bounding boxes will be drawn
labels (Optional[List[str]]): An optional list of labels
corresponding to each detection. If `labels` are not provided,
corresponding `class_id` will be used as label.
skip_label (bool): Is set to `True`, skips bounding box label annotation.
Returns:
np.ndarray: The image with the bounding boxes drawn on it
Example:
```python
import supervision as sv
classes = ['person', ...]
image = ...
detections = sv.Detections(...)
box_annotator = sv.BoxAnnotator()
labels = [
f"{classes[class_id]} {confidence:0.2f}"
for _, _, confidence, class_id, _ in detections
]
annotated_frame = box_annotator.annotate(
scene=image.copy(),
detections=detections,
labels=labels
)
```
"""
font = cv2.FONT_HERSHEY_SIMPLEX
for i in range(len(detections)):
x1, y1, x2, y2 = detections.xyxy[i].astype(int)
class_id = (
detections.class_id[i] if detections.class_id is not None else None
)
idx = class_id if class_id is not None else i
color = (
self.color.by_idx(idx)
if isinstance(self.color, ColorPalette)
else self.color
)
cv2.rectangle(
img=scene,
pt1=(x1, y1),
pt2=(x2, y2),
color=color.as_bgr(),
thickness=self.thickness,
)
if skip_label:
continue
text = (
f"{class_id}"
if (labels is None or len(detections) != len(labels))
else labels[i]
)
text_width, text_height = cv2.getTextSize(
text=text,
fontFace=font,
fontScale=self.text_scale,
thickness=self.text_thickness,
)[0]
if not self.avoid_overlap:
text_x = x1 + self.text_padding
text_y = y1 - self.text_padding
text_background_x1 = x1
text_background_y1 = y1 - 2 * self.text_padding - text_height
text_background_x2 = x1 + 2 * self.text_padding + text_width
text_background_y2 = y1
# text_x = x1 - self.text_padding - text_width
# text_y = y1 + self.text_padding + text_height
# text_background_x1 = x1 - 2 * self.text_padding - text_width
# text_background_y1 = y1
# text_background_x2 = x1
# text_background_y2 = y1 + 2 * self.text_padding + text_height
else:
text_x, text_y, text_background_x1, text_background_y1, text_background_x2, text_background_y2 = get_optimal_label_pos(self.text_padding, text_width, text_height, x1, y1, x2, y2, detections, image_size)
cv2.rectangle(
img=scene,
pt1=(text_background_x1, text_background_y1),
pt2=(text_background_x2, text_background_y2),
color=color.as_bgr(),
thickness=cv2.FILLED,
)
# import pdb; pdb.set_trace()
box_color = color.as_rgb()
luminance = 0.299 * box_color[0] + 0.587 * box_color[1] + 0.114 * box_color[2]
text_color = (0,0,0) if luminance > 160 else (255,255,255)
cv2.putText(
img=scene,
text=text,
org=(text_x, text_y),
fontFace=font,
fontScale=self.text_scale,
# color=self.text_color.as_rgb(),
color=text_color,
thickness=self.text_thickness,
lineType=cv2.LINE_AA,
)
return scene
def box_area(box):
return (box[2] - box[0]) * (box[3] - box[1])
def intersection_area(box1, box2):
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
return max(0, x2 - x1) * max(0, y2 - y1)
def IoU(box1, box2, return_max=True):
intersection = intersection_area(box1, box2)
union = box_area(box1) + box_area(box2) - intersection
if box_area(box1) > 0 and box_area(box2) > 0:
ratio1 = intersection / box_area(box1)
ratio2 = intersection / box_area(box2)
else:
ratio1, ratio2 = 0, 0
if return_max:
return max(intersection / union, ratio1, ratio2)
else:
return intersection / union
def get_optimal_label_pos(text_padding, text_width, text_height, x1, y1, x2, y2, detections, image_size):
""" check overlap of text and background detection box, and get_optimal_label_pos,
pos: str, position of the text, must be one of 'top left', 'top right', 'outer left', 'outer right' TODO: if all are overlapping, return the last one, i.e. outer right
Threshold: default to 0.3
"""
def get_is_overlap(detections, text_background_x1, text_background_y1, text_background_x2, text_background_y2, image_size):
is_overlap = False
for i in range(len(detections)):
detection = detections.xyxy[i].astype(int)
if IoU([text_background_x1, text_background_y1, text_background_x2, text_background_y2], detection) > 0.3:
is_overlap = True
break
# check if the text is out of the image
if text_background_x1 < 0 or text_background_x2 > image_size[0] or text_background_y1 < 0 or text_background_y2 > image_size[1]:
is_overlap = True
return is_overlap
# if pos == 'top left':
text_x = x1 + text_padding
text_y = y1 - text_padding
text_background_x1 = x1
text_background_y1 = y1 - 2 * text_padding - text_height
text_background_x2 = x1 + 2 * text_padding + text_width
text_background_y2 = y1
is_overlap = get_is_overlap(detections, text_background_x1, text_background_y1, text_background_x2, text_background_y2, image_size)
if not is_overlap:
return text_x, text_y, text_background_x1, text_background_y1, text_background_x2, text_background_y2
# elif pos == 'outer left':
text_x = x1 - text_padding - text_width
text_y = y1 + text_padding + text_height
text_background_x1 = x1 - 2 * text_padding - text_width
text_background_y1 = y1
text_background_x2 = x1
text_background_y2 = y1 + 2 * text_padding + text_height
is_overlap = get_is_overlap(detections, text_background_x1, text_background_y1, text_background_x2, text_background_y2, image_size)
if not is_overlap:
return text_x, text_y, text_background_x1, text_background_y1, text_background_x2, text_background_y2
# elif pos == 'outer right':
text_x = x2 + text_padding
text_y = y1 + text_padding + text_height
text_background_x1 = x2
text_background_y1 = y1
text_background_x2 = x2 + 2 * text_padding + text_width
text_background_y2 = y1 + 2 * text_padding + text_height
is_overlap = get_is_overlap(detections, text_background_x1, text_background_y1, text_background_x2, text_background_y2, image_size)
if not is_overlap:
return text_x, text_y, text_background_x1, text_background_y1, text_background_x2, text_background_y2
# elif pos == 'top right':
text_x = x2 - text_padding - text_width
text_y = y1 - text_padding
text_background_x1 = x2 - 2 * text_padding - text_width
text_background_y1 = y1 - 2 * text_padding - text_height
text_background_x2 = x2
text_background_y2 = y1
is_overlap = get_is_overlap(detections, text_background_x1, text_background_y1, text_background_x2, text_background_y2, image_size)
if not is_overlap:
return text_x, text_y, text_background_x1, text_background_y1, text_background_x2, text_background_y2
return text_x, text_y, text_background_x1, text_background_y1, text_background_x2, text_background_y2
+582
View File
@@ -0,0 +1,582 @@
# from ultralytics import YOLO
import os
import io
import base64
import time
from PIL import Image, ImageDraw, ImageFont
import json
import requests
# utility function
import os
from openai import AzureOpenAI
import json
import sys
import os
import cv2
import numpy as np
# %matplotlib inline
from matplotlib import pyplot as plt
import easyocr
_easyocr_reader = None
_paddle_ocr = None
def get_easyocr_reader():
global _easyocr_reader
if _easyocr_reader is None:
_easyocr_reader = easyocr.Reader(['en'])
# EasyOCR unconditionally wraps its nets in DataParallel. Across our
# unbalanced 1080 Ti + 1070 Ti pair the split buys nothing warm, and
# with batched recognition it re-flattens the CRNN's RNN weights into
# inference tensors -> RuntimeError on the 2nd parse under
# torch.inference_mode. Pin both nets to the primary GPU instead.
for attr in ('detector', 'recognizer'):
net = getattr(_easyocr_reader, attr, None)
if isinstance(net, torch.nn.DataParallel):
setattr(_easyocr_reader, attr, net.module)
return _easyocr_reader
def get_paddle_ocr():
global _paddle_ocr
if _paddle_ocr is None:
try:
from paddleocr import PaddleOCR # optional; only needed when use_paddleocr=True
except ImportError:
raise ImportError(
'PaddleOCR is not installed in this environment. '
'Run: pip install paddlepaddle paddleocr==2.10.0, '
'or switch the OCR engine to EasyOCR.')
_paddle_ocr = PaddleOCR(
lang='en', # other lang also available
use_angle_cls=False,
use_gpu=False, # using cuda will conflict with pytorch in the same process
show_log=False,
max_batch_size=1024,
use_dilation=True, # improves accuracy
det_db_score_mode='slow', # improves accuracy
rec_batch_num=1024)
return _paddle_ocr
import time
import base64
import os
import ast
import torch
from pathlib import Path
from typing import Tuple, List, Union
from torchvision.ops import box_convert
import re
from torchvision.transforms import ToPILImage
import supervision as sv
import torchvision.transforms as T
from util.box_annotator import BoxAnnotator
def get_caption_model_processor(model_name, model_name_or_path="Salesforce/blip2-opt-2.7b", device=None):
if not device:
device = "cuda" if torch.cuda.is_available() else "cpu"
if model_name == "blip2":
from transformers import Blip2Processor, Blip2ForConditionalGeneration
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
if device == 'cpu':
model = Blip2ForConditionalGeneration.from_pretrained(
model_name_or_path, device_map=None, torch_dtype=torch.float32
)
else:
model = Blip2ForConditionalGeneration.from_pretrained(
model_name_or_path, device_map=None, torch_dtype=torch.float16
).to(device)
elif model_name == "florence2":
from transformers import AutoProcessor, AutoModelForCausalLM
processor = AutoProcessor.from_pretrained("microsoft/Florence-2-base", trust_remote_code=True)
if device == 'cpu':
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, torch_dtype=torch.float32, trust_remote_code=True)
else:
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, torch_dtype=torch.float16, trust_remote_code=True).to(device)
return {'model': model.to(device), 'processor': processor}
def get_yolo_model(model_path=None, device=None):
if model_path is None:
local_model_path = Path(__file__).resolve().parents[1] / "weights/icon_detect_v3/model.pt"
if local_model_path.is_file():
model_path = local_model_path
if model_path is None or "icon_detect_v3" in Path(model_path).parts:
from util.yolov9 import YOLOv9Detector
return YOLOv9Detector(model_path=model_path, device=device)
from ultralytics import YOLO
return YOLO(model_path)
@torch.inference_mode()
def get_parsed_content_icon(filtered_boxes, starting_idx, image_source, caption_model_processor, prompt=None, batch_size=128):
# Number of samples per batch, --> 128 roughly takes 4 GB of GPU memory for florence v2 model
to_pil = ToPILImage()
if starting_idx:
non_ocr_boxes = filtered_boxes[starting_idx:]
else:
non_ocr_boxes = filtered_boxes
croped_pil_image = []
for i, coord in enumerate(non_ocr_boxes):
try:
xmin, xmax = int(coord[0]*image_source.shape[1]), int(coord[2]*image_source.shape[1])
ymin, ymax = int(coord[1]*image_source.shape[0]), int(coord[3]*image_source.shape[0])
cropped_image = image_source[ymin:ymax, xmin:xmax, :]
cropped_image = cv2.resize(cropped_image, (64, 64))
croped_pil_image.append(to_pil(cropped_image))
except:
continue
model, processor = caption_model_processor['model'], caption_model_processor['processor']
if not prompt:
if 'florence' in model.config.name_or_path:
prompt = "<CAPTION>"
else:
prompt = "The image shows"
generated_texts = []
device = model.device
for i in range(0, len(croped_pil_image), batch_size):
start = time.time()
batch = croped_pil_image[i:i+batch_size]
t1 = time.time()
if model.device.type == 'cuda':
model_dtype = next(model.parameters()).dtype # inputs must match the loaded checkpoint dtype
inputs = processor(images=batch, text=[prompt]*len(batch), return_tensors="pt", do_resize=False).to(device=device, dtype=model_dtype)
else:
inputs = processor(images=batch, text=[prompt]*len(batch), return_tensors="pt").to(device=device)
if 'florence' in model.config.name_or_path:
generated_ids = model.generate(input_ids=inputs["input_ids"],pixel_values=inputs["pixel_values"],max_new_tokens=20,num_beams=1, do_sample=False)
else:
generated_ids = model.generate(**inputs, max_length=100, num_beams=5, no_repeat_ngram_size=2, early_stopping=True, num_return_sequences=1) # temperature=0.01, do_sample=True,
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
generated_text = [gen.strip() for gen in generated_text]
generated_texts.extend(generated_text)
return generated_texts
def get_parsed_content_icon_phi3v(filtered_boxes, ocr_bbox, image_source, caption_model_processor):
to_pil = ToPILImage()
if ocr_bbox:
non_ocr_boxes = filtered_boxes[len(ocr_bbox):]
else:
non_ocr_boxes = filtered_boxes
croped_pil_image = []
for i, coord in enumerate(non_ocr_boxes):
xmin, xmax = int(coord[0]*image_source.shape[1]), int(coord[2]*image_source.shape[1])
ymin, ymax = int(coord[1]*image_source.shape[0]), int(coord[3]*image_source.shape[0])
cropped_image = image_source[ymin:ymax, xmin:xmax, :]
croped_pil_image.append(to_pil(cropped_image))
model, processor = caption_model_processor['model'], caption_model_processor['processor']
device = model.device
messages = [{"role": "user", "content": "<|image_1|>\ndescribe the icon in one sentence"}]
prompt = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
batch_size = 5 # Number of samples per batch
generated_texts = []
for i in range(0, len(croped_pil_image), batch_size):
images = croped_pil_image[i:i+batch_size]
image_inputs = [processor.image_processor(x, return_tensors="pt") for x in images]
inputs ={'input_ids': [], 'attention_mask': [], 'pixel_values': [], 'image_sizes': []}
texts = [prompt] * len(images)
for i, txt in enumerate(texts):
input = processor._convert_images_texts_to_inputs(image_inputs[i], txt, return_tensors="pt")
inputs['input_ids'].append(input['input_ids'])
inputs['attention_mask'].append(input['attention_mask'])
inputs['pixel_values'].append(input['pixel_values'])
inputs['image_sizes'].append(input['image_sizes'])
max_len = max([x.shape[1] for x in inputs['input_ids']])
for i, v in enumerate(inputs['input_ids']):
inputs['input_ids'][i] = torch.cat([processor.tokenizer.pad_token_id * torch.ones(1, max_len - v.shape[1], dtype=torch.long), v], dim=1)
inputs['attention_mask'][i] = torch.cat([torch.zeros(1, max_len - v.shape[1], dtype=torch.long), inputs['attention_mask'][i]], dim=1)
inputs_cat = {k: torch.concatenate(v).to(device) for k, v in inputs.items()}
generation_args = {
"max_new_tokens": 25,
"temperature": 0.01,
"do_sample": False,
}
generate_ids = model.generate(**inputs_cat, eos_token_id=processor.tokenizer.eos_token_id, **generation_args)
# # remove input tokens
generate_ids = generate_ids[:, inputs_cat['input_ids'].shape[1]:]
response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
response = [res.strip('\n').strip() for res in response]
generated_texts.extend(response)
return generated_texts
def remove_overlap(boxes, iou_threshold, ocr_bbox=None):
assert ocr_bbox is None or isinstance(ocr_bbox, List)
def box_area(box):
return (box[2] - box[0]) * (box[3] - box[1])
def intersection_area(box1, box2):
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
return max(0, x2 - x1) * max(0, y2 - y1)
def IoU(box1, box2):
intersection = intersection_area(box1, box2)
union = box_area(box1) + box_area(box2) - intersection + 1e-6
if box_area(box1) > 0 and box_area(box2) > 0:
ratio1 = intersection / box_area(box1)
ratio2 = intersection / box_area(box2)
else:
ratio1, ratio2 = 0, 0
return max(intersection / union, ratio1, ratio2)
def is_inside(box1, box2):
# return box1[0] >= box2[0] and box1[1] >= box2[1] and box1[2] <= box2[2] and box1[3] <= box2[3]
intersection = intersection_area(box1, box2)
ratio1 = intersection / box_area(box1)
return ratio1 > 0.95
boxes = boxes.tolist()
filtered_boxes = []
if ocr_bbox:
filtered_boxes.extend(ocr_bbox)
# print('ocr_bbox!!!', ocr_bbox)
for i, box1 in enumerate(boxes):
# if not any(IoU(box1, box2) > iou_threshold and box_area(box1) > box_area(box2) for j, box2 in enumerate(boxes) if i != j):
is_valid_box = True
for j, box2 in enumerate(boxes):
# keep the smaller box
if i != j and IoU(box1, box2) > iou_threshold and box_area(box1) > box_area(box2):
is_valid_box = False
break
if is_valid_box:
# add the following 2 lines to include ocr bbox
if ocr_bbox:
# only add the box if it does not overlap with any ocr bbox
if not any(IoU(box1, box3) > iou_threshold and not is_inside(box1, box3) for k, box3 in enumerate(ocr_bbox)):
filtered_boxes.append(box1)
else:
filtered_boxes.append(box1)
return torch.tensor(filtered_boxes)
def remove_overlap_new(boxes, iou_threshold, ocr_bbox=None):
'''
ocr_bbox format: [{'type': 'text', 'bbox':[x,y], 'interactivity':False, 'content':str }, ...]
boxes format: [{'type': 'icon', 'bbox':[x,y], 'interactivity':True, 'content':None }, ...]
'''
assert ocr_bbox is None or isinstance(ocr_bbox, List)
def box_area(box):
return (box[2] - box[0]) * (box[3] - box[1])
def intersection_area(box1, box2):
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
return max(0, x2 - x1) * max(0, y2 - y1)
def IoU(box1, box2):
intersection = intersection_area(box1, box2)
union = box_area(box1) + box_area(box2) - intersection + 1e-6
if box_area(box1) > 0 and box_area(box2) > 0:
ratio1 = intersection / box_area(box1)
ratio2 = intersection / box_area(box2)
else:
ratio1, ratio2 = 0, 0
return max(intersection / union, ratio1, ratio2)
def is_inside(box1, box2):
# return box1[0] >= box2[0] and box1[1] >= box2[1] and box1[2] <= box2[2] and box1[3] <= box2[3]
intersection = intersection_area(box1, box2)
ratio1 = intersection / box_area(box1)
return ratio1 > 0.80
# boxes = boxes.tolist()
filtered_boxes = []
if ocr_bbox:
filtered_boxes.extend(ocr_bbox)
# print('ocr_bbox!!!', ocr_bbox)
for i, box1_elem in enumerate(boxes):
box1 = box1_elem['bbox']
is_valid_box = True
for j, box2_elem in enumerate(boxes):
# keep the smaller box
box2 = box2_elem['bbox']
if i != j and IoU(box1, box2) > iou_threshold and box_area(box1) > box_area(box2):
is_valid_box = False
break
if is_valid_box:
if ocr_bbox:
# keep yolo boxes + prioritize ocr label
box_added = False
ocr_labels = ''
for box3_elem in ocr_bbox:
if not box_added:
box3 = box3_elem['bbox']
if is_inside(box3, box1): # ocr inside icon
# box_added = True
# delete the box3_elem from ocr_bbox
try:
# gather all ocr labels
ocr_labels += box3_elem['content'] + ' '
filtered_boxes.remove(box3_elem)
except:
continue
# break
elif is_inside(box1, box3): # icon inside ocr, don't added this icon box, no need to check other ocr bbox bc no overlap between ocr bbox, icon can only be in one ocr box
box_added = True
break
else:
continue
if not box_added:
if ocr_labels:
filtered_boxes.append({'type': 'icon', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': ocr_labels, 'source':'box_yolo_content_ocr'})
else:
filtered_boxes.append({'type': 'icon', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': None, 'source':'box_yolo_content_yolo'})
else:
filtered_boxes.append(box1_elem) # dict not raw list (upstream bug, textless path)
return filtered_boxes # torch.tensor(filtered_boxes)
def load_image(image_path: str) -> Tuple[np.array, torch.Tensor]:
transform = T.Compose(
[
T.RandomResize([800], max_size=1333),
T.ToTensor(),
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
image_source = Image.open(image_path).convert("RGB")
image = np.asarray(image_source)
image_transformed, _ = transform(image_source, None)
return image, image_transformed
def annotate(image_source: np.ndarray, boxes: torch.Tensor, logits: torch.Tensor, phrases: List[str], text_scale: float,
text_padding=5, text_thickness=2, thickness=3) -> np.ndarray:
"""
This function annotates an image with bounding boxes and labels.
Parameters:
image_source (np.ndarray): The source image to be annotated.
boxes (torch.Tensor): A tensor containing bounding box coordinates. in cxcywh format, pixel scale
logits (torch.Tensor): A tensor containing confidence scores for each bounding box.
phrases (List[str]): A list of labels for each bounding box.
text_scale (float): The scale of the text to be displayed. 0.8 for mobile/web, 0.3 for desktop # 0.4 for mind2web
Returns:
np.ndarray: The annotated image.
"""
h, w, _ = image_source.shape
boxes = boxes * torch.Tensor([w, h, w, h])
xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").numpy()
xywh = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xywh").numpy()
detections = sv.Detections(xyxy=xyxy)
labels = [f"{phrase}" for phrase in range(boxes.shape[0])]
box_annotator = BoxAnnotator(text_scale=text_scale, text_padding=text_padding,text_thickness=text_thickness,thickness=thickness) # 0.8 for mobile/web, 0.3 for desktop # 0.4 for mind2web
annotated_frame = image_source.copy()
annotated_frame = box_annotator.annotate(scene=annotated_frame, detections=detections, labels=labels, image_size=(w,h))
label_coordinates = {f"{phrase}": v for phrase, v in zip(phrases, xywh)}
return annotated_frame, label_coordinates
def predict(model, image, caption, box_threshold, text_threshold):
""" Use huggingface model to replace the original model
"""
model, processor = model['model'], model['processor']
device = model.device
inputs = processor(images=image, text=caption, return_tensors="pt").to(device)
with torch.no_grad():
outputs = model(**inputs)
results = processor.post_process_grounded_object_detection(
outputs,
inputs.input_ids,
box_threshold=box_threshold, # 0.4,
text_threshold=text_threshold, # 0.3,
target_sizes=[image.size[::-1]]
)[0]
boxes, logits, phrases = results["boxes"], results["scores"], results["labels"]
return boxes, logits, phrases
def predict_yolo(model, image, box_threshold, imgsz, scale_img, iou_threshold=0.7):
""" Use huggingface model to replace the original model
"""
# model = model['model']
if scale_img:
result = model.predict(
source=image,
conf=box_threshold,
imgsz=imgsz,
iou=iou_threshold, # default 0.7
)
else:
result = model.predict(
source=image,
conf=box_threshold,
iou=iou_threshold, # default 0.7
)
boxes = result[0].boxes.xyxy#.tolist() # in pixel space
conf = result[0].boxes.conf
phrases = [str(i) for i in range(len(boxes))]
return boxes, conf, phrases
def int_box_area(box, w, h):
x1, y1, x2, y2 = box
int_box = [int(x1*w), int(y1*h), int(x2*w), int(y2*h)]
area = (int_box[2] - int_box[0]) * (int_box[3] - int_box[1])
return area
def get_som_labeled_img(image_source: Union[str, Image.Image], model=None, BOX_TRESHOLD=0.01, output_coord_in_ratio=False, ocr_bbox=None, text_scale=0.4, text_padding=5, draw_bbox_config=None, caption_model_processor=None, ocr_text=[], use_local_semantics=True, iou_threshold=0.9,prompt=None, scale_img=False, imgsz=None, batch_size=128):
"""Process either an image path or Image object
Args:
image_source: Either a file path (str) or PIL Image object
...
"""
if isinstance(image_source, str):
image_source = Image.open(image_source)
image_source = image_source.convert("RGB") # for CLIP
w, h = image_source.size
if not imgsz:
imgsz = (h, w)
# print('image size:', w, h)
xyxy, logits, phrases = predict_yolo(model=model, image=image_source, box_threshold=BOX_TRESHOLD, imgsz=imgsz, scale_img=scale_img, iou_threshold=0.1)
xyxy = xyxy / torch.Tensor([w, h, w, h]).to(xyxy.device)
image_source = np.asarray(image_source)
phrases = [str(i) for i in range(len(phrases))]
# annotate the image with labels
if ocr_bbox:
ocr_bbox = torch.tensor(ocr_bbox) / torch.Tensor([w, h, w, h])
ocr_bbox=ocr_bbox.tolist()
else:
print('no ocr bbox!!!')
ocr_bbox = [] # text-free frame: [] not None (zip below must not die)
ocr_bbox_elem = [{'type': 'text', 'bbox':box, 'interactivity':False, 'content':txt, 'source': 'box_ocr_content_ocr'} for box, txt in zip(ocr_bbox, ocr_text) if int_box_area(box, w, h) > 0]
xyxy_elem = [{'type': 'icon', 'bbox':box, 'interactivity':True, 'content':None} for box in xyxy.tolist() if int_box_area(box, w, h) > 0]
filtered_boxes = remove_overlap_new(boxes=xyxy_elem, iou_threshold=iou_threshold, ocr_bbox=ocr_bbox_elem)
# sort the filtered_boxes so that the one with 'content': None is at the end, and get the index of the first 'content': None
filtered_boxes_elem = sorted(filtered_boxes, key=lambda x: x['content'] is None)
# get the index of the first 'content': None
starting_idx = next((i for i, box in enumerate(filtered_boxes_elem) if box['content'] is None), -1)
filtered_boxes = torch.tensor([box['bbox'] for box in filtered_boxes_elem])
print('len(filtered_boxes):', len(filtered_boxes), starting_idx)
# get parsed icon local semantics
time1 = time.time()
if use_local_semantics:
caption_model = caption_model_processor['model']
if 'phi3_v' in caption_model.config.model_type:
parsed_content_icon = get_parsed_content_icon_phi3v(filtered_boxes, ocr_bbox, image_source, caption_model_processor)
else:
parsed_content_icon = get_parsed_content_icon(filtered_boxes, starting_idx, image_source, caption_model_processor, prompt=prompt,batch_size=batch_size)
ocr_text = [f"Text Box ID {i}: {txt}" for i, txt in enumerate(ocr_text)]
icon_start = len(ocr_text)
parsed_content_icon_ls = []
# fill the filtered_boxes_elem None content with parsed_content_icon in order
for i, box in enumerate(filtered_boxes_elem):
if box['content'] is None:
box['content'] = parsed_content_icon.pop(0)
for i, txt in enumerate(parsed_content_icon):
parsed_content_icon_ls.append(f"Icon Box ID {str(i+icon_start)}: {txt}")
parsed_content_merged = ocr_text + parsed_content_icon_ls
else:
ocr_text = [f"Text Box ID {i}: {txt}" for i, txt in enumerate(ocr_text)]
parsed_content_merged = ocr_text
print('time to get parsed content:', time.time()-time1)
filtered_boxes = box_convert(boxes=filtered_boxes, in_fmt="xyxy", out_fmt="cxcywh")
phrases = [i for i in range(len(filtered_boxes))]
# draw boxes
if draw_bbox_config:
annotated_frame, label_coordinates = annotate(image_source=image_source, boxes=filtered_boxes, logits=logits, phrases=phrases, **draw_bbox_config)
else:
annotated_frame, label_coordinates = annotate(image_source=image_source, boxes=filtered_boxes, logits=logits, phrases=phrases, text_scale=text_scale, text_padding=text_padding)
pil_img = Image.fromarray(annotated_frame)
buffered = io.BytesIO()
pil_img.save(buffered, format="PNG")
encoded_image = base64.b64encode(buffered.getvalue()).decode('ascii')
if output_coord_in_ratio:
label_coordinates = {k: [v[0]/w, v[1]/h, v[2]/w, v[3]/h] for k, v in label_coordinates.items()}
assert w == annotated_frame.shape[1] and h == annotated_frame.shape[0]
return encoded_image, label_coordinates, filtered_boxes_elem
def get_xywh(input):
x, y, w, h = input[0][0], input[0][1], input[2][0] - input[0][0], input[2][1] - input[0][1]
x, y, w, h = int(x), int(y), int(w), int(h)
return x, y, w, h
def get_xyxy(input):
x, y, xp, yp = input[0][0], input[0][1], input[2][0], input[2][1]
x, y, xp, yp = int(x), int(y), int(xp), int(yp)
return x, y, xp, yp
def get_xywh_yolo(input):
x, y, w, h = input[0], input[1], input[2] - input[0], input[3] - input[1]
x, y, w, h = int(x), int(y), int(w), int(h)
return x, y, w, h
def check_ocr_box(image_source: Union[str, Image.Image], display_img = True, output_bb_format='xywh', goal_filtering=None, easyocr_args=None, use_paddleocr=False):
if isinstance(image_source, str):
image_source = Image.open(image_source)
if image_source.mode == 'RGBA':
# Convert RGBA to RGB to avoid alpha channel issues
image_source = image_source.convert('RGB')
image_np = np.array(image_source)
w, h = image_source.size
if use_paddleocr:
if easyocr_args is None:
text_threshold = 0.5
else:
text_threshold = easyocr_args['text_threshold']
result = get_paddle_ocr().ocr(image_np, cls=False)[0]
coord = [item[0] for item in result if item[1][1] > text_threshold]
text = [item[1][0] for item in result if item[1][1] > text_threshold]
else: # EasyOCR
if easyocr_args is None:
easyocr_args = {}
result = get_easyocr_reader().readtext(image_np, **easyocr_args)
coord = [item[0] for item in result]
text = [item[1] for item in result]
if display_img:
opencv_img = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
bb = []
for item in coord:
x, y, a, b = get_xywh(item)
bb.append((x, y, a, b))
cv2.rectangle(opencv_img, (x, y), (x+a, y+b), (0, 255, 0), 2)
# matplotlib expects RGB
plt.imshow(cv2.cvtColor(opencv_img, cv2.COLOR_BGR2RGB))
else:
if output_bb_format == 'xywh':
bb = [get_xywh(item) for item in coord]
elif output_bb_format == 'xyxy':
bb = [get_xyxy(item) for item in coord]
return (text, bb), goal_filtering
+136
View File
@@ -0,0 +1,136 @@
from contextlib import nullcontext
from pathlib import Path
from typing import Union
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from torchvision.ops import batched_nms
DEFAULT_REPO_ID = "microsoft/OmniParser-v2.0"
DEFAULT_MODEL_FILE = "icon_detect_v3/model.pt"
class Boxes:
def __init__(self, xyxy: torch.Tensor, confidence: torch.Tensor):
self.xyxy = xyxy
self.conf = confidence
class Result:
def __init__(self, boxes: Boxes):
self.boxes = boxes
class YOLOv9Detector:
"""TorchScript YOLOv9-E detector with an Ultralytics-compatible predict API."""
strides = (8, 16, 32)
def __init__(
self,
model_path: Union[str, Path, None] = None,
device: Union[str, torch.device, None] = None,
repo_id: str = DEFAULT_REPO_ID,
revision: str = "main",
):
self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
if self.device.type == "cuda" and not torch.cuda.is_available():
raise RuntimeError(f"CUDA device requested but unavailable: {self.device}")
if model_path is None:
model_path = hf_hub_download(
repo_id=repo_id,
filename=DEFAULT_MODEL_FILE,
revision=revision,
)
self.model_path = Path(model_path)
self.model = torch.jit.load(str(self.model_path), map_location=self.device).eval()
@staticmethod
def _normalize_image_size(image_size):
if isinstance(image_size, int):
width = height = image_size
elif len(image_size) == 2:
height, width = image_size
else:
raise ValueError(f"Expected one or two image dimensions, got {image_size}")
width = ((int(width) + 31) // 32) * 32
height = ((int(height) + 31) // 32) * 32
return width, height
@staticmethod
def _load_image(source):
if isinstance(source, Image.Image):
return source.convert("RGB")
if isinstance(source, np.ndarray):
return Image.fromarray(source).convert("RGB")
with Image.open(source) as image:
return image.convert("RGB")
def _preprocess(self, image, image_size):
target_width, target_height = self._normalize_image_size(image_size)
image_width, image_height = image.size
scale = min(target_width / image_width, target_height / image_height)
resized_width = int(image_width * scale)
resized_height = int(image_height * scale)
pad_left = (target_width - resized_width) // 2
pad_top = (target_height - resized_height) // 2
resized = image.resize((resized_width, resized_height), Image.Resampling.LANCZOS)
padded = Image.new("RGB", (target_width, target_height), (114, 114, 114))
padded.paste(resized, (pad_left, pad_top))
image_array = np.asarray(padded, dtype=np.float32).transpose(2, 0, 1) / 255.0
image_tensor = torch.from_numpy(image_array).unsqueeze(0).to(self.device)
return image_tensor, scale, pad_left, pad_top
def _decode(self, outputs):
class_logits = []
decoded_boxes = []
for output_index, stride in zip(range(0, len(outputs), 2), self.strides):
layer_logits, layer_distances = outputs[output_index : output_index + 2]
batch_size, _, height, width = layer_logits.shape
layer_logits = layer_logits.permute(0, 2, 3, 1).reshape(batch_size, -1, layer_logits.shape[1])
layer_distances = layer_distances.permute(0, 2, 3, 1).reshape(batch_size, -1, 4) * stride
grid_y, grid_x = torch.meshgrid(
torch.arange(height, device=self.device),
torch.arange(width, device=self.device),
indexing="ij",
)
anchors = (torch.stack((grid_x, grid_y), dim=-1).reshape(-1, 2) + 0.5) * stride
left_top, right_bottom = layer_distances.chunk(2, dim=-1)
decoded_boxes.append(torch.cat((anchors - left_top, anchors + right_bottom), dim=-1))
class_logits.append(layer_logits)
return torch.cat(class_logits, dim=1).sigmoid(), torch.cat(decoded_boxes, dim=1)
def _inference_context(self):
if self.device.type == "cuda":
return torch.autocast(device_type="cuda", dtype=torch.float16)
return nullcontext()
@torch.inference_mode()
def predict(self, source, conf=0.25, imgsz=640, iou=0.7, max_det=300):
image = self._load_image(source)
image_tensor, scale, pad_left, pad_top = self._preprocess(image, imgsz)
with self._inference_context(), torch.jit.optimized_execution(False):
class_scores, boxes = self._decode(self.model(image_tensor))
scores, class_ids = class_scores[0].max(dim=-1)
valid = scores > conf
scores = scores[valid]
class_ids = class_ids[valid]
boxes = boxes[0][valid]
boxes[:, [0, 2]] = (boxes[:, [0, 2]] - pad_left) / scale
boxes[:, [1, 3]] = (boxes[:, [1, 3]] - pad_top) / scale
keep = batched_nms(boxes, scores, class_ids, iou)[:max_det]
boxes = boxes[keep]
scores = scores[keep]
boxes[:, [0, 2]] = boxes[:, [0, 2]].clamp(0, image.width)
boxes[:, [1, 3]] = boxes[:, [1, 3]].clamp(0, image.height)
return [Result(Boxes(boxes, scores))]