Datasets:
Commit ·
23054b5
0
Parent(s):
Duplicate from inclusionAI/FinixDocBench
Browse filesCo-authored-by: mingcheng, aka 明城 <m1ngcheng@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +60 -0
- CITATION.cff +39 -0
- FinixDocBench_Eval_for_Markdown/README.md +142 -0
- FinixDocBench_Eval_for_Markdown/examples/gt/sample_001.md +10 -0
- FinixDocBench_Eval_for_Markdown/examples/pred/sample_001.md +10 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/__init__.py +0 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/metrics/__init__.py +0 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/metrics/table_metric.py +260 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/omnidocbench_adapter.py +226 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/__init__.py +0 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/data_preprocess.py +452 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/extract.py +571 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/match.py +310 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/match_quick.py +1292 -0
- FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/table_utils.py +100 -0
- FinixDocBench_Eval_for_Markdown/requirements.txt +8 -0
- FinixDocBench_Eval_for_Markdown/run_eval.py +116 -0
- LICENSE.md +47 -0
- README.md +375 -0
- dataset_manifest.jsonl +0 -0
- metadata.jsonl +0 -0
- track1_finixdigital_242_insurance_terms/images/008053f7-47b1-4810-bfad-6f51c0ddc390.png +3 -0
- track1_finixdigital_242_insurance_terms/images/01c9577f-0cca-440e-a037-93c754764553.png +3 -0
- track1_finixdigital_242_insurance_terms/images/03b07d4a-2895-48d7-b3f4-841f3875d387.png +3 -0
- track1_finixdigital_242_insurance_terms/images/03e0c0a4-6b6f-432a-8e1d-08425b02fe55.png +3 -0
- track1_finixdigital_242_insurance_terms/images/0603ab53-ea60-4698-983f-c4d9a3d391fd.png +3 -0
- track1_finixdigital_242_insurance_terms/images/08c42598-d27d-43b6-9797-991b86d1aa2b.png +3 -0
- track1_finixdigital_242_insurance_terms/images/090e980a-47b3-4ba9-898d-87047e69cb7f.png +3 -0
- track1_finixdigital_242_insurance_terms/images/0915fdd1-dc13-42e4-bc3f-1deb95fc242e.png +3 -0
- track1_finixdigital_242_insurance_terms/images/091f1637-c551-4669-9ba3-bb55d9bd8754.png +3 -0
- track1_finixdigital_242_insurance_terms/images/09cc7e9d-308f-446f-85cb-686673746367.png +3 -0
- track1_finixdigital_242_insurance_terms/images/0b2dfaff-0b84-40d1-b8ed-32419263ec42.png +3 -0
- track1_finixdigital_242_insurance_terms/images/0bc4bb5f-8b93-4ab2-b197-40d187b83e00.png +3 -0
- track1_finixdigital_242_insurance_terms/images/0d657279-1e0b-4e3e-8ff6-2abd6767119c.png +3 -0
- track1_finixdigital_242_insurance_terms/images/0eb11f58-5a95-4a53-a4fa-b5a5d28273ed.png +3 -0
- track1_finixdigital_242_insurance_terms/images/0f05d9b0-8b83-40cd-9a07-24c0c9179729.png +3 -0
- track1_finixdigital_242_insurance_terms/images/1017cac1-9cb9-4c70-b9ed-a22d8ab865a8.png +3 -0
- track1_finixdigital_242_insurance_terms/images/10d17bd5-5291-4474-8a5d-45d0b6e45c20.png +3 -0
- track1_finixdigital_242_insurance_terms/images/11bceca9-0986-4d27-a5a5-73665c032f6e.png +3 -0
- track1_finixdigital_242_insurance_terms/images/11f5554a-2a43-4f96-b76b-d9f2e90bd863.png +3 -0
- track1_finixdigital_242_insurance_terms/images/12b01854-1d57-46e3-a743-d90588dccef3.png +3 -0
- track1_finixdigital_242_insurance_terms/images/12cae7f9-8d69-4093-b328-a23d71683dfa.png +3 -0
- track1_finixdigital_242_insurance_terms/images/13977ebf-0bb0-4e16-a1ae-3cef62246628.png +3 -0
- track1_finixdigital_242_insurance_terms/images/164da4c7-6bb4-42a0-95e1-c9c5fdb8e5d9.png +3 -0
- track1_finixdigital_242_insurance_terms/images/16b1433c-4238-449c-9c16-6a85b622767a.png +3 -0
- track1_finixdigital_242_insurance_terms/images/190d2be8-7426-51a4-bc90-8c3dce04fd42.png +3 -0
- track1_finixdigital_242_insurance_terms/images/1abb05d2-55aa-43de-8a87-f53157e27338.png +3 -0
- track1_finixdigital_242_insurance_terms/images/1aed3e59-ad28-44f1-b53b-ca0ff336373e.png +3 -0
- track1_finixdigital_242_insurance_terms/images/1cd8ead1-35d7-43c6-b8e2-e9edc3cfdd09.png +3 -0
- track1_finixdigital_242_insurance_terms/images/1dafdf2d-a448-483a-83a1-5d223b473300.png +3 -0
.gitattributes
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.avro filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
# Audio files - uncompressed
|
| 40 |
+
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
# Audio files - compressed
|
| 44 |
+
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
# Image files - uncompressed
|
| 50 |
+
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
# Image files - compressed
|
| 55 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
# Video files - compressed
|
| 59 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
*.webm filter=lfs diff=lfs merge=lfs -text
|
CITATION.cff
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cff-version: 1.2.0
|
| 2 |
+
message: "If you use this FinixDocBench release, please cite the FinixDoc technical report."
|
| 3 |
+
title: "FinixDoc: Rethinking Financial Document Parsing Beyond Saturated Benchmarks"
|
| 4 |
+
authors:
|
| 5 |
+
- family-names: Wang
|
| 6 |
+
given-names: Hang
|
| 7 |
+
- family-names: Zhang
|
| 8 |
+
given-names: Jin
|
| 9 |
+
- family-names: Xu
|
| 10 |
+
given-names: Guoliang
|
| 11 |
+
- family-names: Lu
|
| 12 |
+
given-names: Pengyue
|
| 13 |
+
- family-names: Li
|
| 14 |
+
given-names: Yao
|
| 15 |
+
- family-names: Zhang
|
| 16 |
+
given-names: Zijiao
|
| 17 |
+
- family-names: Huang
|
| 18 |
+
given-names: Tianyu
|
| 19 |
+
- family-names: Xiong
|
| 20 |
+
given-names: Weiqi
|
| 21 |
+
- family-names: Wang
|
| 22 |
+
given-names: Yulong
|
| 23 |
+
- family-names: Lu
|
| 24 |
+
given-names: Chuqiao
|
| 25 |
+
- family-names: Huang
|
| 26 |
+
given-names: Wenkang
|
| 27 |
+
- family-names: Yang
|
| 28 |
+
given-names: Kai
|
| 29 |
+
- family-names: Li
|
| 30 |
+
given-names: Yadong
|
| 31 |
+
- family-names: Li
|
| 32 |
+
given-names: Hui
|
| 33 |
+
- family-names: Xu
|
| 34 |
+
given-names: Xingzhong
|
| 35 |
+
- family-names: Xu
|
| 36 |
+
given-names: Xiao
|
| 37 |
+
date-released: "2026-06-09"
|
| 38 |
+
url: "https://finix.alipay.com/"
|
| 39 |
+
license: "CC-BY-NC-SA-4.0"
|
FinixDocBench_Eval_for_Markdown/README.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FinixDocBench Markdown Evaluation
|
| 2 |
+
|
| 3 |
+
This folder contains a lightweight evaluator for FinixDocBench Markdown parsing outputs. It compares a directory of ground-truth `.md` files with a directory of predicted `.md` files whose file names match exactly.
|
| 4 |
+
|
| 5 |
+
The evaluator is intended for the public Markdown task. It does not evaluate structured JSON layout annotations.
|
| 6 |
+
|
| 7 |
+
## Metrics
|
| 8 |
+
|
| 9 |
+
The evaluator reports:
|
| 10 |
+
|
| 11 |
+
| Metric | Direction | Meaning |
|
| 12 |
+
|---|---|---|
|
| 13 |
+
| `text_block_Edit_dist` | Lower is better | Normalized edit distance over matched text blocks. |
|
| 14 |
+
| `reading_order_Edit_dist` | Lower is better | Normalized edit distance over serialized reading-order sequences. |
|
| 15 |
+
| `table_TEDS` | Higher is better | TEDS table-structure similarity, scaled to 0-100. |
|
| 16 |
+
| `overall` | Higher is better | Composite score on a 0-100 scale. |
|
| 17 |
+
|
| 18 |
+
The overall score is:
|
| 19 |
+
|
| 20 |
+
```python
|
| 21 |
+
overall = (
|
| 22 |
+
(1 - text_block_Edit_dist) * 100
|
| 23 |
+
+ (1 - reading_order_Edit_dist) * 100
|
| 24 |
+
+ table_TEDS
|
| 25 |
+
) / 3
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
Formula parsing is not evaluated separately.
|
| 29 |
+
|
| 30 |
+
## Installation
|
| 31 |
+
|
| 32 |
+
Python 3.9+ is recommended.
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
cd FinixDocBench_Eval_for_Markdown
|
| 36 |
+
python3 -m venv .venv
|
| 37 |
+
source .venv/bin/activate
|
| 38 |
+
pip install -r requirements.txt
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
## Quick Check
|
| 42 |
+
|
| 43 |
+
Run the bundled minimal example first:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
python run_eval.py \
|
| 47 |
+
--gt_dir examples/gt \
|
| 48 |
+
--pred_dir examples/pred \
|
| 49 |
+
--output_json outputs/example_result.json
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
## Evaluate a FinixDocBench Track
|
| 53 |
+
|
| 54 |
+
Prepare a prediction directory with one `.md` file per evaluated page. Prediction file names must match the ground-truth Markdown file names.
|
| 55 |
+
|
| 56 |
+
Example for FinixPhoto:
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
python run_eval.py \
|
| 60 |
+
--gt_dir ../track2_finixphoto_300/mds \
|
| 61 |
+
--pred_dir /path/to/predicted_mds \
|
| 62 |
+
--output_json outputs/finixphoto_result.json
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Example for FinixHuge-Table:
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
python run_eval.py \
|
| 69 |
+
--gt_dir ../track3_finixhuge_100_table/mds \
|
| 70 |
+
--pred_dir /path/to/predicted_mds \
|
| 71 |
+
--output_json outputs/finixhuge_table_result.json
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
## Output Format
|
| 75 |
+
|
| 76 |
+
The output JSON has the following structure:
|
| 77 |
+
|
| 78 |
+
```json
|
| 79 |
+
{
|
| 80 |
+
"success": true,
|
| 81 |
+
"metrics": {
|
| 82 |
+
"text_block_Edit_dist": 0.0123,
|
| 83 |
+
"reading_order_Edit_dist": 0.0,
|
| 84 |
+
"table_TEDS": 98.7,
|
| 85 |
+
"overall": 99.15,
|
| 86 |
+
"num_samples": 2,
|
| 87 |
+
"score": 99.15
|
| 88 |
+
},
|
| 89 |
+
"inputs": {
|
| 90 |
+
"gt_files": 2,
|
| 91 |
+
"pred_files": 2,
|
| 92 |
+
"missing_predictions": 0,
|
| 93 |
+
"unexpected_predictions": 0
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
`score` is identical to `overall` and is included for leaderboard or automation systems that expect a generic score field.
|
| 99 |
+
|
| 100 |
+
## File Name Validation
|
| 101 |
+
|
| 102 |
+
By default, the evaluator fails if the `.md` file names in `gt_dir` and `pred_dir` do not match exactly. This avoids accidentally skipping pages.
|
| 103 |
+
|
| 104 |
+
If you want to allow missing predictions and score missing files as empty outputs, pass:
|
| 105 |
+
|
| 106 |
+
```bash
|
| 107 |
+
python run_eval.py \
|
| 108 |
+
--gt_dir /path/to/gt_mds \
|
| 109 |
+
--pred_dir /path/to/pred_mds \
|
| 110 |
+
--allow_name_mismatch
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
## FinixHuge Reporting
|
| 114 |
+
|
| 115 |
+
For FinixHuge-Long and FinixHuge-Table, also report a success rate outside this script:
|
| 116 |
+
|
| 117 |
+
```text
|
| 118 |
+
success_rate = valid_non_empty_predictions / total_pages
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
A prediction should be counted as successful only if it is a syntactically valid, non-empty page-level Markdown result without runtime failure, severe truncation, or format errors that prevent downstream evaluation.
|
| 122 |
+
|
| 123 |
+
## Large Table Safeguards
|
| 124 |
+
|
| 125 |
+
TEDS can be slow on extremely large tables. To keep evaluation practical, this implementation assigns a table TEDS score of `0` when a ground-truth or predicted table exceeds `50000` `<td>` cells.
|
| 126 |
+
|
| 127 |
+
The matching stage also keeps broad safety thresholds:
|
| 128 |
+
|
| 129 |
+
```text
|
| 130 |
+
MAX_PRED_ITEMS = 50000
|
| 131 |
+
RATIO_THRESHOLD = 100
|
| 132 |
+
MAX_TOTAL_LENGTH = 10000000
|
| 133 |
+
MAX_SINGLE_ITEM_LENGTH = 10000000
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
## Notes
|
| 137 |
+
|
| 138 |
+
- Only `.md` files are evaluated.
|
| 139 |
+
- Images, JSON annotations, and other files are ignored by this evaluator.
|
| 140 |
+
- Markdown tables are converted to HTML before table evaluation.
|
| 141 |
+
- One page image should correspond to one Markdown file.
|
| 142 |
+
- File names are the matching keys; the evaluator does not read images.
|
FinixDocBench_Eval_for_Markdown/examples/gt/sample_001.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Sample Insurance Clause
|
| 2 |
+
|
| 3 |
+
The policy covers accidental medical expenses during the insurance period.
|
| 4 |
+
|
| 5 |
+
<table>
|
| 6 |
+
<tr><td>Item</td><td>Limit</td></tr>
|
| 7 |
+
<tr><td>Medical</td><td>10000</td></tr>
|
| 8 |
+
</table>
|
| 9 |
+
|
| 10 |
+
Final note.
|
FinixDocBench_Eval_for_Markdown/examples/pred/sample_001.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Sample Insurance Clause
|
| 2 |
+
|
| 3 |
+
The policy covers accidental medical expense during the insurance period.
|
| 4 |
+
|
| 5 |
+
<table>
|
| 6 |
+
<tr><td>Item</td><td>Limit</td></tr>
|
| 7 |
+
<tr><td>Medical</td><td>9000</td></tr>
|
| 8 |
+
</table>
|
| 9 |
+
|
| 10 |
+
Final note.
|
FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/__init__.py
ADDED
|
File without changes
|
FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/metrics/__init__.py
ADDED
|
File without changes
|
FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/metrics/table_metric.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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2020 IBM
|
| 2 |
+
# Author: peter.zhong@au1.ibm.com
|
| 3 |
+
#
|
| 4 |
+
# This is free software; you can redistribute it and/or modify
|
| 5 |
+
# it under the terms of the Apache 2.0 License.
|
| 6 |
+
#
|
| 7 |
+
# This software is distributed in the hope that it will be useful,
|
| 8 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 9 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 10 |
+
# Apache 2.0 License for more details.
|
| 11 |
+
|
| 12 |
+
import Levenshtein
|
| 13 |
+
# import rapidfuzz.distance as distance
|
| 14 |
+
from apted import APTED, Config
|
| 15 |
+
from apted.helpers import Tree
|
| 16 |
+
from lxml import etree, html
|
| 17 |
+
from collections import deque
|
| 18 |
+
# from parallel import parallel_process
|
| 19 |
+
from tqdm import tqdm
|
| 20 |
+
|
| 21 |
+
class TableTree(Tree):
|
| 22 |
+
def __init__(self, tag, colspan=None, rowspan=None, content=None, *children):
|
| 23 |
+
self.tag = tag
|
| 24 |
+
self.colspan = colspan
|
| 25 |
+
self.rowspan = rowspan
|
| 26 |
+
self.content = content
|
| 27 |
+
self.children = list(children)
|
| 28 |
+
|
| 29 |
+
def bracket(self):
|
| 30 |
+
"""Show tree using brackets notation"""
|
| 31 |
+
if self.tag == 'td':
|
| 32 |
+
result = '"tag": %s, "colspan": %d, "rowspan": %d, "text": %s' % \
|
| 33 |
+
(self.tag, self.colspan, self.rowspan, self.content)
|
| 34 |
+
else:
|
| 35 |
+
result = '"tag": %s' % self.tag
|
| 36 |
+
for child in self.children:
|
| 37 |
+
result += child.bracket()
|
| 38 |
+
return "{{{}}}".format(result)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CustomConfig(Config):
|
| 42 |
+
@staticmethod
|
| 43 |
+
def maximum(*sequences):
|
| 44 |
+
"""Get maximum possible value
|
| 45 |
+
"""
|
| 46 |
+
return max(map(len, sequences))
|
| 47 |
+
|
| 48 |
+
def normalized_distance(self, *sequences):
|
| 49 |
+
"""Get distance from 0 to 1
|
| 50 |
+
"""
|
| 51 |
+
return float(Levenshtein.distance(*sequences)) / self.maximum(*sequences)
|
| 52 |
+
|
| 53 |
+
def rename(self, node1, node2):
|
| 54 |
+
"""Compares attributes of trees"""
|
| 55 |
+
if (node1.tag != node2.tag) or (node1.colspan != node2.colspan) or (node1.rowspan != node2.rowspan):
|
| 56 |
+
return 1.
|
| 57 |
+
if node1.tag == 'td':
|
| 58 |
+
if node1.content or node2.content:
|
| 59 |
+
return self.normalized_distance(node1.content, node2.content)
|
| 60 |
+
return 0.
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class TEDS(object):
|
| 64 |
+
''' Tree Edit Distance basead Similarity
|
| 65 |
+
'''
|
| 66 |
+
def __init__(self, structure_only=False, n_jobs=16, ignore_nodes=None):
|
| 67 |
+
assert isinstance(n_jobs, int) and (n_jobs >= 1), 'n_jobs must be an integer greather than 1'
|
| 68 |
+
self.structure_only = structure_only
|
| 69 |
+
self.n_jobs = n_jobs
|
| 70 |
+
self.ignore_nodes = ignore_nodes
|
| 71 |
+
self.__tokens__ = []
|
| 72 |
+
|
| 73 |
+
def tokenize(self, node):
|
| 74 |
+
''' Tokenizes table cells
|
| 75 |
+
'''
|
| 76 |
+
self.__tokens__.append('<%s>' % node.tag)
|
| 77 |
+
if node.text is not None:
|
| 78 |
+
self.__tokens__ += list(node.text)
|
| 79 |
+
for n in node.getchildren():
|
| 80 |
+
self.tokenize(n)
|
| 81 |
+
if node.tag != 'unk':
|
| 82 |
+
self.__tokens__.append('</%s>' % node.tag)
|
| 83 |
+
if node.tag != 'td' and node.tail is not None:
|
| 84 |
+
self.__tokens__ += list(node.tail)
|
| 85 |
+
|
| 86 |
+
def load_html_tree(self, node, parent=None):
|
| 87 |
+
''' Converts HTML tree to the format required by apted
|
| 88 |
+
'''
|
| 89 |
+
global __tokens__
|
| 90 |
+
if node.tag == 'td':
|
| 91 |
+
if self.structure_only:
|
| 92 |
+
cell = []
|
| 93 |
+
else:
|
| 94 |
+
self.__tokens__ = []
|
| 95 |
+
self.tokenize(node)
|
| 96 |
+
cell = self.__tokens__[1:-1].copy()
|
| 97 |
+
new_node = TableTree(node.tag,
|
| 98 |
+
int(node.attrib.get('colspan', '1')),
|
| 99 |
+
int(node.attrib.get('rowspan', '1')),
|
| 100 |
+
cell, *deque())
|
| 101 |
+
else:
|
| 102 |
+
new_node = TableTree(node.tag, None, None, None, *deque())
|
| 103 |
+
if parent is not None:
|
| 104 |
+
parent.children.append(new_node)
|
| 105 |
+
if node.tag != 'td':
|
| 106 |
+
for n in node.getchildren():
|
| 107 |
+
self.load_html_tree(n, new_node)
|
| 108 |
+
if parent is None:
|
| 109 |
+
return new_node
|
| 110 |
+
|
| 111 |
+
# def evaluate(self, pred, true):
|
| 112 |
+
# ''' Computes TEDS score between the prediction and the ground truth of a
|
| 113 |
+
# given sample
|
| 114 |
+
# '''
|
| 115 |
+
# if (not pred) or (not true):
|
| 116 |
+
# return 0.0
|
| 117 |
+
# parser = html.HTMLParser(remove_comments=True, encoding='utf-8')
|
| 118 |
+
# pred = html.fromstring(pred, parser=parser)
|
| 119 |
+
# true = html.fromstring(true, parser=parser)
|
| 120 |
+
# if pred.xpath('body/table') and true.xpath('body/table'):
|
| 121 |
+
# pred = pred.xpath('body/table')[0]
|
| 122 |
+
# true = true.xpath('body/table')[0]
|
| 123 |
+
# if self.ignore_nodes:
|
| 124 |
+
# etree.strip_tags(pred, *self.ignore_nodes)
|
| 125 |
+
# etree.strip_tags(true, *self.ignore_nodes)
|
| 126 |
+
# n_nodes_pred = len(pred.xpath(".//*"))
|
| 127 |
+
# n_nodes_true = len(true.xpath(".//*"))
|
| 128 |
+
# n_nodes = max(n_nodes_pred, n_nodes_true)
|
| 129 |
+
# tree_pred = self.load_html_tree(pred)
|
| 130 |
+
# tree_true = self.load_html_tree(true)
|
| 131 |
+
# distance = APTED(tree_pred, tree_true, CustomConfig()).compute_edit_distance()
|
| 132 |
+
# return 1.0 - (float(distance) / n_nodes)
|
| 133 |
+
# else:
|
| 134 |
+
# return 0.0
|
| 135 |
+
# def evaluate(self, pred, true):
|
| 136 |
+
# ''' Computes TEDS score between the prediction and the ground truth of a
|
| 137 |
+
# given sample
|
| 138 |
+
# '''
|
| 139 |
+
# from multiprocessing import Process, Queue
|
| 140 |
+
# import sys
|
| 141 |
+
|
| 142 |
+
# def _evaluate_inner(pred, true, queue):
|
| 143 |
+
# try:
|
| 144 |
+
# if (not pred) or (not true):
|
| 145 |
+
# queue.put(0.0)
|
| 146 |
+
# return
|
| 147 |
+
|
| 148 |
+
# parser = html.HTMLParser(remove_comments=True, encoding='utf-8')
|
| 149 |
+
# pred_doc = html.fromstring(pred, parser=parser)
|
| 150 |
+
# true_doc = html.fromstring(true, parser=parser)
|
| 151 |
+
|
| 152 |
+
# if pred_doc.xpath('body/table') and true_doc.xpath('body/table'):
|
| 153 |
+
# pred_table = pred_doc.xpath('body/table')[0]
|
| 154 |
+
# true_table = true_doc.xpath('body/table')[0]
|
| 155 |
+
# if self.ignore_nodes:
|
| 156 |
+
# etree.strip_tags(pred_table, *self.ignore_nodes)
|
| 157 |
+
# etree.strip_tags(true_table, *self.ignore_nodes)
|
| 158 |
+
# n_nodes_pred = len(pred_table.xpath(".//*"))
|
| 159 |
+
# n_nodes_true = len(true_table.xpath(".//*"))
|
| 160 |
+
# n_nodes = max(n_nodes_pred, n_nodes_true)
|
| 161 |
+
# if n_nodes == 0:
|
| 162 |
+
# queue.put(1.0)
|
| 163 |
+
# return
|
| 164 |
+
# tree_pred = self.load_html_tree(pred_table)
|
| 165 |
+
# tree_true = self.load_html_tree(true_table)
|
| 166 |
+
# distance = APTED(tree_pred, tree_true, CustomConfig()).compute_edit_distance()
|
| 167 |
+
# score = 1.0 - (float(distance) / n_nodes)
|
| 168 |
+
# queue.put(score)
|
| 169 |
+
# else:
|
| 170 |
+
# queue.put(0.0)
|
| 171 |
+
# except Exception:
|
| 172 |
+
# queue.put(0.0)
|
| 173 |
+
|
| 174 |
+
# # 超时时间(秒),可调整
|
| 175 |
+
# TIMEOUT_SECONDS = 60
|
| 176 |
+
|
| 177 |
+
# q = Queue()
|
| 178 |
+
# p = Process(target=_evaluate_inner, args=(pred, true, q))
|
| 179 |
+
# p.start()
|
| 180 |
+
# p.join(timeout=TIMEOUT_SECONDS)
|
| 181 |
+
|
| 182 |
+
# if p.is_alive():
|
| 183 |
+
# p.terminate()
|
| 184 |
+
# p.join()
|
| 185 |
+
# return 0.0
|
| 186 |
+
# else:
|
| 187 |
+
# if not q.empty():
|
| 188 |
+
# return q.get()
|
| 189 |
+
# else:
|
| 190 |
+
# return 0.0
|
| 191 |
+
|
| 192 |
+
def evaluate(self, pred, true):
|
| 193 |
+
try:
|
| 194 |
+
if (not pred) or (not true):
|
| 195 |
+
return 0.0
|
| 196 |
+
|
| 197 |
+
parser = html.HTMLParser(remove_comments=True, encoding='utf-8')
|
| 198 |
+
pred_doc = html.fromstring(pred, parser=parser)
|
| 199 |
+
true_doc = html.fromstring(true, parser=parser)
|
| 200 |
+
|
| 201 |
+
pred_tables = pred_doc.xpath('//table')
|
| 202 |
+
true_tables = true_doc.xpath('//table')
|
| 203 |
+
if not pred_tables or not true_tables:
|
| 204 |
+
return 0.0
|
| 205 |
+
|
| 206 |
+
pred_table = pred_tables[0]
|
| 207 |
+
true_table = true_tables[0]
|
| 208 |
+
|
| 209 |
+
if self.ignore_nodes:
|
| 210 |
+
etree.strip_tags(pred_table, *self.ignore_nodes)
|
| 211 |
+
etree.strip_tags(true_table, *self.ignore_nodes)
|
| 212 |
+
|
| 213 |
+
n_td_pred = len(pred_table.xpath(".//td"))
|
| 214 |
+
n_td_true = len(true_table.xpath(".//td"))
|
| 215 |
+
if n_td_pred > 50000 or n_td_true > 50000:
|
| 216 |
+
print(f"Skipping large table: pred={n_td_pred}, true={n_td_true}", flush=True)
|
| 217 |
+
return 0.0
|
| 218 |
+
|
| 219 |
+
n_nodes_pred = len(pred_table.xpath(".//*"))
|
| 220 |
+
n_nodes_true = len(true_table.xpath(".//*"))
|
| 221 |
+
n_nodes = max(n_nodes_pred, n_nodes_true)
|
| 222 |
+
if n_nodes == 0:
|
| 223 |
+
return 1.0
|
| 224 |
+
|
| 225 |
+
tree_pred = self.load_html_tree(pred_table)
|
| 226 |
+
tree_true = self.load_html_tree(true_table)
|
| 227 |
+
distance = APTED(tree_pred, tree_true, CustomConfig()).compute_edit_distance()
|
| 228 |
+
return 1.0 - (float(distance) / n_nodes)
|
| 229 |
+
except Exception:
|
| 230 |
+
return 0.0
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def batch_evaluate(self, pred_json, true_json):
|
| 234 |
+
''' Computes TEDS score between the prediction and the ground truth of
|
| 235 |
+
a batch of samples
|
| 236 |
+
@params pred_json: {'FILENAME': 'HTML CODE', ...}
|
| 237 |
+
@params true_json: {'FILENAME': {'html': 'HTML CODE'}, ...}
|
| 238 |
+
@output: {'FILENAME': 'TEDS SCORE', ...}
|
| 239 |
+
'''
|
| 240 |
+
samples = true_json.keys()
|
| 241 |
+
# if self.n_jobs == 1:
|
| 242 |
+
scores = [self.evaluate(pred_json.get(filename, ''), true_json[filename]['html']) for filename in tqdm(samples)]
|
| 243 |
+
# else:
|
| 244 |
+
# inputs = [{'pred': pred_json.get(filename, ''), 'true': true_json[filename]['html']} for filename in samples]
|
| 245 |
+
# scores = parallel_process(inputs, self.evaluate, use_kwargs=True, n_jobs=self.n_jobs, front_num=1)
|
| 246 |
+
scores = dict(zip(samples, scores))
|
| 247 |
+
return scores
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
if __name__ == '__main__':
|
| 251 |
+
import json
|
| 252 |
+
import pprint
|
| 253 |
+
with open('sample_pred.json') as fp:
|
| 254 |
+
pred_json = json.load(fp)
|
| 255 |
+
with open('sample_gt.json') as fp:
|
| 256 |
+
true_json = json.load(fp)
|
| 257 |
+
teds = TEDS(n_jobs=4)
|
| 258 |
+
scores = teds.batch_evaluate(pred_json, true_json)
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
|
| 5 |
+
from .metrics.table_metric import TEDS
|
| 6 |
+
from .utils.extract import md_tex_filter
|
| 7 |
+
from .utils.match_quick import match_gt2pred_quick
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _read_text(path):
|
| 11 |
+
with open(path, 'r', encoding='utf-8') as f:
|
| 12 |
+
return f.read()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _sequence_distance(a, b):
|
| 16 |
+
if a == b:
|
| 17 |
+
return 0
|
| 18 |
+
if a is None:
|
| 19 |
+
a = ''
|
| 20 |
+
if b is None:
|
| 21 |
+
b = ''
|
| 22 |
+
if len(a) < len(b):
|
| 23 |
+
a, b = b, a
|
| 24 |
+
if not b:
|
| 25 |
+
return len(a)
|
| 26 |
+
|
| 27 |
+
previous = list(range(len(b) + 1))
|
| 28 |
+
for i, ca in enumerate(a, 1):
|
| 29 |
+
current = [i]
|
| 30 |
+
for j, cb in enumerate(b, 1):
|
| 31 |
+
insert_cost = current[j - 1] + 1
|
| 32 |
+
delete_cost = previous[j] + 1
|
| 33 |
+
replace_cost = previous[j - 1] + (0 if ca == cb else 1)
|
| 34 |
+
current.append(min(insert_cost, delete_cost, replace_cost))
|
| 35 |
+
previous = current
|
| 36 |
+
return previous[-1]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _normalized_edit(a, b):
|
| 40 |
+
if a is None:
|
| 41 |
+
a = ''
|
| 42 |
+
if b is None:
|
| 43 |
+
b = ''
|
| 44 |
+
upper_len = max(len(a), len(b))
|
| 45 |
+
if upper_len == 0:
|
| 46 |
+
return 0.0, 0, 0
|
| 47 |
+
edit_num = _sequence_distance(a, b)
|
| 48 |
+
return edit_num / upper_len, edit_num, upper_len
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _safe_mean(values, default=float('nan')):
|
| 52 |
+
values = [v for v in values if v is not None and not math.isnan(float(v))]
|
| 53 |
+
if not values:
|
| 54 |
+
return default
|
| 55 |
+
return sum(values) / len(values)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _get_order_paired(order_match_s, img_name):
|
| 59 |
+
matched = [
|
| 60 |
+
(item['gt_position'], item['pred_position'])
|
| 61 |
+
for item in order_match_s
|
| 62 |
+
if item['gt_position'] != [''] and item['pred_position'] != ''
|
| 63 |
+
]
|
| 64 |
+
gt_idx_all = [item['gt_position'] for item in order_match_s if item['gt_position'] != ['']]
|
| 65 |
+
read_order_pred = [i[0] for i in sorted(matched, key=lambda x: x[1])]
|
| 66 |
+
read_order_gt = sum(gt_idx_all, [])
|
| 67 |
+
read_order_gt = [x for x in read_order_gt if x]
|
| 68 |
+
gt = sorted(read_order_gt)
|
| 69 |
+
pred = sum(read_order_pred, [])
|
| 70 |
+
pred = [x for x in pred if x]
|
| 71 |
+
if len(pred) > 0 or len(gt) > 0:
|
| 72 |
+
edit = _normalized_edit(gt, pred)[0]
|
| 73 |
+
return {
|
| 74 |
+
'gt': gt,
|
| 75 |
+
'pred': pred,
|
| 76 |
+
'img_id': img_name,
|
| 77 |
+
'edit': edit,
|
| 78 |
+
}
|
| 79 |
+
return {}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _calculate_edit_dist(samples):
|
| 83 |
+
if not samples:
|
| 84 |
+
return float('nan')
|
| 85 |
+
|
| 86 |
+
grouped = defaultdict(lambda: {'edit': 0, 'upper': 0})
|
| 87 |
+
for sample in samples:
|
| 88 |
+
img_name = sample['img_id']
|
| 89 |
+
if not (img_name.endswith('.jpg') or img_name.endswith('.png')):
|
| 90 |
+
img_name = '_'.join(img_name.split('_')[:-1])
|
| 91 |
+
|
| 92 |
+
gt = sample.get('norm_gt') if sample.get('norm_gt') is not None else sample.get('gt', '')
|
| 93 |
+
pred = sample.get('norm_pred') if sample.get('norm_pred') is not None else sample.get('pred', '')
|
| 94 |
+
_, edit_num, upper_len = _normalized_edit(pred, gt)
|
| 95 |
+
if upper_len == 0:
|
| 96 |
+
continue
|
| 97 |
+
grouped[img_name]['edit'] += edit_num
|
| 98 |
+
grouped[img_name]['upper'] += upper_len
|
| 99 |
+
|
| 100 |
+
page_scores = [
|
| 101 |
+
val['edit'] / val['upper']
|
| 102 |
+
for val in grouped.values()
|
| 103 |
+
if val['upper'] > 0
|
| 104 |
+
]
|
| 105 |
+
return _safe_mean(page_scores)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _missing_table_samples(gt_tables, img_name):
|
| 109 |
+
samples = []
|
| 110 |
+
for idx, item in enumerate(gt_tables):
|
| 111 |
+
content = str(item.get('content', ''))
|
| 112 |
+
samples.append({
|
| 113 |
+
'gt_idx': [idx],
|
| 114 |
+
'gt': content,
|
| 115 |
+
'pred_idx': [''],
|
| 116 |
+
'pred': '',
|
| 117 |
+
'gt_position': [item.get('order') if item.get('order') else item.get('position', [''])[0]],
|
| 118 |
+
'pred_position': '',
|
| 119 |
+
'norm_gt': content,
|
| 120 |
+
'norm_pred': '',
|
| 121 |
+
'gt_category_type': item.get('fine_category_type') or item.get('category_type', 'table'),
|
| 122 |
+
'pred_category_type': '',
|
| 123 |
+
'gt_attribute': [item.get('attribute', {})],
|
| 124 |
+
'edit': 1,
|
| 125 |
+
'img_id': img_name,
|
| 126 |
+
})
|
| 127 |
+
return samples
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _calculate_table_teds(table_samples):
|
| 131 |
+
if not table_samples:
|
| 132 |
+
return 100.0
|
| 133 |
+
|
| 134 |
+
teds = TEDS(structure_only=False)
|
| 135 |
+
scores = []
|
| 136 |
+
for sample in table_samples:
|
| 137 |
+
gt = sample.get('norm_gt') if sample.get('norm_gt') else sample.get('gt', '')
|
| 138 |
+
pred = sample.get('norm_pred') if sample.get('norm_pred') else sample.get('pred', '')
|
| 139 |
+
try:
|
| 140 |
+
score = teds.evaluate(pred, gt)
|
| 141 |
+
except Exception:
|
| 142 |
+
score = 0.0
|
| 143 |
+
scores.append(max(0.0, min(1.0, float(score))))
|
| 144 |
+
return _safe_mean(scores, default=0.0) * 100.0
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _clamp(value, low, high):
|
| 148 |
+
if value is None or math.isnan(float(value)):
|
| 149 |
+
return value
|
| 150 |
+
return max(low, min(high, float(value)))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def evaluate_md_dirs(gt_dir, pred_dir):
|
| 154 |
+
plain_text_match = []
|
| 155 |
+
html_table_match = []
|
| 156 |
+
latex_table_match = []
|
| 157 |
+
order_match = []
|
| 158 |
+
|
| 159 |
+
sample_names = sorted(name for name in os.listdir(gt_dir) if name.endswith('.md'))
|
| 160 |
+
for sample_name in sample_names:
|
| 161 |
+
img_name = sample_name[:-3] + '.jpg'
|
| 162 |
+
gt_content = _read_text(os.path.join(gt_dir, sample_name))
|
| 163 |
+
pred_path = os.path.join(pred_dir, sample_name)
|
| 164 |
+
pred_content = _read_text(pred_path) if os.path.exists(pred_path) else ''
|
| 165 |
+
|
| 166 |
+
gt_dataset = md_tex_filter(gt_content)
|
| 167 |
+
pred_dataset = md_tex_filter(pred_content)
|
| 168 |
+
|
| 169 |
+
plain_text_match_clean = []
|
| 170 |
+
if gt_dataset.get('text_all'):
|
| 171 |
+
plain_text_match_s = match_gt2pred_quick(
|
| 172 |
+
gt_dataset['text_all'],
|
| 173 |
+
pred_dataset.get('text_all', []),
|
| 174 |
+
'text',
|
| 175 |
+
img_name,
|
| 176 |
+
)
|
| 177 |
+
plain_text_match_clean = plain_text_match_s
|
| 178 |
+
plain_text_match.extend(plain_text_match_s)
|
| 179 |
+
|
| 180 |
+
if gt_dataset.get('latex_table'):
|
| 181 |
+
if pred_dataset.get('latex_table'):
|
| 182 |
+
table_match_s = match_gt2pred_quick(
|
| 183 |
+
gt_dataset['latex_table'],
|
| 184 |
+
pred_dataset['latex_table'],
|
| 185 |
+
'latex_table',
|
| 186 |
+
img_name,
|
| 187 |
+
)
|
| 188 |
+
latex_table_match.extend([x for x in table_match_s if x['gt_idx'] != ['']])
|
| 189 |
+
else:
|
| 190 |
+
latex_table_match.extend(_missing_table_samples(gt_dataset['latex_table'], img_name))
|
| 191 |
+
elif gt_dataset.get('html_table'):
|
| 192 |
+
if pred_dataset.get('html_table'):
|
| 193 |
+
table_match_s = match_gt2pred_quick(
|
| 194 |
+
gt_dataset['html_table'],
|
| 195 |
+
pred_dataset['html_table'],
|
| 196 |
+
'html_table',
|
| 197 |
+
img_name,
|
| 198 |
+
)
|
| 199 |
+
html_table_match.extend([x for x in table_match_s if x['gt_idx'] != ['']])
|
| 200 |
+
else:
|
| 201 |
+
html_table_match.extend(_missing_table_samples(gt_dataset['html_table'], img_name))
|
| 202 |
+
|
| 203 |
+
order_match_s = _get_order_paired(plain_text_match_clean, img_name)
|
| 204 |
+
if order_match_s:
|
| 205 |
+
order_match.append(order_match_s)
|
| 206 |
+
|
| 207 |
+
table_match = latex_table_match if latex_table_match else html_table_match
|
| 208 |
+
text_block_edit = _clamp(_calculate_edit_dist(plain_text_match), 0.0, 1.0)
|
| 209 |
+
reading_order_edit = _clamp(_calculate_edit_dist(order_match), 0.0, 1.0)
|
| 210 |
+
table_teds = _clamp(_calculate_table_teds(table_match), 0.0, 100.0)
|
| 211 |
+
|
| 212 |
+
if math.isnan(float(text_block_edit)):
|
| 213 |
+
text_block_edit = 0.0
|
| 214 |
+
if math.isnan(float(reading_order_edit)):
|
| 215 |
+
reading_order_edit = 0.0
|
| 216 |
+
|
| 217 |
+
overall = ((1 - text_block_edit) * 100.0 + (1 - reading_order_edit) * 100.0 + table_teds) / 3.0
|
| 218 |
+
overall = max(0.0, min(100.0, overall))
|
| 219 |
+
|
| 220 |
+
return {
|
| 221 |
+
'text_block_Edit_dist': text_block_edit,
|
| 222 |
+
'reading_order_Edit_dist': reading_order_edit,
|
| 223 |
+
'table_TEDS': table_teds,
|
| 224 |
+
'overall': overall,
|
| 225 |
+
'num_samples': len(sample_names),
|
| 226 |
+
}
|
FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/__init__.py
ADDED
|
File without changes
|
FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/data_preprocess.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import unicodedata
|
| 3 |
+
from pylatexenc.latex2text import LatexNodes2Text
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
import subprocess
|
| 6 |
+
import shutil
|
| 7 |
+
import uuid
|
| 8 |
+
import html
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
def remove_markdown_fences(content):
|
| 12 |
+
content = re.sub(r'^```markdown\n?', '', content, flags=re.MULTILINE)
|
| 13 |
+
content = re.sub(r'^```html\n?', '', content, flags=re.MULTILINE)
|
| 14 |
+
content = re.sub(r'^```latex\n?', '', content, flags=re.MULTILINE)
|
| 15 |
+
content = re.sub(r'```\n?$', '', content, flags=re.MULTILINE)
|
| 16 |
+
return content
|
| 17 |
+
|
| 18 |
+
# Standardize all consecutive characters
|
| 19 |
+
def replace_repeated_chars(input_str):
|
| 20 |
+
input_str = re.sub(r'_{4,}', '____', input_str) # Replace more than 4 consecutive underscores with 4 underscores
|
| 21 |
+
input_str = re.sub(r' {4,}', ' ', input_str) # Replace more than 4 consecutive spaces with 4 spaces
|
| 22 |
+
return input_str
|
| 23 |
+
# return re.sub(r'([^a-zA-Z0-9])\1{10,}', r'\1\1\1\1', input_str) # For other consecutive symbols (except numbers and letters), replace more than 10 occurrences with 4
|
| 24 |
+
|
| 25 |
+
# Special Unicode handling
|
| 26 |
+
def fullwidth_to_halfwidth(s):
|
| 27 |
+
result = []
|
| 28 |
+
for char in s:
|
| 29 |
+
code = ord(char)
|
| 30 |
+
# Convert full-width space to half-width space
|
| 31 |
+
if code == 0x3000:
|
| 32 |
+
code = 0x0020
|
| 33 |
+
# Convert other full-width characters to half-width
|
| 34 |
+
elif 0xFF01 <= code <= 0xFF5E:
|
| 35 |
+
code -= 0xFEE0
|
| 36 |
+
result.append(chr(code))
|
| 37 |
+
return ''.join(result)
|
| 38 |
+
|
| 39 |
+
def find_special_unicode(s):
|
| 40 |
+
special_chars = {}
|
| 41 |
+
for char in s:
|
| 42 |
+
if ord(char) > 127: # Non-ASCII characters
|
| 43 |
+
# unicode_name = unicodedata.name(char, None)
|
| 44 |
+
unicode_name = unicodedata.category(char)
|
| 45 |
+
special_chars[char] = f'U+{ord(char):04X} ({unicode_name})'
|
| 46 |
+
return special_chars
|
| 47 |
+
|
| 48 |
+
# # Define dictionary for Unicode character replacements
|
| 49 |
+
# unicode_replacements = {
|
| 50 |
+
# "\u00A9": r"$\copyright$", # Copyright symbol © to latex
|
| 51 |
+
# "\u00AE": r"$^\circledR$", # Registered trademark ® to latex
|
| 52 |
+
# "\u2122": r"$^\text{TM}$", # Trademark ™ to latex
|
| 53 |
+
# "\u2018": "'", # Left single quote to straight quote
|
| 54 |
+
# "\u2019": "'", # Right single quote to straight quote
|
| 55 |
+
# "\u201C": "\"", # Left double quote to straight quote
|
| 56 |
+
# "\u201D": "\"", # Right double quote to straight quote
|
| 57 |
+
# "\u2013": "-", # En dash to hyphen
|
| 58 |
+
# "\u2014": "-", # Em dash to hyphen
|
| 59 |
+
# "\u2026": "...", # Unicode ellipsis to three dots
|
| 60 |
+
# "\u2103": r"$\textdegree C$", # ℃
|
| 61 |
+
# "\u03B1": r"$\alpha$", # α
|
| 62 |
+
# "\u03B2": r"$\beta$", # β
|
| 63 |
+
# "\u03A3": r"$\Sigma$", # Σ
|
| 64 |
+
# }
|
| 65 |
+
|
| 66 |
+
# # Use regex to replace Unicode characters
|
| 67 |
+
# def replace_unicode(match):
|
| 68 |
+
# char = match.group(0)
|
| 69 |
+
# return unicode_replacements.get(char, char)
|
| 70 |
+
|
| 71 |
+
inline_reg = re.compile(
|
| 72 |
+
r'\$(.*?)\$|'
|
| 73 |
+
r'\\\((.*?)\\\)',
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
def textblock2unicode(text):
|
| 77 |
+
inline_matches = inline_reg.finditer(text)
|
| 78 |
+
removal_positions = []
|
| 79 |
+
for match in inline_matches:
|
| 80 |
+
position = [match.start(), match.end()]
|
| 81 |
+
content = match.group(1) if match.group(1) is not None else match.group(2)
|
| 82 |
+
# print('-------- content-------', content)
|
| 83 |
+
# Remove escape characters \
|
| 84 |
+
clean_content = re.sub(r'\\([\\_&%^])', '', content)
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
if any(char in clean_content for char in r'\^_'):
|
| 88 |
+
if clean_content.endswith('\\'):
|
| 89 |
+
clean_content += ' '
|
| 90 |
+
# inline_array.append(match.group(0))
|
| 91 |
+
unicode_content = LatexNodes2Text().latex_to_text(clean_content)
|
| 92 |
+
removal_positions.append((position[0], position[1], unicode_content))
|
| 93 |
+
except:
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
# Remove inline formulas from original text
|
| 97 |
+
for start, end, unicode_content in sorted(removal_positions, reverse=True):
|
| 98 |
+
text = text[:start] + unicode_content.strip() + text[end:]
|
| 99 |
+
|
| 100 |
+
return text
|
| 101 |
+
|
| 102 |
+
def normalized_formula(text):
|
| 103 |
+
# Normalize math formulas before matching
|
| 104 |
+
filter_list = ['\\mathbf', '\\mathrm', '\\mathnormal', '\\mathit', '\\mathbb', '\\mathcal', '\\mathscr', '\\mathfrak', '\\mathsf', '\\mathtt',
|
| 105 |
+
'\\textbf', '\\text', '\\boldmath', '\\boldsymbol', '\\operatorname', '\\bm',
|
| 106 |
+
'\\symbfit', '\\mathbfcal', '\\symbf', '\\scriptscriptstyle', '\\notag',
|
| 107 |
+
'\\setlength', '\\coloneqq', '\\space', '\\thickspace', '\\thinspace', '\\medspace', '\\nobreakspace', '\\negmedspace',
|
| 108 |
+
'\\quad', '\\qquad', '\\enspace', '\\substackw', ' ', '$$', '\\left', '\\right', '\\displaystyle', '\\text']
|
| 109 |
+
# '\\left', '\\right', '{', '}', ' ']
|
| 110 |
+
|
| 111 |
+
# delimiter_filter
|
| 112 |
+
text = text.strip().strip('$').strip('\n')
|
| 113 |
+
pattern = re.compile(r"\\\[(.+?)(?<!\\)\\\]")
|
| 114 |
+
match = pattern.search(text)
|
| 115 |
+
|
| 116 |
+
if match:
|
| 117 |
+
text = match.group(1).strip()
|
| 118 |
+
|
| 119 |
+
tag_pattern = re.compile(r"\\tag\{.*?\}")
|
| 120 |
+
text = tag_pattern.sub('', text)
|
| 121 |
+
hspace_pattern = re.compile(r"\\hspace\{.*?\}")
|
| 122 |
+
text = hspace_pattern.sub('', text)
|
| 123 |
+
begin_pattern = re.compile(r"\\begin\{.*?\}")
|
| 124 |
+
text = begin_pattern.sub('', text)
|
| 125 |
+
end_pattern = re.compile(r"\\end\{.*?\}")
|
| 126 |
+
text = end_pattern.sub('', text)
|
| 127 |
+
col_sep = re.compile(r"\\arraycolsep.*?\}")
|
| 128 |
+
text = col_sep.sub('', text)
|
| 129 |
+
text = text.strip('.')
|
| 130 |
+
|
| 131 |
+
for filter_text in filter_list:
|
| 132 |
+
text = text.replace(filter_text, '')
|
| 133 |
+
|
| 134 |
+
# text = normalize_text(delimiter_filter(text))
|
| 135 |
+
# text = delimiter_filter(text)
|
| 136 |
+
text = text.lower()
|
| 137 |
+
return text
|
| 138 |
+
|
| 139 |
+
def normalized_html_table(text):
|
| 140 |
+
def process_table_html(md_i):
|
| 141 |
+
"""
|
| 142 |
+
pred_md format edit
|
| 143 |
+
"""
|
| 144 |
+
def process_table_html(html_content):
|
| 145 |
+
soup = BeautifulSoup(html_content, 'html.parser')
|
| 146 |
+
th_tags = soup.find_all('th')
|
| 147 |
+
for th in th_tags:
|
| 148 |
+
th.name = 'td'
|
| 149 |
+
thead_tags = soup.find_all('thead')
|
| 150 |
+
for thead in thead_tags:
|
| 151 |
+
thead.unwrap() # unwrap()会移除标签但保留其内容
|
| 152 |
+
math_tags = soup.find_all('math')
|
| 153 |
+
for math_tag in math_tags:
|
| 154 |
+
alttext = math_tag.get('alttext', '')
|
| 155 |
+
alttext = f'${alttext}$'
|
| 156 |
+
if alttext:
|
| 157 |
+
math_tag.replace_with(alttext)
|
| 158 |
+
span_tags = soup.find_all('span')
|
| 159 |
+
for span in span_tags:
|
| 160 |
+
span.unwrap()
|
| 161 |
+
return str(soup)
|
| 162 |
+
|
| 163 |
+
table_res=''
|
| 164 |
+
table_res_no_space=''
|
| 165 |
+
if '<table' in md_i.replace(" ","").replace("'",'"'):
|
| 166 |
+
md_i = process_table_html(md_i)
|
| 167 |
+
table_res = html.unescape(md_i).replace('\n', '')
|
| 168 |
+
table_res = unicodedata.normalize('NFKC', table_res).strip()
|
| 169 |
+
pattern = r'<table\b[^>]*>(.*)</table>'
|
| 170 |
+
tables = re.findall(pattern, table_res, re.DOTALL | re.IGNORECASE)
|
| 171 |
+
table_res = ''.join(tables)
|
| 172 |
+
# table_res = re.sub('<table.*?>','',table_res)
|
| 173 |
+
table_res = re.sub('( style=".*?")', "", table_res)
|
| 174 |
+
table_res = re.sub('( height=".*?")', "", table_res)
|
| 175 |
+
table_res = re.sub('( width=".*?")', "", table_res)
|
| 176 |
+
table_res = re.sub('( align=".*?")', "", table_res)
|
| 177 |
+
table_res = re.sub('( class=".*?")', "", table_res)
|
| 178 |
+
table_res = re.sub('</?tbody>',"",table_res)
|
| 179 |
+
|
| 180 |
+
table_res = re.sub(r'\s+', " ", table_res)
|
| 181 |
+
table_res_no_space = '<html><body><table border="1" >' + table_res.replace(' ','') + '</table></body></html>'
|
| 182 |
+
# table_res_no_space = re.sub(' (style=".*?")',"",table_res_no_space)
|
| 183 |
+
# table_res_no_space = re.sub(r'[ ]', " ", table_res_no_space)
|
| 184 |
+
table_res_no_space = re.sub('colspan="', ' colspan="', table_res_no_space)
|
| 185 |
+
table_res_no_space = re.sub('rowspan="', ' rowspan="', table_res_no_space)
|
| 186 |
+
table_res_no_space = re.sub('border="', ' border="', table_res_no_space)
|
| 187 |
+
|
| 188 |
+
table_res = '<html><body><table border="1" >' + table_res + '</table></body></html>'
|
| 189 |
+
# table_flow.append(table_res)
|
| 190 |
+
# table_flow_no_space.append(table_res_no_space)
|
| 191 |
+
|
| 192 |
+
return table_res, table_res_no_space
|
| 193 |
+
|
| 194 |
+
def clean_table(input_str,flag=True):
|
| 195 |
+
if flag:
|
| 196 |
+
input_str = input_str.replace('<sup>', '').replace('</sup>', '')
|
| 197 |
+
input_str = input_str.replace('<sub>', '').replace('</sub>', '')
|
| 198 |
+
input_str = input_str.replace('<span>', '').replace('</span>', '')
|
| 199 |
+
input_str = input_str.replace('<div>', '').replace('</div>', '')
|
| 200 |
+
input_str = input_str.replace('<p>', '').replace('</p>', '')
|
| 201 |
+
input_str = input_str.replace('<spandata-span-identity="">', '')
|
| 202 |
+
input_str = re.sub('<colgroup>.*?</colgroup>','',input_str)
|
| 203 |
+
return input_str
|
| 204 |
+
|
| 205 |
+
norm_text, _ = process_table_html(text)
|
| 206 |
+
norm_text = clean_table(norm_text)
|
| 207 |
+
return norm_text
|
| 208 |
+
|
| 209 |
+
def normalized_latex_table(text):
|
| 210 |
+
def latex_template(latex_code):
|
| 211 |
+
template = r'''
|
| 212 |
+
\documentclass[border=20pt]{article}
|
| 213 |
+
\usepackage{subcaption}
|
| 214 |
+
\usepackage{url}
|
| 215 |
+
\usepackage{graphicx}
|
| 216 |
+
\usepackage{caption}
|
| 217 |
+
\usepackage{multirow}
|
| 218 |
+
\usepackage{booktabs}
|
| 219 |
+
\usepackage{color}
|
| 220 |
+
\usepackage{colortbl}
|
| 221 |
+
\usepackage{xcolor,soul,framed}
|
| 222 |
+
\usepackage{fontspec}
|
| 223 |
+
\usepackage{amsmath,amssymb,mathtools,bm,mathrsfs,textcomp}
|
| 224 |
+
\setlength{\parindent}{0pt}''' + \
|
| 225 |
+
r'''
|
| 226 |
+
\begin{document}
|
| 227 |
+
''' + \
|
| 228 |
+
latex_code + \
|
| 229 |
+
r'''
|
| 230 |
+
\end{document}'''
|
| 231 |
+
|
| 232 |
+
return template
|
| 233 |
+
|
| 234 |
+
def process_table_latex(latex_code):
|
| 235 |
+
SPECIAL_STRINGS= [
|
| 236 |
+
['\\\\vspace\\{.*?\\}', ''],
|
| 237 |
+
['\\\\hspace\\{.*?\\}', ''],
|
| 238 |
+
['\\\\rule\\{.*?\\}\\{.*?\\}', ''],
|
| 239 |
+
['\\\\addlinespace\\[.*?\\]', ''],
|
| 240 |
+
['\\\\addlinespace', ''],
|
| 241 |
+
['\\\\renewcommand\\{\\\\arraystretch\\}\\{.*?\\}', ''],
|
| 242 |
+
['\\\\arraystretch\\{.*?\\}', ''],
|
| 243 |
+
['\\\\(row|column)?colors?\\{[^}]*\\}(\\{[^}]*\\}){0,2}', ''],
|
| 244 |
+
['\\\\color\\{.*?\\}', ''],
|
| 245 |
+
['\\\\textcolor\\{.*?\\}', ''],
|
| 246 |
+
['\\\\rowcolor(\\[.*?\\])?\\{.*?\\}', ''],
|
| 247 |
+
['\\\\columncolor(\\[.*?\\])?\\{.*?\\}', ''],
|
| 248 |
+
['\\\\cellcolor(\\[.*?\\])?\\{.*?\\}', ''],
|
| 249 |
+
['\\\\colorbox\\{.*?\\}', ''],
|
| 250 |
+
['\\\\(tiny|scriptsize|footnotesize|small|normalsize|large|Large|LARGE|huge|Huge)', ''],
|
| 251 |
+
[r'\s+', ' '],
|
| 252 |
+
['\\\\centering', ''],
|
| 253 |
+
['\\\\begin\\{table\\}\\[.*?\\]', '\\\\begin{table}'],
|
| 254 |
+
['\t', ''],
|
| 255 |
+
['@{}', ''],
|
| 256 |
+
['\\\\toprule(\\[.*?\\])?', '\\\\hline'],
|
| 257 |
+
['\\\\bottomrule(\\[.*?\\])?', '\\\\hline'],
|
| 258 |
+
['\\\\midrule(\\[.*?\\])?', '\\\\hline'],
|
| 259 |
+
['p\\{[^}]*\\}', 'l'],
|
| 260 |
+
['m\\{[^}]*\\}', 'c'],
|
| 261 |
+
['\\\\scalebox\\{[^}]*\\}\\{([^}]*)\\}', '\\1'],
|
| 262 |
+
['\\\\textbf\\{([^}]*)\\}', '\\1'],
|
| 263 |
+
['\\\\textit\\{([^}]*)\\}', '\\1'],
|
| 264 |
+
['\\\\cmidrule(\\[.*?\\])?\\(.*?\\)\\{([0-9]-[0-9])\\}', '\\\\cline{\\2}'],
|
| 265 |
+
['\\\\hline', ''],
|
| 266 |
+
[r'\\multicolumn\{1\}\{[^}]*\}\{((?:[^{}]|(?:\{[^{}]*\}))*)\}', r'\1']
|
| 267 |
+
]
|
| 268 |
+
pattern = r'\\begin\{tabular\}.*\\end\{tabular\}' # 注意这里不用 .*?
|
| 269 |
+
matches = re.findall(pattern, latex_code, re.DOTALL)
|
| 270 |
+
latex_code = ' '.join(matches)
|
| 271 |
+
|
| 272 |
+
for special_str in SPECIAL_STRINGS:
|
| 273 |
+
latex_code = re.sub(fr'{special_str[0]}', fr'{special_str[1]}', latex_code)
|
| 274 |
+
|
| 275 |
+
return latex_code
|
| 276 |
+
|
| 277 |
+
def convert_latex_to_html(latex_content, cache_dir='./temp'):
|
| 278 |
+
if not os.path.exists(cache_dir):
|
| 279 |
+
os.makedirs(cache_dir)
|
| 280 |
+
|
| 281 |
+
uuid_str = str(uuid.uuid1())
|
| 282 |
+
with open(f'{cache_dir}/{uuid_str}.tex', 'w') as f:
|
| 283 |
+
f.write(latex_template(latex_content))
|
| 284 |
+
|
| 285 |
+
cmd = ['latexmlc', '--quiet', '--nocomments', f'--log={cache_dir}/{uuid_str}.log',
|
| 286 |
+
f'{cache_dir}/{uuid_str}.tex', f'--dest={cache_dir}/{uuid_str}.html']
|
| 287 |
+
try:
|
| 288 |
+
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 289 |
+
with open(f'{cache_dir}/{uuid_str}.html', 'r') as f:
|
| 290 |
+
html_content = f.read()
|
| 291 |
+
|
| 292 |
+
pattern = r'<table\b[^>]*>(.*)</table>'
|
| 293 |
+
tables = re.findall(pattern, html_content, re.DOTALL | re.IGNORECASE)
|
| 294 |
+
tables = [f'<table>{table}</table>' for table in tables]
|
| 295 |
+
html_content = '\n'.join(tables)
|
| 296 |
+
|
| 297 |
+
except Exception as e:
|
| 298 |
+
html_content = ''
|
| 299 |
+
|
| 300 |
+
shutil.rmtree(cache_dir)
|
| 301 |
+
return html_content
|
| 302 |
+
|
| 303 |
+
html_text = convert_latex_to_html(text)
|
| 304 |
+
normlized_tables = normalized_html_table(html_text)
|
| 305 |
+
return normlized_tables
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def normalized_table(text, format='html'):
|
| 309 |
+
if format not in ['html', 'latex']:
|
| 310 |
+
raise ValueError('Invalid format: {}'.format(format))
|
| 311 |
+
else:
|
| 312 |
+
return globals()['normalized_{}_table'.format(format)](text)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def textblock_with_norm_formula(text):
|
| 316 |
+
inline_matches = inline_reg.finditer(text)
|
| 317 |
+
removal_positions = []
|
| 318 |
+
for match in inline_matches:
|
| 319 |
+
position = [match.start(), match.end()]
|
| 320 |
+
content = match.group(1) if match.group(1) is not None else match.group(2)
|
| 321 |
+
# print('-------- content-------', content)
|
| 322 |
+
|
| 323 |
+
norm_content = normalized_formula(content)
|
| 324 |
+
removal_positions.append((position[0], position[1], norm_content))
|
| 325 |
+
|
| 326 |
+
# Remove inline formulas from original text
|
| 327 |
+
for start, end, norm_content in sorted(removal_positions, reverse=True):
|
| 328 |
+
text = text[:start] + norm_content.strip() + text[end:]
|
| 329 |
+
|
| 330 |
+
return text
|
| 331 |
+
|
| 332 |
+
# def inline_filter_unicode(text):
|
| 333 |
+
# # Ensure text is string type
|
| 334 |
+
# if not isinstance(text, str):
|
| 335 |
+
# text = str(text)
|
| 336 |
+
|
| 337 |
+
# # Convert LaTeX content to Unicode representation
|
| 338 |
+
# text = LatexNodes2Text().latex_to_text(text)
|
| 339 |
+
|
| 340 |
+
# inline_array = []
|
| 341 |
+
# inline_matches = inline_reg.finditer(text)
|
| 342 |
+
|
| 343 |
+
# for match in inline_matches:
|
| 344 |
+
# position = [match.start(), match.end()]
|
| 345 |
+
# content = match.group(1) if match.group(1) is not None else match.group(2)
|
| 346 |
+
|
| 347 |
+
# # Remove escape characters \
|
| 348 |
+
# clean_content = re.sub(r'\\([\\_&%^])', '', content)
|
| 349 |
+
|
| 350 |
+
# if any(char in clean_content for char in r'\^_'):
|
| 351 |
+
# # inline_array.append(match.group(0))
|
| 352 |
+
# inline_array.append({
|
| 353 |
+
# 'category_type': 'equation_inline',
|
| 354 |
+
# 'position': position,
|
| 355 |
+
# 'content': match.group(0),
|
| 356 |
+
# })
|
| 357 |
+
# text = text.replace(match.group(0), '')
|
| 358 |
+
# # print('-----Found inline formula: ', match.group(0))
|
| 359 |
+
# else:
|
| 360 |
+
# text = text.replace(match.group(0), content)
|
| 361 |
+
# # # Add to inline_array
|
| 362 |
+
# # inline_array.append({
|
| 363 |
+
# # 'category_type': 'equation_inline',
|
| 364 |
+
# # 'position': position,
|
| 365 |
+
# # 'content': content,
|
| 366 |
+
# # })
|
| 367 |
+
|
| 368 |
+
# # # Remove matched formula from original text, can choose to replace with spaces or remove directly
|
| 369 |
+
# # text = text[:position[0]] + ' '*(position[1]-position[0]) + text[position[1]:]
|
| 370 |
+
|
| 371 |
+
# return text, inline_array
|
| 372 |
+
|
| 373 |
+
def inline_filter_unicode(text):
|
| 374 |
+
# Ensure text is string type
|
| 375 |
+
if not isinstance(text, str):
|
| 376 |
+
text = str(text)
|
| 377 |
+
|
| 378 |
+
# Replace inline formula boundary markers
|
| 379 |
+
#print('--------text-------',text)
|
| 380 |
+
placeholder = '__INLINE_FORMULA_BOUNDARY__'
|
| 381 |
+
text_copy = text.replace('$', placeholder).replace('\\(', placeholder).replace('\\)', placeholder)
|
| 382 |
+
#print('--------text_copy-------',text_copy)
|
| 383 |
+
# Convert LaTeX content to Unicode representation
|
| 384 |
+
text_copy = LatexNodes2Text().latex_to_text(text_copy)
|
| 385 |
+
#print('--------text_copy---unicode----',text_copy)
|
| 386 |
+
# Restore boundary markers
|
| 387 |
+
text_copy = text_copy.replace(placeholder, '$')
|
| 388 |
+
|
| 389 |
+
inline_array = []
|
| 390 |
+
inline_matches = inline_reg.finditer(text_copy)
|
| 391 |
+
# Record positions of inline formulas to be removed
|
| 392 |
+
removal_positions = []
|
| 393 |
+
|
| 394 |
+
for match in inline_matches:
|
| 395 |
+
position = [match.start(), match.end()]
|
| 396 |
+
content = match.group(1) if match.group(1) is not None else match.group(2)
|
| 397 |
+
print('-------- content-------', content)
|
| 398 |
+
# Remove escape characters \
|
| 399 |
+
clean_content = re.sub(r'\\([\\_&%^])', '', content)
|
| 400 |
+
|
| 401 |
+
if any(char in clean_content for char in r'\^_'):
|
| 402 |
+
# inline_array.append(match.group(0))
|
| 403 |
+
inline_array.append({
|
| 404 |
+
'category_type': 'equation_inline',
|
| 405 |
+
'position': position,
|
| 406 |
+
'content': content,
|
| 407 |
+
})
|
| 408 |
+
removal_positions.append((position[0], position[1]))
|
| 409 |
+
|
| 410 |
+
# Remove inline formulas from original text
|
| 411 |
+
for start, end in sorted(removal_positions, reverse=True):
|
| 412 |
+
text = text[:start] + text[end:]
|
| 413 |
+
|
| 414 |
+
return text, inline_array
|
| 415 |
+
|
| 416 |
+
def inline_filter(text):
|
| 417 |
+
# Ensure text is string type
|
| 418 |
+
if not isinstance(text, str):
|
| 419 |
+
text = str(text)
|
| 420 |
+
|
| 421 |
+
inline_array = []
|
| 422 |
+
inline_matches = inline_reg.finditer(text)
|
| 423 |
+
|
| 424 |
+
for match in inline_matches:
|
| 425 |
+
position = [match.start(), match.end()]
|
| 426 |
+
content = match.group(1) if match.group(1) is not None else match.group(2)
|
| 427 |
+
# print('inline_content: ', content)
|
| 428 |
+
|
| 429 |
+
# Remove escape characters \
|
| 430 |
+
clean_content = re.sub(r'\\([\\_&%^])', '', content)
|
| 431 |
+
|
| 432 |
+
if any(char in clean_content for char in r'\^_'):
|
| 433 |
+
# inline_array.append(match.group(0))
|
| 434 |
+
inline_array.append({
|
| 435 |
+
'category_type': 'equation_inline',
|
| 436 |
+
'position': position,
|
| 437 |
+
'content': match.group(0),
|
| 438 |
+
})
|
| 439 |
+
text = text.replace(match.group(0), '')
|
| 440 |
+
# print('-----Found inline formula: ', match.group(0))
|
| 441 |
+
else:
|
| 442 |
+
text = text.replace(match.group(0), content)
|
| 443 |
+
|
| 444 |
+
return text, inline_array
|
| 445 |
+
|
| 446 |
+
# Text OCR quality check processing:
|
| 447 |
+
def clean_string(input_string):
|
| 448 |
+
# Use regex to keep Chinese characters, English letters and numbers
|
| 449 |
+
# input_string = input_string.replace('\\t', '').replace('\\n', '').replace('\t', '').replace('\n', '').replace('/t', '').replace('/n', '')
|
| 450 |
+
input_string = input_string.replace('\\t', '').replace('\\n', '').replace('\t', '').replace('\n', '').replace('/t', '').replace('/n', '')
|
| 451 |
+
cleaned_string = re.sub(r'[^\w\u4e00-\u9fff]', '', input_string) # 只保留中英文和数字
|
| 452 |
+
return cleaned_string
|
FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/extract.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ules.table_utils import convert_markdown_to_html #end
|
| 6 |
+
from .table_utils import convert_markdown_to_html
|
| 7 |
+
import re
|
| 8 |
+
import unicodedata
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
+
from pylatexenc.latexencode import unicode_to_latex
|
| 11 |
+
from pylatexenc.latex2text import LatexNodes2Text
|
| 12 |
+
from pylatexenc.latexwalker import LatexWalker, LatexEnvironmentNode, LatexCharsNode, LatexGroupNode, LatexMacroNode, LatexSpecialsNode
|
| 13 |
+
from collections import defaultdict
|
| 14 |
+
import pdb
|
| 15 |
+
from .data_preprocess import remove_markdown_fences, replace_repeated_chars, textblock_with_norm_formula, textblock2unicode
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def extract_tabular(text):
|
| 19 |
+
begin_pattern = r'\\begin{tabular}'
|
| 20 |
+
end_pattern = r'\\end{tabular}'
|
| 21 |
+
|
| 22 |
+
tabulars = []
|
| 23 |
+
positions = []
|
| 24 |
+
current_pos = 0
|
| 25 |
+
stack = []
|
| 26 |
+
|
| 27 |
+
while current_pos < len(text):
|
| 28 |
+
begin_match = re.search(begin_pattern, text[current_pos:])
|
| 29 |
+
end_match = re.search(end_pattern, text[current_pos:])
|
| 30 |
+
|
| 31 |
+
if not begin_match and not end_match:
|
| 32 |
+
break
|
| 33 |
+
|
| 34 |
+
if begin_match and (not end_match or begin_match.start() < end_match.start()):
|
| 35 |
+
stack.append(current_pos + begin_match.start())
|
| 36 |
+
current_pos += begin_match.start() + len(end_pattern)
|
| 37 |
+
elif end_match:
|
| 38 |
+
if stack:
|
| 39 |
+
start_pos = stack.pop()
|
| 40 |
+
if not stack:
|
| 41 |
+
end_pos = current_pos + end_match.start() + len(end_pattern)
|
| 42 |
+
tabular_code = text[start_pos:end_pos]
|
| 43 |
+
tabulars.append(tabular_code)
|
| 44 |
+
positions.append((start_pos, end_pos))
|
| 45 |
+
current_pos += end_match.start() + len(end_pattern)
|
| 46 |
+
else:
|
| 47 |
+
current_pos += 1
|
| 48 |
+
|
| 49 |
+
if stack:
|
| 50 |
+
new_start = stack[0] + len(begin_pattern)
|
| 51 |
+
new_tabulars, new_positions = extract_tabular(text[new_start:])
|
| 52 |
+
new_positions = [(start + new_start, end + new_start) for start, end in new_positions]
|
| 53 |
+
tabulars.extend(new_tabulars)
|
| 54 |
+
positions.extend(new_positions)
|
| 55 |
+
|
| 56 |
+
return tabulars, positions
|
| 57 |
+
|
| 58 |
+
# math reg
|
| 59 |
+
# r'\\begin{equation\*?}(.*?)\\end{equation\*?}|'
|
| 60 |
+
# r'\\begin{align\*?}(.*?)\\end{align\*?}|'
|
| 61 |
+
# r'\\begin{gather\*?}(.*?)\\end{gather\*?}|'
|
| 62 |
+
display_reg = re.compile(
|
| 63 |
+
# r'\\begin{equation\*?}(.*?)\\end{equation\*?}|'
|
| 64 |
+
# r'\\begin{align\*?}(.*?)\\end{align\*?}|'
|
| 65 |
+
# r'\\begin{gather\*?}(.*?)\\end{gather\*?}|'
|
| 66 |
+
# r'\\begin{array\*?}(.*?)\\end{array\*?}|'
|
| 67 |
+
r'\$\$(.*?)\$\$|'
|
| 68 |
+
r'\\\[(.*?)\\\]|'
|
| 69 |
+
r'\$(.*?)\$|'
|
| 70 |
+
r'\\\((.*?)\\\)',
|
| 71 |
+
re.DOTALL
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# inline_reg = re.compile(
|
| 75 |
+
# r'(?<!\$)\$(?!\$)(.*?)(?<!\$)\$(?!\$)|'
|
| 76 |
+
# r'\\\((.*?)\\\)',
|
| 77 |
+
# )
|
| 78 |
+
inline_reg = re.compile(
|
| 79 |
+
r'\$(.*?)\$|'
|
| 80 |
+
r'\\\((.*?)\\\)',
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# table
|
| 84 |
+
table_reg = re.compile(
|
| 85 |
+
r'\\begin{table\*?}(.*?)\\end{table\*?}|'
|
| 86 |
+
r'\\begin{tabular\*?}(.*?)\\end{tabular\*?}',
|
| 87 |
+
re.DOTALL
|
| 88 |
+
)
|
| 89 |
+
md_table_reg = re.compile(
|
| 90 |
+
r'\|\s*.*?\s*\|\n',
|
| 91 |
+
re.DOTALL)
|
| 92 |
+
html_table_reg = re.compile(
|
| 93 |
+
r'(<table.*?</table>)',
|
| 94 |
+
re.DOTALL
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# title
|
| 98 |
+
title_reg = re.compile(
|
| 99 |
+
r'^\s*#.*$',
|
| 100 |
+
re.MULTILINE)
|
| 101 |
+
|
| 102 |
+
# img
|
| 103 |
+
img_pattern = r'!\[.*?\]\(.*?\)'
|
| 104 |
+
|
| 105 |
+
# code block
|
| 106 |
+
code_block_reg = re.compile(
|
| 107 |
+
r'```(\w+)\n(.*?)```',
|
| 108 |
+
re.DOTALL
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def md_tex_filter(content):
|
| 112 |
+
'''
|
| 113 |
+
Input: 1 page md or tex content - String
|
| 114 |
+
Output: text, display, inline, table, title, code - list
|
| 115 |
+
'''
|
| 116 |
+
content = re.sub(img_pattern, '', content) # remove image
|
| 117 |
+
content = remove_markdown_fences(content) # remove markdown fences
|
| 118 |
+
content = replace_repeated_chars(content) # replace all consecutive characters
|
| 119 |
+
content = content.replace('<html>', '').replace('</html>', '').replace('<body>', '').replace('</body>', '')
|
| 120 |
+
|
| 121 |
+
# # 使用正则表达式对unicode进行替换
|
| 122 |
+
# special_unicode = ''.join(unicode_replacements.keys())
|
| 123 |
+
# content = re.sub(f'[{special_unicode}]', replace_unicode, content)
|
| 124 |
+
|
| 125 |
+
# content = fullwidth_to_halfwidth(content) # fullwidth to halfwidth, TODO: GT also needs this operation
|
| 126 |
+
|
| 127 |
+
# # pylatexenc's unicode to latex
|
| 128 |
+
# content = unicode_to_latex(content, unknown_char_warning=False)
|
| 129 |
+
# markdown_table_content[i, j] = LatexNodes2Text().latex_to_text(content_str)
|
| 130 |
+
# content_ori = copy.deepcopy(content)
|
| 131 |
+
|
| 132 |
+
# print('--------------After pre_process: \n', content)
|
| 133 |
+
|
| 134 |
+
pred_all = []
|
| 135 |
+
# deal with inline formula
|
| 136 |
+
# content_new, inline_array = inline_filter_unicode(content)
|
| 137 |
+
# #print('------------inline_array----------------',inline_array)
|
| 138 |
+
# for inline_item in inline_array:
|
| 139 |
+
# inline_item['content'] = inline_to_unicode(inline_item['content'])
|
| 140 |
+
# #print('------------inline_array_unicode----------------',inline_item['content'])
|
| 141 |
+
# pred_all.append({
|
| 142 |
+
# 'category_type': 'text_all',
|
| 143 |
+
# 'position': inline_item['position'],
|
| 144 |
+
# 'content': inline_item['content'],
|
| 145 |
+
# 'fine_category_type': 'equation_inline'
|
| 146 |
+
# })
|
| 147 |
+
|
| 148 |
+
# extract latex table
|
| 149 |
+
latex_table_array, table_positions = extract_tex_table(content)
|
| 150 |
+
for latex_table, position in zip(latex_table_array, table_positions):
|
| 151 |
+
position = [position[0], position[0]+len(latex_table)] # !!!
|
| 152 |
+
pred_all.append({
|
| 153 |
+
'category_type': 'latex_table',
|
| 154 |
+
'position': position,
|
| 155 |
+
'content': latex_table
|
| 156 |
+
})
|
| 157 |
+
content = content[:position[0]] + ' '*(position[1]-position[0]) + content[position[1]:] # replace latex table with space
|
| 158 |
+
|
| 159 |
+
# print('--------After latex table: \n', content)
|
| 160 |
+
# print('-------latex_table_array: \n', latex_table_array)
|
| 161 |
+
|
| 162 |
+
# extract html table
|
| 163 |
+
html_table_array, table_positions = extract_html_table(content)
|
| 164 |
+
for html_table, position in zip(html_table_array, table_positions):
|
| 165 |
+
position = [position[0], position[0]+len(html_table)]
|
| 166 |
+
pred_all.append({
|
| 167 |
+
'category_type': 'html_table',
|
| 168 |
+
'position': position,
|
| 169 |
+
'content': html_table
|
| 170 |
+
})
|
| 171 |
+
content = content[:position[0]] + ' '*(position[1]-position[0]) + content[position[1]:] # replace html table with space
|
| 172 |
+
# html_table_array = []
|
| 173 |
+
# html_table_matches = html_table_reg.finditer(content)
|
| 174 |
+
# if html_table_matches:
|
| 175 |
+
# for match in html_table_matches:
|
| 176 |
+
# matched = match.group(0)
|
| 177 |
+
# position = [match.start(), match.end()]
|
| 178 |
+
# html_table_array.append(matched.strip())
|
| 179 |
+
# # content = content.replace(matched, ' '*len(matched)) # replace html table with space
|
| 180 |
+
# content = content[:position[0]] + ' '*(position[1]-position[0]) + content[position[1]:] # replace html table with space
|
| 181 |
+
# pred_all.append({
|
| 182 |
+
# 'category_type': 'html_table',
|
| 183 |
+
# 'position': position,
|
| 184 |
+
# 'content': matched.strip()
|
| 185 |
+
# })
|
| 186 |
+
|
| 187 |
+
# print('--------------After html table: \n', content)
|
| 188 |
+
# # extract tables in latex and html
|
| 189 |
+
# table_array = []
|
| 190 |
+
# table_matches = table_reg.finditer(content)
|
| 191 |
+
# tables = ""
|
| 192 |
+
# for match in table_matches:
|
| 193 |
+
# matched = match.group(0)
|
| 194 |
+
# if matched:
|
| 195 |
+
# tables += matched
|
| 196 |
+
# tables += "\n\n"
|
| 197 |
+
# table_array.append(matched)
|
| 198 |
+
# content = content.replace(matched, '')
|
| 199 |
+
|
| 200 |
+
# extract interline formula
|
| 201 |
+
display_matches = display_reg.finditer(content)
|
| 202 |
+
content_copy = content
|
| 203 |
+
for match in display_matches:
|
| 204 |
+
matched = match.group(0)
|
| 205 |
+
if matched:
|
| 206 |
+
# single_line = ''.join(matched.split())
|
| 207 |
+
single_line = ' '.join(matched.strip().split('\n'))
|
| 208 |
+
position = [match.start(), match.end()]
|
| 209 |
+
# replace $$ with \[\]
|
| 210 |
+
dollar_pattern = re.compile(r'\$\$(.*?)\$\$|\$(.*?)\$|\\\((.*?)\\\)', re.DOTALL)
|
| 211 |
+
sub_match = dollar_pattern.search(single_line)
|
| 212 |
+
if sub_match is None:
|
| 213 |
+
# pass
|
| 214 |
+
content = content[:position[0]] + ' '*(position[1]-position[0]) + content[position[1]:]
|
| 215 |
+
pred_all.append({
|
| 216 |
+
'category_type': 'equation_isolated',
|
| 217 |
+
'position': position,
|
| 218 |
+
'content': single_line
|
| 219 |
+
})
|
| 220 |
+
elif sub_match.group(1):
|
| 221 |
+
single_line = re.sub(dollar_pattern, r'\\[\1\\]', single_line)
|
| 222 |
+
content = content[:position[0]] + ' '*(position[1]-position[0]) + content[position[1]:] # replace equation with space
|
| 223 |
+
pred_all.append({
|
| 224 |
+
'category_type': 'equation_isolated',
|
| 225 |
+
'position': position,
|
| 226 |
+
'content': single_line
|
| 227 |
+
})
|
| 228 |
+
else:
|
| 229 |
+
# start, end = match.span()
|
| 230 |
+
# char_before = content_copy[start-1] if start > 0 else '\n'
|
| 231 |
+
# char_after = content_copy[end] if end < len(content_copy) else '\n'
|
| 232 |
+
# if char_before == '\n' or char_after == '\n':
|
| 233 |
+
# single_line = re.sub(dollar_pattern, r'\\[\2\3\\]', single_line)
|
| 234 |
+
# pred_all.append({
|
| 235 |
+
# 'category_type': 'equation_isolated',
|
| 236 |
+
# 'position': position,
|
| 237 |
+
# 'content': single_line,
|
| 238 |
+
# 'fine_category_type': 'equation_inline'
|
| 239 |
+
# })
|
| 240 |
+
single_line = re.sub(dollar_pattern, r'\\[\2\3\\]', single_line)
|
| 241 |
+
pred_all.append({
|
| 242 |
+
'category_type': 'equation_isolated',
|
| 243 |
+
'position': position,
|
| 244 |
+
'content': single_line,
|
| 245 |
+
'fine_category_type': 'equation_inline'
|
| 246 |
+
})
|
| 247 |
+
# single_line = re.sub(dollar_pattern, r'\\[\1\2\3\\]', single_line)
|
| 248 |
+
# print('single_line: ', single_line)
|
| 249 |
+
# content = content.replace(matched, ' '*len(matched))
|
| 250 |
+
# pred_all.append({
|
| 251 |
+
# 'category_type': 'equation_isolated',
|
| 252 |
+
# 'position': position,
|
| 253 |
+
# 'content': single_line
|
| 254 |
+
# })
|
| 255 |
+
# print('-----Found display formula: ', matched)
|
| 256 |
+
|
| 257 |
+
# print('-------------After display: \n', content)
|
| 258 |
+
# extract md table with ||
|
| 259 |
+
md_table_mathces = md_table_reg.findall(content+'\n')
|
| 260 |
+
if len(md_table_mathces) >= 2:
|
| 261 |
+
# print("md table found!")
|
| 262 |
+
# print("content:", content)
|
| 263 |
+
content = convert_markdown_to_html(content)
|
| 264 |
+
# print('----------content after converting md table to html:', content)
|
| 265 |
+
html_table_matches = html_table_reg.finditer(content)
|
| 266 |
+
if html_table_matches:
|
| 267 |
+
for match in html_table_matches:
|
| 268 |
+
matched = match.group(0)
|
| 269 |
+
position = [match.start(), match.end()]
|
| 270 |
+
# content = content.replace(match, '')
|
| 271 |
+
# print('content after removing the md table:', content)
|
| 272 |
+
content = content[:position[0]] + ' '*(position[1]-position[0]) + content[position[1]:] # replace md table with space
|
| 273 |
+
pred_all.append({
|
| 274 |
+
'category_type': 'html_table',
|
| 275 |
+
'position': position,
|
| 276 |
+
'content': matched.strip(),
|
| 277 |
+
'fine_category_type': 'md2html_table'
|
| 278 |
+
})
|
| 279 |
+
# print('---------After md table: \n', content)
|
| 280 |
+
|
| 281 |
+
# extract code blocks
|
| 282 |
+
code_matches = code_block_reg.finditer(content)
|
| 283 |
+
if code_matches:
|
| 284 |
+
for match in code_matches:
|
| 285 |
+
position = [match.start(), match.end()]
|
| 286 |
+
language = match.group(1)
|
| 287 |
+
code = match.group(2).strip()
|
| 288 |
+
# content = content.replace(match.group(0), '')
|
| 289 |
+
content = content[:position[0]] + ' '*(position[1]-position[0]) + content[position[1]:] # replace code block with space
|
| 290 |
+
pred_all.append({
|
| 291 |
+
'category_type': 'text_all',
|
| 292 |
+
'position': position,
|
| 293 |
+
'content': code,
|
| 294 |
+
'language': language,
|
| 295 |
+
'fine_category_type': 'code'
|
| 296 |
+
})
|
| 297 |
+
|
| 298 |
+
# print('-------After code block: \n', content)
|
| 299 |
+
|
| 300 |
+
# # Extract titles: Do not extract titles, as some models do not wrap code blocks, causing all comments to be treated as titles
|
| 301 |
+
# title_matches = title_reg.finditer(content)
|
| 302 |
+
# if title_matches:
|
| 303 |
+
# for match in title_matches:
|
| 304 |
+
# position = [match.start(), match.end()]
|
| 305 |
+
# matched = match.group(0)
|
| 306 |
+
# matched = matched.replace("#", "").strip()
|
| 307 |
+
# # content = content.replace(match, '')
|
| 308 |
+
# # print('content after removing the titles:', content)
|
| 309 |
+
# if matched:
|
| 310 |
+
# # print('Add title: ', matched)
|
| 311 |
+
# content = content[:position[0]] + ' '*(position[1]-position[0]) + content[position[1]:]
|
| 312 |
+
# pred_all.append({
|
| 313 |
+
# 'category_type': 'text_all',
|
| 314 |
+
# 'position': position,
|
| 315 |
+
# 'content': matched,
|
| 316 |
+
# 'fine_category_type': 'title'
|
| 317 |
+
# })
|
| 318 |
+
|
| 319 |
+
# print('----------After title: \n', content)
|
| 320 |
+
|
| 321 |
+
# # Delete extracted content
|
| 322 |
+
# extracted_position = [_['position'] for _ in pred_all]
|
| 323 |
+
# for start, end in sorted(extracted_position, reverse=True):
|
| 324 |
+
# content = content[:start] + content[end:]
|
| 325 |
+
|
| 326 |
+
# print('----------After delete extracted: \n', content)
|
| 327 |
+
|
| 328 |
+
# Remove latex style
|
| 329 |
+
content = re.sub(r'\\title\{(.*?)\}', r'\1', content)
|
| 330 |
+
content = re.sub(r'\\title\s*\{\s*(.*?)\s*\}', r'\1', content, flags=re.DOTALL)
|
| 331 |
+
content = re.sub(r'\\text\s*\{\s*(.*?)\s*\}', r'\1', content, flags=re.DOTALL)
|
| 332 |
+
content = re.sub(r'\\section\*?\{(.*?)\}', r'\1', content)
|
| 333 |
+
content = re.sub(r'\\section\*?\{\s*(.*?)\s*\}', r'\1', content, flags=re.DOTALL)
|
| 334 |
+
|
| 335 |
+
# extract texts
|
| 336 |
+
res = content.split('\n\n')
|
| 337 |
+
if len(res) == 1:
|
| 338 |
+
res = content.split('\n') # some models do not use double newlines, so use single newlines to split
|
| 339 |
+
|
| 340 |
+
content_position = 0
|
| 341 |
+
for text in res:
|
| 342 |
+
position = [content_position, content_position+len(text)]
|
| 343 |
+
content_position += len(text)
|
| 344 |
+
text = text.strip()
|
| 345 |
+
text = text.strip('\n')
|
| 346 |
+
# print('ori_text: ', text)
|
| 347 |
+
text = '\n'.join([_.strip() for _ in text.split('\n') if _.strip()]) # avoid some single newline content with many spaces
|
| 348 |
+
# print('after strip text: ', text)
|
| 349 |
+
|
| 350 |
+
if text: # Check if the stripped text is not empty
|
| 351 |
+
if text.startswith('<table') and text.endswith('</table>'):
|
| 352 |
+
pred_all.append({
|
| 353 |
+
'category_type': 'html_table',
|
| 354 |
+
'position': position,
|
| 355 |
+
'content': text,
|
| 356 |
+
})
|
| 357 |
+
# elif text.startswith('#') and '\n' not in text:
|
| 358 |
+
# text = text.replace('#', '').strip()
|
| 359 |
+
# if text:
|
| 360 |
+
# # print('Add title: ', matched)
|
| 361 |
+
# pred_all.append({
|
| 362 |
+
# 'category_type': 'text_all',
|
| 363 |
+
# 'position': position,
|
| 364 |
+
# 'content': text,
|
| 365 |
+
# 'fine_category_type': 'title'
|
| 366 |
+
# })
|
| 367 |
+
elif text.startswith('$') and text.endswith('$'):
|
| 368 |
+
if text.replace('$', '').strip():
|
| 369 |
+
pred_all.append({
|
| 370 |
+
'category_type': 'equation_isolated',
|
| 371 |
+
'position': position,
|
| 372 |
+
'content': text.strip(),
|
| 373 |
+
})
|
| 374 |
+
else:
|
| 375 |
+
text = text.strip()
|
| 376 |
+
if text:
|
| 377 |
+
pred_all.append({
|
| 378 |
+
'category_type': 'text_all',
|
| 379 |
+
'position': position,
|
| 380 |
+
'content': text,
|
| 381 |
+
'fine_category_type': 'text_block'
|
| 382 |
+
})
|
| 383 |
+
# if '$' in text:
|
| 384 |
+
# for formula in re.findall(r'\$(.*?)\$', text):
|
| 385 |
+
# formula_array.append(formula)
|
| 386 |
+
|
| 387 |
+
pred_dataset = defaultdict(list)
|
| 388 |
+
pred_all = sorted(pred_all, key=lambda x: x['position'][0])
|
| 389 |
+
for item in pred_all:
|
| 390 |
+
pred_dataset[item['category_type']].append(item)
|
| 391 |
+
# pdb.set_trace()
|
| 392 |
+
return pred_dataset
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
# def replace_or_extract(match):
|
| 396 |
+
# content = match.group(1) if match.group(1) is not None else match.group(2)
|
| 397 |
+
|
| 398 |
+
# if any(char in content for char in r'\^_'):
|
| 399 |
+
# inline_array.append(match.group(0))
|
| 400 |
+
# return ''
|
| 401 |
+
# else:
|
| 402 |
+
# return content
|
| 403 |
+
|
| 404 |
+
# extract inline math equations in text
|
| 405 |
+
# def inline_filter(text):
|
| 406 |
+
|
| 407 |
+
# inline_array = []
|
| 408 |
+
# inline_matches = inline_reg.finditer(text)
|
| 409 |
+
# for match in inline_matches:
|
| 410 |
+
# content = match.group(1) if match.group(1) is not None else match.group(2)
|
| 411 |
+
|
| 412 |
+
# # remove \\, \_, \&, \%, \^
|
| 413 |
+
# clean_content = re.sub(r'\\([\\_&%^])', '', content)
|
| 414 |
+
|
| 415 |
+
# if any(char in clean_content for char in r'\^_'):
|
| 416 |
+
# inline_array.append(match.group(0))
|
| 417 |
+
# text = text.replace(match.group(0), '')
|
| 418 |
+
# else:
|
| 419 |
+
# text = text.replace(match.group(0), content)
|
| 420 |
+
|
| 421 |
+
# return text, inline_array
|
| 422 |
+
|
| 423 |
+
# def extract_tex_table(content):
|
| 424 |
+
# tables = []
|
| 425 |
+
# positions = []
|
| 426 |
+
|
| 427 |
+
# walker = LatexWalker(content)
|
| 428 |
+
# nodes, _, _ = walker.get_latex_nodes()
|
| 429 |
+
# if nodes is None:
|
| 430 |
+
# return tables, positions
|
| 431 |
+
|
| 432 |
+
# for node in nodes:
|
| 433 |
+
# if isinstance(node, LatexEnvironmentNode) and (
|
| 434 |
+
# node.environmentname == 'tabular' or node.environmentname == 'table'):
|
| 435 |
+
# # table_latex = extract_node_content(node)
|
| 436 |
+
# table_latex = content[node.pos:node.pos_end]
|
| 437 |
+
# tables.append(table_latex)
|
| 438 |
+
# start_pos = node.pos
|
| 439 |
+
# end_pos = get_node_end_pos(node)
|
| 440 |
+
# positions.append((start_pos, end_pos))
|
| 441 |
+
|
| 442 |
+
# return tables, positions
|
| 443 |
+
|
| 444 |
+
def extract_tex_table(content):
|
| 445 |
+
tables = []
|
| 446 |
+
tables_positions = []
|
| 447 |
+
|
| 448 |
+
pattern = r'\\begin{table}(.*?)\\end{table}'
|
| 449 |
+
for match in re.finditer(pattern, content, re.DOTALL):
|
| 450 |
+
start_pos = match.start()
|
| 451 |
+
end_pos = match.end()
|
| 452 |
+
table_content = match.group(0)
|
| 453 |
+
tables.append(table_content)
|
| 454 |
+
tables_positions.append((start_pos, end_pos))
|
| 455 |
+
content = content[:start_pos] + ' '*(end_pos-start_pos) + content[end_pos:]
|
| 456 |
+
|
| 457 |
+
tabulars, tabular_positions = extract_tabular(content)
|
| 458 |
+
all_tables = tables + tabulars
|
| 459 |
+
all_positions = tables_positions + tabular_positions
|
| 460 |
+
|
| 461 |
+
all_result = sorted([[pos, table]for pos, table in zip(all_positions, all_tables)], key=lambda x: x[0][0])
|
| 462 |
+
all_tables = [x[1] for x in all_result]
|
| 463 |
+
all_positions = [x[0] for x in all_result]
|
| 464 |
+
|
| 465 |
+
return all_tables, all_positions
|
| 466 |
+
|
| 467 |
+
# def extract_html_table(content):
|
| 468 |
+
# soup = BeautifulSoup(content, 'html.parser')
|
| 469 |
+
# all_tables = soup.find_all('table')
|
| 470 |
+
# tables = []
|
| 471 |
+
# positions = []
|
| 472 |
+
|
| 473 |
+
# for table in all_tables:
|
| 474 |
+
# if table.find_parent('table') is None:
|
| 475 |
+
# table_str = str(table)
|
| 476 |
+
# start_pos = content.find(table_str)
|
| 477 |
+
# end_pos = start_pos + len(table_str)
|
| 478 |
+
|
| 479 |
+
# tables.append(table_str)
|
| 480 |
+
# positions.append((start_pos, end_pos))
|
| 481 |
+
# return tables, positions
|
| 482 |
+
|
| 483 |
+
def extract_html_table(text):
|
| 484 |
+
begin_pattern = r'<table(?:[^>]*)>'
|
| 485 |
+
end_pattern = r'</table>'
|
| 486 |
+
|
| 487 |
+
tabulars = []
|
| 488 |
+
positions = []
|
| 489 |
+
current_pos = 0
|
| 490 |
+
stack = []
|
| 491 |
+
|
| 492 |
+
while current_pos < len(text):
|
| 493 |
+
begin_match = re.search(begin_pattern, text[current_pos:])
|
| 494 |
+
end_match = re.search(end_pattern, text[current_pos:])
|
| 495 |
+
|
| 496 |
+
if not begin_match and not end_match:
|
| 497 |
+
break
|
| 498 |
+
|
| 499 |
+
if begin_match and (not end_match or begin_match.start() < end_match.start()):
|
| 500 |
+
stack.append(current_pos + begin_match.start())
|
| 501 |
+
current_pos += begin_match.start() + len(end_pattern)
|
| 502 |
+
elif end_match:
|
| 503 |
+
if stack:
|
| 504 |
+
start_pos = stack.pop()
|
| 505 |
+
if not stack:
|
| 506 |
+
end_pos = current_pos + end_match.start() + len(end_pattern)
|
| 507 |
+
tabular_code = text[start_pos:end_pos]
|
| 508 |
+
tabulars.append(tabular_code)
|
| 509 |
+
positions.append((start_pos, end_pos))
|
| 510 |
+
current_pos += end_match.start() + len(end_pattern)
|
| 511 |
+
else:
|
| 512 |
+
current_pos += 1
|
| 513 |
+
|
| 514 |
+
if stack:
|
| 515 |
+
new_start = stack[0] + len(begin_pattern)
|
| 516 |
+
new_tabulars, new_positions = extract_html_table(text[new_start:])
|
| 517 |
+
new_positions = [(start + new_start, end + new_start) for start, end in new_positions]
|
| 518 |
+
tabulars.extend(new_tabulars)
|
| 519 |
+
positions.extend(new_positions)
|
| 520 |
+
|
| 521 |
+
return tabulars, positions
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def extract_node_content(node):
|
| 525 |
+
""" Recursively extract content from LatexEnvironmentNode and rebuild LaTeX table representation """
|
| 526 |
+
if isinstance(node, LatexCharsNode):
|
| 527 |
+
return node.chars # Use chars attribute
|
| 528 |
+
elif isinstance(node, LatexGroupNode):
|
| 529 |
+
return "{" + "".join(extract_node_content(n) for n in node.nodelist) + "}"
|
| 530 |
+
elif isinstance(node, LatexMacroNode):
|
| 531 |
+
# Extract macro command and its arguments
|
| 532 |
+
macro_content = "\\" + node.macroname
|
| 533 |
+
if node.nodeargs:
|
| 534 |
+
macro_content += "".join([extract_node_content(arg) for arg in node.nodeargs])
|
| 535 |
+
return macro_content
|
| 536 |
+
elif isinstance(node, LatexEnvironmentNode):
|
| 537 |
+
# Extract environment, preserve environment name and arguments
|
| 538 |
+
content = "\\begin{" + node.environmentname + "}"
|
| 539 |
+
if node.nodeargd and node.nodeargd.argnlist:
|
| 540 |
+
# content += "".join("{" + extract_node_content(arg) + "}" for arg in node.nodeargd)
|
| 541 |
+
# content += "".join("{" + extract_node_content(node.nodeargd) + "}")
|
| 542 |
+
content += "{" + extract_node_content(node.nodeargd.argnlist[0]) + "}"
|
| 543 |
+
if node.nodelist:
|
| 544 |
+
content += "".join(extract_node_content(n) for n in node.nodelist)
|
| 545 |
+
content += "\\end{" + node.environmentname + "}"
|
| 546 |
+
return content
|
| 547 |
+
elif isinstance(node, LatexSpecialsNode): # Changed to LatexSpecialsNode
|
| 548 |
+
return node.specials_chars
|
| 549 |
+
else:
|
| 550 |
+
return ""
|
| 551 |
+
|
| 552 |
+
def get_node_end_pos(node):
|
| 553 |
+
"""Recursively determine the end position of a node"""
|
| 554 |
+
if hasattr(node, 'nodelist') and node.nodelist:
|
| 555 |
+
# If the node has child nodes, recursively find the end position of the last child node
|
| 556 |
+
return get_node_end_pos(node.nodelist[-1])
|
| 557 |
+
elif hasattr(node, 'pos_end'):
|
| 558 |
+
# If the node has pos_end attribute, return it directly
|
| 559 |
+
return node.pos_end
|
| 560 |
+
else:
|
| 561 |
+
# If there are no child nodes, assume the node ends at the last character of its content
|
| 562 |
+
return node.pos + len(str(node))
|
| 563 |
+
|
| 564 |
+
def remove_tex_table(content):
|
| 565 |
+
tables, positions = extract_tex_table(content)
|
| 566 |
+
|
| 567 |
+
# Delete in reverse order by position to avoid affecting unprocessed start positions
|
| 568 |
+
for start, end in sorted(positions, reverse=True):
|
| 569 |
+
content = content[:start] + content[end:] # Remove table content
|
| 570 |
+
|
| 571 |
+
return content
|
FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/match.py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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from scipy.optimize import linear_sum_assignment
|
| 2 |
+
import Levenshtein
|
| 3 |
+
import numpy as np
|
| 4 |
+
import re
|
| 5 |
+
import sys
|
| 6 |
+
import pdb
|
| 7 |
+
from .data_preprocess import textblock_with_norm_formula, normalized_formula, textblock2unicode, clean_string
|
| 8 |
+
import re
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
|
| 12 |
+
def get_pred_category_type(pred_idx, pred_items):
|
| 13 |
+
if pred_items[pred_idx].get('fine_category_type'):
|
| 14 |
+
pred_pred_category_type = pred_items[pred_idx]['fine_category_type']
|
| 15 |
+
else:
|
| 16 |
+
pred_pred_category_type = pred_items[pred_idx]['category_type']
|
| 17 |
+
return pred_pred_category_type
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def compute_edit_distance_matrix_new(gt_lines, matched_lines):
|
| 21 |
+
try:
|
| 22 |
+
distance_matrix = np.zeros((len(gt_lines), len(matched_lines)))
|
| 23 |
+
for i, gt_line in enumerate(gt_lines):
|
| 24 |
+
for j, matched_line in enumerate(matched_lines):
|
| 25 |
+
if len(gt_line) == 0 and len(matched_line) == 0:
|
| 26 |
+
distance_matrix[i][j] = 0
|
| 27 |
+
else:
|
| 28 |
+
distance_matrix[i][j] = Levenshtein.distance(gt_line, matched_line) / max(len(matched_line), len(gt_line))
|
| 29 |
+
return distance_matrix
|
| 30 |
+
except ZeroDivisionError:
|
| 31 |
+
raise
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
## 混合匹配here 0403
|
| 35 |
+
def get_gt_pred_lines(gt_mix,pred_dataset_mix,line_type):
|
| 36 |
+
|
| 37 |
+
norm_html_lines,gt_lines,pred_lines,norm_gt_lines,norm_pred_lines,gt_cat_list = [],[],[],[],[],[]
|
| 38 |
+
if line_type in ['html_table','latex_table']:
|
| 39 |
+
for item in gt_mix:
|
| 40 |
+
if item.get('fine_category_type'):
|
| 41 |
+
gt_cat_list.append(item['fine_category_type'])
|
| 42 |
+
else:
|
| 43 |
+
gt_cat_list.append(item['category_type'])
|
| 44 |
+
if item.get('content'):
|
| 45 |
+
gt_lines.append(str(item['content']))
|
| 46 |
+
norm_html_lines.append(str(item['content']))
|
| 47 |
+
elif line_type == 'text':
|
| 48 |
+
gt_lines.append(str(item['text']))
|
| 49 |
+
elif line_type == 'html_table':
|
| 50 |
+
gt_lines.append(str(item['html']))
|
| 51 |
+
elif line_type == 'formula':
|
| 52 |
+
gt_lines.append(str(item['latex']))
|
| 53 |
+
elif line_type == 'latex_table':
|
| 54 |
+
try:
|
| 55 |
+
gt_lines.append(str(item['latex']))
|
| 56 |
+
except:
|
| 57 |
+
print(item)
|
| 58 |
+
gt_lines.append("")
|
| 59 |
+
norm_html_lines.append(str(item['html']))
|
| 60 |
+
|
| 61 |
+
pred_lines = [str(item['content']) for item in pred_dataset_mix]
|
| 62 |
+
if line_type == 'formula':
|
| 63 |
+
norm_gt_lines = [normalized_formula(_) for _ in gt_lines]
|
| 64 |
+
norm_pred_lines = [normalized_formula(_) for _ in pred_lines]
|
| 65 |
+
elif line_type == 'text':
|
| 66 |
+
norm_gt_lines = [clean_string(textblock2unicode(_)) for _ in gt_lines]
|
| 67 |
+
norm_pred_lines = [clean_string(textblock2unicode(_)) for _ in pred_lines]
|
| 68 |
+
else:
|
| 69 |
+
norm_gt_lines = gt_lines
|
| 70 |
+
norm_pred_lines = pred_lines
|
| 71 |
+
if line_type == 'latex_table':
|
| 72 |
+
gt_lines = norm_html_lines
|
| 73 |
+
|
| 74 |
+
else:
|
| 75 |
+
for item in pred_dataset_mix:
|
| 76 |
+
# text
|
| 77 |
+
if item['category_type'] == 'text_all':
|
| 78 |
+
pred_lines.append(str(item['content']))
|
| 79 |
+
norm_pred_lines.append(clean_string(textblock2unicode(str(item['content']))))
|
| 80 |
+
# formula
|
| 81 |
+
elif item['category_type']=='equation_isolated':
|
| 82 |
+
pred_lines.append(str(item['content']))
|
| 83 |
+
norm_pred_lines.append(normalized_formula(str(item['content'])))
|
| 84 |
+
# table
|
| 85 |
+
else:
|
| 86 |
+
pred_lines.append(str(item['content']))
|
| 87 |
+
norm_pred_lines.append(str(item['content']))
|
| 88 |
+
|
| 89 |
+
for item in gt_mix:
|
| 90 |
+
if item.get('content'):
|
| 91 |
+
gt_lines.append(str(item['content']))
|
| 92 |
+
if item['category_type'] == 'text_all':
|
| 93 |
+
norm_gt_lines.append(clean_string(textblock2unicode(str(item['content']))))
|
| 94 |
+
else:
|
| 95 |
+
norm_gt_lines.append(item['content'])
|
| 96 |
+
|
| 97 |
+
norm_html_lines.append(str(item['content']))
|
| 98 |
+
|
| 99 |
+
if item.get('fine_category_type'):
|
| 100 |
+
gt_cat_list.append(item['fine_category_type'])
|
| 101 |
+
else:
|
| 102 |
+
gt_cat_list.append(item['category_type'])
|
| 103 |
+
# text
|
| 104 |
+
elif item['category_type'] in ['text_block', 'title', 'code_txt', 'code_txt_caption', 'reference', 'equation_caption','figure_caption', 'figure_footnote', 'table_caption', 'table_footnote', 'code_algorithm', 'code_algorithm_caption','header', 'footer', 'page_footnote', 'page_number']:
|
| 105 |
+
gt_lines.append(str(item['text']))
|
| 106 |
+
norm_gt_lines.append(clean_string(textblock2unicode(str(item['text']))))
|
| 107 |
+
|
| 108 |
+
if item.get('fine_category_type'):
|
| 109 |
+
gt_cat_list.append(item['fine_category_type'])
|
| 110 |
+
else:
|
| 111 |
+
gt_cat_list.append(item['category_type'])
|
| 112 |
+
|
| 113 |
+
# formula
|
| 114 |
+
elif item['category_type'] == 'equation_isolated':
|
| 115 |
+
gt_lines.append(str(item['latex']))
|
| 116 |
+
norm_gt_lines.append(normalized_formula(str(item['latex'])))
|
| 117 |
+
|
| 118 |
+
if item.get('fine_category_type'):
|
| 119 |
+
gt_cat_list.append(item['fine_category_type'])
|
| 120 |
+
else:
|
| 121 |
+
gt_cat_list.append(item['category_type'])
|
| 122 |
+
# table
|
| 123 |
+
# elif item['category_type'] == 'table':
|
| 124 |
+
# gt_lines.append(str(item['html']))
|
| 125 |
+
# norm_gt_lines.append(str(item['html']))
|
| 126 |
+
|
| 127 |
+
# if item.get('fine_category_type'):
|
| 128 |
+
# gt_cat_list.append(item['fine_category_type'])
|
| 129 |
+
# else:
|
| 130 |
+
# gt_cat_list.append(item['category_type'])
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
filtered_lists = [(a, b, c) for a, b, c in zip(gt_lines, norm_gt_lines, gt_cat_list) if a and b]
|
| 134 |
+
|
| 135 |
+
# decompress to three lists
|
| 136 |
+
if filtered_lists:
|
| 137 |
+
gt_lines_c, norm_gt_lines_c, gt_cat_list_c = zip(*filtered_lists)
|
| 138 |
+
|
| 139 |
+
# convert to lists
|
| 140 |
+
gt_lines_c = list(gt_lines_c)
|
| 141 |
+
norm_gt_lines_c = list(norm_gt_lines_c)
|
| 142 |
+
gt_cat_list_c = list(gt_cat_list_c)
|
| 143 |
+
else:
|
| 144 |
+
gt_lines_c = []
|
| 145 |
+
norm_gt_lines_c = []
|
| 146 |
+
gt_cat_list_c = []
|
| 147 |
+
|
| 148 |
+
# pred's empty values
|
| 149 |
+
filtered_lists = [(a, b) for a, b in zip(pred_lines, norm_pred_lines) if a and b]
|
| 150 |
+
|
| 151 |
+
# decompress to two lists
|
| 152 |
+
if filtered_lists:
|
| 153 |
+
pred_lines_c, norm_pred_lines_c = zip(*filtered_lists)
|
| 154 |
+
|
| 155 |
+
# convert to lists
|
| 156 |
+
pred_lines_c = list(pred_lines_c)
|
| 157 |
+
norm_pred_lines_c = list(norm_pred_lines_c)
|
| 158 |
+
else:
|
| 159 |
+
pred_lines_c = []
|
| 160 |
+
norm_pred_lines_c = []
|
| 161 |
+
|
| 162 |
+
return gt_lines_c, norm_gt_lines_c, gt_cat_list_c, pred_lines_c, norm_pred_lines_c, gt_mix, pred_dataset_mix
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def match_gt2pred_simple(gt_items, pred_items, line_type, img_name):
|
| 166 |
+
|
| 167 |
+
gt_lines, norm_gt_lines, gt_cat_list, pred_lines, norm_pred_lines, gt_items, pred_items = get_gt_pred_lines(gt_items, pred_items,line_type)
|
| 168 |
+
match_list = []
|
| 169 |
+
|
| 170 |
+
if not norm_gt_lines: # not matched pred should be concatenate
|
| 171 |
+
pred_idx_list = range(len(norm_pred_lines))
|
| 172 |
+
match_list.append({
|
| 173 |
+
'gt_idx': [""],
|
| 174 |
+
'gt': "",
|
| 175 |
+
'pred_idx': pred_idx_list,
|
| 176 |
+
'pred': ''.join(pred_lines[_] for _ in pred_idx_list),
|
| 177 |
+
'gt_position': [""],
|
| 178 |
+
'pred_position': pred_items[pred_idx_list[0]]['position'][0], # get the first pred's position
|
| 179 |
+
'norm_gt': "",
|
| 180 |
+
'norm_pred': ''.join(norm_pred_lines[_] for _ in pred_idx_list),
|
| 181 |
+
'gt_category_type': "",
|
| 182 |
+
'pred_category_type': get_pred_category_type(pred_idx_list[0], pred_items), # get the first pred's category
|
| 183 |
+
'gt_attribute': [{}],
|
| 184 |
+
'edit': 1,
|
| 185 |
+
'img_id': img_name
|
| 186 |
+
})
|
| 187 |
+
return match_list,None
|
| 188 |
+
elif not norm_pred_lines: # not matched gt should be separated
|
| 189 |
+
for gt_idx in range(len(norm_gt_lines)):
|
| 190 |
+
match_list.append({
|
| 191 |
+
'gt_idx': [gt_idx],
|
| 192 |
+
'gt': gt_lines[gt_idx],
|
| 193 |
+
'pred_idx': [""],
|
| 194 |
+
'pred': "",
|
| 195 |
+
'gt_position': [gt_items[gt_idx].get('order') if gt_items[gt_idx].get('order') else gt_items[gt_idx].get('position', [""])[0]],
|
| 196 |
+
'pred_position': "",
|
| 197 |
+
'norm_gt': norm_gt_lines[gt_idx],
|
| 198 |
+
'norm_pred': "",
|
| 199 |
+
'gt_category_type': gt_cat_list[gt_idx],
|
| 200 |
+
'pred_category_type': "",
|
| 201 |
+
'gt_attribute': [gt_items[gt_idx].get("attribute", {})],
|
| 202 |
+
'edit': 1,
|
| 203 |
+
'img_id': img_name
|
| 204 |
+
})
|
| 205 |
+
return match_list,None
|
| 206 |
+
|
| 207 |
+
cost_matrix = compute_edit_distance_matrix_new(norm_gt_lines, norm_pred_lines)
|
| 208 |
+
|
| 209 |
+
row_ind, col_ind = linear_sum_assignment(cost_matrix)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
for gt_idx in range(len(norm_gt_lines)):
|
| 213 |
+
if gt_idx in row_ind:
|
| 214 |
+
row_i = list(row_ind).index(gt_idx)
|
| 215 |
+
pred_idx = int(col_ind[row_i])
|
| 216 |
+
pred_line = pred_lines[pred_idx]
|
| 217 |
+
norm_pred_line = norm_pred_lines[pred_idx]
|
| 218 |
+
edit = cost_matrix[gt_idx][pred_idx]
|
| 219 |
+
else:
|
| 220 |
+
pred_idx = ""
|
| 221 |
+
pred_line = ""
|
| 222 |
+
norm_pred_line = ""
|
| 223 |
+
edit = 1
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
match_list.append({
|
| 227 |
+
'gt_idx': [gt_idx],
|
| 228 |
+
'gt': gt_lines[gt_idx],
|
| 229 |
+
'norm_gt': norm_gt_lines[gt_idx],
|
| 230 |
+
'gt_category_type': gt_cat_list[gt_idx],
|
| 231 |
+
'gt_position': [gt_items[gt_idx].get('order') if gt_items[gt_idx].get('order') else gt_items[gt_idx].get('position', [""])[0]],
|
| 232 |
+
'gt_attribute': [gt_items[gt_idx].get("attribute", {})],
|
| 233 |
+
'pred_idx': [pred_idx],
|
| 234 |
+
'pred': pred_line,
|
| 235 |
+
'norm_pred': norm_pred_line,
|
| 236 |
+
'pred_category_type': get_pred_category_type(pred_idx, pred_items) if pred_idx else "",
|
| 237 |
+
'pred_position': pred_items[pred_idx]['position'][0] if pred_idx else "",
|
| 238 |
+
'edit': edit,
|
| 239 |
+
'img_id': img_name
|
| 240 |
+
})
|
| 241 |
+
|
| 242 |
+
pred_idx_list = [pred_idx for pred_idx in range(len(norm_pred_lines)) if pred_idx not in col_ind] # get not matched preds
|
| 243 |
+
if pred_idx_list:
|
| 244 |
+
if line_type in ['html_table', 'latex_table']:
|
| 245 |
+
unmatch_table_pred = []
|
| 246 |
+
for i in pred_idx_list:
|
| 247 |
+
original_item = pred_items[i]
|
| 248 |
+
soup = BeautifulSoup(original_item.get('content'),'html.parser')
|
| 249 |
+
text_block = [re.sub(r'\$\\cdot\$','',item.string).strip() for item in soup.findAll('td') if item.string]
|
| 250 |
+
for concatenate_text in text_block:
|
| 251 |
+
new_item = deepcopy(original_item)
|
| 252 |
+
new_item['content'] = concatenate_text
|
| 253 |
+
new_item['category_type'] = 'text_all'
|
| 254 |
+
unmatch_table_pred.append(new_item)
|
| 255 |
+
return match_list, unmatch_table_pred
|
| 256 |
+
|
| 257 |
+
else:
|
| 258 |
+
match_list.append({
|
| 259 |
+
'gt_idx': [""],
|
| 260 |
+
'gt': "",
|
| 261 |
+
'pred_idx': pred_idx_list,
|
| 262 |
+
'pred': ''.join(pred_lines[_] for _ in pred_idx_list),
|
| 263 |
+
'gt_position': [""],
|
| 264 |
+
'pred_position': pred_items[pred_idx_list[0]]['position'][0], # get the first pred's position
|
| 265 |
+
'norm_gt': "",
|
| 266 |
+
'norm_pred': ''.join(norm_pred_lines[_] for _ in pred_idx_list),
|
| 267 |
+
'gt_category_type': "",
|
| 268 |
+
'pred_category_type': get_pred_category_type(pred_idx_list[0], pred_items), # get the first pred's category
|
| 269 |
+
'gt_attribute': [{}],
|
| 270 |
+
'edit': 1,
|
| 271 |
+
'img_id': img_name
|
| 272 |
+
})
|
| 273 |
+
return match_list,None
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def match_gt2pred_no_split(gt_items, pred_items, line_type, img_name):
|
| 277 |
+
# directly concatenate gt and pred by position
|
| 278 |
+
gt_lines, norm_gt_lines, gt_cat_list, pred_lines, norm_pred_lines = get_gt_pred_lines(gt_items, pred_items)
|
| 279 |
+
gt_line_with_position = []
|
| 280 |
+
for gt_line, norm_gt_line, gt_item in zip(gt_lines, norm_gt_lines, gt_items):
|
| 281 |
+
gt_position = gt_item['order'] if gt_item.get('order') else gt_item.get('position', [""])[0]
|
| 282 |
+
if gt_position:
|
| 283 |
+
gt_line_with_position.append((gt_position, gt_line, norm_gt_line))
|
| 284 |
+
sorted_gt_lines = sorted(gt_line_with_position, key=lambda x: x[0])
|
| 285 |
+
gt = '\n\n'.join([_[1] for _ in sorted_gt_lines])
|
| 286 |
+
norm_gt = '\n\n'.join([_[2] for _ in sorted_gt_lines])
|
| 287 |
+
pred_line_with_position = [(pred_item['position'], pred_line, pred_norm_line) for pred_line, pred_norm_line, pred_item in zip(pred_lines, norm_pred_lines, pred_items)]
|
| 288 |
+
sorted_pred_lines = sorted(pred_line_with_position, key=lambda x: x[0])
|
| 289 |
+
pred = '\n\n'.join([_[1] for _ in sorted_pred_lines])
|
| 290 |
+
norm_pred = '\n\n'.join([_[2] for _ in sorted_pred_lines])
|
| 291 |
+
# edit = Levenshtein.distance(norm_gt, norm_pred)/max(len(norm_gt), len(norm_pred))
|
| 292 |
+
if norm_gt or norm_pred:
|
| 293 |
+
return [{
|
| 294 |
+
'gt_idx': [0],
|
| 295 |
+
'gt': gt,
|
| 296 |
+
'norm_gt': norm_gt,
|
| 297 |
+
'gt_category_type': "text_merge",
|
| 298 |
+
'gt_position': [""],
|
| 299 |
+
'gt_attribute': [{}],
|
| 300 |
+
'pred_idx': [0],
|
| 301 |
+
'pred': pred,
|
| 302 |
+
'norm_pred': norm_pred,
|
| 303 |
+
'pred_category_type': "text_merge",
|
| 304 |
+
'pred_position': "",
|
| 305 |
+
# 'edit': edit,
|
| 306 |
+
'img_id': img_name
|
| 307 |
+
}]
|
| 308 |
+
else:
|
| 309 |
+
return []
|
| 310 |
+
|
FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/match_quick.py
ADDED
|
@@ -0,0 +1,1292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from scipy.optimize import linear_sum_assignment
|
| 2 |
+
# from rapidfuzz.distance import Levenshtein
|
| 3 |
+
import Levenshtein
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
import copy
|
| 6 |
+
from .match import compute_edit_distance_matrix_new, get_gt_pred_lines, get_pred_category_type
|
| 7 |
+
import pdb
|
| 8 |
+
import numpy as np
|
| 9 |
+
from collections import Counter
|
| 10 |
+
from Levenshtein import distance as Levenshtein_distance
|
| 11 |
+
|
| 12 |
+
import re
|
| 13 |
+
from copy import deepcopy
|
| 14 |
+
from typing import List, Dict, Any
|
| 15 |
+
|
| 16 |
+
# ARRAY_RE = re.compile(
|
| 17 |
+
# r'\\begin\{array\}\{[^}]*\}(.*?)\\end\{array\}', re.S
|
| 18 |
+
# )
|
| 19 |
+
|
| 20 |
+
# def split_gt_equation_arrays(data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 21 |
+
# """
|
| 22 |
+
# 拆分带 \\begin{array} … \\end{array} 的 GT 字典条目。
|
| 23 |
+
|
| 24 |
+
# - 仅针对 category_type == 'equation_isolated' 且 latex 含 array。
|
| 25 |
+
# - 每行公式拆出一个新条目:
|
| 26 |
+
# * 更新 'latex'
|
| 27 |
+
# * 若存在 line_with_spans,则同步替换其内部 latex
|
| 28 |
+
# * 'order' 由 7 --> 7.1, 7.2, …
|
| 29 |
+
# """
|
| 30 |
+
# output = []
|
| 31 |
+
|
| 32 |
+
# for item in data:
|
| 33 |
+
# # 只处理满足条件的字典
|
| 34 |
+
# if (item.get("category_type") == "equation_isolated" and
|
| 35 |
+
# "\\begin{array" in item.get("latex", "")):
|
| 36 |
+
|
| 37 |
+
# # 抽取 array 内部内容
|
| 38 |
+
# match = ARRAY_RE.search(item["latex"])
|
| 39 |
+
# if match:
|
| 40 |
+
# body = match.group(1) # 去掉 array 外壳
|
| 41 |
+
# # 按 LaTeX 行分隔符 \\\\ 拆分
|
| 42 |
+
# lines = [ln.strip() for ln in re.split(r'\\\\', body) if ln.strip()]
|
| 43 |
+
|
| 44 |
+
# base_order = float(item["order"]) # 7 -> 7.0,可兼容 float/int
|
| 45 |
+
|
| 46 |
+
# for idx, line in enumerate(lines, start=1):
|
| 47 |
+
# new_item = deepcopy(item)
|
| 48 |
+
# new_item["latex"] = f"\\[{line}\\]"
|
| 49 |
+
# new_item["order"] = round(base_order + idx / 10, 1)
|
| 50 |
+
# output.append(new_item)
|
| 51 |
+
# continue # 跳过把原 item 加入
|
| 52 |
+
# # 其它情况不修改
|
| 53 |
+
# output.append(item)
|
| 54 |
+
|
| 55 |
+
# return output
|
| 56 |
+
|
| 57 |
+
# def _wrap(line: str) -> str:
|
| 58 |
+
# """给单行公式重新包 \\[ ... \\]"""
|
| 59 |
+
# return f"\\[{line.strip()}\\]"
|
| 60 |
+
|
| 61 |
+
# def split_equation_arrays(data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 62 |
+
# """
|
| 63 |
+
# 处理 category_type == 'equation_isolated' 且含 \\begin{array} … 的条目:
|
| 64 |
+
# * 拆分多行公式
|
| 65 |
+
# * 重新包装 content
|
| 66 |
+
# * **重计算 position / positions**
|
| 67 |
+
# """
|
| 68 |
+
# out: List[Dict[str, Any]] = []
|
| 69 |
+
|
| 70 |
+
# for item in data:
|
| 71 |
+
# if (item.get("category_type") == "equation_isolated" and
|
| 72 |
+
# "\\begin{array" in item.get("content", "")):
|
| 73 |
+
|
| 74 |
+
# content = item["content"]
|
| 75 |
+
# m = ARRAY_RE.search(content)
|
| 76 |
+
# if not m:
|
| 77 |
+
# out.append(item)
|
| 78 |
+
# continue
|
| 79 |
+
|
| 80 |
+
# body = m.group(1)
|
| 81 |
+
# lines = [ln.strip() for ln in re.split(r'\\\\', body) if ln.strip()]
|
| 82 |
+
|
| 83 |
+
# # 全局起始字符索引
|
| 84 |
+
# pos_key = "position" if "position" in item else "positions"
|
| 85 |
+
# global_start = item[pos_key][0]
|
| 86 |
+
|
| 87 |
+
# # array 正文在原 content 内的起点
|
| 88 |
+
# body_start_in_content = m.start(1)
|
| 89 |
+
|
| 90 |
+
# search_from = 0 # 在 body 中的游标
|
| 91 |
+
# for ln in lines:
|
| 92 |
+
# # 在 body 中找到当前行的偏移
|
| 93 |
+
# idx_in_body = body.find(ln, search_from)
|
| 94 |
+
# if idx_in_body == -1:
|
| 95 |
+
# # 不太可能发生;保守处理
|
| 96 |
+
# idx_in_body = search_from
|
| 97 |
+
# search_from = idx_in_body + len(ln) # 更新游标
|
| 98 |
+
|
| 99 |
+
# # 计算全局索引
|
| 100 |
+
# line_start_global = global_start + body_start_in_content + idx_in_body
|
| 101 |
+
# line_end_global = line_start_global + len(ln) - 1
|
| 102 |
+
|
| 103 |
+
# new_item = deepcopy(item)
|
| 104 |
+
# new_item["content"] = _wrap(ln)
|
| 105 |
+
# new_item[pos_key] = [line_start_global, line_end_global]
|
| 106 |
+
|
| 107 |
+
# out.append(new_item)
|
| 108 |
+
|
| 109 |
+
# # 拆分完成,不保留原条目
|
| 110 |
+
# continue
|
| 111 |
+
|
| 112 |
+
# # 其它条目直接加入
|
| 113 |
+
# out.append(item)
|
| 114 |
+
|
| 115 |
+
# return out
|
| 116 |
+
|
| 117 |
+
ARRAY_RE = re.compile(
|
| 118 |
+
r'\\begin\{array\}\{(?P<spec>[^}]*)\}(?P<body>.*?)\\end\{array\}',
|
| 119 |
+
re.S
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
def is_all_l(spec: str) -> bool:
|
| 123 |
+
"""检查是否为单列array格式,用于排除矩阵等多列格式。这个函数只拆分单列的array"""
|
| 124 |
+
spec = re.sub(r'\s+|\|', '', spec) # 删空白与竖线
|
| 125 |
+
spec = re.sub(r'@{[^}]*}', '', spec) # 删 @{…} 修饰
|
| 126 |
+
spec = re.sub(r'!{[^}]*}', '', spec) # 删 !{…} 修饰
|
| 127 |
+
# 检查是否为单列基本对齐格式:l, c, r
|
| 128 |
+
return bool(spec) and len(spec) == 1 and spec in {'l', 'c', 'r'}
|
| 129 |
+
|
| 130 |
+
# def is_all_l(spec: str) -> bool:
|
| 131 |
+
# """忽略空格 / 竖线 / @{…} 之后,判断列格式是否只剩基本对齐格式。这个函数会将多行多列的array按行拆分"""
|
| 132 |
+
# spec = re.sub(r'\s+|\|', '', spec) # 删空白与竖线
|
| 133 |
+
# spec = re.sub(r'@{[^}]*}', '', spec) # 删 @{…} 修饰
|
| 134 |
+
# spec = re.sub(r'!{[^}]*}', '', spec) # 删 !{…} 修饰
|
| 135 |
+
# # 检查是否只包含基本对齐格式:l, c, r
|
| 136 |
+
# return bool(spec) and set(spec) <= {'l', 'c', 'r'}
|
| 137 |
+
|
| 138 |
+
def split_gt_equation_arrays(data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 139 |
+
"""
|
| 140 |
+
拆分带 \\begin{array} … \\end{array} 的 GT 字典条目。
|
| 141 |
+
|
| 142 |
+
- 仅针对 category_type == 'equation_isolated' 且 latex 含 array。
|
| 143 |
+
- 每行公式拆出一个新条目:
|
| 144 |
+
* 更新 'latex'
|
| 145 |
+
* 若存在 line_with_spans,则同步替换其内部 latex
|
| 146 |
+
* 'order' 由 7 --> 7.1, 7.2, …
|
| 147 |
+
"""
|
| 148 |
+
output = []
|
| 149 |
+
|
| 150 |
+
for item in data:
|
| 151 |
+
# 只处理满足条件的字典
|
| 152 |
+
if (item.get("category_type") == "equation_isolated" and
|
| 153 |
+
"\\begin{array" in item.get("latex", "")):
|
| 154 |
+
|
| 155 |
+
# 抽取 array 内部内容
|
| 156 |
+
match = ARRAY_RE.search(item["latex"])
|
| 157 |
+
if match:
|
| 158 |
+
|
| 159 |
+
spec = match.group("spec")
|
| 160 |
+
if not is_all_l(spec):
|
| 161 |
+
# 若列里混有 r / c / p{…} 等,直接保留原条目
|
| 162 |
+
output.append(item)
|
| 163 |
+
continue
|
| 164 |
+
|
| 165 |
+
body = match.group("body")
|
| 166 |
+
# body = match.group(1) # 去掉 array 外壳
|
| 167 |
+
# 按 LaTeX 行分隔符 \\\\ 拆分
|
| 168 |
+
lines = [ln.strip() for ln in re.split(r'\\\\', body) if ln.strip()]
|
| 169 |
+
|
| 170 |
+
base_order = float(item["order"]) # 7 -> 7.0,可兼容 float/int
|
| 171 |
+
|
| 172 |
+
for idx, line in enumerate(lines, start=1):
|
| 173 |
+
new_item = deepcopy(item)
|
| 174 |
+
new_item["latex"] = f"\\[{line}\\]"
|
| 175 |
+
new_item["order"] = round(base_order + idx / 10, 1)
|
| 176 |
+
output.append(new_item)
|
| 177 |
+
continue # 跳过把原 item 加入
|
| 178 |
+
# 其它情况不修改
|
| 179 |
+
output.append(item)
|
| 180 |
+
|
| 181 |
+
return output
|
| 182 |
+
|
| 183 |
+
def _wrap(line: str) -> str:
|
| 184 |
+
"""给单行公式重新包 \\[ ... \\]"""
|
| 185 |
+
return f"\\[{line.strip()}\\]"
|
| 186 |
+
|
| 187 |
+
def split_equation_arrays(data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 188 |
+
"""
|
| 189 |
+
处理 category_type == 'equation_isolated' 且含 \\begin{array} … 的条目:
|
| 190 |
+
* 拆分多行公式
|
| 191 |
+
* 重新包装 content
|
| 192 |
+
* **重计算 position / positions**
|
| 193 |
+
"""
|
| 194 |
+
out: List[Dict[str, Any]] = []
|
| 195 |
+
|
| 196 |
+
for item in data:
|
| 197 |
+
if (item.get("category_type") == "equation_isolated" and
|
| 198 |
+
"\\begin{array" in item.get("content", "")):
|
| 199 |
+
|
| 200 |
+
content = item["content"]
|
| 201 |
+
m = ARRAY_RE.search(content)
|
| 202 |
+
if not m:
|
| 203 |
+
out.append(item)
|
| 204 |
+
continue
|
| 205 |
+
|
| 206 |
+
if not is_all_l(m.group('spec')):
|
| 207 |
+
out.append(item)
|
| 208 |
+
continue
|
| 209 |
+
|
| 210 |
+
# body = m.group(1)
|
| 211 |
+
body = m.group('body')
|
| 212 |
+
lines = [ln.strip() for ln in re.split(r'\\\\', body) if ln.strip()]
|
| 213 |
+
|
| 214 |
+
# 全局起始字符索引
|
| 215 |
+
pos_key = "position" if "position" in item else "positions"
|
| 216 |
+
global_start = item[pos_key][0]
|
| 217 |
+
|
| 218 |
+
# array 正文在原 content 内的起点
|
| 219 |
+
# body_start_in_content = m.start(1)
|
| 220 |
+
body_start_in_content = m.start('body')
|
| 221 |
+
|
| 222 |
+
search_from = 0 # 在 body 中的游标
|
| 223 |
+
for ln in lines:
|
| 224 |
+
# 在 body 中找到当前行的偏移
|
| 225 |
+
idx_in_body = body.find(ln, search_from)
|
| 226 |
+
if idx_in_body == -1:
|
| 227 |
+
# 不太可能发生;保守处理
|
| 228 |
+
idx_in_body = search_from
|
| 229 |
+
search_from = idx_in_body + len(ln) # 更新游标
|
| 230 |
+
|
| 231 |
+
# 计算全局索引
|
| 232 |
+
line_start_global = global_start + body_start_in_content + idx_in_body
|
| 233 |
+
line_end_global = line_start_global + len(ln) - 1
|
| 234 |
+
|
| 235 |
+
new_item = deepcopy(item)
|
| 236 |
+
new_item["content"] = _wrap(ln)
|
| 237 |
+
new_item[pos_key] = [line_start_global, line_end_global]
|
| 238 |
+
|
| 239 |
+
out.append(new_item)
|
| 240 |
+
|
| 241 |
+
# 拆分完成,不保留原条目
|
| 242 |
+
continue
|
| 243 |
+
|
| 244 |
+
# 其它条目直接加入
|
| 245 |
+
out.append(item)
|
| 246 |
+
|
| 247 |
+
return out
|
| 248 |
+
|
| 249 |
+
def sort_by_position_skip_inline(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 250 |
+
"""
|
| 251 |
+
先按 position[0] 从小到大排序;
|
| 252 |
+
若 fine_category_type == 'equation_inline',则统一放到最后,
|
| 253 |
+
并保持它们在原列表中的相对顺序(稳定排序)。
|
| 254 |
+
"""
|
| 255 |
+
# enumerate 保留原始顺序索引,用于 equation_inline “并列时” 的稳定性
|
| 256 |
+
return sorted(
|
| 257 |
+
enumerate(items),
|
| 258 |
+
key=lambda pair: (
|
| 259 |
+
pair[1].get('fine_category_type') == 'equation_inline', # False < True
|
| 260 |
+
pair[1]['position'][0], # 位置起点
|
| 261 |
+
pair[0] # 原序号,确保稳定
|
| 262 |
+
)
|
| 263 |
+
)
|
| 264 |
+
def match_gt2pred_quick(gt_items, pred_items, line_type, img_name):
|
| 265 |
+
# ========== 降级匹配阈值检测 ==========
|
| 266 |
+
# 当 pred_items 过多且远超 gt_items 时,降级为整体匹配,避免 O(m*n) 复杂度过高
|
| 267 |
+
MAX_PRED_ITEMS = 50000 # pred项数超过此值触发检查
|
| 268 |
+
RATIO_THRESHOLD = 100 # pred/gt 比例超过此值则降级
|
| 269 |
+
MAX_TOTAL_LENGTH = 10000000 # 内容总长度超过此值也降级
|
| 270 |
+
MAX_SINGLE_ITEM_LENGTH = 10000000 # 单个项内容超过此值也降级(针对大表格)
|
| 271 |
+
|
| 272 |
+
gt_count = len(gt_items)
|
| 273 |
+
pred_count = len(pred_items)
|
| 274 |
+
|
| 275 |
+
# 计算内容总长度
|
| 276 |
+
def get_item_content(item):
|
| 277 |
+
content = item.get('content')
|
| 278 |
+
if content is None:
|
| 279 |
+
content = item.get('text', '')
|
| 280 |
+
return str(content) if content else ''
|
| 281 |
+
|
| 282 |
+
gt_total_len = sum(len(get_item_content(item)) for item in gt_items)
|
| 283 |
+
pred_total_len = sum(len(get_item_content(item)) for item in pred_items)
|
| 284 |
+
|
| 285 |
+
# 计算单个项最大长度(针对大表格)
|
| 286 |
+
gt_max_len = max((len(get_item_content(item)) for item in gt_items), default=0)
|
| 287 |
+
pred_max_len = max((len(get_item_content(item)) for item in pred_items), default=0)
|
| 288 |
+
|
| 289 |
+
# 判断是否需要降级:项数过多 或 内容过大
|
| 290 |
+
need_downgrade = False
|
| 291 |
+
downgrade_reason = ""
|
| 292 |
+
|
| 293 |
+
if pred_count > MAX_PRED_ITEMS and gt_count > 0 and pred_count > RATIO_THRESHOLD * gt_count:
|
| 294 |
+
need_downgrade = True
|
| 295 |
+
downgrade_reason = f"pred_items({pred_count})/gt_items({gt_count})={pred_count/gt_count:.1f}"
|
| 296 |
+
elif gt_total_len > MAX_TOTAL_LENGTH or pred_total_len > MAX_TOTAL_LENGTH:
|
| 297 |
+
need_downgrade = True
|
| 298 |
+
downgrade_reason = f"content_too_large(gt_len={gt_total_len},pred_len={pred_total_len})"
|
| 299 |
+
elif gt_max_len > MAX_SINGLE_ITEM_LENGTH or pred_max_len > MAX_SINGLE_ITEM_LENGTH:
|
| 300 |
+
# 单个项内容过大(针对大表格导致的慢速编辑距离计算)
|
| 301 |
+
need_downgrade = True
|
| 302 |
+
downgrade_reason = f"single_item_too_large(gt_max={gt_max_len},pred_max={pred_max_len})"
|
| 303 |
+
|
| 304 |
+
if need_downgrade:
|
| 305 |
+
# 判断是否为表格类型
|
| 306 |
+
is_table_type = line_type in ['html_table', 'latex_table']
|
| 307 |
+
|
| 308 |
+
if is_table_type:
|
| 309 |
+
# 表格类型:不允许随意拼接,直接给低分
|
| 310 |
+
# 如果 GT 和 Pred 数量相同,尝试一一配对;否则 TEDS=0
|
| 311 |
+
print(f"[DOWNGRADE-TABLE] {img_name}: {downgrade_reason}, TEDS=0")
|
| 312 |
+
|
| 313 |
+
gt_positions = []
|
| 314 |
+
for item in gt_items:
|
| 315 |
+
pos = item.get('order')
|
| 316 |
+
if pos is None:
|
| 317 |
+
pos = item.get('position', [''])[0] if item.get('position') else ''
|
| 318 |
+
gt_positions.append(pos)
|
| 319 |
+
|
| 320 |
+
pred_positions = []
|
| 321 |
+
for item in pred_items:
|
| 322 |
+
pos = item.get('order')
|
| 323 |
+
if pos is None:
|
| 324 |
+
pos = item.get('position', [''])[0] if item.get('position') else ''
|
| 325 |
+
pred_positions.append(pos)
|
| 326 |
+
|
| 327 |
+
gt_category = gt_items[0].get('fine_category_type') or gt_items[0].get('category_type', line_type) if gt_items else line_type
|
| 328 |
+
pred_category = pred_items[0].get('fine_category_type') or pred_items[0].get('category_type', line_type) if pred_items else line_type
|
| 329 |
+
|
| 330 |
+
# 对于表格,返回一个 TEDS=0 的结果
|
| 331 |
+
gt_all = '\n'.join([get_item_content(item) for item in gt_items])
|
| 332 |
+
pred_all = '\n'.join([get_item_content(item) for item in pred_items])
|
| 333 |
+
|
| 334 |
+
return [{
|
| 335 |
+
'gt_idx': list(range(gt_count)),
|
| 336 |
+
'gt': gt_all,
|
| 337 |
+
'pred_idx': list(range(pred_count)),
|
| 338 |
+
'pred': pred_all,
|
| 339 |
+
'gt_position': gt_positions,
|
| 340 |
+
'pred_position': pred_positions[0] if pred_positions else "",
|
| 341 |
+
'norm_gt': gt_all,
|
| 342 |
+
'norm_pred': pred_all,
|
| 343 |
+
'gt_category_type': gt_category,
|
| 344 |
+
'pred_category_type': pred_category,
|
| 345 |
+
'gt_attribute': [item.get('attribute', {}) for item in gt_items],
|
| 346 |
+
'edit': 1.0, # edit 距离给最大值(表示完全不同)
|
| 347 |
+
'TEDS': 0.0, # TEDS 分数直接给 0
|
| 348 |
+
'img_id': img_name,
|
| 349 |
+
'downgrade': True,
|
| 350 |
+
'downgrade_reason': downgrade_reason
|
| 351 |
+
}]
|
| 352 |
+
else:
|
| 353 |
+
# 非表格类型:拼接后计算 edit_distance
|
| 354 |
+
gt_positions = []
|
| 355 |
+
for item in gt_items:
|
| 356 |
+
pos = item.get('order')
|
| 357 |
+
if pos is None:
|
| 358 |
+
pos = item.get('position', [''])[0] if item.get('position') else ''
|
| 359 |
+
gt_positions.append(pos)
|
| 360 |
+
|
| 361 |
+
pred_positions = []
|
| 362 |
+
for item in pred_items:
|
| 363 |
+
pos = item.get('order')
|
| 364 |
+
if pos is None:
|
| 365 |
+
pos = item.get('position', [''])[0] if item.get('position') else ''
|
| 366 |
+
pred_positions.append(pos)
|
| 367 |
+
|
| 368 |
+
gt_all = '\n'.join([get_item_content(item) for item in gt_items])
|
| 369 |
+
pred_all = '\n'.join([get_item_content(item) for item in pred_items])
|
| 370 |
+
|
| 371 |
+
if not gt_all and not pred_all:
|
| 372 |
+
edit = 0.0
|
| 373 |
+
elif not gt_all or not pred_all:
|
| 374 |
+
edit = 1.0
|
| 375 |
+
else:
|
| 376 |
+
edit_distance = Levenshtein_distance(gt_all, pred_all)
|
| 377 |
+
edit = edit_distance / max(len(gt_all), len(pred_all))
|
| 378 |
+
|
| 379 |
+
gt_category = gt_items[0].get('fine_category_type') or gt_items[0].get('category_type', line_type) if gt_items else line_type
|
| 380 |
+
pred_category = pred_items[0].get('fine_category_type') or pred_items[0].get('category_type', line_type) if pred_items else line_type
|
| 381 |
+
|
| 382 |
+
print(f"[DOWNGRADE] {img_name}: {downgrade_reason}, edit={edit:.4f}")
|
| 383 |
+
|
| 384 |
+
return [{
|
| 385 |
+
'gt_idx': list(range(gt_count)),
|
| 386 |
+
'gt': gt_all,
|
| 387 |
+
'pred_idx': list(range(pred_count)),
|
| 388 |
+
'pred': pred_all,
|
| 389 |
+
'gt_position': gt_positions,
|
| 390 |
+
'pred_position': pred_positions[0] if pred_positions else "",
|
| 391 |
+
'norm_gt': gt_all,
|
| 392 |
+
'norm_pred': pred_all,
|
| 393 |
+
'gt_category_type': gt_category,
|
| 394 |
+
'pred_category_type': pred_category,
|
| 395 |
+
'gt_attribute': [item.get('attribute', {}) for item in gt_items],
|
| 396 |
+
'edit': edit,
|
| 397 |
+
'img_id': img_name,
|
| 398 |
+
'downgrade': True,
|
| 399 |
+
'downgrade_reason': downgrade_reason
|
| 400 |
+
}]
|
| 401 |
+
# ========== 降级匹配检测结束 ==========
|
| 402 |
+
|
| 403 |
+
gt_items = split_gt_equation_arrays(gt_items)
|
| 404 |
+
|
| 405 |
+
# pred_items = sorted(pred_items, key=lambda x: x['position'][0])
|
| 406 |
+
pred_items = [pair[1] for pair in sort_by_position_skip_inline(pred_items)]
|
| 407 |
+
|
| 408 |
+
pred_items = split_equation_arrays(pred_items)
|
| 409 |
+
|
| 410 |
+
# gt_lines, norm_gt_lines, gt_cat_list, pred_lines, norm_pred_lines= get_gt_pred_lines(gt_items, pred_items, line_type)
|
| 411 |
+
gt_lines, norm_gt_lines, gt_cat_list, pred_lines, norm_pred_lines, gt_items, pred_items = get_gt_pred_lines(gt_items, pred_items, None)
|
| 412 |
+
all_gt_indices = set(range(len(norm_gt_lines)))
|
| 413 |
+
all_pred_indices = set(range(len(norm_pred_lines)))
|
| 414 |
+
|
| 415 |
+
if not norm_gt_lines:
|
| 416 |
+
match_list = []
|
| 417 |
+
for pred_idx in range(len(norm_pred_lines)):
|
| 418 |
+
match_list.append({
|
| 419 |
+
'gt_idx': [""],
|
| 420 |
+
'gt': "",
|
| 421 |
+
'pred_idx': [pred_idx],
|
| 422 |
+
'pred': pred_lines[pred_idx],
|
| 423 |
+
'gt_position': [""],
|
| 424 |
+
'pred_position': pred_items[pred_idx]['position'][0],
|
| 425 |
+
'norm_gt': "",
|
| 426 |
+
'norm_pred': norm_pred_lines[pred_idx],
|
| 427 |
+
'gt_category_type': "",
|
| 428 |
+
'pred_category_type': get_pred_category_type(pred_idx, pred_items),
|
| 429 |
+
'gt_attribute': [{}],
|
| 430 |
+
'edit': 1,
|
| 431 |
+
'img_id': img_name
|
| 432 |
+
})
|
| 433 |
+
return match_list
|
| 434 |
+
elif not norm_pred_lines:
|
| 435 |
+
match_list = []
|
| 436 |
+
for gt_idx in range(len(norm_gt_lines)):
|
| 437 |
+
match_list.append({
|
| 438 |
+
'gt_idx': [gt_idx],
|
| 439 |
+
'gt': gt_lines[gt_idx],
|
| 440 |
+
'pred_idx': [""],
|
| 441 |
+
'pred': "",
|
| 442 |
+
'gt_position': [gt_items[gt_idx].get('order') if gt_items[gt_idx].get('order') else gt_items[gt_idx].get('position', [""])[0]],
|
| 443 |
+
'pred_position': "",
|
| 444 |
+
'norm_gt': norm_gt_lines[gt_idx],
|
| 445 |
+
'norm_pred': "",
|
| 446 |
+
'gt_category_type': gt_cat_list[gt_idx],
|
| 447 |
+
'pred_category_type': "",
|
| 448 |
+
'gt_attribute': [gt_items[gt_idx].get("attribute", {})],
|
| 449 |
+
'edit': 1,
|
| 450 |
+
'img_id': img_name
|
| 451 |
+
})
|
| 452 |
+
return match_list
|
| 453 |
+
elif len(norm_gt_lines) == 1 and len(norm_pred_lines) == 1:
|
| 454 |
+
edit_distance = Levenshtein_distance(norm_gt_lines[0], norm_pred_lines[0])
|
| 455 |
+
normalized_edit_distance = edit_distance / max(len(norm_gt_lines[0]), len(norm_pred_lines[0]))
|
| 456 |
+
return [{
|
| 457 |
+
'gt_idx': [0],
|
| 458 |
+
'gt': gt_lines[0],
|
| 459 |
+
'pred_idx': [0],
|
| 460 |
+
'pred': pred_lines[0],
|
| 461 |
+
'gt_position': [gt_items[0].get('order') if gt_items[0].get('order') else gt_items[0].get('position', [""])[0]],
|
| 462 |
+
'pred_position': pred_items[0]['position'][0],
|
| 463 |
+
'norm_gt': norm_gt_lines[0],
|
| 464 |
+
'norm_pred': norm_pred_lines[0],
|
| 465 |
+
'gt_category_type': gt_cat_list[0],
|
| 466 |
+
'pred_category_type': get_pred_category_type(0, pred_items),
|
| 467 |
+
'gt_attribute': [gt_items[0].get("attribute", {})],
|
| 468 |
+
'edit': normalized_edit_distance,
|
| 469 |
+
'img_id': img_name
|
| 470 |
+
}]
|
| 471 |
+
|
| 472 |
+
# match category ignore first
|
| 473 |
+
ignores = ['figure_caption', 'figure_footnote', 'table_caption', 'table_footnote', 'code_algorithm',
|
| 474 |
+
'code_algorithm_caption', 'header', 'footer', 'page_footnote', 'page_number', 'equation_caption']
|
| 475 |
+
|
| 476 |
+
ignore_gt_lines = []
|
| 477 |
+
ignores_ori_gt_lines= []
|
| 478 |
+
ignores_gt_items = []
|
| 479 |
+
ignore_gt_idxs = []
|
| 480 |
+
ignores_gt_cat_list = []
|
| 481 |
+
|
| 482 |
+
no_ignores_gt_lines = []
|
| 483 |
+
no_ignores_ori_gt_lines = []
|
| 484 |
+
no_ignores_gt_idxs = []
|
| 485 |
+
no_ignores_gt_items = []
|
| 486 |
+
no_ignores_gt_cat_list = []
|
| 487 |
+
|
| 488 |
+
for i, line in enumerate(norm_gt_lines):
|
| 489 |
+
if gt_cat_list[i] in ignores:
|
| 490 |
+
ignore_gt_lines.append(line)
|
| 491 |
+
ignores_ori_gt_lines.append(gt_lines[i])
|
| 492 |
+
ignores_gt_items.append(gt_items[i])
|
| 493 |
+
ignore_gt_idxs.append(i)
|
| 494 |
+
ignores_gt_cat_list.append(gt_cat_list[i])
|
| 495 |
+
else:
|
| 496 |
+
no_ignores_gt_lines.append(line)
|
| 497 |
+
no_ignores_ori_gt_lines.append(gt_lines[i])
|
| 498 |
+
no_ignores_gt_items.append(gt_items[i])
|
| 499 |
+
no_ignores_gt_cat_list.append(gt_cat_list[i])
|
| 500 |
+
no_ignores_gt_idxs.append(i)
|
| 501 |
+
|
| 502 |
+
# print("-------------ignore_gt_lines-------------------")
|
| 503 |
+
# for idx, line in zip(ignore_idx,ignore_gt_lines):
|
| 504 |
+
# print(f"{gt_cat_list[idx]}: {line}")
|
| 505 |
+
|
| 506 |
+
# print("-------------no_ignores_gt_lines-------------------")
|
| 507 |
+
# for line in no_ignores_gt_lines:
|
| 508 |
+
# print(line)
|
| 509 |
+
|
| 510 |
+
ignore_pred_idxs = []
|
| 511 |
+
ignore_pred_lines = []
|
| 512 |
+
ignores_pred_items = []
|
| 513 |
+
ignores_ori_pred_lines = []
|
| 514 |
+
|
| 515 |
+
merged_ignore_results = []
|
| 516 |
+
|
| 517 |
+
if len(ignore_gt_lines) > 0:
|
| 518 |
+
|
| 519 |
+
ignore_matches_dict = {}
|
| 520 |
+
|
| 521 |
+
ignore_matrix = compute_edit_distance_matrix_new(ignore_gt_lines, norm_pred_lines)
|
| 522 |
+
# print("-------------ignore_matrix-------------")
|
| 523 |
+
# print(ignore_matrix)
|
| 524 |
+
|
| 525 |
+
ignores_gt_indices = set(range(len(ignore_gt_lines)))
|
| 526 |
+
ignores_pred_indices = set(range(len(ignore_pred_lines)))
|
| 527 |
+
|
| 528 |
+
ignore_matches = np.argwhere(ignore_matrix < 0.25)
|
| 529 |
+
# print("-------------ignore_matches-------------")
|
| 530 |
+
# print(ignore_matches)
|
| 531 |
+
if len(ignore_matches) > 0:
|
| 532 |
+
ignore_pred_idxs = [_[1] for _ in ignore_matches]
|
| 533 |
+
ignore_gt_matched_idxs = [ignore_gt_idxs[_[0]] for _ in ignore_matches]
|
| 534 |
+
# print("-------------ignore_pred_idxs-------------")
|
| 535 |
+
# print(ignore_pred_idxs)
|
| 536 |
+
# print("-------------ignore_gt_matched_idxs-------------")
|
| 537 |
+
# print(ignore_gt_matched_idxs)
|
| 538 |
+
|
| 539 |
+
for i in ignore_pred_idxs:
|
| 540 |
+
ignore_pred_lines.append(norm_pred_lines[i])
|
| 541 |
+
ignores_ori_pred_lines.append(pred_lines[i])
|
| 542 |
+
ignores_pred_items.append(pred_items[i])
|
| 543 |
+
# print("-------------ignore_pred_lines-------------")
|
| 544 |
+
# for i in ignore_pred_lines:
|
| 545 |
+
# print(i)
|
| 546 |
+
|
| 547 |
+
ignores_gt_indices = set(range(len(ignore_gt_lines)))
|
| 548 |
+
ignores_pred_indices = set(range(len(ignore_pred_lines)))
|
| 549 |
+
|
| 550 |
+
for idx, i in enumerate(ignore_matches):
|
| 551 |
+
ignore_matches_dict[i[0]] = {
|
| 552 |
+
'pred_indices': [idx],
|
| 553 |
+
'edit_distance': ignore_matrix[i[0]][i[1]]
|
| 554 |
+
}
|
| 555 |
+
# print("-------------ignore_matches_dict-------------")
|
| 556 |
+
# print(ignore_matches_dict)
|
| 557 |
+
|
| 558 |
+
ignore_final_matches = merge_matches(ignore_matches_dict, {})
|
| 559 |
+
# print("-------------ignore_final_matches-------------")
|
| 560 |
+
# print(ignore_final_matches)
|
| 561 |
+
|
| 562 |
+
recalculate_edit_distances(ignore_final_matches, {}, ignore_gt_lines, ignore_pred_lines)
|
| 563 |
+
# print("-------------recalculate_ignore_final_matches-------------")
|
| 564 |
+
# print(ignore_final_matches)
|
| 565 |
+
|
| 566 |
+
converted_ignore_results = convert_final_matches(ignore_final_matches, ignore_gt_lines, ignore_pred_lines)
|
| 567 |
+
# print("-------------converted_ignore_results-------------")
|
| 568 |
+
# for i in converted_ignore_results:
|
| 569 |
+
# print(i)
|
| 570 |
+
|
| 571 |
+
merged_ignore_results = merge_duplicates_add_unmatched(converted_ignore_results, ignore_gt_lines, ignore_pred_lines, ignores_ori_gt_lines, ignores_ori_pred_lines, ignores_gt_indices, ignores_pred_indices)
|
| 572 |
+
|
| 573 |
+
for entry in merged_ignore_results:
|
| 574 |
+
entry['gt_idx'] = [entry['gt_idx']] if not isinstance(entry['gt_idx'], list) else entry['gt_idx']
|
| 575 |
+
entry['pred_idx'] = [entry['pred_idx']] if not isinstance(entry['pred_idx'], list) else entry['pred_idx']
|
| 576 |
+
entry['gt_position'] = [ignores_gt_items[_].get('order') if ignores_gt_items[_].get('order') else ignores_gt_items[_].get('position', [""])[0] for _ in entry['gt_idx']] if entry['gt_idx'] != [""] else [""]
|
| 577 |
+
entry['pred_position'] = ignores_pred_items[entry['pred_idx'][0]]['position'][0] if entry['pred_idx'] != [""] else ""
|
| 578 |
+
entry['gt'] = ''.join([ignores_ori_gt_lines[_] for _ in entry['gt_idx']]) if entry['gt_idx'] != [""] else ""
|
| 579 |
+
entry['pred'] = ''.join([ignores_ori_pred_lines[_] for _ in entry['pred_idx']]) if entry['pred_idx'] != [""] else ""
|
| 580 |
+
entry['norm_gt'] = ''.join([ignore_gt_lines[_] for _ in entry['gt_idx']]) if entry['gt_idx'] != [""] else ""
|
| 581 |
+
entry['norm_pred'] = ''.join([ignore_pred_lines[_] for _ in entry['pred_idx']]) if entry['pred_idx'] != [""] else ""
|
| 582 |
+
|
| 583 |
+
if entry['gt_idx'] != [""]:
|
| 584 |
+
ignore_type = ['figure_caption', 'figure_footnote', 'table_caption', 'table_footnote', 'code_algorithm', 'code_algorithm_caption', 'header', 'footer', 'page_footnote', 'page_number', 'equation_caption']
|
| 585 |
+
gt_cagegory_clean = [ignores_gt_cat_list[_] for _ in entry['gt_idx'] if ignores_gt_cat_list[_] not in ignore_type]
|
| 586 |
+
if gt_cagegory_clean:
|
| 587 |
+
entry['gt_category_type'] = Counter(gt_cagegory_clean).most_common(1)[0][0]
|
| 588 |
+
else:
|
| 589 |
+
entry['gt_category_type'] = Counter([ignores_gt_cat_list[_] for _ in entry['gt_idx']]).most_common(1)[0][0]
|
| 590 |
+
else:
|
| 591 |
+
entry['gt_category_type'] = ""
|
| 592 |
+
entry['pred_category_type'] = get_pred_category_type(entry['pred_idx'][0], ignores_pred_items) if entry['pred_idx'] != [""] else ""
|
| 593 |
+
if entry['pred_category_type'] == 'equation_inline':
|
| 594 |
+
merged_ignore_results.remove(entry)
|
| 595 |
+
entry['pred_category_type'] = get_pred_category_type(entry['pred_idx'][0], ignores_pred_items) if entry['pred_idx'] != [""] else ""
|
| 596 |
+
entry['gt_attribute'] = [ignores_gt_items[_].get("attribute", {}) for _ in entry['gt_idx']] if entry['gt_idx'] != [""] else [{}]
|
| 597 |
+
entry['img_id'] = img_name
|
| 598 |
+
|
| 599 |
+
for entry in merged_ignore_results:
|
| 600 |
+
if isinstance(entry['gt_idx'], list) and entry['gt_idx'] != [""]:
|
| 601 |
+
gt_idx = []
|
| 602 |
+
for i in entry['gt_idx']:
|
| 603 |
+
gt_idx.append(ignore_gt_idxs[i])
|
| 604 |
+
entry['gt_idx'] = gt_idx
|
| 605 |
+
if isinstance(entry['pred_idx'], list) and entry['pred_idx'] != [""]:
|
| 606 |
+
pred_idx = []
|
| 607 |
+
for i in entry['pred_idx']:
|
| 608 |
+
pred_idx.append(int(ignore_pred_idxs[i]))
|
| 609 |
+
entry['pred_idx'] = pred_idx
|
| 610 |
+
|
| 611 |
+
# print("-------------merged_ignore_results-------------")
|
| 612 |
+
# for i in merged_ignore_results:
|
| 613 |
+
# print(i)
|
| 614 |
+
|
| 615 |
+
no_ignores_pred_lines = []
|
| 616 |
+
no_ignores_ori_pred_lines = []
|
| 617 |
+
no_ignores_pred_indices = []
|
| 618 |
+
no_ignores_pred_items = []
|
| 619 |
+
no_ignore_pred_idxs = []
|
| 620 |
+
|
| 621 |
+
for idx, line in enumerate(norm_pred_lines):
|
| 622 |
+
if not idx in ignore_pred_idxs:
|
| 623 |
+
no_ignores_pred_lines.append(line)
|
| 624 |
+
no_ignores_ori_pred_lines.append(pred_lines[idx])
|
| 625 |
+
# no_ignores_pred_indices.append(idx)
|
| 626 |
+
no_ignores_pred_items.append(pred_items[idx])
|
| 627 |
+
no_ignore_pred_idxs.append(idx)
|
| 628 |
+
|
| 629 |
+
# initialize new indices for lines without ignore categories
|
| 630 |
+
no_ignores_gt_indices = set(range(len(no_ignores_gt_lines)))
|
| 631 |
+
no_ignores_pred_indices = set(range(len(no_ignores_pred_lines)))
|
| 632 |
+
|
| 633 |
+
# exclude ignore categories
|
| 634 |
+
cost_matrix = compute_edit_distance_matrix_new(no_ignores_gt_lines, no_ignores_pred_lines)
|
| 635 |
+
# print("-------------cost matrix-------------")
|
| 636 |
+
# print(cost_matrix)
|
| 637 |
+
|
| 638 |
+
matched_col_idx, row_ind, cost_list = cal_final_match(cost_matrix, no_ignores_gt_lines, no_ignores_pred_lines)
|
| 639 |
+
# print("-------------matched_col_idx-------------")
|
| 640 |
+
# print(matched_col_idx)
|
| 641 |
+
|
| 642 |
+
# print("-------------gt_row_ind-------------")
|
| 643 |
+
# print(row_ind)
|
| 644 |
+
|
| 645 |
+
# print("-------------cost_list-------------")
|
| 646 |
+
# print(cost_list)
|
| 647 |
+
|
| 648 |
+
gt_lens_dict, pred_lens_dict = initialize_indices(no_ignores_gt_lines, no_ignores_pred_lines)
|
| 649 |
+
# print("-------------gt_lens_dict-------------")
|
| 650 |
+
# print(gt_lens_dict)
|
| 651 |
+
|
| 652 |
+
# print("-------------pred_lens_dict-------------")
|
| 653 |
+
# print(pred_lens_dict)
|
| 654 |
+
|
| 655 |
+
matches, unmatched_gt_indices, unmatched_pred_indices = process_matches(matched_col_idx, row_ind, cost_list, no_ignores_gt_lines, no_ignores_pred_lines, no_ignores_ori_pred_lines)
|
| 656 |
+
|
| 657 |
+
# print("-------------matches-------------")
|
| 658 |
+
# print(matches)
|
| 659 |
+
|
| 660 |
+
# print("-------------unmatched_gt_indices-------------")
|
| 661 |
+
# print(unmatched_gt_indices)
|
| 662 |
+
|
| 663 |
+
# print("-------------unmatched_pred_indices-------------")
|
| 664 |
+
# print(unmatched_pred_indices)
|
| 665 |
+
|
| 666 |
+
matching_dict = fuzzy_match_unmatched_items(unmatched_gt_indices, no_ignores_gt_lines, no_ignores_pred_lines)
|
| 667 |
+
# print("-------------matching_dict-------------")
|
| 668 |
+
# print(matching_dict)
|
| 669 |
+
|
| 670 |
+
final_matches = merge_matches(matches, matching_dict)
|
| 671 |
+
# print("-------------final_matches-------------")
|
| 672 |
+
# print(final_matches)
|
| 673 |
+
|
| 674 |
+
recalculate_edit_distances(final_matches, gt_lens_dict, no_ignores_gt_lines, no_ignores_pred_lines)
|
| 675 |
+
# print("-------------recalculate_edit_distances-------------")
|
| 676 |
+
# print(final_matches)
|
| 677 |
+
|
| 678 |
+
converted_results = convert_final_matches(final_matches, no_ignores_gt_lines, no_ignores_pred_lines)
|
| 679 |
+
# print("-------------converted_results-------------")
|
| 680 |
+
# print(converted_results)
|
| 681 |
+
|
| 682 |
+
merged_results = merge_duplicates_add_unmatched(converted_results, no_ignores_gt_lines, no_ignores_pred_lines, no_ignores_ori_gt_lines, no_ignores_ori_pred_lines, no_ignores_gt_indices, no_ignores_pred_indices)
|
| 683 |
+
|
| 684 |
+
for entry in merged_results:
|
| 685 |
+
if entry['gt_idx'] != [""]:
|
| 686 |
+
ignore_type = ['figure_caption', 'figure_footnote', 'table_caption', 'table_footnote', 'code_algorithm', 'code_algorithm_caption', 'header', 'footer', 'page_footnote', 'page_number', 'equation_caption']
|
| 687 |
+
gt_cagegory_clean = [no_ignores_gt_cat_list[_] for _ in entry['gt_idx'] if no_ignores_gt_cat_list[_] not in ignore_type]
|
| 688 |
+
if gt_cagegory_clean:
|
| 689 |
+
entry['gt_category_type'] = Counter(gt_cagegory_clean).most_common(1)[0][0]
|
| 690 |
+
else:
|
| 691 |
+
entry['gt_category_type'] = Counter([no_ignores_gt_cat_list[_] for _ in entry['gt_idx']]).most_common(1)[0][0]
|
| 692 |
+
else:
|
| 693 |
+
entry['gt_category_type'] = ""
|
| 694 |
+
entry['pred_category_type'] = get_pred_category_type(entry['pred_idx'][0], no_ignores_pred_items) if entry['pred_idx'] != [""] else ""
|
| 695 |
+
if entry['pred_category_type'] == 'equation_inline':
|
| 696 |
+
merged_results.remove(entry)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
entry['gt_idx'] = [entry['gt_idx']] if not isinstance(entry['gt_idx'], list) else entry['gt_idx']
|
| 700 |
+
entry['pred_idx'] = [entry['pred_idx']] if not isinstance(entry['pred_idx'], list) else entry['pred_idx']
|
| 701 |
+
entry['gt_position'] = [no_ignores_gt_items[_].get('order') if no_ignores_gt_items[_].get('order') else no_ignores_gt_items[_].get('position', [""])[0] for _ in entry['gt_idx']] if entry['gt_idx'] != [""] else [""]
|
| 702 |
+
entry['pred_position'] = no_ignores_pred_items[entry['pred_idx'][0]]['position'][0] if entry['pred_idx'] != [""] else ""
|
| 703 |
+
# 0507 多行公式拼接修改
|
| 704 |
+
if entry['gt_category_type'] == 'equation_isolated' and len(entry['gt_idx']) > 1:
|
| 705 |
+
mutli_formula = ' \\\\ '.join(['{'+no_ignores_ori_gt_lines[_].strip('$$').strip('\n')+'}' for _ in entry['gt_idx']]) if entry['gt_idx'] != [""] else ""
|
| 706 |
+
mutli_formula = '\\\\begin{array}{l} ' + mutli_formula + ' \\\\end{array}'
|
| 707 |
+
entry['gt'] = mutli_formula
|
| 708 |
+
else:
|
| 709 |
+
entry['gt'] = ''.join([no_ignores_ori_gt_lines[_] for _ in entry['gt_idx']]) if entry['gt_idx'] != [""] else ""
|
| 710 |
+
|
| 711 |
+
entry['pred_category_type'] = get_pred_category_type(entry['pred_idx'][0], no_ignores_pred_items) if entry['pred_idx'] != [""] else ""
|
| 712 |
+
entry['gt_attribute'] = [no_ignores_gt_items[_].get("attribute", {}) for _ in entry['gt_idx']] if entry['gt_idx'] != [""] else [{}]
|
| 713 |
+
entry['img_id'] = img_name
|
| 714 |
+
|
| 715 |
+
# 0724 多行公式拼接修改pred
|
| 716 |
+
if 'equation' in entry['pred_category_type'] and len(entry['pred_idx']) > 1:
|
| 717 |
+
mutli_formula = ' \\\\ '.join(['{'+no_ignores_ori_pred_lines[_].strip('$$').strip('\n')+'}' for _ in entry['pred_idx']]) if entry['pred_idx'] != [""] else ""
|
| 718 |
+
mutli_formula = '\\\\begin{array}{l} ' + mutli_formula + ' \\\\end{array}'
|
| 719 |
+
entry['pred'] = mutli_formula
|
| 720 |
+
else:
|
| 721 |
+
entry['pred'] = ''.join([no_ignores_ori_pred_lines[_] for _ in entry['pred_idx']]) if entry['pred_idx'] != [""] else ""
|
| 722 |
+
|
| 723 |
+
entry['norm_gt'] = ''.join([no_ignores_gt_lines[_] for _ in entry['gt_idx']]) if entry['gt_idx'] != [""] else ""
|
| 724 |
+
entry['norm_pred'] = ''.join([no_ignores_pred_lines[_] for _ in entry['pred_idx']]) if entry['pred_idx'] != [""] else ""
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
# print("-------------merged_results-------------")
|
| 728 |
+
# for i in merged_results:
|
| 729 |
+
# print(i)
|
| 730 |
+
for entry in merged_results:
|
| 731 |
+
if isinstance(entry['gt_idx'], list) and entry['gt_idx'] != [""]:
|
| 732 |
+
gt_idx = []
|
| 733 |
+
for i in entry['gt_idx']:
|
| 734 |
+
gt_idx.append(no_ignores_gt_idxs[i])
|
| 735 |
+
entry['gt_idx'] = gt_idx
|
| 736 |
+
if isinstance(entry['pred_idx'], list) and entry['pred_idx'] != [""]:
|
| 737 |
+
pred_idx = []
|
| 738 |
+
for i in entry['pred_idx']:
|
| 739 |
+
pred_idx.append(int(no_ignore_pred_idxs[i]))
|
| 740 |
+
entry['pred_idx'] = pred_idx
|
| 741 |
+
|
| 742 |
+
if len(merged_ignore_results) > 0:
|
| 743 |
+
merged_results.extend(merged_ignore_results)
|
| 744 |
+
# for i in merged_ignore_results:
|
| 745 |
+
# merged_results.append(i)
|
| 746 |
+
|
| 747 |
+
return merged_results
|
| 748 |
+
|
| 749 |
+
# cost_matrix = compute_edit_distance_matrix_new(norm_gt_lines, norm_pred_lines)
|
| 750 |
+
|
| 751 |
+
# matched_col_idx, row_ind, cost_list = cal_final_match(cost_matrix, norm_gt_lines, norm_pred_lines)
|
| 752 |
+
|
| 753 |
+
# gt_lens_dict, pred_lens_dict = initialize_indices(norm_gt_lines, norm_pred_lines)
|
| 754 |
+
|
| 755 |
+
# matches, unmatched_gt_indices, unmatched_pred_indices = process_matches(matched_col_idx, row_ind, cost_list, norm_gt_lines, norm_pred_lines, pred_lines)
|
| 756 |
+
|
| 757 |
+
# matching_dict = fuzzy_match_unmatched_items(unmatched_gt_indices, norm_gt_lines, norm_pred_lines)
|
| 758 |
+
|
| 759 |
+
# final_matches = merge_matches(matches, matching_dict)
|
| 760 |
+
|
| 761 |
+
# recalculate_edit_distances(final_matches, gt_lens_dict, norm_gt_lines, norm_pred_lines)
|
| 762 |
+
|
| 763 |
+
# converted_results = convert_final_matches(final_matches, norm_gt_lines, norm_pred_lines)
|
| 764 |
+
|
| 765 |
+
# merged_results = merge_duplicates_add_unmatched(converted_results, norm_gt_lines, norm_pred_lines, gt_lines, pred_lines, all_gt_indices, all_pred_indices)
|
| 766 |
+
|
| 767 |
+
# for entry in merged_results:
|
| 768 |
+
# entry['gt_idx'] = [entry['gt_idx']] if not isinstance(entry['gt_idx'], list) else entry['gt_idx']
|
| 769 |
+
# entry['pred_idx'] = [entry['pred_idx']] if not isinstance(entry['pred_idx'], list) else entry['pred_idx']
|
| 770 |
+
# entry['gt_position'] = [gt_items[_].get('order') if gt_items[_].get('order') else gt_items[_].get('position', [""])[0] for _ in entry['gt_idx']] if entry['gt_idx'] != [""] else [""]
|
| 771 |
+
# entry['pred_position'] = pred_items[entry['pred_idx'][0]]['position'][0] if entry['pred_idx'] != [""] else ""
|
| 772 |
+
# entry['gt'] = ''.join([gt_lines[_] for _ in entry['gt_idx']]) if entry['gt_idx'] != [""] else ""
|
| 773 |
+
# entry['pred'] = ''.join([pred_lines[_] for _ in entry['pred_idx']]) if entry['pred_idx'] != [""] else ""
|
| 774 |
+
# entry['norm_gt'] = ''.join([norm_gt_lines[_] for _ in entry['gt_idx']]) if entry['gt_idx'] != [""] else ""
|
| 775 |
+
# entry['norm_pred'] = ''.join([norm_pred_lines[_] for _ in entry['pred_idx']]) if entry['pred_idx'] != [""] else ""
|
| 776 |
+
|
| 777 |
+
# if entry['gt_idx'] != [""]:
|
| 778 |
+
# ignore_type = ['figure_caption', 'figure_footnote', 'table_caption', 'table_footnote', 'code_algorithm', 'code_algorithm_caption', 'header', 'footer', 'page_footnote', 'page_number', 'equation_caption']
|
| 779 |
+
# gt_cagegory_clean = [gt_cat_list[_] for _ in entry['gt_idx'] if gt_cat_list[_] not in ignore_type]
|
| 780 |
+
# if gt_cagegory_clean:
|
| 781 |
+
# entry['gt_category_type'] = Counter(gt_cagegory_clean).most_common(1)[0][0]
|
| 782 |
+
# else:
|
| 783 |
+
# entry['gt_category_type'] = Counter([gt_cat_list[_] for _ in entry['gt_idx']]).most_common(1)[0][0]
|
| 784 |
+
# else:
|
| 785 |
+
# entry['gt_category_type'] = ""
|
| 786 |
+
# entry['pred_category_type'] = get_pred_category_type(entry['pred_idx'][0], pred_items) if entry['pred_idx'] != [""] else ""
|
| 787 |
+
# entry['gt_attribute'] = [gt_items[_].get("attribute", {}) for _ in entry['gt_idx']] if entry['gt_idx'] != [""] else [{}]
|
| 788 |
+
# entry['img_id'] = img_name
|
| 789 |
+
|
| 790 |
+
# return merged_results
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
def merge_duplicates_add_unmatched(converted_results, norm_gt_lines, norm_pred_lines, gt_lines, pred_lines, all_gt_indices, all_pred_indices):
|
| 794 |
+
merged_results = []
|
| 795 |
+
processed_pred = set()
|
| 796 |
+
processed_gt = set()
|
| 797 |
+
|
| 798 |
+
for entry in converted_results:
|
| 799 |
+
pred_idx = tuple(entry['pred_idx']) if isinstance(entry['pred_idx'], list) else (entry['pred_idx'],)
|
| 800 |
+
if pred_idx not in processed_pred and pred_idx != ("",):
|
| 801 |
+
merged_entry = {
|
| 802 |
+
'gt_idx': [entry['gt_idx']],
|
| 803 |
+
'gt': entry['gt'],
|
| 804 |
+
'pred_idx': entry['pred_idx'],
|
| 805 |
+
'pred': entry['pred'],
|
| 806 |
+
'edit': entry['edit']
|
| 807 |
+
}
|
| 808 |
+
for other_entry in converted_results:
|
| 809 |
+
other_pred_idx = tuple(other_entry['pred_idx']) if isinstance(other_entry['pred_idx'], list) else (other_entry['pred_idx'],)
|
| 810 |
+
if other_pred_idx == pred_idx and other_entry is not entry:
|
| 811 |
+
merged_entry['gt_idx'].append(other_entry['gt_idx'])
|
| 812 |
+
merged_entry['gt'] += other_entry['gt']
|
| 813 |
+
processed_gt.add(other_entry['gt_idx'])
|
| 814 |
+
merged_results.append(merged_entry)
|
| 815 |
+
processed_pred.add(pred_idx)
|
| 816 |
+
processed_gt.add(entry['gt_idx'])
|
| 817 |
+
|
| 818 |
+
# for entry in converted_results:
|
| 819 |
+
# if entry['gt_idx'] not in processed_gt:
|
| 820 |
+
# merged_results.append(entry)
|
| 821 |
+
|
| 822 |
+
for gt_idx in range(len(norm_gt_lines)):
|
| 823 |
+
if gt_idx not in processed_gt:
|
| 824 |
+
merged_results.append({
|
| 825 |
+
'gt_idx': [gt_idx],
|
| 826 |
+
'gt': gt_lines[gt_idx],
|
| 827 |
+
'pred_idx': [""],
|
| 828 |
+
'pred': "",
|
| 829 |
+
'edit': 1
|
| 830 |
+
})
|
| 831 |
+
return merged_results
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def formula_format(formula_matches, img_name):
|
| 837 |
+
return [
|
| 838 |
+
{
|
| 839 |
+
"gt": item["gt"],
|
| 840 |
+
"pred": item["pred"],
|
| 841 |
+
"img_id": f"{img_name}_{i}"
|
| 842 |
+
}
|
| 843 |
+
for i, item in enumerate(formula_matches)
|
| 844 |
+
]
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
def merge_lists_with_sublists(main_list, sub_lists):
|
| 848 |
+
main_list_final = list(copy.deepcopy(main_list))
|
| 849 |
+
for sub_list in sub_lists:
|
| 850 |
+
pop_idx = main_list_final.index(sub_list[0])
|
| 851 |
+
for _ in sub_list:
|
| 852 |
+
main_list_final.pop(pop_idx)
|
| 853 |
+
main_list_final.insert(pop_idx, sub_list)
|
| 854 |
+
return main_list_final
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def sub_pred_fuzzy_matching(gt, pred):
|
| 858 |
+
|
| 859 |
+
min_d = float('inf')
|
| 860 |
+
# pos = -1
|
| 861 |
+
|
| 862 |
+
gt_len = len(gt)
|
| 863 |
+
pred_len = len(pred)
|
| 864 |
+
|
| 865 |
+
if gt_len >= pred_len and pred_len > 0:
|
| 866 |
+
for i in range(gt_len - pred_len + 1):
|
| 867 |
+
sub = gt[i:i + pred_len]
|
| 868 |
+
dist = Levenshtein_distance(sub, pred)/pred_len
|
| 869 |
+
if dist < min_d:
|
| 870 |
+
min_d = dist
|
| 871 |
+
pos = i
|
| 872 |
+
|
| 873 |
+
return min_d
|
| 874 |
+
else:
|
| 875 |
+
return False
|
| 876 |
+
|
| 877 |
+
def sub_gt_fuzzy_matching(pred, gt):
|
| 878 |
+
|
| 879 |
+
min_d = float('inf')
|
| 880 |
+
pos = ""
|
| 881 |
+
matched_sub = ""
|
| 882 |
+
gt_len = len(gt)
|
| 883 |
+
pred_len = len(pred)
|
| 884 |
+
|
| 885 |
+
if pred_len >= gt_len and gt_len > 0:
|
| 886 |
+
for i in range(pred_len - gt_len + 1):
|
| 887 |
+
sub = pred[i:i + gt_len]
|
| 888 |
+
dist = Levenshtein.distance(sub, gt) /gt_len
|
| 889 |
+
if dist < min_d:
|
| 890 |
+
min_d = dist
|
| 891 |
+
pos = i
|
| 892 |
+
matched_sub = sub
|
| 893 |
+
return min_d, pos, gt_len, matched_sub
|
| 894 |
+
else:
|
| 895 |
+
return 1, "", gt_len, ""
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def get_final_subset(subset_certain, subset_certain_cost):
|
| 899 |
+
if not subset_certain or not subset_certain_cost:
|
| 900 |
+
return []
|
| 901 |
+
|
| 902 |
+
subset_turple = sorted([(a, b) for a, b in zip(subset_certain, subset_certain_cost)], key=lambda x: x[0][0])
|
| 903 |
+
|
| 904 |
+
group_list = defaultdict(list)
|
| 905 |
+
group_idx = 0
|
| 906 |
+
group_list[group_idx].append(subset_turple[0])
|
| 907 |
+
|
| 908 |
+
for item in subset_turple[1:]:
|
| 909 |
+
overlap_flag = False
|
| 910 |
+
for subset in group_list[group_idx]:
|
| 911 |
+
for idx in item[0]:
|
| 912 |
+
if idx in subset[0]:
|
| 913 |
+
overlap_flag = True
|
| 914 |
+
break
|
| 915 |
+
if overlap_flag:
|
| 916 |
+
break
|
| 917 |
+
if overlap_flag:
|
| 918 |
+
group_list[group_idx].append(item)
|
| 919 |
+
else:
|
| 920 |
+
group_idx += 1
|
| 921 |
+
group_list[group_idx].append(item)
|
| 922 |
+
|
| 923 |
+
final_subset = []
|
| 924 |
+
for _, group in group_list.items():
|
| 925 |
+
if len(group) == 1:
|
| 926 |
+
final_subset.append(group[0][0])
|
| 927 |
+
else:
|
| 928 |
+
path_dict = defaultdict(list)
|
| 929 |
+
path_idx = 0
|
| 930 |
+
path_dict[path_idx].append(group[0])
|
| 931 |
+
|
| 932 |
+
for subset in group[1:]:
|
| 933 |
+
new_path = True
|
| 934 |
+
for path_idx_s, path_items in path_dict.items():
|
| 935 |
+
is_dup = False
|
| 936 |
+
is_same = False
|
| 937 |
+
for path_item in path_items:
|
| 938 |
+
if path_item[0] == subset[0]:
|
| 939 |
+
is_dup = True
|
| 940 |
+
is_same = True
|
| 941 |
+
if path_item[1] > subset[1]:
|
| 942 |
+
path_dict[path_idx_s].pop(path_dict[path_idx_s].index(path_item))
|
| 943 |
+
path_dict[path_idx_s].append(subset)
|
| 944 |
+
else:
|
| 945 |
+
for num_1 in path_item[0]:
|
| 946 |
+
for num_2 in subset[0]:
|
| 947 |
+
if num_1 == num_2:
|
| 948 |
+
is_dup = True
|
| 949 |
+
if not is_dup:
|
| 950 |
+
path_dict[path_idx_s].append(subset)
|
| 951 |
+
new_path = False
|
| 952 |
+
if is_same:
|
| 953 |
+
new_path = False
|
| 954 |
+
if new_path:
|
| 955 |
+
path_idx = len(path_dict.keys())
|
| 956 |
+
path_dict[path_idx].append(subset)
|
| 957 |
+
|
| 958 |
+
saved_cost = float('inf')
|
| 959 |
+
saved_subset = []
|
| 960 |
+
for path_idx, path in path_dict.items():
|
| 961 |
+
avg_cost = sum([i[1] for i in path]) / len(path)
|
| 962 |
+
if avg_cost < saved_cost:
|
| 963 |
+
saved_subset = [i[0] for i in path]
|
| 964 |
+
saved_cost = avg_cost
|
| 965 |
+
|
| 966 |
+
final_subset.extend(saved_subset)
|
| 967 |
+
|
| 968 |
+
return final_subset
|
| 969 |
+
|
| 970 |
+
def judge_pred_merge(gt_list, pred_list, threshold=0.6):
|
| 971 |
+
if len(pred_list) == 1:
|
| 972 |
+
return False, False
|
| 973 |
+
|
| 974 |
+
cur_pred = ' '.join(pred_list[:-1])
|
| 975 |
+
merged_pred = ' '.join(pred_list)
|
| 976 |
+
|
| 977 |
+
cur_dist = Levenshtein.distance(gt_list[0], cur_pred) / max(len(gt_list[0]), len(cur_pred))
|
| 978 |
+
merged_dist = Levenshtein.distance(gt_list[0], merged_pred) / max(len(gt_list[0]), len(merged_pred))
|
| 979 |
+
|
| 980 |
+
if merged_dist > cur_dist:
|
| 981 |
+
return False, False
|
| 982 |
+
|
| 983 |
+
cur_fuzzy_dists = [sub_pred_fuzzy_matching(gt_list[0], cur_pred) for cur_pred in pred_list[:-1]]
|
| 984 |
+
if any(dist is False or dist > threshold for dist in cur_fuzzy_dists):
|
| 985 |
+
return False, False
|
| 986 |
+
|
| 987 |
+
add_fuzzy_dist = sub_pred_fuzzy_matching(gt_list[0], pred_list[-1])
|
| 988 |
+
if add_fuzzy_dist is False:
|
| 989 |
+
return False, False
|
| 990 |
+
|
| 991 |
+
merged_pred_flag = add_fuzzy_dist < threshold
|
| 992 |
+
continue_flag = len(merged_pred) <= len(gt_list[0])
|
| 993 |
+
|
| 994 |
+
return merged_pred_flag, continue_flag
|
| 995 |
+
|
| 996 |
+
def deal_with_truncated(cost_matrix, norm_gt_lines, norm_pred_lines):
|
| 997 |
+
matched_first = np.argwhere(cost_matrix < 0.25)
|
| 998 |
+
masked_gt_idx = [i[0] for i in matched_first]
|
| 999 |
+
unmasked_gt_idx = [i for i in range(cost_matrix.shape[0]) if i not in masked_gt_idx]
|
| 1000 |
+
masked_pred_idx = [i[1] for i in matched_first]
|
| 1001 |
+
unmasked_pred_idx = [i for i in range(cost_matrix.shape[1]) if i not in masked_pred_idx]
|
| 1002 |
+
|
| 1003 |
+
merges_gt_dict = {}
|
| 1004 |
+
merges_pred_dict = {}
|
| 1005 |
+
merged_gt_subsets = []
|
| 1006 |
+
|
| 1007 |
+
for gt_idx in unmasked_gt_idx:
|
| 1008 |
+
check_merge_subset = []
|
| 1009 |
+
merged_dist = []
|
| 1010 |
+
|
| 1011 |
+
for pred_idx in unmasked_pred_idx:
|
| 1012 |
+
step = 1
|
| 1013 |
+
merged_pred = [norm_pred_lines[pred_idx]]
|
| 1014 |
+
|
| 1015 |
+
while True:
|
| 1016 |
+
if pred_idx + step in masked_pred_idx or pred_idx + step >= len(norm_pred_lines):
|
| 1017 |
+
break
|
| 1018 |
+
else:
|
| 1019 |
+
merged_pred.append(norm_pred_lines[pred_idx + step])
|
| 1020 |
+
merged_pred_flag, continue_flag = judge_pred_merge([norm_gt_lines[gt_idx]], merged_pred)
|
| 1021 |
+
if not merged_pred_flag:
|
| 1022 |
+
break
|
| 1023 |
+
else:
|
| 1024 |
+
step += 1
|
| 1025 |
+
if not continue_flag:
|
| 1026 |
+
break
|
| 1027 |
+
|
| 1028 |
+
check_merge_subset.append(list(range(pred_idx, pred_idx + step)))
|
| 1029 |
+
matched_line = ' '.join([norm_pred_lines[i] for i in range(pred_idx, pred_idx + step)])
|
| 1030 |
+
dist = Levenshtein_distance(norm_gt_lines[gt_idx], matched_line) / max(len(matched_line), len(norm_gt_lines[gt_idx]))
|
| 1031 |
+
merged_dist.append(dist)
|
| 1032 |
+
|
| 1033 |
+
if not merged_dist:
|
| 1034 |
+
subset_certain = []
|
| 1035 |
+
min_cost_idx = ""
|
| 1036 |
+
min_cost = float('inf')
|
| 1037 |
+
else:
|
| 1038 |
+
min_cost = min(merged_dist)
|
| 1039 |
+
min_cost_idx = merged_dist.index(min_cost)
|
| 1040 |
+
subset_certain = check_merge_subset[min_cost_idx]
|
| 1041 |
+
|
| 1042 |
+
merges_gt_dict[gt_idx] = {
|
| 1043 |
+
'merge_subset': check_merge_subset,
|
| 1044 |
+
'merged_cost': merged_dist,
|
| 1045 |
+
'min_cost_idx': min_cost_idx,
|
| 1046 |
+
'subset_certain': subset_certain,
|
| 1047 |
+
'min_cost': min_cost
|
| 1048 |
+
}
|
| 1049 |
+
|
| 1050 |
+
subset_certain = [merges_gt_dict[gt_idx]['subset_certain'] for gt_idx in unmasked_gt_idx if merges_gt_dict[gt_idx]['subset_certain']]
|
| 1051 |
+
subset_certain_cost = [merges_gt_dict[gt_idx]['min_cost'] for gt_idx in unmasked_gt_idx if merges_gt_dict[gt_idx]['subset_certain']]
|
| 1052 |
+
|
| 1053 |
+
subset_certain_final = get_final_subset(subset_certain, subset_certain_cost)
|
| 1054 |
+
|
| 1055 |
+
if not subset_certain_final:
|
| 1056 |
+
return cost_matrix, norm_pred_lines, range(len(norm_pred_lines))
|
| 1057 |
+
|
| 1058 |
+
final_pred_idx_list = merge_lists_with_sublists(range(len(norm_pred_lines)), subset_certain_final)
|
| 1059 |
+
final_norm_pred_lines = [' '.join(norm_pred_lines[idx_list[0]:idx_list[-1]+1]) if isinstance(idx_list, list) else norm_pred_lines[idx_list] for idx_list in final_pred_idx_list]
|
| 1060 |
+
|
| 1061 |
+
new_cost_matrix = compute_edit_distance_matrix_new(norm_gt_lines, final_norm_pred_lines)
|
| 1062 |
+
|
| 1063 |
+
return new_cost_matrix, final_norm_pred_lines, final_pred_idx_list
|
| 1064 |
+
|
| 1065 |
+
def cal_move_dist(gt, pred):
|
| 1066 |
+
assert len(gt) == len(pred), 'Not right length'
|
| 1067 |
+
step = 0
|
| 1068 |
+
for i, gt_c in enumerate(gt):
|
| 1069 |
+
if gt_c != pred[i]:
|
| 1070 |
+
step += abs(i - pred.index(gt_c))
|
| 1071 |
+
pred[i], pred[pred.index(gt_c)] = pred[pred.index(gt_c)], pred[i]
|
| 1072 |
+
return step / len(gt)
|
| 1073 |
+
|
| 1074 |
+
def cal_final_match(cost_matrix, norm_gt_lines, norm_pred_lines):
|
| 1075 |
+
# min_indice = cost_matrix.argmax(axis=1)
|
| 1076 |
+
|
| 1077 |
+
new_cost_matrix, final_norm_pred_lines, final_pred_idx_list = deal_with_truncated(cost_matrix, norm_gt_lines, norm_pred_lines)
|
| 1078 |
+
|
| 1079 |
+
row_ind, col_ind = linear_sum_assignment(new_cost_matrix)
|
| 1080 |
+
|
| 1081 |
+
cost_list = [new_cost_matrix[r][c] for r, c in zip(row_ind, col_ind)]
|
| 1082 |
+
matched_col_idx = [final_pred_idx_list[i] for i in col_ind]
|
| 1083 |
+
|
| 1084 |
+
return matched_col_idx, row_ind, cost_list
|
| 1085 |
+
|
| 1086 |
+
def initialize_indices(norm_gt_lines, norm_pred_lines):
|
| 1087 |
+
gt_lens_dict = {idx: len(gt_line) for idx, gt_line in enumerate(norm_gt_lines)}
|
| 1088 |
+
pred_lens_dict = {idx: len(pred_line) for idx, pred_line in enumerate(norm_pred_lines)}
|
| 1089 |
+
return gt_lens_dict, pred_lens_dict
|
| 1090 |
+
|
| 1091 |
+
def process_matches(matched_col_idx, row_ind, cost_list, norm_gt_lines, norm_pred_lines, pred_lines):
|
| 1092 |
+
matches = {}
|
| 1093 |
+
unmatched_gt_indices = []
|
| 1094 |
+
unmatched_pred_indices = []
|
| 1095 |
+
|
| 1096 |
+
for i in range(len(norm_gt_lines)):
|
| 1097 |
+
if i in row_ind:
|
| 1098 |
+
idx = list(row_ind).index(i)
|
| 1099 |
+
pred_idx = matched_col_idx[idx]
|
| 1100 |
+
|
| 1101 |
+
if pred_idx is None or (isinstance(pred_idx, list) and None in pred_idx):
|
| 1102 |
+
unmatched_pred_indices.append(pred_idx)
|
| 1103 |
+
continue
|
| 1104 |
+
|
| 1105 |
+
if isinstance(pred_idx, list):
|
| 1106 |
+
pred_line = ' | '.join(norm_pred_lines[pred_idx[0]:pred_idx[-1]+1])
|
| 1107 |
+
ori_pred_line = ' | '.join(pred_lines[pred_idx[0]:pred_idx[-1]+1])
|
| 1108 |
+
matched_pred_indices_range = list(range(pred_idx[0], pred_idx[-1]+1))
|
| 1109 |
+
else:
|
| 1110 |
+
pred_line = norm_pred_lines[pred_idx]
|
| 1111 |
+
ori_pred_line = pred_lines[pred_idx]
|
| 1112 |
+
matched_pred_indices_range = [pred_idx]
|
| 1113 |
+
|
| 1114 |
+
edit = cost_list[idx]
|
| 1115 |
+
|
| 1116 |
+
if edit > 0.7:
|
| 1117 |
+
unmatched_pred_indices.extend(matched_pred_indices_range)
|
| 1118 |
+
unmatched_gt_indices.append(i)
|
| 1119 |
+
else:
|
| 1120 |
+
matches[i] = {
|
| 1121 |
+
'pred_indices': matched_pred_indices_range,
|
| 1122 |
+
'edit_distance': edit,
|
| 1123 |
+
}
|
| 1124 |
+
for matched_pred_idx in matched_pred_indices_range:
|
| 1125 |
+
if matched_pred_idx in unmatched_pred_indices:
|
| 1126 |
+
unmatched_pred_indices.remove(matched_pred_idx)
|
| 1127 |
+
else:
|
| 1128 |
+
unmatched_gt_indices.append(i)
|
| 1129 |
+
|
| 1130 |
+
return matches, unmatched_gt_indices, unmatched_pred_indices
|
| 1131 |
+
|
| 1132 |
+
def fuzzy_match_unmatched_items(unmatched_gt_indices, norm_gt_lines, norm_pred_lines):
|
| 1133 |
+
matching_dict = {}
|
| 1134 |
+
|
| 1135 |
+
for pred_idx, pred_content in enumerate(norm_pred_lines):
|
| 1136 |
+
if isinstance(pred_idx, list):
|
| 1137 |
+
continue
|
| 1138 |
+
|
| 1139 |
+
matching_indices = []
|
| 1140 |
+
|
| 1141 |
+
for unmatched_gt_idx in unmatched_gt_indices:
|
| 1142 |
+
gt_content = norm_gt_lines[unmatched_gt_idx]
|
| 1143 |
+
cur_fuzzy_dist_unmatch, cur_pos, gt_lens, matched_field = sub_gt_fuzzy_matching(pred_content, gt_content)
|
| 1144 |
+
if cur_fuzzy_dist_unmatch < 0.4:
|
| 1145 |
+
matching_indices.append(unmatched_gt_idx)
|
| 1146 |
+
|
| 1147 |
+
if matching_indices:
|
| 1148 |
+
matching_dict[pred_idx] = matching_indices
|
| 1149 |
+
|
| 1150 |
+
return matching_dict
|
| 1151 |
+
|
| 1152 |
+
def merge_matches(matches, matching_dict):
|
| 1153 |
+
final_matches = {}
|
| 1154 |
+
processed_gt_indices = set()
|
| 1155 |
+
|
| 1156 |
+
for gt_idx, match_info in matches.items():
|
| 1157 |
+
pred_indices = match_info['pred_indices']
|
| 1158 |
+
edit_distance = match_info['edit_distance']
|
| 1159 |
+
|
| 1160 |
+
pred_key = tuple(sorted(pred_indices))
|
| 1161 |
+
|
| 1162 |
+
if pred_key in final_matches:
|
| 1163 |
+
if gt_idx not in processed_gt_indices:
|
| 1164 |
+
final_matches[pred_key]['gt_indices'].append(gt_idx)
|
| 1165 |
+
processed_gt_indices.add(gt_idx)
|
| 1166 |
+
else:
|
| 1167 |
+
final_matches[pred_key] = {
|
| 1168 |
+
'gt_indices': [gt_idx],
|
| 1169 |
+
'edit_distance': edit_distance
|
| 1170 |
+
}
|
| 1171 |
+
processed_gt_indices.add(gt_idx)
|
| 1172 |
+
|
| 1173 |
+
for pred_idx, gt_indices in matching_dict.items():
|
| 1174 |
+
pred_key = (pred_idx,) if not isinstance(pred_idx, (list, tuple)) else tuple(sorted(pred_idx))
|
| 1175 |
+
|
| 1176 |
+
if pred_key in final_matches:
|
| 1177 |
+
for gt_idx in gt_indices:
|
| 1178 |
+
if gt_idx not in processed_gt_indices:
|
| 1179 |
+
final_matches[pred_key]['gt_indices'].append(gt_idx)
|
| 1180 |
+
processed_gt_indices.add(gt_idx)
|
| 1181 |
+
else:
|
| 1182 |
+
final_matches[pred_key] = {
|
| 1183 |
+
'gt_indices': [gt_idx for gt_idx in gt_indices if gt_idx not in processed_gt_indices],
|
| 1184 |
+
'edit_distance': None
|
| 1185 |
+
}
|
| 1186 |
+
processed_gt_indices.update(final_matches[pred_key]['gt_indices'])
|
| 1187 |
+
|
| 1188 |
+
return final_matches
|
| 1189 |
+
|
| 1190 |
+
|
| 1191 |
+
|
| 1192 |
+
def recalculate_edit_distances(final_matches, gt_lens_dict, norm_gt_lines, norm_pred_lines):
|
| 1193 |
+
for pred_key, info in final_matches.items():
|
| 1194 |
+
gt_indices = sorted(set(info['gt_indices']))
|
| 1195 |
+
|
| 1196 |
+
if not gt_indices:
|
| 1197 |
+
info['edit_distance'] = 1
|
| 1198 |
+
continue
|
| 1199 |
+
|
| 1200 |
+
if len(gt_indices) > 1:
|
| 1201 |
+
merged_gt_content = ''.join(norm_gt_lines[gt_idx] for gt_idx in gt_indices)
|
| 1202 |
+
pred_content = norm_pred_lines[pred_key[0]] if isinstance(pred_key[0], int) else ''
|
| 1203 |
+
|
| 1204 |
+
try:
|
| 1205 |
+
edit_distance = Levenshtein_distance(merged_gt_content, pred_content)
|
| 1206 |
+
normalized_edit_distance = edit_distance / max(len(merged_gt_content), len(pred_content))
|
| 1207 |
+
except ZeroDivisionError:
|
| 1208 |
+
normalized_edit_distance = 1
|
| 1209 |
+
|
| 1210 |
+
info['edit_distance'] = normalized_edit_distance
|
| 1211 |
+
else:
|
| 1212 |
+
gt_idx = gt_indices[0]
|
| 1213 |
+
pred_content = ' '.join(norm_pred_lines[pred_idx] for pred_idx in pred_key if isinstance(pred_idx, int))
|
| 1214 |
+
|
| 1215 |
+
try:
|
| 1216 |
+
edit_distance = Levenshtein_distance(norm_gt_lines[gt_idx], pred_content)
|
| 1217 |
+
normalized_edit_distance = edit_distance / max(len(norm_gt_lines[gt_idx]), len(pred_content))
|
| 1218 |
+
except ZeroDivisionError:
|
| 1219 |
+
normalized_edit_distance = 1
|
| 1220 |
+
|
| 1221 |
+
info['edit_distance'] = normalized_edit_distance
|
| 1222 |
+
info['pred_content'] = pred_content
|
| 1223 |
+
|
| 1224 |
+
|
| 1225 |
+
def convert_final_matches(final_matches, norm_gt_lines, norm_pred_lines):
|
| 1226 |
+
converted_results = []
|
| 1227 |
+
|
| 1228 |
+
all_gt_indices = set(range(len(norm_gt_lines)))
|
| 1229 |
+
all_pred_indices = set(range(len(norm_pred_lines)))
|
| 1230 |
+
|
| 1231 |
+
for pred_key, info in final_matches.items():
|
| 1232 |
+
pred_content = ' '.join(norm_pred_lines[pred_idx] for pred_idx in pred_key if isinstance(pred_idx, int))
|
| 1233 |
+
|
| 1234 |
+
for gt_idx in sorted(set(info['gt_indices'])):
|
| 1235 |
+
result_entry = {
|
| 1236 |
+
'gt_idx': int(gt_idx),
|
| 1237 |
+
'gt': norm_gt_lines[gt_idx],
|
| 1238 |
+
'pred_idx': list(pred_key),
|
| 1239 |
+
'pred': pred_content,
|
| 1240 |
+
'edit': info['edit_distance']
|
| 1241 |
+
}
|
| 1242 |
+
converted_results.append(result_entry)
|
| 1243 |
+
|
| 1244 |
+
matched_gt_indices = set().union(*[set(info['gt_indices']) for info in final_matches.values()])
|
| 1245 |
+
unmatched_gt_indices = all_gt_indices - matched_gt_indices
|
| 1246 |
+
matched_pred_indices = set(idx for pred_key in final_matches.keys() for idx in pred_key if isinstance(idx, int))
|
| 1247 |
+
unmatched_pred_indices = all_pred_indices - matched_pred_indices
|
| 1248 |
+
|
| 1249 |
+
if unmatched_pred_indices:
|
| 1250 |
+
if unmatched_gt_indices:
|
| 1251 |
+
distance_matrix = [
|
| 1252 |
+
# [Levenshtein_distance(norm_gt_lines[gt_idx], norm_pred_lines[pred_idx]) for pred_idx in unmatched_pred_indices]
|
| 1253 |
+
[Levenshtein_distance(norm_gt_lines[gt_idx], norm_pred_lines[pred_idx])/max(len(norm_gt_lines[gt_idx]), len(norm_pred_lines[pred_idx])) for pred_idx in unmatched_pred_indices]
|
| 1254 |
+
for gt_idx in unmatched_gt_indices
|
| 1255 |
+
]
|
| 1256 |
+
|
| 1257 |
+
row_ind, col_ind = linear_sum_assignment(distance_matrix)
|
| 1258 |
+
|
| 1259 |
+
for i, j in zip(row_ind, col_ind):
|
| 1260 |
+
gt_idx = list(unmatched_gt_indices)[i]
|
| 1261 |
+
pred_idx = list(unmatched_pred_indices)[j]
|
| 1262 |
+
result_entry = {
|
| 1263 |
+
'gt_idx': int(gt_idx),
|
| 1264 |
+
'gt': norm_gt_lines[gt_idx],
|
| 1265 |
+
'pred_idx': [pred_idx],
|
| 1266 |
+
'pred': norm_pred_lines[pred_idx],
|
| 1267 |
+
'edit': 1
|
| 1268 |
+
}
|
| 1269 |
+
converted_results.append(result_entry)
|
| 1270 |
+
|
| 1271 |
+
matched_gt_indices.update(list(unmatched_gt_indices)[i] for i in row_ind)
|
| 1272 |
+
else:
|
| 1273 |
+
result_entry = {
|
| 1274 |
+
'gt_idx': "",
|
| 1275 |
+
'gt': '',
|
| 1276 |
+
'pred_idx': list(unmatched_pred_indices),
|
| 1277 |
+
'pred': ' '.join(norm_pred_lines[pred_idx] for pred_idx in unmatched_pred_indices),
|
| 1278 |
+
'edit': 1
|
| 1279 |
+
}
|
| 1280 |
+
converted_results.append(result_entry)
|
| 1281 |
+
else:
|
| 1282 |
+
for gt_idx in unmatched_gt_indices:
|
| 1283 |
+
result_entry = {
|
| 1284 |
+
'gt_idx': int(gt_idx),
|
| 1285 |
+
'gt': norm_gt_lines[gt_idx],
|
| 1286 |
+
'pred_idx': "",
|
| 1287 |
+
'pred': '',
|
| 1288 |
+
'edit': 1
|
| 1289 |
+
}
|
| 1290 |
+
converted_results.append(result_entry)
|
| 1291 |
+
|
| 1292 |
+
return converted_results
|
FinixDocBench_Eval_for_Markdown/finixdoc_md_eval/utils/table_utils.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def markdown_to_html(markdown_table):
|
| 5 |
+
rows = [row.strip() for row in markdown_table.strip().split('\n') if row.strip()]
|
| 6 |
+
if len(rows) < 2:
|
| 7 |
+
return markdown_table
|
| 8 |
+
|
| 9 |
+
html_table = '<table>\n <thead>\n <tr>\n'
|
| 10 |
+
header_cells = [cell.strip() for cell in rows[0].split('|')[1:-1]]
|
| 11 |
+
for cell in header_cells:
|
| 12 |
+
html_table += f' <th>{cell}</th>\n'
|
| 13 |
+
html_table += ' </tr>\n </thead>\n <tbody>\n'
|
| 14 |
+
|
| 15 |
+
for row in rows[2:]:
|
| 16 |
+
cells = [cell.strip() for cell in row.split('|')[1:-1]]
|
| 17 |
+
html_table += ' <tr>\n'
|
| 18 |
+
for cell in cells:
|
| 19 |
+
html_table += f' <td>{cell}</td>\n'
|
| 20 |
+
html_table += ' </tr>\n'
|
| 21 |
+
|
| 22 |
+
html_table += ' </tbody>\n</table>\n'
|
| 23 |
+
return html_table
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def convert_table_str(s):
|
| 27 |
+
s = re.sub(r'<table.*?>', '<table>', s)
|
| 28 |
+
s = re.sub(r'<th', '<td', s)
|
| 29 |
+
s = re.sub(r'</th>', '</td>', s)
|
| 30 |
+
res = '\n\n'
|
| 31 |
+
temp_item = ''
|
| 32 |
+
for c in s:
|
| 33 |
+
temp_item += c
|
| 34 |
+
if c == '>' and not re.search(r'<td.*?>\$', temp_item):
|
| 35 |
+
res += temp_item + '\n'
|
| 36 |
+
temp_item = ''
|
| 37 |
+
return res + '\n'
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def find_md_table_mode(line):
|
| 41 |
+
return bool(re.search(r'-*?:', line) or re.search(r'---', line) or re.search(r':-*?', line))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def delete_table_and_body(input_list):
|
| 45 |
+
return [line for line in input_list if not re.search(r'</?t(able|head|body)>', line)]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def merge_table(md):
|
| 49 |
+
return convert_table_str(''.join(md))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def replace_table_with_placeholder(input_string):
|
| 53 |
+
lines = input_string.split('\n')
|
| 54 |
+
output_lines = []
|
| 55 |
+
in_table_block = False
|
| 56 |
+
temp_block = ''
|
| 57 |
+
last_line = ''
|
| 58 |
+
|
| 59 |
+
for line in lines:
|
| 60 |
+
if '<table>' in line:
|
| 61 |
+
in_table_block = True
|
| 62 |
+
temp_block += last_line
|
| 63 |
+
elif in_table_block:
|
| 64 |
+
if not find_md_table_mode(last_line) and '</thead>' not in last_line:
|
| 65 |
+
temp_block += '\n' + last_line
|
| 66 |
+
if '</table>' in last_line:
|
| 67 |
+
if '<table>' not in line:
|
| 68 |
+
in_table_block = False
|
| 69 |
+
output_lines.append(merge_table(temp_block))
|
| 70 |
+
temp_block = ''
|
| 71 |
+
else:
|
| 72 |
+
output_lines.append(last_line)
|
| 73 |
+
last_line = line
|
| 74 |
+
|
| 75 |
+
if last_line:
|
| 76 |
+
if in_table_block or '</table>' in last_line:
|
| 77 |
+
temp_block += '\n' + last_line
|
| 78 |
+
output_lines.append(merge_table(temp_block))
|
| 79 |
+
else:
|
| 80 |
+
output_lines.append(last_line)
|
| 81 |
+
|
| 82 |
+
return '\n'.join(output_lines)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def convert_table(input_str):
|
| 86 |
+
output_str = input_str.replace('<table>', '<table border="1" >')
|
| 87 |
+
output_str = output_str.replace('<td>', '<td colspan="1" rowspan="1">')
|
| 88 |
+
return output_str
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def convert_markdown_to_html(markdown_content):
|
| 92 |
+
markdown_content = markdown_content.replace('\r', '') + '\n'
|
| 93 |
+
pattern = re.compile(r'\|\s*.*?\s*\|\n', re.DOTALL)
|
| 94 |
+
matches = pattern.findall(markdown_content)
|
| 95 |
+
|
| 96 |
+
for match in matches:
|
| 97 |
+
html_table = markdown_to_html(match)
|
| 98 |
+
markdown_content = markdown_content.replace(match, html_table, 1)
|
| 99 |
+
|
| 100 |
+
return convert_table(replace_table_with_placeholder(markdown_content))
|
FinixDocBench_Eval_for_Markdown/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
python-Levenshtein==0.25.1
|
| 2 |
+
apted==1.0.3
|
| 3 |
+
lxml==4.9.4
|
| 4 |
+
beautifulsoup4==4.12.3
|
| 5 |
+
tqdm==4.66.4
|
| 6 |
+
pylatexenc==2.10
|
| 7 |
+
numpy==1.26.4
|
| 8 |
+
scipy==1.13.1
|
FinixDocBench_Eval_for_Markdown/run_eval.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from finixdoc_md_eval.omnidocbench_adapter import evaluate_md_dirs
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def parse_args():
|
| 12 |
+
parser = argparse.ArgumentParser(
|
| 13 |
+
description="Evaluate Markdown OCR/parsing results with text, reading-order, and table metrics."
|
| 14 |
+
)
|
| 15 |
+
parser.add_argument("--gt_dir", required=True, help="Directory containing ground-truth .md files.")
|
| 16 |
+
parser.add_argument("--pred_dir", required=True, help="Directory containing prediction .md files.")
|
| 17 |
+
parser.add_argument(
|
| 18 |
+
"--output_json",
|
| 19 |
+
default="eval_result.json",
|
| 20 |
+
help="Path to write metric results. Default: eval_result.json",
|
| 21 |
+
)
|
| 22 |
+
parser.add_argument(
|
| 23 |
+
"--allow_name_mismatch",
|
| 24 |
+
action="store_true",
|
| 25 |
+
help="Do not fail when gt/pred .md file names differ. Missing predictions are scored as empty.",
|
| 26 |
+
)
|
| 27 |
+
return parser.parse_args()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def md_names(path):
|
| 31 |
+
return {p.name for p in Path(path).iterdir() if p.is_file() and p.suffix == ".md"}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def validate_inputs(gt_dir, pred_dir, allow_name_mismatch=False):
|
| 35 |
+
gt_path = Path(gt_dir)
|
| 36 |
+
pred_path = Path(pred_dir)
|
| 37 |
+
if not gt_path.is_dir():
|
| 38 |
+
raise ValueError(f"GT directory does not exist: {gt_path}")
|
| 39 |
+
if not pred_path.is_dir():
|
| 40 |
+
raise ValueError(f"Prediction directory does not exist: {pred_path}")
|
| 41 |
+
|
| 42 |
+
gt_files = md_names(gt_path)
|
| 43 |
+
pred_files = md_names(pred_path)
|
| 44 |
+
if not gt_files:
|
| 45 |
+
raise ValueError(f"No .md files found in GT directory: {gt_path}")
|
| 46 |
+
if not pred_files:
|
| 47 |
+
raise ValueError(f"No .md files found in prediction directory: {pred_path}")
|
| 48 |
+
|
| 49 |
+
missing = sorted(gt_files - pred_files)
|
| 50 |
+
extra = sorted(pred_files - gt_files)
|
| 51 |
+
if not allow_name_mismatch and (missing or extra):
|
| 52 |
+
message = [
|
| 53 |
+
"GT and prediction .md file names must match.",
|
| 54 |
+
f"GT files: {len(gt_files)}",
|
| 55 |
+
f"Prediction files: {len(pred_files)}",
|
| 56 |
+
]
|
| 57 |
+
if missing:
|
| 58 |
+
message.append(f"Missing predictions: {len(missing)}; first: {missing[0]}")
|
| 59 |
+
if extra:
|
| 60 |
+
message.append(f"Unexpected predictions: {len(extra)}; first: {extra[0]}")
|
| 61 |
+
raise ValueError(" ".join(message))
|
| 62 |
+
|
| 63 |
+
return {
|
| 64 |
+
"gt_files": len(gt_files),
|
| 65 |
+
"pred_files": len(pred_files),
|
| 66 |
+
"missing_predictions": len(missing),
|
| 67 |
+
"unexpected_predictions": len(extra),
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def rounded_metrics(metrics):
|
| 72 |
+
clean = {}
|
| 73 |
+
for key, value in metrics.items():
|
| 74 |
+
if isinstance(value, float):
|
| 75 |
+
clean[key] = None if math.isnan(value) else round(value, 6)
|
| 76 |
+
else:
|
| 77 |
+
clean[key] = value
|
| 78 |
+
clean["score"] = clean["overall"]
|
| 79 |
+
return clean
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def main():
|
| 83 |
+
args = parse_args()
|
| 84 |
+
try:
|
| 85 |
+
input_summary = validate_inputs(args.gt_dir, args.pred_dir, args.allow_name_mismatch)
|
| 86 |
+
metrics = evaluate_md_dirs(args.gt_dir, args.pred_dir)
|
| 87 |
+
result = {
|
| 88 |
+
"success": True,
|
| 89 |
+
"metrics": rounded_metrics(metrics),
|
| 90 |
+
"inputs": input_summary,
|
| 91 |
+
}
|
| 92 |
+
output_path = Path(args.output_json)
|
| 93 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 94 |
+
output_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 95 |
+
|
| 96 |
+
print("FinixDoc Markdown Evaluation")
|
| 97 |
+
print(f" samples: {metrics['num_samples']}")
|
| 98 |
+
print(f" text_block_Edit_dist: {metrics['text_block_Edit_dist']:.6f}")
|
| 99 |
+
print(f" reading_order_Edit_dist: {metrics['reading_order_Edit_dist']:.6f}")
|
| 100 |
+
print(f" table_TEDS: {metrics['table_TEDS']:.6f}")
|
| 101 |
+
print(f" overall: {metrics['overall']:.6f}")
|
| 102 |
+
print(f" result_json: {output_path}")
|
| 103 |
+
except Exception as exc:
|
| 104 |
+
result = {
|
| 105 |
+
"success": False,
|
| 106 |
+
"error": str(exc),
|
| 107 |
+
}
|
| 108 |
+
output_path = Path(args.output_json)
|
| 109 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 110 |
+
output_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 111 |
+
print(f"Evaluation failed: {exc}", file=sys.stderr)
|
| 112 |
+
sys.exit(1)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
main()
|
LICENSE.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
| 2 |
+
|
| 3 |
+
SPDX-License-Identifier: CC-BY-NC-SA-4.0
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2026 Ant Group and the FinixDocBench authors.
|
| 6 |
+
|
| 7 |
+
This FinixDocBench release, including page images, Markdown ground truth, structured JSON annotations, benchmark metadata, and accompanying evaluation materials unless otherwise stated, is released under the **Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0)**.
|
| 8 |
+
|
| 9 |
+
Official license deed:
|
| 10 |
+
|
| 11 |
+
https://creativecommons.org/licenses/by-nc-sa/4.0/
|
| 12 |
+
|
| 13 |
+
Official legal code:
|
| 14 |
+
|
| 15 |
+
https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
|
| 16 |
+
|
| 17 |
+
## Human-Readable Summary
|
| 18 |
+
|
| 19 |
+
Under CC BY-NC-SA 4.0, you may share and adapt the licensed material for non-commercial purposes, provided that you give appropriate credit, indicate if changes were made, and distribute adaptations under the same license.
|
| 20 |
+
|
| 21 |
+
This summary is provided for convenience only. If there is any inconsistency, the official Creative Commons legal code governs.
|
| 22 |
+
|
| 23 |
+
## Attribution
|
| 24 |
+
|
| 25 |
+
If you use this FinixDocBench release, please cite the FinixDoc technical report:
|
| 26 |
+
|
| 27 |
+
```bibtex
|
| 28 |
+
@misc{wang2026finixdoc,
|
| 29 |
+
title = {FinixDoc: Rethinking Financial Document Parsing Beyond Saturated Benchmarks},
|
| 30 |
+
author = {Hang Wang and Jin Zhang and Guoliang Xu and Pengyue Lu and Yao Li and Zijiao Zhang and Tianyu Huang and Weiqi Xiong and Yulong Wang and Chuqiao Lu and Wenkang Huang and Kai Yang and Yadong Li and Hui Li and Xingzhong Xu and Xiao Xu},
|
| 31 |
+
year = {2026},
|
| 32 |
+
institution = {Ant Group},
|
| 33 |
+
url = {https://finix.alipay.com}
|
| 34 |
+
}
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
## Benchmark Integrity Notice
|
| 38 |
+
|
| 39 |
+
This FinixDocBench release is intended for research, benchmark evaluation, academic comparison, and reproducibility studies of OCR and document parsing systems.
|
| 40 |
+
|
| 41 |
+
If you use the benchmark labels, annotations, or ground truth for model training, fine-tuning, data augmentation, prompt optimization, or any other model-improvement process, please do not report the resulting model performance as an official FinixDocBench benchmark result.
|
| 42 |
+
|
| 43 |
+
The dataset is not intended for individual profiling, personal information extraction, identity inference, or automated financial, medical, insurance, legal, employment, credit, or similarly consequential decision-making.
|
| 44 |
+
|
| 45 |
+
## No Warranty
|
| 46 |
+
|
| 47 |
+
This FinixDocBench release is provided as-is, without warranty of any kind, express or implied, including but not limited to warranties of accuracy, completeness, merchantability, fitness for a particular purpose, and non-infringement.
|
README.md
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
- financial-documents
|
| 16 |
+
- layout-analysis
|
| 17 |
+
- table-recognition
|
| 18 |
+
- reading-order
|
| 19 |
+
- camera-captured-documents
|
| 20 |
+
- ultra-large-documents
|
| 21 |
+
- markdown
|
| 22 |
+
- chinese
|
| 23 |
+
configs:
|
| 24 |
+
- config_name: default
|
| 25 |
+
data_files:
|
| 26 |
+
- split: test
|
| 27 |
+
path:
|
| 28 |
+
- metadata.jsonl
|
| 29 |
+
- track*/images/*.png
|
| 30 |
+
---
|
| 31 |
+
|
| 32 |
+
# FinixDocBench
|
| 33 |
+
|
| 34 |
+
This repository contains a compliance-reviewed public subset of **FinixDocBench**, the financial-domain document parsing benchmark introduced in the technical report **"FinixDoc: Rethinking Financial Document Parsing Beyond Saturated Benchmarks"**.
|
| 35 |
+
|
| 36 |
+
The benchmark focuses on document parsing conditions that are common in real financial workflows but underrepresented in saturated clean-document benchmarks: digitally native insurance clauses, noisy camera-captured medical receipts, ultra-long pages, and very large dense tables. The expected model outputs are page-level Markdown and, where available, structured JSON layout annotations.
|
| 37 |
+
|
| 38 |
+
Project links:
|
| 39 |
+
|
| 40 |
+
- Project page: https://finix.alipay.com/
|
| 41 |
+
- Hugging Face dataset: https://huggingface.co/datasets/inclusionAI/FinixDocBench
|
| 42 |
+
- License: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
| 43 |
+
|
| 44 |
+
## Released Subset Contents
|
| 45 |
+
|
| 46 |
+
This release contains **742 page samples** from the broader FinixDocBench benchmark. Track 3 is split into two directories so that ultra-long pages and large-table pages can be evaluated separately.
|
| 47 |
+
|
| 48 |
+
| Track | Directory | Source type | Pages | Files per sample | Main task |
|
| 49 |
+
|---|---|---|---:|---|---|
|
| 50 |
+
| FinixDigital | `track1_finixdigital_242_insurance_terms/` | Digitally native insurance terms | 242 | image + Markdown + JSON | Markdown parsing and structured layout parsing |
|
| 51 |
+
| FinixPhoto | `track2_finixphoto_300/` | Mobile-captured medical receipts | 300 | image + Markdown + JSON | Robust Markdown parsing and structured layout parsing |
|
| 52 |
+
| FinixHuge-Long | `track3_finixhuge_100_long/` | Ultra-long financial or insurance pages | 100 | image + Markdown | Ultra-large page Markdown parsing |
|
| 53 |
+
| FinixHuge-Table | `track3_finixhuge_100_table/` | Large dense table pages | 100 | image + Markdown | Ultra-large table reconstruction |
|
| 54 |
+
|
| 55 |
+
The full FinixDocBench described in the technical report also includes a larger internal evaluation track, **FinixInner**, which is not included in this release because of privacy and compliance constraints. The FinixDigital package here is a 242-page insurance-terms subset of the broader FinixDigital track discussed in the report.
|
| 56 |
+
|
| 57 |
+
## Repository Structure
|
| 58 |
+
|
| 59 |
+
```text
|
| 60 |
+
FinixDocBench/
|
| 61 |
+
README.md
|
| 62 |
+
LICENSE.md
|
| 63 |
+
CITATION.cff
|
| 64 |
+
dataset_manifest.jsonl
|
| 65 |
+
metadata.jsonl
|
| 66 |
+
track1_finixdigital_242_insurance_terms/
|
| 67 |
+
images/
|
| 68 |
+
mds/
|
| 69 |
+
jsons/
|
| 70 |
+
track2_finixphoto_300/
|
| 71 |
+
images/
|
| 72 |
+
mds/
|
| 73 |
+
jsons/
|
| 74 |
+
track3_finixhuge_100_long/
|
| 75 |
+
images/
|
| 76 |
+
mds/
|
| 77 |
+
track3_finixhuge_100_table/
|
| 78 |
+
images/
|
| 79 |
+
mds/
|
| 80 |
+
FinixDocBench_Eval_for_Markdown/
|
| 81 |
+
README.md
|
| 82 |
+
requirements.txt
|
| 83 |
+
run_eval.py
|
| 84 |
+
finixdoc_md_eval/
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
Each sample is matched by file stem. For example, `abc123.png`, `abc123.md`, and `abc123.json` describe the same page when all three files are present.
|
| 88 |
+
|
| 89 |
+
The `dataset_manifest.jsonl` file provides one row per sample with relative paths, track metadata, image dimensions, and basic annotation counts. It is intended as a lightweight index for users who want to load the release programmatically.
|
| 90 |
+
|
| 91 |
+
## Tasks
|
| 92 |
+
|
| 93 |
+
This FinixDocBench release supports three complementary task settings.
|
| 94 |
+
|
| 95 |
+
### 1. Full-Page Markdown Parsing
|
| 96 |
+
|
| 97 |
+
Given a page image, a model should produce a complete page-level Markdown reconstruction. This task is available for all public tracks.
|
| 98 |
+
|
| 99 |
+
The Markdown ground truth preserves text order, headings, tables, and other page-level structure. HTML `<table>` blocks are used where table structure, merged cells, or dense financial layouts need to be represented more faithfully than plain Markdown tables.
|
| 100 |
+
|
| 101 |
+
### 2. Structured Layout Parsing
|
| 102 |
+
|
| 103 |
+
Given a page image, a model should produce structured page elements with category labels, bounding boxes, transcribed content, and reading order. This task is available for FinixDigital and FinixPhoto, which include `jsons/` annotations.
|
| 104 |
+
|
| 105 |
+
The public JSON files use pixel-space bounding boxes in the original image coordinate system. Each JSON file includes page metadata plus a `layout` list.
|
| 106 |
+
|
| 107 |
+
### 3. Ultra-Large Page Processability
|
| 108 |
+
|
| 109 |
+
FinixHuge-Long and FinixHuge-Table evaluate whether a system can return a syntactically valid, non-empty, page-level Markdown result for oversized documents. These pages stress page resolution, output length, table complexity, and reading-order preservation.
|
| 110 |
+
|
| 111 |
+
Because FinixHuge is Markdown-only in this release, it is best evaluated with Markdown metrics plus a success-rate style processability check.
|
| 112 |
+
|
| 113 |
+
## Annotation Schema
|
| 114 |
+
|
| 115 |
+
FinixDigital and FinixPhoto use a unified 10-class page-element schema:
|
| 116 |
+
|
| 117 |
+
```text
|
| 118 |
+
page-header
|
| 119 |
+
page-footer
|
| 120 |
+
title
|
| 121 |
+
section-header
|
| 122 |
+
text
|
| 123 |
+
table
|
| 124 |
+
figure
|
| 125 |
+
caption
|
| 126 |
+
footnote
|
| 127 |
+
other
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
Top-level JSON fields:
|
| 131 |
+
|
| 132 |
+
| Field | Description |
|
| 133 |
+
|---|---|
|
| 134 |
+
| `width` | Original page image width in pixels. |
|
| 135 |
+
| `height` | Original page image height in pixels. |
|
| 136 |
+
| `resized_width` | Width used by the annotation or preprocessing pipeline. |
|
| 137 |
+
| `resized_height` | Height used by the annotation or preprocessing pipeline. |
|
| 138 |
+
| `max_pixels` | Maximum pixel budget recorded by the preprocessing pipeline. |
|
| 139 |
+
| `min_pixels` | Minimum pixel budget recorded by the preprocessing pipeline. |
|
| 140 |
+
| `layout` | Ordered list of page elements. |
|
| 141 |
+
|
| 142 |
+
Each `layout` item contains:
|
| 143 |
+
|
| 144 |
+
| Field | Description |
|
| 145 |
+
|---|---|
|
| 146 |
+
| `category` | One of the 10 page-element labels. |
|
| 147 |
+
| `bbox` | Pixel-space bounding box `[x1, y1, x2, y2]` in the page image coordinate system. |
|
| 148 |
+
| `content` | Transcribed text, Markdown structural marker, or serialized table content. This field may be absent for some `figure` elements. |
|
| 149 |
+
| `order` | Reading-order index of the layout element. |
|
| 150 |
+
|
| 151 |
+
Example:
|
| 152 |
+
|
| 153 |
+
```json
|
| 154 |
+
{
|
| 155 |
+
"width": 993,
|
| 156 |
+
"height": 1404,
|
| 157 |
+
"resized_width": 992,
|
| 158 |
+
"resized_height": 1408,
|
| 159 |
+
"max_pixels": 16777216,
|
| 160 |
+
"min_pixels": 4096,
|
| 161 |
+
"layout": [
|
| 162 |
+
{
|
| 163 |
+
"category": "section-header",
|
| 164 |
+
"bbox": [82, 364, 223, 394],
|
| 165 |
+
"content": "## 2.3 责任免除",
|
| 166 |
+
"order": 5
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"category": "table",
|
| 170 |
+
"bbox": [337, 156, 916, 295],
|
| 171 |
+
"content": "<table>...</table>",
|
| 172 |
+
"order": 3
|
| 173 |
+
}
|
| 174 |
+
]
|
| 175 |
+
}
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
## Dataset Statistics
|
| 179 |
+
|
| 180 |
+
| Track | Images | Markdown files | JSON files | Notes |
|
| 181 |
+
|---|---:|---:|---:|---|
|
| 182 |
+
| FinixDigital | 242 | 242 | 242 | 6,223 structured layout elements; 214 tables |
|
| 183 |
+
| FinixPhoto | 300 | 300 | 300 | 8,517 structured layout elements; 224 tables |
|
| 184 |
+
| FinixHuge-Long | 100 | 100 | 0 | Ultra-long page images, up to 287M pixels |
|
| 185 |
+
| FinixHuge-Table | 100 | 100 | 0 | Large dense table images, up to 386M pixels |
|
| 186 |
+
| **Total** | **742** | **742** | **542** | All samples have paired images and Markdown |
|
| 187 |
+
|
| 188 |
+
Category counts for the structured JSON tracks:
|
| 189 |
+
|
| 190 |
+
| Category | Count |
|
| 191 |
+
|---|---:|
|
| 192 |
+
| `text` | 10,158 |
|
| 193 |
+
| `section-header` | 1,522 |
|
| 194 |
+
| `figure` | 1,307 |
|
| 195 |
+
| `title` | 504 |
|
| 196 |
+
| `table` | 438 |
|
| 197 |
+
| `caption` | 265 |
|
| 198 |
+
| `page-footer` | 223 |
|
| 199 |
+
| `footnote` | 204 |
|
| 200 |
+
| `page-header` | 64 |
|
| 201 |
+
| `other` | 55 |
|
| 202 |
+
|
| 203 |
+
## Loading Examples
|
| 204 |
+
|
| 205 |
+
Load the manifest with the Hugging Face `datasets` library:
|
| 206 |
+
|
| 207 |
+
```python
|
| 208 |
+
from datasets import load_dataset
|
| 209 |
+
|
| 210 |
+
manifest = load_dataset(
|
| 211 |
+
"json",
|
| 212 |
+
data_files="dataset_manifest.jsonl",
|
| 213 |
+
split="train",
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
print(manifest[0])
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
Read a sample locally after cloning the repository:
|
| 220 |
+
|
| 221 |
+
```python
|
| 222 |
+
from pathlib import Path
|
| 223 |
+
from PIL import Image
|
| 224 |
+
import json
|
| 225 |
+
|
| 226 |
+
repo = Path("FinixDocBench")
|
| 227 |
+
row = manifest[0]
|
| 228 |
+
|
| 229 |
+
image = Image.open(repo / row["image_path"])
|
| 230 |
+
markdown = (repo / row["markdown_path"]).read_text(encoding="utf-8")
|
| 231 |
+
|
| 232 |
+
annotation = None
|
| 233 |
+
if row["json_path"] is not None:
|
| 234 |
+
annotation = json.loads((repo / row["json_path"]).read_text(encoding="utf-8"))
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
## Evaluation
|
| 238 |
+
|
| 239 |
+
The repository includes a lightweight Markdown evaluator:
|
| 240 |
+
|
| 241 |
+
```bash
|
| 242 |
+
cd FinixDocBench_Eval_for_Markdown
|
| 243 |
+
python3 -m venv .venv
|
| 244 |
+
source .venv/bin/activate
|
| 245 |
+
pip install -r requirements.txt
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
Run evaluation on a track by providing a ground-truth Markdown directory and a prediction Markdown directory with matching file names:
|
| 249 |
+
|
| 250 |
+
```bash
|
| 251 |
+
python run_eval.py \
|
| 252 |
+
--gt_dir ../track2_finixphoto_300/mds \
|
| 253 |
+
--pred_dir /path/to/predicted_mds \
|
| 254 |
+
--output_json outputs/finixphoto_result.json
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
The Markdown evaluator reports:
|
| 258 |
+
|
| 259 |
+
| Metric | Direction | Description |
|
| 260 |
+
|---|---|---|
|
| 261 |
+
| `text_block_Edit_dist` | Lower is better | Normalized edit distance over matched text blocks. |
|
| 262 |
+
| `reading_order_Edit_dist` | Lower is better | Normalized edit distance over serialized reading-order sequences. |
|
| 263 |
+
| `table_TEDS` | Higher is better | Tree-edit-distance-based table similarity, scaled to 0-100. |
|
| 264 |
+
| `overall` | Higher is better | Composite score on a 0-100 scale. |
|
| 265 |
+
|
| 266 |
+
The overall score is:
|
| 267 |
+
|
| 268 |
+
```text
|
| 269 |
+
overall = ((1 - text_block_Edit_dist) * 100
|
| 270 |
+
+ (1 - reading_order_Edit_dist) * 100
|
| 271 |
+
+ table_TEDS) / 3
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
For FinixHuge, users should additionally report a success rate: the fraction of pages for which the system returns a syntactically valid, non-empty page-level Markdown result without runtime failure, severe truncation, or format errors that prevent downstream evaluation.
|
| 275 |
+
|
| 276 |
+
Structured JSON annotations are provided for FinixDigital and FinixPhoto. This repository currently ships the Markdown evaluator; if you report structured layout metrics, please describe the evaluator, matching rules, and coordinate convention used.
|
| 277 |
+
|
| 278 |
+
## Reference Results from the Technical Report
|
| 279 |
+
|
| 280 |
+
The following values are copied from the FinixDoc technical report for context. They correspond to the benchmark protocol reported in the paper and should not be treated as precomputed scores for every subset in this release unless the same split and evaluation protocol are reproduced.
|
| 281 |
+
|
| 282 |
+
### FinixDigital
|
| 283 |
+
|
| 284 |
+
| Model | Overall | TextEdit | TableTEDS | TableTEDS-S | ReadOrderEdit |
|
| 285 |
+
|---|---:|---:|---:|---:|---:|
|
| 286 |
+
| Qwen3-VL-4B | 80.18 | 0.145 | 76.04 | 81.23 | 0.210 |
|
| 287 |
+
| FinixDoc-VL | 93.19 | 0.039 | 92.07 | 93.67 | 0.086 |
|
| 288 |
+
| DeepSeek-OCR-2 | 82.80 | 0.139 | 90.00 | 92.32 | 0.277 |
|
| 289 |
+
| FireRed-OCR | 83.10 | 0.119 | 87.10 | 89.14 | 0.259 |
|
| 290 |
+
| PaddleOCR-VL-1.5 | 85.41 | 0.116 | 86.12 | 88.26 | 0.183 |
|
| 291 |
+
| GLM-OCR | 86.28 | 0.121 | 89.44 | 90.99 | 0.185 |
|
| 292 |
+
| Youtu-Parsing | 89.26 | 0.091 | 87.79 | 90.85 | 0.109 |
|
| 293 |
+
| Dots.OCR | 90.36 | 0.058 | 89.78 | 92.26 | 0.129 |
|
| 294 |
+
| MinerU 2.5 | 92.96 | 0.045 | 91.18 | 92.70 | 0.078 |
|
| 295 |
+
| Qwen3.5-397B-A17B | 84.90 | 0.119 | 87.30 | 89.51 | 0.207 |
|
| 296 |
+
| Kimi-K2.5 | 85.05 | 0.119 | 85.95 | 88.24 | 0.189 |
|
| 297 |
+
| Qwen3-VL-235B-A22B-Instruct | 87.26 | 0.076 | 82.77 | 85.44 | 0.134 |
|
| 298 |
+
|
| 299 |
+
### FinixPhoto
|
| 300 |
+
|
| 301 |
+
| Model | Overall | TextEdit | TableTEDS | TableTEDS-S | ReadOrderEdit |
|
| 302 |
+
|---|---:|---:|---:|---:|---:|
|
| 303 |
+
| Qwen3-VL-4B | 54.28 | 0.408 | 50.13 | 63.04 | 0.465 |
|
| 304 |
+
| FinixDoc-VL | 67.03 | 0.276 | 69.08 | 77.69 | 0.404 |
|
| 305 |
+
| PaddleOCR-VL-1.5 | 41.28 | 0.512 | 34.54 | 46.72 | 0.595 |
|
| 306 |
+
| MinerU 2.5 | 43.08 | 0.513 | 35.54 | 48.58 | 0.550 |
|
| 307 |
+
| DeepSeek-OCR-2 | 43.20 | 0.459 | 30.69 | 43.52 | 0.552 |
|
| 308 |
+
| GLM-OCR | 45.82 | 0.521 | 50.47 | 60.22 | 0.609 |
|
| 309 |
+
| FireRed-OCR | 47.20 | 0.487 | 38.50 | 53.72 | 0.482 |
|
| 310 |
+
| Dots.OCR | 52.57 | 0.399 | 44.90 | 56.92 | 0.473 |
|
| 311 |
+
| Youtu-Parsing | 60.90 | 0.345 | 59.01 | 66.23 | 0.418 |
|
| 312 |
+
| Qwen3.5-397B-A17B | 62.58 | 0.384 | 62.04 | 71.82 | 0.359 |
|
| 313 |
+
| Qwen3-VL-235B-A22B-Instruct | 62.65 | 0.359 | 63.55 | 72.13 | 0.397 |
|
| 314 |
+
| Kimi-K2.5 | 65.55 | 0.325 | 70.16 | 77.34 | 0.410 |
|
| 315 |
+
|
| 316 |
+
### FinixHuge
|
| 317 |
+
|
| 318 |
+
| Model | Success Rate | Overall | TextEdit | TableTEDS | TableTEDS-S | ReadOrderEdit |
|
| 319 |
+
|---|---:|---:|---:|---:|---:|---:|
|
| 320 |
+
| FinixDoc | 0.92 | 68.23 | 0.357 | 57.09 | 60.10 | 0.167 |
|
| 321 |
+
| Qwen3-VL-235B-A22B-Instruct | 0.68 | 34.85 | 0.847 | 47.05 | 63.20 | 0.578 |
|
| 322 |
+
| GLM-OCR | 0.34 | 38.06 | 0.816 | 59.39 | 62.43 | 0.636 |
|
| 323 |
+
|
| 324 |
+
## Intended Uses
|
| 325 |
+
|
| 326 |
+
This dataset is intended for:
|
| 327 |
+
|
| 328 |
+
- Evaluating OCR and document parsing systems on financial-domain documents.
|
| 329 |
+
- Testing full-page Markdown reconstruction.
|
| 330 |
+
- Testing layout parsing, table parsing, bounding boxes, and reading-order recovery on FinixDigital and FinixPhoto.
|
| 331 |
+
- Measuring robustness on noisy camera-captured receipt images.
|
| 332 |
+
- Evaluating end-to-end processability on ultra-large document pages.
|
| 333 |
+
|
| 334 |
+
## Out-of-Scope Uses
|
| 335 |
+
|
| 336 |
+
This dataset is not intended for:
|
| 337 |
+
|
| 338 |
+
- Individual profiling or personal information extraction.
|
| 339 |
+
- Automated financial, medical, insurance, legal, employment, credit, or similarly consequential decision-making.
|
| 340 |
+
- Reporting benchmark numbers after using benchmark labels or ground truth for training, fine-tuning, data augmentation, or prompt optimization.
|
| 341 |
+
- Claiming complete coverage of all financial document scenarios.
|
| 342 |
+
|
| 343 |
+
## Limitations
|
| 344 |
+
|
| 345 |
+
FinixDocBench is an evaluation benchmark, not a comprehensive training corpus. This release covers selected high-value financial document parsing scenarios and does not include the private FinixInner track.
|
| 346 |
+
|
| 347 |
+
FinixPhoto is derived from public-scenario medical receipt sources and re-annotated under the FinixDocBench schema. Prior exposure of some external models to the original public sources cannot be fully ruled out.
|
| 348 |
+
|
| 349 |
+
FinixHuge emphasizes system-level processability with Markdown-only public annotations. Direct single-pass model comparisons may understate or overstate practical usability if failed pages, truncation, or invalid outputs are not reported consistently.
|
| 350 |
+
|
| 351 |
+
Some page images may be very large. Users should use image loading libraries carefully and configure decompression or pixel limits intentionally when evaluating FinixHuge.
|
| 352 |
+
|
| 353 |
+
## License
|
| 354 |
+
|
| 355 |
+
This FinixDocBench release is distributed under the **Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0)**.
|
| 356 |
+
|
| 357 |
+
See [LICENSE.md](LICENSE.md) for the human-readable license notice and the official Creative Commons license link.
|
| 358 |
+
|
| 359 |
+
## Citation
|
| 360 |
+
|
| 361 |
+
If you use this FinixDocBench release, please cite:
|
| 362 |
+
|
| 363 |
+
```bibtex
|
| 364 |
+
@misc{wang2026finixdoc,
|
| 365 |
+
title = {FinixDoc: Rethinking Financial Document Parsing Beyond Saturated Benchmarks},
|
| 366 |
+
author = {Hang Wang and Jin Zhang and Guoliang Xu and Pengyue Lu and Yao Li and Zijiao Zhang and Tianyu Huang and Weiqi Xiong and Yulong Wang and Chuqiao Lu and Wenkang Huang and Kai Yang and Yadong Li and Hui Li and Xingzhong Xu and Xiao Xu},
|
| 367 |
+
year = {2026},
|
| 368 |
+
institution = {Ant Group},
|
| 369 |
+
url = {https://finix.alipay.com}
|
| 370 |
+
}
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
## Contact
|
| 374 |
+
|
| 375 |
+
For questions about the benchmark, please contact the FinixDoc authors through the project page or the Ant Group Hugging Face organization.
|
dataset_manifest.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
metadata.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
track1_finixdigital_242_insurance_terms/images/008053f7-47b1-4810-bfad-6f51c0ddc390.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/01c9577f-0cca-440e-a037-93c754764553.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/03b07d4a-2895-48d7-b3f4-841f3875d387.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/03e0c0a4-6b6f-432a-8e1d-08425b02fe55.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/0603ab53-ea60-4698-983f-c4d9a3d391fd.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/08c42598-d27d-43b6-9797-991b86d1aa2b.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/090e980a-47b3-4ba9-898d-87047e69cb7f.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/0915fdd1-dc13-42e4-bc3f-1deb95fc242e.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/091f1637-c551-4669-9ba3-bb55d9bd8754.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/09cc7e9d-308f-446f-85cb-686673746367.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/0b2dfaff-0b84-40d1-b8ed-32419263ec42.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/0bc4bb5f-8b93-4ab2-b197-40d187b83e00.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/0d657279-1e0b-4e3e-8ff6-2abd6767119c.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/0eb11f58-5a95-4a53-a4fa-b5a5d28273ed.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/0f05d9b0-8b83-40cd-9a07-24c0c9179729.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/1017cac1-9cb9-4c70-b9ed-a22d8ab865a8.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/10d17bd5-5291-4474-8a5d-45d0b6e45c20.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/11bceca9-0986-4d27-a5a5-73665c032f6e.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/11f5554a-2a43-4f96-b76b-d9f2e90bd863.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/12b01854-1d57-46e3-a743-d90588dccef3.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/12cae7f9-8d69-4093-b328-a23d71683dfa.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/13977ebf-0bb0-4e16-a1ae-3cef62246628.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/164da4c7-6bb4-42a0-95e1-c9c5fdb8e5d9.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/16b1433c-4238-449c-9c16-6a85b622767a.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/190d2be8-7426-51a4-bc90-8c3dce04fd42.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/1abb05d2-55aa-43de-8a87-f53157e27338.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/1aed3e59-ad28-44f1-b53b-ca0ff336373e.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/1cd8ead1-35d7-43c6-b8e2-e9edc3cfdd09.png
ADDED
|
Git LFS Details
|
track1_finixdigital_242_insurance_terms/images/1dafdf2d-a448-483a-83a1-5d223b473300.png
ADDED
|
Git LFS Details
|