|
| 1 | +import pymupdf # PyMuPDF |
| 2 | +import numpy as np |
| 3 | +import cv2 |
| 4 | + |
| 5 | + |
| 6 | +WHITE_CHARS = set( |
| 7 | + [chr(i) for i in range(33)] |
| 8 | + + [ |
| 9 | + "\u00a0", # Non-breaking space |
| 10 | + "\u2000", # En quad |
| 11 | + "\u2001", # Em quad |
| 12 | + "\u2002", # En space |
| 13 | + "\u2003", # Em space |
| 14 | + "\u2004", # Three-per-em space |
| 15 | + "\u2005", # Four-per-em space |
| 16 | + "\u2006", # Six-per-em space |
| 17 | + "\u2007", # Figure space |
| 18 | + "\u2008", # Punctuation space |
| 19 | + "\u2009", # Thin space |
| 20 | + "\u200a", # Hair space |
| 21 | + "\u202f", # Narrow no-break space |
| 22 | + "\u205f", # Medium mathematical space |
| 23 | + "\u3000", # Ideographic space |
| 24 | + ] |
| 25 | +) |
| 26 | + |
| 27 | + |
| 28 | +def detect_qr_codes(img): |
| 29 | + detector = cv2.QRCodeDetector() |
| 30 | + data, points, _ = detector.detectAndDecode(img) |
| 31 | + |
| 32 | + if points is not None and data: |
| 33 | + pts = points[0].astype(int) |
| 34 | + return {"data": data, "bbox": pts.tolist()} |
| 35 | + return None |
| 36 | + |
| 37 | + |
| 38 | +def detect_barcodes(img): |
| 39 | + try: |
| 40 | + from pyzbar.pyzbar import decode as barcode_decode |
| 41 | + except ImportError: |
| 42 | + raise ImportError("pyzbar is required for barcode detection") |
| 43 | + gray = img |
| 44 | + barcodes = barcode_decode(gray) |
| 45 | + results = [] |
| 46 | + |
| 47 | + for barcode in barcodes: |
| 48 | + results.append( |
| 49 | + { |
| 50 | + "type": barcode.type, |
| 51 | + "data": barcode.data.decode("utf-8"), |
| 52 | + "bbox": [(p.x, p.y) for p in barcode.polygon], |
| 53 | + } |
| 54 | + ) |
| 55 | + return results |
| 56 | + |
| 57 | + |
| 58 | +def get_page_image(page, dpi=150): |
| 59 | + pix = page.get_pixmap(dpi=dpi) |
| 60 | + matrix = pymupdf.Rect(pix.irect).torect(page.rect) |
| 61 | + img = np.frombuffer(pix.samples, dtype=np.uint8).reshape( |
| 62 | + pix.height, pix.width, pix.n |
| 63 | + ) |
| 64 | + gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) |
| 65 | + return gray, matrix, pix |
| 66 | + |
| 67 | + |
| 68 | +def detect_lines(img, min_length=50, max_gap=10, matrix=pymupdf.Identity): |
| 69 | + gray = img |
| 70 | + edges = cv2.Canny(gray, 50, 150, apertureSize=3) |
| 71 | + pix_lines = cv2.HoughLinesP( |
| 72 | + edges, |
| 73 | + 1, |
| 74 | + np.pi / 180, |
| 75 | + threshold=100, |
| 76 | + minLineLength=min_length, |
| 77 | + maxLineGap=max_gap, |
| 78 | + ) |
| 79 | + lines = [] |
| 80 | + for np_linesr in pix_lines: |
| 81 | + for r in np_linesr: |
| 82 | + p0 = pymupdf.Point(r[0], r[1]) * matrix |
| 83 | + p1 = pymupdf.Point(r[2], r[3]) * matrix |
| 84 | + lines.append((p0, p1)) |
| 85 | + return lines # array of (point1, point2) |
| 86 | + |
| 87 | + |
| 88 | +def detect_curves(img, matrix=pymupdf.Identity): |
| 89 | + gray = img |
| 90 | + _, thresh = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV) |
| 91 | + contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) |
| 92 | + |
| 93 | + curves = [] |
| 94 | + for cnt in contours: |
| 95 | + if len(cnt) > 5: |
| 96 | + ellipse = cv2.fitEllipse(cnt) |
| 97 | + curves.append(ellipse) |
| 98 | + return curves |
| 99 | + |
| 100 | + |
| 101 | +def detect_rectangles(img, min_area=1000, matrix=pymupdf.Identity): |
| 102 | + gray |
| 103 | + _, thresh = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV) |
| 104 | + contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
| 105 | + |
| 106 | + rectangles = [] |
| 107 | + for cnt in contours: |
| 108 | + approx = cv2.approxPolyDP(cnt, 0.02 * cv2.arcLength(cnt, True), True) |
| 109 | + if len(approx) == 4 and cv2.contourArea(cnt) > min_area: |
| 110 | + r = pymupdf.Rect(approx) * matrix |
| 111 | + rectangles.append(r) |
| 112 | + return rectangles |
| 113 | + |
| 114 | + |
| 115 | +def should_ocr_page( |
| 116 | + page, |
| 117 | + dpi=150, |
| 118 | + edge_thresh=0.015, |
| 119 | + vector_thresh=500, |
| 120 | + image_coverage_thresh=0.9, |
| 121 | + text_readability_thresh=0.9, |
| 122 | +): |
| 123 | + """ |
| 124 | + Decide whether a PyMuPDF page should be OCR'd. |
| 125 | +
|
| 126 | + Parameters: |
| 127 | + page: PyMuPDF page object |
| 128 | + dpi: DPI used for rasterization |
| 129 | + edge_thresh: minimum edge density to suggest text presence |
| 130 | + vector_thresh: minimum number of vector paths to suggest glyph simulation |
| 131 | + image_coverage_thresh: fraction of page area covered by images to trigger OCR |
| 132 | + text_readability_thresh: fraction of readable characters to skip OCR |
| 133 | +
|
| 134 | + Returns: |
| 135 | + dict with decision and diagnostic flags |
| 136 | + """ |
| 137 | + decision = { |
| 138 | + "should_ocr": False, |
| 139 | + "has_ocr_text": False, |
| 140 | + "has_text": False, |
| 141 | + "readable_text": False, |
| 142 | + "image_covers_page": False, |
| 143 | + "has_vector_drawings": False, |
| 144 | + "transform": pymupdf.Identity, |
| 145 | + "pixmap": None, |
| 146 | + "image": None, |
| 147 | + "edge_density": 0.0, |
| 148 | + "vector_count": 0, |
| 149 | + } |
| 150 | + page_rect = page.rect |
| 151 | + page_area = abs(page_rect) # size of the full page |
| 152 | + # Check for text |
| 153 | + text = page.get_text(flags=0) |
| 154 | + decision["has_text"] = not WHITE_CHARS.issuperset(text) |
| 155 | + if decision["has_text"]: |
| 156 | + not_readable_count = len([c for c in text if c == chr(0xFFFD)]) |
| 157 | + readability = 1 - not_readable_count / len(text) |
| 158 | + decision["readable_text"] = readability >= text_readability_thresh |
| 159 | + |
| 160 | + all_text_bboxes = [b for b in page.get_bboxlog() if "text" in b[0]] |
| 161 | + ocr_text_bboxes = [b for b in all_text_bboxes if b[0] == "ignore-text"] |
| 162 | + decision["has_ocr_text"] = bool(ocr_text_bboxes) |
| 163 | + # Check for image coverage |
| 164 | + image_rects=[page_rect&img["bbox"] for img in page.get_image_info()] |
| 165 | + image_rect=pymupdf.EMPTY_RECT() |
| 166 | + for r in image_rects: |
| 167 | + image_rect|=r |
| 168 | + image_area=abs(image_rect) |
| 169 | + if image_area: |
| 170 | + images_cover = image_area / page_area |
| 171 | + else: |
| 172 | + images_cover = 0.0 |
| 173 | + decision["image_covers_page"] = images_cover >= image_coverage_thresh |
| 174 | + |
| 175 | + # Check vector drawings |
| 176 | + drawings = [ |
| 177 | + p for p in page.get_drawings() if p["rect"].width > 3 or p["rect"].height > 3 |
| 178 | + ] |
| 179 | + decision["vector_count"] = len(drawings) |
| 180 | + decision["has_vector_drawings"] = len(drawings) >= vector_thresh |
| 181 | + |
| 182 | + # Rasterize and analyze edge density |
| 183 | + img, matrix, pix = get_page_image(page, dpi=dpi) |
| 184 | + decision["transform"] = matrix |
| 185 | + decision["pixmap"] = pix |
| 186 | + decision["image"] = img |
| 187 | + edges = cv2.Canny(img, 100, 200) |
| 188 | + decision["edge_density"] = np.sum(edges > 0) / edges.size |
| 189 | + |
| 190 | + # Final decision |
| 191 | + if ( |
| 192 | + 1 |
| 193 | + and not decision["has_text"] |
| 194 | + and not decision["readable_text"] |
| 195 | + and ( |
| 196 | + 0 |
| 197 | + or decision["image_covers_page"] |
| 198 | + or decision["has_vector_drawings"] |
| 199 | + or decision["edge_density"] > edge_thresh |
| 200 | + ) |
| 201 | + ): |
| 202 | + decision["should_ocr"] = True |
| 203 | + |
| 204 | + return decision |
0 commit comments