import copy import io import json import os import re import statistics import time from collections import defaultdict # For efficient grouping from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from typing import Any, Dict, List, Optional, Tuple, Union import boto3 import cv2 import gradio as gr import numpy as np import pandas as pd import pymupdf from gradio import Progress from pdfminer.high_level import extract_pages from pdfminer.layout import ( LTAnno, LTTextContainer, LTTextLine, LTTextLineHorizontal, ) from pikepdf import Dictionary, Name, Pdf from PIL import Image, ImageDraw, ImageFile, ImageFont from presidio_analyzer import AnalyzerEngine from pymupdf import Document, Page, Rect from tqdm import tqdm from tools.aws_textract import ( analyse_page_with_textract, convert_page_question_answer_to_custom_image_recognizer_results, convert_question_answer_to_dataframe, json_to_ocrresult, load_and_convert_textract_json, textract_prioritizes_signature_extraction, ) from tools.config import ( APPLY_REDACTIONS_GRAPHICS, APPLY_REDACTIONS_IMAGES, APPLY_REDACTIONS_TEXT, AWS_ACCESS_KEY, AWS_LLM_PII_OPTION, AWS_PII_OPTION, AWS_REGION, AWS_SECRET_KEY, AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION, BEDROCK_VLM_TEXT_EXTRACT_OPTION, CLOUD_LLM_PII_MODEL_CHOICE, CLOUD_VLM_MODEL_CHOICE, CUSTOM_BOX_COLOUR, CUSTOM_ENTITIES, CUSTOM_VLM_BACKEND, CUSTOM_VLM_MIN_CONFIDENCE, DEFAULT_LANGUAGE, DEFAULT_LOCAL_OCR_MODEL, EFFICIENT_OCR, EFFICIENT_OCR_MIN_EMBEDDED_IMAGE_PX, EFFICIENT_OCR_MIN_IMAGE_COVERAGE_FRACTION, EFFICIENT_OCR_MIN_WORDS, GEMINI_VLM_TEXT_EXTRACT_OPTION, HYBRID_TEXTRACT_BEDROCK_VLM, HYBRID_TEXTRACT_BEDROCK_VLM_CONFIDENCE_THRESHOLD, HYBRID_TEXTRACT_BEDROCK_VLM_PADDING, IMAGES_DPI, INCLUDE_OCR_VISUALISATION_IN_OUTPUT_FILES, INFERENCE_SERVER_API_URL, INFERENCE_SERVER_LLM_PII_MODEL_CHOICE, INFERENCE_SERVER_PII_OPTION, INPUT_FOLDER, LOAD_TRUNCATED_IMAGES, LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION, LOCAL_PII_OPTION, LOCAL_TRANSFORMERS_LLM_PII_MODEL_CHOICE, LOCAL_TRANSFORMERS_LLM_PII_OPTION, MAX_DOC_PAGES, MAX_IMAGE_PIXELS, MAX_SIMULTANEOUS_FILES, MAX_TIME_VALUE, MAX_WORKERS, MERGE_BOUNDING_BOXES, MERGE_SMALL_REDACTIONS, MERGE_SMALL_REDACTIONS_MIN_Y_OVERLAP_RATIO, MERGE_SMALL_REDACTIONS_SAME_LINE_ONLY, NO_REDACTION_PII_OPTION, OCR_FIRST_PASS_MAX_WORKERS, OUTPUT_FOLDER, OVERWRITE_EXISTING_OCR_RESULTS, PADDLE_MAX_WORKERS, PAGE_BREAK_VALUE, PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS, REDACT_TEXT_STRIP_HEIGHT_FRACTION, RETURN_PDF_FOR_REVIEW, RETURN_REDACTED_PDF, RUN_AWS_FUNCTIONS, SAVE_PAGE_OCR_VISUALISATIONS, SELECTABLE_TEXT_EXTRACT_OPTION, TESSERACT_MAX_WORKERS, TEXTRACT_TEXT_EXTRACT_OPTION, USE_GUI_BOX_COLOURS_FOR_OUTPUTS, aws_comprehend_language_choices, textract_language_choices, ) from tools.custom_image_analyser_engine import ( CustomImageAnalyzerEngine, CustomImageRecognizerResult, OCRResult, _bedrock_page_ocr_predict, _inference_server_page_ocr_predict, _process_textract_page_with_hybrid_bedrock_vlm, _vlm_page_ocr_predict, combine_ocr_results, recreate_page_line_level_ocr_results_with_page, run_page_text_redaction, ) from tools.file_conversion import ( convert_annotation_data_to_dataframe, convert_annotation_json_to_review_df, convert_pymupdf_to_image_coords, create_annotation_dicts_from_annotation_df, divide_coordinates_by_page_sizes, fill_missing_box_ids, fill_missing_ids, is_pdf, is_pdf_or_image, load_and_convert_ocr_results_with_words_json, prepare_image_or_pdf, prepare_images_for_pages, process_single_page_for_image_conversion, remove_duplicate_images_with_blank_boxes, save_pdf_with_or_without_compression, word_level_ocr_output_to_dataframe, ) from tools.helper_functions import ( LINE_LEVEL_OCR_DF_COLUMNS, clean_unicode_text, get_file_name_without_type, get_ocr_visualisation_font_path, get_textract_file_suffix, line_level_ocr_row, normalize_line_level_ocr_df, ) from tools.load_spacy_model_custom_recognisers import ( CustomWordFuzzyRecognizer, create_nlp_analyser, custom_word_list_recogniser, download_tesseract_lang_pack, load_spacy_model, nlp_analyser, score_threshold, ) from tools.ocr_reading_order import ( reorder_structured_text_lines, should_preserve_paddle_line_boxes, ) from tools.redaction_types import ( RedactionContext, RedactionOptions, from_legacy_dict, to_legacy_kwargs, ) from tools.secure_path_utils import ( secure_file_write, secure_path_join, validate_folder_containment, validate_path_containment, validate_path_safety, ) # Extract numbers before 'seconds' using secure regex from tools.secure_regex_utils import safe_extract_numbers_with_seconds ImageFile.LOAD_TRUNCATED_IMAGES = LOAD_TRUNCATED_IMAGES if not MAX_IMAGE_PIXELS: Image.MAX_IMAGE_PIXELS = None else: Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS image_dpi = float(IMAGES_DPI) custom_entities = CUSTOM_ENTITIES def bounding_boxes_overlap(box1, box2): """Check if two bounding boxes overlap.""" return ( box1[0] < box2[2] and box2[0] < box1[2] and box1[1] < box2[3] and box2[1] < box1[3] ) def sum_numbers_before_seconds(string: str): """Extracts numbers that precede the word 'seconds' from a string and adds them up. Args: string: The input string. Returns: The sum of all numbers before 'seconds' in the string. """ numbers = safe_extract_numbers_with_seconds(string) # Sum up the extracted numbers sum_of_numbers = round(sum(numbers), 1) return sum_of_numbers def reverse_y_coords(df: pd.DataFrame, column: str): df[column] = df[column] df[column] = 1 - df[column].astype(float) df[column] = df[column].round(4) return df[column] def _merge_one_page_results(page: int, items: list) -> dict: """Merge results for a single page; safe to run in a thread.""" merged = {"page": page, "results": {}} for item in items: merged["results"].update(item.get("results", {})) return merged def merge_page_results(data: list): if not data: return [] # Group items by page by_page = defaultdict(list) for item in data: page = item["page"] by_page[page].append(item) # Merge each page's items in parallel pages = list(by_page.keys()) n = len(pages) max_workers = min(MAX_WORKERS, n) with ThreadPoolExecutor(max_workers=max_workers) as executor: merged_list = list( executor.map( lambda p: _merge_one_page_results(p, by_page[p]), pages, ) ) return sorted(merged_list, key=lambda x: x["page"]) def _word_count_by_page_from_ocr_results_with_words( ocr_with_words: List[dict], page_numbers_1based: List[int] ) -> Dict[int, int]: """ Compute word count per page from the flat list of line-level OCR results with words. Used by EFFICIENT_OCR to classify pages as above/below efficient_ocr_min_words threshold. Args: ocr_with_words: List of dicts with "page" and "results" (line_key -> {words: [...]}). page_numbers_1based: 1-based page numbers to include in the returned dict. Returns: Dict mapping page number (1-based) to word count. """ by_page = defaultdict(int) for item in ocr_with_words or []: if not item: continue p = item.get("page") if p is None: continue page_num = int(p) if isinstance(p, str) else p for line_data in item.get("results", {}).values(): words = line_data.get("words", []) by_page[page_num] += len(words) if isinstance(words, list) else 0 return {p: by_page.get(p, 0) for p in page_numbers_1based} def _page_has_significant_embedded_image( page: Page, min_coverage_fraction: float, min_embedded_image_px: int = 0, ) -> bool: """ True if any embedded image on the page covers at least min_coverage_fraction of the MediaBox area (single placement). Uses PyMuPDF get_images / get_image_rects. If min_embedded_image_px > 0, the placement's width and height (PDF points) must both be >= that value so tiny artifacts on small pages do not force OCR. """ if min_coverage_fraction <= 0: return False mediabox = page.mediabox page_area = float(abs(mediabox.width) * abs(mediabox.height)) if page_area <= 0: return False for img_item in page.get_images(full=True): try: rects = page.get_image_rects(img_item) except Exception: try: xref = img_item[0] if img_item else None rects = page.get_image_rects(xref) if xref is not None else [] except Exception: continue for r in rects: if isinstance(r, tuple): r = r[0] try: rw = float(abs(r.width)) rh = float(abs(r.height)) rect_area = rw * rh except Exception: continue if min_embedded_image_px > 0 and ( rw < min_embedded_image_px or rh < min_embedded_image_px ): continue if rect_area / page_area >= min_coverage_fraction: return True return False def _efficient_ocr_pages_with_significant_embedded_images( file_path: str, pages_1based: List[int], min_coverage_fraction: float, pymupdf_doc: Optional[Document] = None, min_embedded_image_px: int = 0, ) -> set: """ 1-based page numbers that should use the OCR path due to a significant embedded image, regardless of selectable word count. """ if min_coverage_fraction <= 0 or not pages_1based: return set() doc: Optional[Document] = None close_doc = False if isinstance(pymupdf_doc, Document) and getattr(pymupdf_doc, "page_count", 0) > 0: doc = pymupdf_doc else: try: doc = pymupdf.open(file_path) close_doc = True except Exception: return set() out = set() try: for p1 in pages_1based: p0 = int(p1) - 1 if p0 < 0 or p0 >= doc.page_count: continue page = doc.load_page(p0) if _page_has_significant_embedded_image( page, min_coverage_fraction, min_embedded_image_px ): out.add(int(p1)) return out finally: if close_doc and doc is not None: doc.close() def _build_full_merged_pdf_image_paths_for_vlm( file_path: str, num_pages: int, pages_needing_ocr_1based: List[int], pages_with_text_1based: List[int], pdf_image_file_paths: List[str], all_pages_1based: List[int], input_folder: str, pymupdf_doc: Document, page_sizes: List[dict], progress, ) -> Tuple[List[str], List[dict]]: """ Merge OCR-page images with text-route page images so every page has an image path (full-document pass). Used for CUSTOM_VLM_SIGNATURE under EFFICIENT_OCR when some pages used the selectable-text path. """ if pages_needing_ocr_1based: if pages_with_text_1based: text_page_image_paths, page_sizes = prepare_images_for_pages( file_path, pages_with_text_1based, input_folder, pymupdf_doc, page_sizes, progress, ) return [ (pdf_image_file_paths[i] if i < len(pdf_image_file_paths) else "") or (text_page_image_paths[i] if i < len(text_page_image_paths) else "") for i in range(num_pages) ], page_sizes return pdf_image_file_paths, page_sizes full_paths, page_sizes = prepare_images_for_pages( file_path, all_pages_1based, input_folder, pymupdf_doc, page_sizes, progress, ) return full_paths, page_sizes def add_page_range_suffix_to_file_path( file_path: str, page_min: int, current_loop_page: int, number_of_pages: int, page_max: int = None, ) -> str: """ Add page range suffix to file path if redaction didn't complete all pages. Args: file_path: The original file path page_min: The minimum page number to start redaction from (0-indexed, after conversion in redact_image_pdf/redact_text_pdf) current_loop_page: The number of pages processed (0-indexed count) number_of_pages: Total number of pages in the document (1-indexed) page_max: The maximum page number to end redaction at (1-indexed) Returns: File path with page range suffix if partial processing, otherwise original path """ # if page_min == 0 and page_max == 0: # return file_path # If we processed all pages, don't add suffix if current_loop_page >= number_of_pages: return file_path # Calculate the page range that was actually processed (for display in filename) # page_min from UI: 0 means "first page", 1+ means that page. Never show 0 in suffix (not a real page number). start_page = page_min if page_min >= 1 else 1 # Calculate end_page: page_min is 1-indexed (UI), current_loop_page is count of pages processed # Last page processed (1-indexed) = start + count - 1 last_page_processed_1_indexed = page_min + current_loop_page - 1 if page_min < 1: last_page_processed_1_indexed = ( current_loop_page # started from "first page" (0) ) end_page = ( min(page_max, last_page_processed_1_indexed) if page_max and page_max > 0 else last_page_processed_1_indexed ) # Never show 0 in suffix (not a real page number) if end_page < 1: end_page = 1 if end_page < start_page: end_page = start_page # Add suffix before file extension if "." in file_path: name, ext = file_path.rsplit(".", 1) return f"{name}_{start_page}_{end_page}.{ext}" else: return f"{file_path}_{start_page}_{end_page}" def _parse_vlm_person_signature_result(ocr_result, entity_type: str, text_label: str): """Parse VLM OCR result dict into list of CustomImageRecognizerResult. Shared across backends. Rows are expected to use canonical labels in the parallel ``text`` list (``[FACE]`` / ``[SIGNATURE]``) as produced by ``_parse_vlm_page_ocr_response`` and local/inference page OCR paths; the engine coerces person/signature JSON so mis-keyed text fields do not drop valid boxes. """ boxes = [] if isinstance(ocr_result, tuple) and len(ocr_result) >= 1: ocr_result = ocr_result[0] if not isinstance(ocr_result, dict): return boxes texts = ocr_result.get("text", []) lefts = ocr_result.get("left", []) tops = ocr_result.get("top", []) widths = ocr_result.get("width", []) heights = ocr_result.get("height", []) confs = ocr_result.get("conf", []) for idx, text in enumerate(texts): if text != text_label: continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf_raw = float(confs[idx]) if idx < len(confs) else 0.0 except Exception: continue conf = conf_raw / 100.0 if conf_raw > 1.0 else conf_raw conf = max(0.0, min(1.0, conf)) if conf < CUSTOM_VLM_MIN_CONFIDENCE: continue boxes.append( CustomImageRecognizerResult( entity_type, 0, 0, conf, left, top, width, height, text_label, ) ) return boxes def _gui_tqdm_subphase( tqdm_bar, gradio_progress, phase: str, page_str: str, total_str: str ): """Show face/signature (or other) sub-phases in tqdm postfix and Gradio progress.""" detail = f"{phase} · page {page_str}/{total_str}" try: if tqdm_bar is not None and hasattr(tqdm_bar, "set_postfix_str"): tqdm_bar.set_postfix_str(detail, refresh=True) except Exception: pass try: if gradio_progress is not None: frac = 0.5 if tqdm_bar is not None: total = getattr(tqdm_bar, "total", None) or 0 n = getattr(tqdm_bar, "n", 0) if total and total > 0: frac = min(0.999, max(0.0, (float(n) + 0.05) / float(total))) gradio_progress(frac, desc=detail) except Exception: pass def _run_vlm_only_pass_one_page( args: tuple, ) -> tuple: """ Worker for one page: run VLM person/signature detection using the backend set in CUSTOM_VLM_BACKEND (transformers_vlm, inference_vlm, or bedrock_vlm). Returns (page_no, image_path, page_width, page_height, vlm_boxes, input_tokens, output_tokens, model_name). """ ( page_no, image_path, file_name, run_person, run_signature, normalised_coords_range, output_folder, bedrock_runtime, custom_vlm_backend, inference_server_vlm_model, ) = args reported_page_number = page_no + 1 vlm_boxes = [] ti, to, name = 0, 0, "" try: image = Image.open(image_path) except Exception: return (page_no, image_path, 0, 0, [], 0, 0, "") page_width, page_height = image.size image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) def add_tokens(result_tuple): nonlocal ti, to, name if isinstance(result_tuple, tuple) and len(result_tuple) == 4: _, pi, po, pname = result_tuple ti, to, name = ti + pi, to + po, pname or name if custom_vlm_backend == "bedrock_vlm" and bedrock_runtime: if run_person: try: people_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_people_only=True, model_choice=CLOUD_VLM_MODEL_CHOICE or None, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) add_tokens(people_ocr_result) vlm_boxes.extend( _parse_vlm_person_signature_result( people_ocr_result, "CUSTOM_VLM_FACES", "[FACE]" ) ) except Exception as e: print( f"Warning: Bedrock VLM person detection failed on page {reported_page_number}: {e}" ) if run_signature: try: sig_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_signatures_only=True, model_choice=CLOUD_VLM_MODEL_CHOICE or None, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) add_tokens(sig_ocr_result) vlm_boxes.extend( _parse_vlm_person_signature_result( sig_ocr_result, "CUSTOM_VLM_SIGNATURE", "[SIGNATURE]" ) ) except Exception as e: print( f"Warning: Bedrock VLM signature detection failed on page {reported_page_number}: {e}" ) elif custom_vlm_backend == "inference_vlm": model_name = inference_server_vlm_model or None if run_person: try: people_ocr_result = _inference_server_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_people_only=True, detect_signatures_only=False, model_name=model_name, page_index_0=page_no, ) add_tokens(people_ocr_result) vlm_boxes.extend( _parse_vlm_person_signature_result( people_ocr_result, "CUSTOM_VLM_FACES", "[FACE]" ) ) except Exception as e: print( f"Warning: Inference VLM person detection failed on page {reported_page_number}: {e}" ) if run_signature: try: sig_ocr_result = _inference_server_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_people_only=False, detect_signatures_only=True, model_name=model_name, page_index_0=page_no, ) add_tokens(sig_ocr_result) vlm_boxes.extend( _parse_vlm_person_signature_result( sig_ocr_result, "CUSTOM_VLM_SIGNATURE", "[SIGNATURE]" ) ) except Exception as e: print( f"Warning: Inference VLM signature detection failed on page {reported_page_number}: {e}" ) elif custom_vlm_backend == "transformers_vlm": if run_person: try: people_ocr_result = _vlm_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_people_only=True, detect_signatures_only=False, page_index_0=page_no, ) add_tokens(people_ocr_result) vlm_boxes.extend( _parse_vlm_person_signature_result( people_ocr_result, "CUSTOM_VLM_FACES", "[FACE]" ) ) except Exception as e: print( f"Warning: Transformers VLM person detection failed on page {reported_page_number}: {e}" ) if run_signature: try: sig_ocr_result = _vlm_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_people_only=False, detect_signatures_only=True, page_index_0=page_no, ) add_tokens(sig_ocr_result) vlm_boxes.extend( _parse_vlm_person_signature_result( sig_ocr_result, "CUSTOM_VLM_SIGNATURE", "[SIGNATURE]" ) ) except Exception as e: print( f"Warning: Transformers VLM signature detection failed on page {reported_page_number}: {e}" ) return (page_no, image_path, page_width, page_height, vlm_boxes, ti, to, name) def run_custom_vlm_only_pass( file_path: str, pdf_image_file_paths: list, pymupdf_doc, page_sizes_df: pd.DataFrame, chosen_redact_entities: list, bedrock_runtime, output_folder: str, input_folder: str, number_of_pages: int, page_min: int = 0, page_max: int = 0, progress=None, inference_server_vlm_model: str = "", ) -> tuple: """ Run only the CUSTOM_VLM (face, signature) detection on page images and apply those redactions to the existing pages in pymupdf_doc. Used when text extraction is selectable text but user selected CUSTOM_VLM_* entities (so text comes from PDF, VLM detection from images). Backend is chosen by config CUSTOM_VLM_BACKEND: 'transformers_vlm', 'inference_vlm', or 'bedrock_vlm'. Only ``bedrock_vlm`` runs page VLM calls in parallel (ThreadPoolExecutor); ``inference_vlm`` and ``transformers_vlm`` process pages sequentially. Returns (vlm_total_input_tokens, vlm_total_output_tokens, vlm_model_name, vlm_annotations_list, vlm_decision_rows) for merging into annotations_all_pages and all_pages_decision_process_table. """ vlm_total_input_tokens = 0 vlm_total_output_tokens = 0 vlm_model_name = "" vlm_annotations_list = [] # list of {"image": path, "boxes": [dict, ...]} vlm_decision_rows = [] # list of dicts for decision process table file_name = get_file_name_without_type(file_path) normalised_coords_range = 999 custom_vlm_backend = CUSTOM_VLM_BACKEND run_person = "CUSTOM_VLM_FACES" in (chosen_redact_entities or []) run_signature = "CUSTOM_VLM_SIGNATURE" in (chosen_redact_entities or []) # Skip if chosen backend is not available if custom_vlm_backend == "bedrock_vlm" and not bedrock_runtime: return ( vlm_total_input_tokens, vlm_total_output_tokens, vlm_model_name, vlm_annotations_list, vlm_decision_rows, ) start_page_0 = (page_min - 1) if page_min > 0 else 0 end_page_0 = min( number_of_pages, (page_max if page_max > 0 else number_of_pages), ) # Build list of (page_no, image_path, ...) for pages we can process page_args = [] for page_no in range(start_page_0, end_page_0): if page_no >= len(pdf_image_file_paths): break image_path = pdf_image_file_paths[page_no] if not image_path or not os.path.exists(image_path): continue page_args.append( ( page_no, image_path, file_name, run_person, run_signature, normalised_coords_range, output_folder, bedrock_runtime, custom_vlm_backend, inference_server_vlm_model or "", ) ) # Only Bedrock runs page VLM calls in parallel (separate cloud requests). Inference server and # local Transformers VLM run sequentially to avoid overloading the server or local GPU/memory. if not page_args: return ( vlm_total_input_tokens, vlm_total_output_tokens, vlm_model_name, vlm_annotations_list, vlm_decision_rows, ) _vlm_sub = [] if run_person: _vlm_sub.append("face") if run_signature: _vlm_sub.append("signature") _vlm_phase_label = ( " & ".join(_vlm_sub).title() + " detection" if _vlm_sub else "CUSTOM_VLM detection" ) _n_vlm_pages = len(page_args) def _vlm_inference_progress_frac(completed: int) -> float: """First half of the VLM sub-progress band (parallel API calls).""" if _n_vlm_pages <= 0: return 0.79 return min(0.79, 0.68 + 0.11 * float(completed) / float(_n_vlm_pages)) def _vlm_apply_progress_frac(i_done: int) -> float: """Second half of the VLM sub-progress band (sequential pymupdf apply).""" if _n_vlm_pages <= 0: return 0.92 return min(0.92, 0.79 + 0.11 * float(i_done + 1) / float(_n_vlm_pages)) _use_parallel_vlm = custom_vlm_backend == "bedrock_vlm" if _use_parallel_vlm: futures_map = {} max_workers = min(MAX_WORKERS, _n_vlm_pages) with ThreadPoolExecutor(max_workers=max_workers) as executor: for arg in page_args: fut = executor.submit(_run_vlm_only_pass_one_page, arg) futures_map[fut] = arg[0] results_by_page: Dict[int, tuple] = {} _completed = 0 for fut in as_completed(futures_map): page_no = futures_map[fut] try: res = fut.result() except Exception as e: print( f"Warning: CUSTOM_VLM worker failed on page {page_no + 1}: {e}" ) _failed_path = next( (a[1] for a in page_args if a[0] == page_no), "" ) res = (page_no, _failed_path, 0, 0, [], 0, 0, "") results_by_page[page_no] = res _completed += 1 if progress is not None: try: progress( _vlm_inference_progress_frac(_completed), desc=( f"{_vlm_phase_label} · VLM page {page_no + 1}/" f"{number_of_pages} ({_completed}/{_n_vlm_pages} done)" ), ) except Exception: pass page_results = [results_by_page[arg[0]] for arg in page_args] else: page_results = [] for _completed, arg in enumerate(page_args, start=1): page_no = arg[0] try: res = _run_vlm_only_pass_one_page(arg) except Exception as e: print(f"Warning: CUSTOM_VLM failed on page {page_no + 1}: {e}") _failed_path = arg[1] if len(arg) > 1 else "" res = (page_no, _failed_path, 0, 0, [], 0, 0, "") page_results.append(res) if progress is not None: try: progress( _vlm_inference_progress_frac(_completed), desc=( f"{_vlm_phase_label} · VLM page {page_no + 1}/" f"{number_of_pages} ({_completed}/{_n_vlm_pages} done)" ), ) except Exception: pass # Apply redactions and build annotations in page order (pymupdf is not thread-safe) for _vlm_i, res in enumerate(page_results): page_no, image_path, page_width, page_height, vlm_boxes, ti, to, name = res try: if progress is not None and _n_vlm_pages: progress( _vlm_apply_progress_frac(_vlm_i), desc=( f"{_vlm_phase_label} · applying redactions " f"page {page_no + 1}/{number_of_pages}" ), ) except Exception: pass vlm_total_input_tokens += ti vlm_total_output_tokens += to if name and not vlm_model_name: vlm_model_name = name if not vlm_boxes: continue pymupdf_page = pymupdf_doc.load_page(page_no) image_dimensions_override = { "image_width": page_width, "image_height": page_height, } redact_result = redact_page_with_pymupdf( pymupdf_page, {"boxes": vlm_boxes}, image_path, page_sizes_df=page_sizes_df, input_folder=input_folder, image_dimensions_override=image_dimensions_override, ) # In dual-output mode, capture the final redacted page copy so _redacted.pdf # merge includes CUSTOM_VLM pages (signature/face post-pass as well). try: if ( isinstance(redact_result, tuple) and len(redact_result) >= 1 and isinstance(redact_result[0], tuple) and len(redact_result[0]) == 2 ): _review_page, _applied_redaction_page = redact_result[0] if not hasattr(redact_image_pdf, "_applied_redaction_pages"): redact_image_pdf._applied_redaction_pages = list() redact_image_pdf._applied_redaction_pages.append( (_applied_redaction_page, page_no) ) except Exception: pass # Build annotations and decision rows for review/outputs reported_page_number = page_no + 1 w, h = max(1, page_width), max(1, page_height) if ( CUSTOM_BOX_COLOUR and isinstance(CUSTOM_BOX_COLOUR, (tuple, list)) and len(CUSTOM_BOX_COLOUR) >= 3 ): vlm_box_color = tuple(int(CUSTOM_BOX_COLOUR[i]) for i in range(3)) else: vlm_box_color = (0, 0, 0) all_image_annotations_boxes = [] for box in vlm_boxes: try: xmin = box.left / w ymin = box.top / h xmax = (box.left + box.width) / w ymax = (box.top + box.height) / h label = getattr(box, "entity_type", "Redaction") text = getattr(box, "text", "") or "" img_annotation_box = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, "label": label, "text": text, "color": vlm_box_color, } filled = fill_missing_box_ids(img_annotation_box) all_image_annotations_boxes.append(filled) vlm_decision_rows.append( { "image_path": image_path, "page": reported_page_number, "label": label, "xmin": xmin, "xmax": xmax, "ymin": ymin, "ymax": ymax, "boundingBox": [xmin, ymin, xmax, ymax], "text": text, "start": getattr(box, "start", 0), "end": getattr(box, "end", 0), "score": getattr(box, "score", 0.0), "id": filled.get("id", ""), } ) except AttributeError: continue if all_image_annotations_boxes: vlm_annotations_list.append( { "image": image_path, "boxes": all_image_annotations_boxes, # 0-based index for aligning placeholders with pymupdf / page_sizes "page_index_0": page_no, "page": reported_page_number, } ) return ( vlm_total_input_tokens, vlm_total_output_tokens, vlm_model_name, vlm_annotations_list, vlm_decision_rows, ) def _choose_and_run_redactor_impl( file_paths: List[str], prepared_pdf_file_paths: Optional[List[str]] = None, pdf_image_file_paths: Optional[List[str]] = None, chosen_redact_entities: Optional[List[str]] = None, chosen_redact_comprehend_entities: Optional[List[str]] = None, chosen_llm_entities: List[str] = None, text_extraction_method: str = None, in_allow_list: List[str] = list(), in_deny_list: List[str] = list(), redact_whole_page_list: List[str] = list(), latest_file_completed: int = 0, combined_out_message: List = list(), out_file_paths: List = list(), log_files_output_paths: List = list(), page_min: int = 0, page_max: int = 0, estimated_time_taken_state: float = 0.0, handwrite_signature_checkbox: List[str] = list(["Extract handwriting"]), all_request_metadata_str: str = "", annotations_all_pages: List[dict] = list(), all_page_line_level_ocr_results_df: pd.DataFrame = None, all_pages_decision_process_table: pd.DataFrame = None, pymupdf_doc=list(), pii_identification_method: str = "Local", max_fuzzy_spelling_mistakes_num: int = 1, match_fuzzy_whole_phrase_bool: bool = True, aws_access_key_textbox: str = "", aws_secret_key_textbox: str = "", annotate_max_pages: int = 1, review_file_state: pd.DataFrame = list(), output_folder: str = OUTPUT_FOLDER, document_cropboxes: List = list(), page_sizes: List[dict] = list(), textract_output_found: bool = False, text_extraction_only: bool = False, duplication_file_path_outputs: list = list(), review_file_path: str = "", input_folder: str = INPUT_FOLDER, ocr_file_path: str = "", all_page_line_level_ocr_results: list[dict] = list(), all_page_line_level_ocr_results_with_words: list[dict] = list(), all_page_line_level_ocr_results_with_words_df: pd.DataFrame = None, chosen_local_ocr_model: str = DEFAULT_LOCAL_OCR_MODEL, language: str = DEFAULT_LANGUAGE, ocr_review_files: list = list(), custom_llm_instructions: str = "", inference_server_vlm_model: str = "", efficient_ocr: bool = EFFICIENT_OCR, efficient_ocr_min_words: Union[int, float, None] = EFFICIENT_OCR_MIN_WORDS, efficient_ocr_min_image_coverage_fraction: Optional[float] = None, efficient_ocr_min_embedded_image_px: Optional[int] = None, hybrid_textract_bedrock_vlm: bool = HYBRID_TEXTRACT_BEDROCK_VLM, overwrite_existing_ocr_results: bool = OVERWRITE_EXISTING_OCR_RESULTS, save_page_ocr_visualisations: bool = SAVE_PAGE_OCR_VISUALISATIONS, ocr_first_pass_max_workers: Optional[int] = None, prepare_images: bool = True, RETURN_REDACTED_PDF: bool = RETURN_REDACTED_PDF, RETURN_PDF_FOR_REVIEW: bool = RETURN_PDF_FOR_REVIEW, post_redact_pass1_qa: bool | None = None, post_redact_pass1_auto_prune: bool | None = None, progress=gr.Progress(track_tqdm=True), ): """ This function orchestrates the redaction process based on the specified method and parameters. It takes the following inputs: - file_paths (List[str]): A list of paths to the files to be redacted. - prepared_pdf_file_paths (List[str]): A list of paths to the PDF files prepared for redaction. - pdf_image_file_paths (List[str]): A list of paths to the PDF files converted to images for redaction. - chosen_redact_entities (List[str]): A list of entity types to redact from the files using the local model (spacy) with Microsoft Presidio. - chosen_redact_comprehend_entities (List[str]): A list of entity types to redact from files, chosen from the official list from AWS Comprehend service. - text_extraction_method (str): The method to use to extract text from documents. - in_allow_list (List[List[str]], optional): A list of allowed terms for redaction. Defaults to empty list. Can also be entered as a string path to a CSV file, or as a single column pandas dataframe. - in_deny_list (List[List[str]], optional): A list of denied terms for redaction. Defaults to empty list. Can also be entered as a string path to a CSV file, or as a single column pandas dataframe. - redact_whole_page_list (List[List[str]], optional): A list of whole page numbers for redaction. Defaults to empty list. Can also be entered as a string path to a CSV file, or as a single column pandas dataframe. - latest_file_completed (int, optional): The index of the last completed file. Defaults to 0. - combined_out_message (list, optional): A list to store output messages. Defaults to an empty list. - out_file_paths (list, optional): A list to store paths to the output files. Defaults to an empty list. - log_files_output_paths (list, optional): A list to store paths to the log files. Defaults to an empty list. - page_min (int, optional): The minimum page number to start redaction from. Defaults to 0 (first page). - page_max (int, optional): The maximum page number to end redaction at. Defaults to 0 (last page). - estimated_time_taken_state (float, optional): The estimated time taken for the redaction process. Defaults to 0.0. - handwrite_signature_checkbox (List[str], optional): A list of options for redacting handwriting and signatures. Defaults to ["Extract handwriting", "Extract signatures"]. - all_request_metadata_str (str, optional): A string containing all request metadata. Defaults to an empty string. - annotations_all_pages (List[dict], optional): A list of dictionaries containing all image annotations. Defaults to an empty list. - all_page_line_level_ocr_results_df (pd.DataFrame, optional): A DataFrame containing all line-level OCR results. Defaults to an empty DataFrame. - all_pages_decision_process_table (pd.DataFrame, optional): A DataFrame containing all decision process tables. Defaults to an empty DataFrame. - pymupdf_doc (optional): A list containing the PDF document object. Defaults to an empty list. - pii_identification_method (str, optional): The method to redact personal information. Either 'Local' (spacy model), or 'AWS Comprehend' (AWS Comprehend API). - max_fuzzy_spelling_mistakes_num (int, optional): The maximum number of spelling mistakes allowed in a searched phrase for fuzzy matching. Can range from 0-9. - match_fuzzy_whole_phrase_bool (bool, optional): A boolean where 'True' means that the whole phrase is fuzzy matched, and 'False' means that each word is fuzzy matched separately (excluding stop words). - aws_access_key_textbox (str, optional): AWS access key for account with Textract and Comprehend permissions. - aws_secret_key_textbox (str, optional): AWS secret key for account with Textract and Comprehend permissions. - annotate_max_pages (int, optional): Maximum page value for the annotation object. - review_file_state (pd.DataFrame, optional): Output review file dataframe. - output_folder (str, optional): Output folder for results. - document_cropboxes (List, optional): List of document cropboxes for the PDF. - page_sizes (List[dict], optional): List of dictionaries of PDF page sizes in PDF or image format. - textract_output_found (bool, optional): Boolean is true when a textract OCR output for the file has been found. - text_extraction_only (bool, optional): Boolean to determine if function should only extract text from the document, and not redact. - duplication_file_outputs (list, optional): List to allow for export to the duplication function page. - review_file_path (str, optional): The latest review file path created by the app - input_folder (str, optional): The custom input path, if provided - ocr_file_path (str, optional): The latest ocr file path created by the app. - all_page_line_level_ocr_results (list, optional): All line level text on the page with bounding boxes. - all_page_line_level_ocr_results_with_words (list, optional): All word level text on the page with bounding boxes. - all_page_line_level_ocr_results_with_words_df (pd.Dataframe, optional): All word level text on the page with bounding boxes as a dataframe. - chosen_local_ocr_model (str): Which local model is being used for OCR on images - uses the value of DEFAULT_LOCAL_OCR_MODEL by default, choices are "tesseract", "paddle" for PaddleOCR, or "hybrid-paddle" to combine both. - language (str, optional): The language of the text in the files. Defaults to English. - language (str, optional): The language to do AWS Comprehend calls. Defaults to value of language if not provided. - ocr_review_files (list, optional): A list of OCR review files to be used for the redaction process. Defaults to an empty list. - custom_llm_instructions (str, optional): Custom instructions for LLM-based entity detection. Defaults to an empty string. - inference_server_vlm_model (str, optional): The name of the inference server VLM model to use for OCR. Defaults to an empty string. - efficient_ocr (bool, optional): Boolean to determine whether to use efficient OCR. - efficient_ocr_min_words (int, optional): The minimum number of words on a page for efficient OCR. - save_page_ocr_visualisations (bool, optional): Boolean to determine whether to save page OCR visualisations. Defaults to SAVE_PAGE_OCR_VISUALISATIONS. - prepare_images (bool, optional): Boolean to determine whether to load images for the PDF. - RETURN_REDACTED_PDF (bool, optional): Boolean to determine whether to return a redacted PDF at the end of the redaction process. - RETURN_PDF_FOR_REVIEW (bool, optional): Boolean to determine whether to return a review PDF at the end of the redaction process. - progress (gr.Progress, optional): A progress tracker for the redaction process. Defaults to a Progress object with track_tqdm set to True. """ tic = time.perf_counter() out_message = "" pdf_file_name_with_ext = "" pdf_file_name_without_ext = "" page_break_return = False blank_request_metadata = list() custom_recogniser_word_list_flat = list() # Ensure all_request_metadata_str is a string (handle case where list might be passed) if isinstance(all_request_metadata_str, list): all_request_metadata_str = ( "\n".join(str(item) for item in all_request_metadata_str) if all_request_metadata_str else "" ) all_textract_request_metadata = ( all_request_metadata_str.split("\n") if all_request_metadata_str else [] ) task_textbox = "redact" selection_element_results_list_df = pd.DataFrame() form_key_value_results_list_df = pd.DataFrame() out_review_pdf_file_path = "" out_redacted_pdf_file_path = "" if not ocr_review_files: ocr_review_files = list() current_loop_page = 0 # When EFFICIENT_OCR uses simple text extraction, OCR results are in PDF points; when # OCR path runs, they are in image pixels. Used so divide_coordinates_by_page_sizes # uses mediabox (not image) dimensions when appropriate. ocr_results_use_pdf_points = None # When EFFICIENT_OCR runs both paths, page numbers (1-based) that used text extraction # (so their coordinates are in PDF points). Passed as pages_in_pdf_points for per-page division. pages_with_text_extraction_1based = None efficient_ocr_min_words = ( int(efficient_ocr_min_words) if efficient_ocr_min_words is not None else EFFICIENT_OCR_MIN_WORDS ) if efficient_ocr_min_image_coverage_fraction is None: efficient_ocr_min_image_coverage_fraction = float( EFFICIENT_OCR_MIN_IMAGE_COVERAGE_FRACTION ) else: efficient_ocr_min_image_coverage_fraction = float( efficient_ocr_min_image_coverage_fraction ) if efficient_ocr_min_embedded_image_px is None: efficient_ocr_min_embedded_image_px = int(EFFICIENT_OCR_MIN_EMBEDDED_IMAGE_PX) else: efficient_ocr_min_embedded_image_px = max( 0, int(efficient_ocr_min_embedded_image_px) ) if efficient_ocr is None: efficient_ocr = EFFICIENT_OCR # CLI mode may provide options to enter method names in a different format print("Text extraction method requested:", text_extraction_method) if text_extraction_method == "AWS Textract": text_extraction_method = TEXTRACT_TEXT_EXTRACT_OPTION if text_extraction_method == "Local OCR": text_extraction_method = LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION print("Performing local OCR with" + chosen_local_ocr_model + " model.") if text_extraction_method == "Local text": text_extraction_method = SELECTABLE_TEXT_EXTRACT_OPTION # Default chosen_llm_entities to chosen_redact_comprehend_entities if not provided if chosen_llm_entities is None: chosen_llm_entities = chosen_redact_comprehend_entities # Auto-include CUSTOM_FUZZY in local entity list when fuzzy matching is enabled chosen_redact_entities = list(chosen_redact_entities or []) if (max_fuzzy_spelling_mistakes_num or 0) > 0: if "CUSTOM_FUZZY" not in chosen_redact_entities: chosen_redact_entities.append("CUSTOM_FUZZY") if "CUSTOM_FUZZY" not in chosen_redact_comprehend_entities: chosen_redact_comprehend_entities.append("CUSTOM_FUZZY") if "CUSTOM_FUZZY" not in chosen_llm_entities: chosen_llm_entities.append("CUSTOM_FUZZY") # Any entity starting with CUSTOM_VLM (e.g. CUSTOM_VLM_FACES, CUSTOM_VLM_SIGNATURE) requires # image-based analysis; when user selected simple text extraction we still run image path for these. _has_any_custom_vlm_entity = any( str(e).startswith("CUSTOM_VLM") for lst in ( chosen_redact_entities, chosen_redact_comprehend_entities or [], chosen_llm_entities or [], ) for e in lst ) if pii_identification_method == "None": pii_identification_method = NO_REDACTION_PII_OPTION print("PII identification method requested:", pii_identification_method) # Normalise the output folder path separator (handles Windows backslash paths) if not output_folder.endswith(("/", os.sep)): output_folder = output_folder + "/" # Use provided language or default language = language or DEFAULT_LANGUAGE if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: if language not in textract_language_choices: out_message = f"Language '{language}' is not supported by AWS Textract. Please select a different language." raise Warning(out_message) elif pii_identification_method == AWS_PII_OPTION: if language not in aws_comprehend_language_choices: out_message = f"Language '{language}' is not supported by AWS Comprehend. Please select a different language." raise Warning(out_message) if all_page_line_level_ocr_results_with_words_df is None: all_page_line_level_ocr_results_with_words_df = pd.DataFrame() # Create copies of out_file_path objects to avoid overwriting each other on append actions out_file_paths = out_file_paths.copy() log_files_output_paths = log_files_output_paths.copy() # Ensure all_pages_decision_process_table is in correct format for downstream processes if isinstance(all_pages_decision_process_table, list): if not all_pages_decision_process_table: all_pages_decision_process_table = pd.DataFrame( columns=[ "image_path", "page", "label", "xmin", "xmax", "ymin", "ymax", "boundingBox", "text", "start", "end", "score", "id", ] ) elif isinstance(all_pages_decision_process_table, pd.DataFrame): if all_pages_decision_process_table.empty: all_pages_decision_process_table = pd.DataFrame( columns=[ "image_path", "page", "label", "xmin", "xmax", "ymin", "ymax", "boundingBox", "text", "start", "end", "score", "id", ] ) # Initialize per-run counters/state (these are still returned as outputs) latest_file_completed = 0 current_loop_page = 0 out_file_paths = list() log_files_output_paths = list() estimated_time_taken_state = 0 comprehend_query_number = 0 total_textract_query_number = 0 llm_model_name = "" llm_total_input_tokens = 0 llm_total_output_tokens = 0 vlm_model_name = "" vlm_total_input_tokens = 0 vlm_total_output_tokens = 0 # elif current_loop_page == 0: # comprehend_query_number = 0 # Do not reset total_textract_query_number here: EFFICIENT_OCR and other paths # accumulate Textract count during the run; resetting would overwrite the # value when the run completes and report 0 to the UI. # If not the first time around, and the current page loop has been set to a huge number (been through all pages), reset current page to 0 # elif (first_loop_state is False) & (current_loop_page == 999): # current_loop_page = 0 # total_textract_query_number = 0 # comprehend_query_number = 0 if not file_paths: raise Exception("No files to redact") if prepared_pdf_file_paths: review_out_file_paths = [prepared_pdf_file_paths[0]] else: review_out_file_paths = list() # Choose the correct file to prepare # Normalize so we support both path strings and Gradio file objects (dict with "name" or object with .name) if isinstance(file_paths, str): file_paths_list = [os.path.abspath(file_paths)] elif isinstance(file_paths, dict): file_paths = file_paths["name"] file_paths_list = [os.path.abspath(file_paths)] else: # List from Gradio: can be list of path strings or list of file objects (dict / object with .name) def _file_item_to_path(item): if isinstance(item, str): return item if isinstance(item, dict): return item.get("name") or item.get("path") or "" return getattr(item, "name", None) or getattr(item, "path", None) or "" file_paths_list = [_file_item_to_path(f) for f in file_paths if f is not None] # Resolve to absolute paths so paths work consistently in Docker (cwd may differ) file_paths_list = [ os.path.abspath(p) for p in file_paths_list if p and str(p).strip() ] if len(file_paths_list) > MAX_SIMULTANEOUS_FILES: out_message = f"Number of files to redact is greater than {MAX_SIMULTANEOUS_FILES}. Please submit a smaller number of files." print(out_message) raise Exception(out_message) valid_extensions = {".pdf", ".jpg", ".jpeg", ".png"} # Filter only files with valid extensions. Currently only allowing one file to be redacted at a time # Filter the file_paths_list to include only files with valid extensions filtered_files = [ file for file in file_paths_list if os.path.splitext(file)[1].lower() in valid_extensions ] # Check if any files were found and assign to file_paths_list file_paths_list = filtered_files if filtered_files else [] # print("Latest file completed:", latest_file_completed) # If latest_file_completed is used, get the specific file if not isinstance(file_paths, (str, dict)): file_paths_loop = ( [file_paths_list[int(latest_file_completed)]] if len(file_paths_list) > latest_file_completed else [] ) else: file_paths_loop = file_paths_list latest_file_completed = int(latest_file_completed) if isinstance(file_paths, str): number_of_files = 1 else: number_of_files = len(file_paths_list) # If we have already redacted the last file, return the input out_message and file list to the relevant outputs if latest_file_completed >= number_of_files: print("Completed last file, performing final checks") progress(0.95, "Completed last file, performing final checks") current_loop_page = 0 if isinstance(combined_out_message, list): combined_out_message = "\n".join(combined_out_message) _sep = "\n" if combined_out_message else "" if isinstance(out_message, list) and out_message: combined_out_message = combined_out_message + _sep + "\n".join(out_message) elif out_message: combined_out_message = combined_out_message + _sep + out_message from tools.secure_regex_utils import safe_remove_leading_newlines combined_out_message = safe_remove_leading_newlines(combined_out_message) end_message = "\n\nPlease review and modify the suggested redaction outputs on the 'Review redactions' tab of the app (you can find this under the introduction text at the top of the page)." if end_message not in combined_out_message: combined_out_message = combined_out_message + end_message # Only send across review file if redaction has been done if pii_identification_method != NO_REDACTION_PII_OPTION: if len(review_out_file_paths) == 1: if review_file_path: review_out_file_paths.append(review_file_path) # Use document page count when available (pymupdf_doc is set by state from last run). # Default to 1 only when we have no valid document (e.g. initial state pymupdf_doc=list(), # or no files were processed in this session). number_of_pages = 1 if pymupdf_doc is not None and not isinstance(pymupdf_doc, list): if hasattr(pymupdf_doc, "page_count"): _cnt = pymupdf_doc.page_count if _cnt and _cnt > 0: number_of_pages = _cnt if number_of_pages and number_of_pages > 0: if total_textract_query_number > number_of_pages: total_textract_query_number = number_of_pages annotate_max_pages = number_of_pages annotate_max_pages_bottom = number_of_pages # No files to process: total page count stays 0 for usage logging total_pages_for_ui = number_of_pages if number_of_pages else 1 print("number_of_pages:", number_of_pages) sum_numbers_before_seconds(combined_out_message) print(combined_out_message) gr.Info(combined_out_message) page_break_return = True return ( combined_out_message, out_file_paths, out_file_paths, latest_file_completed, log_files_output_paths, log_files_output_paths, estimated_time_taken_state, all_request_metadata_str, pymupdf_doc, annotations_all_pages, current_loop_page, page_break_return, all_page_line_level_ocr_results_df, all_pages_decision_process_table, comprehend_query_number, review_out_file_paths, annotate_max_pages, annotate_max_pages, prepared_pdf_file_paths, pdf_image_file_paths, review_file_state, page_sizes, duplication_file_path_outputs, duplication_file_path_outputs, # Write ocr_file_path to in_duplicate_pages duplication_file_path_outputs, # Write ocr_file_path to in_summarisation_ocr_files review_file_path, total_textract_query_number, ocr_file_path, ( all_page_line_level_ocr_results if all_page_line_level_ocr_results else gr.update() ), ( all_page_line_level_ocr_results_with_words if all_page_line_level_ocr_results_with_words else gr.update() ), ( all_page_line_level_ocr_results_with_words_df if ( isinstance( all_page_line_level_ocr_results_with_words_df, pd.DataFrame ) and not all_page_line_level_ocr_results_with_words_df.empty ) else gr.update() ), review_file_state, task_textbox, ocr_review_files, vlm_model_name, vlm_total_input_tokens, vlm_total_output_tokens, llm_model_name, llm_total_input_tokens, llm_total_output_tokens, total_pages_for_ui, ) else: # ocr_review_files will be replaced by latest file output ocr_review_files = list() # if first_loop_state == False: # Prepare documents and images as required if they don't already exist prepare_images_flag = None # Determines whether to call prepare_image_or_pdf # When Textract + Extract signatures/forms/tables (not Face detection alone), we run all # pages through redact_image_pdf (skip EFFICIENT_OCR). Face detection keeps EFFICIENT_OCR; # CUSTOM_VLM_FACES then runs only on OCR-classified pages (see EFFICIENT_OCR VLM block). _textract_needs_full_analysis_global = ( text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and any( opt in (handwrite_signature_checkbox or []) for opt in ( "Extract signatures", "Extract forms", "Extract tables", ) ) ) # After EFFICIENT_OCR, run CUSTOM_VLM passes when selected or Textract + Face detection. # Routing: CUSTOM_VLM_SIGNATURE = full-document images; CUSTOM_VLM_FACES = OCR pages only. _run_vlm_pass_after_all_pages = _has_any_custom_vlm_entity or ( text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and "Face detection" in (handwrite_signature_checkbox or []) ) # When user selected simple text extraction but any CUSTOM_VLM_* entity (face, signature, etc.), # run all pages through redact_image_pdf so VLM-based detection can take place. _custom_vlm_requires_image_global = ( text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION and _has_any_custom_vlm_entity ) if ( efficient_ocr and file_paths_loop and not _textract_needs_full_analysis_global and not _custom_vlm_requires_image_global ): # Defer image load: only create images for pages that need OCR, after word check first_file = ( file_paths_loop[0] if isinstance(file_paths_loop[0], str) else getattr(file_paths_loop[0], "name", "") ) if first_file and is_pdf(first_file): print( "EFFICIENT_OCR enabled: skipping initial image load; images will be created only for pages that need OCR." ) prepare_images_flag = False if ( prepare_images_flag is None and textract_output_found and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION ): print("Existing Textract outputs found, not preparing images or documents.") prepare_images_flag = False # return # No need to call `prepare_image_or_pdf`, exit early elif ( prepare_images_flag is None and text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION and not _custom_vlm_requires_image_global ): print("Running text extraction analysis, not preparing images.") prepare_images_flag = False elif prepare_images_flag is None and prepare_images and not pdf_image_file_paths: print("Prepared PDF images not found, loading from file") prepare_images_flag = True elif prepare_images_flag is None and not prepare_images: print("Not loading images for file") prepare_images_flag = False elif prepare_images_flag is None: print("Loading images for file") prepare_images_flag = True # Call prepare_image_or_pdf only if needed if prepare_images_flag is not None: ( out_message, prepared_pdf_file_paths, pdf_image_file_paths, annotate_max_pages, annotate_max_pages_bottom, pymupdf_doc, annotations_all_pages, review_file_state, document_cropboxes, page_sizes, textract_output_found, all_img_details_state, placeholder_ocr_results_df, local_ocr_output_found_checkbox, all_page_line_level_ocr_results_with_words_df, ) = prepare_image_or_pdf( file_paths_loop, text_extraction_method, all_page_line_level_ocr_results_df, all_page_line_level_ocr_results_with_words_df, 0, out_message, True, annotate_max_pages, annotations_all_pages, prepare_for_review=False, in_fully_redacted_list=redact_whole_page_list, output_folder=output_folder, prepare_images=prepare_images_flag, page_sizes=page_sizes, pymupdf_doc=pymupdf_doc, input_folder=input_folder, page_min=page_min, page_max=page_max, ) page_sizes_df = pd.DataFrame(page_sizes) if page_sizes_df.empty: page_sizes_df = pd.DataFrame( columns=[ "page", "image_path", "image_width", "image_height", "mediabox_width", "mediabox_height", "cropbox_width", "cropbox_height", "original_cropbox", ] ) page_sizes_df[["page"]] = page_sizes_df[["page"]].apply( pd.to_numeric, errors="coerce" ) page_sizes = page_sizes_df.to_dict(orient="records") number_of_pages = pymupdf_doc.page_count # page_max 0 means "last page of document" if page_min == 0 and page_max == 0: number_of_pages_to_process = number_of_pages elif page_max == 0: number_of_pages_to_process = (number_of_pages - page_min) + 1 else: number_of_pages_to_process = (page_max - page_min) + 1 if number_of_pages_to_process > MAX_DOC_PAGES: out_message = f"Number of pages to process is greater than {MAX_DOC_PAGES}. Please submit a smaller document." print(out_message) raise Exception(out_message) # If we have reached the last page, return message and outputs if current_loop_page >= number_of_pages_to_process: print("Reached last page of document to process") if total_textract_query_number > number_of_pages: total_textract_query_number = number_of_pages # Reset current loop page to 0 current_loop_page = 0 if out_message: combined_out_message = combined_out_message + "\n" + out_message # Only send across review file if redaction has been done if pii_identification_method != NO_REDACTION_PII_OPTION: # If only pdf currently in review outputs, add on the latest review file if len(review_out_file_paths) == 1: if review_file_path: review_out_file_paths.append(review_file_path) page_break_return = False return ( combined_out_message, out_file_paths, out_file_paths, latest_file_completed, log_files_output_paths, log_files_output_paths, estimated_time_taken_state, all_request_metadata_str, pymupdf_doc, annotations_all_pages, current_loop_page, page_break_return, all_page_line_level_ocr_results_df, all_pages_decision_process_table, comprehend_query_number, review_out_file_paths, annotate_max_pages, annotate_max_pages, prepared_pdf_file_paths, pdf_image_file_paths, review_file_state, page_sizes, duplication_file_path_outputs, duplication_file_path_outputs, duplication_file_path_outputs, # Write ocr_file_path to in_summarisation_ocr_files review_file_path, total_textract_query_number, ocr_file_path, all_page_line_level_ocr_results, all_page_line_level_ocr_results_with_words, all_page_line_level_ocr_results_with_words_df, review_file_state, task_textbox, ocr_review_files, vlm_model_name, vlm_total_input_tokens, vlm_total_output_tokens, llm_model_name, llm_total_input_tokens, llm_total_output_tokens, number_of_pages, ) ### Load/create allow list, deny list, and whole page redaction list # If string, assume file path if isinstance(in_allow_list, str): if in_allow_list: in_allow_list = pd.read_csv(in_allow_list, header=None) # Handle both DataFrame (legacy) and list (new Dropdown format) if isinstance(in_allow_list, pd.DataFrame): if not in_allow_list.empty: in_allow_list_flat = in_allow_list.iloc[:, 0].tolist() else: in_allow_list_flat = list() elif isinstance(in_allow_list, list): # Dropdown component returns a list directly in_allow_list_flat = ( [str(item) for item in in_allow_list if item] if in_allow_list else list() ) else: in_allow_list_flat = list() ### Load/create deny list # If string, assume file path if isinstance(in_deny_list, str): if in_deny_list: in_deny_list = pd.read_csv(in_deny_list, header=None) # Handle both DataFrame (legacy) and list (new Dropdown format) if isinstance(in_deny_list, pd.DataFrame): if not in_deny_list.empty: custom_recogniser_word_list_flat = in_deny_list.iloc[:, 0].tolist() else: custom_recogniser_word_list_flat = list() # Sort the strings in order from the longest string to the shortest custom_recogniser_word_list_flat = sorted( custom_recogniser_word_list_flat, key=len, reverse=True ) elif isinstance(in_deny_list, list): # Dropdown component returns a list directly custom_recogniser_word_list_flat = ( [str(item) for item in in_deny_list if item] if in_deny_list else list() ) # Sort the strings in order from the longest string to the shortest custom_recogniser_word_list_flat = sorted( custom_recogniser_word_list_flat, key=len, reverse=True ) else: custom_recogniser_word_list_flat = list() ### Load/create whole page redaction list # If string, assume file path if isinstance(redact_whole_page_list, str): if redact_whole_page_list: redact_whole_page_list = pd.read_csv(redact_whole_page_list, header=None) # Handle both DataFrame (legacy) and list (new Dropdown format) if isinstance(redact_whole_page_list, pd.DataFrame): if not redact_whole_page_list.empty: try: redact_whole_page_list_flat = ( redact_whole_page_list.iloc[:, 0].astype(int).tolist() ) except Exception as e: print( "Could not convert whole page redaction data to number list due to:", e, ) redact_whole_page_list_flat = redact_whole_page_list.iloc[:, 0].tolist() else: redact_whole_page_list_flat = list() elif isinstance(redact_whole_page_list, list): # Dropdown component returns a list directly if redact_whole_page_list: try: # Try to convert to integers for page numbers redact_whole_page_list_flat = [ int(item) for item in redact_whole_page_list if item ] except (ValueError, TypeError) as e: print( "Could not convert whole page redaction data to number list due to:", e, ) # Fall back to string list if conversion fails redact_whole_page_list_flat = [ str(item) for item in redact_whole_page_list if item ] else: redact_whole_page_list_flat = list() else: redact_whole_page_list_flat = list() ### Load/create PII identification method # Try to connect to AWS services directly only if RUN_AWS_FUNCTIONS environmental variable is True, otherwise an environment variable or direct textbox input is needed. if pii_identification_method == AWS_PII_OPTION: if RUN_AWS_FUNCTIONS and PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS: print("Connecting to Comprehend via existing SSO connection") comprehend_client = boto3.client("comprehend", region_name=AWS_REGION) elif aws_access_key_textbox and aws_secret_key_textbox: print( "Connecting to Comprehend using AWS access key and secret keys from user input." ) comprehend_client = boto3.client( "comprehend", aws_access_key_id=aws_access_key_textbox, aws_secret_access_key=aws_secret_key_textbox, region_name=AWS_REGION, ) elif RUN_AWS_FUNCTIONS: print("Connecting to Comprehend via existing SSO connection") comprehend_client = boto3.client("comprehend", region_name=AWS_REGION) elif AWS_ACCESS_KEY and AWS_SECRET_KEY: print("Getting Comprehend credentials from environment variables") comprehend_client = boto3.client( "comprehend", aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY, region_name=AWS_REGION, ) else: comprehend_client = "" out_message = "Cannot connect to AWS Comprehend service. Please provide access keys under Textract settings on the Redaction settings tab, or choose another PII identification method." print(out_message) raise Exception(out_message) else: comprehend_client = "" # Try to connect to AWS Bedrock Runtime Client if using LLM-based PII detection if pii_identification_method == AWS_LLM_PII_OPTION or ( text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and hybrid_textract_bedrock_vlm ): if RUN_AWS_FUNCTIONS and PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS: print("Connecting to Bedrock via existing SSO connection") bedrock_runtime = boto3.client("bedrock-runtime", region_name=AWS_REGION) elif aws_access_key_textbox and aws_secret_key_textbox: print( "Connecting to Bedrock using AWS access key and secret keys from user input." ) bedrock_runtime = boto3.client( "bedrock-runtime", aws_access_key_id=aws_access_key_textbox, aws_secret_access_key=aws_secret_key_textbox, region_name=AWS_REGION, ) elif RUN_AWS_FUNCTIONS: print("Connecting to Bedrock via existing SSO connection") bedrock_runtime = boto3.client("bedrock-runtime", region_name=AWS_REGION) elif AWS_ACCESS_KEY and AWS_SECRET_KEY: print("Getting Bedrock credentials from environment variables") bedrock_runtime = boto3.client( "bedrock-runtime", aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY, region_name=AWS_REGION, ) else: bedrock_runtime = None out_message = "Cannot connect to AWS Bedrock service. Please provide access keys under Textract settings on the Redaction settings tab, or choose another PII identification method." print(out_message) raise Exception(out_message) elif pii_identification_method == INFERENCE_SERVER_PII_OPTION: # For inference server, we don't need bedrock_runtime bedrock_runtime = None print("Using inference server for PII detection") elif pii_identification_method == LOCAL_TRANSFORMERS_LLM_PII_OPTION: # For local transformers LLM, we don't need bedrock_runtime bedrock_runtime = None print("Using local transformers LLM for PII detection") else: bedrock_runtime = None # If using AWS Comprehend and CUSTOM_VLM_FACES or CUSTOM_VLM_SIGNATURE is selected, # ensure bedrock_runtime is available only when CUSTOM_VLM_BACKEND is bedrock_vlm. if ( pii_identification_method == AWS_PII_OPTION and bedrock_runtime is None and CUSTOM_VLM_BACKEND == "bedrock_vlm" and ( "CUSTOM_VLM_FACES" in chosen_redact_comprehend_entities or "CUSTOM_VLM_SIGNATURE" in chosen_redact_comprehend_entities ) ): print( "CUSTOM_VLM_FACES or CUSTOM_VLM_SIGNATURE selected with AWS Comprehend. Connecting to Bedrock for additional detection." ) if RUN_AWS_FUNCTIONS and PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS: print("Connecting to Bedrock via existing SSO connection for VLM detection") bedrock_runtime = boto3.client("bedrock-runtime", region_name=AWS_REGION) elif aws_access_key_textbox and aws_secret_key_textbox: print( "Connecting to Bedrock using AWS access key and secret keys from user input for VLM detection." ) bedrock_runtime = boto3.client( "bedrock-runtime", aws_access_key_id=aws_access_key_textbox, aws_secret_access_key=aws_secret_key_textbox, region_name=AWS_REGION, ) elif RUN_AWS_FUNCTIONS: print("Connecting to Bedrock via existing SSO connection for VLM detection") bedrock_runtime = boto3.client("bedrock-runtime", region_name=AWS_REGION) elif AWS_ACCESS_KEY and AWS_SECRET_KEY: print( "Getting Bedrock credentials from environment variables for VLM detection" ) bedrock_runtime = boto3.client( "bedrock-runtime", aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY, region_name=AWS_REGION, ) else: out_message = "Cannot connect to AWS Bedrock service for VLM detection. Please provide access keys under Textract settings on the Redaction settings tab." print(out_message) raise Exception(out_message) # Try to connect to AWS Textract Client if using that text extraction method if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: if RUN_AWS_FUNCTIONS and PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS: print("Connecting to Textract via existing SSO connection") textract_client = boto3.client("textract", region_name=AWS_REGION) elif aws_access_key_textbox and aws_secret_key_textbox: print( "Connecting to Textract using AWS access key and secret keys from user input." ) textract_client = boto3.client( "textract", aws_access_key_id=aws_access_key_textbox, aws_secret_access_key=aws_secret_key_textbox, region_name=AWS_REGION, ) elif RUN_AWS_FUNCTIONS: print("Connecting to Textract via existing SSO connection") textract_client = boto3.client("textract", region_name=AWS_REGION) elif AWS_ACCESS_KEY and AWS_SECRET_KEY: print("Getting Textract credentials from environment variables.") textract_client = boto3.client( "textract", aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY, region_name=AWS_REGION, ) elif textract_output_found is True: print( "Existing Textract data found for file, no need to connect to AWS Textract" ) textract_client = boto3.client("textract", region_name=AWS_REGION) else: textract_client = "" out_message = "Cannot connect to AWS Textract service." print(out_message) raise Exception(out_message) else: textract_client = "" # Try to connect to cloud VLM clients if using cloud VLM OCR gemini_client = None gemini_config = None azure_openai_client = None if text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION: # Use the same bedrock_runtime that may have been created for LLM PII detection if bedrock_runtime is None: if RUN_AWS_FUNCTIONS and PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS: print("Connecting to Bedrock via existing SSO connection for VLM OCR") bedrock_runtime = boto3.client( "bedrock-runtime", region_name=AWS_REGION ) elif aws_access_key_textbox and aws_secret_key_textbox: print( "Connecting to Bedrock using AWS access key and secret keys from user input for VLM OCR." ) bedrock_runtime = boto3.client( "bedrock-runtime", aws_access_key_id=aws_access_key_textbox, aws_secret_access_key=aws_secret_key_textbox, region_name=AWS_REGION, ) elif RUN_AWS_FUNCTIONS: print("Connecting to Bedrock via existing SSO connection for VLM OCR") bedrock_runtime = boto3.client( "bedrock-runtime", region_name=AWS_REGION ) elif AWS_ACCESS_KEY and AWS_SECRET_KEY: print( "Getting Bedrock credentials from environment variables for VLM OCR" ) bedrock_runtime = boto3.client( "bedrock-runtime", aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY, region_name=AWS_REGION, ) else: bedrock_runtime = None out_message = "Cannot connect to AWS Bedrock service for VLM OCR. Please provide access keys under Textract settings on the Redaction settings tab." print(out_message) raise Exception(out_message) # If using image-based extraction (Textract, Bedrock VLM, etc.) or simple text + any CUSTOM_VLM_* # entity, ensure bedrock_runtime is available only when actually needed: Face detection # (Textract) uses Bedrock; CUSTOM_VLM_* uses Bedrock only when CUSTOM_VLM_BACKEND is bedrock_vlm. _image_based_extraction = text_extraction_method in ( TEXTRACT_TEXT_EXTRACT_OPTION, BEDROCK_VLM_TEXT_EXTRACT_OPTION, LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION, GEMINI_VLM_TEXT_EXTRACT_OPTION, AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION, ) _needs_bedrock_for_vlm = "Face detection" in ( handwrite_signature_checkbox or [] ) or (_has_any_custom_vlm_entity and CUSTOM_VLM_BACKEND == "bedrock_vlm") if ( (_image_based_extraction or _custom_vlm_requires_image_global) and bedrock_runtime is None and _needs_bedrock_for_vlm ): print( "CUSTOM_VLM entity (face/signature/etc.) or Face detection enabled. Connecting to Bedrock for additional detection." ) if RUN_AWS_FUNCTIONS and PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS: print("Connecting to Bedrock via existing SSO connection for VLM detection") bedrock_runtime = boto3.client("bedrock-runtime", region_name=AWS_REGION) elif aws_access_key_textbox and aws_secret_key_textbox: print( "Connecting to Bedrock using AWS access key and secret keys from user input for VLM detection." ) bedrock_runtime = boto3.client( "bedrock-runtime", aws_access_key_id=aws_access_key_textbox, aws_secret_access_key=aws_secret_key_textbox, region_name=AWS_REGION, ) elif RUN_AWS_FUNCTIONS: print("Connecting to Bedrock via existing SSO connection for VLM detection") bedrock_runtime = boto3.client("bedrock-runtime", region_name=AWS_REGION) elif AWS_ACCESS_KEY and AWS_SECRET_KEY: print( "Getting Bedrock credentials from environment variables for VLM detection" ) bedrock_runtime = boto3.client( "bedrock-runtime", aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY, region_name=AWS_REGION, ) else: out_message = "Cannot connect to AWS Bedrock service for VLM detection. Please provide access keys under Textract settings on the Redaction settings tab." print(out_message) raise Exception(out_message) elif text_extraction_method == GEMINI_VLM_TEXT_EXTRACT_OPTION: from tools.llm_funcs import construct_gemini_generative_model try: gemini_client, gemini_config = construct_gemini_generative_model( in_api_key="", # Will use environment variable temperature=0.0, # Use low temperature for OCR model_choice=CLOUD_VLM_MODEL_CHOICE, system_prompt="", # No system prompt needed for OCR max_tokens=4096, # Reasonable default for OCR ) print("Connected to Google Gemini for VLM OCR") except Exception as e: out_message = f"Cannot connect to Google Gemini service for VLM OCR: {e}. Please ensure GEMINI_API_KEY is set." print(out_message) raise Exception(out_message) elif text_extraction_method == AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION: from tools.llm_funcs import construct_azure_client try: azure_openai_client, _ = construct_azure_client( in_api_key="", # Will use environment variable endpoint="", # Will use environment variable ) print("Connected to Azure/OpenAI for VLM OCR") except Exception as e: out_message = f"Cannot connect to Azure/OpenAI service for VLM OCR: {e}. Please ensure AZURE_OPENAI_API_KEY and AZURE_OPENAI_ENDPOINT are set." print(out_message) raise Exception(out_message) ### Language check - check if selected language packs exist try: if ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and chosen_local_ocr_model == "tesseract" ): if language != "en": progress( 0.1, desc=f"Downloading Tesseract language pack for {language}" ) download_tesseract_lang_pack(language) if language != "en": progress(0.1, desc=f"Loading SpaCy model for {language}") load_spacy_model(language) except Exception as e: print(f"Error downloading language packs for {language}: {e}") raise Exception(f"Error downloading language packs for {language}: {e}") # Check if output_folder exists, create it if it doesn't if not os.path.exists(output_folder): os.makedirs(output_folder) progress(0.2, desc="Extracting text and redacting document") all_pages_decision_process_table = pd.DataFrame( columns=[ "image_path", "page", "label", "xmin", "xmax", "ymin", "ymax", "boundingBox", "text", "start", "end", "score", "id", ] ) all_page_line_level_ocr_results_df = pd.DataFrame(columns=LINE_LEVEL_OCR_DF_COLUMNS) # Run through file loop, redact each file at a time for file in file_paths_loop: # Get a string file path if isinstance(file, str): file_path = file else: file_path = file.name if file_path: pdf_file_name_without_ext = get_file_name_without_type(file_path) pdf_file_name_with_ext = os.path.basename(file_path) efficient_ocr_text_pages = ( None # set when efficient_ocr used; for combined_out_message ) efficient_ocr_ocr_pages = None is_a_pdf = is_pdf(file_path) is True if ( is_a_pdf is False and text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION ): # If user has not submitted a pdf, assume it's an image print( "File is not a PDF, assuming that image analysis needs to be used." ) text_extraction_method = LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION else: out_message = "No file selected" print(out_message) raise Exception(out_message) # Output file paths names orig_pdf_file_path = output_folder + pdf_file_name_without_ext # Load in all_ocr_results_with_words if it exists as a file path and doesn't exist already if text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION: file_ending = "local_text" elif text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION: file_ending = "local_ocr" elif text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: file_ending = "textract" elif text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION: file_ending = "bedrock_vlm" elif text_extraction_method == GEMINI_VLM_TEXT_EXTRACT_OPTION: file_ending = "gemini_vlm" elif text_extraction_method == AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION: file_ending = "azure_openai_vlm" else: print( "No valid text extraction method found. Defaulting to local text extraction." ) text_extraction_method = SELECTABLE_TEXT_EXTRACT_OPTION file_ending = "local_text" all_page_line_level_ocr_results_with_words_json_file_path = ( output_folder + pdf_file_name_without_ext + "_ocr_results_with_words_" + file_ending + ".json" ) if not all_page_line_level_ocr_results_with_words: if ( not overwrite_existing_ocr_results and local_ocr_output_found_checkbox is True and os.path.exists( all_page_line_level_ocr_results_with_words_json_file_path ) ): ( all_page_line_level_ocr_results_with_words, is_missing, log_files_output_paths, ) = load_and_convert_ocr_results_with_words_json( all_page_line_level_ocr_results_with_words_json_file_path, log_files_output_paths, page_sizes_df, ) # original_all_page_line_level_ocr_results_with_words = all_page_line_level_ocr_results_with_words.copy() # Remove any existing review_file paths from the review file outputs # EFFICIENT_OCR: two-step process per page - try selectable text first, OCR only if needed. # When text extraction is selectable-text only, skip EFFICIENT_OCR checks and run only redact_text_pdf. # When Textract is selected with Extract signatures/forms/tables (not Face alone), skip # EFFICIENT_OCR so all pages go through redact_image_pdf (full Textract analysis). if ( efficient_ocr and is_pdf(file_path) and text_extraction_method != SELECTABLE_TEXT_EXTRACT_OPTION and not _textract_needs_full_analysis_global ): print( "Redacting file " + pdf_file_name_with_ext + " using efficient OCR (text extraction first, OCR fallback per page)" ) # OCR method for pages that have no selectable text ocr_fallback_method = ( text_extraction_method if text_extraction_method in ( LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION, TEXTRACT_TEXT_EXTRACT_OPTION, BEDROCK_VLM_TEXT_EXTRACT_OPTION, GEMINI_VLM_TEXT_EXTRACT_OPTION, AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION, ) else LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION ) start_page_0 = (page_min - 1) if page_min > 0 else 0 end_page_0 = start_page_0 + number_of_pages_to_process all_pages_1based = list(range(start_page_0 + 1, end_page_0 + 1)) # Try to reuse existing OCR results (from a previous run) for the # Efficient OCR word-count classification pass, so we do not # re-extract text for all pages in subsequent sessions. use_cached_word_counts = False all_page_line_level_ocr_results_with_words_first = [] extraction_results = None if not overwrite_existing_ocr_results: if ocr_fallback_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION: cached_ocr_path = ( output_folder + pdf_file_name_without_ext + "_ocr_results_with_words_local_ocr.json" ) if os.path.exists(cached_ocr_path): print( "EFFICIENT_OCR: Using existing local OCR results for word-count classification." ) ( all_page_line_level_ocr_results_with_words_first, _, log_files_output_paths, ) = load_and_convert_ocr_results_with_words_json( cached_ocr_path, log_files_output_paths, page_sizes_df, ) use_cached_word_counts = bool( all_page_line_level_ocr_results_with_words_first ) elif ocr_fallback_method == TEXTRACT_TEXT_EXTRACT_OPTION: # Use OCR-results-with-words file (same format as local OCR), not raw # Textract JSON, so _word_count_by_page_from_ocr_results_with_words gets # a list of dicts with "page" and "results". cached_ocr_path = ( output_folder + pdf_file_name_without_ext + "_ocr_results_with_words_textract.json" ) if os.path.exists(cached_ocr_path): print( "EFFICIENT_OCR: Using existing Textract OCR results for word-count classification." ) ( all_page_line_level_ocr_results_with_words_first, _, log_files_output_paths, ) = load_and_convert_ocr_results_with_words_json( cached_ocr_path, log_files_output_paths, page_sizes_df, ) use_cached_word_counts = bool( all_page_line_level_ocr_results_with_words_first ) if use_cached_word_counts: page_word_counts = _word_count_by_page_from_ocr_results_with_words( all_page_line_level_ocr_results_with_words_first, all_pages_1based, ) else: # EFFICIENT_OCR: use redact_text_pdf (extraction only) on all pages to get word counts; # no separate check loop—extraction doubles as the check. Then classify pages by threshold. progress( 0.4, desc="Efficient OCR: Extracting text on all pages (word-count check)", ) ( pymupdf_doc, _, _, annotations_all_pages, _, page_break_return, comprehend_query_number, all_page_line_level_ocr_results_with_words_first, llm_model_name_text, llm_total_input_tokens_text, llm_total_output_tokens_text, extraction_results, ) = redact_text_pdf( file_path, language, chosen_redact_entities, chosen_redact_comprehend_entities, in_allow_list_flat, page_min, page_max if page_max > 0 else number_of_pages, 0, page_break_return, annotations_all_pages, all_page_line_level_ocr_results_df, all_pages_decision_process_table, pymupdf_doc, list(), # empty: first pass only used for word-count classification pii_identification_method, comprehend_query_number, comprehend_client, custom_recogniser_word_list_flat, redact_whole_page_list_flat, max_fuzzy_spelling_mistakes_num, match_fuzzy_whole_phrase_bool, page_sizes_df, document_cropboxes, True, # text_extraction_only output_folder=output_folder, input_folder=input_folder, bedrock_runtime=bedrock_runtime, model_choice=CLOUD_LLM_PII_MODEL_CHOICE, custom_llm_instructions=custom_llm_instructions, chosen_llm_entities=chosen_llm_entities, efficient_ocr=efficient_ocr, pages_to_process=all_pages_1based, efficient_ocr_extraction_pass=True, ) llm_total_input_tokens += llm_total_input_tokens_text llm_total_output_tokens += llm_total_output_tokens_text if llm_model_name_text and not llm_model_name: llm_model_name = llm_model_name_text page_word_counts = _word_count_by_page_from_ocr_results_with_words( all_page_line_level_ocr_results_with_words_first, all_pages_1based ) if efficient_ocr_min_image_coverage_fraction > 0: progress( 0.42, desc="Efficient OCR: scanning pages for significant embedded images", ) pages_flagged_for_image_ocr = ( _efficient_ocr_pages_with_significant_embedded_images( file_path, all_pages_1based, efficient_ocr_min_image_coverage_fraction, pymupdf_doc, min_embedded_image_px=efficient_ocr_min_embedded_image_px, ) ) if pages_flagged_for_image_ocr: _img_ocr_msg = ( "EFFICIENT_OCR: " + str(len(pages_flagged_for_image_ocr)) + " page(s) routed to OCR due to embedded images (coverage >= " + f"{efficient_ocr_min_image_coverage_fraction:.1%}" + " of page area" ) if efficient_ocr_min_embedded_image_px > 0: _img_ocr_msg += f"; min placement width/height {efficient_ocr_min_embedded_image_px} pt" _img_ocr_msg += ")." print(_img_ocr_msg) pages_with_text_1based = [ p for p in all_pages_1based if page_word_counts.get(p, 0) >= efficient_ocr_min_words and p not in pages_flagged_for_image_ocr ] pages_needing_ocr_1based = [ p for p in all_pages_1based if page_word_counts.get(p, 0) < efficient_ocr_min_words or p in pages_flagged_for_image_ocr ] efficient_ocr_text_pages = len(pages_with_text_1based) efficient_ocr_ocr_pages = len(pages_needing_ocr_1based) # Hold text-path outputs for merge after OCR when we have both paths _text_path_decision_table = None _text_path_annotations = None if pages_with_text_1based: progress( 0.5, desc="Processing pages with selectable text extraction (no OCR)", ) print( f"EFFICIENT_OCR: Processing {len(pages_with_text_1based)} page(s) with selectable text extraction (no OCR)." ) pages_with_text_set = set(pages_with_text_1based) if extraction_results is not None: pre_extracted_for_text = [ r for r in extraction_results if (r[0] + 1) in pages_with_text_set ] else: pre_extracted_for_text = None ( pymupdf_doc, all_pages_decision_process_table, all_page_line_level_ocr_results_df, annotations_all_pages, current_loop_page, page_break_return, comprehend_query_number, all_page_line_level_ocr_results_with_words, llm_model_name_text, llm_total_input_tokens_text, llm_total_output_tokens_text, ) = redact_text_pdf( file_path, language, chosen_redact_entities, chosen_redact_comprehend_entities, in_allow_list_flat, page_min, page_max if page_max > 0 else number_of_pages, 0, page_break_return, annotations_all_pages, all_page_line_level_ocr_results_df, all_pages_decision_process_table, pymupdf_doc, list(), # empty so only text-page data is accumulated (OCR pages filled by redact_image_pdf) pii_identification_method, comprehend_query_number, comprehend_client, custom_recogniser_word_list_flat, redact_whole_page_list_flat, max_fuzzy_spelling_mistakes_num, match_fuzzy_whole_phrase_bool, page_sizes_df, document_cropboxes, text_extraction_only, output_folder=output_folder, input_folder=input_folder, bedrock_runtime=bedrock_runtime, model_choice=CLOUD_LLM_PII_MODEL_CHOICE, custom_llm_instructions=custom_llm_instructions, chosen_llm_entities=chosen_llm_entities, efficient_ocr=efficient_ocr, pages_to_process=pages_with_text_1based, pre_extracted_results=pre_extracted_for_text, ) llm_total_input_tokens += llm_total_input_tokens_text llm_total_output_tokens += llm_total_output_tokens_text if llm_model_name_text and not llm_model_name: llm_model_name = llm_model_name_text # Save text-path outputs so we can merge them after OCR (ensures review file includes text-path redactions) if pages_needing_ocr_1based: _text_path_decision_table = all_pages_decision_process_table.copy() _text_path_annotations = list(annotations_all_pages) if pages_needing_ocr_1based: progress(0.55, desc="Creating images for pages that need OCR") pdf_image_file_paths, page_sizes = prepare_images_for_pages( file_path, pages_needing_ocr_1based, input_folder, pymupdf_doc, page_sizes, progress, ) page_sizes_df = pd.DataFrame(page_sizes) page_sizes_df[["page"]] = page_sizes_df[["page"]].apply( pd.to_numeric, errors="coerce" ) progress(0.6, desc="Processing pages with OCR") if ocr_fallback_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION: _local_ocr_display = { "tesseract": "Tesseract (local OCR)", "paddle": "PaddleOCR (local)", "hybrid-paddle": "Hybrid Paddle (local)", "hybrid-vlm": "Hybrid VLM (local)", "hybrid-paddle-vlm": "Hybrid Paddle+VLM (local)", "hybrid-paddle-inference-server": "Hybrid Paddle + inference server", "vlm": "Local VLM", "inference-server": "Inference server VLM OCR", } ocr_method_label = _local_ocr_display.get( chosen_local_ocr_model or "tesseract", f"Local OCR ({chosen_local_ocr_model})", ) else: ocr_method_label = ( "AWS Textract" if ocr_fallback_method == TEXTRACT_TEXT_EXTRACT_OPTION else ( "Bedrock VLM" if ocr_fallback_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION else ( "Gemini VLM" if ocr_fallback_method == GEMINI_VLM_TEXT_EXTRACT_OPTION else ( "Azure/OpenAI VLM" if ocr_fallback_method == AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION else str(ocr_fallback_method) ) ) ) ) print( f"EFFICIENT_OCR: Processing {len(pages_needing_ocr_1based)} page(s) with OCR ({ocr_method_label})." ) _defer_inline_vlm_detection_for_post_pass = ( _run_vlm_pass_after_all_pages and ( CUSTOM_VLM_BACKEND != "bedrock_vlm" or bedrock_runtime is not None ) ) # When both text and OCR paths run, pass an empty decision table so the image path # only returns OCR rows; we then merge with the saved text-path table (no overwrite). _decision_table_for_ocr = ( pd.DataFrame() if ( pages_with_text_1based and _text_path_decision_table is not None ) else all_pages_decision_process_table ) ( pymupdf_doc, all_pages_decision_process_table, log_files_output_paths, new_textract_request_metadata, annotations_all_pages, current_loop_page, page_break_return, all_page_line_level_ocr_results_df, comprehend_query_number, all_page_line_level_ocr_results, all_page_line_level_ocr_results_with_words, selection_element_results_list_df, form_key_value_results_list_df, out_file_paths, llm_model_name, llm_total_input_tokens, llm_total_output_tokens, vlm_model_name_page, vlm_total_input_tokens_page, vlm_total_output_tokens_page, ) = redact_image_pdf( file_path, pdf_image_file_paths, language, chosen_redact_entities, chosen_redact_comprehend_entities, in_allow_list_flat, chosen_llm_entities, page_min, page_max if page_max > 0 else number_of_pages, ocr_fallback_method, handwrite_signature_checkbox, blank_request_metadata, 0, page_break_return, annotations_all_pages, all_page_line_level_ocr_results_df, _decision_table_for_ocr, pymupdf_doc, pii_identification_method, comprehend_query_number, comprehend_client, bedrock_runtime, textract_client, gemini_client, gemini_config, azure_openai_client, custom_recogniser_word_list_flat, redact_whole_page_list_flat, max_fuzzy_spelling_mistakes_num, match_fuzzy_whole_phrase_bool, page_sizes_df, text_extraction_only, textract_output_found, all_page_line_level_ocr_results, all_page_line_level_ocr_results_with_words, chosen_local_ocr_model, log_files_output_paths=log_files_output_paths, out_file_paths=out_file_paths, nlp_analyser=nlp_analyser, output_folder=output_folder, input_folder=input_folder, custom_llm_instructions=custom_llm_instructions, inference_server_vlm_model=inference_server_vlm_model, efficient_ocr=efficient_ocr, save_page_ocr_visualisations=save_page_ocr_visualisations, pages_to_process=pages_needing_ocr_1based, ocr_first_pass_max_workers=ocr_first_pass_max_workers, pages_in_pdf_points=pages_with_text_1based, hybrid_textract_bedrock_vlm=hybrid_textract_bedrock_vlm, overwrite_existing_ocr_results=overwrite_existing_ocr_results, defer_inline_custom_vlm_detection_pass=_defer_inline_vlm_detection_for_post_pass, ) out_file_paths = out_file_paths.copy() vlm_total_input_tokens += vlm_total_input_tokens_page vlm_total_output_tokens += vlm_total_output_tokens_page if vlm_model_name_page and not vlm_model_name: vlm_model_name = vlm_model_name_page if new_textract_request_metadata and isinstance( new_textract_request_metadata, list ): all_textract_request_metadata.extend(new_textract_request_metadata) # Merge text-path and OCR-path outputs so review file and CSV include text-path redactions if ( pages_with_text_1based and _text_path_decision_table is not None and not _text_path_decision_table.empty ): if ( "page" in _text_path_decision_table.columns and "page" in all_pages_decision_process_table.columns ): text_rows = _text_path_decision_table[ _text_path_decision_table["page"] .astype(int) .isin(pages_with_text_1based) ] ocr_rows = all_pages_decision_process_table[ all_pages_decision_process_table["page"] .astype(int) .isin(pages_needing_ocr_1based) ] all_pages_decision_process_table = ( pd.concat([text_rows, ocr_rows], ignore_index=True) .sort_values("page") .reset_index(drop=True) ) if _text_path_annotations: seen_images = { ann.get("image") for ann in annotations_all_pages } for ann in _text_path_annotations: if ann.get("image") and ann.get("image") not in seen_images: annotations_all_pages.append(ann) seen_images.add(ann.get("image")) # Set current_loop_page so downstream logic sees "all pages done" current_loop_page = number_of_pages_to_process # Ensure Total pages (annotate_max_pages / annotate_max_pages_bottom) show full # document count when mixing text extraction and OCR pages annotate_max_pages = number_of_pages # OCR results are in PDF points only when no OCR path ran (text path only). # When redact_image_pdf ran, results are in image pixels. ocr_results_use_pdf_points = not pages_needing_ocr_1based # For mixed (text + OCR) we need per-page division; record text-extracted pages. pages_with_text_extraction_1based = ( list(pages_with_text_1based) if pages_with_text_1based else None ) # CUSTOM_VLM under EFFICIENT_OCR: CUSTOM_VLM_SIGNATURE uses full merged page # images; CUSTOM_VLM_FACES (and Textract Face detection) uses sparse OCR-only # paths (pages_needing_ocr_1based). Two passes when both are selected. _vlm_backend_available = ( CUSTOM_VLM_BACKEND != "bedrock_vlm" or bedrock_runtime is not None ) if ( _run_vlm_pass_after_all_pages and _vlm_backend_available and pymupdf_doc is not None and not isinstance(pymupdf_doc, list) ): num_pages = pymupdf_doc.page_count if num_pages and num_pages > 0: progress( 0.65, desc="Preparing custom VLM entity (face/signature) pass" ) entities_for_vlm = list(chosen_redact_entities or []) for _vlm_src in ( chosen_redact_comprehend_entities or [], chosen_llm_entities or [], ): for _e in _vlm_src: if ( str(_e).startswith("CUSTOM_VLM") and _e not in entities_for_vlm ): entities_for_vlm.append(_e) if ( "Face detection" in (handwrite_signature_checkbox or []) and "CUSTOM_VLM_FACES" not in entities_for_vlm ): entities_for_vlm.append("CUSTOM_VLM_FACES") _vlm_wants_person = "CUSTOM_VLM_FACES" in entities_for_vlm _vlm_wants_signature = ( "CUSTOM_VLM_SIGNATURE" in entities_for_vlm and not textract_prioritizes_signature_extraction( text_extraction_method, handwrite_signature_checkbox ) ) if ( "CUSTOM_VLM_SIGNATURE" in entities_for_vlm and textract_prioritizes_signature_extraction( text_extraction_method, handwrite_signature_checkbox ) ): print( "Textract Extract signatures enabled — skipping " "CUSTOM_VLM_SIGNATURE VLM pass (Textract signatures take priority)." ) _vlm_rounds = [] if _vlm_wants_signature: full_merged_paths, page_sizes = ( _build_full_merged_pdf_image_paths_for_vlm( file_path, num_pages, pages_needing_ocr_1based, pages_with_text_1based, pdf_image_file_paths, all_pages_1based, input_folder, pymupdf_doc, page_sizes, progress, ) ) full_page_sizes_df = pd.DataFrame(page_sizes) if ( not full_page_sizes_df.empty and "page" in full_page_sizes_df.columns ): full_page_sizes_df[["page"]] = full_page_sizes_df[ ["page"] ].apply(pd.to_numeric, errors="coerce") _vlm_rounds.append( ( ["CUSTOM_VLM_SIGNATURE"], full_merged_paths, full_page_sizes_df, "Running CUSTOM_VLM signature detection on all page images", ) ) if _vlm_wants_person: person_page_sizes_df = pd.DataFrame(page_sizes) if ( not person_page_sizes_df.empty and "page" in person_page_sizes_df.columns ): person_page_sizes_df[["page"]] = person_page_sizes_df[ ["page"] ].apply(pd.to_numeric, errors="coerce") _vlm_rounds.append( ( ["CUSTOM_VLM_FACES"], pdf_image_file_paths, person_page_sizes_df, "Running custom VLM entity detection on OCR-classified pages only", ) ) if not _vlm_rounds: full_merged_paths, page_sizes = ( _build_full_merged_pdf_image_paths_for_vlm( file_path, num_pages, pages_needing_ocr_1based, pages_with_text_1based, pdf_image_file_paths, all_pages_1based, input_folder, pymupdf_doc, page_sizes, progress, ) ) full_page_sizes_df = pd.DataFrame(page_sizes) if ( not full_page_sizes_df.empty and "page" in full_page_sizes_df.columns ): full_page_sizes_df[["page"]] = full_page_sizes_df[ ["page"] ].apply(pd.to_numeric, errors="coerce") _vlm_rounds.append( ( entities_for_vlm, full_merged_paths, full_page_sizes_df, "Running custom VLM entity detection on all page images", ) ) for _round_idx, ( _vlm_entities, _vlm_paths, _vlm_sizes_df, _vlm_msg, ) in enumerate(_vlm_rounds): progress( 0.7 + 0.02 * float(_round_idx), desc=_vlm_msg, ) print(_vlm_msg) ( vlm_in, vlm_out, vlm_name, vlm_annotations_list, vlm_decision_rows, ) = run_custom_vlm_only_pass( file_path, _vlm_paths, pymupdf_doc, _vlm_sizes_df, _vlm_entities, bedrock_runtime, output_folder, input_folder, num_pages, page_min=page_min, page_max=page_max if page_max > 0 else num_pages, progress=progress, inference_server_vlm_model=inference_server_vlm_model, ) vlm_total_input_tokens += vlm_in vlm_total_output_tokens += vlm_out if vlm_name and not vlm_model_name: vlm_model_name = vlm_name # Merge VLM boxes into annotations and decision table. if vlm_annotations_list: annotations_all_pages.extend(vlm_annotations_list) if vlm_decision_rows: vlm_df = pd.DataFrame(vlm_decision_rows) if ( all_pages_decision_process_table is not None and not all_pages_decision_process_table.empty ): all_pages_decision_process_table = pd.concat( [ all_pages_decision_process_table, vlm_df, ], ignore_index=True, ) else: all_pages_decision_process_table = vlm_df elif ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION or text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION or text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION or text_extraction_method == GEMINI_VLM_TEXT_EXTRACT_OPTION or text_extraction_method == AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION ): # Analyse and redact image-based pdf or image if is_pdf_or_image(file_path) is False: out_message = "Please upload a PDF file or image file (JPG, PNG) for image analysis." raise Exception(out_message) print( "Redacting file " + pdf_file_name_with_ext + " as an image-based file" ) ( pymupdf_doc, all_pages_decision_process_table, log_files_output_paths, new_textract_request_metadata, annotations_all_pages, current_loop_page, page_break_return, all_page_line_level_ocr_results_df, comprehend_query_number, all_page_line_level_ocr_results, all_page_line_level_ocr_results_with_words, selection_element_results_list_df, form_key_value_results_list_df, out_file_paths, llm_model_name, llm_total_input_tokens, llm_total_output_tokens, vlm_model_name_page, vlm_total_input_tokens_page, vlm_total_output_tokens_page, ) = redact_image_pdf( file_path, pdf_image_file_paths, language, chosen_redact_entities, chosen_redact_comprehend_entities, in_allow_list_flat, chosen_llm_entities, page_min, page_max, text_extraction_method, handwrite_signature_checkbox, blank_request_metadata, current_loop_page, page_break_return, annotations_all_pages, all_page_line_level_ocr_results_df, all_pages_decision_process_table, pymupdf_doc, pii_identification_method, comprehend_query_number, comprehend_client, bedrock_runtime, textract_client, gemini_client, gemini_config, azure_openai_client, custom_recogniser_word_list_flat, redact_whole_page_list_flat, max_fuzzy_spelling_mistakes_num, match_fuzzy_whole_phrase_bool, page_sizes_df, text_extraction_only, textract_output_found, all_page_line_level_ocr_results, all_page_line_level_ocr_results_with_words, chosen_local_ocr_model, log_files_output_paths=log_files_output_paths, out_file_paths=out_file_paths, nlp_analyser=nlp_analyser, output_folder=output_folder, input_folder=input_folder, custom_llm_instructions=custom_llm_instructions, inference_server_vlm_model=inference_server_vlm_model, efficient_ocr=efficient_ocr, save_page_ocr_visualisations=save_page_ocr_visualisations, ocr_first_pass_max_workers=ocr_first_pass_max_workers, hybrid_textract_bedrock_vlm=hybrid_textract_bedrock_vlm, overwrite_existing_ocr_results=overwrite_existing_ocr_results, ) # This line creates a copy of out_file_paths to break potential links with log_files_output_paths out_file_paths = out_file_paths.copy() # Accumulate VLM token usage vlm_total_input_tokens += vlm_total_input_tokens_page vlm_total_output_tokens += vlm_total_output_tokens_page if vlm_model_name_page and not vlm_model_name: vlm_model_name = vlm_model_name_page # Save Textract request metadata (if exists) if new_textract_request_metadata and isinstance( new_textract_request_metadata, list ): all_textract_request_metadata.extend(new_textract_request_metadata) elif text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION: if is_pdf(file_path) is False: out_message = "Please upload a PDF file for text analysis. If you have an image, select 'Image analysis'." raise Exception(out_message) # Analyse text-based pdf print("Redacting file as text-based PDF") ( pymupdf_doc, all_pages_decision_process_table, all_page_line_level_ocr_results_df, annotations_all_pages, current_loop_page, page_break_return, comprehend_query_number, all_page_line_level_ocr_results_with_words, llm_model_name_text, llm_total_input_tokens_text, llm_total_output_tokens_text, ) = redact_text_pdf( file_path, language, chosen_redact_entities, chosen_redact_comprehend_entities, in_allow_list_flat, page_min, page_max, current_loop_page, page_break_return, annotations_all_pages, all_page_line_level_ocr_results_df, all_pages_decision_process_table, pymupdf_doc, all_page_line_level_ocr_results_with_words, pii_identification_method, comprehend_query_number, comprehend_client, custom_recogniser_word_list_flat, redact_whole_page_list_flat, max_fuzzy_spelling_mistakes_num, match_fuzzy_whole_phrase_bool, page_sizes_df, document_cropboxes, text_extraction_only, output_folder=output_folder, input_folder=input_folder, bedrock_runtime=bedrock_runtime, model_choice=CLOUD_LLM_PII_MODEL_CHOICE, custom_llm_instructions=custom_llm_instructions, chosen_llm_entities=chosen_llm_entities, efficient_ocr=efficient_ocr, ) # Accumulate LLM token usage from text PDF redaction llm_total_input_tokens += llm_total_input_tokens_text llm_total_output_tokens += llm_total_output_tokens_text if llm_model_name_text and not llm_model_name: llm_model_name = llm_model_name_text # When selectable text + CUSTOM_VLM_*: keep text from PDF, run VLM (face/signature) on images only. # Backend from CUSTOM_VLM_BACKEND (bedrock_vlm, inference_vlm, transformers_vlm). _vlm_backend_available_selectable = ( CUSTOM_VLM_BACKEND != "bedrock_vlm" or bedrock_runtime is not None ) if ( _custom_vlm_requires_image_global and _vlm_backend_available_selectable and pdf_image_file_paths ): print( "CUSTOM_VLM entity (face/signature/etc.) selected with simple text extraction: " "running VLM detection on page images and merging with text-based redactions." ) _entities_vlm_selectable = list(chosen_redact_entities or []) for _vlm_src in ( chosen_redact_comprehend_entities or [], chosen_llm_entities or [], ): for _e in _vlm_src: if ( str(_e).startswith("CUSTOM_VLM") and _e not in _entities_vlm_selectable ): _entities_vlm_selectable.append(_e) ( vlm_in, vlm_out, vlm_name, vlm_annotations_list, vlm_decision_rows, ) = run_custom_vlm_only_pass( file_path, pdf_image_file_paths, pymupdf_doc, page_sizes_df, _entities_vlm_selectable, bedrock_runtime, output_folder, input_folder, number_of_pages, page_min=page_min, page_max=page_max if page_max > 0 else number_of_pages, progress=progress, inference_server_vlm_model=inference_server_vlm_model, ) vlm_total_input_tokens += vlm_in vlm_total_output_tokens += vlm_out if vlm_name and not vlm_model_name: vlm_model_name = vlm_name if vlm_annotations_list: annotations_all_pages.extend(vlm_annotations_list) if vlm_decision_rows: vlm_df = pd.DataFrame(vlm_decision_rows) if ( all_pages_decision_process_table is not None and not all_pages_decision_process_table.empty ): all_pages_decision_process_table = pd.concat( [all_pages_decision_process_table, vlm_df], ignore_index=True, ) else: all_pages_decision_process_table = vlm_df else: out_message = "No redaction method selected" print(out_message) raise Exception(out_message) # If at last page, save to file - CHANGED - now will return outputs regardless of page progress. # if current_loop_page >= number_of_pages_to_process: print( "Current page number", (page_min + current_loop_page), "is the last page processed.", ) latest_file_completed += 1 # current_loop_page = 999 if latest_file_completed != len(file_paths_list): print( "Completed file number:", str(latest_file_completed), "there are more files to do", ) # Save redacted file if pii_identification_method != NO_REDACTION_PII_OPTION: if RETURN_REDACTED_PDF is True: progress(0.9, "Saving redacted file") if is_pdf(file_path) is False: out_redacted_png_path = ( output_folder + pdf_file_name_without_ext + "_redacted.png" ) # Add page range suffix if partial processing out_redacted_png_path = add_page_range_suffix_to_file_path( out_redacted_png_path, page_min, current_loop_page, number_of_pages, page_max, ) # pymupdf_doc is an image list in this case if isinstance(pymupdf_doc[-1], str): # Normalize and validate path safety before opening image normalized_path = os.path.normpath( os.path.abspath(pymupdf_doc[-1]) ) if validate_path_containment(normalized_path, INPUT_FOLDER): img = Image.open(normalized_path) else: raise ValueError( f"Unsafe image path detected: {pymupdf_doc[-1]}" ) # Otherwise could be an image object else: img = pymupdf_doc[-1] img.save(out_redacted_png_path, "PNG", resolution=image_dpi) if isinstance(out_redacted_png_path, str): out_file_paths.append(out_redacted_png_path) else: out_file_paths.append(out_redacted_png_path[0]) # Same outputs as PDF route: _redacted.pdf and _redactions_for_review.pdf try: img_doc = pymupdf.open() page = img_doc.new_page(width=img.width, height=img.height) page.insert_image(page.rect, filename=out_redacted_png_path) out_redacted_pdf_file_path = ( output_folder + pdf_file_name_without_ext + "_redacted.pdf" ) out_redacted_pdf_file_path = add_page_range_suffix_to_file_path( out_redacted_pdf_file_path, page_min, current_loop_page, number_of_pages, page_max, ) save_pdf_with_or_without_compression( img_doc, out_redacted_pdf_file_path ) if isinstance(out_redacted_pdf_file_path, str): out_file_paths.append(out_redacted_pdf_file_path) else: out_file_paths.append(out_redacted_pdf_file_path[0]) img_doc.close() if RETURN_PDF_FOR_REVIEW is True: out_review_pdf_file_path = ( output_folder + pdf_file_name_without_ext + "_redactions_for_review.pdf" ) out_review_pdf_file_path = ( add_page_range_suffix_to_file_path( out_review_pdf_file_path, page_min, current_loop_page, number_of_pages, page_max, ) ) review_img_doc = pymupdf.open(out_redacted_pdf_file_path) save_pdf_with_or_without_compression( review_img_doc, out_review_pdf_file_path ) if isinstance(out_review_pdf_file_path, str): out_file_paths.append(out_review_pdf_file_path) else: out_file_paths.append(out_review_pdf_file_path[0]) review_img_doc.close() except Exception as e: print(f"Failed to create PDF outputs from image: {e}") else: # Check if we have dual PDF documents to save applied_redaction_pymupdf_doc = None if RETURN_PDF_FOR_REVIEW and RETURN_REDACTED_PDF: # When efficient_ocr is true, some pages come from redact_image_pdf (OCR) # and some from redact_text_pdf (selectable text). Merge both into one map # so the final document has redactions applied to all processed pages. has_image_pages = ( hasattr(redact_image_pdf, "_applied_redaction_pages") and redact_image_pdf._applied_redaction_pages ) has_text_pages = ( hasattr(redact_text_pdf, "_applied_redaction_pages") and redact_text_pdf._applied_redaction_pages ) if has_image_pages or has_text_pages: # Create final document by copying the original document and replacing specific pages applied_redaction_pymupdf_doc = pymupdf.open() applied_redaction_pymupdf_doc.insert_pdf(pymupdf_doc) # Build a single mapping from both image (OCR) and text paths. # Add text-path pages first so they are not overwritten; then OCR pages. applied_redaction_pages_map = {} # Keep references to parent docs so insert_pdf can use them (avoid GC) _applied_redaction_parent_docs = [] def add_pages_to_map(source_pages): for applied_redaction_page_data in source_pages: if isinstance(applied_redaction_page_data, tuple): applied_redaction_page, original_page_number = ( applied_redaction_page_data ) applied_redaction_pages_map[ original_page_number ] = applied_redaction_page if ( hasattr(applied_redaction_page, "parent") and applied_redaction_page.parent is not None ): _applied_redaction_parent_docs.append( applied_redaction_page.parent ) else: applied_redaction_page = ( applied_redaction_page_data ) applied_redaction_pages_map[0] = ( applied_redaction_page # Default to page 0 if no original number ) if ( hasattr(applied_redaction_page, "parent") and applied_redaction_page.parent is not None ): _applied_redaction_parent_docs.append( applied_redaction_page.parent ) if has_text_pages: add_pages_to_map( redact_text_pdf._applied_redaction_pages, ) if has_image_pages: add_pages_to_map( redact_image_pdf._applied_redaction_pages, ) # Replace pages in the final document with their final versions. # Process in descending page order so delete_page() does not shift # indices of pages we have not yet replaced (text and OCR pages). for original_page_number in sorted( applied_redaction_pages_map.keys(), reverse=True ): applied_redaction_page = applied_redaction_pages_map[ original_page_number ] if ( original_page_number < applied_redaction_pymupdf_doc.page_count ): # Remove the original page and insert the final page applied_redaction_pymupdf_doc.delete_page( original_page_number ) try: applied_redaction_pymupdf_doc.insert_pdf( applied_redaction_page.parent, from_page=applied_redaction_page.number, to_page=applied_redaction_page.number, start_at=original_page_number, ) except IndexError: # Retry without link processing if it fails print( "IndexError: Retrying without link processing" ) applied_redaction_pymupdf_doc.insert_pdf( applied_redaction_page.parent, from_page=applied_redaction_page.number, to_page=applied_redaction_page.number, start_at=original_page_number, links=False, ) applied_redaction_pymupdf_doc[ original_page_number ].apply_redactions( images=APPLY_REDACTIONS_IMAGES, graphics=APPLY_REDACTIONS_GRAPHICS, text=APPLY_REDACTIONS_TEXT, ) # Clear the stored final pages from both sources (guard for concurrent requests) if has_image_pages and hasattr( redact_image_pdf, "_applied_redaction_pages" ): delattr(redact_image_pdf, "_applied_redaction_pages") if has_text_pages and hasattr( redact_text_pdf, "_applied_redaction_pages" ): delattr(redact_text_pdf, "_applied_redaction_pages") # Save final redacted PDF if we have dual outputs or if RETURN_PDF_FOR_REVIEW is False if RETURN_PDF_FOR_REVIEW is False or applied_redaction_pymupdf_doc: out_redacted_pdf_file_path = ( output_folder + pdf_file_name_without_ext + "_redacted.pdf" ) # Add page range suffix if partial processing out_redacted_pdf_file_path = add_page_range_suffix_to_file_path( out_redacted_pdf_file_path, page_min, current_loop_page, number_of_pages, page_max, ) # print("Saving redacted PDF file:", out_redacted_pdf_file_path) # Use final document if available, otherwise use main document doc_to_save = ( applied_redaction_pymupdf_doc if applied_redaction_pymupdf_doc else pymupdf_doc ) if out_redacted_pdf_file_path: save_pdf_with_or_without_compression( doc_to_save, out_redacted_pdf_file_path ) if isinstance(out_redacted_pdf_file_path, str): out_file_paths.append(out_redacted_pdf_file_path) else: out_file_paths.append(out_redacted_pdf_file_path[0]) # Release file handle so Gradio can read the output (Windows) # if applied_redaction_pymupdf_doc is not None: # applied_redaction_pymupdf_doc.close() # applied_redaction_pymupdf_doc = None # elif ( # not RETURN_PDF_FOR_REVIEW # and pymupdf_doc is not None # and not isinstance(pymupdf_doc, list) # ): # try: # pymupdf_doc.close() # except Exception: # pass # pymupdf_doc = None # Always return a file for review if a pdf is given and RETURN_PDF_FOR_REVIEW is True if is_pdf(file_path) is True: if RETURN_PDF_FOR_REVIEW is True: out_review_pdf_file_path = ( output_folder + pdf_file_name_without_ext + "_redactions_for_review.pdf" ) # Add page range suffix if partial processing out_review_pdf_file_path = add_page_range_suffix_to_file_path( out_review_pdf_file_path, page_min, current_loop_page, number_of_pages, page_max, ) if out_review_pdf_file_path: save_pdf_with_or_without_compression( pymupdf_doc, out_review_pdf_file_path ) if isinstance(out_review_pdf_file_path, str): out_file_paths.append(out_review_pdf_file_path) else: out_file_paths.append(out_review_pdf_file_path[0]) # Release file handle so Gradio can read the output (Windows) # if pymupdf_doc is not None and not isinstance(pymupdf_doc, list): # try: # pymupdf_doc.close() # except Exception: # pass # pymupdf_doc = None if not all_page_line_level_ocr_results_df.empty: all_page_line_level_ocr_results_df = normalize_line_level_ocr_df( all_page_line_level_ocr_results_df ) else: all_page_line_level_ocr_results_df = pd.DataFrame( columns=LINE_LEVEL_OCR_DF_COLUMNS ) ocr_file_path = ( output_folder + pdf_file_name_without_ext + "_ocr_output_" + file_ending + ".csv" ) # Add page range suffix if partial processing ocr_file_path = add_page_range_suffix_to_file_path( ocr_file_path, page_min, current_loop_page, number_of_pages, page_max ) all_page_line_level_ocr_results_df.sort_values(["page", "line"], inplace=True) all_page_line_level_ocr_results_df.to_csv( ocr_file_path, index=None, encoding="utf-8-sig" ) if isinstance(ocr_file_path, str): out_file_paths.append(ocr_file_path) else: out_file_paths.append(ocr_file_path[0]) # Set when word-level OCR JSON/CSV is written; required below even if list is empty # (e.g. parallel Tesseract produced no merged results). all_page_line_level_ocr_results_with_words_df_file_path = None if all_page_line_level_ocr_results_with_words: all_page_line_level_ocr_results_with_words = merge_page_results( all_page_line_level_ocr_results_with_words ) with open( all_page_line_level_ocr_results_with_words_json_file_path, "w" ) as json_file: json.dump( all_page_line_level_ocr_results_with_words, json_file, separators=(",", ":"), ) all_page_line_level_ocr_results_with_words_df = ( word_level_ocr_output_to_dataframe( all_page_line_level_ocr_results_with_words ) ) # When EFFICIENT_OCR mixes text (PDF points) and OCR (image pixels), pass # pages_in_pdf_points so division uses mediabox for text pages and image dims for OCR. _pages_pdf_points = ( set(pages_with_text_extraction_1based) if pages_with_text_extraction_1based else None ) all_page_line_level_ocr_results_with_words_df = ( divide_coordinates_by_page_sizes( all_page_line_level_ocr_results_with_words_df, page_sizes_df, xmin="word_x0", xmax="word_x1", ymin="word_y0", ymax="word_y1", coordinates_in_pdf_points=( text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION or ocr_results_use_pdf_points is True ), pages_in_pdf_points=_pages_pdf_points, ) ) # Normalize line-level coordinates too (used as fallback max for word_y1) all_page_line_level_ocr_results_with_words_df = ( divide_coordinates_by_page_sizes( all_page_line_level_ocr_results_with_words_df, page_sizes_df, xmin="line_x0", xmax="line_x1", ymin="line_y0", ymax="line_y1", coordinates_in_pdf_points=( text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION or ocr_results_use_pdf_points is True ), pages_in_pdf_points=_pages_pdf_points, ) ) all_page_line_level_ocr_results_with_words_df["line_text"] = "" # Keep line_x0, line_x1, line_y0, line_y1 so downstream can clip word boxes to line sort_cols = ["page", "line", "word_x0"] if not all_page_line_level_ocr_results_with_words_df.empty and all( c in all_page_line_level_ocr_results_with_words_df.columns for c in sort_cols ): all_page_line_level_ocr_results_with_words_df.sort_values( sort_cols, inplace=True ) all_page_line_level_ocr_results_with_words_df_file_path = ( all_page_line_level_ocr_results_with_words_json_file_path.replace( ".json", ".csv" ) ) # Add page range suffix if partial processing all_page_line_level_ocr_results_with_words_df_file_path = ( add_page_range_suffix_to_file_path( all_page_line_level_ocr_results_with_words_df_file_path, page_min, current_loop_page, number_of_pages, page_max, ) ) # For rows where the subset columns are duplicated (i.e., all fields identical within the subset), # set their values to empty values in those columns except for the first occurrence. subset_cols = [ "line_text", "line_x0", "line_y0", "line_x1", "line_y1", "line_conf", "line_model", ] # Identify duplicated rows (excluding the first occurrence) dupes_mask = all_page_line_level_ocr_results_with_words_df.duplicated( subset=subset_cols, keep="first" ) # Set these columns to empty for duplicated rows for col in subset_cols: all_page_line_level_ocr_results_with_words_df.loc[dupes_mask, col] = ( "" if all_page_line_level_ocr_results_with_words_df[col].dtype == "O" else None ) all_page_line_level_ocr_results_with_words_df.to_csv( all_page_line_level_ocr_results_with_words_df_file_path, index=False, encoding="utf-8-sig", ) if ( all_page_line_level_ocr_results_with_words_json_file_path not in log_files_output_paths ): if isinstance( all_page_line_level_ocr_results_with_words_json_file_path, str ): log_files_output_paths.append( all_page_line_level_ocr_results_with_words_json_file_path ) else: log_files_output_paths.append( all_page_line_level_ocr_results_with_words_json_file_path[0] ) if ( all_page_line_level_ocr_results_with_words_df_file_path not in log_files_output_paths ): if isinstance( all_page_line_level_ocr_results_with_words_df_file_path, str ): log_files_output_paths.append( all_page_line_level_ocr_results_with_words_df_file_path ) else: log_files_output_paths.append( all_page_line_level_ocr_results_with_words_df_file_path[0] ) if ( all_page_line_level_ocr_results_with_words_df_file_path not in out_file_paths ): if isinstance( all_page_line_level_ocr_results_with_words_df_file_path, str ): out_file_paths.append( all_page_line_level_ocr_results_with_words_df_file_path ) else: out_file_paths.append( all_page_line_level_ocr_results_with_words_df_file_path[0] ) # Save decision process outputs if not all_pages_decision_process_table.empty: all_pages_decision_process_table_file_path = ( output_folder + pdf_file_name_without_ext + "_all_pages_decision_process_table_output_" + file_ending + ".csv" ) # Add page range suffix if partial processing all_pages_decision_process_table_file_path = ( add_page_range_suffix_to_file_path( all_pages_decision_process_table_file_path, page_min, current_loop_page, number_of_pages, page_max, ) ) all_pages_decision_process_table.to_csv( all_pages_decision_process_table_file_path, index=None, encoding="utf-8-sig", ) log_files_output_paths.append(all_pages_decision_process_table_file_path) # Save outputs from form analysis if they exist if not selection_element_results_list_df.empty: selection_element_results_list_df_file_path = ( output_folder + pdf_file_name_without_ext + "_selection_element_results_output_" + file_ending + ".csv" ) # Add page range suffix if partial processing selection_element_results_list_df_file_path = ( add_page_range_suffix_to_file_path( selection_element_results_list_df_file_path, page_min, current_loop_page, number_of_pages, page_max, ) ) selection_element_results_list_df.to_csv( selection_element_results_list_df_file_path, index=None, encoding="utf-8-sig", ) out_file_paths.append(selection_element_results_list_df_file_path) if not form_key_value_results_list_df.empty: form_key_value_results_list_df_file_path = ( output_folder + pdf_file_name_without_ext + "_form_key_value_results_output_" + file_ending + ".csv" ) # Add page range suffix if partial processing form_key_value_results_list_df_file_path = ( add_page_range_suffix_to_file_path( form_key_value_results_list_df_file_path, page_min, current_loop_page, number_of_pages, page_max, ) ) form_key_value_results_list_df.to_csv( form_key_value_results_list_df_file_path, index=None, encoding="utf-8-sig", ) out_file_paths.append(form_key_value_results_list_df_file_path) # Convert the gradio annotation boxes to relative coordinates progress(0.95, "Creating review file output") # EFFICIENT_OCR: ensure text-extracted pages have mediabox dimensions and # placeholder image path so divide_coordinates_by_page_sizes uses mediabox (not nan). if ( pages_with_text_extraction_1based and pymupdf_doc is not None and not isinstance(pymupdf_doc, list) and hasattr(pymupdf_doc, "load_page") ): pages_in_df = set( pd.to_numeric(page_sizes_df["page"], errors="coerce") .dropna() .astype(int) ) placeholder_base = "placeholder_image_{}.png" for page_num in pages_with_text_extraction_1based: try: pymupdf_page = pymupdf_doc.load_page(int(page_num) - 1) mb = pymupdf_page.mediabox page_int = int(page_num) if page_int in pages_in_df: # Update existing row (e.g. placeholder with nan) so division has mediabox mask = page_sizes_df["page"] == page_int page_sizes_df.loc[mask, "image_width"] = mb.width page_sizes_df.loc[mask, "image_height"] = mb.height if "mediabox_width" in page_sizes_df.columns: page_sizes_df.loc[mask, "mediabox_width"] = mb.width if "mediabox_height" in page_sizes_df.columns: page_sizes_df.loc[mask, "mediabox_height"] = mb.height # Align image_path with placeholder so annotations match page_sizes_df.loc[mask, "image_path"] = placeholder_base.format( page_int - 1 ) else: new_row = { "page": page_num, "image_path": placeholder_base.format(page_int - 1), "image_width": mb.width, "image_height": mb.height, "mediabox_width": mb.width, "mediabox_height": mb.height, } if "cropbox_width" in page_sizes_df.columns: new_row["cropbox_width"] = pymupdf_page.cropbox.width if "cropbox_height" in page_sizes_df.columns: new_row["cropbox_height"] = pymupdf_page.cropbox.height page_sizes_df = pd.concat( [page_sizes_df, pd.DataFrame([new_row])], ignore_index=True, ) pages_in_df.add(page_int) except Exception as e: print( f"Warning: Could not add/update mediabox for text-extracted page {page_num}: {e}" ) page_sizes = page_sizes_df.to_dict(orient="records") all_image_annotations_df = convert_annotation_data_to_dataframe( annotations_all_pages ) _pages_pdf_pts = ( set(pages_with_text_extraction_1based) if pages_with_text_extraction_1based else None ) all_image_annotations_df = divide_coordinates_by_page_sizes( all_image_annotations_df, page_sizes_df, xmin="xmin", xmax="xmax", ymin="ymin", ymax="ymax", coordinates_in_pdf_points=( text_extraction_method == SELECTABLE_TEXT_EXTRACT_OPTION or ocr_results_use_pdf_points is True ), pages_in_pdf_points=_pages_pdf_pts, ) annotations_all_pages_divide = create_annotation_dicts_from_annotation_df( all_image_annotations_df, page_sizes ) annotations_all_pages_divide = remove_duplicate_images_with_blank_boxes( annotations_all_pages_divide ) # Save the gradio_annotation_boxes to a review csv file review_file_state = convert_annotation_json_to_review_df( annotations_all_pages_divide, all_pages_decision_process_table, page_sizes=page_sizes, ) # Don't need page sizes in outputs review_file_state.drop( [ "image_width", "image_height", "mediabox_width", "mediabox_height", "cropbox_width", "cropbox_height", ], axis=1, inplace=True, errors="ignore", ) if ( pii_identification_method == NO_REDACTION_PII_OPTION and not form_key_value_results_list_df.empty ): print( "Form outputs found with no redaction method selected. Creating review file from form outputs." ) review_file_state = form_key_value_results_list_df annotations_all_pages_divide = create_annotation_dicts_from_annotation_df( review_file_state, page_sizes ) review_file_path = orig_pdf_file_path + "_review_file.csv" # Add page range suffix if partial processing review_file_path = add_page_range_suffix_to_file_path( review_file_path, page_min, current_loop_page, number_of_pages, page_max ) if isinstance(review_file_path, str): review_file_state.to_csv(review_file_path, index=None, encoding="utf-8-sig") else: review_file_state.to_csv( review_file_path[0], index=None, encoding="utf-8-sig" ) if pii_identification_method != NO_REDACTION_PII_OPTION: if isinstance(review_file_path, str): out_file_paths.append(review_file_path) else: out_file_paths.append(review_file_path[0]) _rev_csv = ( review_file_path if isinstance(review_file_path, str) else review_file_path[0] ) _ocr_words = all_page_line_level_ocr_results_with_words_df_file_path if isinstance(_ocr_words, list): _ocr_words = _ocr_words[0] if _ocr_words else None if _rev_csv and _ocr_words: try: from tools.post_redaction_pass1_qa import ( run_post_redaction_pass1_qa, ) qa_result = run_post_redaction_pass1_qa( review_csv_path=_rev_csv, ocr_words_csv_path=_ocr_words, output_folder=output_folder, total_pages=number_of_pages, deny_list=custom_recogniser_word_list_flat, allow_list=in_allow_list_flat, enabled=post_redact_pass1_qa, auto_prune=post_redact_pass1_auto_prune, ) if qa_result.get("summary"): if isinstance(combined_out_message, list): combined_out_message = "\n".join(combined_out_message) combined_out_message = ( combined_out_message + " " + qa_result["summary"] ) for qa_path in qa_result.get("paths_created") or []: if qa_path not in out_file_paths: out_file_paths.append(qa_path) except Exception as qa_exc: print(f"Post-redaction Pass 1 QA failed: {qa_exc}") # Make a combined message for the file if isinstance(combined_out_message, list): combined_out_message = "\n".join(combined_out_message) elif combined_out_message is None: combined_out_message = "" _sep = "\n" if combined_out_message else "" if isinstance(out_message, list) and out_message: combined_out_message = combined_out_message + _sep + "\n".join(out_message) elif isinstance(out_message, str) and out_message: combined_out_message = combined_out_message + _sep + out_message if efficient_ocr_text_pages is not None: _sep = "\n" if combined_out_message else "" combined_out_message = ( combined_out_message + _sep + "Efficient OCR: " + str(efficient_ocr_text_pages) + " page(s) via text extraction, " + str(efficient_ocr_ocr_pages) + " page(s) via full OCR." ) toc = time.perf_counter() time_taken = toc - tic estimated_time_taken_state += time_taken estimated_time_taken_state = round(estimated_time_taken_state, 1) out_time_message = f" Redacted in {estimated_time_taken_state:0.1f} seconds." combined_out_message = ( combined_out_message + " " + out_time_message ) # Ensure this is a single string # Add redaction summary (total redactions and pages with redactions) if isinstance(review_file_state, pd.DataFrame) and not review_file_state.empty: total_redactions = len(review_file_state) pages_with_redactions = ( review_file_state["page"].nunique() if "page" in review_file_state.columns else 0 ) combined_out_message = ( combined_out_message + f" Total redactions: {total_redactions}. Pages with redactions: {pages_with_redactions}." ) sum_numbers_before_seconds(combined_out_message) # else: # toc = time.perf_counter() # time_taken = toc - tic # estimated_time_taken_state += time_taken # If textract requests made, write to logging file. Also record number of Textract requests if all_textract_request_metadata and isinstance( all_textract_request_metadata, list ): all_request_metadata_str = "\n".join(all_textract_request_metadata).strip() textract_metadata_filename = ( pdf_file_name_without_ext + "_textract_metadata.txt" ) # Add page range suffix if partial processing textract_metadata_filename = add_page_range_suffix_to_file_path( textract_metadata_filename, page_min, current_loop_page, number_of_pages, page_max, ) secure_file_write( output_folder, textract_metadata_filename, all_request_metadata_str, ) all_textract_request_metadata_file_path = ( output_folder + textract_metadata_filename ) # Add the request metadata to the log outputs if not there already if all_textract_request_metadata_file_path not in log_files_output_paths: if isinstance(all_textract_request_metadata_file_path, str): log_files_output_paths.append(all_textract_request_metadata_file_path) else: log_files_output_paths.append( all_textract_request_metadata_file_path[0] ) new_textract_query_numbers = len(all_textract_request_metadata) total_textract_query_number += new_textract_query_numbers # Ensure no duplicated output files log_files_output_paths = sorted(list(set(log_files_output_paths))) out_file_paths = sorted(list(set(out_file_paths))) # Only pass paths that exist to Gradio (avoids FileNotFoundError when gr.File stats paths # that no longer exist, e.g. after loading existing Textract results or in ephemeral containers) out_file_paths = [ p for p in out_file_paths if isinstance(p, str) and os.path.exists(p) ] log_files_output_paths = [ p for p in log_files_output_paths if isinstance(p, str) and os.path.exists(p) ] # Create OCR review files list for input_review_files component if ocr_file_path: if isinstance(ocr_file_path, str): ocr_review_files.append(ocr_file_path) duplication_file_path_outputs.append(ocr_file_path) else: ocr_review_files.append(ocr_file_path[0]) duplication_file_path_outputs.append(ocr_file_path[0]) if all_page_line_level_ocr_results_with_words_df_file_path: if isinstance(all_page_line_level_ocr_results_with_words_df_file_path, str): ocr_review_files.append( all_page_line_level_ocr_results_with_words_df_file_path ) else: ocr_review_files.append( all_page_line_level_ocr_results_with_words_df_file_path[0] ) # Output file paths (only include existing paths so Gradio gr.File does not raise on os.stat) if not review_file_path: review_out_file_paths = [prepared_pdf_file_paths[-1]] else: review_out_file_paths = [prepared_pdf_file_paths[-1], review_file_path] review_out_file_paths = [ p for p in review_out_file_paths if isinstance(p, str) and os.path.exists(p) ] if total_textract_query_number > number_of_pages: total_textract_query_number = number_of_pages page_break_return = True # Ensure Total pages (annotate_max_pages / annotate_max_pages_bottom) reflect the # processed document so the UI is correct (e.g. after EFFICIENT_OCR or multi-file). if not isinstance(pymupdf_doc, list) and hasattr(pymupdf_doc, "page_count"): _doc_pages = pymupdf_doc.page_count if _doc_pages and _doc_pages > 0: annotate_max_pages = _doc_pages # Ensure total_pdf_page_count (for usage logs) reflects the full document page count, # not a subset (e.g. when EFFICIENT_OCR only processes OCR-needed pages or when # loading from existing Textract JSON). total_pages_for_usage_log = number_of_pages if not isinstance(pymupdf_doc, list) and hasattr(pymupdf_doc, "page_count"): _doc_pages = pymupdf_doc.page_count if _doc_pages and _doc_pages > 0: total_pages_for_usage_log = _doc_pages estimated_time_taken_state = round(estimated_time_taken_state, 1) # Only pass existing paths to Gradio for any path lists used by file components duplication_file_path_outputs = [ p for p in duplication_file_path_outputs if isinstance(p, str) and os.path.exists(p) ] ocr_review_files = [ p for p in ocr_review_files if isinstance(p, str) and os.path.exists(p) ] return ( combined_out_message, out_file_paths, out_file_paths, latest_file_completed, log_files_output_paths, log_files_output_paths, estimated_time_taken_state, all_request_metadata_str, pymupdf_doc, annotations_all_pages_divide, current_loop_page, page_break_return, all_page_line_level_ocr_results_df, all_pages_decision_process_table, comprehend_query_number, review_out_file_paths, annotate_max_pages, annotate_max_pages, prepared_pdf_file_paths, pdf_image_file_paths, review_file_state, page_sizes, duplication_file_path_outputs, duplication_file_path_outputs, # Write ocr_file_path to in_duplicate_pages duplication_file_path_outputs, # Write ocr_file_path to in_summarisation_ocr_files review_file_path, total_textract_query_number, ocr_file_path, all_page_line_level_ocr_results, all_page_line_level_ocr_results_with_words, all_page_line_level_ocr_results_with_words_df, review_file_state, task_textbox, ocr_review_files, vlm_model_name, vlm_total_input_tokens, vlm_total_output_tokens, llm_model_name, llm_total_input_tokens, llm_total_output_tokens, total_pages_for_usage_log, ) def run_redaction( file_paths: List[str], options: RedactionOptions, context: Optional[RedactionContext] = None, progress=gr.Progress(track_tqdm=True), ): """Run redaction using typed options and optional session context.""" ctx = context if context is not None else RedactionContext() kw = to_legacy_kwargs(options, ctx) return _choose_and_run_redactor_impl(file_paths, **kw, progress=progress) def choose_and_run_redactor( file_paths: List[str], prepared_pdf_file_paths: Optional[List[str]] = None, pdf_image_file_paths: Optional[List[str]] = None, chosen_redact_entities: Optional[List[str]] = None, chosen_redact_comprehend_entities: Optional[List[str]] = None, chosen_llm_entities: List[str] = None, text_extraction_method: str = None, in_allow_list: List[str] = list(), in_deny_list: List[str] = list(), redact_whole_page_list: List[str] = list(), latest_file_completed: int = 0, combined_out_message: List = list(), out_file_paths: List = list(), log_files_output_paths: List = list(), page_min: int = 0, page_max: int = 0, estimated_time_taken_state: float = 0.0, handwrite_signature_checkbox: List[str] = list(["Extract handwriting"]), all_request_metadata_str: str = "", annotations_all_pages: List[dict] = list(), all_page_line_level_ocr_results_df: pd.DataFrame = None, all_pages_decision_process_table: pd.DataFrame = None, pymupdf_doc=list(), pii_identification_method: str = "Local", max_fuzzy_spelling_mistakes_num: int = 1, match_fuzzy_whole_phrase_bool: bool = True, aws_access_key_textbox: str = "", aws_secret_key_textbox: str = "", annotate_max_pages: int = 1, review_file_state: pd.DataFrame = list(), output_folder: str = OUTPUT_FOLDER, document_cropboxes: List = list(), page_sizes: List[dict] = list(), textract_output_found: bool = False, text_extraction_only: bool = False, duplication_file_path_outputs: list = list(), review_file_path: str = "", input_folder: str = INPUT_FOLDER, ocr_file_path: str = "", all_page_line_level_ocr_results: list[dict] = list(), all_page_line_level_ocr_results_with_words: list[dict] = list(), all_page_line_level_ocr_results_with_words_df: pd.DataFrame = None, chosen_local_ocr_model: str = DEFAULT_LOCAL_OCR_MODEL, language: str = DEFAULT_LANGUAGE, ocr_review_files: list = list(), custom_llm_instructions: str = "", inference_server_vlm_model: str = "", efficient_ocr: bool = EFFICIENT_OCR, efficient_ocr_min_words: Union[int, float, None] = EFFICIENT_OCR_MIN_WORDS, efficient_ocr_min_image_coverage_fraction: Optional[float] = None, efficient_ocr_min_embedded_image_px: Optional[int] = None, hybrid_textract_bedrock_vlm: bool = HYBRID_TEXTRACT_BEDROCK_VLM, overwrite_existing_ocr_results: bool = OVERWRITE_EXISTING_OCR_RESULTS, save_page_ocr_visualisations: bool = SAVE_PAGE_OCR_VISUALISATIONS, ocr_first_pass_max_workers: Optional[int] = None, prepare_images: bool = True, RETURN_REDACTED_PDF: bool = RETURN_REDACTED_PDF, RETURN_PDF_FOR_REVIEW: bool = RETURN_PDF_FOR_REVIEW, post_redact_pass1_qa: bool | None = None, post_redact_pass1_auto_prune: bool | None = None, progress=gr.Progress(track_tqdm=True), ): """Compatibility wrapper: builds RedactionOptions/RedactionContext and calls run_redaction.""" flat = dict(locals()) flat.pop("file_paths", None) prog = flat.pop("progress") opts, ctx = from_legacy_dict(flat) return run_redaction(file_paths, opts, ctx, progress=prog) def convert_pikepdf_coords_to_pymupdf( pymupdf_page: Page, pikepdf_bbox, type="pikepdf_annot" ): """ Convert annotations from pikepdf to pymupdf format, handling the mediabox larger than rect. """ # Use cropbox if available, otherwise use mediabox reference_box = pymupdf_page.rect mediabox = pymupdf_page.mediabox reference_box_height = reference_box.height reference_box_width = reference_box.width # Convert PyMuPDF coordinates back to PDF coordinates (bottom-left origin) media_height = mediabox.height media_width = mediabox.width media_reference_y_diff = media_height - reference_box_height media_reference_x_diff = media_width - reference_box_width y_diff_ratio = media_reference_y_diff / reference_box_height x_diff_ratio = media_reference_x_diff / reference_box_width # Extract the annotation rectangle field (pikepdf may use /Rect or Name.Rect) if type == "pikepdf_annot": try: rect_field = pikepdf_bbox["/Rect"] except (KeyError, TypeError): try: rect_field = pikepdf_bbox[Name.Rect] except (KeyError, TypeError): raise ValueError("pikepdf annotation has no /Rect") from None else: rect_field = pikepdf_bbox rect_coordinates = [float(coord) for coord in rect_field] # Convert to floats # Unpack coordinates x1, y1, x2, y2 = rect_coordinates new_x1 = x1 - (media_reference_x_diff * x_diff_ratio) new_y1 = media_height - y2 - (media_reference_y_diff * y_diff_ratio) new_x2 = x2 - (media_reference_x_diff * x_diff_ratio) new_y2 = media_height - y1 - (media_reference_y_diff * y_diff_ratio) return new_x1, new_y1, new_x2, new_y2 def convert_pikepdf_to_image_coords( pymupdf_page, annot, image: Image, type="pikepdf_annot" ): """ Convert annotations from pikepdf coordinates to image coordinates. """ # Get the dimensions of the page in points with pymupdf rect_height = pymupdf_page.rect.height rect_width = pymupdf_page.rect.width # Get the dimensions of the image image_page_width, image_page_height = image.size # Calculate scaling factors between pymupdf and PIL image scale_width = image_page_width / rect_width scale_height = image_page_height / rect_height # Extract the /Rect field if type == "pikepdf_annot": rect_field = annot["/Rect"] else: rect_field = annot # Convert the extracted /Rect field to a list of floats rect_coordinates = [float(coord) for coord in rect_field] # Convert the Y-coordinates (flip using the image height) x1, y1, x2, y2 = rect_coordinates x1_image = round(x1 * scale_width, 2) new_y1_image = round( image_page_height - (y2 * scale_height), 2 ) # Flip Y0 (since it starts from bottom) x2_image = round(x2 * scale_width, 2) new_y2_image = round(image_page_height - (y1 * scale_height), 2) # Flip Y1 return x1_image, new_y1_image, x2_image, new_y2_image def convert_pikepdf_decision_output_to_image_coords( pymupdf_page: Document, pikepdf_decision_ouput_data: List[dict], image: Image ): if isinstance(image, str): # Normalize and validate path safety before opening image normalized_path = os.path.normpath(os.path.abspath(image)) if validate_path_containment(normalized_path, INPUT_FOLDER): image_path = normalized_path image = Image.open(image_path) else: raise ValueError(f"Unsafe image path detected: {image}") # Loop through each item in the data for item in pikepdf_decision_ouput_data: # Extract the bounding box bounding_box = item["boundingBox"] # Create a pikepdf_bbox dictionary to match the expected input pikepdf_bbox = {"/Rect": bounding_box} # Call the conversion function new_x1, new_y1, new_x2, new_y2 = convert_pikepdf_to_image_coords( pymupdf_page, pikepdf_bbox, image, type="pikepdf_annot" ) # Update the original object with the new bounding box values item["boundingBox"] = [new_x1, new_y1, new_x2, new_y2] return pikepdf_decision_ouput_data def _rect_display_to_unrotated(page: Page, rect: Rect) -> Rect: """ Convert a rectangle from display (page.rect) space to unrotated page space. PyMuPDF requires coordinates in unrotated space for add_redact_annot etc.; we build rects by scaling image coords to page.rect, which is in display space when the page is rotated. """ try: derot = getattr(page, "derotation_matrix", None) if derot is not None: rect = rect * derot rect = rect.normalize() except Exception: pass return rect def convert_image_coords_to_pymupdf( pymupdf_page: Document, annot: dict, image: Image, type: str = "image_recognizer" ): """ Converts an image with redaction coordinates from a CustomImageRecognizerResult or pikepdf object with image coordinates to pymupdf coordinates. Images are always rendered from the MediaBox (via _render_pdf_page_to_png_pymupdf_mediabox), so scaling must use the MediaBox dimensions. When CropBox != MediaBox the cropbox offset is subtracted at the end so that the returned coordinates are in the page's current CropBox-local coordinate system (what PyMuPDF expects for add_redact_annot / Rect). When CropBox == MediaBox the offset is zero and behaviour is unchanged. """ # Use MediaBox dimensions for scaling (the image was rendered from the MediaBox). mediabox_height = pymupdf_page.mediabox.height mediabox_width = pymupdf_page.mediabox.width image_page_width, image_page_height = image.size # Calculate scaling factors between PIL image and MediaBox scale_width = mediabox_width / image_page_width scale_height = mediabox_height / image_page_height # Offset needed to convert from MediaBox-local to CropBox-local coordinates. # cropbox.x0 is always 0 after PyMuPDF normalises the coordinate system, so # cropbox_x_off = -mediabox.x0 (positive when CropBox is to the right of MediaBox origin). cropbox_x_off = pymupdf_page.cropbox.x0 - pymupdf_page.mediabox.x0 cropbox_y_off = pymupdf_page.cropbox.y0 - pymupdf_page.mediabox.y0 # Calculate scaled coordinates if type == "image_recognizer": x1 = annot.left * scale_width new_y1 = annot.top * scale_height x2 = (annot.left + annot.width) * scale_width new_y2 = (annot.top + annot.height) * scale_height # Else assume it is a pikepdf derived object else: rect_field = annot["/Rect"] rect_coordinates = [float(coord) for coord in rect_field] # Convert to floats # Unpack coordinates x1, y1, x2, y2 = rect_coordinates x1 = x1 * scale_width new_y1 = (y2 + (y1 - y2)) * scale_height x2 = (x1 + (x2 - x1)) * scale_width new_y2 = y2 * scale_height # Convert from MediaBox-local to CropBox-local (no-op when they are equal) x1 -= cropbox_x_off new_y1 -= cropbox_y_off x2 -= cropbox_x_off new_y2 -= cropbox_y_off return x1, new_y1, x2, new_y2 def convert_gradio_image_annotator_object_coords_to_pymupdf( pymupdf_page: Page, annot: dict, image: Image, image_dimensions: dict = None ): """ Converts an image with redaction coordinates from a gradio annotation component to pymupdf coordinates. Images are always rendered from the MediaBox, so MediaBox dimensions are used for scaling. The CropBox offset is subtracted at the end to produce CropBox-local coordinates. When CropBox == MediaBox the offset is zero and behaviour is unchanged. """ # Use MediaBox dimensions for scaling (the image was rendered from the MediaBox). mediabox_height = pymupdf_page.mediabox.height mediabox_width = pymupdf_page.mediabox.width if image_dimensions: image_page_width = image_dimensions["image_width"] image_page_height = image_dimensions["image_height"] elif image: image_page_width, image_page_height = image.size # Calculate scaling factors between PIL image and MediaBox scale_width = mediabox_width / image_page_width scale_height = mediabox_height / image_page_height # Offset to convert from MediaBox-local to CropBox-local (zero when they are equal) cropbox_x_off = pymupdf_page.cropbox.x0 - pymupdf_page.mediabox.x0 cropbox_y_off = pymupdf_page.cropbox.y0 - pymupdf_page.mediabox.y0 # Calculate scaled coordinates (MediaBox-local) x1 = annot["xmin"] * scale_width new_y1 = annot["ymin"] * scale_height x2 = annot["xmax"] * scale_width new_y2 = annot["ymax"] * scale_height # Convert to CropBox-local x1 -= cropbox_x_off new_y1 -= cropbox_y_off x2 -= cropbox_x_off new_y2 -= cropbox_y_off return x1, new_y1, x2, new_y2 def move_page_info(file_path: str) -> str: # Split the string at '.png' base, extension = file_path.rsplit(".pdf", 1) # Extract the page info page_info = base.split("page ")[1].split(" of")[0] # Get the page number new_base = base.replace( f"page {page_info} of ", "" ) # Remove the page info from the original position # Construct the new file path new_file_path = f"{new_base}_page_{page_info}.png" return new_file_path def prepare_custom_image_recogniser_result_annotation_box( page: Page, annot: CustomImageRecognizerResult, image: Image, page_sizes_df: pd.DataFrame, custom_colours: bool = USE_GUI_BOX_COLOURS_FOR_OUTPUTS, ): """ Prepare an image annotation box and coordinates based on a CustomImageRecogniserResult, PyMuPDF page, and PIL Image. """ img_annotation_box = dict() # For efficient lookup, set 'page' as index if it's not already if "page" in page_sizes_df.columns: page_sizes_df = page_sizes_df.set_index("page") # PyMuPDF page numbers are 0-based, DataFrame index assumed 1-based page_num_one_based = page.number + 1 pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = 0, 0, 0, 0 # Initialize defaults if image: pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = ( convert_image_coords_to_pymupdf(page, annot, image) ) else: # --- Calculate coordinates when no image is present --- # CustomImageRecognizerResult from OCR/deny-list have coords in image pixel space. # If we have image_width/image_height in page_sizes_df, scale from pixels to PDF. # Otherwise assume annot coords are relative to MediaBox (text-path/legacy). try: page_info = page_sizes_df.loc[page_num_one_based] rect_width = page.rect.width rect_height = page.rect.height img_w = page_info.get("image_width") img_h = page_info.get("image_height") if ( img_w is not None and img_h is not None and pd.notna(img_w) and pd.notna(img_h) and float(img_w) > 0 and float(img_h) > 0 ): # Image pixel coords (from OCR/CUSTOM) -> scale to PDF. # Images are always rendered from the MediaBox, so use MediaBox dimensions # for scaling, then subtract the CropBox offset to get CropBox-local coords. mb_w = page_info.get("mediabox_width") or rect_width mb_h = page_info.get("mediabox_height") or rect_height x_off = float(page_info.get("cropbox_x_offset") or 0) y_off = float(page_info.get("cropbox_y_offset_from_top") or 0) scale_x = float(mb_w) / float(img_w) scale_y = float(mb_h) / float(img_h) pymupdf_x1 = annot.left * scale_x - x_off pymupdf_y1 = annot.top * scale_y - y_off pymupdf_x2 = (annot.left + annot.width) * scale_x - x_off pymupdf_y2 = (annot.top + annot.height) * scale_y - y_off else: # MediaBox-relative (top-left origin), e.g. text-path mb_width = page_info["mediabox_width"] mb_height = page_info["mediabox_height"] x_offset = page_info["cropbox_x_offset"] y_offset = page_info["cropbox_y_offset_from_top"] if mb_width <= 0 or mb_height <= 0: print( f"Warning: Invalid MediaBox dimensions ({mb_width}x{mb_height}) for page {page_num_one_based}. Setting coords to 0." ) else: pymupdf_x1 = annot.left - x_offset pymupdf_x2 = annot.left + annot.width - x_offset pymupdf_y1 = annot.top - y_offset pymupdf_y2 = annot.top + annot.height - y_offset except KeyError: print( f"Warning: Page number {page_num_one_based} not found in page_sizes_df. Cannot get MediaBox dimensions. Setting coords to 0." ) except AttributeError as e: print( f"Error accessing attributes ('left', 'top', etc.) on 'annot' object for page {page_num_one_based}: {e}" ) except Exception as e: print( f"Error during coordinate calculation for page {page_num_one_based}: {e}" ) rect = Rect( pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 ) # Create the PyMuPDF Rect (in display space when built from image) rect = _rect_display_to_unrotated(page, rect) # Now creating image annotation object image_x1 = annot.left image_x2 = annot.left + annot.width image_y1 = annot.top image_y2 = annot.top + annot.height # Create image annotation boxes img_annotation_box["xmin"] = image_x1 img_annotation_box["ymin"] = image_y1 img_annotation_box["xmax"] = image_x2 # annot.left + annot.width img_annotation_box["ymax"] = image_y2 # annot.top + annot.height img_annotation_box["color"] = ( annot.color if custom_colours is True else CUSTOM_BOX_COLOUR ) try: img_annotation_box["label"] = str(annot.entity_type) except Exception as e: print(f"Error getting entity type: {e}") img_annotation_box["label"] = "Redaction" if hasattr(annot, "text") and annot.text: img_annotation_box["text"] = str(annot.text) else: img_annotation_box["text"] = "" # Assign an id img_annotation_box = fill_missing_box_ids(img_annotation_box) return img_annotation_box, rect def convert_pikepdf_annotations_to_result_annotation_box( page: Page, annot: dict, image: Image = None, convert_pikepdf_to_pymupdf_coords: bool = True, page_sizes_df: pd.DataFrame = pd.DataFrame(), image_dimensions: dict = dict(), ): """ Convert redaction objects with pikepdf coordinates to annotation boxes for PyMuPDF that can then be redacted from the document. First 1. converts pikepdf to pymupdf coordinates, then 2. converts pymupdf coordinates to image coordinates if page is an image. """ img_annotation_box = dict() page_no = page.number if convert_pikepdf_to_pymupdf_coords is True: pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = ( convert_pikepdf_coords_to_pymupdf(page, annot) ) else: pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = ( convert_image_coords_to_pymupdf( page, annot, image, type="pikepdf_image_coords" ) ) rect = Rect(pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2) if not convert_pikepdf_to_pymupdf_coords: # Coords from image are in display space when page is rotated rect = _rect_display_to_unrotated(page, rect) # If an image is provided, convert PyMuPDF coordinates to image coordinates # for the annotation box (used in review PDF) if image is not None: # Convert PyMuPDF coordinates to image pixel coordinates image_x1, image_y1, image_x2, image_y2 = convert_pymupdf_to_image_coords( page, pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2, image, image_dimensions, ) # Use image coordinates for the annotation box img_annotation_box["xmin"] = image_x1 img_annotation_box["ymin"] = image_y1 img_annotation_box["xmax"] = image_x2 img_annotation_box["ymax"] = image_y2 else: # If no image, use PyMuPDF coordinates (PDF points). Store 1-based page on box # so convert_annotation_data_to_dataframe can join to correct mediabox row (EFFICIENT_OCR). convert_df = pd.DataFrame( { "page": [page_no], "xmin": [pymupdf_x1], "ymin": [pymupdf_y1], "xmax": [pymupdf_x2], "ymax": [pymupdf_y2], } ) converted_df = convert_df # divide_coordinates_by_page_sizes(convert_df, page_sizes_df, xmin="xmin", xmax="xmax", ymin="ymin", ymax="ymax") img_annotation_box["xmin"] = converted_df["xmin"].max() img_annotation_box["ymin"] = converted_df["ymin"].max() img_annotation_box["xmax"] = converted_df["xmax"].max() img_annotation_box["ymax"] = converted_df["ymax"].max() img_annotation_box["page"] = ( page_no + 1 ) # 1-based for divide_coordinates_by_page_sizes img_annotation_box["color"] = CUSTOM_BOX_COLOUR if isinstance(annot, Dictionary): img_annotation_box["label"] = str(annot["/T"]) if hasattr(annot, "Contents"): img_annotation_box["text"] = str(annot.Contents) else: img_annotation_box["text"] = "" else: img_annotation_box["label"] = "REDACTION" img_annotation_box["text"] = "" return img_annotation_box, rect def set_cropbox_safely(page: Page, original_cropbox: Optional[Rect]): """ Sets the cropbox of a PyMuPDF page safely and defensively. If the 'original_cropbox' is valid (i.e., a pymupdf.Rect instance, not None, not empty, not infinite, and fully contained within the page's mediabox), it is set as the cropbox. Otherwise, the page's mediabox is used, and a warning is printed to explain why. Args: page: The PyMuPDF page object. original_cropbox: The Rect representing the desired cropbox. """ mediabox = page.mediabox reason_for_defaulting = "" # Check for None if original_cropbox is None: reason_for_defaulting = "the original cropbox is None." # Check for incorrect type elif not isinstance(original_cropbox, Rect): reason_for_defaulting = f"the original cropbox is not a pymupdf.Rect instance (got {type(original_cropbox)})." else: # Normalise the cropbox (ensures x0 < x1 and y0 < y1) original_cropbox.normalize() # Check for empty or infinite or out-of-bounds if original_cropbox.is_empty: reason_for_defaulting = ( f"the provided original cropbox {original_cropbox} is empty." ) elif original_cropbox.is_infinite: reason_for_defaulting = ( f"the provided original cropbox {original_cropbox} is infinite." ) elif not mediabox.contains(original_cropbox): reason_for_defaulting = ( f"the provided original cropbox {original_cropbox} is not fully contained " f"within the page's mediabox {mediabox}." ) if reason_for_defaulting: # print( # f"Warning (Page {page.number}): Cannot use original cropbox because {reason_for_defaulting} " # f"Defaulting to the page's mediabox as the cropbox." # ) page.set_cropbox(mediabox) else: page.set_cropbox(original_cropbox) def convert_color_to_range_0_1(color): return tuple(component / 255 for component in color) def define_box_colour( custom_colours: bool, img_annotation_box: dict, CUSTOM_BOX_COLOUR: tuple ): """ Determines the color for a bounding box annotation. If `custom_colours` is True, it attempts to parse the color from `img_annotation_box['color']`. It supports color strings in "(R,G,B)" format (0-255 integers) or tuples/lists of (R,G,B) where components are either 0-1 floats or 0-255 integers. If parsing fails or `custom_colours` is False, it defaults to `CUSTOM_BOX_COLOUR`. All output colors are converted to a 0.0-1.0 float range. Args: custom_colours (bool): If True, attempts to use a custom color from `img_annotation_box`. img_annotation_box (dict): A dictionary that may contain a 'color' key with the custom color. CUSTOM_BOX_COLOUR (tuple): The default color to use if custom colors are not enabled or parsing fails. Expected to be a tuple of (R, G, B) with values in the 0.0-1.0 range. Returns: tuple: A tuple (R, G, B) representing the chosen color, with components in the 0.0-1.0 float range. """ if custom_colours is True: color_input = img_annotation_box["color"] out_colour = (0, 0, 0) # Initialize with a default black color (0.0-1.0 range) if isinstance(color_input, str): # Expected format: "(R,G,B)" where R,G,B are integers 0-255 (e.g., "(255,0,0)") try: # Remove parentheses and split by comma, then convert to integers components_str = color_input.strip().strip("()").split(",") colour_tuple_int = tuple(int(c.strip()) for c in components_str) # Validate the parsed integer tuple if len(colour_tuple_int) == 3 and not all( 0 <= c <= 1 for c in colour_tuple_int ): out_colour = convert_color_to_range_0_1(colour_tuple_int) elif len(colour_tuple_int) == 3 and all( 0 <= c <= 1 for c in colour_tuple_int ): out_colour = colour_tuple_int else: print( f"Warning: Invalid color string values or length for '{color_input}'. Expected (R,G,B) with R,G,B in 0-255. Defaulting to black." ) except (ValueError, IndexError): print( f"Warning: Could not parse color string '{color_input}'. Expected '(R,G,B)' format. Defaulting to black." ) elif isinstance(color_input, (tuple, list)) and len(color_input) == 3: # Expected formats: (R,G,B) where R,G,B are either 0-1 floats or 0-255 integers if all(isinstance(c, (int, float)) for c in color_input): # Case 1: Components are already 0.0-1.0 floats if all(isinstance(c, float) and 0.0 <= c <= 1.0 for c in color_input): out_colour = tuple(color_input) # Case 2: Components are 0-255 integers elif not all( isinstance(c, float) and 0.0 <= c <= 1.0 for c in color_input ): out_colour = convert_color_to_range_0_1(color_input) else: # Numeric values but not in expected 0-1 float or 0-255 integer ranges print( f"Warning: Invalid color tuple/list values {color_input}. Expected (R,G,B) with R,G,B in 0-1 floats or 0-255 integers. Defaulting to black." ) else: # Contains non-numeric values (e.g., (1, 'a', 3)) print( f"Warning: Color tuple/list {color_input} contains non-numeric values. Defaulting to black." ) else: # Catch-all for any other unexpected format (e.g., None, dict, etc.) print( f"Warning: Unexpected color format for {color_input}. Expected string '(R,G,B)' or tuple/list (R,G,B). Defaulting to black." ) # Final safeguard: Ensure out_colour is always a valid PyMuPDF color tuple (3 floats 0.0-1.0) if not ( isinstance(out_colour, tuple) and len(out_colour) == 3 and all(isinstance(c, float) and 0.0 <= c <= 1.0 for c in out_colour) ): out_colour = (0.0, 0.0, 0.0) else: if CUSTOM_BOX_COLOUR: # Should be a tuple of three integers between 0 and 255 from config if ( isinstance(CUSTOM_BOX_COLOUR, (tuple, list)) and len(CUSTOM_BOX_COLOUR) >= 3 ): # Convert from 0-255 range to 0-1 range out_colour = tuple( float(component / 255) if component >= 1 else float(component) for component in CUSTOM_BOX_COLOUR[:3] ) else: out_colour = (0.0, 0.0, 0.0) # PyMuPDF requires 1, 3 or 4 float components in 0-1; ensure tuple of floats if isinstance(out_colour, (tuple, list)) and len(out_colour) in (3, 4): out_colour = tuple(float(max(0.0, min(1.0, c))) for c in out_colour) else: out_colour = (0.0, 0.0, 0.0) return out_colour # Bbox height ≥ this fraction of page height uses a near-full-height text strip (whole blocks / tables). _TEXT_REDACT_STRIP_LARGE_BOX_PAGE_FRACTION = 0.23 def _text_overlap_redact_rect( pymupdf_page: Page, pymupdf_rect: Rect, img_annotation_box: dict, ) -> Rect: """ Rectangle for add_redact_annot text removal: centered strip scaled by bbox height, with guards for whole-page and other tall boxes. """ x1, y1, x2, y2 = ( float(pymupdf_rect[0]), float(pymupdf_rect[1]), float(pymupdf_rect[2]), float(pymupdf_rect[3]), ) box_h = max(0.0, y2 - y1) page_h = float(pymupdf_page.rect.height) label = (img_annotation_box.get("label") or "").strip() hx1, hx2 = x1 + 2, x2 - 2 if hx1 >= hx2: hx1, hx2 = x1, x2 use_near_full_height = label == "Whole page" or ( page_h > 0 and box_h >= _TEXT_REDACT_STRIP_LARGE_BOX_PAGE_FRACTION * page_h ) if use_near_full_height or box_h <= 0: redact_bottom_y = y1 + 2 redact_top_y = y2 - 2 if (redact_top_y - redact_bottom_y) < 1: middle_y = (y1 + y2) / 2 redact_bottom_y = middle_y - 1 redact_top_y = middle_y + 1 return Rect(hx1, redact_bottom_y, hx2, redact_top_y) y_mid = (y1 + y2) / 2 strip_h = box_h * REDACT_TEXT_STRIP_HEIGHT_FRACTION strip_h = max(strip_h, 0.5) strip_h = min(strip_h, box_h) if strip_h < 1.0: redact_bottom_y = y_mid - 1 redact_top_y = y_mid + 1 else: redact_bottom_y = max(y1, y_mid - strip_h / 2) redact_top_y = min(y2, y_mid + strip_h / 2) if redact_top_y <= redact_bottom_y: redact_bottom_y = y_mid - 1 redact_top_y = y_mid + 1 return Rect(hx1, redact_bottom_y, hx2, redact_top_y) def redact_single_box( pymupdf_page: Page, pymupdf_rect: Rect, img_annotation_box: dict, custom_colours: bool = USE_GUI_BOX_COLOURS_FOR_OUTPUTS, retain_text: bool = RETURN_PDF_FOR_REVIEW, return_pdf_end_of_redaction: bool = RETURN_REDACTED_PDF, ): """ Commit redaction boxes to a PyMuPDF page. Args: pymupdf_page (Page): The PyMuPDF page object to which the redaction will be applied. pymupdf_rect (Rect): The PyMuPDF rectangle defining the bounds of the redaction box. img_annotation_box (dict): A dictionary containing annotation details, such as label, text, and color. custom_colours (bool, optional): If True, uses custom colors for the final redacted PDF (..._redacted.pdf). The review PDF (..._redactions_for_review.pdf) always uses custom colours. Defaults to USE_GUI_BOX_COLOURS_FOR_OUTPUTS. retain_text (bool, optional): If True, adds a redaction annotation but retains the underlying text. If False, the text within the redaction area is deleted. Defaults to RETURN_PDF_FOR_REVIEW. return_pdf_end_of_redaction (bool, optional): If True, returns both review and final redacted page objects. Defaults to RETURN_REDACTED_PDF. Returns: Page or Tuple[Page, Page]: If return_pdf_end_of_redaction is True and retain_text is True, returns a tuple of (review_page, applied_redaction_page). Otherwise returns a single Page. """ pymupdf_x1 = pymupdf_rect[0] pymupdf_y1 = pymupdf_rect[1] pymupdf_x2 = pymupdf_rect[2] pymupdf_y2 = pymupdf_rect[3] img_annotation_box["text"] = img_annotation_box.get("text") or "" img_annotation_box["label"] = img_annotation_box.get("label") or "Redaction" # Full size redaction box for covering all the text of a word full_size_redaction_box = Rect( pymupdf_x1 - 1, pymupdf_y1 - 1, pymupdf_x2 + 1, pymupdf_y2 + 1 ) rect_small_pixel_height = _text_overlap_redact_rect( pymupdf_page, pymupdf_rect, img_annotation_box ) # Review PDF (..._redactions_for_review.pdf): always use custom colours review_colour = define_box_colour(True, img_annotation_box, CUSTOM_BOX_COLOUR) # Final redacted PDF (..._redacted.pdf): respect USE_GUI_BOX_COLOURS_FOR_OUTPUTS output_colour = define_box_colour( custom_colours, img_annotation_box, CUSTOM_BOX_COLOUR ) # Create a copy of the page for final redaction if needed applied_redaction_page = None if return_pdf_end_of_redaction and retain_text: # Create a deep copy of the page for final redaction applied_redaction_page = pymupdf.open() applied_redaction_page.insert_pdf( pymupdf_page.parent, from_page=pymupdf_page.number, to_page=pymupdf_page.number, ) applied_redaction_page = applied_redaction_page[0] # Handle review page first, then deal with final redacted page (retain_text = True) if retain_text is True: annot = pymupdf_page.add_redact_annot(full_size_redaction_box) annot.set_colors(stroke=review_colour, fill=review_colour, colors=review_colour) annot.set_name(img_annotation_box["label"]) # Cache creationDate per second to avoid thousands of strftime calls per document now_sec = int(time.time()) if not hasattr(redact_single_box, "_creation_date_cache"): redact_single_box._creation_date_cache = [0, ""] if redact_single_box._creation_date_cache[0] != now_sec: redact_single_box._creation_date_cache[0] = now_sec redact_single_box._creation_date_cache[1] = datetime.now().strftime( "%Y%m%d%H%M%S" ) annot.set_info( info=img_annotation_box["label"], title=img_annotation_box["label"], subject=img_annotation_box["label"], content=img_annotation_box["text"], creationDate=redact_single_box._creation_date_cache[1], ) annot.update(opacity=0.5, cross_out=False) # If we need both review and final pages, and the applied redaction page has been prepared, apply final redaction to the copy if return_pdf_end_of_redaction and applied_redaction_page is not None: # Apply final redaction to the copy # Add the annotation to the middle of the character line, so that it doesn't delete text from adjacent lines applied_redaction_page.add_redact_annot(rect_small_pixel_height) # Only create a box over the whole rect if we want to delete the text shape = applied_redaction_page.new_shape() shape.draw_rect(pymupdf_rect) # Use solid fill for normal redaction shape.finish(color=output_colour, fill=output_colour) shape.commit() return pymupdf_page, applied_redaction_page else: return pymupdf_page # If we don't need to retain the text, we only have one page which is the applied redaction page, so just apply the redaction to the page else: # Add the annotation to the middle of the character line, so that it doesn't delete text from adjacent lines pymupdf_page.add_redact_annot(rect_small_pixel_height) # Only create a box over the whole rect if we want to delete the text shape = pymupdf_page.new_shape() shape.draw_rect(pymupdf_rect) # PyMuPDF requires 1, 3 or 4 float components in range 0-1 _colour = output_colour if isinstance(_colour, (tuple, list)) and len(_colour) in (3, 4): _colour = tuple(float(max(0.0, min(1.0, c))) for c in _colour) else: _colour = (0.0, 0.0, 0.0) shape.finish(color=_colour, fill=_colour) shape.commit() return pymupdf_page def redact_whole_pymupdf_page( rect_height: float, rect_width: float, page: Page, custom_colours: bool = False, border: float = 5, redact_pdf: bool = True, ): """ Redacts a whole page of a PDF document. Args: rect_height (float): The height of the page in points. rect_width (float): The width of the page in points. page (Page): The PyMuPDF page object to be redacted. custom_colours (bool, optional): If True, uses custom colors for the redaction box. border (float, optional): The border width in points. Defaults to 5. redact_pdf (bool, optional): If True, redacts the PDF document. Defaults to True. """ # Small border to page that remains white # Define the coordinates for the Rect (PDF coordinates for actual redaction) whole_page_x1, whole_page_y1 = 0 + border, 0 + border # Bottom-left corner whole_page_x2, whole_page_y2 = ( rect_width - border, rect_height - border, ) # Top-right corner # Create new image annotation element based on whole page coordinates whole_page_rect = Rect(whole_page_x1, whole_page_y1, whole_page_x2, whole_page_y2) # Calculate relative coordinates for the annotation box (0-1 range) # This ensures the coordinates are already in relative format for output files relative_border = border / min( rect_width, rect_height ) # Scale border proportionally relative_x1 = relative_border relative_y1 = relative_border relative_x2 = 1 - relative_border relative_y2 = 1 - relative_border # Write whole page annotation to annotation boxes using relative coordinates whole_page_img_annotation_box = dict() whole_page_img_annotation_box["xmin"] = relative_x1 whole_page_img_annotation_box["ymin"] = relative_y1 whole_page_img_annotation_box["xmax"] = relative_x2 whole_page_img_annotation_box["ymax"] = relative_y2 # Match word-level redactions: define_box_colour uses this when GUI/output colours are on. whole_page_img_annotation_box["color"] = CUSTOM_BOX_COLOUR whole_page_img_annotation_box["label"] = "Whole page" if redact_pdf is True: redact_single_box( page, whole_page_rect, whole_page_img_annotation_box, custom_colours ) return whole_page_img_annotation_box def _merge_adjacent_redaction_boxes( boxes: List[dict], threshold: float = 2.0, ) -> List[dict]: """ Merge overlapping or nearly touching dict-style redaction boxes into fewer larger rectangles. Boxes must have xmin, ymin, xmax, ymax. Other keys are taken from the first box in each merged group. In-place style: repeatedly merge any two boxes that overlap or are within threshold (in coordinate units), until no merges possible. """ if not boxes or len(boxes) <= 1: return list(boxes) def _union(b1: dict, b2: dict) -> dict: out = dict(b1) out["xmin"] = min(b1["xmin"], b2["xmin"]) out["ymin"] = min(b1["ymin"], b2["ymin"]) out["xmax"] = max(b1["xmax"], b2["xmax"]) out["ymax"] = max(b1["ymax"], b2["ymax"]) return out def _y_overlap_ratio(b1: dict, b2: dict) -> float: h1 = max(0.0, float(b1["ymax"]) - float(b1["ymin"])) h2 = max(0.0, float(b2["ymax"]) - float(b2["ymin"])) denom = min(h1, h2) if denom <= 0: return 0.0 overlap = max( 0.0, min(float(b1["ymax"]), float(b2["ymax"])) - max(float(b1["ymin"]), float(b2["ymin"])), ) return overlap / denom def _overlap_or_close(b1: dict, b2: dict) -> bool: # Guard rail: do not merge across separate visual lines unless explicitly allowed. # This prevents a single giant union box when two redactions happen to be consecutive # in reading order but are located on very different y positions. if MERGE_SMALL_REDACTIONS_SAME_LINE_ONLY: if _y_overlap_ratio(b1, b2) < MERGE_SMALL_REDACTIONS_MIN_Y_OVERLAP_RATIO: return False if b1["xmax"] + threshold < b2["xmin"] or b2["xmax"] + threshold < b1["xmin"]: return False if b1["ymax"] + threshold < b2["ymin"] or b2["ymax"] + threshold < b1["ymin"]: return False return True merged = list(boxes) while True: changed = False for i in range(len(merged)): for j in range(i + 1, len(merged)): if _overlap_or_close(merged[i], merged[j]): merged[i] = _union(merged[i], merged[j]) merged.pop(j) changed = True break if changed: break if not changed: break return merged def redact_page_with_pymupdf( page: Page, page_annotations: dict, image: Image = None, custom_colours: bool = USE_GUI_BOX_COLOURS_FOR_OUTPUTS, redact_whole_page: bool = False, convert_pikepdf_to_pymupdf_coords: bool = True, original_cropbox: List[Rect] = list(), page_sizes_df: pd.DataFrame = pd.DataFrame(), return_pdf_for_review: bool = RETURN_PDF_FOR_REVIEW, return_pdf_end_of_redaction: bool = RETURN_REDACTED_PDF, input_folder: str = INPUT_FOLDER, image_dimensions_override: Optional[dict] = None, review_page: Optional[Page] = None, ): """ Applies redactions to a single PyMuPDF page based on provided annotations. This function processes various types of annotations (Gradio, CustomImageRecognizerResult, or pikepdf-like) and applies them as redactions to the given PyMuPDF page. It can also redact the entire page if specified. Args: page (Page): The PyMuPDF page object to which redactions will be applied. page_annotations (dict): A dictionary containing annotation data for the current page. Expected to have a 'boxes' key with a list of annotation boxes. image (Image, optional): A PIL Image object or path to an image file associated with the page. Used for coordinate conversions if available. Defaults to None. custom_colours (bool, optional): If True, custom box colors will be used for redactions. Defaults to USE_GUI_BOX_COLOURS_FOR_OUTPUTS. redact_whole_page (bool, optional): If True, the entire page will be redacted. Defaults to False. convert_pikepdf_to_pymupdf_coords (bool, optional): If True, coordinates from pikepdf-like annotations will be converted to PyMuPDF's coordinate system. Defaults to True. original_cropbox (List[Rect], optional): The original cropbox of the page. This is used to restore the cropbox after redactions. Defaults to an empty list. page_sizes_df (pd.DataFrame, optional): A DataFrame containing page size and image dimension information, used for coordinate scaling. Defaults to an empty DataFrame. return_pdf_for_review (bool, optional): If True, redactions are applied in a way suitable for review (e.g., not removing underlying text/images completely). Defaults to RETURN_PDF_FOR_REVIEW. return_pdf_end_of_redaction (bool, optional): If True, returns both review and final redacted page objects. Defaults to RETURN_REDACTED_PDF. review_page (Page, optional): When provided, the same redactions are applied to this page (with text retained for review) in a single pass, avoiding a second full annotation loop. Returns: Tuple[Page, dict] or Tuple[Tuple[Page, Page], dict]: A tuple containing: - page (Page or Tuple[Page, Page]): The PyMuPDF page object(s) with redactions applied. If return_pdf_end_of_redaction is True and return_pdf_for_review is True, returns a tuple of (review_page, applied_redaction_page). - out_annotation_boxes (dict): A dictionary containing the processed annotation boxes for the page, including the image path. """ rect_height = page.rect.height rect_width = page.rect.width mediabox_height = page.mediabox.height mediabox_width = page.mediabox.width page_no = page.number page_num_reported = page_no + 1 # Use precomputed dimensions when provided (skips all DataFrame work on hot path) if image_dimensions_override and isinstance(image_dimensions_override, dict): image_dimensions = dict(image_dimensions_override) else: image_dimensions = dict() # Only convert/lookup when caller did not pass dimensions (avoids O(n_pages) per call) if not page_sizes_df.empty and "page" in page_sizes_df.columns: if not pd.api.types.is_numeric_dtype(page_sizes_df["page"]): page_sizes_df[["page"]] = page_sizes_df[["page"]].apply( pd.to_numeric, errors="coerce" ) if not image and "image_width" in page_sizes_df.columns: if not pd.api.types.is_numeric_dtype(page_sizes_df["image_width"]): page_sizes_df[["image_width"]] = page_sizes_df[["image_width"]].apply( pd.to_numeric, errors="coerce" ) if not pd.api.types.is_numeric_dtype(page_sizes_df["image_height"]): page_sizes_df[["image_height"]] = page_sizes_df[["image_height"]].apply( pd.to_numeric, errors="coerce" ) image_dimensions["image_width"] = page_sizes_df.loc[ page_sizes_df["page"] == page_num_reported, "image_width" ].max() image_dimensions["image_height"] = page_sizes_df.loc[ page_sizes_df["page"] == page_num_reported, "image_height" ].max() if pd.isna(image_dimensions.get("image_width")): image_dimensions = dict() out_annotation_boxes = dict() all_image_annotation_boxes = list() dual_output_same_pass = ( return_pdf_end_of_redaction and return_pdf_for_review and review_page is None ) applied_redaction_page = None if dual_output_same_pass: applied_redaction_doc = pymupdf.open() applied_redaction_doc.insert_pdf( page.parent, from_page=page.number, to_page=page.number, ) applied_redaction_page = applied_redaction_doc[0] if isinstance(image, Image.Image): # Create an image path using the input folder with PDF filename # Get the PDF filename from the page's parent document pdf_filename = ( os.path.basename(page.parent.name) if hasattr(page.parent, "name") and page.parent.name else "document" ) # Normalize and validate path safety before using in file path construction normalized_filename = os.path.normpath(pdf_filename) # Ensure the filename doesn't contain path traversal characters if ( ".." in normalized_filename or "/" in normalized_filename or "\\" in normalized_filename ): normalized_filename = "document" # Fallback to safe default image_path = os.path.join( input_folder, f"{normalized_filename}_{page.number}.png" ) # Skip disk save when dimensions were precomputed (avoids I/O; file not needed for lookup) if not image_dimensions_override and not os.path.exists(image_path): image.save(image_path) elif isinstance(image, str): # Normalize and validate path safety before checking existence. # Use input_folder (caller's) so page images under output_folder can be loaded # when the caller passes a folder that contains them (e.g. second redaction run). normalized_path = os.path.normpath(os.path.abspath(image)) if validate_path_containment(normalized_path, input_folder): image_path = normalized_path image = Image.open(image_path) elif "image_path" in page_sizes_df.columns: try: image_path = page_sizes_df.loc[ page_sizes_df["page"] == (page_no + 1), "image_path" ].iloc[0] except IndexError: image_path = "" image = None else: image_path = "" image = None else: # print("image is not an Image object or string") image_path = "" image = None # Check if this is an object used in the Gradio Annotation component if isinstance(page_annotations, dict): page_annotations = page_annotations["boxes"] # Optional: merge overlapping/close dict boxes to reduce redact_single_box calls if ( MERGE_SMALL_REDACTIONS and page_annotations and all(isinstance(b, dict) for b in page_annotations) ): page_annotations = _merge_adjacent_redaction_boxes(page_annotations) for annot in page_annotations: # Pikepdf redaction annotations (from text-path create_pikepdf_annotations_for_bounding_boxes) # must be handled first; do not treat Dictionary as dict. if isinstance(annot, Dictionary): if not image: convert_pikepdf_to_pymupdf_coords = True img_annotation_box, rect = ( convert_pikepdf_annotations_to_result_annotation_box( page, annot, image, convert_pikepdf_to_pymupdf_coords, page_sizes_df, image_dimensions=image_dimensions, ) ) img_annotation_box = fill_missing_box_ids(img_annotation_box) all_image_annotation_boxes.append(img_annotation_box) if review_page is not None: redact_single_box( page, rect, img_annotation_box, custom_colours, retain_text=False, return_pdf_end_of_redaction=False, ) redact_single_box( review_page, rect, img_annotation_box, custom_colours, retain_text=True, return_pdf_end_of_redaction=False, ) elif dual_output_same_pass and applied_redaction_page is not None: # Apply both review and final redactions cumulatively on the same page copies. redact_single_box( page, rect, img_annotation_box, custom_colours, retain_text=True, return_pdf_end_of_redaction=False, ) redact_single_box( applied_redaction_page, rect, img_annotation_box, custom_colours, retain_text=False, return_pdf_end_of_redaction=False, ) else: redact_result = redact_single_box( page, rect, img_annotation_box, custom_colours, return_pdf_for_review, return_pdf_end_of_redaction, ) if isinstance(redact_result, tuple): page, _ = redact_result continue # Check if an Image recogniser result, or a Gradio annotation object if (isinstance(annot, CustomImageRecognizerResult)) or isinstance(annot, dict): img_annotation_box = dict() # Should already be in correct format if img_annotator_box is an input if isinstance(annot, dict): annot = fill_missing_box_ids(annot) img_annotation_box = annot # Whole page redactions: always use full-page rect so they are reliably # included when applying from Review tab (e.g. redactions_for_review.pdf) whole_page_border = 5 if img_annotation_box.get("label") == "Whole page": pymupdf_x1 = 0 + whole_page_border pymupdf_y1 = 0 + whole_page_border pymupdf_x2 = rect_width - whole_page_border pymupdf_y2 = rect_height - whole_page_border rect = Rect(pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2) rect = _rect_display_to_unrotated(page, rect) else: box_coordinates = ( img_annotation_box["xmin"], img_annotation_box["ymin"], img_annotation_box["xmax"], img_annotation_box["ymax"], ) # Check if all coordinates are equal to or less than 1 are_coordinates_relative = all( coord <= 1 for coord in box_coordinates ) if are_coordinates_relative is True: # Check if coordinates are relative, if so then multiply by mediabox size pymupdf_x1 = img_annotation_box["xmin"] * mediabox_width pymupdf_y1 = img_annotation_box["ymin"] * mediabox_height pymupdf_x2 = img_annotation_box["xmax"] * mediabox_width pymupdf_y2 = img_annotation_box["ymax"] * mediabox_height elif image_dimensions or image: pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 = ( convert_gradio_image_annotator_object_coords_to_pymupdf( page, img_annotation_box, image, image_dimensions ) ) else: print( "Could not convert image annotator coordinates in redact_page_with_pymupdf" ) pymupdf_x1 = img_annotation_box["xmin"] pymupdf_y1 = img_annotation_box["ymin"] pymupdf_x2 = img_annotation_box["xmax"] pymupdf_y2 = img_annotation_box["ymax"] if "text" in annot and annot["text"]: img_annotation_box["text"] = str(annot["text"]) else: img_annotation_box["text"] = "" rect = Rect( pymupdf_x1, pymupdf_y1, pymupdf_x2, pymupdf_y2 ) # Create the PyMuPDF Rect (display space when from image/gradio) rect = _rect_display_to_unrotated(page, rect) # Else should be CustomImageRecognizerResult elif isinstance(annot, CustomImageRecognizerResult): # print("annot is a CustomImageRecognizerResult") img_annotation_box, rect = ( prepare_custom_image_recogniser_result_annotation_box( page, annot, image, page_sizes_df, custom_colours ) ) # Else it should be a pikepdf annotation object (handled above via Dictionary check) else: img_annotation_box, rect = ( convert_pikepdf_annotations_to_result_annotation_box( page, annot, image, convert_pikepdf_to_pymupdf_coords, page_sizes_df, image_dimensions=image_dimensions, ) ) img_annotation_box = fill_missing_box_ids(img_annotation_box) all_image_annotation_boxes.append(img_annotation_box) # Redact the annotations from the document if review_page is not None: redact_single_box( page, rect, img_annotation_box, custom_colours, retain_text=False, return_pdf_end_of_redaction=False, ) redact_single_box( review_page, rect, img_annotation_box, custom_colours, retain_text=True, return_pdf_end_of_redaction=False, ) elif dual_output_same_pass and applied_redaction_page is not None: # Apply both review and final redactions cumulatively on the same page copies. redact_single_box( page, rect, img_annotation_box, custom_colours, retain_text=True, return_pdf_end_of_redaction=False, ) redact_single_box( applied_redaction_page, rect, img_annotation_box, custom_colours, retain_text=False, return_pdf_end_of_redaction=False, ) else: redact_result = redact_single_box( page, rect, img_annotation_box, custom_colours, return_pdf_for_review, return_pdf_end_of_redaction, ) # Handle dual page objects if returned if isinstance(redact_result, tuple): page, _ = redact_result # If whole page is to be redacted, do that here if redact_whole_page is True: whole_page_img_annotation_box = redact_whole_pymupdf_page( rect_height, rect_width, page, custom_colours, border=5 ) if review_page is not None: redact_whole_pymupdf_page( rect_height, rect_width, review_page, custom_colours, border=5 ) # Ensure the whole page annotation box has a unique ID whole_page_img_annotation_box = fill_missing_box_ids( whole_page_img_annotation_box ) all_image_annotation_boxes.append(whole_page_img_annotation_box) # In dual-output mode, apply whole-page redaction to the final page copy too. if dual_output_same_pass and applied_redaction_page is not None: redact_whole_pymupdf_page( rect_height, rect_width, applied_redaction_page, custom_colours, border=5, ) out_annotation_boxes = { "image": image_path, # Image.open(image_path), #image_path, "boxes": all_image_annotation_boxes, } # If we are not returning the review page, can directly remove text and all images if return_pdf_for_review is False: page.apply_redactions( images=APPLY_REDACTIONS_IMAGES, graphics=APPLY_REDACTIONS_GRAPHICS, text=APPLY_REDACTIONS_TEXT, ) set_cropbox_safely(page, original_cropbox) page.clean_contents() if review_page is not None: set_cropbox_safely(review_page, original_cropbox) review_page.clean_contents() # Handle dual page objects if we have a final page if dual_output_same_pass and applied_redaction_page is not None: # Apply redactions to applied redaction page only applied_redaction_page.apply_redactions( images=APPLY_REDACTIONS_IMAGES, graphics=APPLY_REDACTIONS_GRAPHICS, text=APPLY_REDACTIONS_TEXT, ) set_cropbox_safely(applied_redaction_page, original_cropbox) applied_redaction_page.clean_contents() return (page, applied_redaction_page), out_annotation_boxes else: return page, out_annotation_boxes ### # IMAGE-BASED OCR PDF TEXT DETECTION/REDACTION WITH TESSERACT OR AWS TEXTRACT ### def merge_img_bboxes( bboxes: list, combined_results: Dict, page_signature_recogniser_results: list = list(), page_handwriting_recogniser_results: list = list(), handwrite_signature_checkbox: List[str] = [ "Extract handwriting", "Extract signatures", ], horizontal_threshold: int = 50, vertical_threshold: int = 12, max_word_gap_px: int | None = None, max_word_gap_height_multiplier: float = 3.0, ): """ Merges bounding boxes for image annotations based on the provided results. Args: bboxes (list): A list of bounding boxes to be merged. combined_results (Dict): A dictionary containing combined results with line text and their corresponding bounding boxes. page_signature_recogniser_results (list, optional): A list of results from the signature recognizer. Defaults to an empty list. page_handwriting_recogniser_results (list, optional): A list of results from the handwriting recognizer. Defaults to an empty list. handwrite_signature_checkbox (List[str], optional): A list of options indicating whether to extract handwriting and signatures. Defaults to ["Extract handwriting", "Extract signatures"]. horizontal_threshold (int, optional): The threshold for merging bounding boxes horizontally. Defaults to 50. vertical_threshold (int, optional): The threshold for merging bounding boxes vertically. Defaults to 12. max_word_gap_px (int | None, optional): Maximum horizontal pixel gap allowed between consecutive OCR words when reconstructing a single bbox from multiple word boxes. If None, this is derived from `horizontal_threshold` and word height. Defaults to None. max_word_gap_height_multiplier (float, optional): Additional guard rail for word merging: consecutive words must also be within (multiplier * typical_word_height) pixels horizontally. Defaults to 3.0. Returns: None: This function modifies the bounding boxes in place and does not return a value. """ all_bboxes = list() merged_bboxes = list() grouped_bboxes = defaultdict(list) # Deep copy original bounding boxes to retain them original_bboxes = copy.deepcopy(bboxes) # Process signature and handwriting results if page_signature_recogniser_results or page_handwriting_recogniser_results: if "Extract handwriting" in handwrite_signature_checkbox: # print("Extracting handwriting in merge_img_bboxes function") merged_bboxes.extend(copy.deepcopy(page_handwriting_recogniser_results)) if "Extract signatures" in handwrite_signature_checkbox: # print("Extracting signatures in merge_img_bboxes function") merged_bboxes.extend(copy.deepcopy(page_signature_recogniser_results)) # Add VLM [FACE] and [SIGNATURE] detections from combined_results, if present try: for line_info in combined_results.values(): words = line_info.get("words", []) for word in words: text_val = word.get("text") if text_val not in ["[FACE]", "[SIGNATURE]"]: continue conf_raw = float(word.get("conf", word.get("confidence", 0.0))) conf = conf_raw / 100.0 if conf_raw > 1.0 else conf_raw conf = max(0.0, min(1.0, conf)) if conf < CUSTOM_VLM_MIN_CONFIDENCE: continue x0, y0, x1, y1 = word.get("bounding_box", (0, 0, 0, 0)) width = x1 - x0 height = y1 - y0 entity_type = ( "CUSTOM_VLM_FACES" if text_val == "[FACE]" else "CUSTOM_VLM_SIGNATURE" ) merged_bboxes.append( CustomImageRecognizerResult( entity_type, 0, 0, conf, int(x0), int(y0), int(width), int(height), text_val, ) ) except Exception as e: print( f"Warning: Error while adding VLM [FACE]/[SIGNATURE] boxes in merge_img_bboxes: {e}" ) # Reconstruct and merge bounding boxes only if MERGE_BOUNDING_BOXES is enabled if MERGE_BOUNDING_BOXES: # Reconstruct bounding boxes for substrings of interest reconstructed_bboxes = list() for bbox in bboxes: bbox_box = ( bbox.left, bbox.top, bbox.left + bbox.width, bbox.top + bbox.height, ) for line_key, line_info in combined_results.items(): line_box = line_info["bounding_box"] # Use actual line text (not the key, which is e.g. "text_line_1") for substring matching actual_line_text = line_info.get("text", "") if bounding_boxes_overlap(bbox_box, line_box): if actual_line_text and bbox.text in actual_line_text: start_char = actual_line_text.index(bbox.text) end_char = start_char + len(bbox.text) relevant_words = list() current_char = 0 for word in line_info["words"]: word_end = current_char + len(word["text"]) if ( current_char <= start_char < word_end or current_char < end_char <= word_end or (start_char <= current_char and word_end <= end_char) ): relevant_words.append(word) if word_end >= end_char: break current_char = word_end if not word["text"].endswith(" "): current_char += 1 # +1 for space if the word doesn't already end with a space if relevant_words: # Sort by x so we can guard against large physical gaps between consecutive words. relevant_words_sorted = sorted( relevant_words, key=lambda w: w["bounding_box"][0] ) # Derive a sensible max word-gap if not provided: # - keep existing `horizontal_threshold` behaviour as an absolute cap # - also cap by a multiple of typical word height (helps across varying DPI/font sizes) word_heights = [ max(0, int(w["bounding_box"][3] - w["bounding_box"][1])) for w in relevant_words_sorted ] typical_word_height = 0 if word_heights: word_heights_sorted = sorted(word_heights) typical_word_height = word_heights_sorted[ len(word_heights_sorted) // 2 ] derived_gap_px = None if typical_word_height > 0: derived_gap_px = int( max_word_gap_height_multiplier * typical_word_height ) gap_px_limit = ( max_word_gap_px if max_word_gap_px is not None else ( min(horizontal_threshold, derived_gap_px) if derived_gap_px is not None else horizontal_threshold ) ) # Cluster words into contiguous groups; don't span large whitespace gaps. word_clusters: list[list[dict]] = [] current_cluster: list[dict] = [] for w in relevant_words_sorted: if not current_cluster: current_cluster = [w] continue prev = current_cluster[-1] prev_right = prev["bounding_box"][2] cur_left = w["bounding_box"][0] gap = cur_left - prev_right # If the OCR token sequence implies adjacency but the physical gap is large, # split into separate clusters (prevents over-wide merged redaction boxes). if gap > gap_px_limit: word_clusters.append(current_cluster) current_cluster = [w] else: current_cluster.append(w) if current_cluster: word_clusters.append(current_cluster) # Create one reconstructed bbox per cluster (often 1, but can be >1 when OCR words # are consecutive in text yet far apart in image coordinates). for cluster in word_clusters: left = min(word["bounding_box"][0] for word in cluster) top = min(word["bounding_box"][1] for word in cluster) right = max(word["bounding_box"][2] for word in cluster) bottom = max( word["bounding_box"][3] for word in cluster ) combined_text = " ".join( word["text"] for word in cluster ) reconstructed_bboxes.append( CustomImageRecognizerResult( bbox.entity_type, bbox.start, bbox.end, bbox.score, left, top, right - left, # width bottom - top, # height, combined_text, ) ) break else: reconstructed_bboxes.append(bbox) # Group reconstructed bboxes by approximate vertical proximity for box in reconstructed_bboxes: grouped_bboxes[round(box.top / vertical_threshold)].append(box) # Merge within each group for _, group in grouped_bboxes.items(): group.sort(key=lambda box: box.left) merged_box = group[0] for next_box in group[1:]: gap = next_box.left - (merged_box.left + merged_box.width) # Extra guard rail: require both the absolute threshold and a height-scaled threshold. # This reduces accidental merges across big whitespace when text is small. height_scaled_limit = int( max_word_gap_height_multiplier * max(1, min(merged_box.height, next_box.height)) ) if gap <= horizontal_threshold and gap <= height_scaled_limit: if next_box.text != merged_box.text: new_text = merged_box.text + " " + next_box.text else: new_text = merged_box.text if merged_box.entity_type != next_box.entity_type: new_entity_type = ( merged_box.entity_type + " - " + next_box.entity_type ) else: new_entity_type = merged_box.entity_type new_left = min(merged_box.left, next_box.left) new_top = min(merged_box.top, next_box.top) new_width = ( max( merged_box.left + merged_box.width, next_box.left + next_box.width, ) - new_left ) new_height = ( max( merged_box.top + merged_box.height, next_box.top + next_box.height, ) - new_top ) merged_box = CustomImageRecognizerResult( new_entity_type, merged_box.start, merged_box.end, merged_box.score, new_left, new_top, new_width, new_height, new_text, ) else: merged_bboxes.append(merged_box) merged_box = next_box merged_bboxes.append(merged_box) all_bboxes.extend(original_bboxes) all_bboxes.extend(merged_bboxes) # Return the unique original and merged bounding boxes unique_bboxes = list( { (bbox.left, bbox.top, bbox.width, bbox.height): bbox for bbox in all_bboxes }.values() ) return unique_bboxes def redact_image_pdf( file_path: str, pdf_image_file_paths: List[str], language: str, chosen_redact_entities: List[str], chosen_redact_comprehend_entities: List[str], allow_list: List[str] = None, chosen_llm_entities: List[str] = None, page_min: int = 0, page_max: int = 0, text_extraction_method: str = LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION, handwrite_signature_checkbox: List[str] = [ "Extract handwriting", "Extract signatures", ], textract_request_metadata: list = list(), current_loop_page: int = 0, page_break_return: bool = False, annotations_all_pages: List = list(), all_page_line_level_ocr_results_df: pd.DataFrame = pd.DataFrame( columns=LINE_LEVEL_OCR_DF_COLUMNS ), all_pages_decision_process_table: pd.DataFrame = pd.DataFrame( columns=[ "image_path", "page", "label", "xmin", "xmax", "ymin", "ymax", "boundingBox", "text", "start", "end", "score", "id", ] ), pymupdf_doc: Document = list(), pii_identification_method: str = "Local", comprehend_query_number: int = 0, comprehend_client: str = "", bedrock_runtime=None, textract_client: str = "", gemini_client=None, gemini_config=None, azure_openai_client=None, in_deny_list: List[str] = list(), redact_whole_page_list: List[str] = list(), max_fuzzy_spelling_mistakes_num: int = 1, match_fuzzy_whole_phrase_bool: bool = True, page_sizes_df: pd.DataFrame = pd.DataFrame(), text_extraction_only: bool = False, textract_output_found: bool = False, all_page_line_level_ocr_results=list(), all_page_line_level_ocr_results_with_words=list(), chosen_local_ocr_model: str = DEFAULT_LOCAL_OCR_MODEL, page_break_val: int = int(PAGE_BREAK_VALUE), log_files_output_paths: List = list(), out_file_paths: List = list(), max_time: int = int(MAX_TIME_VALUE), nlp_analyser: AnalyzerEngine = nlp_analyser, output_folder: str = OUTPUT_FOLDER, input_folder: str = INPUT_FOLDER, custom_llm_instructions: str = "", inference_server_vlm_model: str = "", efficient_ocr: bool = EFFICIENT_OCR, hybrid_textract_bedrock_vlm: bool = HYBRID_TEXTRACT_BEDROCK_VLM, overwrite_existing_ocr_results: bool = OVERWRITE_EXISTING_OCR_RESULTS, save_page_ocr_visualisations: bool = SAVE_PAGE_OCR_VISUALISATIONS, pages_to_process: Optional[List[int]] = None, ocr_first_pass_max_workers: Optional[int] = None, pages_in_pdf_points: Optional[List[int]] = None, progress=Progress(track_tqdm=True), defer_inline_custom_vlm_detection_pass: bool = False, ): # Initialize LLM token tracking variables llm_total_input_tokens = 0 llm_total_output_tokens = 0 llm_model_name = "" # Initialize VLM token tracking variables vlm_total_input_tokens = 0 vlm_total_output_tokens = 0 vlm_model_name = "" """ This function redacts sensitive information from a PDF document. It takes the following parameters in order: - file_path (str): The path to the PDF file to be redacted. - pdf_image_file_paths (List[str]): A list of paths to the PDF file pages converted to images. - language (str): The language of the text in the PDF. - chosen_redact_entities (List[str]): A list of entity types to redact from the PDF. - chosen_redact_comprehend_entities (List[str]): A list of entity types to redact from the list allowed by the AWS Comprehend service. - allow_list (List[str], optional): A list of entity types to allow in the PDF. Defaults to None. - page_min (int, optional): The minimum page number to start redaction from. Defaults to 0. - page_max (int, optional): The maximum page number to end redaction at. Defaults to 0. - text_extraction_method (str, optional): The type of analysis to perform on the PDF. Defaults to LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION. - handwrite_signature_checkbox (List[str], optional): A list of options for redacting handwriting and signatures. Defaults to ["Extract handwriting", "Extract signatures"]. - textract_request_metadata (list, optional): Metadata related to the redaction request. Defaults to an empty string. - current_loop_page (int, optional): The current page being processed. Defaults to 0. - page_break_return (bool, optional): Indicates if the function should return after a page break. Defaults to False. - annotations_all_pages (List, optional): List of annotations on all pages that is used by the gradio_image_annotation_redaction object. - all_page_line_level_ocr_results_df (pd.DataFrame, optional): All line level OCR results for the document as a Pandas dataframe, - all_pages_decision_process_table (pd.DataFrame, optional): All redaction decisions for document as a Pandas dataframe. - pymupdf_doc (Document, optional): The document as a PyMupdf object. - pii_identification_method (str, optional): The method to redact personal information. Either 'Local' (spacy model), or 'AWS Comprehend' (AWS Comprehend API). - comprehend_query_number (int, optional): A counter tracking the number of queries to AWS Comprehend. - comprehend_client (optional): A connection to the AWS Comprehend service via the boto3 package. - textract_client (optional): A connection to the AWS Textract service via the boto3 package. - in_deny_list (optional): A list of custom words that the user has chosen specifically to redact. - redact_whole_page_list (optional, List[str]): A list of pages to fully redact. - max_fuzzy_spelling_mistakes_num (int, optional): The maximum number of spelling mistakes allowed in a searched phrase for fuzzy matching. Can range from 0-9. - match_fuzzy_whole_phrase_bool (bool, optional): A boolean where 'True' means that the whole phrase is fuzzy matched, and 'False' means that each word is fuzzy matched separately (excluding stop words). - page_sizes_df (pd.DataFrame, optional): A pandas dataframe of PDF page sizes in PDF or image format. - text_extraction_only (bool, optional): Should the function only extract text, or also do redaction. - textract_output_found (bool, optional): Boolean is true when a textract OCR output for the file has been found. - all_page_line_level_ocr_results (optional): List of all page line level OCR results. - all_page_line_level_ocr_results_with_words (optional): List of all page line level OCR results with words. - chosen_local_ocr_model (str, optional): The local model chosen for OCR. Defaults to DEFAULT_LOCAL_OCR_MODEL, other choices are "paddle" for PaddleOCR, or "hybrid-paddle" for a combination of both. - page_break_val (int, optional): The value at which to trigger a page break. Defaults to PAGE_BREAK_VALUE. - log_files_output_paths (List, optional): List of file paths used for saving redaction process logging results. - out_file_paths (List, optional): List of file paths used for saving redaction process output results. - max_time (int, optional): The maximum amount of time (s) that the function should be running before it breaks. To avoid timeout errors with some APIs. - nlp_analyser (AnalyzerEngine, optional): The nlp_analyser object to use for entity detection. Defaults to nlp_analyser. - output_folder (str, optional): The folder for file outputs. - input_folder (str, optional): The folder for file inputs. - custom_llm_instructions (str, optional): Custom instructions for LLM-based entity detection. Defaults to an empty string. - inference_server_vlm_model (str, optional): The inference-server VLM model to use for OCR. Defaults to an empty string. If empty, uses DEFAULT_INFERENCE_SERVER_VLM_MODEL. - efficient_ocr (bool, optional): Whether to use efficient OCR. Defaults to EFFICIENT_OCR. - progress (Progress, optional): A progress tracker for the redaction process. Defaults to a Progress object with track_tqdm set to True. The function returns a redacted PDF document along with processing output objects. """ # Default chosen_llm_entities to chosen_redact_comprehend_entities if not provided # if chosen_llm_entities is None: # chosen_llm_entities = chosen_redact_comprehend_entities # When AWS Textract + Face detection: always analyse all pages for faces (as if # CUSTOM_VLM_FACES were enabled), regardless of PII method or text_extraction_only. if "Face detection" in (handwrite_signature_checkbox or []): chosen_redact_entities = list(chosen_redact_entities or []) chosen_redact_comprehend_entities = list( chosen_redact_comprehend_entities or [] ) chosen_llm_entities = list(chosen_llm_entities or []) if "CUSTOM_VLM_FACES" not in chosen_redact_entities: chosen_redact_entities.append("CUSTOM_VLM_FACES") if "CUSTOM_VLM_FACES" not in chosen_redact_comprehend_entities: chosen_redact_comprehend_entities.append("CUSTOM_VLM_FACES") if "CUSTOM_VLM_FACES" not in chosen_llm_entities: chosen_llm_entities.append("CUSTOM_VLM_FACES") # When True, skip per-page VLM face/signature detection; run_custom_vlm_only_pass # (after OCR in efficient-OCR flow) handles each once per page on full images. _skip_inline_custom_vlm_detection = defer_inline_custom_vlm_detection_pass _skip_custom_vlm_signature_textract = textract_prioritizes_signature_extraction( text_extraction_method, handwrite_signature_checkbox ) if _skip_custom_vlm_signature_textract: print( "Textract Extract signatures enabled — skipping inline " "CUSTOM_VLM_SIGNATURE VLM detection (Textract signatures take priority)." ) tic = time.perf_counter() file_name = get_file_name_without_type(file_path) comprehend_query_number_new = 0 selection_element_results_list_df = pd.DataFrame() form_key_value_results_list_df = pd.DataFrame() textract_json_file_path = "" textract_client_not_found = False # Try updating the supported languages for the spacy analyser try: nlp_analyser = create_nlp_analyser(language, existing_nlp_analyser=nlp_analyser) # Check list of nlp_analyser recognisers and languages if language != "en": gr.Info( f"Language: {language} only supports the following entity detection: {str(nlp_analyser.registry.get_supported_entities(languages=[language]))}" ) except Exception as e: print(f"Error creating nlp_analyser for {language}: {e}") raise Exception(f"Error creating nlp_analyser for {language}: {e}") # Update custom word list analyser object with any new words that have been added to the custom deny list if in_deny_list: nlp_analyser.registry.remove_recognizer("CUSTOM") new_custom_recogniser = custom_word_list_recogniser(in_deny_list) nlp_analyser.registry.add_recognizer(new_custom_recogniser) nlp_analyser.registry.remove_recognizer("CustomWordFuzzyRecognizer") new_custom_fuzzy_recogniser = CustomWordFuzzyRecognizer( supported_entities=["CUSTOM_FUZZY"], custom_list=in_deny_list, spelling_mistakes_max=max_fuzzy_spelling_mistakes_num, search_whole_phrase=match_fuzzy_whole_phrase_bool, ) nlp_analyser.registry.add_recognizer(new_custom_fuzzy_recogniser) # Map text extraction method to OCR engine if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: ocr_engine = "tesseract" # Not actually used, but required for initialization elif text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION: ocr_engine = "bedrock-vlm" elif text_extraction_method == GEMINI_VLM_TEXT_EXTRACT_OPTION: ocr_engine = "gemini-vlm" elif text_extraction_method == AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION: ocr_engine = "azure-openai-vlm" else: ocr_engine = chosen_local_ocr_model image_analyser = CustomImageAnalyzerEngine( analyzer_engine=nlp_analyser, ocr_engine=ocr_engine, language=language, output_folder=output_folder, save_page_ocr_visualisations=save_page_ocr_visualisations, ) if pii_identification_method == "AWS Comprehend" and comprehend_client == "": out_message = "Connection to AWS Comprehend service unsuccessful." print(out_message) raise Exception(out_message) if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and textract_client == "": out_message_warning = "Connection to AWS Textract service unsuccessful. Redaction will only continue if local AWS Textract results can be found." textract_client_not_found = True print(out_message_warning) # raise Exception(out_message) number_of_pages = pymupdf_doc.page_count print("Number of pages in document:", str(number_of_pages)) # Check that page_min and page_max are within expected ranges if page_max > number_of_pages or page_max == 0: page_max = number_of_pages if page_min <= 0: page_min = 0 else: page_min = page_min - 1 print("Page range:", str(page_min + 1), "to", str(page_max)) # If running Textract, check if file already exists. If it does, load in existing data if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: # Generate suffix based on checkbox options textract_suffix = get_textract_file_suffix(handwrite_signature_checkbox) textract_json_file_path = ( output_folder + file_name + textract_suffix + "_textract.json" ) if overwrite_existing_ocr_results: # Skip loading existing results, start fresh textract_data = {} is_missing = True else: textract_data, is_missing, log_files_output_paths = ( load_and_convert_textract_json( textract_json_file_path, log_files_output_paths, page_sizes_df ) ) if textract_data: pass original_textract_data = textract_data.copy() if textract_client_not_found and is_missing: print( "No existing Textract results file found and no Textract client found. Redaction will not continue." ) raise Exception( "No existing Textract results file found and no Textract client found. Redaction will not continue." ) # If running local OCR option, check if file already exists. If it does, load in existing data if text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION: all_page_line_level_ocr_results_with_words_json_file_path = ( output_folder + file_name + "_ocr_results_with_words_local_ocr.json" ) # Preserve any pre-existing word-level OCR results passed in (e.g. from # EFFICIENT_OCR's selectable-text path). This prevents us from accidentally # dropping those pages when we load/recompute OCR-needed pages. pre_existing_word_results = ( list(all_page_line_level_ocr_results_with_words or []) if all_page_line_level_ocr_results_with_words is not None else [] ) if overwrite_existing_ocr_results: # Skip loading existing cached results. Keep any pre-existing word # results for pages outside `pages_to_process` so we don't erase # selectable-text path output in efficient-ocr mixed mode. if pages_to_process: pages_to_process_set = set(pages_to_process) def _page_in_to_process(item) -> bool: try: return int(item.get("page")) in pages_to_process_set except Exception: return False pre_existing_word_results = [ item for item in pre_existing_word_results if not _page_in_to_process(item) ] all_page_line_level_ocr_results_with_words = list(pre_existing_word_results) is_missing = True print("overwriting existing OCR results with words") elif os.path.exists(all_page_line_level_ocr_results_with_words_json_file_path): print("Loading existing OCR results with words for local OCR analysis") cached_word_results = [] ( cached_word_results, _is_missing, log_files_output_paths, ) = load_and_convert_ocr_results_with_words_json( all_page_line_level_ocr_results_with_words_json_file_path, log_files_output_paths, page_sizes_df, ) all_page_line_level_ocr_results_with_words = merge_page_results( list(pre_existing_word_results) + list(cached_word_results) ) original_all_page_line_level_ocr_results_with_words = ( all_page_line_level_ocr_results_with_words.copy() ) ### if current_loop_page == 0: page_loop_start = page_min else: page_loop_start = current_loop_page page_loop_end = page_max # When pages_to_process is provided (e.g. from efficient_ocr), iterate only over those pages (1-based list). if pages_to_process is not None: page_loop_pages = sorted([p - 1 for p in pages_to_process]) # 0-indexed, sorted page_min = 0 page_max = number_of_pages else: page_loop_pages = None # If there's data from a previous run (passed in via the DataFrame parameters), add it all_line_level_ocr_results_list = list() all_pages_decision_process_list = list() selection_element_results_list = list() form_key_value_results_list = list() # Track which pages already have line-level OCR outputs so we don't duplicate rows # when we rebuild from cached Textract `ocr_results_with_words` entries. existing_line_level_pages_1based = set() if ( isinstance(all_page_line_level_ocr_results_df, pd.DataFrame) and not all_page_line_level_ocr_results_df.empty and "page" in all_page_line_level_ocr_results_df.columns ): try: existing_line_level_pages_1based = set( pd.to_numeric( all_page_line_level_ocr_results_df["page"], errors="coerce" ) .dropna() .astype(int) .unique() .tolist() ) except Exception: existing_line_level_pages_1based = set() if not all_page_line_level_ocr_results_df.empty: all_line_level_ocr_results_list.extend( all_page_line_level_ocr_results_df.to_dict("records") ) if not all_pages_decision_process_table.empty: all_pages_decision_process_list.extend( all_pages_decision_process_table.to_dict("records") ) # Dictionary to store OCR results and page metadata for two-pass processing # This allows us to do all OCR first, then all PII detection, avoiding model switching ocr_results_by_page = {} # Pre-initialise ocr_results_by_page from pages that already have OCR/text results # (e.g. when EFFICIENT_OCR is True, text-extraction pages are already processed by redact_text_pdf) if all_page_line_level_ocr_results_with_words: by_page = {} for item in all_page_line_level_ocr_results_with_words: p = item.get("page") if p is None: continue page_1based = int(p) if isinstance(p, str) else p if page_1based not in by_page: by_page[page_1based] = {"page": page_1based, "results": {}} by_page[page_1based]["results"].update(item.get("results", {})) for page_1based in by_page: page_no = page_1based - 1 if page_no < 0 or page_no >= number_of_pages: continue try: image_path = page_sizes_df.loc[ page_sizes_df["page"] == page_1based, "image_path" ].iloc[0] except Exception: image_path = ( pdf_image_file_paths[page_no] if page_no < len(pdf_image_file_paths) else "" ) try: pymupdf_page = pymupdf_doc.load_page(page_no) except Exception: continue try: original_cropbox = page_sizes_df.loc[ page_sizes_df["page"] == page_1based, "original_cropbox" ].iloc[0] except Exception: original_cropbox = pymupdf_page.cropbox.irect image = None page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height if isinstance(image_path, str) and image_path: normalized_path = os.path.normpath(os.path.abspath(image_path)) if validate_path_containment(normalized_path, input_folder): try: image = Image.open(normalized_path) page_width, page_height = image.size except Exception: pass page_data_merged = by_page[page_1based] page_line_level_ocr_results_with_words = [page_data_merged] ocr_results_by_page[page_no] = { "page_line_level_ocr_results": None, "page_line_level_ocr_results_with_words": page_line_level_ocr_results_with_words, "page_signature_recogniser_results": list(), "page_handwriting_recogniser_results": list(), "handwriting_or_signature_boxes": list(), "image_path": image_path, "pymupdf_page": pymupdf_page, "original_cropbox": original_cropbox, "page_width": page_width, "page_height": page_height, "image": image, "reported_page_number": str(page_1based), } # Load existing Textract OCR results from output folder if present (per-page use in loop). # When a page exists in this file, use it as page_line_level_ocr_results_with_words, # recreate page_line_level_ocr_results, and skip OCR (including hybrid textract-bedrock). textract_ocr_by_page_1based = None if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: existing_ocr_file_name = file_name + "_ocr_results_with_words_textract.json" existing_textract_ocr_path = output_folder + existing_ocr_file_name if os.path.exists(existing_textract_ocr_path): ( loaded_textract_ocr_list, is_missing, log_files_output_paths, ) = load_and_convert_ocr_results_with_words_json( existing_textract_ocr_path, log_files_output_paths, page_sizes_df, ) if not is_missing and loaded_textract_ocr_list: textract_ocr_by_page_1based = {} for item in loaded_textract_ocr_list: p = item.get("page") if p is not None: page_1based = int(p) if isinstance(p, str) else p textract_ocr_by_page_1based[page_1based] = item if textract_ocr_by_page_1based: print( f"Found existing Textract OCR results file: {existing_ocr_file_name} " f"({len(textract_ocr_by_page_1based)} pages). Will use for matching pages and skip OCR/hybrid." ) # When > 1, OCR first pass runs analyse_page_with_textract in parallel (AWS Textract only). # With efficient_ocr, the caller can pass pages_to_process so multiple OCR-needed pages # are processed in one call, enabling parallel OCR. _ocr_first_pass_max_workers = ( ocr_first_pass_max_workers if ocr_first_pass_max_workers is not None else OCR_FIRST_PASS_MAX_WORKERS ) use_ocr_parallel_textract = ( _ocr_first_pass_max_workers > 1 and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION ) ocr_parallel_jobs_textract = [] if use_ocr_parallel_textract else None ocr_pymupdf_pages_textract = {} if use_ocr_parallel_textract else None # FIRST PASS: Perform OCR on all pages # This collects OCR results without doing PII detection, which is more efficient # when using inference servers that need to switch between VLM and LLM models print("First pass: Performing OCR on all pages...") if page_loop_pages is not None: ocr_progress_bar = tqdm( page_loop_pages, unit="pages", desc="Performing image-based processing", ) else: ocr_progress_bar = tqdm( range(page_loop_start, page_loop_end), unit="pages", desc="Performing image-based processing", ) _ocr_gui_total_pages = ( len(page_loop_pages) if page_loop_pages is not None else max(0, page_loop_end - page_loop_start) ) _ocr_gui_total_str = str(_ocr_gui_total_pages) if _ocr_gui_total_pages > 0 else "?" # Parallel Bedrock VLM page OCR: run perform_ocr for all pages that need it, then use results in the loop. ocr_results_from_parallel = {} # Parallel local page OCR (Tesseract / Paddle / etc.): perform_ocr per page, then use in loop. ocr_results_from_parallel_local_ocr = {} if ( text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION and bedrock_runtime is not None ): _bedrock_ocr_tasks = [] _pages_iter = ( list(page_loop_pages) if page_loop_pages is not None else list(range(page_loop_start, page_loop_end)) ) for _pno in _pages_iter: try: _img_path = page_sizes_df.loc[ page_sizes_df["page"] == (_pno + 1), "image_path" ].iloc[0] except Exception: _img_path = ( pdf_image_file_paths[_pno] if _pno < len(pdf_image_file_paths) else "" ) if all_page_line_level_ocr_results_with_words: _reported = str(_pno + 1) _match = next( ( item for item in all_page_line_level_ocr_results_with_words if int(item.get("page", -1)) == int(_reported) ), None, ) if _match: continue _actual = _img_path if isinstance(_img_path, str) and ( "placeholder_image" in _img_path or "image_placeholder" in _img_path ): try: _, _created, _, _ = process_single_page_for_image_conversion( pdf_path=file_path, page_num=_pno, image_dpi=IMAGES_DPI, create_images=True, input_folder=input_folder, ) if os.path.exists(_created): _actual = _created if not page_sizes_df.empty: page_sizes_df.loc[ page_sizes_df["page"] == (_pno + 1), "image_path", ] = _created except Exception: pass _bedrock_ocr_tasks.append((_pno, _actual)) if _bedrock_ocr_tasks: def _run_bedrock_page_ocr(task): pno, actual_path = task return ( pno, image_analyser.perform_ocr( actual_path, bedrock_runtime=bedrock_runtime, gemini_client=gemini_client, gemini_config=gemini_config, azure_openai_client=azure_openai_client, vlm_model_choice=CLOUD_VLM_MODEL_CHOICE, inference_server_model_name=( inference_server_vlm_model if inference_server_vlm_model else None ), page_index_0=pno, ), ) _max_workers = min(MAX_WORKERS, len(_bedrock_ocr_tasks)) with ThreadPoolExecutor(max_workers=_max_workers) as executor: for pno, result in executor.map( _run_bedrock_page_ocr, _bedrock_ocr_tasks ): ocr_results_from_parallel[pno] = result if text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION: _local_ocr_tasks = [] _pages_iter = ( list(page_loop_pages) if page_loop_pages is not None else list(range(page_loop_start, page_loop_end)) ) for _pno in _pages_iter: if all_page_line_level_ocr_results_with_words: _reported = str(_pno + 1) _match = next( ( item for item in all_page_line_level_ocr_results_with_words if int(item.get("page", -1)) == int(_reported) ), None, ) if _match: continue try: _img_path = page_sizes_df.loc[ page_sizes_df["page"] == (_pno + 1), "image_path" ].iloc[0] except Exception: _img_path = ( pdf_image_file_paths[_pno] if _pno < len(pdf_image_file_paths) else "" ) _actual = _img_path if isinstance(_img_path, str) and ( "placeholder_image" in _img_path or "image_placeholder" in _img_path ): try: _, _created, _, _ = process_single_page_for_image_conversion( pdf_path=file_path, page_num=_pno, image_dpi=IMAGES_DPI, create_images=True, input_folder=input_folder, ) if os.path.exists(_created): _actual = _created if not page_sizes_df.empty: page_sizes_df.loc[ page_sizes_df["page"] == (_pno + 1), "image_path", ] = _created except Exception: pass _local_ocr_tasks.append((_pno, _actual)) if _local_ocr_tasks: def _run_local_page_ocr(task): pno, actual_path = task ( page_word_level_ocr_results, page_vlm_input_tokens, page_vlm_output_tokens, page_vlm_model_name, ) = image_analyser.perform_ocr( actual_path, page_index_0=pno, ) # Pre-compute line-level OCR structures here so the main loop can # skip the expensive combine_ocr_results step. ( page_line_level_ocr_results, page_line_level_ocr_results_with_words, ) = combine_ocr_results( page_word_level_ocr_results, page=str(pno + 1), preserve_line_boxes=should_preserve_paddle_line_boxes( chosen_local_ocr_model ), ) return ( pno, ( page_word_level_ocr_results, page_vlm_input_tokens, page_vlm_output_tokens, page_vlm_model_name, page_line_level_ocr_results, page_line_level_ocr_results_with_words, ), ) if chosen_local_ocr_model == "paddle": _max_workers = min(PADDLE_MAX_WORKERS, len(_local_ocr_tasks)) _parallel_label = "Paddle" elif chosen_local_ocr_model == "tesseract": _max_workers = min(TESSERACT_MAX_WORKERS, len(_local_ocr_tasks)) _parallel_label = "Tesseract" else: # hybrid-paddle, VLM hybrids, local VLM, etc. (same cap as before Tesseract split) _max_workers = min(TESSERACT_MAX_WORKERS, len(_local_ocr_tasks)) _parallel_label = "local model" _local_ocr_sequential_only = frozenset( ( "vlm", "inference-server", "hybrid-paddle-vlm", "hybrid-paddle-inference-server", ) ) _sequential_local_ocr = chosen_local_ocr_model in _local_ocr_sequential_only _phase = "Sequential" if _sequential_local_ocr else "Parallel" _n_local = len(_local_ocr_tasks) if _sequential_local_ocr: print( f"{_phase} {_parallel_label} page OCR: processing {_n_local} page(s) " f"one at a time ({chosen_local_ocr_model!r})." ) else: print( f"{_phase} {_parallel_label} page OCR: processing {_n_local} page(s) " f"with {int(_max_workers)} worker(s)." ) # Progress slice for this phase (first pass OCR); main page loop uses tqdm after this. _prog_lo, _prog_hi = 0.0, 1.0 try: progress( _prog_lo, desc=f"{_phase} {_parallel_label} OCR (0/{_n_local} pages)", ) except Exception: pass _completed_local = 0 if _sequential_local_ocr: for task in _local_ocr_tasks: pno = task[0] try: res_pno, result = _run_local_page_ocr(task) ocr_results_from_parallel_local_ocr[res_pno] = result except Exception as _e: print(f"Sequential local OCR failed for page {pno + 1}: {_e}") _completed_local += 1 try: frac = _prog_lo + (_prog_hi - _prog_lo) * ( _completed_local / max(_n_local, 1) ) progress( frac, desc=( f"{_phase} {_parallel_label} OCR " f"({_completed_local}/{_n_local} pages)" ), ) except Exception: pass else: with ThreadPoolExecutor(max_workers=_max_workers) as executor: future_to_pno = { executor.submit(_run_local_page_ocr, task): task[0] for task in _local_ocr_tasks } for fut in as_completed(future_to_pno): pno = future_to_pno[fut] try: res_pno, result = fut.result() ocr_results_from_parallel_local_ocr[res_pno] = result except Exception as _e: print(f"Parallel local OCR failed for page {pno + 1}: {_e}") _completed_local += 1 try: frac = _prog_lo + (_prog_hi - _prog_lo) * ( _completed_local / max(_n_local, 1) ) progress( frac, desc=( f"{_phase} {_parallel_label} OCR " f"({_completed_local}/{_n_local} pages)" ), ) except Exception: pass for page_no in ocr_progress_bar: reported_page_number = str(page_no + 1) try: ocr_progress_bar.set_postfix_str( f"OCR · page {reported_page_number}/{_ocr_gui_total_str}", refresh=False, ) except Exception: pass # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "start iteration (init lists, entity flags)" # ) # Define once per iteration so they are always set before use at _include_vlm_boxes_in_outputs (line ~7610) _person_selected = ( "CUSTOM_VLM_FACES" in (chosen_redact_entities or []) or "CUSTOM_VLM_FACES" in (chosen_redact_comprehend_entities or []) or "CUSTOM_VLM_FACES" in (chosen_llm_entities or []) ) _textract_face_identification = ( text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and "Face detection" in (handwrite_signature_checkbox or []) ) _run_face_pass = _person_selected or _textract_face_identification handwriting_or_signature_boxes = list() page_signature_recogniser_results = list() page_handwriting_recogniser_results = list() page_line_level_ocr_results_with_words = list() page_line_level_ocr_results = None # Initialize to None, will be set during OCR page_break_return = False # Try to find image location try: image_path = page_sizes_df.loc[ page_sizes_df["page"] == (page_no + 1), "image_path" ].iloc[0] except Exception as e: print("Could not find image_path in page_sizes_df due to:", e) image_path = pdf_image_file_paths[page_no] page_image_annotations = {"image": image_path, "boxes": []} pymupdf_page = pymupdf_doc.load_page(page_no) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "PyMuPDF load_page" # ) if not (page_no >= page_min and page_no < page_max): # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "outside page_min/page_max — skipping OCR block for this page" # ) continue if page_no >= page_min and page_no < page_max: # Need image size to convert OCR outputs to the correct sizes if isinstance(image_path, str): # Normalize and validate path safety before checking existence normalized_path = os.path.normpath(os.path.abspath(image_path)) if validate_path_containment(normalized_path, input_folder): image = Image.open(normalized_path) page_width, page_height = image.size else: # If validation fails and input file is an image file, try using file_path as fallback if ( is_pdf(file_path) is False and isinstance(file_path, str) and file_path ): normalized_file_path = os.path.normpath( os.path.abspath(file_path) ) # Check if it's a Gradio temporary file (often in temp directories) is_gradio_temp = ( "gradio" in normalized_file_path.lower() and "temp" in normalized_file_path.lower() ) if is_gradio_temp or validate_path_containment( normalized_file_path, input_folder ): try: image = Image.open(normalized_file_path) page_width, page_height = image.size except Exception as e: print( f"Could not open image from file_path {file_path}: {e}" ) image = None page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height else: # For image files, at least keep image_path as a string for later use image = None page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height else: # print("Image path does not exist, using mediabox coordinates as page sizes") image = None page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height elif not isinstance(image_path, Image.Image): # If image_path is not a string or Image, and input file is an image file, try file_path if ( is_pdf(file_path) is False and isinstance(file_path, str) and file_path ): normalized_file_path = os.path.normpath(os.path.abspath(file_path)) is_gradio_temp = ( "gradio" in normalized_file_path.lower() and "temp" in normalized_file_path.lower() ) if is_gradio_temp or validate_path_containment( normalized_file_path, input_folder ): try: image = Image.open(normalized_file_path) page_width, page_height = image.size except Exception as e: print( f"Could not open image from file_path {file_path}: {e}" ) image = None page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height else: image = None page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height else: print( f"Unexpected image_path type: {type(image_path)}, using page mediabox coordinates as page sizes" ) # Ensure image_path is valid image = None page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height try: if not page_sizes_df.empty: original_cropbox = page_sizes_df.loc[ page_sizes_df["page"] == (page_no + 1), "original_cropbox" ].iloc[0] except IndexError: print( "Can't find original cropbox details for page, using current PyMuPDF page cropbox" ) original_cropbox = pymupdf_page.cropbox.irect if image is None: # Check if image_path is a placeholder and create the actual image if isinstance(image_path, str) and ( "placeholder_image" in image_path or "image_placeholder" in image_path ): # print(f"Detected placeholder image path: {image_path}") try: # Extract page number from placeholder path (e.g. placeholder_image_0.png or image_placeholder_0.png) page_num_from_placeholder = int( image_path.split("_")[-1].split(".")[0] ) # Create the actual image using process_single_page_for_image_conversion _, created_image_path, page_width, page_height = ( process_single_page_for_image_conversion( pdf_path=file_path, page_num=page_num_from_placeholder, image_dpi=IMAGES_DPI, create_images=True, input_folder=input_folder, ) ) # Load the created image if os.path.exists(created_image_path): image = Image.open(created_image_path) # print( # f"Successfully created and loaded image from: {created_image_path}" # ) else: # print(f"Failed to create image at: {created_image_path}") page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height except Exception as e: print(f"Error creating image from placeholder: {e}") page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height else: try: # Create the actual image using process_single_page_for_image_conversion _, created_image_path, page_width, page_height = ( process_single_page_for_image_conversion( pdf_path=file_path, page_num=page_no, image_dpi=IMAGES_DPI, create_images=True, input_folder=input_folder, ) ) # Load the created image if os.path.exists(created_image_path): image = Image.open(created_image_path) else: page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height except Exception as e: print(f"Error creating image from file_path: {e}") page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height if image is None: print("Image is None - using mediabox coordinates") page_width = pymupdf_page.mediabox.width page_height = pymupdf_page.mediabox.height # Ensure page_sizes_df has the dimensions we're using for this page (image or # mediabox) so that divide_coordinates_by_page_sizes uses the same size later. # Otherwise OCR/Textract boxes (in image pixels) get divided by mediabox and # appear too big and shifted (e.g. towards bottom-right). try: _page_1based = page_no + 1 if not page_sizes_df.empty and "page" in page_sizes_df.columns: mask = page_sizes_df["page"] == _page_1based if mask.any(): if "image_width" not in page_sizes_df.columns: page_sizes_df["image_width"] = float("nan") if "image_height" not in page_sizes_df.columns: page_sizes_df["image_height"] = float("nan") page_sizes_df.loc[mask, "image_width"] = float(page_width) page_sizes_df.loc[mask, "image_height"] = float(page_height) except Exception: pass # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # f"page image ready (size {int(page_width)}x{int(page_height)}, " # f"PIL image loaded={image is not None})" # ) # Step 1: Perform OCR. Either with Tesseract, cloud VLM, or with AWS Textract # If using Tesseract or cloud VLM (all image-based OCR methods) if ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION or text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION or text_extraction_method == GEMINI_VLM_TEXT_EXTRACT_OPTION or text_extraction_method == AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION ): if all_page_line_level_ocr_results_with_words: # Find the first dict where 'page' matches matching_page = next( ( item for item in all_page_line_level_ocr_results_with_words if int(item.get("page", -1)) == int(reported_page_number) ), None, ) page_line_level_ocr_results_with_words = ( matching_page if matching_page else [] ) else: page_line_level_ocr_results_with_words = list() if page_line_level_ocr_results_with_words: # print( # "Found OCR results for page in existing OCR with words object" # ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "OCR source — existing loaded JSON (recreate_page_line_level_ocr_results_with_page)" # ) page_line_level_ocr_results = ( recreate_page_line_level_ocr_results_with_page( page_line_level_ocr_results_with_words ) ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "OCR JSON path — line-level recreated (aggregate list unchanged here)" # ) else: cached_precombined = False # Use pre-computed result from parallel Bedrock OCR if available if page_no in ocr_results_from_parallel: # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "OCR source — parallel Bedrock VLM cache" # ) ( page_word_level_ocr_results, page_vlm_input_tokens, page_vlm_output_tokens, page_vlm_model_name, ) = ocr_results_from_parallel[page_no] elif page_no in ocr_results_from_parallel_local_ocr: # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "OCR source — parallel local OCR cache (pre-combined line structure)" # ) ( page_word_level_ocr_results, page_vlm_input_tokens, page_vlm_output_tokens, page_vlm_model_name, page_line_level_ocr_results, page_line_level_ocr_results_with_words, ) = ocr_results_from_parallel_local_ocr[page_no] cached_precombined = True else: # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "OCR source — inline perform_ocr (no parallel/cache hit)" # ) # Check if image_path is a placeholder and create the actual image if needed actual_image_path = image_path if isinstance(image_path, str) and ( "placeholder_image" in image_path or "image_placeholder" in image_path ): try: # Use the current page number (page_no is 0-indexed) # Create the actual image using process_single_page_for_image_conversion _, created_image_path, _, _ = ( process_single_page_for_image_conversion( pdf_path=file_path, page_num=page_no, # page_no is already 0-indexed image_dpi=IMAGES_DPI, create_images=True, input_folder=input_folder, ) ) # Use the created image path if it exists if os.path.exists(created_image_path): actual_image_path = created_image_path # Update image_path in page_sizes_df for future reference if not page_sizes_df.empty: page_sizes_df.loc[ page_sizes_df["page"] == (page_no + 1), "image_path", ] = created_image_path print( f"Created actual image for page {page_no + 1} from placeholder: {created_image_path}" ) else: print( f"Warning: Failed to create image for page {page_no + 1} from placeholder" ) except Exception as e: print( f"Error creating image from placeholder for OCR: {e}" ) # Fall back to using the placeholder path (will likely fail, but preserves original behavior) actual_image_path = image_path print( f"Performing OCR on page {page_no + 1} from {actual_image_path}" ) ( page_word_level_ocr_results, page_vlm_input_tokens, page_vlm_output_tokens, page_vlm_model_name, ) = image_analyser.perform_ocr( actual_image_path, bedrock_runtime=bedrock_runtime, gemini_client=gemini_client, gemini_config=gemini_config, azure_openai_client=azure_openai_client, vlm_model_choice=CLOUD_VLM_MODEL_CHOICE, inference_server_model_name=( inference_server_vlm_model if inference_server_vlm_model else None ), page_index_0=page_no, ) # Accumulate VLM token usage vlm_total_input_tokens += page_vlm_input_tokens vlm_total_output_tokens += page_vlm_output_tokens if page_vlm_model_name and not vlm_model_name: vlm_model_name = page_vlm_model_name if not cached_precombined: ( page_line_level_ocr_results, page_line_level_ocr_results_with_words, ) = combine_ocr_results( page_word_level_ocr_results, page=reported_page_number, preserve_line_boxes=should_preserve_paddle_line_boxes( chosen_local_ocr_model ), ) # else: line/word structures already set from parallel local OCR worker if all_page_line_level_ocr_results_with_words is None: all_page_line_level_ocr_results_with_words = list() all_page_line_level_ocr_results_with_words.append( page_line_level_ocr_results_with_words ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "appended page OCR to aggregate list" # ) # Optional additional Bedrock VLM pass to detect people # and inject [FACE] entries into the word-level OCR structure for AWS Bedrock VLM OCR. # Run when CUSTOM_VLM_FACES is selected (in any entity selector), or when AWS Textract # + Face detection is selected (all pages analysed for faces regardless of PII method # or text_extraction_only). # (_run_face_pass, _textract_face_identification set at start of loop) if ( not _skip_inline_custom_vlm_detection and ( text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION or text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION or pii_identification_method == AWS_PII_OPTION or pii_identification_method == AWS_LLM_PII_OPTION ) and _run_face_pass and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None and bedrock_runtime is not None ): try: _gui_tqdm_subphase( ocr_progress_bar, progress, "Face detection (VLM)", reported_page_number, _ocr_gui_total_str, ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "optional — Bedrock VLM person detection" # ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) # Use Bedrock VLM for people detection model_choice = ( CLOUD_VLM_MODEL_CHOICE if CLOUD_VLM_MODEL_CHOICE else None ) normalised_coords_range = ( 999 # Full-page prompt uses 0-999 for all Bedrock models ) people_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_people_only=True, model_choice=model_choice, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) # Unpack tuple: (Dict[str, List], int, int, str) -> (ocr_data, vlm_input_tokens, vlm_output_tokens, vlm_model_name) if ( isinstance(people_ocr_result, tuple) and len(people_ocr_result) == 4 ): ( people_ocr, people_vlm_input_tokens, people_vlm_output_tokens, people_vlm_model_name, ) = people_ocr_result # Accumulate VLM token usage vlm_total_input_tokens += people_vlm_input_tokens vlm_total_output_tokens += people_vlm_output_tokens if people_vlm_model_name and not vlm_model_name: vlm_model_name = people_vlm_model_name else: people_ocr = ( people_ocr_result[0] if isinstance(people_ocr_result, tuple) else people_ocr_result ) # Convert people_ocr outputs into additional word-level entries texts = people_ocr.get("text", []) lefts = people_ocr.get("left", []) tops = people_ocr.get("top", []) widths = people_ocr.get("width", []) heights = people_ocr.get("height", []) confs = people_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words["results"] # Determine a valid starting line number for synthetic [FACE] lines existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) person_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[FACE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = float(confs[idx]) if idx < len(confs) else 0.0 except Exception: continue key = f"person_line_{person_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[FACE]", "bounding_box": bbox, "words": [ { "text": "[FACE]", "bounding_box": bbox, "conf": conf, "model": "bedrock-vlm", } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: Bedrock VLM person detection failed on page {reported_page_number}: {e}" ) # Optional additional Bedrock VLM pass to detect signatures # and inject [SIGNATURE] entries into the word-level OCR structure for AWS Bedrock VLM OCR. # Only run when the user has selected CUSTOM_VLM_SIGNATURE (in any entity selector). _signature_selected = ( "CUSTOM_VLM_SIGNATURE" in chosen_redact_entities or "CUSTOM_VLM_SIGNATURE" in (chosen_redact_comprehend_entities or []) or "CUSTOM_VLM_SIGNATURE" in (chosen_llm_entities or []) ) if ( not _skip_inline_custom_vlm_detection and not ( _skip_custom_vlm_signature_textract and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION ) and ( text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION or text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION or pii_identification_method == AWS_PII_OPTION or pii_identification_method == AWS_LLM_PII_OPTION ) and _signature_selected and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None and bedrock_runtime is not None ): try: _gui_tqdm_subphase( ocr_progress_bar, progress, "Signature detection (VLM)", reported_page_number, _ocr_gui_total_str, ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "optional — Bedrock VLM signature detection" # ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) # Use Bedrock VLM for signature detection model_choice = ( CLOUD_VLM_MODEL_CHOICE if CLOUD_VLM_MODEL_CHOICE else None ) normalised_coords_range = ( 999 # Full-page prompt uses 0-999 for all Bedrock models ) sig_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_signatures_only=True, model_choice=model_choice, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) # Unpack tuple: (Dict[str, List], int, int, str) -> (ocr_data, vlm_input_tokens, vlm_output_tokens, vlm_model_name) if ( isinstance(sig_ocr_result, tuple) and len(sig_ocr_result) == 4 ): ( sig_ocr, sig_vlm_input_tokens, sig_vlm_output_tokens, sig_vlm_model_name, ) = sig_ocr_result # Accumulate VLM token usage vlm_total_input_tokens += sig_vlm_input_tokens vlm_total_output_tokens += sig_vlm_output_tokens if sig_vlm_model_name and not vlm_model_name: vlm_model_name = sig_vlm_model_name else: sig_ocr = ( sig_ocr_result[0] if isinstance(sig_ocr_result, tuple) else sig_ocr_result ) # Convert sig_ocr outputs into additional word-level entries texts = sig_ocr.get("text", []) lefts = sig_ocr.get("left", []) tops = sig_ocr.get("top", []) widths = sig_ocr.get("width", []) heights = sig_ocr.get("height", []) confs = sig_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words["results"] # Determine a valid starting line number for synthetic [SIGNATURE] lines existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) sig_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[SIGNATURE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = float(confs[idx]) if idx < len(confs) else 0.0 except Exception: continue key = f"signature_line_{sig_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[SIGNATURE]", "bounding_box": bbox, "words": [ { "text": "[SIGNATURE]", "bounding_box": bbox, "conf": conf, "model": "bedrock-vlm", } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: Bedrock VLM signature detection failed on page {reported_page_number}: {e}" ) # Optional additional VLM / inference-server pass to detect people # and inject [FACE] entries into the word-level OCR structure. # Supports pure and hybrid VLM/inference-server local OCR models. if ( not _skip_inline_custom_vlm_detection and chosen_local_ocr_model in [ "vlm", "inference-server", "hybrid-vlm", "hybrid-paddle-vlm", "hybrid-paddle-inference-server", ] and "CUSTOM_VLM_FACES" in chosen_redact_entities and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None ): try: _gui_tqdm_subphase( ocr_progress_bar, progress, "Face detection (local VLM)", reported_page_number, _ocr_gui_total_str, ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # f"optional — local VLM/inference person detection ({chosen_local_ocr_model})" # ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) # Decide which backend to use for people detection if chosen_local_ocr_model in [ "vlm", "hybrid-vlm", "hybrid-paddle-vlm", ]: people_ocr_result = _vlm_page_ocr_predict( image, image_name=image_name, normalised_coords_range=999, output_folder=output_folder, detect_people_only=True, page_index_0=page_no, ) else: # inference-server based hybrids people_ocr_result = _inference_server_page_ocr_predict( image, image_name=image_name, normalised_coords_range=999, output_folder=output_folder, detect_people_only=True, page_index_0=page_no, ) # Unpack tuple: (Dict[str, List], int, int, str) -> (ocr_data, vlm_input_tokens, vlm_output_tokens, vlm_model_name) if ( isinstance(people_ocr_result, tuple) and len(people_ocr_result) == 4 ): ( people_ocr, people_vlm_input_tokens, people_vlm_output_tokens, people_vlm_model_name, ) = people_ocr_result # Accumulate VLM token usage vlm_total_input_tokens += people_vlm_input_tokens vlm_total_output_tokens += people_vlm_output_tokens if people_vlm_model_name and not vlm_model_name: vlm_model_name = people_vlm_model_name else: people_ocr = ( people_ocr_result[0] if isinstance(people_ocr_result, tuple) else people_ocr_result ) # Convert people_ocr outputs into additional word-level entries texts = people_ocr.get("text", []) lefts = people_ocr.get("left", []) tops = people_ocr.get("top", []) widths = people_ocr.get("width", []) heights = people_ocr.get("height", []) confs = people_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words["results"] # Determine a valid starting line number for synthetic [FACE] lines existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) person_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[FACE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = float(confs[idx]) if idx < len(confs) else 0.0 except Exception: continue key = f"person_line_{person_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[FACE]", "bounding_box": bbox, "words": [ { "text": "[FACE]", "bounding_box": bbox, "conf": conf, "model": chosen_local_ocr_model, } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: VLM person detection failed on page {reported_page_number}: {e}" ) # Optional additional VLM / inference-server pass to detect signatures # and inject [SIGNATURE] entries into the word-level OCR structure. # Supports pure and hybrid VLM/inference-server local OCR models. if ( not _skip_inline_custom_vlm_detection and not _skip_custom_vlm_signature_textract and chosen_local_ocr_model in [ "vlm", "inference-server", "hybrid-vlm", "hybrid-paddle-vlm", "hybrid-paddle-inference-server", ] and "CUSTOM_VLM_SIGNATURE" in chosen_redact_entities and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None ): try: _gui_tqdm_subphase( ocr_progress_bar, progress, "Signature detection (local VLM)", reported_page_number, _ocr_gui_total_str, ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # f"optional — local VLM/inference signature detection ({chosen_local_ocr_model})" # ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) # Decide which backend to use for signature detection if chosen_local_ocr_model in [ "vlm", "hybrid-vlm", "hybrid-paddle-vlm", ]: sig_ocr_result = _vlm_page_ocr_predict( image, image_name=image_name, normalised_coords_range=999, output_folder=output_folder, detect_signatures_only=True, page_index_0=page_no, ) else: # inference-server based hybrids sig_ocr_result = _inference_server_page_ocr_predict( image, image_name=image_name, normalised_coords_range=999, output_folder=output_folder, detect_signatures_only=True, page_index_0=page_no, ) # Unpack tuple: (Dict[str, List], int, int, str) -> (ocr_data, vlm_input_tokens, vlm_output_tokens, vlm_model_name) if ( isinstance(sig_ocr_result, tuple) and len(sig_ocr_result) == 4 ): ( sig_ocr, sig_vlm_input_tokens, sig_vlm_output_tokens, sig_vlm_model_name, ) = sig_ocr_result # Accumulate VLM token usage vlm_total_input_tokens += sig_vlm_input_tokens vlm_total_output_tokens += sig_vlm_output_tokens if sig_vlm_model_name and not vlm_model_name: vlm_model_name = sig_vlm_model_name else: sig_ocr = ( sig_ocr_result[0] if isinstance(sig_ocr_result, tuple) else sig_ocr_result ) # Convert sig_ocr outputs into additional word-level entries texts = sig_ocr.get("text", []) lefts = sig_ocr.get("left", []) tops = sig_ocr.get("top", []) widths = sig_ocr.get("width", []) heights = sig_ocr.get("height", []) confs = sig_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words["results"] # Determine a valid starting line number for synthetic [SIGNATURE] lines existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) sig_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[SIGNATURE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = float(confs[idx]) if idx < len(confs) else 0.0 except Exception: continue key = f"signature_line_{sig_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[SIGNATURE]", "bounding_box": bbox, "words": [ { "text": "[SIGNATURE]", "bounding_box": bbox, "conf": conf, "model": chosen_local_ocr_model, } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: VLM signature detection failed on page {reported_page_number}: {e}" ) # Check if page exists in existing textract data. If not, send to service to analyse if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract branch — entering page processing" # ) # Use existing Textract ocr_results_with_words file if this page is present: # load as page_line_level_ocr_results_with_words, recreate page_line_level_ocr_results, # store in ocr_results_by_page, and skip all OCR (including hybrid textract-bedrock). if ( textract_ocr_by_page_1based is not None and (page_no + 1) in textract_ocr_by_page_1based ): # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract — using cached per-page ocr_results_with_words (no API)" # ) page_line_level_ocr_results_with_words = ( textract_ocr_by_page_1based[page_no + 1] ) page_line_level_ocr_results = ( recreate_page_line_level_ocr_results_with_page( page_line_level_ocr_results_with_words ) ) if all_page_line_level_ocr_results_with_words is None: all_page_line_level_ocr_results_with_words = list() all_page_line_level_ocr_results_with_words.append( page_line_level_ocr_results_with_words ) # Ensure the line-level OCR outputs table is populated for cached pages too. # Otherwise the UI `all_page_line_level_ocr_results_df_base` can remain empty # even though `ocr_results_with_words` loaded successfully. try: page_1based = int( page_line_level_ocr_results.get("page", page_no + 1) ) except Exception: page_1based = page_no + 1 if page_1based not in existing_line_level_pages_1based: try: _line_results = ( page_line_level_ocr_results.get("results", []) or [] ) page_text_ocr_outputs = pd.DataFrame( [ line_level_ocr_row(page_1based, r) for r in _line_results ] ) if not page_text_ocr_outputs.empty: all_line_level_ocr_results_list.append( page_text_ocr_outputs ) existing_line_level_pages_1based.add(page_1based) except Exception as _e: print( f"Warning: Could not rebuild line-level OCR dataframe from cached Textract results for page {page_1based}: {_e}" ) if page_no >= page_min and page_no < page_max: ocr_results_by_page[page_no] = { "page_line_level_ocr_results": page_line_level_ocr_results, "page_line_level_ocr_results_with_words": page_line_level_ocr_results_with_words, "page_signature_recogniser_results": page_signature_recogniser_results, "page_handwriting_recogniser_results": page_handwriting_recogniser_results, "handwriting_or_signature_boxes": handwriting_or_signature_boxes, "image_path": image_path, "pymupdf_page": pymupdf_page, "original_cropbox": original_cropbox, "page_width": page_width, "page_height": page_height, "image": image, "reported_page_number": reported_page_number, } # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract cached — stored ocr_results_by_page for second pass" # ) # Skip parallel/sequential Textract and hybrid Bedrock for pages loaded from # _ocr_results_with_words_textract.json (already finalised OCR). continue text_blocks = list() page_exists = False # Parallel Textract: build lightweight job and defer API call to post-loop worker. # To keep memory usage low on large documents, we avoid storing full image # objects or image bytes here; workers will reopen the image from disk. if use_ocr_parallel_textract: if not image or _is_placeholder_image_path(image_path): image, image_path = open_page_image_for_pipeline( image_path, file_path, page_no, input_folder=input_folder, page_sizes_df=page_sizes_df, ) if image is None: print( f"Could not load image for Textract job page {reported_page_number}" ) continue page_width, page_height = image.size page_exists = ( any( pg.get("page_no") == reported_page_number for pg in textract_data.get("pages", []) ) if textract_data else False ) cached_text_blocks = None if page_exists: cached_text_blocks = next( pg["data"] for pg in textract_data["pages"] if pg["page_no"] == reported_page_number ) ocr_parallel_jobs_textract.append( { "page_no": page_no, "reported_page_number": reported_page_number, "cached_text_blocks": cached_text_blocks, "page_width": page_width, "page_height": page_height, "image_path": image_path, "original_cropbox": original_cropbox, "handwriting_or_signature_boxes": handwriting_or_signature_boxes, "page_signature_recogniser_results": page_signature_recogniser_results, "page_handwriting_recogniser_results": page_handwriting_recogniser_results, } ) ocr_pymupdf_pages_textract[page_no] = pymupdf_page _tb_note = ( "cached blocks" if cached_text_blocks is not None else "will call Textract API in parallel batch" ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # f"Textract — queued for parallel pass ({_tb_note})" # ) continue if not textract_data: # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract sequential — calling analyse_page_with_textract (no JSON loaded yet)" # ) try: # print(f"Image object: {image}") # Convert the image_path to bytes using an in-memory buffer image_buffer = io.BytesIO() image.save( image_buffer, format="PNG" ) # Save as PNG, or adjust format if needed pdf_page_as_bytes = image_buffer.getvalue() text_blocks, new_textract_request_metadata = ( analyse_page_with_textract( pdf_page_as_bytes, reported_page_number, textract_client, handwrite_signature_checkbox, ) ) # Analyse page with Textract if textract_json_file_path not in log_files_output_paths: log_files_output_paths.append(textract_json_file_path) textract_data = {"pages": [text_blocks]} except Exception as e: out_message = ( "Textract extraction for page " + reported_page_number + " failed due to:" + str(e) ) textract_data = {"pages": []} new_textract_request_metadata = "Failed Textract API call" raise Exception(out_message) textract_request_metadata.append(new_textract_request_metadata) else: # Check if the current reported_page_number exists in the loaded JSON page_exists = any( page["page_no"] == reported_page_number for page in textract_data.get("pages", []) ) if not page_exists: # If the page does not exist, analyze again print( f"Page number {reported_page_number} not found in existing Textract data. Analysing." ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract sequential — page not in JSON, calling analyse_page_with_textract" # ) try: if not image: page_num, image_path, width, height = ( process_single_page_for_image_conversion( file_path, page_no ) ) # Normalize and validate path safety before opening image normalized_path = os.path.normpath( os.path.abspath(image_path) ) if validate_path_containment( normalized_path, input_folder ): image = Image.open(normalized_path) else: raise ValueError( f"Unsafe image path detected: {image_path}" ) # Convert the image_path to bytes using an in-memory buffer image_buffer = io.BytesIO() image.save( image_buffer, format="PNG" ) # Save as PNG, or adjust format if needed pdf_page_as_bytes = image_buffer.getvalue() text_blocks, new_textract_request_metadata = ( analyse_page_with_textract( pdf_page_as_bytes, reported_page_number, textract_client, handwrite_signature_checkbox, ) ) # Analyse page with Textract # Check if "pages" key exists, if not, initialise it as an empty list if "pages" not in textract_data: textract_data["pages"] = list() # Append the new page data textract_data["pages"].append(text_blocks) except Exception as e: out_message = ( "Textract extraction for page " + reported_page_number + " failed due to:" + str(e) ) print(out_message) text_blocks = list() new_textract_request_metadata = "Failed Textract API call" # Check if "pages" key exists, if not, initialise it as an empty list if "pages" not in textract_data: textract_data["pages"] = list() raise Exception(out_message) textract_request_metadata.append(new_textract_request_metadata) else: # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract sequential — reusing text_blocks from loaded Textract JSON" # ) # If the page exists, retrieve the data text_blocks = next( page["data"] for page in textract_data["pages"] if page["page_no"] == reported_page_number ) # Use image dimensions for json_to_ocrresult so that OCR result coordinates # are in image pixel space. textract_page_width = page_width textract_page_height = page_height # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract — json_to_ocrresult (blocks → line/word structures)" # ) ( page_line_level_ocr_results, handwriting_or_signature_boxes, page_signature_recogniser_results, page_handwriting_recogniser_results, page_line_level_ocr_results_with_words, selection_element_results, form_key_value_results, ) = json_to_ocrresult( text_blocks, textract_page_width, textract_page_height, reported_page_number, ) # Hybrid Textract + Bedrock VLM: re-run low-confidence lines with Bedrock VLM if ( hybrid_textract_bedrock_vlm and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and image is not None and bedrock_runtime is not None and CLOUD_VLM_MODEL_CHOICE ): # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # f"Textract hybrid — Bedrock VLM on low-confidence lines " # f"(threshold={HYBRID_TEXTRACT_BEDROCK_VLM_CONFIDENCE_THRESHOLD}, " # f"padding={HYBRID_TEXTRACT_BEDROCK_VLM_PADDING})" # ) image_name_seq = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) hybrid_result = _process_textract_page_with_hybrid_bedrock_vlm( page_line_level_ocr_results, page_line_level_ocr_results_with_words, image, textract_page_width, textract_page_height, HYBRID_TEXTRACT_BEDROCK_VLM_CONFIDENCE_THRESHOLD, HYBRID_TEXTRACT_BEDROCK_VLM_PADDING, bedrock_runtime, CLOUD_VLM_MODEL_CHOICE, output_folder, image_name_seq, ) if isinstance(hybrid_result, tuple) and len(hybrid_result) == 4: ( page_line_level_ocr_results_with_words, hybrid_vlm_input_tokens, hybrid_vlm_output_tokens, hybrid_vlm_model_name, ) = hybrid_result else: page_line_level_ocr_results_with_words = ( hybrid_result[0] if isinstance(hybrid_result, tuple) else hybrid_result ) hybrid_vlm_input_tokens = 0 hybrid_vlm_output_tokens = 0 hybrid_vlm_model_name = "" if isinstance(hybrid_result, tuple) and len(hybrid_result) == 4: vlm_total_input_tokens += hybrid_vlm_input_tokens vlm_total_output_tokens += hybrid_vlm_output_tokens if hybrid_vlm_model_name and not vlm_model_name: vlm_model_name = hybrid_vlm_model_name if all_page_line_level_ocr_results_with_words is None: all_page_line_level_ocr_results_with_words = list() all_page_line_level_ocr_results_with_words.append( page_line_level_ocr_results_with_words ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract — appended page to aggregate ocr_results_with_words list" # ) # Optional additional Bedrock VLM pass to detect people # and inject [FACE] entries into the word-level OCR structure for AWS Textract. if ( not _skip_inline_custom_vlm_detection and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and "CUSTOM_VLM_FACES" in chosen_redact_entities and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None ): try: _gui_tqdm_subphase( ocr_progress_bar, progress, "Face detection (VLM, Textract path)", reported_page_number, _ocr_gui_total_str, ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract optional — Bedrock VLM person detection" # ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) # Use Bedrock VLM for people detection model_choice = CLOUD_VLM_MODEL_CHOICE normalised_coords_range = ( 999 # Full-page prompt uses 0-999 for all Bedrock models ) people_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_people_only=True, model_choice=model_choice, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) # Unpack tuple: (Dict[str, List], int, int, str) -> (ocr_data, vlm_input_tokens, vlm_output_tokens, vlm_model_name) if ( isinstance(people_ocr_result, tuple) and len(people_ocr_result) == 4 ): ( people_ocr, people_vlm_input_tokens, people_vlm_output_tokens, people_vlm_model_name, ) = people_ocr_result # Accumulate VLM token usage vlm_total_input_tokens += people_vlm_input_tokens vlm_total_output_tokens += people_vlm_output_tokens if people_vlm_model_name and not vlm_model_name: vlm_model_name = people_vlm_model_name else: people_ocr = ( people_ocr_result[0] if isinstance(people_ocr_result, tuple) else people_ocr_result ) # Convert people_ocr outputs into additional word-level entries texts = people_ocr.get("text", []) lefts = people_ocr.get("left", []) tops = people_ocr.get("top", []) widths = people_ocr.get("width", []) heights = people_ocr.get("height", []) confs = people_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words["results"] # Determine a valid starting line number for synthetic [FACE] lines existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) person_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[FACE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = float(confs[idx]) if idx < len(confs) else 0.0 except Exception: continue key = f"person_line_{person_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[FACE]", "bounding_box": bbox, "words": [ { "text": "[FACE]", "bounding_box": bbox, "conf": conf, "model": "bedrock-vlm", } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: Bedrock VLM person detection failed on page {reported_page_number}: {e}" ) # Optional additional Bedrock VLM pass to detect signatures # and inject [SIGNATURE] entries into the word-level OCR structure for AWS Textract. if ( not _skip_inline_custom_vlm_detection and not _skip_custom_vlm_signature_textract and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and "CUSTOM_VLM_SIGNATURE" in chosen_redact_entities and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None ): try: _gui_tqdm_subphase( ocr_progress_bar, progress, "Signature detection (VLM, Textract path)", reported_page_number, _ocr_gui_total_str, ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "Textract optional — Bedrock VLM signature detection" # ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) # Use Bedrock VLM for signature detection model_choice = CLOUD_VLM_MODEL_CHOICE normalised_coords_range = ( 999 # Full-page prompt uses 0-999 for all Bedrock models ) sig_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_signatures_only=True, model_choice=model_choice, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) # Unpack tuple: (Dict[str, List], int, int, str) -> (ocr_data, vlm_input_tokens, vlm_output_tokens, vlm_model_name) if ( isinstance(sig_ocr_result, tuple) and len(sig_ocr_result) == 4 ): ( sig_ocr, sig_vlm_input_tokens, sig_vlm_output_tokens, sig_vlm_model_name, ) = sig_ocr_result # Accumulate VLM token usage vlm_total_input_tokens += sig_vlm_input_tokens vlm_total_output_tokens += sig_vlm_output_tokens if sig_vlm_model_name and not vlm_model_name: vlm_model_name = sig_vlm_model_name else: sig_ocr = ( sig_ocr_result[0] if isinstance(sig_ocr_result, tuple) else sig_ocr_result ) # Convert sig_ocr outputs into additional word-level entries texts = sig_ocr.get("text", []) lefts = sig_ocr.get("left", []) tops = sig_ocr.get("top", []) widths = sig_ocr.get("width", []) heights = sig_ocr.get("height", []) confs = sig_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words["results"] # Determine a valid starting line number for synthetic [SIGNATURE] lines existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) sig_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[SIGNATURE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = float(confs[idx]) if idx < len(confs) else 0.0 except Exception: continue key = f"signature_line_{sig_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[SIGNATURE]", "bounding_box": bbox, "words": [ { "text": "[SIGNATURE]", "bounding_box": bbox, "conf": conf, "model": "bedrock-vlm", } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: Bedrock VLM signature detection failed on page {reported_page_number}: {e}" ) if selection_element_results: selection_element_results_list.extend(selection_element_results) if form_key_value_results: form_key_value_results_list.extend(form_key_value_results) # Convert to DataFrame and add to ongoing logging table # Only process if page_line_level_ocr_results is initialized and has results # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "tail — line-level DataFrame for logging table" # ) try: if ( page_line_level_ocr_results and "results" in page_line_level_ocr_results ): line_level_ocr_results_df = pd.DataFrame( [ line_level_ocr_row( page_line_level_ocr_results["page"], result ) for result in page_line_level_ocr_results["results"] ] ) else: line_level_ocr_results_df = pd.DataFrame() except (UnboundLocalError, NameError, KeyError): # page_line_level_ocr_results not initialized or missing expected structure line_level_ocr_results_df = pd.DataFrame() if not line_level_ocr_results_df.empty: # Ensure there are records to add all_line_level_ocr_results_list.extend( line_level_ocr_results_df.to_dict("records") ) # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # f"tail — extended all_line_level_ocr_results_list ({len(line_level_ocr_results_df)} rows)" # ) # Save OCR visualization with bounding boxes (works for all OCR methods) if ( ( text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and save_page_ocr_visualisations is True ) or ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and save_page_ocr_visualisations is True ) or ( text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION and save_page_ocr_visualisations is True ) ): if ( page_line_level_ocr_results_with_words and "results" in page_line_level_ocr_results_with_words ): image_for_visualization = resolve_image_for_ocr_visualization( image, image_path, file_path, page_no, input_folder=input_folder, page_sizes_df=page_sizes_df, ) # Only proceed if we have a valid image or image path if image_for_visualization is not None: # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "tail — visualise_ocr_words_bounding_boxes" # ) # Store the length before the call to detect new additions log_files_output_paths_length_before = len( log_files_output_paths ) log_files_output_paths = visualise_ocr_words_bounding_boxes( image_for_visualization, page_line_level_ocr_results_with_words["results"], image_name=f"{file_name}_{reported_page_number}", output_folder=output_folder, text_extraction_method=text_extraction_method, chosen_local_ocr_model=chosen_local_ocr_model, log_files_output_paths=log_files_output_paths, textract_hybrid_bedrock_used=hybrid_textract_bedrock_vlm, file_path=file_path, page_no=page_no, input_folder=input_folder, page_sizes_df=page_sizes_df, ) # If config is enabled and a new visualization file was added, add it to out_file_paths if ( INCLUDE_OCR_VISUALISATION_IN_OUTPUT_FILES and log_files_output_paths is not None and len(log_files_output_paths) > log_files_output_paths_length_before ): # Get the newly added visualization file path (last item in the list) new_visualisation_path = log_files_output_paths[-1] if new_visualisation_path not in out_file_paths: out_file_paths.append(new_visualisation_path) else: print( f"Warning: Could not determine image for visualization at page {reported_page_number}. Skipping visualization." ) # Store OCR results and page metadata for second pass (PII detection) if page_no >= page_min and page_no < page_max: # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "tail — storing ocr_results_by_page for second pass" # ) ocr_results_by_page[page_no] = { "page_line_level_ocr_results": page_line_level_ocr_results, "page_line_level_ocr_results_with_words": page_line_level_ocr_results_with_words, "page_signature_recogniser_results": page_signature_recogniser_results, "page_handwriting_recogniser_results": page_handwriting_recogniser_results, "handwriting_or_signature_boxes": handwriting_or_signature_boxes, "image_path": image_path, "pymupdf_page": pymupdf_page, "original_cropbox": original_cropbox, "page_width": page_width, "page_height": page_height, "image": image, "reported_page_number": reported_page_number, } # else: # print( # f"[Performing image-based processing] page {reported_page_number}/{_ocr_gui_total_str}: " # "tail — page outside range, skipped ocr_results_by_page" # ) # Skip PII detection and redaction in first pass - we'll do it in second pass # Continue to next page for OCR continue # Parallel Textract first pass: run analyse_page_with_textract in worker threads, then merge in page order if use_ocr_parallel_textract and ocr_parallel_jobs_textract: num_textract_pages = len(ocr_parallel_jobs_textract) print( f"First pass: Running AWS Textract on {num_textract_pages} pages (parallel), then processing results..." ) try: progress( 0.45, desc=f"Running AWS Textract on {num_textract_pages} pages (parallel)", ) except Exception: pass def _textract_first_pass_worker(job): if job.get("cached_text_blocks") is not None: text_blocks = { "page_no": job["reported_page_number"], "data": job["cached_text_blocks"], } new_textract_request_metadata = "cached" else: # Reopen image from path and convert to bytes inside the worker to avoid # holding all page image bytes in memory in the main process. image_path = job.get("image_path", "") page_no_str = job.get("reported_page_number", "") try: if isinstance(image_path, str) and image_path: normalized_path = os.path.normpath(os.path.abspath(image_path)) image = Image.open(normalized_path) image_buffer = io.BytesIO() image.save(image_buffer, format="PNG") pdf_page_as_bytes = image_buffer.getvalue() else: raise ValueError( f"Invalid image_path for Textract job page {page_no_str}: {image_path}" ) except Exception as e: raise Exception( f"Could not open image for Textract job page {page_no_str}: {e}" ) text_blocks, new_textract_request_metadata = analyse_page_with_textract( pdf_page_as_bytes, job["reported_page_number"], textract_client, handwrite_signature_checkbox, ) ( page_line_level_ocr_results, handwriting_or_signature_boxes, page_signature_recogniser_results, page_handwriting_recogniser_results, page_line_level_ocr_results_with_words, selection_element_results, form_key_value_results, ) = json_to_ocrresult( text_blocks, job["page_width"], job["page_height"], job["reported_page_number"], ) return ( text_blocks, new_textract_request_metadata, page_line_level_ocr_results, handwriting_or_signature_boxes, page_signature_recogniser_results, page_handwriting_recogniser_results, page_line_level_ocr_results_with_words, selection_element_results, form_key_value_results, ) max_workers = min(_ocr_first_pass_max_workers, len(ocr_parallel_jobs_textract)) results = [None] * len(ocr_parallel_jobs_textract) with ThreadPoolExecutor(max_workers=max_workers) as executor: future_to_index = { executor.submit(_textract_first_pass_worker, job): idx for idx, job in enumerate(ocr_parallel_jobs_textract) } with tqdm( as_completed(future_to_index), total=len(future_to_index), unit="pages", desc="AWS Textract OCR calls", ) as textract_pbar: for future in textract_pbar: idx = future_to_index[future] results[idx] = future.result() # Merge parallel results into existing loaded data so we don't overwrite # pages that were in the JSON but not in this run (e.g. EFFICIENT_OCR only processes OCR pages). new_pages_from_parallel = [r[0] for r in results] pages_by_no = {str(pg.get("page_no")): pg for pg in new_pages_from_parallel} existing_pages = textract_data.get("pages", []) seen_page_nos = set() merged_pages = [] for pg in existing_pages: pno = str(pg.get("page_no")) seen_page_nos.add(pno) merged_pages.append(pages_by_no.get(pno, pg)) for pg in new_pages_from_parallel: pno = str(pg.get("page_no")) if pno not in seen_page_nos: merged_pages.append(pg) seen_page_nos.add(pno) merged_pages.sort(key=lambda p: int(p.get("page_no", 0))) textract_data = {"pages": merged_pages} textract_request_metadata.extend(r[1] for r in results) if ( textract_json_file_path and textract_json_file_path not in log_files_output_paths ): log_files_output_paths.append(textract_json_file_path) if all_page_line_level_ocr_results_with_words is None: all_page_line_level_ocr_results_with_words = list() print("First pass: Processing Textract results per page...") try: progress(0.5, desc="Processing Textract results per page") except Exception: pass post_process_pbar = tqdm( zip(ocr_parallel_jobs_textract, results), total=len(results), unit="pages", desc="Processing Textract OCR (per page)", ) for job, result in post_process_pbar: ( _text_blocks, _metadata, page_line_level_ocr_results, handwriting_or_signature_boxes, page_signature_recogniser_results, page_handwriting_recogniser_results, page_line_level_ocr_results_with_words, selection_element_results, form_key_value_results, ) = result page_no = job["page_no"] reported_page_number = job["reported_page_number"] post_process_pbar.set_postfix_str(f"page {reported_page_number}") image_path = job["image_path"] # Reopen image on demand instead of storing it in every job to reduce memory usage. image, image_path = open_page_image_for_pipeline( image_path, file_path, page_no, input_folder=input_folder, page_sizes_df=page_sizes_df, ) page_width = job["page_width"] page_height = job["page_height"] original_cropbox = job["original_cropbox"] pymupdf_page = ocr_pymupdf_pages_textract[page_no] # Hybrid Textract + Bedrock VLM: re-run low-confidence lines with Bedrock VLM if ( hybrid_textract_bedrock_vlm and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and image is not None and CLOUD_VLM_MODEL_CHOICE and bedrock_runtime is not None ): print( f"Hybrid Textract + Bedrock VLM: re-running low-confidence lines for page {reported_page_number} (threshold={HYBRID_TEXTRACT_BEDROCK_VLM_CONFIDENCE_THRESHOLD}, padding={HYBRID_TEXTRACT_BEDROCK_VLM_PADDING})" ) image_name_par = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) hybrid_result_par = _process_textract_page_with_hybrid_bedrock_vlm( page_line_level_ocr_results, page_line_level_ocr_results_with_words, image, page_width, page_height, HYBRID_TEXTRACT_BEDROCK_VLM_CONFIDENCE_THRESHOLD, HYBRID_TEXTRACT_BEDROCK_VLM_PADDING, bedrock_runtime, CLOUD_VLM_MODEL_CHOICE, output_folder, image_name_par, ) if isinstance(hybrid_result_par, tuple) and len(hybrid_result_par) == 4: ( page_line_level_ocr_results_with_words, hybrid_vlm_input_tokens_par, hybrid_vlm_output_tokens_par, hybrid_vlm_model_name_par, ) = hybrid_result_par else: page_line_level_ocr_results_with_words = ( hybrid_result_par[0] if isinstance(hybrid_result_par, tuple) else hybrid_result_par ) hybrid_vlm_input_tokens_par = 0 hybrid_vlm_output_tokens_par = 0 hybrid_vlm_model_name_par = "" if isinstance(hybrid_result_par, tuple) and len(hybrid_result_par) == 4: vlm_total_input_tokens += hybrid_vlm_input_tokens_par vlm_total_output_tokens += hybrid_vlm_output_tokens_par if hybrid_vlm_model_name_par and not vlm_model_name: vlm_model_name = hybrid_vlm_model_name_par all_page_line_level_ocr_results_with_words.append( page_line_level_ocr_results_with_words ) if selection_element_results: selection_element_results_list.extend(selection_element_results) if form_key_value_results: form_key_value_results_list.extend(form_key_value_results) # Textract person/signature VLM injection (same logic as sequential path) if ( not _skip_inline_custom_vlm_detection and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and "CUSTOM_VLM_FACES" in chosen_redact_entities and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None ): try: _pp_total = str( post_process_pbar.total if getattr(post_process_pbar, "total", None) else len(results) ) _gui_tqdm_subphase( post_process_pbar, progress, "Face detection (VLM, Textract parallel)", str(reported_page_number), _pp_total, ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) model_choice = CLOUD_VLM_MODEL_CHOICE normalised_coords_range = ( 999 # Full-page prompt uses 0-999 for all Bedrock models ) people_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_people_only=True, model_choice=model_choice, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) if ( isinstance(people_ocr_result, tuple) and len(people_ocr_result) == 4 ): ( people_ocr, people_vlm_input_tokens, people_vlm_output_tokens, people_vlm_model_name, ) = people_ocr_result vlm_total_input_tokens += people_vlm_input_tokens vlm_total_output_tokens += people_vlm_output_tokens if people_vlm_model_name and not vlm_model_name: vlm_model_name = people_vlm_model_name else: people_ocr = ( people_ocr_result[0] if isinstance(people_ocr_result, tuple) else people_ocr_result ) texts = people_ocr.get("text", []) lefts = people_ocr.get("left", []) tops = people_ocr.get("top", []) widths = people_ocr.get("width", []) heights = people_ocr.get("height", []) confs = people_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words["results"] existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) person_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[FACE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = float(confs[idx]) if idx < len(confs) else 0.0 except Exception: continue key = f"person_line_{person_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[FACE]", "bounding_box": bbox, "words": [ { "text": "[FACE]", "bounding_box": bbox, "conf": conf, "model": "bedrock-vlm", } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: Bedrock VLM person detection failed on page {reported_page_number}: {e}" ) if ( not _skip_inline_custom_vlm_detection and not _skip_custom_vlm_signature_textract and text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and "CUSTOM_VLM_SIGNATURE" in chosen_redact_entities and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None ): try: _pp_total_sig = str( post_process_pbar.total if getattr(post_process_pbar, "total", None) else len(results) ) _gui_tqdm_subphase( post_process_pbar, progress, "Signature detection (VLM, Textract parallel)", str(reported_page_number), _pp_total_sig, ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) model_choice = CLOUD_VLM_MODEL_CHOICE normalised_coords_range = ( 999 # Full-page prompt uses 0-999 for all Bedrock models ) sig_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_signatures_only=True, model_choice=model_choice, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) if isinstance(sig_ocr_result, tuple) and len(sig_ocr_result) == 4: ( sig_ocr, sig_vlm_input_tokens, sig_vlm_output_tokens, sig_vlm_model_name, ) = sig_ocr_result vlm_total_input_tokens += sig_vlm_input_tokens vlm_total_output_tokens += sig_vlm_output_tokens if sig_vlm_model_name and not vlm_model_name: vlm_model_name = sig_vlm_model_name else: sig_ocr = ( sig_ocr_result[0] if isinstance(sig_ocr_result, tuple) else sig_ocr_result ) texts = sig_ocr.get("text", []) lefts = sig_ocr.get("left", []) tops = sig_ocr.get("top", []) widths = sig_ocr.get("width", []) heights = sig_ocr.get("height", []) confs = sig_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words["results"] existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) sig_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[SIGNATURE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = float(confs[idx]) if idx < len(confs) else 0.0 except Exception: continue key = f"signature_line_{sig_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[SIGNATURE]", "bounding_box": bbox, "words": [ { "text": "[SIGNATURE]", "bounding_box": bbox, "conf": conf, "model": "bedrock-vlm", } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: Bedrock VLM signature detection failed on page {reported_page_number}: {e}" ) try: if ( page_line_level_ocr_results and "results" in page_line_level_ocr_results ): line_level_ocr_results_df = pd.DataFrame( [ line_level_ocr_row( page_line_level_ocr_results["page"], result ) for result in page_line_level_ocr_results["results"] ] ) else: line_level_ocr_results_df = pd.DataFrame() except (UnboundLocalError, NameError, KeyError): line_level_ocr_results_df = pd.DataFrame() if not line_level_ocr_results_df.empty: all_line_level_ocr_results_list.extend( line_level_ocr_results_df.to_dict("records") ) if ( text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and save_page_ocr_visualisations is True ): if ( page_line_level_ocr_results_with_words and "results" in page_line_level_ocr_results_with_words ): image_for_visualization = resolve_image_for_ocr_visualization( image, image_path, file_path, page_no, input_folder=input_folder, page_sizes_df=page_sizes_df, ) if image_for_visualization is not None: log_files_output_paths_length_before = len( log_files_output_paths ) log_files_output_paths = visualise_ocr_words_bounding_boxes( image_for_visualization, page_line_level_ocr_results_with_words["results"], image_name=f"{file_name}_{reported_page_number}", output_folder=output_folder, text_extraction_method=text_extraction_method, chosen_local_ocr_model=chosen_local_ocr_model, log_files_output_paths=log_files_output_paths, textract_hybrid_bedrock_used=hybrid_textract_bedrock_vlm, file_path=file_path, page_no=page_no, input_folder=input_folder, page_sizes_df=page_sizes_df, ) if ( INCLUDE_OCR_VISUALISATION_IN_OUTPUT_FILES and log_files_output_paths is not None and len(log_files_output_paths) > log_files_output_paths_length_before ): new_visualisation_path = log_files_output_paths[-1] if new_visualisation_path not in out_file_paths: out_file_paths.append(new_visualisation_path) else: print( f"Warning: Could not determine image for visualization at page {reported_page_number}. Skipping visualization." ) ocr_results_by_page[page_no] = { "page_line_level_ocr_results": page_line_level_ocr_results, "page_line_level_ocr_results_with_words": page_line_level_ocr_results_with_words, "page_signature_recogniser_results": page_signature_recogniser_results, "page_handwriting_recogniser_results": page_handwriting_recogniser_results, "handwriting_or_signature_boxes": handwriting_or_signature_boxes, "image_path": image_path, "pymupdf_page": pymupdf_page, "original_cropbox": original_cropbox, "page_width": page_width, "page_height": page_height, "image": image, "reported_page_number": reported_page_number, } # SECOND PASS: Perform PII detection on all pages using stored OCR results print("Second pass: Performing PII detection on all pages...") # Optional: run PII detection in parallel for Local and AWS Comprehend (skip when CUSTOM_VLM_FACES is used). # IMPORTANT: never parallelise PII when using inference-server or local-transformers LLM backends. pii_results_by_page_image = {} _use_parallel_image_pii = ( pii_identification_method in (LOCAL_PII_OPTION, AWS_PII_OPTION) and pii_identification_method not in (INFERENCE_SERVER_PII_OPTION, LOCAL_TRANSFORMERS_LLM_PII_OPTION) and (chosen_redact_entities or chosen_redact_comprehend_entities) and not ( pii_identification_method == AWS_PII_OPTION and "CUSTOM_VLM_FACES" in (chosen_redact_comprehend_entities or []) ) ) if _use_parallel_image_pii and ocr_results_by_page: _pii_pages = ( list(page_loop_pages) if page_loop_pages is not None else list(range(page_loop_start, page_loop_end)) ) _pii_jobs = [] for _pno in _pii_pages: if _pno not in ocr_results_by_page: continue _pdata = ocr_results_by_page[_pno] _plocr = _pdata.get("page_line_level_ocr_results") _plocrw = _pdata.get("page_line_level_ocr_results_with_words") if ( not _plocr or not isinstance(_plocr, dict) or "results" not in _plocr or not _plocrw ): continue if isinstance(_plocrw, list): if ( not _plocrw or not isinstance(_plocrw[0], dict) or "results" not in _plocrw[0] ): continue elif not isinstance(_plocrw, dict) or "results" not in _plocrw: continue _pii_jobs.append((_pno, _pdata)) text_analyzer_kwargs_parallel = {} if _pii_jobs: _n = len(_pii_jobs) _workers = min(MAX_WORKERS, _n) with ThreadPoolExecutor(max_workers=_workers) as executor: _results = list( tqdm( executor.map( lambda item: _run_image_pii_for_one_page( item[0], item[1], image_analyser, chosen_redact_comprehend_entities, chosen_llm_entities, pii_identification_method, comprehend_client, bedrock_runtime, chosen_redact_entities, language, allow_list, score_threshold, nlp_analyser, custom_llm_instructions, file_name, text_analyzer_kwargs_parallel, ), _pii_jobs, ), total=_n, unit="pages", desc="Detecting PII (parallel, image path)", ) ) for ( _pno, _boxes, _cq, _llm_name, _llm_in, _llm_out, ) in _results: pii_results_by_page_image[_pno] = ( _boxes, _cq, _llm_name, _llm_in, _llm_out, ) # Precompute redact_whole_page set for O(1) membership in the loop (same speedup as redact_text_pdf) redact_whole_page_set_image = set() if redact_whole_page_list: for _p in redact_whole_page_list: try: redact_whole_page_set_image.add(int(_p)) except (TypeError, ValueError): redact_whole_page_set_image.add(_p) if page_loop_pages is not None: pii_progress_bar = tqdm( page_loop_pages, unit="pages", desc=( "Applying redactions to pages" if pii_results_by_page_image else "Detecting PII (following image-based OCR)" ), ) else: pii_progress_bar = tqdm( range(page_loop_start, page_loop_end), unit="pages remaining", desc=( "Applying redactions to pages" if pii_results_by_page_image else "Detecting PII (following image-based OCR)" ), ) _pii_gui_total_pages = ( len(page_loop_pages) if page_loop_pages is not None else max(0, page_loop_end - page_loop_start) ) _pii_gui_total_str = str(_pii_gui_total_pages) if _pii_gui_total_pages else "?" # Initialize redacted_image - will be updated inside loop for image files redacted_image = None for page_no in pii_progress_bar: reported_page_number = str(page_no + 1) # print(f"PII Detection - Current page: {reported_page_number}") # Retrieve stored OCR results and page metadata if page_no not in ocr_results_by_page: print( f"Warning: No OCR results found for page {reported_page_number}, skipping PII detection" ) continue page_data = ocr_results_by_page[page_no] page_line_level_ocr_results = page_data["page_line_level_ocr_results"] page_line_level_ocr_results_with_words = page_data[ "page_line_level_ocr_results_with_words" ] page_signature_recogniser_results = page_data[ "page_signature_recogniser_results" ] page_handwriting_recogniser_results = page_data[ "page_handwriting_recogniser_results" ] handwriting_or_signature_boxes = page_data["handwriting_or_signature_boxes"] image_path = page_data["image_path"] pymupdf_page = page_data["pymupdf_page"] original_cropbox = page_data["original_cropbox"] page_width = page_data["page_width"] page_height = page_data["page_height"] image = page_data["image"] reported_page_number = page_data["reported_page_number"] try: pii_progress_bar.set_postfix_str( f"PII · page {reported_page_number}/{_pii_gui_total_str}", refresh=False, ) except Exception: pass # Initialize redacted_image for image files as fallback (will be updated if redactions are applied) if is_pdf(file_path) is False and redacted_image is None: # Try to get image from image_path or use the image from page_data if isinstance(image_path, str): try: normalized_path = os.path.normpath(os.path.abspath(image_path)) is_gradio_temp = ( "gradio" in normalized_path.lower() and "temp" in normalized_path.lower() ) if is_gradio_temp or validate_path_containment( normalized_path, input_folder ): redacted_image = Image.open(normalized_path) else: redacted_image = image if image is not None else None except Exception as e: print(f"Error loading image for redacted_image fallback: {e}") redacted_image = image if image is not None else None elif isinstance(image_path, Image.Image): redacted_image = image_path else: redacted_image = image if image is not None else None page_image_annotations = {"image": image_path, "boxes": []} page_break_return = False # Skip if OCR results are missing or invalid if ( not page_line_level_ocr_results or not isinstance(page_line_level_ocr_results, dict) or "results" not in page_line_level_ocr_results or not page_line_level_ocr_results_with_words or not isinstance(page_line_level_ocr_results_with_words, dict) or "results" not in page_line_level_ocr_results_with_words ): print( f"Warning: Missing or invalid OCR results for page {reported_page_number}, skipping PII detection" ) # Still need to handle page_image_annotations and current_loop_page for consistency page_image_annotations = {"image": image_path, "boxes": []} # Check if the image_path already exists in annotations_all_pages existing_index = next( ( index for index, ann in enumerate(annotations_all_pages) if ann.get("image") == page_image_annotations["image"] ), None, ) if existing_index is not None: annotations_all_pages[existing_index] = page_image_annotations else: annotations_all_pages.append(page_image_annotations) current_loop_page += 1 continue # Include VLM (face/signature) boxes in outputs even when "Only extract text (no redaction)" _include_vlm_boxes_in_outputs = _run_face_pass or _textract_face_identification _vlm_boxes_only_no_redaction = ( False # set True when we add VLM boxes to outputs only (no PDF redaction) ) if ( pii_identification_method != NO_REDACTION_PII_OPTION or RETURN_PDF_FOR_REVIEW is True or _include_vlm_boxes_in_outputs ): page_redaction_bounding_boxes = list() comprehend_query_number_new = 0 redact_whole_page = False if pii_identification_method != NO_REDACTION_PII_OPTION: # Step 2: Analyse text and identify PII if chosen_redact_entities or chosen_redact_comprehend_entities: # Set up inference server or local transformers parameters for PII detection text_analyzer_kwargs = {} if pii_identification_method == INFERENCE_SERVER_PII_OPTION: text_analyzer_kwargs["inference_method"] = "inference-server" text_analyzer_kwargs["api_url"] = INFERENCE_SERVER_API_URL # Use INFERENCE_SERVER_LLM_PII_MODEL_CHOICE for inference server PII detection text_analyzer_kwargs["model_choice"] = ( INFERENCE_SERVER_LLM_PII_MODEL_CHOICE ) elif pii_identification_method == LOCAL_TRANSFORMERS_LLM_PII_OPTION: # Set up local transformers LLM parameters text_analyzer_kwargs["inference_method"] = "local" # Use LOCAL_TRANSFORMERS_LLM_PII_MODEL_CHOICE as default model for local transformers text_analyzer_kwargs["model_choice"] = ( LOCAL_TRANSFORMERS_LLM_PII_MODEL_CHOICE ) # Optional additional Bedrock VLM pass to detect people # and inject [FACE] entries into the word-level OCR structure for AWS Comprehend. if ( not _skip_inline_custom_vlm_detection and pii_identification_method == AWS_PII_OPTION and "CUSTOM_VLM_FACES" in chosen_redact_comprehend_entities and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None ): try: _gui_tqdm_subphase( pii_progress_bar, progress, "Face detection (VLM, during PII)", str(reported_page_number), _pii_gui_total_str, ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) # Use Bedrock VLM for people detection model_choice = CLOUD_VLM_MODEL_CHOICE normalised_coords_range = 999 # Full-page prompt uses 0-999 for all Bedrock models people_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_people_only=True, model_choice=model_choice, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) # Unpack tuple: (Dict[str, List], int, int, str) -> (ocr_data, vlm_input_tokens, vlm_output_tokens, vlm_model_name) if ( isinstance(people_ocr_result, tuple) and len(people_ocr_result) == 4 ): ( people_ocr, people_vlm_input_tokens, people_vlm_output_tokens, people_vlm_model_name, ) = people_ocr_result # Accumulate VLM token usage vlm_total_input_tokens += people_vlm_input_tokens vlm_total_output_tokens += people_vlm_output_tokens if people_vlm_model_name and not vlm_model_name: vlm_model_name = people_vlm_model_name else: people_ocr = ( people_ocr_result[0] if isinstance(people_ocr_result, tuple) else people_ocr_result ) # Convert people_ocr outputs into additional word-level entries texts = people_ocr.get("text", []) lefts = people_ocr.get("left", []) tops = people_ocr.get("top", []) widths = people_ocr.get("width", []) heights = people_ocr.get("height", []) confs = people_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words[ "results" ] # Determine a valid starting line number for synthetic [FACE] lines existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) person_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[FACE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = ( float(confs[idx]) if idx < len(confs) else 0.0 ) except Exception: continue key = f"person_line_{person_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[FACE]", "bounding_box": bbox, "words": [ { "text": "[FACE]", "bounding_box": bbox, "conf": conf, "model": "bedrock-vlm", } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: Bedrock VLM person detection failed on page {reported_page_number}: {e}" ) # Optional additional Bedrock VLM pass to detect signatures # and inject [SIGNATURE] entries into the word-level OCR structure for AWS Comprehend. # Skipped when defer_inline_custom_vlm_detection_pass: post-pass covers PDF/decision table. if ( not _skip_inline_custom_vlm_detection and not _skip_custom_vlm_signature_textract and pii_identification_method == AWS_PII_OPTION and "CUSTOM_VLM_SIGNATURE" in chosen_redact_comprehend_entities and isinstance(page_line_level_ocr_results_with_words, dict) and page_line_level_ocr_results_with_words.get("results") and image is not None ): try: _gui_tqdm_subphase( pii_progress_bar, progress, "Signature detection (VLM, during PII)", str(reported_page_number), _pii_gui_total_str, ) image_name = ( os.path.basename(image_path) if isinstance(image_path, str) else f"{file_name}_{reported_page_number}.png" ) # Use Bedrock VLM for signature detection model_choice = CLOUD_VLM_MODEL_CHOICE normalised_coords_range = 999 # Full-page prompt uses 0-999 for all Bedrock models sig_ocr_result = _bedrock_page_ocr_predict( image, image_name=image_name, normalised_coords_range=normalised_coords_range, output_folder=output_folder, detect_signatures_only=True, model_choice=model_choice, bedrock_runtime=bedrock_runtime, page_index_0=page_no, ) # Unpack tuple: (Dict[str, List], int, int, str) -> (ocr_data, vlm_input_tokens, vlm_output_tokens, vlm_model_name) if ( isinstance(sig_ocr_result, tuple) and len(sig_ocr_result) == 4 ): ( sig_ocr, sig_vlm_input_tokens, sig_vlm_output_tokens, sig_vlm_model_name, ) = sig_ocr_result # Accumulate VLM token usage vlm_total_input_tokens += sig_vlm_input_tokens vlm_total_output_tokens += sig_vlm_output_tokens if sig_vlm_model_name and not vlm_model_name: vlm_model_name = sig_vlm_model_name else: sig_ocr = ( sig_ocr_result[0] if isinstance(sig_ocr_result, tuple) else sig_ocr_result ) # Convert sig_ocr outputs into additional word-level entries texts = sig_ocr.get("text", []) lefts = sig_ocr.get("left", []) tops = sig_ocr.get("top", []) widths = sig_ocr.get("width", []) heights = sig_ocr.get("height", []) confs = sig_ocr.get("conf", []) results_dict = page_line_level_ocr_results_with_words[ "results" ] # Determine a valid starting line number for synthetic [SIGNATURE] lines existing_lines = [] for _line_key, _line_data in results_dict.items(): line_val = _line_data.get("line") if isinstance(line_val, (int, float, str)): try: existing_lines.append(int(line_val)) except Exception: continue next_line_number = ( max(existing_lines) if existing_lines else 0 ) + 1 existing_keys = list(results_dict.keys()) sig_index_start = len(existing_keys) + 1 for idx, text in enumerate(texts): if text != "[SIGNATURE]": continue try: left = int(lefts[idx]) top = int(tops[idx]) width = int(widths[idx]) height = int(heights[idx]) conf = ( float(confs[idx]) if idx < len(confs) else 0.0 ) except Exception: continue key = f"signature_line_{sig_index_start + idx}" bbox = (left, top, left + width, top + height) results_dict[key] = { "line": int(next_line_number), "text": "[SIGNATURE]", "bounding_box": bbox, "words": [ { "text": "[SIGNATURE]", "bounding_box": bbox, "conf": conf, "model": "bedrock-vlm", } ], "conf": conf, } next_line_number += 1 except Exception as e: print( f"Warning: Bedrock VLM signature detection failed on page {reported_page_number}: {e}" ) # Call analyze_text for all PII detection methods (Local, AWS Comprehend, LLM, Inference Server) # Use precomputed result when parallel PII was run (Local/AWS Comprehend). if page_no in pii_results_by_page_image: ( page_redaction_bounding_boxes, comprehend_query_number_new, llm_model_name_page, llm_input_tokens_page, llm_output_tokens_page, ) = pii_results_by_page_image[page_no] else: ( page_redaction_bounding_boxes, comprehend_query_number_new, llm_model_name_page, llm_input_tokens_page, llm_output_tokens_page, ) = image_analyser.analyze_text( page_line_level_ocr_results["results"], page_line_level_ocr_results_with_words["results"], chosen_redact_comprehend_entities=chosen_redact_comprehend_entities, chosen_llm_entities=chosen_llm_entities, pii_identification_method=pii_identification_method, comprehend_client=comprehend_client, bedrock_runtime=bedrock_runtime, custom_entities=chosen_redact_entities, language=language, allow_list=allow_list, score_threshold=score_threshold, nlp_analyser=nlp_analyser, custom_llm_instructions=custom_llm_instructions, file_name=file_name, page_number=int(reported_page_number), **text_analyzer_kwargs, ) comprehend_query_number = ( comprehend_query_number + comprehend_query_number_new ) # Accumulate LLM token usage across pages llm_total_input_tokens += llm_input_tokens_page llm_total_output_tokens += llm_output_tokens_page if llm_model_name_page and not llm_model_name: llm_model_name = llm_model_name_page else: page_redaction_bounding_boxes = list() # Merge redaction bounding boxes that are close together # This happens regardless of whether entities were chosen, as long as PII detection is enabled page_merged_redaction_bboxes = merge_img_bboxes( page_redaction_bounding_boxes, page_line_level_ocr_results_with_words["results"], page_signature_recogniser_results, page_handwriting_recogniser_results, handwrite_signature_checkbox, ) else: page_merged_redaction_bboxes = list() if is_pdf(file_path) is True: int_reported_page_number = int(reported_page_number) redact_whole_page = ( int_reported_page_number in redact_whole_page_set_image if redact_whole_page_set_image else False ) # Check if there are question answer boxes if form_key_value_results_list: page_merged_redaction_bboxes.extend( convert_page_question_answer_to_custom_image_recognizer_results( form_key_value_results_list, page_sizes_df, reported_page_number, ) ) # When "Only extract text (no redaction)" but we have VLM (face/signature) boxes: # add them to annotations and decision table without applying redactions to the PDF. if ( pii_identification_method == NO_REDACTION_PII_OPTION and page_merged_redaction_bboxes ): _vlm_boxes_only_no_redaction = True all_image_annotations_boxes = list() for box in page_merged_redaction_bboxes: try: img_annotation_box = { "xmin": box.left, "ymin": box.top, "xmax": box.left + box.width, "ymax": box.top + box.height, "label": getattr(box, "entity_type", "Redaction"), "text": getattr(box, "text", "") or "", "color": CUSTOM_BOX_COLOUR, } all_image_annotations_boxes.append( fill_missing_box_ids(img_annotation_box) ) except AttributeError: continue page_image_annotations = { "image": image_path, "boxes": all_image_annotations_boxes, } existing_index = next( ( index for index, ann in enumerate(annotations_all_pages) if ann.get("image") == page_image_annotations["image"] ), None, ) if existing_index is not None: annotations_all_pages[existing_index] = page_image_annotations else: annotations_all_pages.append(page_image_annotations) decision_process_table = pd.DataFrame( [ { "text": result.text, "xmin": result.left, "ymin": result.top, "xmax": result.left + result.width, "ymax": result.top + result.height, "label": result.entity_type, "start": result.start, "end": result.end, "score": result.score, "page": reported_page_number, } for result in page_merged_redaction_bboxes ] ) if not decision_process_table.empty: all_pages_decision_process_list.extend( decision_process_table.to_dict("records") ) else: # 3. Draw the merged boxes ## Apply annotations to pdf with pymupdf (pass dimensions to skip .loc in redact_page_with_pymupdf) redact_result = redact_page_with_pymupdf( pymupdf_page, page_merged_redaction_bboxes, image_path, redact_whole_page=redact_whole_page, original_cropbox=original_cropbox, page_sizes_df=page_sizes_df, input_folder=input_folder, image_dimensions_override={ "image_width": page_width, "image_height": page_height, }, ) # Handle dual page objects if returned if isinstance(redact_result[0], tuple): ( pymupdf_page, pymupdf_applied_redaction_page, ), page_image_annotations = redact_result # Store the final page with its original page number for later use if not hasattr(redact_image_pdf, "_applied_redaction_pages"): redact_image_pdf._applied_redaction_pages = list() redact_image_pdf._applied_redaction_pages.append( (pymupdf_applied_redaction_page, page_no) ) else: pymupdf_page, page_image_annotations = redact_result # When dual output is requested but this page had no redaction boxes, # we still need an "applied" page entry so the final PDF replace loop # replaces every page. Otherwise only pages with at least one redaction # get replaced, and other pages stay as review-style (annotations only). if RETURN_PDF_FOR_REVIEW and RETURN_REDACTED_PDF: if not hasattr( redact_image_pdf, "_applied_redaction_pages" ): redact_image_pdf._applied_redaction_pages = list() applied_doc = pymupdf.open() applied_doc.insert_pdf( pymupdf_page.parent, from_page=page_no, to_page=page_no, ) applied_page_copy = applied_doc[0] redact_image_pdf._applied_redaction_pages.append( (applied_page_copy, page_no) ) # If an image_path file, draw onto the image_path elif is_pdf(file_path) is False: if isinstance(image_path, str): # Normalise and validate path safety before checking existence normalized_path = os.path.normpath(os.path.abspath(image_path)) # Check if it's a Gradio temporary file is_gradio_temp = ( "gradio" in normalized_path.lower() and "temp" in normalized_path.lower() ) if is_gradio_temp or validate_path_containment( normalized_path, INPUT_FOLDER ): image = Image.open(normalized_path) else: print(f"Path validation failed for: {normalized_path}") # You might want to handle this case differently continue # or raise an exception elif isinstance(image_path, Image.Image): image = image_path else: # Assume image_path is an image image = image_path fill = CUSTOM_BOX_COLOUR # Fill colour for redactions draw = ImageDraw.Draw(image) all_image_annotations_boxes = list() for box in page_merged_redaction_bboxes: try: x0 = box.left y0 = box.top x1 = x0 + box.width y1 = y0 + box.height label = box.entity_type # Attempt to get the label text = box.text except AttributeError as e: print(f"Error accessing box attributes: {e}") label = "Redaction" # Default label if there's an error # Check if coordinates are valid numbers if any(v is None for v in [x0, y0, x1, y1]): print(f"Invalid coordinates for box: {box}") continue # Skip this box if coordinates are invalid img_annotation_box = { "xmin": x0, "ymin": y0, "xmax": x1, "ymax": y1, "label": label, "color": CUSTOM_BOX_COLOUR, "text": text, } img_annotation_box = fill_missing_box_ids(img_annotation_box) # Directly append the dictionary with the required keys all_image_annotations_boxes.append(img_annotation_box) # Draw the rectangle try: draw.rectangle([x0, y0, x1, y1], fill=fill) except Exception as e: print(f"Error drawing rectangle: {e}") # Update redacted_image with the redacted version for image files redacted_image = image page_image_annotations = { "image": image_path, "boxes": all_image_annotations_boxes, } # Convert decision process to table (skip when already done in NO_REDACTION VLM-only branch) if not _vlm_boxes_only_no_redaction: decision_process_table = pd.DataFrame( [ { "text": result.text, "xmin": result.left, "ymin": result.top, "xmax": result.left + result.width, "ymax": result.top + result.height, "label": result.entity_type, "start": result.start, "end": result.end, "score": result.score, "page": reported_page_number, } for result in page_merged_redaction_bboxes ] ) # all_pages_decision_process_list.append(decision_process_table.to_dict('records')) if not decision_process_table.empty: # Ensure there are records to add all_pages_decision_process_list.extend( decision_process_table.to_dict("records") ) decision_process_table = fill_missing_ids(decision_process_table) toc = time.perf_counter() time_taken = toc - tic # Break if time taken is greater than max_time seconds if time_taken > max_time: print("Processing for", max_time, "seconds, breaking loop.") page_break_return = True progress.close(_tqdm=pii_progress_bar) tqdm._instances.clear() if is_pdf(file_path) is False: # Ensure redacted_image is set before appending (timeout case) if redacted_image is None: # Fallback: try to use image_path or image from page_data if isinstance(image_path, str): try: normalized_path = os.path.normpath( os.path.abspath(image_path) ) is_gradio_temp = ( "gradio" in normalized_path.lower() and "temp" in normalized_path.lower() ) if is_gradio_temp or validate_path_containment( normalized_path, input_folder ): redacted_image = Image.open(normalized_path) else: redacted_image = ( image if image is not None else image_path ) except Exception as e: print( f"Error loading image for redacted_image timeout fallback: {e}" ) redacted_image = ( image if image is not None else image_path ) elif isinstance(image_path, Image.Image): redacted_image = image_path else: redacted_image = image if image is not None else image_path if redacted_image is not None: pdf_image_file_paths.append( redacted_image ) # .append(image_path) pymupdf_doc = pdf_image_file_paths else: print( f"Warning: redacted_image is None for image file {file_path} in timeout case, skipping append" ) # Check if the image_path already exists in annotations_all_pages existing_index = next( ( index for index, ann in enumerate(annotations_all_pages) if ann["image"] == page_image_annotations["image"] ), None, ) if existing_index is not None: # Replace the existing annotation annotations_all_pages[existing_index] = page_image_annotations else: # Append new annotation if it doesn't exist annotations_all_pages.append(page_image_annotations) # Save word level options if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: if original_textract_data != textract_data: # Write the updated existing textract data back to the JSON file secure_file_write( output_folder, file_name + textract_suffix + "_textract.json", json.dumps(textract_data, separators=(",", ":")), ) if textract_json_file_path not in log_files_output_paths: log_files_output_paths.append(textract_json_file_path) all_pages_decision_process_table = pd.DataFrame( all_pages_decision_process_list ) all_line_level_ocr_results_df = normalize_line_level_ocr_df( pd.DataFrame(all_line_level_ocr_results_list) ) if selection_element_results_list: selection_element_results_list_df = pd.DataFrame( selection_element_results_list ) if form_key_value_results_list: pd.DataFrame(form_key_value_results_list) form_key_value_results_list_df = ( convert_question_answer_to_dataframe( form_key_value_results_list, page_sizes_df ) ) current_loop_page += 1 return ( pymupdf_doc, all_pages_decision_process_table, log_files_output_paths, textract_request_metadata, annotations_all_pages, current_loop_page, page_break_return, all_line_level_ocr_results_df, comprehend_query_number, all_page_line_level_ocr_results, all_page_line_level_ocr_results_with_words, selection_element_results_list_df, form_key_value_results_list_df, out_file_paths, ) # If it's an image file if is_pdf(file_path) is False: # Ensure redacted_image is set before appending if redacted_image is None: # Fallback: try to use image_path or image from page_data if isinstance(image_path, str): try: normalized_path = os.path.normpath(os.path.abspath(image_path)) is_gradio_temp = ( "gradio" in normalized_path.lower() and "temp" in normalized_path.lower() ) if is_gradio_temp or validate_path_containment( normalized_path, input_folder ): redacted_image = Image.open(normalized_path) else: redacted_image = image if image is not None else image_path except Exception as e: print( f"Error loading image for redacted_image final fallback: {e}" ) redacted_image = image if image is not None else image_path elif isinstance(image_path, Image.Image): redacted_image = image_path else: redacted_image = image if image is not None else image_path if redacted_image is not None: pdf_image_file_paths.append(redacted_image) # .append(image_path) pymupdf_doc = pdf_image_file_paths else: print( f"Warning: redacted_image is None for image file {file_path}, skipping append" ) # Check if the image_path already exists in annotations_all_pages existing_index = next( ( index for index, ann in enumerate(annotations_all_pages) if ann["image"] == page_image_annotations["image"] ), None, ) if existing_index is not None: # Replace the existing annotation annotations_all_pages[existing_index] = page_image_annotations else: # Append new annotation if it doesn't exist annotations_all_pages.append(page_image_annotations) current_loop_page += 1 # Break if new page is a multiple of chosen page_break_val if current_loop_page % page_break_val == 0: print( f"current_loop_page: {current_loop_page} is a multiple of page_break_val: {page_break_val}, breaking loop" ) page_break_return = True progress.close(_tqdm=pii_progress_bar) tqdm._instances.clear() if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: # Write the updated existing textract data back to the JSON file if original_textract_data != textract_data: secure_file_write( output_folder, file_name + textract_suffix + "_textract.json", json.dumps(textract_data, separators=(",", ":")), ) if textract_json_file_path not in log_files_output_paths: log_files_output_paths.append(textract_json_file_path) if text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION: if ( original_all_page_line_level_ocr_results_with_words != all_page_line_level_ocr_results_with_words ): # Write the updated existing local OCR data back to the JSON file with open( all_page_line_level_ocr_results_with_words_json_file_path, "w" ) as json_file: json.dump( all_page_line_level_ocr_results_with_words, json_file, separators=(",", ":"), ) # indent=4 makes the JSON file pretty-printed if ( all_page_line_level_ocr_results_with_words_json_file_path not in log_files_output_paths ): log_files_output_paths.append( all_page_line_level_ocr_results_with_words_json_file_path ) all_pages_decision_process_table = pd.DataFrame( all_pages_decision_process_list ) all_line_level_ocr_results_df = normalize_line_level_ocr_df( pd.DataFrame(all_line_level_ocr_results_list) ) if selection_element_results_list: selection_element_results_list_df = pd.DataFrame( selection_element_results_list ) if form_key_value_results_list: pd.DataFrame(form_key_value_results_list) form_key_value_results_list_df = convert_question_answer_to_dataframe( form_key_value_results_list, page_sizes_df ) return ( pymupdf_doc, all_pages_decision_process_table, log_files_output_paths, textract_request_metadata, annotations_all_pages, current_loop_page, page_break_return, all_line_level_ocr_results_df, comprehend_query_number, all_page_line_level_ocr_results, all_page_line_level_ocr_results_with_words, selection_element_results_list_df, form_key_value_results_list_df, out_file_paths, ) if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: # Write the updated existing textract data back to the JSON file if overwrite_existing_ocr_results or original_textract_data != textract_data: secure_file_write( output_folder, file_name + textract_suffix + "_textract.json", json.dumps(textract_data, separators=(",", ":")), ) if textract_json_file_path not in log_files_output_paths: log_files_output_paths.append(textract_json_file_path) if text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION: # print( # f"Writing updated existing local OCR data back to the JSON file: {all_page_line_level_ocr_results_with_words_json_file_path}" # ) if ( overwrite_existing_ocr_results or original_all_page_line_level_ocr_results_with_words != all_page_line_level_ocr_results_with_words ): # Write the updated existing textract data back to the JSON file with open( all_page_line_level_ocr_results_with_words_json_file_path, "w" ) as json_file: json.dump( all_page_line_level_ocr_results_with_words, json_file, separators=(",", ":"), ) # indent=4 makes the JSON file pretty-printed if ( all_page_line_level_ocr_results_with_words_json_file_path not in log_files_output_paths ): log_files_output_paths.append( all_page_line_level_ocr_results_with_words_json_file_path ) # Build outputs as DataFrames (lists can contain either DataFrames or dict rows). # Some code paths append per-page DataFrames; others append dict records. if all_pages_decision_process_list: _dp_dfs = [ x for x in all_pages_decision_process_list if isinstance(x, pd.DataFrame) ] _dp_rows = [x for x in all_pages_decision_process_list if isinstance(x, dict)] if _dp_dfs and _dp_rows: all_pages_decision_process_table = pd.concat( _dp_dfs + [pd.DataFrame(_dp_rows)], ignore_index=True ) elif _dp_dfs: all_pages_decision_process_table = pd.concat(_dp_dfs, ignore_index=True) else: all_pages_decision_process_table = pd.DataFrame(_dp_rows) else: all_pages_decision_process_table = pd.DataFrame() if all_line_level_ocr_results_list: _ocr_dfs = [ x for x in all_line_level_ocr_results_list if isinstance(x, pd.DataFrame) ] _ocr_rows = [x for x in all_line_level_ocr_results_list if isinstance(x, dict)] if _ocr_dfs and _ocr_rows: all_line_level_ocr_results_df = normalize_line_level_ocr_df( pd.concat(_ocr_dfs + [pd.DataFrame(_ocr_rows)], ignore_index=True) ) elif _ocr_dfs: all_line_level_ocr_results_df = normalize_line_level_ocr_df( pd.concat(_ocr_dfs, ignore_index=True) ) else: all_line_level_ocr_results_df = normalize_line_level_ocr_df( pd.DataFrame(_ocr_rows) ) else: all_line_level_ocr_results_df = pd.DataFrame(columns=LINE_LEVEL_OCR_DF_COLUMNS) # Convert decision table and ocr results to relative coordinates _pages_pdf_pts = set(pages_in_pdf_points) if pages_in_pdf_points else None all_pages_decision_process_table = divide_coordinates_by_page_sizes( all_pages_decision_process_table, page_sizes_df, xmin="xmin", xmax="xmax", ymin="ymin", ymax="ymax", pages_in_pdf_points=_pages_pdf_pts, ) all_line_level_ocr_results_df = divide_coordinates_by_page_sizes( all_line_level_ocr_results_df, page_sizes_df, xmin="left", xmax="width", ymin="top", ymax="height", ) if selection_element_results_list: selection_element_results_list_df = pd.DataFrame(selection_element_results_list) if form_key_value_results_list: pd.DataFrame(form_key_value_results_list) form_key_value_results_list_df = convert_question_answer_to_dataframe( form_key_value_results_list, page_sizes_df ) return ( pymupdf_doc, all_pages_decision_process_table, log_files_output_paths, textract_request_metadata, annotations_all_pages, current_loop_page, page_break_return, all_line_level_ocr_results_df, comprehend_query_number, all_page_line_level_ocr_results, all_page_line_level_ocr_results_with_words, selection_element_results_list_df, form_key_value_results_list_df, out_file_paths, llm_model_name, llm_total_input_tokens, llm_total_output_tokens, vlm_model_name, vlm_total_input_tokens, vlm_total_output_tokens, ) ### # PIKEPDF TEXT DETECTION/REDACTION ### def get_text_container_characters(text_container: LTTextContainer): if isinstance(text_container, LTTextContainer): characters = [ char for line in text_container if isinstance(line, LTTextLine) or isinstance(line, LTTextLineHorizontal) for char in line ] return characters return [] def create_line_level_ocr_results_from_characters( char_objects: List, line_number: int ) -> Tuple[List[OCRResult], List[List]]: """ Create OCRResult objects based on a list of pdfminer LTChar objects. This version is corrected to use the specified OCRResult class definition. """ line_level_results_out = list() line_level_characters_out = list() character_objects_out = list() full_text = "" # [x0, y0, x1, y1] overall_bbox = [float("inf"), float("inf"), float("-inf"), float("-inf")] for char in char_objects: character_objects_out.append(char) if isinstance(char, LTAnno): added_text = char.get_text() full_text += added_text if "\n" in added_text: if full_text.strip(): # Create OCRResult for line line_level_results_out.append( OCRResult( text=full_text.strip(), left=round(overall_bbox[0], 2), top=round(overall_bbox[1], 2), width=round(overall_bbox[2] - overall_bbox[0], 2), height=round(overall_bbox[3] - overall_bbox[1], 2), line=line_number, model="pdfminer", ) ) line_level_characters_out.append(character_objects_out) # Reset for the next line character_objects_out = list() full_text = "" overall_bbox = [ float("inf"), float("inf"), float("-inf"), float("-inf"), ] line_number += 1 continue # This part handles LTChar objects added_text = clean_unicode_text( char.get_text(), preserve_international_scripts=True ) full_text += added_text x0, y0, x1, y1 = char.bbox overall_bbox[0] = min(overall_bbox[0], x0) overall_bbox[1] = min(overall_bbox[1], y0) overall_bbox[2] = max(overall_bbox[2], x1) overall_bbox[3] = max(overall_bbox[3], y1) # Process the last line if full_text.strip(): line_number += 1 line_ocr_result = OCRResult( text=full_text.strip(), left=round(overall_bbox[0], 2), top=round(overall_bbox[1], 2), width=round(overall_bbox[2] - overall_bbox[0], 2), height=round(overall_bbox[3] - overall_bbox[1], 2), line=line_number, model="pdfminer", ) line_level_results_out.append(line_ocr_result) line_level_characters_out.append(character_objects_out) return line_level_results_out, line_level_characters_out def generate_words_for_line(line_chars: List) -> List[Dict[str, Any]]: """ Generates word-level results for a single, pre-defined line of characters. This robust version correctly identifies word breaks by: 1. Treating specific punctuation characters as standalone words. 2. Explicitly using space characters (' ') as a primary word separator. 3. Using a geometric gap between characters as a secondary, heuristic separator. Args: line_chars: A list of pdfminer.six LTChar/LTAnno objects for one line. Returns: A list of dictionaries, where each dictionary represents an individual word. """ # We only care about characters with coordinates and text for word building. text_chars = [c for c in line_chars if hasattr(c, "bbox") and c.get_text()] if not text_chars: return [] # Sort characters by horizontal position for correct processing. text_chars.sort(key=lambda c: c.bbox[0]) # NEW: Define punctuation that should be split into separate words. # The hyphen '-' is intentionally excluded to keep words like 'high-tech' together. PUNCTUATION_TO_SPLIT = {".", ",", "?", "!", ":", ";", "(", ")", "[", "]", "{", "}"} line_words = list() current_word_text = "" current_word_bbox = [float("inf"), float("inf"), -1, -1] # [x0, y0, x1, y1] prev_char = None def finalize_word(): nonlocal current_word_text, current_word_bbox # Only add the word if it contains non-space text if current_word_text.strip(): # Safeguard: avoid emitting y=-1 (e.g. single-char word edge case) if current_word_bbox[1] == -1 and current_word_bbox[3] != -1: current_word_bbox[1] = current_word_bbox[3] # bbox from [x0, y0, x1, y1] to your required format final_bbox = [ round(current_word_bbox[0], 2), round(current_word_bbox[3], 2), # Note: using y1 from pdfminer bbox round(current_word_bbox[2], 2), round(current_word_bbox[1], 2), # Note: using y0 from pdfminer bbox ] line_words.append( { "text": current_word_text.strip(), "bounding_box": final_bbox, "conf": 100.0, } ) # Reset for the next word current_word_text = "" current_word_bbox = [float("inf"), float("inf"), -1, -1] for char in text_chars: char_text = clean_unicode_text( char.get_text(), preserve_international_scripts=True ) # 1. NEW: Check for splitting punctuation first. if char_text in PUNCTUATION_TO_SPLIT: # Finalize any word that came immediately before the punctuation. finalize_word() # Treat the punctuation itself as a separate word. px0, py0, px1, py1 = char.bbox punc_bbox = [round(px0, 2), round(py1, 2), round(px1, 2), round(py0, 2)] line_words.append( {"text": char_text, "bounding_box": punc_bbox, "conf": 100.0} ) prev_char = char continue # Skip to the next character # 2. Primary Signal: Is the character a space? if char_text.isspace(): finalize_word() # End the preceding word prev_char = char continue # Skip to the next character, do not add the space to any word # 3. Secondary Signal: Is there a large geometric gap? if prev_char: # A gap is considered a word break if it's larger than a fraction of the font size. space_threshold = prev_char.size * 0.25 # 25% of the char size min_gap = 1.0 # Or at least 1.0 unit gap = ( char.bbox[0] - prev_char.bbox[2] ) # gap = current_char.x0 - prev_char.x1 if gap > max(space_threshold, min_gap): finalize_word() # Found a gap, so end the previous word. # Append the character's text and update the bounding box for the current word current_word_text += char_text x0, y0, x1, y1 = char.bbox # First character of this word: set bbox from character (avoids -1 for single-char words) if current_word_bbox[1] == -1 or current_word_bbox[3] == -1: current_word_bbox = [x0, y0, x1, y1] else: current_word_bbox[0] = min(current_word_bbox[0], x0) current_word_bbox[1] = min( current_word_bbox[3], y0 ) # pdfminer y0 is bottom current_word_bbox[2] = max(current_word_bbox[2], x1) current_word_bbox[3] = max(current_word_bbox[1], y1) # pdfminer y1 is top prev_char = char # After the loop, finalize the last word that was being built. finalize_word() return line_words def process_page_to_structured_ocr( all_char_objects: List, page_number: int, text_line_number: int, # This will now be treated as the STARTING line number ) -> Tuple[Dict[str, Any], List[OCRResult], List[List]]: """ Orchestrates the OCR process, correctly handling multiple lines. Returns: A tuple containing: 1. A dictionary with detailed line/word results for the page. 2. A list of the complete OCRResult objects for each line. 3. A list of lists, containing the character objects for each line. """ page_data = {"page": str(page_number), "results": {}} # Step 1: Get definitive lines and their character groups. # This function correctly returns all lines found in the input characters. line_results, lines_char_groups = create_line_level_ocr_results_from_characters( all_char_objects, text_line_number ) if not line_results: return {}, [], [] # Step 2: Iterate through each found line and generate its words. for i, (line_info, char_group) in enumerate(zip(line_results, lines_char_groups)): current_line_number = line_info.line # text_line_number + i word_level_results = generate_words_for_line(char_group) # Create a unique, incrementing line number for each iteration. line_key = f"text_line_{current_line_number}" line_bbox = [ line_info.left, line_info.top, line_info.left + line_info.width, line_info.top + line_info.height, ] # Now, each line is added to the dictionary with its own unique key. page_data["results"][line_key] = { "line": current_line_number, # Use the unique line number "text": line_info.text, "bounding_box": line_bbox, "words": word_level_results, "conf": 100.0, } # The list of OCRResult objects is already correct. line_level_ocr_results_list = line_results # Return the structured dictionary, the list of OCRResult objects, and the character groups return page_data, line_level_ocr_results_list, lines_char_groups def _extract_text_from_single_page(file_path: str, page_no: int) -> Tuple[ int, List, List, pd.DataFrame, List[Dict[str, Any]], ]: """ Extract selectable text and structured OCR-style results for a single PDF page. Used by redact_text_pdf for parallel text extraction (ThreadPoolExecutor). Only reads file_path; safe to call from multiple threads. Returns: Tuple of (page_no, all_page_line_level_text_extraction_results_list, all_page_line_text_extraction_characters, page_text_ocr_outputs, page_ocr_results_with_words). """ reported_page_number = page_no + 1 all_page_line_level_text_extraction_results_list = list() all_page_line_text_extraction_characters = list() page_ocr_results_with_words = list() page_text_ocr_outputs_list = list() empty_ocr_df = pd.DataFrame(columns=LINE_LEVEL_OCR_DF_COLUMNS) text_line_no = 1 for page_layout in extract_pages(file_path, page_numbers=[page_no], maxpages=1): for text_container in page_layout: characters = list() if isinstance(text_container, LTTextContainer) or isinstance( text_container, LTAnno ): characters = get_text_container_characters(text_container) ( line_level_ocr_results_with_words, line_level_text_results_list, line_characters, ) = process_page_to_structured_ocr( characters, page_number=int(reported_page_number), text_line_number=text_line_no, ) text_line_no += len(line_level_text_results_list) if line_level_text_results_list: line_level_text_results_df = pd.DataFrame( [ { **line_level_ocr_row(page_no + 1, result), "text": (result.text).strip(), "conf": getattr(result, "conf", 100.0), } for result in line_level_text_results_list ] ) page_text_ocr_outputs_list.append(line_level_text_results_df) all_page_line_level_text_extraction_results_list.extend( line_level_text_results_list ) all_page_line_text_extraction_characters.extend(line_characters) page_ocr_results_with_words.append(line_level_ocr_results_with_words) if page_text_ocr_outputs_list: non_empty = [df for df in page_text_ocr_outputs_list if not df.empty] page_text_ocr_outputs = ( pd.concat(non_empty, ignore_index=True) if non_empty else empty_ocr_df ) else: page_text_ocr_outputs = empty_ocr_df.copy() return ( page_no, all_page_line_level_text_extraction_results_list, all_page_line_text_extraction_characters, page_text_ocr_outputs, page_ocr_results_with_words, ) # Punctuation that should be split into separate words (same as generate_words_for_line). _PUNCTUATION_TO_SPLIT = {".", ",", "?", "!", ":", ";", "(", ")", "[", "]", "{", "}"} def _words_from_line_chars_pymupdf( line_chars: List[Dict[str, Any]], off_x: float, off_y: float ) -> List[Dict[str, Any]]: """ Build word-level results from PyMuPDF line characters, splitting punctuation into separate words (same behaviour as generate_words_for_line). Args: line_chars: List of dicts with "text", "bbox" (x0,y0,x1,y1), "size". off_x, off_y: Page offset to add to bounding boxes. Returns: List of {"text", "bounding_box": [x0,y0,x1,y1], "conf": 100.0}. """ if not line_chars: return [] # Sort by horizontal position sorted_chars = sorted(line_chars, key=lambda c: c["bbox"][0]) line_words: List[Dict[str, Any]] = [] current_word_text = "" current_word_bbox: List[float] = [float("inf"), float("inf"), -1, -1] prev_char: Optional[Dict[str, Any]] = None def finalize_word() -> None: nonlocal current_word_text, current_word_bbox if not current_word_text.strip(): current_word_text = "" current_word_bbox = [float("inf"), float("inf"), -1, -1] return if current_word_bbox[1] == -1 and current_word_bbox[3] != -1: current_word_bbox[1] = current_word_bbox[3] if current_word_bbox[3] == -1 and current_word_bbox[1] != -1: current_word_bbox[3] = current_word_bbox[1] x0, y0, x1, y1 = current_word_bbox line_words.append( { "text": current_word_text.strip(), "bounding_box": [ round(x0 + off_x, 2), round(y0 + off_y, 2), round(x1 + off_x, 2), round(y1 + off_y, 2), ], "conf": 100.0, } ) current_word_text = "" current_word_bbox = [float("inf"), float("inf"), -1, -1] for char in sorted_chars: char_text = clean_unicode_text( char["text"], preserve_international_scripts=True ) bbox = char["bbox"] x0, y0, x1, y1 = bbox char.get("size", 12.0) if char_text in _PUNCTUATION_TO_SPLIT: finalize_word() line_words.append( { "text": char_text, "bounding_box": [ round(x0 + off_x, 2), round(y0 + off_y, 2), round(x1 + off_x, 2), round(y1 + off_y, 2), ], "conf": 100.0, } ) prev_char = char continue if char_text.isspace(): finalize_word() prev_char = char continue if prev_char is not None: space_threshold = prev_char.get("size", 12.0) * 0.25 min_gap = 1.0 gap = x0 - prev_char["bbox"][2] if gap > max(space_threshold, min_gap): finalize_word() current_word_text += char_text if current_word_bbox[1] == -1 or current_word_bbox[3] == -1: current_word_bbox = [x0, y0, x1, y1] else: current_word_bbox[0] = min(current_word_bbox[0], x0) current_word_bbox[1] = min(current_word_bbox[1], y0) current_word_bbox[2] = max(current_word_bbox[2], x1) current_word_bbox[3] = max(current_word_bbox[3], y1) prev_char = char finalize_word() return line_words def process_page_to_structured_ocr_pymupdf( page: pymupdf.Page, page_number: int, start_line_number: int ) -> Tuple[Dict[str, Any], List[OCRResult], List[List[Dict]]]: # 1. Extract once (no page.get_text("words") needed; words built from chars) raw_dict = page.get_text("rawdict") # Coordinates from get_text() are in CropBox-local space (0,0 = CropBox top-left). # Compute the offset needed to convert to MediaBox-local space, which is what the # downstream coordinate division (divide_coordinates_by_page_sizes) and the # image_annotator display expect. When CropBox == MediaBox the offset is 0. off_x = ( page.cropbox.x0 - page.mediabox.x0 ) # = -page.mediabox.x0 (cropbox.x0 is always 0) off_y = page.cropbox.y0 - page.mediabox.y0 # = -page.mediabox.y0 page_data = {"page": str(page_number), "results": {}} line_results = [] lines_char_groups = [] valid_line_count = 0 for block in raw_dict["blocks"]: if "lines" not in block: continue for line in block["lines"]: # Join text and filter blanks line_text = "".join( ["".join([c["c"] for c in s["chars"]]) for s in line["spans"]] ) if not line_text.strip(): continue current_line_idx = start_line_number + valid_line_count lx0, ly0, lx1, ly1 = line["bbox"] # 2. Collect Character Objects in MediaBox-local space (same as lines/words). # Raw get_text("rawdict") char bboxes are CropBox-local; merge_text_bounding_boxes # uses these dicts — without the offset, merged redaction boxes stay CropBox-local # while convert_redaction_boxes_pymupdf_to_pdf assumes MediaBox-local coords. line_chars = [] for span in line["spans"]: for char in span["chars"]: cx0, cy0, cx1, cy1 = char["bbox"] line_chars.append( { "text": char["c"], "bbox": [ cx0 + off_x, cy0 + off_y, cx1 + off_x, cy1 + off_y, ], "size": span["size"], } ) # 3. Create OCRResult (Corrected math) line_obj = OCRResult( text=line_text.strip(), left=round(lx0 + off_x, 2), # Position + Offset top=round(ly0 + off_y, 2), # Position + Offset width=round(lx1 - lx0, 2), # Distance (No offset!) height=round(ly1 - ly0, 2), # Distance (No offset!) line=current_line_idx, conf=100.0, model="PyMuPDF", ) # 4. Build words from line chars with punctuation split into separate words # (char bboxes already include off_x/off_y) word_level_results = _words_from_line_chars_pymupdf(line_chars, 0.0, 0.0) # 5. Build final dictionary line_key = f"text_line_{current_line_idx}" page_data["results"][line_key] = { "line": current_line_idx, "text": line_text.strip(), "bounding_box": [ round(lx0 + off_x, 2), round(ly0 + off_y, 2), round(lx1 + off_x, 2), round(ly1 + off_y, 2), ], "words": word_level_results, "conf": 100.0, } line_results.append(line_obj) lines_char_groups.append(line_chars) valid_line_count += 1 if line_results: mediabox = page.mediabox line_results, lines_char_groups, page_data = reorder_structured_text_lines( line_results, lines_char_groups, page_data, page_width=float(mediabox.width), page_height=float(mediabox.height), start_line_number=start_line_number, ) return page_data, line_results, lines_char_groups def _extract_text_from_single_page_pymupdf(pdf_bytes: bytes, page_no: int) -> Tuple[ int, List[Any], # OCRResult objects List[List[Dict]], # Character groups per line pd.DataFrame, # Structured DataFrame List[Dict[str, Any]], # Page OCR results with words ]: """ Optimized version using PyMuPDF. Maintains the same return signature for parallel processing. """ reported_page_number = page_no + 1 # Initialize containers all_page_line_results = [] # List of OCRResult objects all_page_char_groups = [] # List of List of char dicts page_ocr_results_with_words = [] # List of page_data dicts # 1. Open the document inside the function for thread safety doc = pymupdf.open(stream=pdf_bytes, filetype="pdf") page = doc[page_no] # 2. Call our helper to get structured data # We pass 1 as the starting line number for this page page_data, line_results, char_groups = process_page_to_structured_ocr_pymupdf( page=page, page_number=reported_page_number, start_line_number=1 ) # 3. Handle the return objects to match your original structure all_page_line_results.extend(line_results) all_page_char_groups.extend(char_groups) # Your original code expected a list of these dicts (per container) # Since PyMuPDF processes the page as a whole, we wrap it in a list. page_ocr_results_with_words.append(page_data) # 4. Create the DataFrame if line_results: page_text_ocr_outputs = pd.DataFrame( [ { **line_level_ocr_row(reported_page_number, result), "text": result.text.strip(), "conf": getattr(result, "conf", 100.0), } for result in line_results ] ) else: page_text_ocr_outputs = pd.DataFrame(columns=LINE_LEVEL_OCR_DF_COLUMNS) doc.close() # Always close for memory efficiency return ( page_no, all_page_line_results, all_page_char_groups, page_text_ocr_outputs, page_ocr_results_with_words, ) def page_has_extractable_text( file_path: str, page_no: int, min_words: int = EFFICIENT_OCR_MIN_WORDS ) -> bool: """ Determine if a single PDF page has enough selectable text to use the text-only route (using pdfminer). Used by EFFICIENT_OCR to decide whether to use redact_text_pdf or redact_image_pdf for that page. Prefer get_pages_extractable_text_single_pass() when checking many pages: it opens the PDF once instead of once per page. Args: file_path: Path to the PDF file. page_no: 0-based page index. min_words: Minimum number of words required on the page to use text-only route; below this the page will use OCR. Defaults to EFFICIENT_OCR_MIN_WORDS. Returns: True if the page yields at least min_words of extractable text; False otherwise (page will use OCR). """ try: for _, has_text in get_pages_extractable_text_single_pass( file_path, [page_no], min_words ): return has_text return False except Exception: return False def get_pages_extractable_text_single_pass( file_path: str, page_numbers_0based: List[int], min_words: int = EFFICIENT_OCR_MIN_WORDS, ): """ Determine which pages have enough selectable text in a single PDF pass. Opens the file once and iterates over the given pages, avoiding N separate open/parse cycles. Use this instead of calling page_has_extractable_text in a loop or thread pool for the EFFICIENT_OCR initial check. Args: file_path: Path to the PDF file. page_numbers_0based: 0-based page indices to check. min_words: Minimum words required to use text-only route. Yields: (page_no, has_enough_text) for each page in order. """ if not page_numbers_0based: return try: # Single extract_pages call: one file open for all requested pages for page_no, page_layout in zip( page_numbers_0based, extract_pages( file_path, page_numbers=page_numbers_0based, maxpages=len(page_numbers_0based), ), ): word_count = 0 for text_container in page_layout: if not isinstance(text_container, LTTextContainer): continue characters = get_text_container_characters(text_container) if not characters: continue raw_text = "".join( c.get_text() for c in characters if hasattr(c, "get_text") ) if raw_text.strip(): word_count += len([w for w in raw_text.split() if w.strip()]) if word_count >= min_words: break yield (page_no, word_count >= min_words) except Exception: for p in page_numbers_0based: yield (p, False) def create_text_redaction_process_results( analyser_results, analysed_bounding_boxes, page_num ): decision_process_table = pd.DataFrame() if len(analyser_results) > 0 and len(analysed_bounding_boxes) > 0: # Create summary df of annotations to be made analysed_bounding_boxes_df_new = pd.DataFrame(analysed_bounding_boxes) # Support both camelCase (merge_text_bounding_boxes) and snake_case bbox_col = ( "boundingBox" if "boundingBox" in analysed_bounding_boxes_df_new.columns else "bounding_box" ) if bbox_col not in analysed_bounding_boxes_df_new.columns: return decision_process_table # Split the bounding box list into four separate columns analysed_bounding_boxes_df_new[["xmin", "ymin", "xmax", "ymax"]] = ( analysed_bounding_boxes_df_new[bbox_col].apply(pd.Series) ) # Convert the new columns to integers (if needed) # analysed_bounding_boxes_df_new.loc[:, ['xmin', 'ymin', 'xmax', 'ymax']] = (analysed_bounding_boxes_df_new[['xmin', 'ymin', 'xmax', 'ymax']].astype(float) / 5).round() * 5 analysed_bounding_boxes_df_text = ( analysed_bounding_boxes_df_new["result"] .astype(str) .str.split(",", expand=True) .replace(".*: ", "", regex=True) ) analysed_bounding_boxes_df_text.columns = ["label", "start", "end", "score"] analysed_bounding_boxes_df_new = pd.concat( [analysed_bounding_boxes_df_new, analysed_bounding_boxes_df_text], axis=1 ) analysed_bounding_boxes_df_new["page"] = page_num + 1 decision_process_table = pd.concat( [decision_process_table, analysed_bounding_boxes_df_new], axis=0 ).drop("result", axis=1) return decision_process_table def _build_one_pikepdf_redaction_annotation(analysed_bounding_box: dict): """Build a single pikepdf redaction annotation; safe to run in a thread.""" bounding_box = analysed_bounding_box["boundingBox"] return Dictionary( Type=Name.Annot, Subtype=Name.Square, QuadPoints=[ round(bounding_box[0], 2), round(bounding_box[3], 2), round(bounding_box[2], 2), round(bounding_box[3], 2), round(bounding_box[0], 2), round(bounding_box[1], 2), round(bounding_box[2], 2), round(bounding_box[1], 2), ], Rect=[ round(bounding_box[0], 2), round(bounding_box[1], 2), round(bounding_box[2], 2), round(bounding_box[3], 2), ], C=list(CUSTOM_BOX_COLOUR), IC=[0, 0, 0], CA=1, T=analysed_bounding_box["result"].entity_type, Contents=analysed_bounding_box["text"], BS=Dictionary(W=0, S=Name.S), ) def convert_redaction_boxes_pymupdf_to_pdf( analysed_bounding_boxes: List[dict], page_height: float ) -> List[dict]: """ Convert redaction box coordinates from PyMuPDF (top-left origin, y down) to PDF Rect convention (bottom-left origin, y up). Does not mutate inputs. """ if not analysed_bounding_boxes or page_height <= 0: return list(analysed_bounding_boxes) if analysed_bounding_boxes else [] out = [] for box in analysed_bounding_boxes: box = copy.deepcopy(box) bbox = box.get("boundingBox") or box.get("bounding_box") if not bbox or len(bbox) < 4: out.append(box) continue left, y0, right, y1 = bbox[0], bbox[1], bbox[2], bbox[3] # PyMuPDF: y0 = top (smaller), y1 = bottom (larger). PDF: bottom < top (y up). pdf_y_bottom = page_height - y1 pdf_y_top = page_height - y0 box["boundingBox"] = [left, pdf_y_bottom, right, pdf_y_top] if "bounding_box" in box: box["bounding_box"] = box["boundingBox"] out.append(box) return out def _run_image_pii_for_one_page( page_no: int, page_data: dict, image_analyser, chosen_redact_comprehend_entities: List[str], chosen_llm_entities: List[str], pii_identification_method: str, comprehend_client, bedrock_runtime, chosen_redact_entities: List[str], language: str, allow_list: List[str], score_threshold: float, nlp_analyser, custom_llm_instructions: str, file_name: str, text_analyzer_kwargs: dict, ) -> Tuple[int, List, int, str, int, int]: """ Run image_analyser.analyze_text for a single page (used for parallel Local/AWS Comprehend in redact_image_pdf). Returns (page_no, page_redaction_bounding_boxes, comprehend_query_number_new, llm_model_name, llm_input_tokens, llm_output_tokens). """ page_line_level_ocr_results = page_data.get("page_line_level_ocr_results") page_line_level_ocr_results_with_words = page_data.get( "page_line_level_ocr_results_with_words" ) reported_page_number = page_data.get("reported_page_number", str(page_no + 1)) if ( not page_line_level_ocr_results or not isinstance(page_line_level_ocr_results, dict) or "results" not in page_line_level_ocr_results ): return (page_no, list(), 0, "", 0, 0) if not page_line_level_ocr_results_with_words: return (page_no, list(), 0, "", 0, 0) if isinstance(page_line_level_ocr_results_with_words, list): if not page_line_level_ocr_results_with_words: return (page_no, list(), 0, "", 0, 0) ocr_with_words = page_line_level_ocr_results_with_words[0] else: ocr_with_words = page_line_level_ocr_results_with_words if not isinstance(ocr_with_words, dict) or "results" not in ocr_with_words: return (page_no, list(), 0, "", 0, 0) ( page_redaction_bounding_boxes, comprehend_query_number_new, llm_model_name_page, llm_input_tokens_page, llm_output_tokens_page, ) = image_analyser.analyze_text( page_line_level_ocr_results["results"], ocr_with_words["results"], chosen_redact_comprehend_entities=chosen_redact_comprehend_entities, chosen_llm_entities=chosen_llm_entities, pii_identification_method=pii_identification_method, comprehend_client=comprehend_client, bedrock_runtime=bedrock_runtime, custom_entities=chosen_redact_entities, language=language, allow_list=allow_list, score_threshold=score_threshold, nlp_analyser=nlp_analyser, custom_llm_instructions=custom_llm_instructions, file_name=file_name, page_number=int(reported_page_number), **text_analyzer_kwargs, ) return ( page_no, page_redaction_bounding_boxes, comprehend_query_number_new, llm_model_name_page, llm_input_tokens_page, llm_output_tokens_page, ) def _run_pii_for_one_page( extraction_result: Tuple, language: str, chosen_redact_entities: List[str], chosen_redact_comprehend_entities: List[str], allow_list: List[str], pii_identification_method: str, nlp_analyser, score_threshold: float, custom_entities: List[str], comprehend_client, comprehend_query_number: int, bedrock_runtime, model_choice: str, custom_llm_instructions: str, chosen_llm_entities: List[str], output_folder: str, file_name: str, ) -> Tuple[int, List, int, str, int, int]: """ Run PII identification for a single page (used for parallel Local/AWS Comprehend). Returns (page_no, page_redaction_bounding_boxes, comprehend_units_used, llm_model_name, llm_input_tokens, llm_output_tokens). """ ( page_no, line_level_text_results_list, line_characters, _page_text_ocr_outputs, _page_ocr_results_with_words, ) = extraction_result reported_page_number = page_no + 1 page_analyser_results = list() page_redaction_bounding_boxes = list() ( page_redaction_bounding_boxes, comprehend_units_used, llm_model_name_page, llm_input_tokens_page, llm_output_tokens_page, ) = run_page_text_redaction( language, chosen_redact_entities, chosen_redact_comprehend_entities, line_level_text_results_list, line_characters, page_analyser_results, page_redaction_bounding_boxes, comprehend_client, allow_list, pii_identification_method, nlp_analyser, score_threshold, custom_entities, comprehend_query_number, bedrock_runtime=bedrock_runtime, model_choice=model_choice, custom_llm_instructions=custom_llm_instructions, chosen_llm_entities=chosen_llm_entities, output_folder=output_folder, file_name=file_name, page_number=reported_page_number, ) return ( page_no, page_redaction_bounding_boxes, comprehend_units_used, llm_model_name_page, llm_input_tokens_page, llm_output_tokens_page, ) def create_pikepdf_annotations_for_bounding_boxes(analysed_bounding_boxes): if not analysed_bounding_boxes: return [] n = len(analysed_bounding_boxes) max_workers = min(MAX_WORKERS, n) with ThreadPoolExecutor(max_workers=max_workers) as executor: pikepdf_redaction_annotations_on_page = list( executor.map( _build_one_pikepdf_redaction_annotation, analysed_bounding_boxes ) ) return pikepdf_redaction_annotations_on_page def redact_text_pdf( file_path: str, # Path to the PDF file to be redacted language: str, # Language of the PDF content chosen_redact_entities: List[str], # List of entities to be redacted chosen_redact_comprehend_entities: List[str], allow_list: List[str] = None, # Optional list of allowed entities page_min: int = 0, # Minimum page number to start redaction page_max: int = 0, # Maximum page number to end redaction current_loop_page: int = 0, # Current page being processed in the loop page_break_return: bool = False, # Flag to indicate if a page break should be returned annotations_all_pages: List[dict] = list(), # List of annotations across all pages all_line_level_ocr_results_df: pd.DataFrame = pd.DataFrame( columns=LINE_LEVEL_OCR_DF_COLUMNS ), # DataFrame for OCR results all_pages_decision_process_table: pd.DataFrame = pd.DataFrame( columns=[ "image_path", "page", "label", "xmin", "xmax", "ymin", "ymax", "text", "id", ] ), # DataFrame for decision process table pymupdf_doc: List = list(), # List of PyMuPDF documents all_page_line_level_ocr_results_with_words: List = list(), pii_identification_method: str = "Local", comprehend_query_number: int = 0, comprehend_client="", in_deny_list: List[str] = list(), redact_whole_page_list: List[str] = list(), max_fuzzy_spelling_mistakes_num: int = 1, match_fuzzy_whole_phrase_bool: bool = True, page_sizes_df: pd.DataFrame = pd.DataFrame(), original_cropboxes: List[dict] = list(), text_extraction_only: bool = False, output_folder: str = OUTPUT_FOLDER, input_folder: str = INPUT_FOLDER, page_break_val: int = int(PAGE_BREAK_VALUE), # Value for page break max_time: int = int(MAX_TIME_VALUE), nlp_analyser: AnalyzerEngine = nlp_analyser, progress: Progress = Progress(track_tqdm=True), # Progress tracking object bedrock_runtime=None, model_choice: str = CLOUD_LLM_PII_MODEL_CHOICE, custom_llm_instructions: str = "", chosen_llm_entities: List[str] = None, efficient_ocr: bool = EFFICIENT_OCR, pages_to_process: Optional[List[int]] = None, efficient_ocr_extraction_pass: bool = False, pre_extracted_results: Optional[List[Tuple]] = None, ): # Initialize LLM token tracking variables llm_total_input_tokens = 0 llm_total_output_tokens = 0 llm_model_name = "" """ Redact chosen entities from a PDF that is made up of multiple pages that are not images. Input Variables: - file_path: Path to the PDF file to be redacted - language: Language of the PDF content - chosen_redact_entities: List of entities to be redacted - chosen_redact_comprehend_entities: List of entities to be redacted for AWS Comprehend - allow_list: Optional list of allowed entities - page_min: Minimum page number to start redaction - page_max: Maximum page number to end redaction - text_extraction_method: Type of analysis to perform - current_loop_page: Current page being processed in the loop - page_break_return: Flag to indicate if a page break should be returned - annotations_all_pages: List of annotations across all pages - all_line_level_ocr_results_df: DataFrame for OCR results - all_pages_decision_process_table: DataFrame for decision process table - pymupdf_doc: List of PyMuPDF documents - pii_identification_method (str, optional): The method to redact personal information. Either 'Local' (spacy model), or 'AWS Comprehend' (AWS Comprehend API). - comprehend_query_number (int, optional): A counter tracking the number of queries to AWS Comprehend. - comprehend_client (optional): A connection to the AWS Comprehend service via the boto3 package. - in_deny_list (optional, List[str]): A list of custom words that the user has chosen specifically to redact. - redact_whole_page_list (optional, List[str]): A list of pages to fully redact. - max_fuzzy_spelling_mistakes_num (int, optional): The maximum number of spelling mistakes allowed in a searched phrase for fuzzy matching. Can range from 0-9. - match_fuzzy_whole_phrase_bool (bool, optional): A boolean where 'True' means that the whole phrase is fuzzy matched, and 'False' means that each word is fuzzy matched separately (excluding stop words). - page_sizes_df (pd.DataFrame, optional): A pandas dataframe of PDF page sizes in PDF or image format. - original_cropboxes (List[dict], optional): A list of dictionaries containing pymupdf cropbox information. - text_extraction_only (bool, optional): Should the function only extract text, or also do redaction. - language (str, optional): The language to do AWS Comprehend calls. Defaults to value of language if not provided. - output_folder (str, optional): The output folder for the function - input_folder (str, optional): The folder for file inputs. - page_break_val: Value for page break - max_time (int, optional): The maximum amount of time (s) that the function should be running before it breaks. To avoid timeout errors with some APIs. - nlp_analyser (AnalyzerEngine, optional): The nlp_analyser object to use for entity detection. Defaults to nlp_analyser. - efficient_ocr (bool, optional): Whether to use efficient OCR. Defaults to EFFICIENT_OCR. - progress: Progress tracking object """ tic = time.perf_counter() if isinstance(all_line_level_ocr_results_df, pd.DataFrame): all_line_level_ocr_results_list = [all_line_level_ocr_results_df] if isinstance(all_pages_decision_process_table, pd.DataFrame): # Convert decision outputs to list of dataframes: all_pages_decision_process_list = [all_pages_decision_process_table] if pii_identification_method == "AWS Comprehend" and comprehend_client == "": out_message = "Connection to AWS Comprehend service not found." raise Exception(out_message) # Try updating the supported languages for the spacy analyser try: nlp_analyser = create_nlp_analyser(language, existing_nlp_analyser=nlp_analyser) # Check list of nlp_analyser recognisers and languages if language != "en": gr.Info( f"Language: {language} only supports the following entity detection: {str(nlp_analyser.registry.get_supported_entities(languages=[language]))}" ) except Exception as e: print(f"Error creating nlp_analyser for {language}: {e}") raise Exception(f"Error creating nlp_analyser for {language}: {e}") # Update custom word list analyser object with any new words that have been added to the custom deny list if in_deny_list: nlp_analyser.registry.remove_recognizer("CUSTOM") new_custom_recogniser = custom_word_list_recogniser(in_deny_list) nlp_analyser.registry.add_recognizer(new_custom_recogniser) nlp_analyser.registry.remove_recognizer("CustomWordFuzzyRecognizer") new_custom_fuzzy_recogniser = CustomWordFuzzyRecognizer( supported_entities=["CUSTOM_FUZZY"], custom_list=in_deny_list, spelling_mistakes_max=max_fuzzy_spelling_mistakes_num, search_whole_phrase=match_fuzzy_whole_phrase_bool, ) nlp_analyser.registry.add_recognizer(new_custom_fuzzy_recogniser) # Open with Pikepdf to get text lines pikepdf_pdf = Pdf.open(file_path) number_of_pages = len(pikepdf_pdf.pages) file_name = get_file_name_without_type(file_path) if not all_page_line_level_ocr_results_with_words: all_page_line_level_ocr_results_with_words = list() # Check that page_min and page_max are within expected ranges if page_max > number_of_pages or page_max == 0: page_max = number_of_pages if page_min <= 0: page_min = 0 else: page_min = page_min - 1 ### if current_loop_page == 0: page_loop_start = page_min else: page_loop_start = current_loop_page page_loop_end = page_max # When pages_to_process is provided (e.g. from efficient_ocr), iterate only over those pages (1-based list). if pages_to_process is not None: page_loop_pages = sorted([p - 1 for p in pages_to_process]) # 0-indexed, sorted else: page_loop_pages = None print("Page range: ", str(page_loop_start + 1), "to", str(page_loop_end)) # First pass: parallel text extraction (read-only per page, thread-safe). # When pre_extracted_results is provided (e.g. EFFICIENT_OCR second pass), reuse them. if page_loop_pages is not None: pages_to_iterate = list(page_loop_pages) else: pages_to_iterate = list(range(page_loop_start, page_loop_end)) if pre_extracted_results is not None and pages_to_process is not None: pages_set = set(p - 1 for p in pages_to_process) extraction_results = [r for r in pre_extracted_results if r[0] in pages_set] extraction_results.sort(key=lambda r: r[0]) else: max_workers = min(MAX_WORKERS, len(pages_to_iterate)) with open(file_path, "rb") as f: pdf_buffer = f.read() with ThreadPoolExecutor(max_workers=max_workers) as executor: extraction_results = list( tqdm( executor.map( lambda p: _extract_text_from_single_page_pymupdf(pdf_buffer, p), pages_to_iterate, ), total=len(pages_to_iterate), unit="pages", desc="Extracting text (simple text extraction)", ) ) extraction_results.sort(key=lambda r: r[0]) # Optional: run PII detection in parallel for Local and AWS Comprehend (bounded by MAX_WORKERS). # IMPORTANT: never parallelize PII when using inference-server or local-transformers LLM backends. pii_results_by_page = {} if ( pii_identification_method in (LOCAL_PII_OPTION, AWS_PII_OPTION) and pii_identification_method not in (INFERENCE_SERVER_PII_OPTION, LOCAL_TRANSFORMERS_LLM_PII_OPTION) and not text_extraction_only and (chosen_redact_entities or chosen_redact_comprehend_entities) and extraction_results ): num_pages = len(extraction_results) max_workers = min(MAX_WORKERS, num_pages) progress( 0.45, desc=f"Detecting PII in parallel ({pii_identification_method}, {num_pages} pages)", ) with ThreadPoolExecutor(max_workers=max_workers) as executor: pii_results_list = list( tqdm( executor.map( lambda ext: _run_pii_for_one_page( ext, language, chosen_redact_entities, chosen_redact_comprehend_entities, allow_list, pii_identification_method, nlp_analyser, score_threshold, custom_entities, comprehend_client, comprehend_query_number, bedrock_runtime, model_choice, custom_llm_instructions, chosen_llm_entities, output_folder, file_name, ), extraction_results, ), total=num_pages, unit="pages", desc="Detecting PII (parallel)", ) ) _comprehend_units_parallel = 0 for ( page_no, page_redaction_bounding_boxes, comprehend_units_used, llm_name, llm_in, llm_out, ) in pii_results_list: pii_results_by_page[page_no] = ( page_redaction_bounding_boxes, comprehend_units_used, llm_name, llm_in, llm_out, ) try: _comprehend_units_parallel += int(comprehend_units_used or 0) except Exception: pass # Accumulate Comprehend usage across parallel pages (billing units). comprehend_query_number += int(_comprehend_units_parallel or 0) # Precompute per-page lookups so the loop does O(1) access instead of repeated DataFrame .loc # (Same approach as redaction_review: pass image_dimensions_override to skip per-call .loc in redact_page_with_pymupdf.) image_path_by_page = {} page_to_image_dimensions = {} if not page_sizes_df.empty and "page" in page_sizes_df.columns: if "image_path" in page_sizes_df.columns: for _page_one_based, _row in page_sizes_df.set_index("page")[ "image_path" ].items(): try: image_path_by_page[int(_page_one_based)] = _row except (TypeError, ValueError): pass if ( "image_width" in page_sizes_df.columns and "image_height" in page_sizes_df.columns ): sub = page_sizes_df[ ["page", "image_width", "image_height"] ].drop_duplicates("page") for _, row in sub.iterrows(): p = row["page"] if pd.notna(p): w, h = row["image_width"], row["image_height"] if pd.notna(w) and pd.notna(h): try: page_to_image_dimensions[int(p)] = { "image_width": float(w), "image_height": float(h), } except (TypeError, ValueError): pass redact_whole_page_set = set() if redact_whole_page_list: for _p in redact_whole_page_list: try: redact_whole_page_set.add(int(_p)) except (TypeError, ValueError): redact_whole_page_set.add(_p) progress_bar_redact = tqdm( extraction_results, unit="pages", desc=( "Applying redactions to pages" if pii_results_by_page else ( "Extracting text (efficient OCR word-count pass)" if text_extraction_only else "Detecting PII (following simple text extraction)" ) ), ) for extraction_result in progress_bar_redact: ( page_no, all_page_line_level_text_extraction_results_list, all_page_line_text_extraction_characters, page_text_ocr_outputs, page_ocr_results_with_words, ) = extraction_result reported_page_number = str(page_no + 1) # Create annotations for every page, even if blank. # Image path: use precomputed lookup to avoid O(n) .loc per page image_path = image_path_by_page.get(int(reported_page_number), "") if image_path == "" or (isinstance(image_path, float) and pd.isna(image_path)): image_path = "" # EFFICIENT_OCR: use placeholder for text-only pages so annotations match page_sizes # and we don't create real images (placeholders have mediabox for coordinate division). if pages_to_process and ( not image_path or "placeholder_image" in str(image_path) or "image_placeholder" in str(image_path) ): image_path = f"placeholder_image_{page_no}.png" page_image_annotations = {"image": image_path, "boxes": []} # image pymupdf_page = pymupdf_doc.load_page(page_no) pymupdf_page.set_cropbox(pymupdf_page.mediabox) # Set CropBox to MediaBox page_analyser_results = list() page_redaction_bounding_boxes = list() page_decision_process_table = pd.DataFrame( columns=[ "image_path", "page", "label", "xmin", "xmax", "ymin", "ymax", "text", "id", ] ) pikepdf_redaction_annotations_on_page = list() all_page_line_level_ocr_results_with_words.extend(page_ocr_results_with_words) ### REDACTION if ( not text_extraction_only and pii_identification_method != NO_REDACTION_PII_OPTION ): if chosen_redact_entities or chosen_redact_comprehend_entities: if page_no in pii_results_by_page: ( page_redaction_bounding_boxes, comprehend_units_used, llm_model_name_page, llm_input_tokens_page, llm_output_tokens_page, ) = pii_results_by_page[page_no] else: ( page_redaction_bounding_boxes, comprehend_units_used, llm_model_name_page, llm_input_tokens_page, llm_output_tokens_page, ) = run_page_text_redaction( language, chosen_redact_entities, chosen_redact_comprehend_entities, all_page_line_level_text_extraction_results_list, all_page_line_text_extraction_characters, page_analyser_results, page_redaction_bounding_boxes, comprehend_client, allow_list, pii_identification_method, nlp_analyser, score_threshold, custom_entities, comprehend_query_number, bedrock_runtime=bedrock_runtime, model_choice=model_choice, custom_llm_instructions=custom_llm_instructions, chosen_llm_entities=chosen_llm_entities, output_folder=output_folder, file_name=file_name, page_number=int(reported_page_number), ) comprehend_query_number += int(comprehend_units_used or 0) if ( not page_redaction_bounding_boxes and pii_identification_method == AWS_PII_OPTION and (chosen_redact_comprehend_entities or chosen_redact_entities) ): # print( # f"EFFICIENT_OCR (text path): No PII bounding boxes for page {reported_page_number}. " # "Check that the page has text and that selected entity types match Comprehend output." # ) pass # Accumulate LLM token usage across pages llm_total_input_tokens += llm_input_tokens_page llm_total_output_tokens += llm_output_tokens_page if llm_model_name_page and not llm_model_name: llm_model_name = llm_model_name_page # Annotate redactions on page (convert PyMuPDF top-left coords to PDF bottom-left for Rect) page_height = pymupdf_page.mediabox.height boxes_for_pdf = convert_redaction_boxes_pymupdf_to_pdf( page_redaction_bounding_boxes, page_height ) pikepdf_redaction_annotations_on_page = ( create_pikepdf_annotations_for_bounding_boxes(boxes_for_pdf) ) else: pikepdf_redaction_annotations_on_page = list() # Make pymupdf page redactions (use set for O(1) membership) int_reported_page_number = int(reported_page_number) redact_whole_page = ( int_reported_page_number in redact_whole_page_set if redact_whole_page_set else False ) # page.cropbox is always reported by PyMuPDF in MediaBox-local coordinates, # so the stored original_cropbox is already in the correct coordinate system # for set_cropbox_safely after set_cropbox(mediabox) has been applied. # No offset transformation is needed here. _orig_cb = original_cropboxes[page_no] redact_result = redact_page_with_pymupdf( pymupdf_page, pikepdf_redaction_annotations_on_page, image_path, redact_whole_page=redact_whole_page, convert_pikepdf_to_pymupdf_coords=True, original_cropbox=_orig_cb, page_sizes_df=page_sizes_df, input_folder=input_folder, image_dimensions_override=page_to_image_dimensions.get( int(reported_page_number) ), ) # Handle dual page objects if returned if isinstance(redact_result[0], tuple): ( pymupdf_page, pymupdf_applied_redaction_page, ), page_image_annotations = redact_result # Store the final page with its original page number for later use if not hasattr(redact_text_pdf, "_applied_redaction_pages"): redact_text_pdf._applied_redaction_pages = list() redact_text_pdf._applied_redaction_pages.append( (pymupdf_applied_redaction_page, page_no) ) else: pymupdf_page, page_image_annotations = redact_result # When dual output is requested but this page had no redaction boxes, # we still need an "applied" page entry so the final PDF replace loop # replaces every page (same fix as in redact_image_pdf). if RETURN_PDF_FOR_REVIEW and RETURN_REDACTED_PDF: if not hasattr(redact_text_pdf, "_applied_redaction_pages"): redact_text_pdf._applied_redaction_pages = list() applied_doc = pymupdf.open() applied_doc.insert_pdf( pymupdf_page.parent, from_page=page_no, to_page=page_no, ) applied_page_copy = applied_doc[0] redact_text_pdf._applied_redaction_pages.append( (applied_page_copy, page_no) ) # Create decision process table page_decision_process_table = create_text_redaction_process_results( page_analyser_results, page_redaction_bounding_boxes, current_loop_page, ) if not page_decision_process_table.empty: all_pages_decision_process_list.append(page_decision_process_table) # Join extracted text outputs for all lines together if not page_text_ocr_outputs.empty: page_text_ocr_outputs = normalize_line_level_ocr_df( page_text_ocr_outputs.sort_values(["line"]).reset_index(drop=True) ) all_line_level_ocr_results_list.append(page_text_ocr_outputs) toc = time.perf_counter() time_taken = toc - tic # Break if time taken is greater than max_time seconds if time_taken > max_time: print("Processing for", max_time, "seconds, breaking.") page_break_return = True progress.close(_tqdm=progress_bar_redact) tqdm._instances.clear() # Check if the image already exists in annotations_all_pages existing_index = next( ( index for index, ann in enumerate(annotations_all_pages) if ann["image"] == page_image_annotations["image"] ), None, ) if existing_index is not None: # Replace the existing annotation annotations_all_pages[existing_index] = page_image_annotations else: # Append new annotation if it doesn't exist annotations_all_pages.append(page_image_annotations) # Write logs # Filter out empty DataFrames before concatenation to avoid FutureWarning non_empty_decision_process = [ df for df in all_pages_decision_process_list if not df.empty ] if non_empty_decision_process: all_pages_decision_process_table = pd.concat( non_empty_decision_process, ignore_index=True ) else: all_pages_decision_process_table = pd.DataFrame( columns=[ "text", "xmin", "ymin", "xmax", "ymax", "label", "start", "end", "score", "page", "id", ] ) non_empty_ocr_results = [ df for df in all_line_level_ocr_results_list if not df.empty ] if non_empty_ocr_results: all_line_level_ocr_results_df = normalize_line_level_ocr_df( pd.concat(non_empty_ocr_results, ignore_index=True) ) else: all_line_level_ocr_results_df = pd.DataFrame( columns=LINE_LEVEL_OCR_DF_COLUMNS ) current_loop_page += 1 early_result = ( pymupdf_doc, all_pages_decision_process_table, all_line_level_ocr_results_df, annotations_all_pages, current_loop_page, page_break_return, comprehend_query_number, all_page_line_level_ocr_results_with_words, ) if efficient_ocr_extraction_pass: return early_result + ( llm_model_name, llm_total_input_tokens, llm_total_output_tokens, extraction_results, ) return early_result # Check if the image already exists in annotations_all_pages existing_index = next( ( index for index, ann in enumerate(annotations_all_pages) if ann["image"] == page_image_annotations["image"] ), None, ) if existing_index is not None: # Replace the existing annotation annotations_all_pages[existing_index] = page_image_annotations else: # Append new annotation if it doesn't exist annotations_all_pages.append(page_image_annotations) current_loop_page += 1 # Break if new page is a multiple of page_break_val if current_loop_page % page_break_val == 0: page_break_return = True progress.close(_tqdm=progress_bar_redact) # Write logs # Filter out empty DataFrames before concatenation to avoid FutureWarning non_empty_decision_process = [ df for df in all_pages_decision_process_list if not df.empty ] if non_empty_decision_process: all_pages_decision_process_table = pd.concat( non_empty_decision_process, ignore_index=True ) else: all_pages_decision_process_table = pd.DataFrame( columns=[ "text", "xmin", "ymin", "xmax", "ymax", "label", "start", "end", "score", "page", "id", ] ) page_break_result = ( pymupdf_doc, all_pages_decision_process_table, all_line_level_ocr_results_df, annotations_all_pages, current_loop_page, page_break_return, comprehend_query_number, all_page_line_level_ocr_results_with_words, ) if efficient_ocr_extraction_pass: return page_break_result + ( llm_model_name, llm_total_input_tokens, llm_total_output_tokens, extraction_results, ) return page_break_result # Write all page outputs # Filter out empty DataFrames before concatenation to avoid FutureWarning non_empty_decision_process = [ df for df in all_pages_decision_process_list if not df.empty ] if non_empty_decision_process: all_pages_decision_process_table = pd.concat( non_empty_decision_process, ignore_index=True ) else: all_pages_decision_process_table = pd.DataFrame( columns=[ "text", "xmin", "ymin", "xmax", "ymax", "label", "start", "end", "score", "page", "id", ] ) non_empty_ocr_results = [ df for df in all_line_level_ocr_results_list if not df.empty ] if non_empty_ocr_results: all_line_level_ocr_results_df = normalize_line_level_ocr_df( pd.concat(non_empty_ocr_results, ignore_index=True) ) else: all_line_level_ocr_results_df = pd.DataFrame(columns=LINE_LEVEL_OCR_DF_COLUMNS) if not all_pages_decision_process_table.empty: # Convert decision table to relative coordinates all_pages_decision_process_table = divide_coordinates_by_page_sizes( all_pages_decision_process_table, page_sizes_df, xmin="xmin", xmax="xmax", ymin="ymin", ymax="ymax", ) # Convert decision table to relative coordinates if not all_line_level_ocr_results_df.empty: all_line_level_ocr_results_df = divide_coordinates_by_page_sizes( all_line_level_ocr_results_df, page_sizes_df, xmin="left", xmax="width", ymin="top", ymax="height", coordinates_in_pdf_points=True, ) # Remove empty dictionary items from ocr results with words all_page_line_level_ocr_results_with_words = [ d for d in all_page_line_level_ocr_results_with_words if d ] result = ( pymupdf_doc, all_pages_decision_process_table, all_line_level_ocr_results_df, annotations_all_pages, current_loop_page, page_break_return, comprehend_query_number, all_page_line_level_ocr_results_with_words, llm_model_name, llm_total_input_tokens, llm_total_output_tokens, ) if efficient_ocr_extraction_pass: return result + (extraction_results,) return result def _pil_ocr_viz_text_size(font: ImageFont.ImageFont, text: str) -> Tuple[int, int]: if not text: text = " " if hasattr(font, "getbbox"): left, top, right, bottom = font.getbbox(text) return max(1, right - left), max(1, bottom - top) dr = ImageDraw.Draw(Image.new("RGB", (1, 1))) bb = dr.textbbox((0, 0), text, font=font) return max(1, bb[2] - bb[0]), max(1, bb[3] - bb[1]) def _pil_ocr_viz_text_bbox( font: ImageFont.ImageFont, text: str ) -> Tuple[int, int, int, int]: if not text: text = " " if hasattr(font, "getbbox"): return font.getbbox(text) dr = ImageDraw.Draw(Image.new("RGB", (1, 1))) return dr.textbbox((0, 0), text, font=font) def _pil_ocr_viz_load_font(font_path: Optional[str], size: int) -> ImageFont.ImageFont: if font_path and os.path.isfile(font_path): try: return ImageFont.truetype(font_path, size) except OSError: pass return ImageFont.load_default() def _ocr_viz_bgr_to_rgb(bgr: Tuple[int, int, int]) -> Tuple[int, int, int]: return (int(bgr[2]), int(bgr[1]), int(bgr[0])) def _ocr_viz_is_punctuation_only_token(text: str) -> bool: s = text.strip() if not s: return False return not any(ch.isalpha() or ch.isdigit() for ch in s) def _ocr_viz_punctuation_only_vertical_fraction(text: str) -> float: """ Vertical position within the OCR word box (0 = top, 1 = bottom of box). Dash-like and symmetric separators are centred; comma / full stop class sit lower. """ compact = "".join(ch for ch in text if not ch.isspace()) if not compact: return 0.5 middle_chars = frozenset("-‐−–—‾_·∙•‧;:|/\\+=*()[]{}\"'«»“”‘’") if all(c in middle_chars for c in compact): return 0.5 return 2.0 / 3.0 def _ocr_viz_overlay_vertical_ref_y( y1: int, y2: int, text: str, line_y_c: float ) -> float: if y2 <= y1: return float(line_y_c) if not _ocr_viz_is_punctuation_only_token(text): return float(line_y_c) frac = _ocr_viz_punctuation_only_vertical_fraction(text) return float(y1) + (y2 - y1) * frac def _ocr_viz_draw_position_from_left_edge( text: str, font: ImageFont.ImageFont, left_edge_x: float, ref_y: float, img_width: int, img_height: int, box_y1: Optional[int] = None, box_y2: Optional[int] = None, ) -> Tuple[int, int]: """Return top-left draw coordinates that place the ink bbox at the requested position. If box_y1/box_y2 are provided the rendered ink is also clamped so it never escapes the word's own OCR bounding box vertically. """ try: left, top, right, bottom = _pil_ocr_viz_text_bbox(font, text) except (TypeError, ValueError, OSError): return int(left_edge_x), int(ref_y) draw_x = int(round(left_edge_x - left)) draw_y = int(round(ref_y - (top + bottom) / 2.0)) # Clamp vertically to the word's own OCR box so text never escapes it. if box_y1 is not None and box_y2 is not None: # Ideal: ink top ≥ box_y1 and ink bottom ≤ box_y2. min_draw_y = box_y1 - top # ink top lands on box_y1 max_draw_y = box_y2 - bottom # ink bottom lands on box_y2 if min_draw_y <= max_draw_y: draw_y = max(min_draw_y, min(max_draw_y, draw_y)) else: # Ink is taller than the box - centre it (should be rare after height cap). draw_y = int(round((box_y1 + box_y2) / 2.0 - (top + bottom) / 2.0)) # Finally clamp to image canvas. if draw_x + left < 0: draw_x -= draw_x + left if draw_x + right > img_width: draw_x -= draw_x + right - img_width if draw_y + top < 0: draw_y -= draw_y + top if draw_y + bottom > img_height: draw_y -= draw_y + bottom - img_height return draw_x, draw_y def _is_placeholder_image_path(image_path: object) -> bool: return isinstance(image_path, str) and ( "placeholder_image" in image_path or "image_placeholder" in image_path ) def _page_num_from_placeholder_path(image_path: str, default_page_no: int) -> int: try: return int(image_path.split("_")[-1].split(".")[0]) except Exception: return default_page_no def open_page_image_for_pipeline( image_path: str, file_path: str, page_no: int, *, input_folder: str = INPUT_FOLDER, page_sizes_df: Optional[pd.DataFrame] = None, image_dpi: float = IMAGES_DPI, ) -> Tuple[Optional[Image.Image], str]: """ Open a page raster for OCR / visualization, materialising PNGs when only a placeholder path exists (e.g. cached Textract with prepare_images_flag=False). """ resolved_path = image_path if isinstance(image_path, str) else "" if _is_placeholder_image_path(resolved_path) or not resolved_path: page_num = ( _page_num_from_placeholder_path(resolved_path, page_no) if _is_placeholder_image_path(resolved_path) else page_no ) try: _, created_path, _, _ = process_single_page_for_image_conversion( pdf_path=file_path, page_num=page_num, image_dpi=image_dpi, create_images=True, input_folder=input_folder, ) if created_path and os.path.exists(created_path): resolved_path = created_path if page_sizes_df is not None and not page_sizes_df.empty: page_sizes_df.loc[ page_sizes_df["page"] == (page_no + 1), "image_path", ] = created_path except Exception: pass if not resolved_path or _is_placeholder_image_path(resolved_path): return None, resolved_path try: normalized_path = os.path.normpath(os.path.abspath(resolved_path)) if validate_path_containment(normalized_path, input_folder) or os.path.isfile( normalized_path ): return Image.open(normalized_path), normalized_path except Exception: pass return None, resolved_path def resolve_image_for_ocr_visualization( image: Optional[Image.Image], image_path: str, file_path: str, page_no: int, *, input_folder: str = INPUT_FOLDER, page_sizes_df: Optional[pd.DataFrame] = None, ) -> Optional[Union[str, Image.Image]]: """Return a PIL image or on-disk path suitable for OCR bbox visualization.""" if image is not None: return image pil_image, resolved_path = open_page_image_for_pipeline( image_path, file_path, page_no, input_folder=input_folder, page_sizes_df=page_sizes_df, ) if pil_image is not None: return pil_image if resolved_path and not _is_placeholder_image_path(resolved_path): return resolved_path if is_pdf(file_path) is False and isinstance(file_path, str) and file_path: return file_path return None def visualise_ocr_words_bounding_boxes( image: Union[str, Image.Image], ocr_results: Dict[str, Any], image_name: str = None, page_number: Optional[int] = None, output_folder: str = OUTPUT_FOLDER, text_extraction_method: str = None, visualisation_folder: str = None, add_legend: bool = True, chosen_local_ocr_model: str = None, log_files_output_paths: List[str] = list(), textract_hybrid_bedrock_used: bool = False, file_path: Optional[str] = None, page_no: Optional[int] = None, input_folder: str = INPUT_FOLDER, page_sizes_df: Optional[pd.DataFrame] = None, ) -> None: """ Visualizes OCR bounding boxes with confidence-based colors and a legend. Handles word-level OCR results from Textract and Tesseract. Args: image: The PIL Image object or image path ocr_results: Dictionary containing word-level OCR results image_name: Optional name for the saved image file output_folder: Output folder path text_extraction_method: The text extraction method being used (determines folder name) visualisation_folder: Subfolder name for visualizations (auto-determined if not provided) add_legend: Whether to add a legend to the visualization log_files_output_paths: List of file paths used for saving redaction process logging results. textract_hybrid_bedrock_used: When True and Textract is the method, use hybrid Textract+Bedrock folder and label for the saved visualization. """ # Determine visualization folder based on text extraction method # Initialize base_model_name with a default value base_model_name = "OCR" # Default fallback value if visualisation_folder is None: if ( text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION and textract_hybrid_bedrock_used ): base_model_name = "Textract + Bedrock VLM (hybrid)" visualisation_folder = "hybrid_textract_bedrock_visualisations" elif text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: base_model_name = "Textract" visualisation_folder = "textract_visualisations" elif ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and chosen_local_ocr_model == "tesseract" ): base_model_name = "Tesseract" visualisation_folder = "tesseract_visualisations" elif ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and chosen_local_ocr_model == "hybrid-paddle" ): base_model_name = "Tesseract" visualisation_folder = "hybrid_paddle_visualisations" elif ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and chosen_local_ocr_model == "paddle" ): base_model_name = "Paddle" visualisation_folder = "paddle_visualisations" elif ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and chosen_local_ocr_model == "hybrid-vlm" ): base_model_name = "Tesseract" visualisation_folder = "hybrid_vlm_visualisations" elif ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and chosen_local_ocr_model == "hybrid-paddle-vlm" ): base_model_name = "Paddle" visualisation_folder = "hybrid_paddle_vlm_visualisations" elif ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and chosen_local_ocr_model == "hybrid-paddle-inference-server" ): base_model_name = "Paddle" visualisation_folder = "hybrid_paddle_inference_server_visualisations" elif ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and chosen_local_ocr_model == "vlm" ): base_model_name = "VLM" visualisation_folder = "vlm_visualisations" elif ( text_extraction_method == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION and chosen_local_ocr_model == "inference-server" ): base_model_name = "Inference Server" visualisation_folder = "inference_server_visualisations" elif text_extraction_method == BEDROCK_VLM_TEXT_EXTRACT_OPTION: # Matches word-level model string from _parse_vlm_page_ocr_response (model_name="Bedrock") base_model_name = "Bedrock" visualisation_folder = "bedrock_visualisations" elif text_extraction_method == GEMINI_VLM_TEXT_EXTRACT_OPTION: base_model_name = "Gemini" visualisation_folder = "gemini_visualisations" elif text_extraction_method == AZURE_OPENAI_VLM_TEXT_EXTRACT_OPTION: base_model_name = "Azure/OpenAI" visualisation_folder = "azure_openai_visualisations" else: base_model_name = "OCR" visualisation_folder = "ocr_visualisations" if not ocr_results: return log_files_output_paths if isinstance(image, str) and _is_placeholder_image_path(image): if file_path is not None and page_no is not None: resolved = resolve_image_for_ocr_visualization( None, image, file_path, page_no, input_folder=input_folder, page_sizes_df=page_sizes_df, ) if resolved is None: raise FileNotFoundError( f"Could not resolve placeholder page image {image!r} for visualization" ) image = resolved else: raise FileNotFoundError( f"Placeholder page image path cannot be opened: {image!r}" ) if isinstance(image, str): image = Image.open(image) # Convert PIL image to OpenCV format image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) # Get image dimensions height, width = image_cv.shape[:2] # Detect if coordinates need conversion from PyMuPDF to image space # This happens when Textract uses mediabox dimensions (PyMuPDF coordinates) # instead of image pixel dimensions # For non-Textract methods (VLM/inference-server), coordinates should already be in image pixel space, # but we need to check if there's a size mismatch between coordinate space and visualization image needs_coordinate_conversion = False source_width = width source_height = height coords_are_normalized = False def _get_word_bbox(word_data: Dict[str, Any]): """ Word bbox compatibility helper. Different pipelines/components use different key styles: - our OCR results: "bounding_box" - some serialized/review flows: "boundingBox" - occasionally: "bbox" - dict with left/top/width/height (normalized or pixel), or xmin/ymin/xmax/ymax """ if not isinstance(word_data, dict): return (0, 0, 0, 0) bb = ( word_data.get("bounding_box") or word_data.get("boundingBox") or word_data.get("bbox") ) if bb is None: return (0, 0, 0, 0) if isinstance(bb, dict): lk = {str(k).lower(): v for k, v in bb.items()} if all(k in lk for k in ("left", "top", "width", "height")): left = float(lk["left"]) top = float(lk["top"]) w = float(lk["width"]) h = float(lk["height"]) return (left, top, left + w, top + h) if all(k in lk for k in ("xmin", "ymin", "xmax", "ymax")): return ( float(lk["xmin"]), float(lk["ymin"]), float(lk["xmax"]), float(lk["ymax"]), ) return (0, 0, 0, 0) if isinstance(bb, (list, tuple)) and len(bb) == 4: try: return tuple(float(x) for x in bb) except (TypeError, ValueError): return (0, 0, 0, 0) return (0, 0, 0, 0) if text_extraction_method == TEXTRACT_TEXT_EXTRACT_OPTION: # Collect all bounding box coordinates to detect coordinate system all_x_coords = [] all_y_coords = [] for line_key, line_data in ocr_results.items(): if not isinstance(line_data, dict) or "words" not in line_data: continue words = line_data.get("words", []) for word_data in words: if not isinstance(word_data, dict): continue bbox = _get_word_bbox(word_data) if len(bbox) == 4: x1, y1, x2, y2 = bbox all_x_coords.extend([x1, x2]) all_y_coords.extend([y1, y2]) else: # For non-Textract methods (Tesseract, VLM, inference-server, etc.), # coordinates should be in image pixel space, but check if there's a size mismatch # Collect all bounding box coordinates to detect coordinate space all_x_coords = [] all_y_coords = [] for line_key, line_data in ocr_results.items(): if not isinstance(line_data, dict) or "words" not in line_data: continue words = line_data.get("words", []) for word_data in words: if not isinstance(word_data, dict): continue bbox = _get_word_bbox(word_data) if len(bbox) == 4: x1, y1, x2, y2 = bbox all_x_coords.extend([x1, x2]) all_y_coords.extend([y1, y2]) # Decide whether OCR bbox coordinates are in: # - normalized fractions [0,1] (common in some OCR pipelines), or # - a different absolute coordinate space than the visualization image (e.g. PDF points). # If so, compute scaling factors to map them into current image pixel space. if all_x_coords and all_y_coords: try: max_x = float(max(all_x_coords)) max_y = float(max(all_y_coords)) min_x = float(min(all_x_coords)) min_y = float(min(all_y_coords)) except Exception: max_x = max_y = 0.0 min_x = min_y = 0.0 # Normalized coordinates: typically 0..1 (sometimes slightly above due to rounding). if ( min_x >= 0.0 and min_y >= 0.0 and max_x <= 1.5 and max_y <= 1.5 and (max_x > 0.0 or max_y > 0.0) ): coords_are_normalized = True source_width = 1.0 source_height = 1.0 needs_coordinate_conversion = True else: # Absolute coords: infer whether they are in a different coordinate space than the # visualization image and scale accordingly. # # Case A: coords larger than the image → likely PDF points / other space → scale down. if max_x > width * 1.2 or max_y > height * 1.2: source_width = max_x source_height = max_y needs_coordinate_conversion = True else: # Case B: coords much smaller than the image but still in a plausible PDF-point range # (e.g. letter ~612x792, A4 ~595x842). When we render a PDF page to an image at a # higher DPI, the image is typically 2–6x larger than the PDF points. In that case, # we should scale UP so boxes/text land at the correct positions on the image. # # Heuristic: if the image is "large" and the bbox max looks like points, scale up. try: ratio_x = (width / max_x) if max_x else 1.0 ratio_y = (height / max_y) if max_y else 1.0 except Exception: ratio_x = ratio_y = 1.0 looks_like_points = ( # Typical PDF-point page sizes are a few hundred to ~1500. (300.0 <= max_x <= 2000.0) and (300.0 <= max_y <= 2500.0) # And the rendered image is meaningfully larger. and (ratio_x >= 1.5 or ratio_y >= 1.5) ) if looks_like_points: source_width = max_x source_height = max_y needs_coordinate_conversion = True # Calculate scaling factors if conversion is needed if needs_coordinate_conversion: scale_x = width / source_width scale_y = height / source_height else: scale_x = 1.0 scale_y = 1.0 # Define confidence ranges and colors for bounding boxes (bright colors) confidence_ranges = [ (80, 100, (0, 255, 0), "High (80-100%)"), # Green (50, 79, (0, 165, 255), "Medium (50-79%)"), # Orange (0, 49, (0, 0, 255), "Low (0-49%)"), # Red ] # Define darker colors for text on white background text_confidence_ranges = [ (80, 100, (0, 150, 0), "High (80-100%)"), # Dark Green (50, 79, (0, 100, 200), "Medium (50-79%)"), # Dark Orange (0, 49, (0, 0, 180), "Low (0-49%)"), # Dark Red ] # Process each line's words for line_key, line_data in ocr_results.items(): if not isinstance(line_data, dict) or "words" not in line_data: continue words = line_data.get("words", []) # Process each word in the line for word_data in words: if not isinstance(word_data, dict): continue text = word_data.get("text", "") # Handle 'conf' / 'confidence'; values may be 0–100 or fractional 0–1. _raw = word_data.get("conf", word_data.get("confidence", 0)) try: _cf = float(_raw) except (TypeError, ValueError): _cf = 0.0 if 0.0 <= _cf <= 1.0: conf = int(round(_cf * 100)) else: conf = int(_cf) # Skip empty text or invalid confidence if not text.strip() or conf == -1: continue # Get bounding box coordinates bbox = _get_word_bbox(word_data) if len(bbox) != 4: continue x1, y1, x2, y2 = bbox # Convert coordinates if needed (from PyMuPDF to image space) if needs_coordinate_conversion: if coords_are_normalized: # Normalized coords in [0,1] → image pixels x1 = x1 * width y1 = y1 * height x2 = x2 * width y2 = y2 * height else: x1 = x1 * scale_x y1 = y1 * scale_y x2 = x2 * scale_x y2 = y2 * scale_y # Ensure coordinates are within image bounds x1 = max(0, min(int(x1), width)) y1 = max(0, min(int(y1), height)) x2 = max(0, min(int(x2), width)) y2 = max(0, min(int(y2), height)) # Skip if bounding box is invalid if x2 <= x1 or y2 <= y1: continue # Check if word was replaced by a different model (e.g. Bedrock VLM in hybrid Textract route) model = word_data.get("model", None) is_replaced = model and model.lower() != base_model_name.lower() # Determine bounding box color: grey for replaced words, otherwise by confidence box_color = (0, 0, 255) # Default to red if is_replaced: box_color = (128, 128, 128) # Grey for model-replaced words else: for min_conf, max_conf, conf_color, _ in confidence_ranges: if min_conf <= conf <= max_conf: box_color = conf_color break cv2.rectangle(image_cv, (x1, y1), (x2, y2), box_color, 1) # Show model replacement in legend when using a model that can have VLM/inference-server replacements # or when hybrid Textract + Bedrock VLM was used (some lines/words may be from Bedrock VLM) show_model_replacement_legend = ( textract_hybrid_bedrock_used or chosen_local_ocr_model in ( "hybrid-paddle-inference-server", "hybrid-paddle-vlm", "hybrid-vlm", "inference-server", ) ) # Add legend if add_legend: add_confidence_legend( image_cv, confidence_ranges, show_model_replacement=show_model_replacement_legend, ) # Second page: recognised text (PIL + system TTF — OpenCV putText is Latin-only → '?' for Cyrillic/CJK/etc.) viz_font_path = get_ocr_visualisation_font_path() text_page_rgb = Image.new("RGB", (width, height), (255, 255, 255)) draw_pil = ImageDraw.Draw(text_page_rgb) # Pre-pass: compute a per-line representative font size and vertical centre so that # all words in the same line share the same font size and are aligned on the same # baseline, regardless of how tall their individual bounding boxes are. absolute_max_font_pt = 56 max_text_height_fraction = 0.55 # normal cap: text ≤ 55% of box height max_text_height_fraction_small = ( 0.95 # relaxed cap for small boxes where strict cap would be unreadable ) min_readable_px = ( 10 # if strict cap gives fewer pixels than this, use the relaxed cap ) line_font_sizes: dict = {} line_y_centres: dict = {} all_word_box_heights: List[int] = [] for _lk, _ld in ocr_results.items(): if not isinstance(_ld, dict) or "words" not in _ld: continue _valid_bboxes = [] for _wd in _ld["words"]: if not isinstance(_wd, dict): continue if not _wd.get("text", "").strip(): continue _rawc = _wd.get("conf", _wd.get("confidence", 0)) try: _cf = float(_rawc) except (TypeError, ValueError): _cf = 0.0 _c = int(round(_cf * 100)) if 0.0 <= _cf <= 1.0 else int(_cf) if _c == -1: continue _bb = _get_word_bbox(_wd) if len(_bb) != 4: continue _bx1, _by1, _bx2, _by2 = _bb if needs_coordinate_conversion: if coords_are_normalized: _bx1, _by1 = _bx1 * width, _by1 * height _bx2, _by2 = _bx2 * width, _by2 * height else: _bx1, _by1 = _bx1 * scale_x, _by1 * scale_y _bx2, _by2 = _bx2 * scale_x, _by2 * scale_y _bx1 = max(0, min(int(_bx1), width)) _by1 = max(0, min(int(_by1), height)) _bx2 = max(0, min(int(_bx2), width)) _by2 = max(0, min(int(_by2), height)) if _bx2 > _bx1 and _by2 > _by1: _valid_bboxes.append((_bx1, _by1, _bx2, _by2)) all_word_box_heights.append(_by2 - _by1) if not _valid_bboxes: continue _line_y1 = min(b[1] for b in _valid_bboxes) _line_y2 = max(b[3] for b in _valid_bboxes) line_y_centres[_lk] = (_line_y1 + _line_y2) / 2 # Use the median box height so outliers (e.g. very tall or very short boxes) # don't skew the font size for the whole line. _heights = sorted(b[3] - b[1] for b in _valid_bboxes) _representative_h = _heights[len(_heights) // 2] line_font_sizes[_lk] = min(160, max(8, int(_representative_h * 1.8))) # Page-wide ceiling so a few mistaken huge boxes cannot drive oversized type. if all_word_box_heights: viz_global_max_font_pt = min( 160, max(8, int(statistics.median(all_word_box_heights) * 1.8)), ) else: viz_global_max_font_pt = 160 viz_global_max_font_pt = min(viz_global_max_font_pt, absolute_max_font_pt) # Process each line's words for text overlay drawn_words = 0 for line_key, line_data in ocr_results.items(): if not isinstance(line_data, dict) or "words" not in line_data: continue words = line_data.get("words", []) # Group words by bounding box (to handle cases where multiple words share the same box) # Use a small tolerance to consider boxes as "the same" if they're very close bbox_tolerance = 5 # pixels bbox_groups = {} # Maps (x1, y1, x2, y2) to list of word_data for word_data in words: if not isinstance(word_data, dict): continue text = word_data.get("text", "") # Handle 'conf' / 'confidence'; values may be 0–100 or fractional 0–1. _raw = word_data.get("conf", word_data.get("confidence", 0)) try: _cf = float(_raw) except (TypeError, ValueError): _cf = 0.0 if 0.0 <= _cf <= 1.0: conf = int(round(_cf * 100)) else: conf = int(_cf) # Skip empty text or invalid confidence if not text.strip() or conf == -1: continue # Get bounding box coordinates bbox = _get_word_bbox(word_data) if len(bbox) != 4: continue x1, y1, x2, y2 = bbox # Convert coordinates if needed (from PyMuPDF to image space) if needs_coordinate_conversion: if coords_are_normalized: x1 = x1 * width y1 = y1 * height x2 = x2 * width y2 = y2 * height else: x1 = x1 * scale_x y1 = y1 * scale_y x2 = x2 * scale_x y2 = y2 * scale_y # Ensure coordinates are within image bounds x1 = max(0, min(int(x1), width)) y1 = max(0, min(int(y1), height)) x2 = max(0, min(int(x2), width)) y2 = max(0, min(int(y2), height)) # Skip if bounding box is invalid if x2 <= x1 or y2 <= y1: continue # Round coordinates to nearest tolerance to group similar boxes x1_rounded = (x1 // bbox_tolerance) * bbox_tolerance y1_rounded = (y1 // bbox_tolerance) * bbox_tolerance x2_rounded = (x2 // bbox_tolerance) * bbox_tolerance y2_rounded = (y2 // bbox_tolerance) * bbox_tolerance bbox_key = (x1_rounded, y1_rounded, x2_rounded, y2_rounded) if bbox_key not in bbox_groups: bbox_groups[bbox_key] = [] bbox_groups[bbox_key].append( {"word_data": word_data, "original_bbox": (x1, y1, x2, y2)} ) # Process each group of words for bbox_key, word_group in bbox_groups.items(): if not word_group: continue # Use the first word's bounding box as the reference (they should all be similar) x1, y1, x2, y2 = word_group[0]["original_bbox"] box_width = x2 - x1 box_height = y2 - y1 # If only one word in the box, process it normally if len(word_group) == 1: word_data = word_group[0]["word_data"] text = word_data.get("text", "") _raw = word_data.get("conf", word_data.get("confidence", 0)) try: _cf = float(_raw) except (TypeError, ValueError): _cf = 0.0 conf = int(round(_cf * 100)) if 0.0 <= _cf <= 1.0 else int(_cf) # Check if word was replaced by a different model model = word_data.get("model", None) is_replaced = model and model.lower() != base_model_name.lower() # Text color always by confidence (replaced words still show confidence; box stays grey) text_color = (0, 0, 180) # Default to dark red (BGR) for min_conf, max_conf, conf_color, _ in text_confidence_ranges: if min_conf <= conf <= max_conf: text_color = conf_color break # Use the line-level font size cap so all words in a line stay # visually consistent; only reduce further if the word is too wide. max_pt = min( line_font_sizes.get( line_key, min(160, max(8, int(box_height * 1.8))) ), viz_global_max_font_pt, ) strict_h = int(box_height * max_text_height_fraction) allowed_text_height = max( 1, ( int(box_height * max_text_height_fraction_small) if strict_h < min_readable_px else strict_h ), ) min_pt = 1 pil_font = _pil_ocr_viz_load_font(viz_font_path, min_pt) tw = 1 th = 1 for pt in range(max_pt, min_pt - 1, -1): pil_font = _pil_ocr_viz_load_font(viz_font_path, pt) tw, th = _pil_ocr_viz_text_size(pil_font, text) if tw <= box_width * 0.95 and th <= allowed_text_height: break text_left_edge = x1 + (box_width - tw) / 2.0 # Word-like tokens: align to line vertical centre. Punctuation-only tokens use a # fraction of the OCR box height so glyphs are not pushed to the bottom when the # font bbox is much taller than a tight comma/period box. line_y_c = line_y_centres.get(line_key, y1 + box_height / 2) ref_y = _ocr_viz_overlay_vertical_ref_y(y1, y2, text, line_y_c) draw_x, draw_y = _ocr_viz_draw_position_from_left_edge( text, pil_font, text_left_edge, ref_y, width, height, y1, y2 ) draw_pil.text( (draw_x, draw_y), text, font=pil_font, fill=_ocr_viz_bgr_to_rgb(text_color), ) drawn_words += 1 if is_replaced: draw_pil.rectangle( [x1, y1, x2, y2], outline=(128, 128, 128), width=1, ) else: # Multiple words in the same box - arrange them side by side # Extract texts and determine colors for each word word_texts = [] word_colors = [] word_is_replaced = [] for item in word_group: word_data = item["word_data"] text = word_data.get("text", "") _raw = word_data.get("conf", word_data.get("confidence", 0)) try: _cf = float(_raw) except (TypeError, ValueError): _cf = 0.0 conf = int(round(_cf * 100)) if 0.0 <= _cf <= 1.0 else int(_cf) model = word_data.get("model", None) is_replaced = model and model.lower() != base_model_name.lower() # Text color always by confidence (replaced words still show confidence; box stays grey) text_color = (0, 0, 180) # Default to dark red for min_conf, max_conf, conf_color, _ in text_confidence_ranges: if min_conf <= conf <= max_conf: text_color = conf_color break word_texts.append(text) word_colors.append(text_color) word_is_replaced.append(is_replaced) n = len(word_texts) # Use the line-level font size cap so all words in a line stay # visually consistent; only reduce further if the combined text is too wide. max_pt = min( line_font_sizes.get( line_key, min(160, max(8, int(box_height * 1.8))) ), viz_global_max_font_pt, ) strict_h = int(box_height * max_text_height_fraction) allowed_text_height = max( 1, ( int(box_height * max_text_height_fraction_small) if strict_h < min_readable_px else strict_h ), ) min_pt = 1 pil_font = _pil_ocr_viz_load_font(viz_font_path, min_pt) total_width = 0 max_text_height = 0 space_w = 1 for pt in range(max_pt, min_pt - 1, -1): pil_font = _pil_ocr_viz_load_font(viz_font_path, pt) total_width = 0 max_text_height = 0 space_w, _ = _pil_ocr_viz_text_size(pil_font, " ") for i, wtext in enumerate(word_texts): tw, th = _pil_ocr_viz_text_size(pil_font, wtext) total_width += tw max_text_height = max(max_text_height, th) if i < n - 1: total_width += space_w if ( total_width <= box_width * 0.95 and max_text_height <= allowed_text_height ): break current_x = x1 + (box_width - total_width) // 2 line_y_c = line_y_centres.get(line_key, y1 + box_height / 2) if all(_ocr_viz_is_punctuation_only_token(wt) for wt in word_texts): ref_y = _ocr_viz_overlay_vertical_ref_y( y1, y2, "".join(word_texts), line_y_c ) else: ref_y = float(line_y_c) for i, (wtext, text_color) in enumerate(zip(word_texts, word_colors)): draw_x, draw_y = _ocr_viz_draw_position_from_left_edge( wtext, pil_font, float(current_x), ref_y, width, height, y1, y2 ) draw_pil.text( (draw_x, draw_y), wtext, font=pil_font, fill=_ocr_viz_bgr_to_rgb(text_color), ) drawn_words += 1 tw, _ = _pil_ocr_viz_text_size(pil_font, wtext) current_x += tw if i < n - 1: current_x += space_w if any(word_is_replaced): draw_pil.rectangle( [x1, y1, x2, y2], outline=(128, 128, 128), width=1, ) text_page = cv2.cvtColor(np.asarray(text_page_rgb), cv2.COLOR_RGB2BGR) # Add legend to second page if add_legend: add_confidence_legend( text_page, text_confidence_ranges, show_model_replacement=show_model_replacement_legend, ) # Concatenate images horizontally combined_image = np.hstack([image_cv, text_page]) # Save the visualization if output_folder: trusted_base = os.path.realpath(str(OUTPUT_FOLDER)) requested_out_dir = os.path.realpath(os.path.normpath(str(output_folder))) out_dir = trusted_base if validate_folder_containment(requested_out_dir, trusted_base): out_dir = requested_out_dir else: # Defense-in-depth: attempt to map a requested directory to a safe relative # path under the trusted base. If that relative contains traversal, the # secure join will reject it and we stay on trusted_base. try: rel_out_dir = os.path.relpath(requested_out_dir, trusted_base) if rel_out_dir not in (".", ""): out_dir = str(secure_path_join(trusted_base, rel_out_dir)) except Exception: out_dir = trusted_base textract_viz_folder = str(secure_path_join(out_dir, visualisation_folder)) # Double-check the constructed path is safe if not validate_path_safety(textract_viz_folder, base_path=out_dir): raise ValueError( f"Unsafe textract visualisations folder path: {textract_viz_folder}" ) os.makedirs(textract_viz_folder, exist_ok=True) # Generate filename if image_name: # Prefer explicit page_number. If not provided, fall back to parsing it # from image_name suffix (legacy behaviour). page_number_str = str(int(page_number)) if page_number is not None else None image_name_without_page = image_name if page_number_str is None: # Extract page number from image_name if it follows the pattern _ at the end # This handles cases like "document_1", "document.pdf_1", etc. page_match = re.search(r"_(\d+)$", image_name) if page_match: page_number_str = page_match.group(1) # Remove the page number suffix from image_name for base_name extraction image_name_without_page = image_name[: page_match.start()] # Remove file extension if present base_name = os.path.splitext(image_name_without_page)[0] # Include page number in filename if it was found if page_number_str: filename = ( f"{base_name}_page_{page_number_str}_{visualisation_folder}.jpg" ) else: filename = f"{base_name}_{visualisation_folder}.jpg" else: timestamp = int(time.time()) filename = f"{visualisation_folder}_{timestamp}.jpg" output_path = str(secure_path_join(textract_viz_folder, filename)) resolved_output_path = os.path.realpath(output_path) if not validate_path_safety( resolved_output_path, base_path=textract_viz_folder ): raise ValueError(f"Unsafe output path rejected: {output_path}") # Save the combined image. Ensure that image file size is 500kb or less max_filesize = 500 * 1024 # 500kb in bytes quality = 95 # Start high, OpenCV JPEG quality range is 0-100 # Try lowering JPEG quality until file is below size limit is_saved = False while quality >= 10: cv2.imwrite( resolved_output_path, combined_image, [int(cv2.IMWRITE_JPEG_QUALITY), quality], ) if ( os.path.exists(resolved_output_path) and os.path.getsize(resolved_output_path) <= max_filesize ): is_saved = True break quality -= 5 if not is_saved: # Save as lowest acceptable quality if cannot get under 500kb, or raise warning cv2.imwrite( resolved_output_path, combined_image, [int(cv2.IMWRITE_JPEG_QUALITY), 10], ) # Optionally log warning here that file could not be compressed below 500kb log_files_output_paths.append(resolved_output_path) return log_files_output_paths def add_confidence_legend( image_cv: np.ndarray, confidence_ranges: List[Tuple], show_model_replacement: bool = False, ) -> None: """ Adds a confidence legend to the visualization image. Args: image_cv: OpenCV image array confidence_ranges: List of tuples containing (min_conf, max_conf, color, label) show_model_replacement: Whether to include a legend entry for model replacements (grey) """ height, width = image_cv.shape[:2] # Calculate legend height based on number of items num_items = len(confidence_ranges) if show_model_replacement: num_items += 1 # Scale the entire legend to ~13% of image width so it never dominates. legend_width = max(90, min(200, int(width * 0.13))) scale = legend_width / 200.0 # proportional to original 200px baseline font_scale_title = max(0.28, round(0.55 * scale, 2)) font_scale_label = max(0.22, round(0.45 * scale, 2)) item_spacing = max(12, int(22 * scale)) box_size = max(7, int(13 * scale)) margin = max(4, int(8 * scale)) (_, title_h), _ = cv2.getTextSize( "Confidence Levels", cv2.FONT_HERSHEY_SIMPLEX, font_scale_title, 1 ) legend_height = title_h + margin * 3 + num_items * item_spacing + margin outer_pad = max(4, int(14 * scale)) legend_x = width - legend_width - outer_pad legend_y = outer_pad # Translucent white background overlay = image_cv.copy() cv2.rectangle( overlay, (legend_x, legend_y), (legend_x + legend_width, legend_y + legend_height), (255, 255, 255), -1, ) cv2.addWeighted(overlay, 0.5, image_cv, 0.5, 0, image_cv) # Title title_text = "Confidence Levels" (title_w, title_h), _ = cv2.getTextSize( title_text, cv2.FONT_HERSHEY_SIMPLEX, font_scale_title, 1 ) title_x = legend_x + max(0, (legend_width - title_w) // 2) title_y = legend_y + title_h + margin cv2.putText( image_cv, title_text, (title_x, title_y), cv2.FONT_HERSHEY_SIMPLEX, font_scale_title, (0, 0, 0), 1, ) start_y = title_y + item_spacing item_index = 0 def _draw_legend_item(img, lx, iy, bsz, col, lbl, lbl_scale, mgn): bx = lx + mgn by = iy - bsz cv2.rectangle(img, (bx, by), (bx + bsz, by + bsz), col, -1) cv2.rectangle(img, (bx, by), (bx + bsz, by + bsz), (0, 0, 0), 1) cv2.putText( img, lbl, (bx + bsz + mgn, iy - max(1, mgn // 3)), cv2.FONT_HERSHEY_SIMPLEX, lbl_scale, (0, 0, 0), 1, ) if show_model_replacement: _draw_legend_item( image_cv, legend_x, start_y + item_index * item_spacing, box_size, (128, 128, 128), "Model Replacement", font_scale_label, margin, ) item_index += 1 for i, (min_conf, max_conf, color, label) in enumerate(confidence_ranges): _draw_legend_item( image_cv, legend_x, start_y + (item_index + i) * item_spacing, box_size, color, label, font_scale_label, margin, ) def _draw_dashed_line_2d( image_cv: np.ndarray, x1: float, y1: float, x2: float, y2: float, color_bgr: Tuple[int, int, int], thickness: int, dash_len: int, gap_len: int, ) -> None: """Draw a polyline from (x1,y1) to (x2,y2) with alternating dash/gap segments.""" length = float(np.hypot(x2 - x1, y2 - y1)) if length < 1e-6: return ux = (x2 - x1) / length uy = (y2 - y1) / length pos = 0.0 draw = True while pos < length: seg = dash_len if draw else gap_len next_pos = min(pos + seg, length) if draw: cv2.line( image_cv, (int(round(x1 + ux * pos)), int(round(y1 + uy * pos))), (int(round(x1 + ux * next_pos)), int(round(y1 + uy * next_pos))), color_bgr, thickness, cv2.LINE_AA, ) pos = next_pos draw = not draw def _dash_gap_for_pattern_span(span_px: int, pattern: str) -> Tuple[int, int]: """ Dash and gap lengths for an edge of length ``span_px`` so dashed/dotted styles repeat visibly. Matches legend line samples to main-image box edges for the same ``pattern`` when spans are similar. """ span_px = max(1, int(span_px)) if pattern == "solid": return (1, 0) if pattern == "dashed": if span_px >= 48: return (8, 4) period = max(6, span_px // 3) dash_len = max(3, (period * 2 + 2) // 3) gap_len = max(2, period - dash_len) return (dash_len, gap_len) # dotted if span_px >= 32: return (2, 4) period = max(4, span_px // 4) dash_len = max(2, min(3, max(1, period // 4))) gap_len = max(2, dash_len * 2) return (dash_len, gap_len) def draw_rectangle_outline_pattern( image_cv: np.ndarray, x1: int, y1: int, x2: int, y2: int, color_bgr: Tuple[int, int, int], thickness: int = 2, pattern: str = "solid", ) -> None: """ Draw a hollow rectangle outline. ``pattern`` is one of: solid, dashed, dotted. """ x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) if x2 <= x1 or y2 <= y1: return if pattern == "solid": cv2.rectangle( image_cv, (x1, y1), (x2, y2), color_bgr, thickness, cv2.LINE_AA, ) return min_side = min(x2 - x1, y2 - y1) dash_len, gap_len = _dash_gap_for_pattern_span(min_side, pattern) _draw_dashed_line_2d( image_cv, x1, y1, x2, y1, color_bgr, thickness, dash_len, gap_len ) _draw_dashed_line_2d( image_cv, x2, y1, x2, y2, color_bgr, thickness, dash_len, gap_len ) _draw_dashed_line_2d( image_cv, x2, y2, x1, y2, color_bgr, thickness, dash_len, gap_len ) _draw_dashed_line_2d( image_cv, x1, y2, x1, y1, color_bgr, thickness, dash_len, gap_len ) def _draw_redaction_legend_pattern_sample( image_cv: np.ndarray, x0: int, y_mid: int, line_width: int, color_bgr: Tuple[int, int, int], pattern: str, thickness: int, ) -> None: """ Horizontal line showing the same dash/dot style as ``draw_rectangle_outline_pattern``, long enough for dashed/dotted to read (unlike a tiny square swatch). """ x1 = x0 + int(line_width) if pattern == "solid": cv2.line( image_cv, (x0, y_mid), (x1, y_mid), color_bgr, thickness, cv2.LINE_AA, ) return dash_len, gap_len = _dash_gap_for_pattern_span(int(line_width), pattern) _draw_dashed_line_2d( image_cv, float(x0), float(y_mid), float(x1), float(y_mid), color_bgr, thickness, dash_len, gap_len, ) def add_redaction_label_legend( image_cv: np.ndarray, legend_rows: List[Tuple[Tuple[int, int, int], str, str]], title: str = "Redaction labels", ) -> None: """ Add a top-right legend for redaction label colours and outline patterns. Args: image_cv: OpenCV BGR image (modified in place). legend_rows: List of (BGR colour, pattern name, display label). title: Legend title text. """ if not legend_rows: return height, width = image_cv.shape[:2] num_items = len(legend_rows) legend_width = max(90, min(220, int(width * 0.14))) scale = legend_width / 200.0 font_scale_title = max(0.28, round(0.55 * scale, 2)) font_scale_label = max(0.22, round(0.45 * scale, 2)) item_spacing = max(12, int(22 * scale)) box_size = max(7, int(13 * scale)) margin = max(4, int(8 * scale)) (_, title_h), _ = cv2.getTextSize( title, cv2.FONT_HERSHEY_SIMPLEX, font_scale_title, 1 ) legend_height = title_h + margin * 3 + num_items * item_spacing + margin outer_pad = max(4, int(14 * scale)) legend_x = width - legend_width - outer_pad legend_y = outer_pad overlay = image_cv.copy() cv2.rectangle( overlay, (legend_x, legend_y), (legend_x + legend_width, legend_y + legend_height), (255, 255, 255), -1, ) cv2.addWeighted(overlay, 0.5, image_cv, 0.5, 0, image_cv) (title_w, title_h), _ = cv2.getTextSize( title, cv2.FONT_HERSHEY_SIMPLEX, font_scale_title, 1 ) title_x = legend_x + max(0, (legend_width - title_w) // 2) title_y = legend_y + title_h + margin cv2.putText( image_cv, title, (title_x, title_y), cv2.FONT_HERSHEY_SIMPLEX, font_scale_title, (0, 0, 0), 1, ) start_y = title_y + item_spacing swatch_thickness = max(1, int(round(1.5 * scale))) swatch_line_w = max(28, min(56, legend_width - 2 * margin - 78)) for idx, (col_bgr, pattern, lbl) in enumerate(legend_rows): iy = start_y + idx * item_spacing bx = legend_x + margin y_line = iy - max(5, box_size // 3) lbl_disp = lbl if len(lbl) <= 42 else lbl[:39] + "..." _draw_redaction_legend_pattern_sample( image_cv, bx, y_line, swatch_line_w, col_bgr, pattern, swatch_thickness, ) cv2.putText( image_cv, lbl_disp, (bx + swatch_line_w + margin, iy - max(1, margin // 3)), cv2.FONT_HERSHEY_SIMPLEX, font_scale_label, (0, 0, 0), 1, )