"""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), }