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:
commit
2a4b1101e6
16 files changed
+2113
No files matched your search
Whitespace-only changes.
@@ -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())]
|
||||
@@ -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')
|
||||
@@ -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),
|
||||
}
|
||||
Reference in new issue
Block a user