Spaces:
Running
Running
Speed up screenshot OCR by downscaling before tesseract
Browse files50 unmodified lines5152535455565758596061626364656638 unmodified lines10510610710810911011111211311411511650 unmodified lines# OCR via tesseract subprocess# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef run_tesseract(image: np.ndarray, min_conf: int = 30) -> list[tuple]:"""Call `tesseract` CLI, parse TSV output, return (x, y, w, h) boxes."""tmp = tempfile.NamedTemporaryFile(suffix=".png", delete=False)try:Image.fromarray(image).save(tmp.name)result = subprocess.run(["tesseract", tmp.name, "stdout", "--psm", "3", "tsv"],capture_output=True,text=True,timeout=30,)except FileNotFoundError:print("[screenshot] tesseract binary not found")38 unmodified linescontinueif conf < min_conf:continueboxes.append((int(cols[idx_left]),int(cols[idx_top]),int(cols[idx_width]),int(cols[idx_height]),))return boxes50 unmodified lines5152535455565758596061626364656667686970717273747576777838 unmodified lines11711811912012112212312412512612712812913013113213313413513613750 unmodified lines# OCR via tesseract subprocess# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββOCR_MAX_DIM = 1500 # downscale before tesseract for speed; boxes scaled backdef run_tesseract(image: np.ndarray, min_conf: int = 30) -> list[tuple]:"""Call `tesseract` CLI, parse TSV output, return (x, y, w, h) boxes."""h, w = image.shape[:2]scale = 1.0ocr_image = imageif max(h, w) > OCR_MAX_DIM:scale = OCR_MAX_DIM / float(max(h, w))new_w = max(1, int(round(w * scale)))new_h = max(1, int(round(h * scale)))ocr_image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)tmp = tempfile.NamedTemporaryFile(suffix=".png", delete=False)try:Image.fromarray(ocr_image).save(tmp.name)result = subprocess.run(["tesseract", tmp.name, "stdout", "--psm", "3", "tsv"],capture_output=True,text=True,timeout=60,)except FileNotFoundError:print("[screenshot] tesseract binary not found")38 unmodified linescontinueif conf < min_conf:continueif scale != 1.0:inv = 1.0 / scaleboxes.append((int(round(int(cols[idx_left]) * inv)),int(round(int(cols[idx_top]) * inv)),int(round(int(cols[idx_width]) * inv)),int(round(int(cols[idx_height]) * inv)),))else:boxes.append((int(cols[idx_left]),int(cols[idx_top]),int(cols[idx_width]),int(cols[idx_height]),))return boxes
app/screenshot.py+29-8