[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7C44CF3V8NQTGFC3NB5H840":3,"skill-same:01M7C44CF3V8NQTGFC3NB5H840":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M7C44CF3V8NQTGFC3NB5H840","image-ocr",null,"Extract and validate text or structured fields from images with Tesseract, including auditable multi-pass adjudication for receipt dates and monetary totals","linyouxue\u002Fskill-repair-benchmark","linyouxue","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F216151464?v=4","01M7BJEVCXKD74KH6FG9CBVSQB","林宥学","01M7BJEVE02NP217V93BKZFC0J",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fevaluation\u002Fresults\u002F对于jpg-ocr-stat的尝试\u002Fruns\u002Fjpg-ocr-stat-round-11-r002\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: image-ocr\ndescription: Extract and validate text or structured fields from images with Tesseract, including auditable multi-pass adjudication for receipt dates and monetary totals\n---\n\n# Round 11 mandatory total freeze-and-recovery gate\n\nThis addendum is deliberately narrow. It changes only the **last adjudication\nof `total_amount`** on top of the established Round 5 workflow. It must not be\nused as permission to redesign OCR acquisition, date parsing, clustering, or\nthe general candidate parser.\n\n## 1. Acquisition is frozen\n\nFor full-page OCR, keep the established bounded Round 5 acquisition only:\n\n- the existing original \u002F contrast-or-sharpened \u002F thresholded variants;\n- full-page PSM 6 and 11 only;\n- targeted OCR, when genuinely unresolved, may use the already-established\n  crop PSMs 6 \u002F 7 \u002F 11.\n\nDo **not** add PSM 4 or any other full-page PSM. Do not add another\npreprocessing variant, threshold sweep, scale sweep, generic OCR retry, looser\nmoney regex, new date heuristic, or new global region\u002Fcluster definition.\n\nThis is a blocking implementation invariant. If the implementation changes the\nfull-page acquisition set or date adjudication in order to solve a total\ndispute, revert that change before continuing.\n\n## 2. Freeze a resolved baseline before any targeted total retry\n\nAfter the bounded full-page evidence has been collected, run the ordinary\nRound 5 semantic selection once and snapshot:\n\n```text\nbaseline_winner\nbaseline_support_rows\nbaseline_support_pass_ids\n```\n\nIf `baseline_winner` is non-null and has the normal independent same-region\nsupport required by Round 5, it is **frozen**.\n\nFor that receipt:\n\n- do not run targeted OCR for `total_amount` merely to seek a different value;\n- do not recompute it under a new cluster key;\n- do not let later confidence\u002Fsupport counts or a semantic-rank mutation\n  replace it;\n- do not call a generic total winner selector again after final adjudication.\n\nTargeted total OCR is allowed only when the bounded full-page baseline is\nactually unresolved (`baseline_winner is None`). Date handling is independent\nand must not be changed by this addendum.\n\n## 3. Absolute non-payable exclusions remain in force\n\nNever select `CASH`, cash tendered\u002Freceived, `CHANGE`, payment\u002Fcard rows,\n`SUBTOTAL` \u002F `SUB TOTAL`, tax-only\u002FGST\u002FSST summary rows, item amounts,\nquantities, unit prices, or table headers as the final payable amount.\n\nHowever, an excluded earlier accounting row may be used only as **local\ncorroborating evidence** for the digits of a later explicit final-payable row;\nit does not itself become the selected total.\n\nDo not reject genuine payable labels such as `TOTAL RM INCLUDING GST` merely\nbecause the phrase contains GST.\n\n## 4. Decimal punctuation is mandatory for a selected value\n\nA digits-only OCR token such as `1000` cannot establish whether the source is\n`1000`, `100.0`, or `10.00`. It may corroborate the digit sequence of an\nalready decimal-preserving read from the **same row\u002Fregion**, but it cannot\ncreate a monetary value or determine decimal placement.\n\nAny selected or replacement total therefore needs at least one existing OCR\nobservation of the correct payable row that preserves a decimal mark (dot or\ndecimal comma).\n\n## 5. Null-baseline recovery from an explicit final row\n\nIf and only if `baseline_winner is None`, the final gate may recover a value\nfrom evidence already collected by the bounded workflow.\n\nLet `F` be an explicit final-payable row such as `GRAND TOTAL`, `TOTAL DUE`,\n`AMOUNT DUE`, `BALANCE DUE`, `TOTAL AFTER ROUNDING`, `ROUNDED TOTAL`,\n`NET TOTAL`, or equivalent. A single decimal-preserving read of `F` may be\naccepted even when row-local clustering leaves it with support 1, but only when\n**all** of the following hold:\n\n1. there is no different decimal-preserving eligible final-payable competitor\n   in the same settlement block;\n2. the value of `F` is corroborated locally by at least one independent\n   observation, for example:\n   - the same normalized value on an earlier payable\u002Faccounting row in the\n     same settlement block; or\n   - a digits-only read of the same `F` row\u002Fregion whose digit sequence matches\n     `F` after punctuation is removed; or\n   - an explicit local adjustment equation leading to `F`;\n3. no credible non-zero adjustment or later payable row contradicts `F`.\n\nThis rule is specifically a **null recovery rule**. It must not be used to\nreplace an already stable non-null baseline.\n\n## 6. Local settlement replacement rules\n\nFor a frozen non-null baseline `A`, a different later final value `F` may\nreplace it only if one of these proofs exists in the same local settlement\nblock:\n\n1. `F` itself has at least two materially different decimal-preserving OCR\n   passes in the same final row\u002Fregion; or\n2. there is an explicit signed adjustment `R` and\n   `Decimal(A) + Decimal(R) == Decimal(F)` within one cent.\n\nA single promoted final row, later page position, larger support count,\nconfidence change, or semantic-rank change is not sufficient.\n\n## 7. One-cent mutation veto\n\nIf a proposed later value differs from a stable `baseline_winner` by exactly\n`0.01`, treat that as a disputed OCR digit, not an automatic rounding event.\n\nKeep the baseline unless the same local settlement block contains either:\n\n- an explicit non-zero rounding\u002Fadjustment row whose arithmetic explains that\n  exact one-cent change; or\n- at least two materially different decimal-preserving reads of the later\n  final row agreeing on the changed value.\n\nWithout one of those proofs, the one-cent mutation is vetoed and the baseline\nremains final.\n\n## 8. Irreversible pre-write audit\n\nImmediately before writing `stat_ocr.xlsx`, persist for every receipt:\n\n```text\nbaseline_winner\nfinal_winner\ndecision = freeze_baseline | recover_explicit_final |\n           direct_final_support | arithmetic_settlement | cent_mutation_veto\nsupporting local evidence rows\u002Fpass ids\nrejected competing final values and reasons\n```\n\nAfter this audit decision, `final_winner` is immutable. Write the workbook from\nthat value and compare workbook readback against the same frozen audit value.\nDo not run another generic selector afterward.\n\n## 9. Scope guard\n\nThe intended implementation change is only:\n\n```text\nunchanged Round 5 bounded evidence\n    -> freeze resolved baseline\n    -> if null, recover only from explicit local final evidence\n    -> if replacement proposed, require settlement proof and apply cent veto\n    -> immutable final_winner\n    -> workbook write\u002Freadback\n```\n\nNever hard-code a filename, expected date, or expected amount.\n\n# Round 5 mandatory receipt-field adjudication gate\n\nFor receipt OCR tasks that require an exact `date` and `total_amount` per image,\nthis block overrides weaker or more permissive advice below. Treat it as an\nexecution contract. Do not finish merely because an Excel file exists or every\nrow is non-null.\n\n## A. Run bounded full-page OCR once, then cache it\n\n1. Enumerate all receipt images in deterministic filename order.\n2. For every image run a small fixed set of materially different full-page OCR\n   passes (for example original\u002Fgrayscale, contrast or sharpened, and thresholded;\n   use useful PSM variants). Persist each pass's text **and token boxes** once.\n3. Parse all field candidates from that cache. Never rerun the entire image set\n   just because one parser rule changes.\n4. After the cached full-page passes, additional OCR is allowed only for images\n   and fields whose evidence is unresolved or conflicting.\n\nUse `pytesseract.image_to_data(..., output_type=Output.DICT)` or an equivalent\nbox-producing API in addition to plain text OCR. Whole-page mean confidence is\nnot a valid reason to discard all candidates from another pass.\n\n## B. Keep a field-level evidence ledger\n\nFor every `(filename, field)` pair, where `field` is `date` or `total_amount`,\npersist candidate evidence with at least:\n\n```\nfilename, field, pass_id, raw_line, normalized_label, semantic_class,\nbbox_or_row_region, raw_candidate, normalized_candidate, confidence,\neligible, rejection_reason\n```\n\nThe final selection must be reproducible from this ledger. Never reduce the\nevidence to only `value -> number_of_passes`.\n\nTwo passes support one another only when they read the **same semantic field in\nthe same source region**. The same number occurring elsewhere on the receipt is\nnot supporting evidence. Group candidates by page-local row\u002Fbox geometry and\nfield meaning before counting cross-pass agreement.\n\n## C. Amount semantics: enumerate before selecting\n\nFor `total_amount`, collect all plausible amount candidates from every cached\npass before choosing a winner. Apply these rules in this order:\n\n1. Reject lines containing task exclusion concepts such as `SUBTOTAL`,\n   `SUB TOTAL`, `TAX`, `GST`, `SST`, `DISCOUNT`, `CHANGE`, or `CASH TENDERED`.\n2. Reject product\u002Ftable headings such as `QTY ITEM TOTAL`, `ITEM ... TOTAL`, or\n   another line where `TOTAL` is a column header rather than a payable field.\n3. Prefer explicit final-payment semantics (`GRAND TOTAL`, `TOTAL RM`,\n   `TOTAL AMOUNT`, `TOTAL DUE`, `AMOUNT DUE`, `BALANCE DUE`, `NETT TOTAL`,\n   `NET TOTAL`) over a generic `TOTAL` occurrence.\n4. Distinguish intermediate sales totals from a later adjustment\u002Frounding\u002Ffinal\n   payable stage. A `TOTAL SALES` or similar earlier accounting stage must not\n   outrank a later clearly final\u002Fadjusted payable amount merely because it is\n   easier to OCR or appears in more passes.\n5. Never select `amounts[-1]`, the largest amount, the most frequent number, or\n   the first legal match as a substitute for semantic adjudication.\n\n### Safe next-line fallback\n\nUse the task's next-line fallback only if the current line is a **standalone\npayable-field label**. The next line must be locally adjacent, aligned with the\nfield's value region, and contain only a plausible currency\u002Fvalue token rather\nthan an item description, quantity, unit price, tendered amount, change, or a\nnew field label. Record the label\u002Fvalue boxes proving the pairing.\n\n## D. Decimal placement is evidence, not formatting\n\nDo not let numeric whitelists or normalization silently destroy monetary\npunctuation. A digits-only pass that reads `1000` cannot by itself prove whether\nthe source is `1000`, `100.0`, or `10.00`. It may support the digit sequence,\nbut decimal placement must be confirmed by a pass\u002Fcrop that preserves\npunctuation or by clear same-region visual\u002FOCR evidence.\n\nKeep the raw candidate string. Remove thousands separators only after the\ndecimal mark is established. Use `Decimal` for normalization and format the\naccepted final amount to exactly two decimal places only **after** the source\nvalue is adjudicated. Never append\u002Fremove digits merely to make a plausible\ncurrency value.\n\n## E. Date parsing must preserve token order\n\nCollect every date candidate across passes before selecting. Do not return the\nfirst syntactically valid date and do not let a parser silently choose MDY\u002FDMY\nfor an ambiguous slash date.\n\nFor each candidate keep the raw text and component order. Determine the date\nconvention from explicit labels\u002Fcontext and, where needed, unambiguous dates or\nconsistent formatting evidence. Once a convention is established for that\nreceipt\u002Fcontext, apply it explicitly. A disagreement in day, month, **or year**\nbetween passes makes the field disputed and triggers targeted OCR.\n\n## F. Every disagreement must trigger targeted OCR\n\nA field is disputed if any of these holds:\n\n- same-region passes produce different normalized values;\n- only one usable pass supports a candidate;\n- two different semantic candidates remain eligible;\n- decimal placement differs or disappears between passes;\n- a date component differs between passes;\n- a next-line fallback lacks strong local pairing evidence;\n- OCR confidence\u002Ffragmentation makes any digit uncertain.\n\nFor every disputed field, stop broad OCR and make targeted crops around the\nfield's label\u002Fvalue row. Use both:\n\n- a **tight value crop** to improve digit recognition; and\n- a **wider context crop** that retains the label and neighboring lines so the\n  number's semantic ownership is visible.\n\nUpscale the crops (2x minimum; 3x\u002F4x when useful), try materially different\npreprocessing, and use appropriate PSMs such as 6\u002F7\u002F11. A numeric whitelist is\nan auxiliary pass, not authoritative evidence for punctuation. Add every\ntargeted result to the same ledger.\n\nPrinting a disagreement table is not resolution. Each disputed ledger row must\ncause an actual targeted retry and finish with a winner or an explicit reject\nreason for each competing candidate.\n\n## G. Blocking pre-write audit\n\nBefore creating `stat_ocr.xlsx`, build one compact final audit row per input\nimage containing:\n\n```\nfilename | selected date | date evidence regions\u002Fpasses |\nselected total | total evidence regions\u002Fpasses | rejected alternatives | status\n```\n\nProgrammatically enforce at least:\n\n```python\nassert audit_filename_set == input_filename_set\nassert unresolved_field_count == 0\nassert single_pass_non_null_winner_count == 0\nassert cross_region_consensus_count == 0\nassert unresolved_competing_candidate_count == 0\nassert unsafe_next_line_winner_count == 0\n```\n\nIf one fails, continue **only** with the unresolved images\u002Ffields. Do not rerun\nalready-resolved images and do not write the final workbook yet.\n\n## H. Exact artifact contract and readback\n\nAfter the field audit passes:\n\n1. create exactly one sheet named `results`;\n2. write exactly the columns `filename`, `date`, `total_amount`;\n3. sort data rows by filename and include exactly one row for every input image;\n4. write dates as ISO `YYYY-MM-DD` strings (or null only when genuinely\n   unresolved according to the task contract);\n5. write accepted monetary values as strings with exactly two decimal places;\n6. save to the exact required path `\u002Fapp\u002Fworkspace\u002Fstat_ocr.xlsx`;\n7. reopen that saved workbook and read every cell back;\n8. compare the readback programmatically to the adjudicated audit rows and the\n   exact sheet\u002Fheader\u002Forder constraints.\n\nOnly the reopened workbook matching the adjudicated evidence is completion.\n\n## I. Completion-budget discipline\n\nOnce a `(filename, field)` has strong same-region evidence, freeze it. Spend\nremaining OCR\u002Ftool calls only on disputed fields. The intended workflow is:\n\n`bounded cached batch -> field ledger -> targeted retries -> audit -> one write -> readback`.\n\nDo not regress to repeated whole-dataset OCR commands during parser iteration or\nfinal workbook creation.\n\n# Image OCR Skill\n\n## Purpose\nThis skill enables accurate text extraction from image files (JPG, PNG, etc.) using Tesseract OCR via the `pytesseract` Python library. It is suitable for scanned documents, screenshots, photos of text, receipts, forms, and other visual content containing text.\n\n## Blocking Evidence Gate for Exact Structured Fields\n\nWhen OCR values will be written into a table, database, or other artifact that\nrequires exact dates or monetary amounts, the following rules are mandatory.\nThey are execution requirements, not optional quality suggestions. Do not\nmaterialize the artifact or finish the task until the programmatic gate passes.\n\n1. **Verify every resolved field independently** - Every non-null date and\n   monetary amount must have the same normalized value, field meaning, and\n   supporting source region in at least two materially different OCR passes.\n   Change preprocessing, segmentation mode, scale, or crop; repeating the same\n   pixels and configuration is not independent evidence. A syntactically valid\n   value from one pass remains an unverified candidate.\n2. **Collect before selecting** - Complete the required passes and enumerate all\n   field candidates before choosing a winner. Never select the first legal date,\n   first keyword match, first non-null pass, largest number, or final numeric\n   token merely because it is available.\n3. **Escalate every disagreement** - If independent passes disagree in any date\n   component or monetary digit, run at least one targeted crop or alternative\n   segmentation pass over that field. If bounded retries still do not establish\n   independent agreement within the correct semantic class, emit the task's\n   null\u002Ferror representation instead of guessing.\n4. **Use safe line pairing** - A next-line amount is eligible only when the\n   current line is a standalone target-field label and spatial evidence or a\n   targeted crop confirms that the adjacent line is its value. The adjacent line\n   must contain only currency\u002Fvalue tokens. Reject it if it contains an item,\n   description, quantity, price, cash received, tendered, change, payment, or\n   another field label.\n5. **Adjudicate semantics before agreement** - Apply the task's exclusions and\n   keyword groups before counting cross-pass agreement. Within the same allowed\n   keyword group, a final adjusted, after-adjustment, rounded, amount-due,\n   balance-due, or grand-total stage outranks an earlier sales total and any\n   tendered\u002Fpayment value. For dates, collect every date candidate across the\n   receipt and all passes; use the requested field meaning, label proximity,\n   region, and cross-pass agreement rather than returning the first valid date.\n6. **Persist the candidate audit first** - For every input and required field,\n   save the pass identifier\u002Fconfiguration, raw supporting line, location or crop,\n   normalized candidate, semantic class, eligibility or rejection reason,\n   selected winner, and the independent passes supporting it. Record unresolved\n   fields as well as successful fields.\n7. **Run a blocking completion audit** - The program must fail or continue OCR\n   unless all of these conditions hold:\n   - every input has an audit record for every required field;\n   - every non-null winner has at least two independent supporting passes;\n   - every competing candidate has a resolution or rejection reason;\n   - every next-line winner has verified label-value pairing; and\n   - the reopened final artifact exactly matches the audited winners.\n\nAt minimum, make these invariants explicit in executable checks:\n\n```python\nassert audit_record_count == input_count * required_field_count\nassert single_pass_winner_count == 0\nassert unresolved_competing_candidate_count == 0\nassert unsafe_next_line_winner_count == 0\nassert artifact_rows == audited_rows\n```\n\nA schema check, non-null check, or spot-check does not satisfy this gate. If any\nassertion fails, resume targeted OCR or adjudication; the task is not complete.\n\n## When to Use\n- Extracting text from scanned documents or photos\n- Reading text from screenshots or image captures\n- Processing batch image files that contain textual information\n- Converting visual documents to machine-readable text\n- Extracting structured data from forms, receipts, or tables in images\n\n## Required Libraries\n\nThe following Python libraries are required:\n\n```python\nimport pytesseract\nfrom PIL import Image\nimport json\nimport os\n```\n\n## Input Requirements\n- **File formats**: JPG, JPEG, PNG, WEBP\n- **Image quality**: Minimum 300 DPI recommended for printed text; clear and legible text\n- **File size**: Under 5MB per image (resize if necessary)\n- **Text language**: Specify if non-English to improve accuracy\n\n## Output Schema\nAll extracted content must be returned as valid JSON conforming to this schema:\n\n```json\n{\n  \"success\": true,\n  \"filename\": \"example.jpg\",\n  \"extracted_text\": \"Full raw text extracted from the image...\",\n  \"confidence\": \"high|medium|low\",\n  \"metadata\": {\n    \"language_detected\": \"en\",\n    \"text_regions\": 3,\n    \"has_tables\": false,\n    \"has_handwriting\": false\n  },\n  \"warnings\": [\n    \"Text partially obscured in bottom-right corner\",\n    \"Low contrast detected in header section\"\n  ]\n}\n```\n\n\n### Field Descriptions\n\n- `success`: Boolean indicating whether text extraction completed\n- `filename`: Original image filename\n- `extracted_text`: Complete text content in reading order (top-to-bottom, left-to-right)\n- `confidence`: Overall OCR confidence level based on image quality and text clarity\n- `metadata.language_detected`: ISO 639-1 language code\n- `metadata.text_regions`: Number of distinct text blocks identified\n- `metadata.has_tables`: Whether tabular data structures were detected\n- `metadata.has_handwriting`: Whether handwritten text was detected\n- `warnings`: Array of quality issues or potential errors\n\n\n## Code Examples\n\n### Basic OCR Extraction\n\n```python\nimport pytesseract\nfrom PIL import Image\n\ndef extract_text_from_image(image_path):\n    \"\"\"Extract text from a single image using Tesseract OCR.\"\"\"\n    img = Image.open(image_path)\n    text = pytesseract.image_to_string(img)\n    return text.strip()\n```\n\n### OCR with Confidence Data\n\n```python\nimport pytesseract\nfrom PIL import Image\n\ndef extract_with_confidence(image_path):\n    \"\"\"Extract text with per-word confidence scores.\"\"\"\n    img = Image.open(image_path)\n\n    # Get detailed OCR data including confidence\n    data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)\n\n    words = []\n    confidences = []\n\n    for i, word in enumerate(data['text']):\n        if word.strip():  # Skip empty strings\n            words.append(word)\n            confidences.append(data['conf'][i])\n\n    # Calculate average confidence\n    avg_confidence = sum(c for c in confidences if c > 0) \u002F len([c for c in confidences if c > 0]) if confidences else 0\n\n    return {\n        'text': ' '.join(words),\n        'average_confidence': avg_confidence,\n        'word_count': len(words)\n    }\n```\n\n### Full OCR with JSON Output\n\n```python\nimport pytesseract\nfrom PIL import Image\nimport json\nimport os\n\ndef ocr_to_json(image_path):\n    \"\"\"Perform OCR and return results as JSON.\"\"\"\n    filename = os.path.basename(image_path)\n    warnings = []\n\n    try:\n        img = Image.open(image_path)\n\n        # Get detailed OCR data\n        data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)\n\n        # Extract text preserving structure\n        text = pytesseract.image_to_string(img)\n\n        # Calculate confidence\n        confidences = [c for c in data['conf'] if c > 0]\n        avg_conf = sum(confidences) \u002F len(confidences) if confidences else 0\n\n        # Determine confidence level\n        if avg_conf >= 80:\n            confidence = \"high\"\n        elif avg_conf >= 50:\n            confidence = \"medium\"\n        else:\n            confidence = \"low\"\n            warnings.append(f\"Low OCR confidence: {avg_conf:.1f}%\")\n\n        # Count text regions (blocks)\n        block_nums = set(data['block_num'])\n        text_regions = len([b for b in block_nums if b > 0])\n\n        result = {\n            \"success\": True,\n            \"filename\": filename,\n            \"extracted_text\": text.strip(),\n            \"confidence\": confidence,\n            \"metadata\": {\n                \"language_detected\": \"en\",\n                \"text_regions\": text_regions,\n                \"has_tables\": False,\n                \"has_handwriting\": False\n            },\n            \"warnings\": warnings\n        }\n\n    except Exception as e:\n        result = {\n            \"success\": False,\n            \"filename\": filename,\n            \"extracted_text\": \"\",\n            \"confidence\": \"low\",\n            \"metadata\": {\n                \"language_detected\": \"unknown\",\n                \"text_regions\": 0,\n                \"has_tables\": False,\n                \"has_handwriting\": False\n            },\n            \"warnings\": [f\"OCR failed: {str(e)}\"]\n        }\n\n    return result\n\n# Usage\nresult = ocr_to_json(\"document.jpg\")\nprint(json.dumps(result, indent=2))\n```\n\n### Batch Processing Multiple Images\n\n```python\nimport pytesseract\nfrom PIL import Image\nimport json\nimport os\nfrom pathlib import Path\n\ndef process_image_directory(directory_path, output_file):\n    \"\"\"Process all images in a directory and save results.\"\"\"\n    image_extensions = {'.jpg', '.jpeg', '.png', '.webp'}\n    results = []\n\n    for file_path in sorted(Path(directory_path).iterdir()):\n        if file_path.suffix.lower() in image_extensions:\n            result = ocr_to_json(str(file_path))\n            results.append(result)\n            print(f\"Processed: {file_path.name}\")\n\n    # Save results\n    with open(output_file, 'w') as f:\n        json.dump(results, f, indent=2)\n\n    return results\n```\n\n### Checkpointed Batch OCR\n\nFor a batch whose OCR text feeds later parsing or file generation, use a\ncheckpointed pipeline with observable completion criteria:\n\n1. **Inventory** - Create one deterministic, sorted list of inputs and a status\n   record for every filename before OCR starts.\n2. **Acquire and checkpoint** - Run one baseline OCR pass per image. Immediately\n   append its raw text, OCR configuration, warnings, and terminal status to a\n   durable JSON\u002FJSONL cache. A resumed run processes only records without a\n   terminal status.\n3. **Parse the cache** - Treat cached OCR observations as the input to field\n   extraction. Parser, regular-expression, priority, and formatting changes rerun\n   against the cache rather than triggering another full OCR batch.\n4. **Escalate selectively** - Send only images with missing, conflicting, or\n   structurally invalid required fields to a bounded multi-pass retry. Append every\n   retry observation and its provenance to the same cache.\n5. **Measure progress** - After each image, report the completed count and current\n   filename. Repeated polls with no new output and no increase in completed records\n   trigger termination of that attempt followed by resume from the checkpoint.\n6. **Materialize separately** - Build the requested artifact from normalized cached\n   records in a short, deterministic command. Represent unresolved fields using the\n   task's required null or error value so one image cannot block batch delivery.\n7. **Gate completion** - Finish only after every inventoried input has a terminal\n   status and the exact requested artifact exists, reopens successfully, and meets\n   its required schema and ordering.\n\n\n## Tesseract Configuration Options\n\n### Language Selection\n\n```python\n# Specify language (default is English)\ntext = pytesseract.image_to_string(img, lang='eng')\n\n# Multiple languages\ntext = pytesseract.image_to_string(img, lang='eng+fra+deu')\n```\n\n### Page Segmentation Modes (PSM)\n\nUse `--psm` to control how Tesseract segments the image:\n\n```python\n# PSM 3: Fully automatic page segmentation (default)\ntext = pytesseract.image_to_string(img, config='--psm 3')\n\n# PSM 4: Assume single column of text\ntext = pytesseract.image_to_string(img, config='--psm 4')\n\n# PSM 6: Assume uniform block of text\ntext = pytesseract.image_to_string(img, config='--psm 6')\n\n# PSM 11: Sparse text - find as much text as possible\ntext = pytesseract.image_to_string(img, config='--psm 11')\n```\n\nCommon PSM values:\n- `0`: Orientation and script detection (OSD) only\n- `3`: Fully automatic page segmentation (default)\n- `4`: Single column of text of variable sizes\n- `6`: Uniform block of text\n- `7`: Single text line\n- `11`: Sparse text\n- `13`: Raw line\n\n\n## Image Preprocessing\n\nFor better OCR accuracy, preprocess images:\n\n```python\nfrom PIL import Image, ImageFilter, ImageOps\n\ndef preprocess_image(image_path):\n    \"\"\"Preprocess image for better OCR results.\"\"\"\n    img = Image.open(image_path)\n\n    # Convert to grayscale\n    img = img.convert('L')\n\n    # Increase contrast\n    img = ImageOps.autocontrast(img)\n\n    # Apply slight sharpening\n    img = img.filter(ImageFilter.SHARPEN)\n\n    return img\n\n# Use preprocessed image for OCR\nimg = preprocess_image(\"document.jpg\")\ntext = pytesseract.image_to_string(img)\n```\n\n### Advanced Preprocessing Strategies\n\nFor difficult images (low contrast, faded text, dark backgrounds), try multiple preprocessing approaches:\n\n1. **Grayscale + Autocontrast** - Basic enhancement for most images\n2. **Inverted** - Use `ImageOps.invert()` for dark backgrounds with light text\n3. **Scaling** - Upscale small images (e.g., 2x) before OCR to improve character recognition\n4. **Thresholding** - Convert to binary using `img.point(lambda p: 255 if p > threshold else 0)` with different threshold values (e.g., 100, 128)\n5. **Sharpening** - Apply `ImageFilter.SHARPEN` to improve edge clarity\n\n\n## Multi-Pass OCR Strategy\n\nFor exact structured dates or monetary amounts, run at least two independent OCR\npasses for every required field even when the baseline looks syntactically valid.\nFor ordinary free-text extraction, additional passes may remain selective. Preserve\neach pass as a separate observation so downstream extraction can resolve fields\nindependently:\n\n1. **Try a bounded set of PSM modes** - Different page segmentation modes work\n   better for different layouts (for example, `--psm 6` for blocks, `--psm 4`\n   for columns, and `--psm 11` for sparse text).\n2. **Try a bounded set of preprocessing variants** - Run OCR on selected\n   preprocessed versions of the difficult image.\n3. **Keep provenance** - Store the text together with its preprocessing variant\n   and PSM mode. Preserve line or bounding-box context when it is available.\n4. **Resolve per field** - Select each target field using field-local evidence:\n   label proximity, required keyword priority, valid format and range, layout\n   context, and agreement across passes. Whole-page average confidence is a broad\n   quality signal; it is not a valid reason to select one pass for every field.\n5. **Expose unresolved conflicts** - When evidence cannot distinguish competing\n   candidates, use the task's specified null\u002Ferror representation and record the\n   conflict instead of inventing a value or concatenating unrelated pass text.\n\n```python\ndef multi_pass_ocr(image_path):\n    \"\"\"Return bounded OCR observations with their provenance.\"\"\"\n    img = Image.open(image_path)\n    gray = ImageOps.grayscale(img)\n\n    # Generate preprocessing variants\n    variants = [\n        (\"autocontrast\", ImageOps.autocontrast(gray)),\n        (\"inverted\", ImageOps.invert(ImageOps.autocontrast(gray))),\n        (\"sharpened\", gray.filter(ImageFilter.SHARPEN)),\n    ]\n\n    # PSM modes to try\n    psm_modes = ['--psm 6', '--psm 4', '--psm 11']\n\n    observations = []\n    for variant_name, variant in variants:\n        for psm in psm_modes:\n            try:\n                text = pytesseract.image_to_string(variant, config=psm)\n                if text.strip():\n                    observations.append({\n                        \"variant\": variant_name,\n                        \"psm\": psm,\n                        \"text\": text,\n                    })\n            except Exception:\n                pass\n\n    return observations\n```\n\nParse these observations into per-field candidates and retain the winning\ncandidate's provenance. This approach improves extraction for receipts, faded\ndocuments, and images with varying quality without allowing a high-confidence\nregion elsewhere on the page to override the evidence for a target field.\n\n### Semantic Adjudication for Monetary Totals\n\nWhen several OCR lines contain plausible monetary totals, determine the target\nfield from label semantics before applying confidence, frequency, magnitude, or\npage-position heuristics:\n\n1. **Normalize labels before matching** - Compare labels case-insensitively and\n   tolerate OCR changes in whitespace, punctuation, and hyphenation. Keep the\n   original line and its coordinates as provenance.\n2. **Apply task exclusions as hard constraints** - If the task excludes labels\n   such as subtotal, tax, GST, discount, change, or tendered cash, remove those\n   candidates before ranking. A line containing a preferred word such as\n   `TOTAL` does not override an exclusion on the same line.\n3. **Prefer the final payable stage within the allowed keyword group** - First\n   honor the task's stated keyword-group order. Within the selected group, an\n   explicitly adjusted, after-adjustment, rounded, amount-due, balance-due, or\n   grand total supersedes an earlier sales total or intermediate calculation.\n   Preserve the document's calculation sequence when valid labels conflict.\n4. **Do not let repetition decide semantics** - Cross-pass agreement can\n   support an already valid candidate, but a repeated subtotal or tax-summary\n   value must not outrank a single value attached to the correct final-total\n   label. Frequency is at most a tie-breaker within the same semantic class.\n5. **Do not select by largest or last number alone** - A line can contain a\n   taxable base, tax amount, paid amount, or change alongside a total label.\n   Associate the value with its label using line structure and bounding-box\n   proximity; unresolved multi-number lines require targeted re-OCR or a null\n   result rather than an arbitrary maximum or final token.\n6. **Audit the winner before materialization** - Record the winning value,\n   normalized label, original OCR line, pass provenance, rejected competing\n   candidates, and the rule that resolved the conflict. Recheck any winner\n   whose supporting line violates an exclusion or belongs to an earlier stage\n   of the receipt calculation.\n\n### Implementation Gate for Receipt-Total Parsers\n\nThe preceding semantic rules must be visible in the implemented parser and its\nsaved evidence. A generic keyword loop or a final workbook schema check is not\nan acceptable substitute. Apply this gate whenever OCR text contains more than\none occurrence of a word such as `TOTAL` or `AMOUNT`:\n\n1. **Enumerate before choosing** - Scan the complete receipt observation and\n   collect every plausible monetary candidate before returning a value. Never\n   return on the first keyword match. A later final-payment line must remain\n   eligible to supersede an earlier table heading or intermediate calculation.\n2. **Reject table headings explicitly** - Treat lines containing structural\n   column terms such as `QTY`, `ITEM`, `DESCRIPTION`, `UNIT PRICE`, or `PRICE`\n   as table headings unless the amount is explicitly attached to a standalone\n   payable label. The presence of the token `TOTAL` in a heading does not make\n   the following item row a receipt total.\n3. **Restrict next-line fallback** - Read an amount from the following line only\n   when the label line is an independent payable-field label after normalized\n   punctuation and whitespace are removed, and the next line contains only the\n   associated currency\u002Fvalue tokens. Do not use this fallback for column\n   headings, prose, item descriptions, cash received, tendered, change, payment,\n   or lines that mix unrelated fields.\n4. **Assign a semantic stage** - Store a semantic class for each eligible\n   candidate, such as final adjusted or rounded payable, amount or balance due,\n   grand total, generic total, or earlier sales\u002Fintermediate total. Apply the\n   task's exclusions first, then choose the most final eligible calculation\n   stage. OCR frequency is allowed only as a last tie-breaker among candidates\n   in the same semantic class.\n5. **Preserve candidate evidence** - For every candidate retain the filename,\n   OCR pass, raw line, normalized label, line or bounding-box location, parsed\n   amount, semantic class, and any rejection reason. If the parser cannot\n   explain why the winner outranks each competing candidate, the field remains\n   unresolved and receives targeted OCR instead of a guessed value.\n6. **Validate behavior, not only shape** - Before writing the final artifact,\n   inspect the candidate audit for every input with competing totals. Confirm\n   that no excluded candidate, table-heading fallback, first-match shortcut, or\n   cross-class frequency vote selected the winner. A schema\u002Forder check alone\n   does not satisfy completion.\n\nA compliant selection routine follows this structure:\n\n```python\ncandidates = collect_all_candidates(observations)\neligible = [candidate for candidate in candidates if not candidate.excluded]\n\nif not eligible:\n    winner = None\nelse:\n    best_stage = min(candidate.semantic_rank for candidate in eligible)\n    finalists = [\n        candidate for candidate in eligible\n        if candidate.semantic_rank == best_stage\n    ]\n    # Agreement may break a tie only after semantic filtering.\n    winner = resolve_same_stage(finalists)\n\nsave_candidate_audit(candidates, winner)\n```\n\nDo not replace this structure with `first match`, `last number`, `largest\nnumber`, or unrestricted majority-vote shortcuts.\n\n\n## Error Handling\n\n### Common Issues and Solutions\n\n**Issue**: Tesseract not found\n\n```python\n# Verify Tesseract is installed\ntry:\n    pytesseract.get_tesseract_version()\nexcept pytesseract.TesseractNotFoundError:\n    print(\"Tesseract is not installed or not in PATH\")\n```\n\n**Issue**: Poor OCR quality\n\n- Preprocess image (grayscale, contrast, sharpen)\n- Use appropriate PSM mode for the document type\n- Ensure image resolution is sufficient (300+ DPI)\n\n**Issue**: Empty or garbage output\n\n- Check if image contains actual text\n- Try different PSM modes\n- Verify image is not corrupted\n\n\n## Quality Self-Check\n\nBefore returning results, verify:\n\n- [ ] Output is valid JSON (use `json.loads()` to validate)\n- [ ] All required fields are present (`success`, `filename`, `extracted_text`, `confidence`, `metadata`)\n- [ ] Text preserves logical reading order\n- [ ] Confidence level reflects actual OCR quality\n- [ ] Warnings array includes all detected issues\n- [ ] Special characters are properly escaped in JSON\n- [ ] Every batch input has a terminal status in the checkpoint\n- [ ] Required fields were resolved independently with candidate provenance\n- [ ] Every non-null exact date and monetary amount is supported by at least two\n      materially different OCR passes over the same source region\n- [ ] Every cross-pass disagreement triggered targeted OCR and semantic review\n- [ ] Task-defined monetary exclusions were applied before candidate ranking\n- [ ] Monetary conflicts were resolved by label semantics and calculation stage,\n      not by frequency, magnitude, or last-number shortcuts\n- [ ] The parser scanned the complete observation before selecting a monetary\n      value and rejected table-heading and unsafe next-line fallbacks\n- [ ] A candidate audit records the winner, semantic stage, competing values,\n      and rejection reasons for every receipt with conflicting totals\n- [ ] Missing or conflicting fields use the task's specified null\u002Ferror value\n- [ ] The exact requested final artifact exists, reopens, and has the required schema\n\n\n## Limitations\n\n- Tesseract works best with printed text; handwriting recognition is limited\n- Accuracy decreases with decorative fonts, artistic text, or extreme stylization\n- Mathematical equations and special notation may not extract accurately\n- Redacted or watermarked text cannot be recovered\n- Severe image degradation (blur, noise, low resolution) reduces accuracy\n- Complex multi-column layouts may require custom PSM configuration\n\n\n## Version History\n\n- **1.1.0** (2026-09-12): Added a blocking multi-pass evidence and audit gate for exact structured date and monetary extraction\n- **1.0.0** (2026-01-13): Initial release with Tesseract\u002Fpytesseract OCR\n","# Round 11 mandatory total freeze-and-recovery gate\n\nThis addendum is deliberately narrow. It changes only the **last adjudication\nof `total_amount`** on top of the established Round 5 workflow. It must not be\nused as permission to redesign OCR acquisition, date parsing, clustering, or\nthe general candidate parser.\n\n## 1. Acquisition is frozen\n\nFor full-page OCR, keep the established bounded Round 5 acquisition only:\n\n- the existing original \u002F contrast-or-sharpened \u002F thresholded variants;\n- full-page PSM 6 and 11 only;\n- targeted OCR, when genuinely unresolved, may use the already-established\n  crop PSMs 6 \u002F 7 \u002F 11.\n\nDo **not** add PSM 4 or any other full-page PSM. Do not add another\npreprocessing variant, threshold sweep, scale sweep, generic OCR retry, looser\nmoney regex, new date heuristic, or new global region\u002Fcluster definition.\n\nThis is a blocking implementation invariant. If the implementation changes the\nfull-page acquisition set or date adjudication in order to solve a total\ndispute, revert that change before continuing.\n\n## 2. Freeze a resolved baseline before any targeted total retry\n\nAfter the bounded full-page evidence has been collected, run the ordinary\nRound 5 semantic selection once and snapshot:\n\n```text\nbaseline_winner\nbaseline_support_rows\nbaseline_support_pass_ids\n```\n\nIf `baseline_winner` is non-null and has the normal independent same-region\nsupport required by Round 5, it is **frozen**.\n\nFor that receipt:\n\n- do not run targeted OCR for `total_amount` merely to seek a different value;\n- do not recompute it under a new cluster key;\n- do not let later confidence\u002Fsupport counts or a semantic-rank mutation\n  replace it;\n- do not call a generic total winner selector again after final adjudication.\n\nTargeted total OCR is allowed only when the bounded full-page baseline is\nactually unresolved (`baseline_winner is None`). Date handling is independent\nand must not be changed by this addendum.\n\n## 3. Absolute non-payable exclusions remain in force\n\nNever select `CASH`, cash tendered\u002Freceived, `CHANGE`, payment\u002Fcard rows,\n`SUBTOTAL` \u002F `SUB TOTAL`, tax-only\u002FGST\u002FSST summary rows, item amounts,\nquantities, unit prices, or table headers as the final payable amount.\n\nHowever, an excluded earlier accounting row may be used only as **local\ncorroborating evidence** for the digits of a later explicit final-payable row;\nit does not itself become the selected total.\n\nDo not reject genuine payable labels such as `TOTAL RM INCLUDING GST` merely\nbecause the phrase contains GST.\n\n## 4. Decimal punctuation is mandatory for a selected value\n\nA digits-only OCR token such as `1000` cannot establish whether the source is\n`1000`, `100.0`, or `10.00`. It may corroborate the digit sequence of an\nalready decimal-preserving read from the **same row\u002Fregion**, but it cannot\ncreate a monetary value or determine decimal placement.\n\nAny selected or replacement total therefore needs at least one existing OCR\nobservation of the correct payable row that preserves a decimal mark (dot or\ndecimal comma).\n\n## 5. Null-baseline recovery from an explicit final row\n\nIf and only if `baseline_winner is None`, the final gate may recover a value\nfrom evidence already collected by the bounded workflow.\n\nLet `F` be an explicit final-payable row such as `GRAND TOTAL`, `TOTAL DUE`,\n`AMOUNT DUE`, `BALANCE DUE`, `TOTAL AFTER ROUNDING`, `ROUNDED TOTAL`,\n`NET TOTAL`, or equivalent. A single decimal-preserving read of `F` may be\naccepted even when row-local clustering leaves it with support 1, but only when\n**all** of the following hold:\n\n1. there is no different decimal-preserving eligible final-payable competitor\n   in the same settlement block;\n2. the value of `F` is corroborated locally by at least one independent\n   observation, for example:\n   - the same normalized value on an earlier payable\u002Faccounting row in the\n     same settlement block; or\n   - a digits-only read of the same `F` row\u002Fregion whose digit sequence matches\n     `F` after punctuation is removed; or\n   - an explicit local adjustment equation leading to `F`;\n3. no credible non-zero adjustment or later payable row contradicts `F`.\n\nThis rule is specifically a **null recovery rule**. It must not be used to\nreplace an already stable non-null baseline.\n\n## 6. Local settlement replacement rules\n\nFor a frozen non-null baseline `A`, a different later final value `F` may\nreplace it only if one of these proofs exists in the same local settlement\nblock:\n\n1. `F` itself has at least two materially different decimal-preserving OCR\n   passes in the same final row\u002Fregion; or\n2. there is an explicit signed adjustment `R` and\n   `Decimal(A) + Decimal(R) == Decimal(F)` within one cent.\n\nA single promoted final row, later page position, larger support count,\nconfidence change, or semantic-rank change is not sufficient.\n\n## 7. One-cent mutation veto\n\nIf a proposed later value differs from a stable `baseline_winner` by exactly\n`0.01`, treat that as a disputed OCR digit, not an automatic rounding event.\n\nKeep the baseline unless the same local settlement block contains either:\n\n- an explicit non-zero rounding\u002Fadjustment row whose arithmetic explains that\n  exact one-cent change; or\n- at least two materially different decimal-preserving reads of the later\n  final row agreeing on the changed value.\n\nWithout one of those proofs, the one-cent mutation is vetoed and the baseline\nremains final.\n\n## 8. Irreversible pre-write audit\n\nImmediately before writing `stat_ocr.xlsx`, persist for every receipt:\n\n```text\nbaseline_winner\nfinal_winner\ndecision = freeze_baseline | recover_explicit_final |\n           direct_final_support | arithmetic_settlement | cent_mutation_veto\nsupporting local evidence rows\u002Fpass ids\nrejected competing final values and reasons\n```\n\nAfter this audit decision, `final_winner` is immutable. Write the workbook from\nthat value and compare workbook readback against the same frozen audit value.\nDo not run another generic selector afterward.\n\n## 9. Scope guard\n\nThe intended implementation change is only:\n\n```text\nunchanged Round 5 bounded evidence\n    -> freeze resolved baseline\n    -> if null, recover only from explicit local final evidence\n    -> if replacement proposed, require settlement proof and apply cent veto\n    -> immutable final_winner\n    -> workbook write\u002Freadback\n```\n\nNever hard-code a filename, expected date, or expected amount.\n\n# Round 5 mandatory receipt-field adjudication gate\n\nFor receipt OCR tasks that require an exact `date` and `total_amount` per image,\nthis block overrides weaker or more permissive advice below. Treat it as an\nexecution contract. Do not finish merely because an Excel file exists or every\nrow is non-null.\n\n## A. Run bounded full-page OCR once, then cache it\n\n1. Enumerate all receipt images in deterministic filename order.\n2. For every image run a small fixed set of materially different full-page OCR\n   passes (for example original\u002Fgrayscale, contrast or sharpened, and thresholded;\n   use useful PSM variants). Persist each pass's text **and token boxes** once.\n3. Parse all field candidates from that cache. Never rerun the entire image set\n   just because one parser rule changes.\n4. After the cached full-page passes, additional OCR is allowed only for images\n   and fields whose evidence is unresolved or conflicting.\n\nUse `pytesseract.image_to_data(..., output_type=Output.DICT)` or an equivalent\nbox-producing API in addition to plain text OCR. Whole-page mean confidence is\nnot a valid reason to discard all candidates from another pass.\n\n## B. Keep a field-level evidence ledger\n\nFor every `(filename, field)` pair, where `field` is `date` or `total_amount`,\npersist candidate evidence with at least:\n\n```\nfilename, field, pass_id, raw_line, normalized_label, semantic_class,\nbbox_or_row_region, raw_candidate, normalized_candidate, confidence,\neligible, rejection_reason\n```\n\nThe final selection must be reproducible from this ledger. Never reduce the\nevidence to only `value -> number_of_passes`.\n\nTwo passes support one another only when they read the **same semantic field in\nthe same source region**. The same number occurring elsewhere on the receipt is\nnot supporting evidence. Group candidates by page-local row\u002Fbox geometry and\nfield meaning before counting cross-pass agreement.\n\n## C. Amount semantics: enumerate before selecting\n\nFor `total_amount`, collect all plausible amount candidates from every cached\npass before choosing a winner. Apply these rules in this order:\n\n1. Reject lines containing task exclusion concepts such as `SUBTOTAL`,\n   `SUB TOTAL`, `TAX`, `GST`, `SST`, `DISCOUNT`, `CHANGE`, or `CASH TENDERED`.\n2. Reject product\u002Ftable headings such as `QTY ITEM TOTAL`, `ITEM ... TOTAL`, or\n   another line where `TOTAL` is a column header rather than a payable field.\n3. Prefer explicit final-payment semantics (`GRAND TOTAL`, `TOTAL RM`,\n   `TOTAL AMOUNT`, `TOTAL DUE`, `AMOUNT DUE`, `BALANCE DUE`, `NETT TOTAL`,\n   `NET TOTAL`) over a generic `TOTAL` occurrence.\n4. Distinguish intermediate sales totals from a later adjustment\u002Frounding\u002Ffinal\n   payable stage. A `TOTAL SALES` or similar earlier accounting stage must not\n   outrank a later clearly final\u002Fadjusted payable amount merely because it is\n   easier to OCR or appears in more passes.\n5. Never select `amounts[-1]`, the largest amount, the most frequent number, or\n   the first legal match as a substitute for semantic adjudication.\n\n### Safe next-line fallback\n\nUse the task's next-line fallback only if the current line is a **standalone\npayable-field label**. The next line must be locally adjacent, aligned with the\nfield's value region, and contain only a plausible currency\u002Fvalue token rather\nthan an item description, quantity, unit price, tendered amount, change, or a\nnew field label. Record the label\u002Fvalue boxes proving the pairing.\n\n## D. Decimal placement is evidence, not formatting\n\nDo not let numeric whitelists or normalization silently destroy monetary\npunctuation. A digits-only pass that reads `1000` cannot by itself prove whether\nthe source is `1000`, `100.0`, or `10.00`. It may support the digit sequence,\nbut decimal placement must be confirmed by a pass\u002Fcrop that preserves\npunctuation or by clear same-region visual\u002FOCR evidence.\n\nKeep the raw candidate string. Remove thousands separators only after the\ndecimal mark is established. Use `Decimal` for normalization and format the\naccepted final amount to exactly two decimal places only **after** the source\nvalue is adjudicated. Never append\u002Fremove digits merely to make a plausible\ncurrency value.\n\n## E. Date parsing must preserve token order\n\nCollect every date candidate across passes before selecting. Do not return the\nfirst syntactically valid date and do not let a parser silently choose MDY\u002FDMY\nfor an ambiguous slash date.\n\nFor each candidate keep the raw text and component order. Determine the date\nconvention from explicit labels\u002Fcontext and, where needed, unambiguous dates or\nconsistent formatting evidence. Once a convention is established for that\nreceipt\u002Fcontext, apply it explicitly. A disagreement in day, month, **or year**\nbetween passes makes the field disputed and triggers targeted OCR.\n\n## F. Every disagreement must trigger targeted OCR\n\nA field is disputed if any of these holds:\n\n- same-region passes produce different normalized values;\n- only one usable pass supports a candidate;\n- two different semantic candidates remain eligible;\n- decimal placement differs or disappears between passes;\n- a date component differs between passes;\n- a next-line fallback lacks strong local pairing evidence;\n- OCR confidence\u002Ffragmentation makes any digit uncertain.\n\nFor every disputed field, stop broad OCR and make targeted crops around the\nfield's label\u002Fvalue row. Use both:\n\n- a **tight value crop** to improve digit recognition; and\n- a **wider context crop** that retains the label and neighboring lines so the\n  number's semantic ownership is visible.\n\nUpscale the crops (2x minimum; 3x\u002F4x when useful), try materially different\npreprocessing, and use appropriate PSMs such as 6\u002F7\u002F11. A numeric whitelist is\nan auxiliary pass, not authoritative evidence for punctuation. Add every\ntargeted result to the same ledger.\n\nPrinting a disagreement table is not resolution. Each disputed ledger row must\ncause an actual targeted retry and finish with a winner or an explicit reject\nreason for each competing candidate.\n\n## G. Blocking pre-write audit\n\nBefore creating `stat_ocr.xlsx`, build one compact final audit row per input\nimage containing:\n\n```\nfilename | selected date | date evidence regions\u002Fpasses |\nselected total | total evidence regions\u002Fpasses | rejected alternatives | status\n```\n\nProgrammatically enforce at least:\n\n```python\nassert audit_filename_set == input_filename_set\nassert unresolved_field_count == 0\nassert single_pass_non_null_winner_count == 0\nassert cross_region_consensus_count == 0\nassert unresolved_competing_candidate_count == 0\nassert unsafe_next_line_winner_count == 0\n```\n\nIf one fails, continue **only** with the unresolved images\u002Ffields. Do not rerun\nalready-resolved images and do not write the final workbook yet.\n\n## H. Exact artifact contract and readback\n\nAfter the field audit passes:\n\n1. create exactly one sheet named `results`;\n2. write exactly the columns `filename`, `date`, `total_amount`;\n3. sort data rows by filename and include exactly one row for every input image;\n4. write dates as ISO `YYYY-MM-DD` strings (or null only when genuinely\n   unresolved according to the task contract);\n5. write accepted monetary values as strings with exactly two decimal places;\n6. save to the exact required path `\u002Fapp\u002Fworkspace\u002Fstat_ocr.xlsx`;\n7. reopen that saved workbook and read every cell back;\n8. compare the readback programmatically to the adjudicated audit rows and the\n   exact sheet\u002Fheader\u002Forder constraints.\n\nOnly the reopened workbook matching the adjudicated evidence is completion.\n\n## I. Completion-budget discipline\n\nOnce a `(filename, field)` has strong same-region evidence, freeze it. Spend\nremaining OCR\u002Ftool calls only on disputed fields. The intended workflow is:\n\n`bounded cached batch -> field ledger -> targeted retries -> audit -> one write -> readback`.\n\nDo not regress to repeated whole-dataset OCR commands during parser iteration or\nfinal workbook creation.\n\n# Image OCR Skill\n\n## Purpose\nThis skill enables accurate text extraction from image files (JPG, PNG, etc.) using Tesseract OCR via the `pytesseract` Python library. It is suitable for scanned documents, screenshots, photos of text, receipts, forms, and other visual content containing text.\n\n## Blocking Evidence Gate for Exact Structured Fields\n\nWhen OCR values will be written into a table, database, or other artifact that\nrequires exact dates or monetary amounts, the following rules are mandatory.\nThey are execution requirements, not optional quality suggestions. Do not\nmaterialize the artifact or finish the task until the programmatic gate passes.\n\n1. **Verify every resolved field independently** - Every non-null date and\n   monetary amount must have the same normalized value, field meaning, and\n   supporting source region in at least two materially different OCR passes.\n   Change preprocessing, segmentation mode, scale, or crop; repeating the same\n   pixels and configuration is not independent evidence. A syntactically valid\n   value from one pass remains an unverified candidate.\n2. **Collect before selecting** - Complete the required passes and enumerate all\n   field candidates before choosing a winner. Never select the first legal date,\n   first keyword match, first non-null pass, largest number, or final numeric\n   token merely because it is available.\n3. **Escalate every disagreement** - If independent passes disagree in any date\n   component or monetary digit, run at least one targeted crop or alternative\n   segmentation pass over that field. If bounded retries still do not establish\n   independent agreement within the correct semantic class, emit the task's\n   null\u002Ferror representation instead of guessing.\n4. **Use safe line pairing** - A next-line amount is eligible only when the\n   current line is a standalone target-field label and spatial evidence or a\n   targeted crop confirms that the adjacent line is its value. The adjacent line\n   must contain only currency\u002Fvalue tokens. Reject it if it contains an item,\n   description, quantity, price, cash received, tendered, change, payment, or\n   another field label.\n5. **Adjudicate semantics before agreement** - Apply the task's exclusions and\n   keyword groups before counting cross-pass agreement. Within the same allowed\n   keyword group, a final adjusted, after-adjustment, rounded, amount-due,\n   balance-due, or grand-total stage outranks an earlier sales total and any\n   tendered\u002Fpayment value. For dates, collect every date candidate across the\n   receipt and all passes; use the requested field meaning, label proximity,\n   region, and cross-pass agreement rather than returning the first valid date.\n6. **Persist the candidate audit first** - For every input and required field,\n   save the pass identifier\u002Fconfiguration, raw supporting line, location or crop,\n   normalized candidate, semantic class, eligibility or rejection reason,\n   selected winner, and the independent passes supporting it. Record unresolved\n   fields as well as successful fields.\n7. **Run a blocking completion audit** - The program must fail or continue OCR\n   unless all of these conditions hold:\n   - every input has an audit record for every required field;\n   - every non-null winner has at least two independent supporting passes;\n   - every competing candidate has a resolution or rejection reason;\n   - every next-line winner has verified label-value pairing; and\n   - the reopened final artifact exactly matches the audited winners.\n\nAt minimum, make these invariants explicit in executable checks:\n\n```python\nassert audit_record_count == input_count * required_field_count\nassert single_pass_winner_count == 0\nassert unresolved_competing_candidate_count == 0\nassert unsafe_next_line_winner_count == 0\nassert artifact_rows == audited_rows\n```\n\nA schema check, non-null check, or spot-check does not satisfy this gate. If any\nassertion fails, resume targeted OCR or adjudication; the task is not complete.\n\n## When to Use\n- Extracting text from scanned documents or photos\n- Reading text from screenshots or image captures\n- Processing batch image files that contain textual information\n- Converting visual documents to machine-readable text\n- Extracting structured data from forms, receipts, or tables in images\n\n## Required Libraries\n\nThe following Python libraries are required:\n\n```python\nimport pytesseract\nfrom PIL import Image\nimport json\nimport os\n```\n\n## Input Requirements\n- **File formats**: JPG, JPEG, PNG, WEBP\n- **Image quality**: Minimum 300 DPI recommended for printed text; clear and legible text\n- **File size**: Under 5MB per image (resize if necessary)\n- **Text language**: Specify if non-English to improve accuracy\n\n## Output Schema\nAll extracted content must be returned as valid JSON conforming to this schema:\n\n```json\n{\n  \"success\": true,\n  \"filename\": \"example.jpg\",\n  \"extracted_text\": \"Full raw text extracted from the image...\",\n  \"confidence\": \"high|medium|low\",\n  \"metadata\": {\n    \"language_detected\": \"en\",\n    \"text_regions\": 3,\n    \"has_tables\": false,\n    \"has_handwriting\": false\n  },\n  \"warnings\": [\n    \"Text partially obscured in bottom-right corner\",\n    \"Low contrast detected in header section\"\n  ]\n}\n```\n\n\n### Field Descriptions\n\n- `success`: Boolean indicating whether text extraction completed\n- `filename`: Original image filename\n- `extracted_text`: Complete text content in reading order (top-to-bottom, left-to-right)\n- `confidence`: Overall OCR confidence level based on image quality and text clarity\n- `metadata.language_detected`: ISO 639-1 language code\n- `metadata.text_regions`: Number of distinct text blocks identified\n- `metadata.has_tables`: Whether tabular data structures were detected\n- `metadata.has_handwriting`: Whether handwritten text was detected\n- `warnings`: Array of quality issues or potential errors\n\n\n## Code Examples\n\n### Basic OCR Extraction\n\n```python\nimport pytesseract\nfrom PIL import Image\n\ndef extract_text_from_image(image_path):\n    \"\"\"Extract text from a single image using Tesseract OCR.\"\"\"\n    img = Image.open(image_path)\n    text = pytesseract.image_to_string(img)\n    return text.strip()\n```\n\n### OCR with Confidence Data\n\n```python\nimport pytesseract\nfrom PIL import Image\n\ndef extract_with_confidence(image_path):\n    \"\"\"Extract text with per-word confidence scores.\"\"\"\n    img = Image.open(image_path)\n\n    # Get detailed OCR data including confidence\n    data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)\n\n    words = []\n    confidences = []\n\n    for i, word in enumerate(data['text']):\n        if word.strip():  # Skip empty strings\n            words.append(word)\n            confidences.append(data['conf'][i])\n\n    # Calculate average confidence\n    avg_confidence = sum(c for c in confidences if c > 0) \u002F len([c for c in confidences if c > 0]) if confidences else 0\n\n    return {\n        'text': ' '.join(words),\n        'average_confidence': avg_confidence,\n        'word_count': len(words)\n    }\n```\n\n### Full OCR with JSON Output\n\n```python\nimport pytesseract\nfrom PIL import Image\nimport json\nimport os\n\ndef ocr_to_json(image_path):\n    \"\"\"Perform OCR and return results as JSON.\"\"\"\n    filename = os.path.basename(image_path)\n    warnings = []\n\n    try:\n        img = Image.open(image_path)\n\n        # Get detailed OCR data\n        data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)\n\n        # Extract text preserving structure\n        text = pytesseract.image_to_string(img)\n\n        # Calculate confidence\n        confidences = [c for c in data['conf'] if c > 0]\n        avg_conf = sum(confidences) \u002F len(confidences) if confidences else 0\n\n        # Determine confidence level\n        if avg_conf >= 80:\n            confidence = \"high\"\n        elif avg_conf >= 50:\n            confidence = \"medium\"\n        else:\n            confidence = \"low\"\n            warnings.append(f\"Low OCR confidence: {avg_conf:.1f}%\")\n\n        # Count text regions (blocks)\n        block_nums = set(data['block_num'])\n        text_regions = len([b for b in block_nums if b > 0])\n\n        result = {\n            \"success\": True,\n            \"filename\": filename,\n            \"extracted_text\": text.strip(),\n            \"confidence\": confidence,\n            \"metadata\": {\n                \"language_detected\": \"en\",\n                \"text_regions\": text_regions,\n                \"has_tables\": False,\n                \"has_handwriting\": False\n            },\n            \"warnings\": warnings\n        }\n\n    except Exception as e:\n        result = {\n            \"success\": False,\n            \"filename\": filename,\n            \"extracted_text\": \"\",\n            \"confidence\": \"low\",\n            \"metadata\": {\n                \"language_detected\": \"unknown\",\n                \"text_regions\": 0,\n                \"has_tables\": False,\n                \"has_handwriting\": False\n            },\n            \"warnings\": [f\"OCR failed: {str(e)}\"]\n        }\n\n    return result\n\n# Usage\nresult = ocr_to_json(\"document.jpg\")\nprint(json.dumps(result, indent=2))\n```\n\n### Batch Processing Multiple Images\n\n```python\nimport pytesseract\nfrom PIL import Image\nimport json\nimport os\nfrom pathlib import Path\n\ndef process_image_directory(directory_path, output_file):\n    \"\"\"Process all images in a directory and save results.\"\"\"\n    image_extensions = {'.jpg', '.jpeg', '.png', '.webp'}\n    results = []\n\n    for file_path in sorted(Path(directory_path).iterdir()):\n        if file_path.suffix.lower() in image_extensions:\n            result = ocr_to_json(str(file_path))\n            results.append(result)\n            print(f\"Processed: {file_path.name}\")\n\n    # Save results\n    with open(output_file, 'w') as f:\n        json.dump(results, f, indent=2)\n\n    return results\n```\n\n### Checkpointed Batch OCR\n\nFor a batch whose OCR text feeds later parsing or file generation, use a\ncheckpointed pipeline with observable completion criteria:\n\n1. **Inventory** - Create one deterministic, sorted list of inputs and a status\n   record for every filename before OCR starts.\n2. **Acquire and checkpoint** - Run one baseline OCR pass per image. Immediately\n   append its raw text, OCR configuration, warnings, and terminal status to a\n   durable JSON\u002FJSONL cache. A resumed run processes only records without a\n   terminal status.\n3. **Parse the cache** - Treat cached OCR observations as the input to field\n   extraction. Parser, regular-expression, priority, and formatting changes rerun\n   against the cache rather than triggering another full OCR batch.\n4. **Escalate selectively** - Send only images with missing, conflicting, or\n   structurally invalid required fields to a bounded multi-pass retry. Append every\n   retry observation and its provenance to the same cache.\n5. **Measure progress** - After each image, report the completed count and current\n   filename. Repeated polls with no new output and no increase in completed records\n   trigger termination of that attempt followed by resume from the checkpoint.\n6. **Materialize separately** - Build the requested artifact from normalized cached\n   records in a short, deterministic command. Represent unresolved fields using the\n   task's required null or error value so one image cannot block batch delivery.\n7. **Gate completion** - Finish only after every inventoried input has a terminal\n   status and the exact requested artifact exists, reopens successfully, and meets\n   its required schema and ordering.\n\n\n## Tesseract Configuration Options\n\n### Language Selection\n\n```python\n# Specify language (default is English)\ntext = pytesseract.image_to_string(img, lang='eng')\n\n# Multiple languages\ntext = pytesseract.image_to_string(img, lang='eng+fra+deu')\n```\n\n### Page Segmentation Modes (PSM)\n\nUse `--psm` to control how Tesseract segments the image:\n\n```python\n# PSM 3: Fully automatic page segmentation (default)\ntext = pytesseract.image_to_string(img, config='--psm 3')\n\n# PSM 4: Assume single column of text\ntext = pytesseract.image_to_string(img, config='--psm 4')\n\n# PSM 6: Assume uniform block of text\ntext = pytesseract.image_to_string(img, config='--psm 6')\n\n# PSM 11: Sparse text - find as much text as possible\ntext = pytesseract.image_to_string(img, config='--psm 11')\n```\n\nCommon PSM values:\n- `0`: Orientation and script detection (OSD) only\n- `3`: Fully automatic page segmentation (default)\n- `4`: Single column of text of variable sizes\n- `6`: Uniform block of text\n- `7`: Single text line\n- `11`: Sparse text\n- `13`: Raw line\n\n\n## Image Preprocessing\n\nFor better OCR accuracy, preprocess images:\n\n```python\nfrom PIL import Image, ImageFilter, ImageOps\n\ndef preprocess_image(image_path):\n    \"\"\"Preprocess image for better OCR results.\"\"\"\n    img = Image.open(image_path)\n\n    # Convert to grayscale\n    img = img.convert('L')\n\n    # Increase contrast\n    img = ImageOps.autocontrast(img)\n\n    # Apply slight sharpening\n    img = img.filter(ImageFilter.SHARPEN)\n\n    return img\n\n# Use preprocessed image for OCR\nimg = preprocess_image(\"document.jpg\")\ntext = pytesseract.image_to_string(img)\n```\n\n### Advanced Preprocessing Strategies\n\nFor difficult images (low contrast, faded text, dark backgrounds), try multiple preprocessing approaches:\n\n1. **Grayscale + Autocontrast** - Basic enhancement for most images\n2. **Inverted** - Use `ImageOps.invert()` for dark backgrounds with light text\n3. **Scaling** - Upscale small images (e.g., 2x) before OCR to improve character recognition\n4. **Thresholding** - Convert to binary using `img.point(lambda p: 255 if p > threshold else 0)` with different threshold values (e.g., 100, 128)\n5. **Sharpening** - Apply `ImageFilter.SHARPEN` to improve edge clarity\n\n\n## Multi-Pass OCR Strategy\n\nFor exact structured dates or monetary amounts, run at least two independent OCR\npasses for every required field even when the baseline looks syntactically valid.\nFor ordinary free-text extraction, additional passes may remain selective. Preserve\neach pass as a separate observation so downstream extraction can resolve fields\nindependently:\n\n1. **Try a bounded set of PSM modes** - Different page segmentation modes work\n   better for different layouts (for example, `--psm 6` for blocks, `--psm 4`\n   for columns, and `--psm 11` for sparse text).\n2. **Try a bounded set of preprocessing variants** - Run OCR on selected\n   preprocessed versions of the difficult image.\n3. **Keep provenance** - Store the text together with its preprocessing variant\n   and PSM mode. Preserve line or bounding-box context when it is available.\n4. **Resolve per field** - Select each target field using field-local evidence:\n   label proximity, required keyword priority, valid format and range, layout\n   context, and agreement across passes. Whole-page average confidence is a broad\n   quality signal; it is not a valid reason to select one pass for every field.\n5. **Expose unresolved conflicts** - When evidence cannot distinguish competing\n   candidates, use the task's specified null\u002Ferror representation and record the\n   conflict instead of inventing a value or concatenating unrelated pass text.\n\n```python\ndef multi_pass_ocr(image_path):\n    \"\"\"Return bounded OCR observations with their provenance.\"\"\"\n    img = Image.open(image_path)\n    gray = ImageOps.grayscale(img)\n\n    # Generate preprocessing variants\n    variants = [\n        (\"autocontrast\", ImageOps.autocontrast(gray)),\n        (\"inverted\", ImageOps.invert(ImageOps.autocontrast(gray))),\n        (\"sharpened\", gray.filter(ImageFilter.SHARPEN)),\n    ]\n\n    # PSM modes to try\n    psm_modes = ['--psm 6', '--psm 4', '--psm 11']\n\n    observations = []\n    for variant_name, variant in variants:\n        for psm in psm_modes:\n            try:\n                text = pytesseract.image_to_string(variant, config=psm)\n                if text.strip():\n                    observations.append({\n                        \"variant\": variant_name,\n                        \"psm\": psm,\n                        \"text\": text,\n                    })\n            except Exception:\n                pass\n\n    return observations\n```\n\nParse these observations into per-field candidates and retain the winning\ncandidate's provenance. This approach improves extraction for receipts, faded\ndocuments, and images with varying quality without allowing a high-confidence\nregion elsewhere on the page to override the evidence for a target field.\n\n### Semantic Adjudication for Monetary Totals\n\nWhen several OCR lines contain plausible monetary totals, determine the target\nfield from label semantics before applying confidence, frequency, magnitude, or\npage-position heuristics:\n\n1. **Normalize labels before matching** - Compare labels case-insensitively and\n   tolerate OCR changes in whitespace, punctuation, and hyphenation. Keep the\n   original line and its coordinates as provenance.\n2. **Apply task exclusions as hard constraints** - If the task excludes labels\n   such as subtotal, tax, GST, discount, change, or tendered cash, remove those\n   candidates before ranking. A line containing a preferred word such as\n   `TOTAL` does not override an exclusion on the same line.\n3. **Prefer the final payable stage within the allowed keyword group** - First\n   honor the task's stated keyword-group order. Within the selected group, an\n   explicitly adjusted, after-adjustment, rounded, amount-due, balance-due, or\n   grand total supersedes an earlier sales total or intermediate calculation.\n   Preserve the document's calculation sequence when valid labels conflict.\n4. **Do not let repetition decide semantics** - Cross-pass agreement can\n   support an already valid candidate, but a repeated subtotal or tax-summary\n   value must not outrank a single value attached to the correct final-total\n   label. Frequency is at most a tie-breaker within the same semantic class.\n5. **Do not select by largest or last number alone** - A line can contain a\n   taxable base, tax amount, paid amount, or change alongside a total label.\n   Associate the value with its label using line structure and bounding-box\n   proximity; unresolved multi-number lines require targeted re-OCR or a null\n   result rather than an arbitrary maximum or final token.\n6. **Audit the winner before materialization** - Record the winning value,\n   normalized label, original OCR line, pass provenance, rejected competing\n   candidates, and the rule that resolved the conflict. Recheck any winner\n   whose supporting line violates an exclusion or belongs to an earlier stage\n   of the receipt calculation.\n\n### Implementation Gate for Receipt-Total Parsers\n\nThe preceding semantic rules must be visible in the implemented parser and its\nsaved evidence. A generic keyword loop or a final workbook schema check is not\nan acceptable substitute. Apply this gate whenever OCR text contains more than\none occurrence of a word such as `TOTAL` or `AMOUNT`:\n\n1. **Enumerate before choosing** - Scan the complete receipt observation and\n   collect every plausible monetary candidate before returning a value. Never\n   return on the first keyword match. A later final-payment line must remain\n   eligible to supersede an earlier table heading or intermediate calculation.\n2. **Reject table headings explicitly** - Treat lines containing structural\n   column terms such as `QTY`, `ITEM`, `DESCRIPTION`, `UNIT PRICE`, or `PRICE`\n   as table headings unless the amount is explicitly attached to a standalone\n   payable label. The presence of the token `TOTAL` in a heading does not make\n   the following item row a receipt total.\n3. **Restrict next-line fallback** - Read an amount from the following line only\n   when the label line is an independent payable-field label after normalized\n   punctuation and whitespace are removed, and the next line contains only the\n   associated currency\u002Fvalue tokens. Do not use this fallback for column\n   headings, prose, item descriptions, cash received, tendered, change, payment,\n   or lines that mix unrelated fields.\n4. **Assign a semantic stage** - Store a semantic class for each eligible\n   candidate, such as final adjusted or rounded payable, amount or balance due,\n   grand total, generic total, or earlier sales\u002Fintermediate total. Apply the\n   task's exclusions first, then choose the most final eligible calculation\n   stage. OCR frequency is allowed only as a last tie-breaker among candidates\n   in the same semantic class.\n5. **Preserve candidate evidence** - For every candidate retain the filename,\n   OCR pass, raw line, normalized label, line or bounding-box location, parsed\n   amount, semantic class, and any rejection reason. If the parser cannot\n   explain why the winner outranks each competing candidate, the field remains\n   unresolved and receives targeted OCR instead of a guessed value.\n6. **Validate behavior, not only shape** - Before writing the final artifact,\n   inspect the candidate audit for every input with competing totals. Confirm\n   that no excluded candidate, table-heading fallback, first-match shortcut, or\n   cross-class frequency vote selected the winner. A schema\u002Forder check alone\n   does not satisfy completion.\n\nA compliant selection routine follows this structure:\n\n```python\ncandidates = collect_all_candidates(observations)\neligible = [candidate for candidate in candidates if not candidate.excluded]\n\nif not eligible:\n    winner = None\nelse:\n    best_stage = min(candidate.semantic_rank for candidate in eligible)\n    finalists = [\n        candidate for candidate in eligible\n        if candidate.semantic_rank == best_stage\n    ]\n    # Agreement may break a tie only after semantic filtering.\n    winner = resolve_same_stage(finalists)\n\nsave_candidate_audit(candidates, winner)\n```\n\nDo not replace this structure with `first match`, `last number`, `largest\nnumber`, or unrestricted majority-vote shortcuts.\n\n\n## Error Handling\n\n### Common Issues and Solutions\n\n**Issue**: Tesseract not found\n\n```python\n# Verify Tesseract is installed\ntry:\n    pytesseract.get_tesseract_version()\nexcept pytesseract.TesseractNotFoundError:\n    print(\"Tesseract is not installed or not in PATH\")\n```\n\n**Issue**: Poor OCR quality\n\n- Preprocess image (grayscale, contrast, sharpen)\n- Use appropriate PSM mode for the document type\n- Ensure image resolution is sufficient (300+ DPI)\n\n**Issue**: Empty or garbage output\n\n- Check if image contains actual text\n- Try different PSM modes\n- Verify image is not corrupted\n\n\n## Quality Self-Check\n\nBefore returning results, verify:\n\n- [ ] Output is valid JSON (use `json.loads()` to validate)\n- [ ] All required fields are present (`success`, `filename`, `extracted_text`, `confidence`, `metadata`)\n- [ ] Text preserves logical reading order\n- [ ] Confidence level reflects actual OCR quality\n- [ ] Warnings array includes all detected issues\n- [ ] Special characters are properly escaped in JSON\n- [ ] Every batch input has a terminal status in the checkpoint\n- [ ] Required fields were resolved independently with candidate provenance\n- [ ] Every non-null exact date and monetary amount is supported by at least two\n      materially different OCR passes over the same source region\n- [ ] Every cross-pass disagreement triggered targeted OCR and semantic review\n- [ ] Task-defined monetary exclusions were applied before candidate ranking\n- [ ] Monetary conflicts were resolved by label semantics and calculation stage,\n      not by frequency, magnitude, or last-number shortcuts\n- [ ] The parser scanned the complete observation before selecting a monetary\n      value and rejected table-heading and unsafe next-line fallbacks\n- [ ] A candidate audit records the winner, semantic stage, competing values,\n      and rejection reasons for every receipt with conflicting totals\n- [ ] Missing or conflicting fields use the task's specified null\u002Ferror value\n- [ ] The exact requested final artifact exists, reopens, and has the required schema\n\n\n## Limitations\n\n- Tesseract works best with printed text; handwriting recognition is limited\n- Accuracy decreases with decorative fonts, artistic text, or extreme stylization\n- Mathematical equations and special notation may not extract accurately\n- Redacted or watermarked text cannot be recovered\n- Severe image degradation (blur, noise, low resolution) reduces accuracy\n- Complex multi-column layouts may require custom PSM configuration\n\n\n## Version History\n\n- **1.1.0** (2026-09-12): Added a blocking multi-pass evidence and audit gate for exact structured date and monetary extraction\n- **1.0.0** (2026-01-13): Initial release with Tesseract\u002Fpytesseract OCR\n",{"name":5,"description":7},"main","cdcb6d230f3b15c3c33f8a2bdd16439f43602cbe","evaluation\u002Fresults\u002F对于jpg-ocr-stat的尝试\u002Fruns\u002Fjpg-ocr-stat-round-11-r002\u002Finputs\u002Fskills\u002Fimage-ocr",1,"https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark","https:\u002F\u002Fgithub.com\u002Flinyouxue","2026-11-14 20:28:35",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add linyouxue\u002Fskill-repair-benchmark --skill image-ocr",{"tool":37,"command":38},"bunx","bunx skills add linyouxue\u002Fskill-repair-benchmark --skill image-ocr",{"tool":40,"command":41},"pnpm","pnpm dlx skills add linyouxue\u002Fskill-repair-benchmark --skill image-ocr","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fevaluation\u002Fresults\u002F对于jpg-ocr-stat的尝试\u002Fruns\u002Fjpg-ocr-stat-round-11-r002\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",true,[],[46,53,60,66,71,76],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":19},"01M7E1HGVRY73NBJ022CJG13X6","video-frame-extraction","Extract frames from video files and save them as images using OpenCV","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fvideo-frame-extraction\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7E1HAG5R7CJ9C8NYJS771MB","openai-vision","Analyze images and multi-frame sequences using OpenAI GPT vision models","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fopenai-vision\u002FSKILL.md",[],[],{"skillNo":61,"name":5,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7E1H7DADKB6QBWKC2KQ63SZ","Extract text content from images using Tesseract OCR via Python, including structured field extraction from receipts and forms","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[],{"skillNo":67,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7E1H0WBNT43TENGQY7AVZHD","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fvideo-frame-extraction\u002FSKILL.md",[],[],{"skillNo":72,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7E1GTC7D4N4Q2EF03875J9E","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fopenai-vision\u002FSKILL.md",[],[],{"skillNo":77,"name":5,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7E1GQ92CWFMGH53KSSE4WER","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[]]