import logging import re import numpy as np log = logging.getLogger("tell") _reader = None # Bits of app chrome that show up in almost every screenshot and mean nothing. UI_NOISE = re.compile( r"^(\d+[smhdw]|\d{1,2}:\d{2}(\s?[ap]m)?|reply|like|likes|share|repost|follow|" r"following|more|send|message|view|views|\d+(\.\d+)?[km]?)$", re.I, ) def get_reader(): # EasyOCR takes a few seconds to load, so every tool shares one reader. global _reader if _reader is None: import easyocr _reader = easyocr.Reader(["en"], gpu=False) return _reader def read_text(image, min_conf: float = 0.3) -> str: try: results = get_reader().readtext(np.array(image.convert("RGB"))) except Exception as e: log.warning("OCR failed: %s", e) return "" # Sort into rough lines (top to bottom, then left to right). # 20px buckets keep words on the same line together. results.sort(key=lambda r: (round(r[0][0][1] / 20), r[0][0][0])) words = [t.strip() for _, t, conf in results if conf >= min_conf] return " ".join(w for w in words if w and not UI_NOISE.match(w))