Spaces:
Running
Running
text heuristic fix
Browse filesFiles changed (4)
3 unmodified lines4567898 unmodified lines1819202122233 unmodified linesgit \libgl1 \libglib2.0-0 \&& rm -rf /var/lib/apt/lists/*WORKDIR /code8 unmodified linesCOPY model.safetensors /code/model.safetensorsCOPY app /code/appEXPOSE 7860CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]3 unmodified lines456789108 unmodified lines192021222324252627283 unmodified linesgit \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.pbEXPOSE 7860CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
123version https://git-lfs.github.com/spec/v1oid sha256:9b486f3c3eee77b4c8cc91a83892c37026cca7d29b79bf3b93772ccd2db58454size 966627567 unmodified lines891011121314151617181920212225 unmodified lines48495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138598 unmodified lines737738739740741742743120 unmodified lines864865866867868869870201 unmodified lines10721073107410751076107710781079108034 unmodified lines11151116111711181119112011211122112311247 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 pandasdependency, which conflicts with the current numpy environment."""from __future__ import annotationsimport osimport subprocessimport tempfilefrom dataclasses import dataclassfrom typing import Optionalimport cv225 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")return []except subprocess.TimeoutExpired:print("[screenshot] tesseract timed out")return []finally:os.unlink(tmp.name)if result.returncode != 0:print(f"[screenshot] tesseract error: {result.stderr.strip()}")return []boxes = []lines = result.stdout.strip().split("\n")if len(lines) < 2:return []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):continuetext = cols[idx_text].strip()if not text:continuetry:conf = int(float(cols[idx_conf]))except (ValueError, TypeError):continueif 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# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ598 unmodified linessat = hsv[:, :, 1]val = hsv[:, :, 2]text_mask = np.zeros((bh, bw), dtype=np.uint8)sub_boxes = run_tesseract(sub)if sub_boxes:pad = max(4, min(bw, bh) // 200)for (tx, ty, tw, th) in sub_boxes:120 unmodified linesif h < 100:return crop_boxsub_boxes = run_tesseract(sub)if not sub_boxes:return crop_box201 unmodified linesdebug={"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.0if _is_reels_ui(arr):cw = int(w * 0.85)34 unmodified linescrop_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_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.0crop_hsv = cv2.cvtColor(crop_arr, cv2.COLOR_RGB2HSV)mean_saturation = float(crop_hsv[:, :, 1].mean())7 unmodified lines89101112131415161718192021222325 unmodified lines495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234598 unmodified lines833834835836837838839120 unmodified lines960961962963964965966201 unmodified lines1168116911701171117211731174117534 unmodified lines1210121112121213121412151216121712187 unmodified lines- status="cropped": one or more embedded media regions were extracted- status="text_only": screenshot is essentially text (tweet, doc, ...)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 annotationsimport mathfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Optionalimport cv225 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Text region detection (EAST scene-text detector via cv2.dnn)# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββEAST_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 = Falsedef _get_east_net():"""Load and cache the EAST text detector. Returns None if unavailable."""global _east_net, _east_load_attemptedif _east_load_attempted:return _east_net_east_load_attempted = Truecandidates = [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():continuetry:_east_net = cv2.dnn.readNet(str(path))print(f"[screenshot] EAST text detector loaded from {path}")return _east_netexcept 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 Nonedef _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:continueoffset_x = x * 4.0offset_y = y * 4.0angle = 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_boxstart_y = end_y - h_boxcx = (start_x + end_x) / 2.0cy = (start_y + end_y) / 2.0rects.append(((float(cx), float(cy)),(w_box, h_box),-float(angle) * 180.0 / math.pi))confidences.append(score)return rects, confidencesdef 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. Theimage is resampled to a fixed 320Γ320 EAST input for speed; the resultingrotated rectangles are projected back to the original frame as theiraxis-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 []h, w = image.shape[:2]if h < 4 or w < 4:return []img = imageif 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) * 32if target < 32:target = 32ratio_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 []rects, confidences = _decode_east(scores, geometry, EAST_SCORE_THRESHOLD)if not rects:return []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_wys = pts[:, 1] * ratio_hx0 = 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 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 amask and averaging gives the correct geometric coverage."""if not boxes or h <= 0 or w <= 0:return 0.0mask = 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] = 1return float(mask.mean())# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ598 unmodified linessat = hsv[:, :, 1]val = hsv[:, :, 2]text_mask = np.zeros((bh, bw), dtype=np.uint8)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 linesif h < 100:return crop_boxsub_boxes = detect_text_boxes(sub)if not sub_boxes:return crop_box201 unmodified linesdebug={"tier": 1, **tier1},)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 linescrop_pct = round(100.0 * total_crop_area / (h * w), 1)crop_arr = np.array(cropped_images[0])crop_boxes = detect_text_boxes(crop_arr)crop_h, crop_w = crop_arr.shape[:2]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