"""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())]