Spaces:
Sleeping
Sleeping
Update app.py
Browse filesAdd log to compare pymupdf result and parsed result
app.py
CHANGED
|
@@ -44,6 +44,9 @@ DEFAULT_ZONE_FRAC = float(os.environ.get("GLMOCR_DEFAULT_ZONE_FRAC", "0.12"))
|
|
| 44 |
# MaaS rejects very small images (400). Only send crops that meet minimum dimensions.
|
| 45 |
MIN_CROP_HEIGHT = int(os.environ.get("GLMOCR_MIN_CROP_HEIGHT", "112"))
|
| 46 |
MIN_CROP_PIXELS = int(os.environ.get("GLMOCR_MIN_CROP_PIXELS", "12544")) # 112*112
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
# Single shared parser to avoid "GLM-OCR initialized" per request and asyncio cleanup issues.
|
| 49 |
_parser = None
|
|
@@ -132,7 +135,20 @@ def get_header_footer_zones(regions, norm_height=1000):
|
|
| 132 |
return he_frac, fs_frac
|
| 133 |
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
def extract_zone_text_pdf(pdf_path, page_num, y_start_frac, y_end_frac):
|
|
|
|
| 136 |
try:
|
| 137 |
import pymupdf as fitz
|
| 138 |
doc = fitz.open(pdf_path)
|
|
@@ -141,13 +157,52 @@ def extract_zone_text_pdf(pdf_path, page_num, y_start_frac, y_end_frac):
|
|
| 141 |
rect = fitz.Rect(0, h * y_start_frac, w, h * y_end_frac)
|
| 142 |
text = page.get_text(clip=rect).strip()
|
| 143 |
doc.close()
|
| 144 |
-
|
| 145 |
return text
|
| 146 |
except Exception as e:
|
| 147 |
log.debug("extract_zone_text_pdf failed: %s", e)
|
| 148 |
return ""
|
| 149 |
|
| 150 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
def ocr_zone(image_path, y_start_frac, y_end_frac):
|
| 152 |
"""Run OCR on a horizontal band. Pads small crops to meet API minimum size instead of skipping."""
|
| 153 |
zone_name = "header" if y_end_frac < 0.5 else "footer"
|
|
@@ -187,6 +242,7 @@ def ocr_zone(image_path, y_start_frac, y_end_frac):
|
|
| 187 |
if out and getattr(out[0], "markdown_result", None):
|
| 188 |
text = (out[0].markdown_result or "").strip()
|
| 189 |
log.info("[%s] ocr_zone: crop %dx%d -> %d chars", zone_name, cw, ch, len(text))
|
|
|
|
| 190 |
return text
|
| 191 |
log.info("[%s] ocr_zone: crop %dx%d -> empty result from API", zone_name, cw, ch)
|
| 192 |
finally:
|
|
@@ -248,6 +304,8 @@ def run_ocr(uploaded_file):
|
|
| 248 |
|
| 249 |
all_pages = []
|
| 250 |
for page_num, page_result in enumerate(results):
|
|
|
|
|
|
|
| 251 |
page_md, regions = get_page_md_and_regions(page_result)
|
| 252 |
header_end_frac, footer_start_frac = get_header_footer_zones(regions, 1000)
|
| 253 |
|
|
@@ -272,14 +330,17 @@ def run_ocr(uploaded_file):
|
|
| 272 |
hdr = ""
|
| 273 |
if is_pdf:
|
| 274 |
hdr = extract_zone_text_pdf(path, page_num, 0, he)
|
|
|
|
|
|
|
| 275 |
if hdr and hdr.strip():
|
| 276 |
-
log.info("run_ocr: page %d header from PDF
|
| 277 |
if not (hdr and hdr.strip()):
|
| 278 |
hdr = ocr_zone(img_path, 0, he)
|
| 279 |
if hdr and hdr.strip():
|
| 280 |
parts.append(hdr.strip())
|
|
|
|
| 281 |
elif not (hdr and hdr.strip()) and he > 0:
|
| 282 |
-
log.info("run_ocr: page %d header empty (PDF
|
| 283 |
|
| 284 |
if page_md:
|
| 285 |
parts.append(page_md)
|
|
@@ -290,14 +351,17 @@ def run_ocr(uploaded_file):
|
|
| 290 |
ftr = ""
|
| 291 |
if is_pdf:
|
| 292 |
ftr = extract_zone_text_pdf(path, page_num, fs, 1.0)
|
|
|
|
|
|
|
| 293 |
if ftr and ftr.strip():
|
| 294 |
-
log.info("run_ocr: page %d footer from PDF
|
| 295 |
if not (ftr and ftr.strip()):
|
| 296 |
ftr = ocr_zone(img_path, fs, 1.0)
|
| 297 |
if ftr and ftr.strip():
|
| 298 |
parts.append(ftr.strip())
|
|
|
|
| 299 |
elif not (ftr and ftr.strip()) and fs < 1.0:
|
| 300 |
-
log.info("run_ocr: page %d footer empty (PDF
|
| 301 |
|
| 302 |
if parts:
|
| 303 |
all_pages.append("\n\n".join(parts))
|
|
|
|
| 44 |
# MaaS rejects very small images (400). Only send crops that meet minimum dimensions.
|
| 45 |
MIN_CROP_HEIGHT = int(os.environ.get("GLMOCR_MIN_CROP_HEIGHT", "112"))
|
| 46 |
MIN_CROP_PIXELS = int(os.environ.get("GLMOCR_MIN_CROP_PIXELS", "12544")) # 112*112
|
| 47 |
+
# Wider PDF bands for position-based extraction (capture account numbers etc. in top/bottom)
|
| 48 |
+
PDF_HEADER_BAND_FRAC = float(os.environ.get("GLMOCR_PDF_HEADER_BAND", "0.15")) # top 15%
|
| 49 |
+
PDF_FOOTER_BAND_FRAC = float(os.environ.get("GLMOCR_PDF_FOOTER_BAND", "0.85")) # bottom 15%
|
| 50 |
|
| 51 |
# Single shared parser to avoid "GLM-OCR initialized" per request and asyncio cleanup issues.
|
| 52 |
_parser = None
|
|
|
|
| 135 |
return he_frac, fs_frac
|
| 136 |
|
| 137 |
|
| 138 |
+
def _log_text(prefix, text, max_display=400):
|
| 139 |
+
"""Log extracted text for comparison with OCR; truncate long content."""
|
| 140 |
+
if not text or not text.strip():
|
| 141 |
+
log.info("%s: (empty)", prefix)
|
| 142 |
+
return
|
| 143 |
+
s = text.strip()
|
| 144 |
+
if len(s) <= max_display:
|
| 145 |
+
log.info("%s: %d chars | %s", prefix, len(s), s)
|
| 146 |
+
else:
|
| 147 |
+
log.info("%s: %d chars | %s ...", prefix, len(s), s[:max_display].rstrip())
|
| 148 |
+
|
| 149 |
+
|
| 150 |
def extract_zone_text_pdf(pdf_path, page_num, y_start_frac, y_end_frac):
|
| 151 |
+
"""Extract text from a horizontal band using a clip rect."""
|
| 152 |
try:
|
| 153 |
import pymupdf as fitz
|
| 154 |
doc = fitz.open(pdf_path)
|
|
|
|
| 157 |
rect = fitz.Rect(0, h * y_start_frac, w, h * y_end_frac)
|
| 158 |
text = page.get_text(clip=rect).strip()
|
| 159 |
doc.close()
|
| 160 |
+
_log_text("pymupdf clip page=%s y=%.2f-%.2f" % (page_num, y_start_frac, y_end_frac), text)
|
| 161 |
return text
|
| 162 |
except Exception as e:
|
| 163 |
log.debug("extract_zone_text_pdf failed: %s", e)
|
| 164 |
return ""
|
| 165 |
|
| 166 |
|
| 167 |
+
def log_pymupdf_full_page(pdf_path, page_num):
|
| 168 |
+
"""Log full-page PyMuPDF text for comparison (length + prefix)."""
|
| 169 |
+
try:
|
| 170 |
+
import pymupdf as fitz
|
| 171 |
+
doc = fitz.open(pdf_path)
|
| 172 |
+
page = doc[page_num]
|
| 173 |
+
text = page.get_text().strip()
|
| 174 |
+
doc.close()
|
| 175 |
+
_log_text("pymupdf full page=%s" % page_num, text, max_display=500)
|
| 176 |
+
except Exception as e:
|
| 177 |
+
log.debug("log_pymupdf_full_page failed: %s", e)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def extract_pdf_text_in_band(pdf_path, page_num, y_start_frac, y_end_frac):
|
| 181 |
+
"""Extract all text whose word bbox falls in the given vertical band (by position).
|
| 182 |
+
Use a wider band (e.g. top 15% / bottom 15%) to capture header/footer that clip might miss."""
|
| 183 |
+
try:
|
| 184 |
+
import pymupdf as fitz
|
| 185 |
+
doc = fitz.open(pdf_path)
|
| 186 |
+
page = doc[page_num]
|
| 187 |
+
h = page.rect.height
|
| 188 |
+
y_lo = h * y_start_frac
|
| 189 |
+
y_hi = h * y_end_frac
|
| 190 |
+
words = page.get_text("words") # list of (x0, y0, x1, y1, word, ...)
|
| 191 |
+
doc.close()
|
| 192 |
+
parts = []
|
| 193 |
+
for w in words:
|
| 194 |
+
if len(w) >= 5:
|
| 195 |
+
y0, y1 = float(w[1]), float(w[3])
|
| 196 |
+
if y0 < y_hi and y1 > y_lo:
|
| 197 |
+
parts.append(w[4])
|
| 198 |
+
text = " ".join(parts).strip()
|
| 199 |
+
_log_text("pymupdf band page=%s y=%.2f-%.2f" % (page_num, y_start_frac, y_end_frac), text)
|
| 200 |
+
return text
|
| 201 |
+
except Exception as e:
|
| 202 |
+
log.debug("extract_pdf_text_in_band failed: %s", e)
|
| 203 |
+
return ""
|
| 204 |
+
|
| 205 |
+
|
| 206 |
def ocr_zone(image_path, y_start_frac, y_end_frac):
|
| 207 |
"""Run OCR on a horizontal band. Pads small crops to meet API minimum size instead of skipping."""
|
| 208 |
zone_name = "header" if y_end_frac < 0.5 else "footer"
|
|
|
|
| 242 |
if out and getattr(out[0], "markdown_result", None):
|
| 243 |
text = (out[0].markdown_result or "").strip()
|
| 244 |
log.info("[%s] ocr_zone: crop %dx%d -> %d chars", zone_name, cw, ch, len(text))
|
| 245 |
+
_log_text("ocr_zone %s result" % zone_name, text)
|
| 246 |
return text
|
| 247 |
log.info("[%s] ocr_zone: crop %dx%d -> empty result from API", zone_name, cw, ch)
|
| 248 |
finally:
|
|
|
|
| 304 |
|
| 305 |
all_pages = []
|
| 306 |
for page_num, page_result in enumerate(results):
|
| 307 |
+
if is_pdf:
|
| 308 |
+
log_pymupdf_full_page(path, page_num)
|
| 309 |
page_md, regions = get_page_md_and_regions(page_result)
|
| 310 |
header_end_frac, footer_start_frac = get_header_footer_zones(regions, 1000)
|
| 311 |
|
|
|
|
| 330 |
hdr = ""
|
| 331 |
if is_pdf:
|
| 332 |
hdr = extract_zone_text_pdf(path, page_num, 0, he)
|
| 333 |
+
if not (hdr and hdr.strip()):
|
| 334 |
+
hdr = extract_pdf_text_in_band(path, page_num, 0, PDF_HEADER_BAND_FRAC)
|
| 335 |
if hdr and hdr.strip():
|
| 336 |
+
log.info("run_ocr: page %d header from PDF: %d chars", page_num, len(hdr.strip()))
|
| 337 |
if not (hdr and hdr.strip()):
|
| 338 |
hdr = ocr_zone(img_path, 0, he)
|
| 339 |
if hdr and hdr.strip():
|
| 340 |
parts.append(hdr.strip())
|
| 341 |
+
_log_text("run_ocr page %d final header (used in output)" % page_num, hdr.strip())
|
| 342 |
elif not (hdr and hdr.strip()) and he > 0:
|
| 343 |
+
log.info("run_ocr: page %d header empty (PDF + ocr_zone)", page_num)
|
| 344 |
|
| 345 |
if page_md:
|
| 346 |
parts.append(page_md)
|
|
|
|
| 351 |
ftr = ""
|
| 352 |
if is_pdf:
|
| 353 |
ftr = extract_zone_text_pdf(path, page_num, fs, 1.0)
|
| 354 |
+
if not (ftr and ftr.strip()):
|
| 355 |
+
ftr = extract_pdf_text_in_band(path, page_num, PDF_FOOTER_BAND_FRAC, 1.0)
|
| 356 |
if ftr and ftr.strip():
|
| 357 |
+
log.info("run_ocr: page %d footer from PDF: %d chars", page_num, len(ftr.strip()))
|
| 358 |
if not (ftr and ftr.strip()):
|
| 359 |
ftr = ocr_zone(img_path, fs, 1.0)
|
| 360 |
if ftr and ftr.strip():
|
| 361 |
parts.append(ftr.strip())
|
| 362 |
+
_log_text("run_ocr page %d final footer (used in output)" % page_num, ftr.strip())
|
| 363 |
elif not (ftr and ftr.strip()) and fs < 1.0:
|
| 364 |
+
log.info("run_ocr: page %d footer empty (PDF + ocr_zone)", page_num)
|
| 365 |
|
| 366 |
if parts:
|
| 367 |
all_pages.append("\n\n".join(parts))
|