Spaces:
Running
Running
text heuristic fix
Browse filesFiles changed (4)
3 unmodified lines456789108 unmodified lines192021222324252627283 unmodified lines git \ libgl1 \ libglib2.0-0 \ wget \ && rm -rf /var/lib/apt/lists/*
WORKDIR /code8 unmodified linesCOPY model.safetensors /code/model.safetensorsCOPY app /code/app
# EAST scene-text detector weights (~96 MB), used by app/screenshot.py.RUN wget --quiet -O /code/app/frozen_east_text_detection.pb \ https://github.com/oyyd/frozen_east_text_detection.pb/raw/master/frozen_east_text_detection.pb
EXPOSE 7860
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]123version https://git-lfs.github.com/spec/v1oid sha256:9b486f3c3eee77b4c8cc91a83892c37026cca7d29b79bf3b93772ccd2db58454size 966627567 unmodified lines891011121112131415161716171818192021222325 unmodified lines49505151525354545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541555758156606162636465666768697071727374757677781571588081159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189838419086871911921931949091921951961971981992002012022032042052062072082092102112122132142159596979899100101102103104105216107108109110111112113114115116117118119120121122123124125126127128129130131132133134135217218219220221222223224225226227228229230231232233234598 unmodified lines833834835740836837838839120 unmodified lines960961962867963964965966201 unmodified lines1168116911701075107610771171117211731174117534 unmodified lines1210121112121118111912131214112112151216121712187 unmodified lines - status="cropped": one or more embedded media regions were extracted - status="text_only": screenshot is essentially text (tweet, doc, ...)
NOTE: Calls `tesseract` via subprocess to avoid pytesseract's pandas dependency, which conflicts with the current numpy environment.Text region detection uses the EAST scene-text detector via OpenCV's`cv2.dnn`. The model file (`frozen_east_text_detection.pb`) lives next tothis module; if it's missing, text detection degrades gracefully to "notext found" (status flips toward `cropped`/`full` rather than text_only)."""from __future__ import annotations
import osimport subprocessimport tempfileimport mathfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Optional
import cv225 unmodified lines
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# OCR via tesseract subprocess# Text region detection (EAST scene-text detector via cv2.dnn)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
OCR_MAX_DIM = 1500 # downscale before tesseract for speed; boxes scaled backEAST_MIN_SIZE = 320 # input dim for small images (multiple of 32)EAST_MAX_SIZE = 1024 # cap for very large imagesEAST_SCALE_DIVISOR = 3 # native_dim / EAST_SCALE_DIVISOR β target dim # then rounded down to a multiple of 32EAST_SCORE_THRESHOLD = 0.5EAST_NMS_THRESHOLD = 0.4EAST_MODEL_FILENAME = "frozen_east_text_detection.pb"EAST_OUTPUT_LAYERS = ( "feature_fusion/Conv_7/Sigmoid", "feature_fusion/concat_3",)
_east_net = None_east_load_attempted = False
def _get_east_net(): """Load and cache the EAST text detector. Returns None if unavailable.""" global _east_net, _east_load_attempted if _east_load_attempted: return _east_net _east_load_attempted = True
candidates = [ Path(__file__).parent / EAST_MODEL_FILENAME, Path(__file__).parent.parent / EAST_MODEL_FILENAME, Path("/code/app") / EAST_MODEL_FILENAME, ] for path in candidates: if not path.exists(): continue try: _east_net = cv2.dnn.readNet(str(path)) print(f"[screenshot] EAST text detector loaded from {path}") return _east_net except Exception as exc: print(f"[screenshot] EAST load failed at {path}: {exc}") print( "[screenshot] EAST model not found β text detection disabled. " "Download frozen_east_text_detection.pb and place it next to app/." ) return None
def _decode_east(scores: np.ndarray, geometry: np.ndarray, score_threshold: float) -> tuple[list, list]: """Decode raw EAST outputs into (rotated-rect, confidence) pairs.""" num_rows, num_cols = scores.shape[2:4] rects: list = [] confidences: list = []
for y in range(num_rows): scores_row = scores[0, 0, y] x0 = geometry[0, 0, y] x1 = geometry[0, 1, y] x2 = geometry[0, 2, y] x3 = geometry[0, 3, y] angles = geometry[0, 4, y]
for x in range(num_cols): score = float(scores_row[x]) if score < score_threshold: continue
offset_x = x * 4.0 offset_y = y * 4.0 angle = float(angles[x]) cos_a = math.cos(angle) sin_a = math.sin(angle)
h_box = float(x0[x] + x2[x]) w_box = float(x1[x] + x3[x])
end_x = offset_x + cos_a * float(x1[x]) + sin_a * float(x2[x]) end_y = offset_y - sin_a * float(x1[x]) + cos_a * float(x2[x]) start_x = end_x - w_box start_y = end_y - h_box
cx = (start_x + end_x) / 2.0 cy = (start_y + end_y) / 2.0 rects.append(((float(cx), float(cy)), (w_box, h_box), -float(angle) * 180.0 / math.pi)) confidences.append(score)
return rects, confidences
def detect_text_boxes(image: np.ndarray) -> list[tuple]: """Find text-region bounding boxes via the EAST scene-text detector.
Returns axis-aligned (x, y, w, h) tuples in original image coords. The image is resampled to a fixed 320Γ320 EAST input for speed; the resulting rotated rectangles are projected back to the original frame as their axis-aligned bounding boxes (good enough for masking and density math). Returns [] if the EAST model file isn't present. """ net = _get_east_net() if net is None: return []
def 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.0 ocr_image = image if 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") if h < 4 or w < 4: return [] except subprocess.TimeoutExpired: print("[screenshot] tesseract timed out") img = image if img.ndim == 2: img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
# Pick an EAST input size that keeps small UI text legible without paying # for inference at native resolution: ~1/3 of the longer dimension, # clamped to [EAST_MIN_SIZE, EAST_MAX_SIZE] and rounded down to a multiple # of 32 (EAST requires that). longest = max(h, w) target = max(EAST_MIN_SIZE, min(EAST_MAX_SIZE, longest // EAST_SCALE_DIVISOR)) target = (target // 32) * 32 if target < 32: target = 32 ratio_w = w / float(target) ratio_h = h / float(target) resized = cv2.resize(img, (target, target)) blob = cv2.dnn.blobFromImage( resized, scalefactor=1.0, size=(target, target), mean=(123.68, 116.78, 103.94), swapRB=True, crop=False, ) net.setInput(blob) try: scores, geometry = net.forward(list(EAST_OUTPUT_LAYERS)) except cv2.error as exc: print(f"[screenshot] EAST forward failed: {exc}") return [] finally: os.unlink(tmp.name)
if result.returncode != 0: print(f"[screenshot] tesseract error: {result.stderr.strip()}") rects, confidences = _decode_east(scores, geometry, EAST_SCORE_THRESHOLD) if not rects: return []
boxes = [] lines = result.stdout.strip().split("\n") if len(lines) < 2: indices = cv2.dnn.NMSBoxesRotated( rects, confidences, EAST_SCORE_THRESHOLD, EAST_NMS_THRESHOLD ) if indices is None or len(indices) == 0: return [] indices = np.asarray(indices).flatten()
boxes: list[tuple] = [] for i in indices: rect = rects[int(i)] pts = cv2.boxPoints(rect) xs = pts[:, 0] * ratio_w ys = pts[:, 1] * ratio_h x0 = int(max(0, math.floor(xs.min()))) y0 = int(max(0, math.floor(ys.min()))) x1 = int(min(w, math.ceil(xs.max()))) y1 = int(min(h, math.ceil(ys.max()))) if x1 > x0 and y1 > y0: boxes.append((x0, y0, x1 - x0, y1 - y0)) return boxes
header = lines[0].split("\t") try: idx_left = header.index("left") idx_top = header.index("top") idx_width = header.index("width") idx_height = header.index("height") idx_conf = header.index("conf") idx_text = header.index("text") except ValueError: print("[screenshot] unexpected tesseract TSV header") return []
for line in lines[1:]: cols = line.split("\t") if len(cols) <= max(idx_left, idx_top, idx_width, idx_height, idx_conf, idx_text): continue text = cols[idx_text].strip() if not text: continue try: conf = int(float(cols[idx_conf])) except (ValueError, TypeError): continue if conf < min_conf: continue if scale != 1.0: inv = 1.0 / scale boxes.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 boxesdef _box_union_fraction(boxes: list[tuple], h: int, w: int) -> float: """Fraction of image area covered by the *union* of boxes.
Sum-of-areas would overcount any time boxes overlap. Rasterizing into a mask and averaging gives the correct geometric coverage. """ if not boxes or h <= 0 or w <= 0: return 0.0 mask = np.zeros((h, w), dtype=np.uint8) for (bx, by, bw, bh) in boxes: x0 = max(0, bx); y0 = max(0, by) x1 = min(w, bx + bw); y1 = min(h, by + bh) if x1 > x0 and y1 > y0: mask[y0:y1, x0:x1] = 1 return float(mask.mean())
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ598 unmodified lines sat = hsv[:, :, 1] val = hsv[:, :, 2] text_mask = np.zeros((bh, bw), dtype=np.uint8) sub_boxes = run_tesseract(sub) sub_boxes = detect_text_boxes(sub) if sub_boxes: pad = max(4, min(bw, bh) // 200) for (tx, ty, tw, th) in sub_boxes:120 unmodified lines if h < 100: return crop_box
sub_boxes = run_tesseract(sub) sub_boxes = detect_text_boxes(sub) if not sub_boxes: return crop_box
201 unmodified lines debug={"tier": 1, **tier1}, )
boxes = run_tesseract(arr) text_area = sum(bw * bh for (_, _, bw, bh) in boxes) text_fraction = text_area / float(h * w) if h * w else 0.0 boxes = detect_text_boxes(arr) text_fraction = _box_union_fraction(boxes, h, w)
if _is_reels_ui(arr): cw = int(w * 0.85)34 unmodified lines crop_pct = round(100.0 * total_crop_area / (h * w), 1)
crop_arr = np.array(cropped_images[0]) crop_boxes = run_tesseract(crop_arr) crop_text_area = sum(cbw * cbh for (_, _, cbw, cbh) in crop_boxes) crop_boxes = detect_text_boxes(crop_arr) crop_h, crop_w = crop_arr.shape[:2] crop_text_frac = crop_text_area / float(crop_h * crop_w) if crop_h * crop_w else 0.0 crop_text_frac = _box_union_fraction(crop_boxes, crop_h, crop_w)
crop_hsv = cv2.cvtColor(crop_arr, cv2.COLOR_RGB2HSV) mean_saturation = float(crop_hsv[:, :, 1].mean())Dockerfile+5
app/__pycache__/screenshot.cpython-310.pyc
app/frozen_east_text_detection.pbAdded+3
app/screenshot.py+179-85