diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FieldValueItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FieldValueItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a509c5a3a998286e9a2902b2494100b2c744b8a1 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FieldValueItem.yaml @@ -0,0 +1,12 @@ +children: [] +content_layer: body +formatting: null +hyperlink: null +kind: fillable +label: field_value +meta: null +orig: whatever +parent: null +prov: [] +self_ref: '#' +text: whatever diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FloatingItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FloatingItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0c11c8f3b6071cdfac6583324ff07a860fd731a2 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FloatingItem.yaml @@ -0,0 +1,11 @@ +captions: [] +children: [] +footnotes: [] +image: null +label: text +parent: null +prov: [] +references: [] +self_ref: '#' +content_layer: body +meta: null diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f296d8014e63e48ecea1d5df5aa4dbd5e051d8c7 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormItem.yaml @@ -0,0 +1,32 @@ +captions: [] +children: [] +content_layer: body +footnotes: [] +graph: + cells: + - cell_id: 0 + item_ref: null + label: key + orig: '#' + prov: null + text: number + - cell_id: 1 + item_ref: null + label: value + orig: '1' + prov: null + text: '1' + links: + - label: to_value + source_cell_id: 0 + target_cell_id: 1 + - label: to_key + source_cell_id: 1 + target_cell_id: 0 +image: null +label: form +meta: null +parent: null +prov: [] +references: [] +self_ref: '#' \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormulaItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormulaItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd631ff56c177a234c3d6b59979f13b1c3579c87 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormulaItem.yaml @@ -0,0 +1,11 @@ +children: [] +label: formula +orig: whatever +parent: null +prov: [] +self_ref: '#' +text: E=mc^2 +content_layer: body +formatting: null +hyperlink: null +meta: null diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/KeyValueItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/KeyValueItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f6db93e10375ea205f17feed86703227373304fb --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/KeyValueItem.yaml @@ -0,0 +1,32 @@ +captions: [] +children: [] +content_layer: body +footnotes: [] +graph: + cells: + - cell_id: 0 + item_ref: null + label: key + orig: '#' + prov: null + text: number + - cell_id: 1 + item_ref: null + label: value + orig: '1' + prov: null + text: '1' + links: + - label: to_value + source_cell_id: 0 + target_cell_id: 1 + - label: to_key + source_cell_id: 1 + target_cell_id: 0 +image: null +label: key_value_region +meta: null +parent: null +prov: [] +references: [] +self_ref: '#' \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/ListItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/ListItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..300661d3ba484a90691648b8199356596dd99e42 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/ListItem.yaml @@ -0,0 +1,13 @@ +children: [] +enumerated: true +label: list_item +marker: (1) +orig: whatever +parent: null +prov: [] +self_ref: '#' +text: whatever +content_layer: body +formatting: null +hyperlink: null +meta: null diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/PictureItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/PictureItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3fc72158834d8a0a927dc702dd8718c942a4d8d5 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/PictureItem.yaml @@ -0,0 +1,12 @@ +annotations: [] +captions: [] +children: [] +footnotes: [] +image: null +label: picture +parent: null +prov: [] +references: [] +self_ref: '#' +content_layer: body +meta: null diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/SectionHeaderItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/SectionHeaderItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ab1a526d9124b7e067ab75dfd5ddb78f6aebb22 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/SectionHeaderItem.yaml @@ -0,0 +1,12 @@ +children: [] +label: section_header +level: 2 +orig: whatever +parent: null +prov: [] +self_ref: '#' +text: whatever +content_layer: body +formatting: null +hyperlink: null +meta: null diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TableItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TableItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5b816a3763fccf5f6d2b1da909e5528f3015db86 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TableItem.yaml @@ -0,0 +1,198 @@ +captions: [] +children: [] +data: + grid: + - - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 1 + end_row_offset_idx: 1 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 0 + start_row_offset_idx: 0 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 2 + end_row_offset_idx: 1 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 1 + start_row_offset_idx: 0 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 3 + end_row_offset_idx: 1 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 2 + start_row_offset_idx: 0 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 4 + end_row_offset_idx: 1 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 3 + start_row_offset_idx: 0 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 5 + end_row_offset_idx: 1 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 4 + start_row_offset_idx: 0 + text: '' + - - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 1 + end_row_offset_idx: 2 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 0 + start_row_offset_idx: 1 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 2 + end_row_offset_idx: 2 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 1 + start_row_offset_idx: 1 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 3 + end_row_offset_idx: 2 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 2 + start_row_offset_idx: 1 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 4 + end_row_offset_idx: 2 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 3 + start_row_offset_idx: 1 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 5 + end_row_offset_idx: 2 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 4 + start_row_offset_idx: 1 + text: '' + - - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 1 + end_row_offset_idx: 3 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 0 + start_row_offset_idx: 2 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 2 + end_row_offset_idx: 3 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 1 + start_row_offset_idx: 2 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 3 + end_row_offset_idx: 3 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 2 + start_row_offset_idx: 2 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 4 + end_row_offset_idx: 3 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 3 + start_row_offset_idx: 2 + text: '' + - bbox: null + col_span: 1 + column_header: false + end_col_offset_idx: 5 + end_row_offset_idx: 3 + fillable: false + row_header: false + row_section: false + row_span: 1 + start_col_offset_idx: 4 + start_row_offset_idx: 2 + text: '' + num_cols: 5 + num_rows: 3 + orientation: rot_0 + table_cells: [] +footnotes: [] +image: null +label: table +parent: null +prov: [] +references: [] +self_ref: '#' +content_layer: body +annotations: [] +meta: null diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TextItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TextItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7061046ac12d327b959223ab48b48424c5b75b8d --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TextItem.yaml @@ -0,0 +1,11 @@ +children: [] +label: text +orig: whatever +parent: null +prov: [] +self_ref: '#' +text: whatever +content_layer: body +formatting: null +hyperlink: null +meta: null diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TitleItem.yaml b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TitleItem.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7fcbb4cc35e2d9a35cf1d5a693028ae1c678368a --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TitleItem.yaml @@ -0,0 +1,11 @@ +children: [] +label: title +orig: whatever +parent: null +prov: [] +self_ref: '#' +text: whatever +content_layer: body +formatting: null +hyperlink: null +meta: null diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.c b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.c new file mode 100644 index 0000000000000000000000000000000000000000..8832ef486b6619c274ac209925954db9cae09b67 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.c @@ -0,0 +1,22 @@ +#include +#include + +double circle_area(double radius) { + return M_PI * radius * radius; +} + +double circle_circumference(double radius) { + return 2 * M_PI * radius; +} + +int fibonacci(int n) { + if (n <= 1) { + return n; + } + return fibonacci(n - 1) + fibonacci(n - 2); +} + +int main() { + printf("Hello, World!\n"); + return 0; +} diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.go b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.go new file mode 100644 index 0000000000000000000000000000000000000000..9e36e6cfb6b5f281b106d0253e198df810ec1738 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.go @@ -0,0 +1,23 @@ +package main + +import "fmt" + +func main() { + fmt.Println("Hello, World!") +} + +func fibonacci(n int) int { + if n <= 1 { + return n + } + return fibonacci(n-1) + fibonacci(n-2) +} + +type Person struct { + Name string + Age int +} + +func (p Person) String() string { + return fmt.Sprintf("%s is %d years old", p.Name, p.Age) +} diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.java b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.java new file mode 100644 index 0000000000000000000000000000000000000000..c65a4925dacf1d226a4aa5c7feccfcc949eea3e6 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.java @@ -0,0 +1,25 @@ +public class Calculator { + private double result; + + public Calculator() { + this.result = 0.0; + } + + public double add(double a, double b) { + this.result = a + b; + return this.result; + } + + public double subtract(double a, double b) { + this.result = a - b; + return this.result; + } + + public double getResult() { + return this.result; + } + + public void reset() { + this.result = 0.0; + } +} diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.js b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.js new file mode 100644 index 0000000000000000000000000000000000000000..65474c683ac219c2cad95f184b30e1a2cfa99dbe --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.js @@ -0,0 +1,23 @@ +function multiply(a, b) { + return a * b; +} + +function divide(a, b) { + return b !== 0 ? a / b : 0; +} + +function greet(name) { + return `Hello, ${name}!`; +} + +class Calculator { + constructor() { + this.history = []; + } + + add(a, b) { + const result = a + b; + this.history.push(`${a} + ${b} = ${result}`); + return result; + } +} diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.md b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.md new file mode 100644 index 0000000000000000000000000000000000000000..64f2bf0b1547eb80b86f455a68f7b975c78a61c3 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.md @@ -0,0 +1,23 @@ +# Sample Markdown File + +This is a sample markdown file for testing repository chunking. + +## Code Example + +Here's some Python code: + +```python +def hello(): + print("Hello, World!") +``` + +## Features + +- Lists +- **Bold text** +- *Italic text* +- [Links](https://example.com) + +## Conclusion + +This file should be processed as text content, not as code. diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.py new file mode 100644 index 0000000000000000000000000000000000000000..ea1addd5b135fe8cff84350bdd6fa6386789eb2a --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.py @@ -0,0 +1,25 @@ +def fibonacci(n): + """Calculate the nth Fibonacci number using recursion.""" + if n <= 1: + return n + return fibonacci(n - 1) + fibonacci(n - 2) + + +class MathUtils: + """Utility class for mathematical operations.""" + + def __init__(self): + self.pi = 3.14159 + + def circle_area(self, radius): + """Calculate the area of a circle.""" + return self.pi * radius**2 + + def circle_circumference(self, radius): + """Calculate the circumference of a circle.""" + return 2 * self.pi * radius + + +def hello(): + """A simple hello function.""" + return "Hello, World!" diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.ts b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.ts new file mode 100644 index 0000000000000000000000000000000000000000..3bc890a8a879700ac811a865098a2e23cf953ea0 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.ts @@ -0,0 +1,20 @@ +interface Point { + x: number; + y: number; +} + +function distance(p1: Point, p2: Point): number { + return Math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2); +} + +class Vector { + constructor(public x: number, public y: number) {} + + magnitude(): number { + return Math.sqrt(this.x ** 2 + this.y ** 2); + } + + add(other: Vector): Vector { + return new Vector(this.x + other.x, this.y + other.y); + } +} diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-01.json b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-01.json new file mode 100644 index 0000000000000000000000000000000000000000..f42202e921a1cb00bd5c8511fee887ee97940550 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-01.json @@ -0,0 +1,33 @@ +{ + "aliases": [ + ".production", + "arxiv" + ], + "created": "2022-08-15T14:10:32.768+00:00", + "description": "arXiv® is a curated research-sharing platform open to anyone. It stores scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and systems science, and economics.", + "source": "https://arxiv.org", + "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-arxiv-data", + "display_name": "arXiv full documents", + "type": "Reference", + "classification": [ + "Public", + "PI" + ], + "license": "https://arxiv.org/about", + "filename": "arxiv-gs.json", + "domain": [ + "Science", + "Literature" + ], + "$ref": "ccs:schemas#/Document", + "ccs_s3_data": { + "endpoint": "s3.eu-de.cloud-object-storage.appdomain.cloud", + "paths": [ + { + "bucket": "foc-deepsearch-s3-elastic", + "prefix": "deepsearch-elastic-dataplatform", + "infix": "cxs-8a1925c96f7b49508855ab270d0f3281" + } + ] + } +} \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-02.json b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-02.json new file mode 100644 index 0000000000000000000000000000000000000000..9b014ee6e76807632eddec19a1716601eaf30d94 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-02.json @@ -0,0 +1,39 @@ +{ + "aliases": [ + ".production", + "arxiv" + ], + "created": "2022-08-15T14:10:32.768+00:00", + "description": "arXiv® is a curated research-sharing platform open to anyone. It stores scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and systems science, and economics.", + "source": "https://arxiv.org", + "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-arxiv-data", + "display_name": "arXiv full documents", + "type": "Document", + "classification": [ + "Public", + "PI" + ], + "version": [ + { + "name": "docling-core", + "version": "beta" + } + ], + "license": "https://arxiv.org/about", + "filename": "arxiv-gs.json", + "domain": [ + "Science", + "Banking & Finance" + ], + "$ref": "cps:schemas#/Record", + "ccs_s3_data": { + "endpoint": "s3.eu-de.cloud-object-storage.appdomain.cloud", + "paths": [ + { + "bucket": "foc-deepsearch-s3-elastic", + "prefix": "deepsearch-elastic-dataplatform", + "infix": "cxs-8a1925c96f7b49508855ab270d0f3281" + } + ] + } +} \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-03.json b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-03.json new file mode 100644 index 0000000000000000000000000000000000000000..52e99f6474d3c2cf47ff11bd4c48e068416b428a --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-03.json @@ -0,0 +1,12 @@ +{ + "created": "2022-08-15T14:10:32.768+00:00", + "version": [ + { + "name": "docling-core", + "version": "1.0.0" + } + ], + "type": "Record", + "$ref": "cps:schemas#/Record", + "extra": "an extra field" +} \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-01.json b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-01.json new file mode 100644 index 0000000000000000000000000000000000000000..34e824815e5a04663be6e29c2770006843c0770f --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-01.json @@ -0,0 +1,38 @@ +{ + "aliases": [ + ".production", + "arxiv" + ], + "created": "2022-08-15T14:10:32.768+00:00", + "description": "arXiv® is a curated research-sharing platform open to anyone. It stores scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and systems science, and economics.", + "source": "https://arxiv.org", + "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-arxiv-data", + "display_name": "arXiv full documents", + "type": "Document", + "classification": [ + "Public", + "PI" + ], + "version": [ + { + "name": "docling-core", + "version": "1.0.1" + } + ], + "license": "https://arxiv.org/about", + "filename": "arxiv-gs.json", + "domain": [ + "Science" + ], + "$ref": "ccs:schemas#/Document", + "ccs_s3_data": { + "endpoint": "s3.eu-de.cloud-object-storage.appdomain.cloud", + "paths": [ + { + "bucket": "foc-deepsearch-s3-elastic", + "prefix": "deepsearch-elastic-dataplatform", + "infix": "cxs-8a1925c96f7b49508855ab270d0f3281" + } + ] + } +} \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-02.json b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-02.json new file mode 100644 index 0000000000000000000000000000000000000000..cb677c39c2b3e0b1fd69f9c4b0e37b6bfebbef73 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-02.json @@ -0,0 +1,32 @@ +{ + "aliases": [ + ".production", + "patent-uspto" + ], + "created": "2022-10-09T20:57:06.860+00:00", + "description": "Patents from the US Patent and Trade Office (USPTO)", + "source": "https://www.uspto.gov/", + "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-uspto-data", + "display_name": "Patents from USPTO", + "type": "Document", + "classification": [ + "Public", + "PI" + ], + "version": [ + { + "name": "docling-core", + "version": "1.0.1" + }, + { + "name": "deepsearch-cxs", + "version": "1.0.0-alpha0.valid" + } + ], + "license": "https://www.uspto.gov/terms-use-uspto-websites", + "domain": [ + "Science", + "Technology" + ], + "$ref": "ccs:schemas#/Document" +} \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-03.json b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-03.json new file mode 100644 index 0000000000000000000000000000000000000000..d5af9147083b1b0569475efbae1d1977fb0e3e28 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-03.json @@ -0,0 +1,29 @@ +{ + "aliases": [ + ".production", + "osm" + ], + "created": "2022-10-09T20:57:06.860+00:00", + "description": "OpenStreetMap dsata", + "source": "https://www.openstreetmap.org", + "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-osm-data", + "display_name": "OpenStreetMap", + "type": "Document", + "classification": [ + "Public" + ], + "version": [ + { + "name": "docling-core", + "version": "1.0.1" + }, + { + "name": "deepsearch-cxs", + "version": "1.0.0-alpha0.valid" + } + ], + "license": "https://www.openstreetmap.org/copyright", + "domain": [ + "Geography" + ] +} diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-04.json b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-04.json new file mode 100644 index 0000000000000000000000000000000000000000..c618240663890bd8c58e0bd3b2711b2cd8b3b5b5 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-04.json @@ -0,0 +1,17 @@ +{ + "license": "", + "index_key": "07a32fab8e3cf827a1d6691fd530941485282dd7", + "created": "2023-11-28T15:10:08.226942+00:00", + "project_key": "9cd28d76ca3d0cc853edb23976f32b44f5739839", + "description": "", + "source": "", + "display_name": "", + "type": "Document", + "version": [ + { + "name": "docling-core", + "version": "1.4.0" + } + ], + "$ref": "ccs:schemas#/Document" +} \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched.dt_viz_p2.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched.dt_viz_p2.png new file mode 100644 index 0000000000000000000000000000000000000000..726fddac7d0d7a98cc5ef492559181a7b0c50a59 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched.dt_viz_p2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:103d27d70cc2b52b891a709097a9c1777131cf648d61968be1f3c69d70bc36e7 +size 532591 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5.png new file mode 100644 index 0000000000000000000000000000000000000000..720890fbb8957b88abe508d844c74d2262cd7696 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60863252174f1a327a15c14c28b890ab5c6be14becfcc3f6a64ab69b8d5ebf93 +size 581738 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5_rows_and_cols.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5_rows_and_cols.png new file mode 100644 index 0000000000000000000000000000000000000000..0507f90ec201593d27a30c10b67336034c4cdab6 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5_rows_and_cols.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50e076c2e9a82fde20fd8d53ada2ef64ec7214a89aa21ad7d609d92f951d8c23 +size 581500 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p1.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p1.png new file mode 100644 index 0000000000000000000000000000000000000000..89d40a062b0452350c2f8c30af66e55c3d63682d --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6c47693821bb54ec1924d437bbcc6895d2943b18ad41ea93027b08cced41e2b +size 420851 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p2.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p2.png new file mode 100644 index 0000000000000000000000000000000000000000..4bb99ae2baf4c14e9078c4a6fcfc6d27a3145e1b --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fee077e0f0ec722a5450d580777a5dbe733dc7f83e352184f7a0de7a3cee18f3 +size 531713 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p3.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p3.png new file mode 100644 index 0000000000000000000000000000000000000000..bfd27170696aa31318f3f5877ef3a9a4ac2f5d53 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bef96e1282bc1d964ca31d23fcf40bdb92ace63f0b55ab4c24bfee20d8b359bf +size 503963 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p1.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p1.png new file mode 100644 index 0000000000000000000000000000000000000000..f0c992e0728b76d5eadd8c9cd599dd35d6d9e617 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f09738ce29cb6cc0bce4b998fb1aaa15da1d84e2209f5358769125b485abb6f2 +size 412485 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p2.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p2.png new file mode 100644 index 0000000000000000000000000000000000000000..89c5da68d80b5abef6a43ca4b31a5417e2c7f727 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f6c02e7638eaf644c7c4f4a9cd0bbda1b62d21eb5bd8d10d2dcc10d8e66a6c2 +size 519696 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p3.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p3.png new file mode 100644 index 0000000000000000000000000000000000000000..07d89224de7ced3493b90205d0b8e392cbe82151 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e264067d8d7d7472a26600ae40aed8d7e726fc6ef135e91719206e3ad59825a9 +size 493371 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p1.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p1.png new file mode 100644 index 0000000000000000000000000000000000000000..ea701b618c933b879139cb3ec1fcbe9d9b2da5f8 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d65b2c1bda7c14a58ee1b67c04aa697267694ab9fdf515e25c0269b8028ff13 +size 288860 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p2.png b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p2.png new file mode 100644 index 0000000000000000000000000000000000000000..cf7cb4b4cd0bf29145a98c1ffd5fab3be1ab2c15 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dd83855b42c1b6fd82cea824c41cf66bcdfd4f8f3a3cffded96c0dd65dc90c2 +size 363749 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_01.vtt b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_01.vtt new file mode 100644 index 0000000000000000000000000000000000000000..333ca4a86a9f296d0c96813bfe6207067eb35878 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_01.vtt @@ -0,0 +1,42 @@ +WEBVTT + +NOTE Copyright © 2019 World Wide Web Consortium. https://www.w3.org/TR/webvtt1/ + +00:11.000 --> 00:13.000 +We are in New York City + +00:13.000 --> 00:16.000 +We’re actually at the Lucern Hotel, just down the street + +00:16.000 --> 00:18.000 +from the American Museum of Natural History + +00:18.000 --> 00:20.000 +And with me is Neil deGrasse Tyson + +00:20.000 --> 00:22.000 +Astrophysicist, Director of the Hayden Planetarium + +00:22.000 --> 00:24.000 +at the AMNH. + +00:24.000 --> 00:26.000 +Thank you for walking down here. + +00:27.000 --> 00:30.000 +And I want to do a follow-up on the last conversation we did. + +00:30.000 --> 00:31.500 align:right size:50% +When we e-mailed— + +00:30.500 --> 00:32.500 align:left size:50% +Didn’t we talk about enough in that conversation? + +00:32.000 --> 00:35.500 align:right size:50% +No! No no no no; 'cos 'cos obviously 'cos + +00:32.500 --> 00:33.500 align:left size:50% +Laughs + +00:35.500 --> 00:38.000 +You know I’m so excited my glasses are falling off here. diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_02.vtt b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_02.vtt new file mode 100644 index 0000000000000000000000000000000000000000..1152a1e8fa00d49361f94730d6b12f9bef7c99dc --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_02.vtt @@ -0,0 +1,15 @@ +WEBVTT + +NOTE Copyright © 2019 World Wide Web Consortium. https://www.w3.org/TR/webvtt1/ + +00:00.000 --> 00:02.000 +It’s a blue apple tree! + +00:02.000 --> 00:04.000 +No way! + +00:04.000 --> 00:06.000 +Hee! laughter + +00:06.000 --> 00:08.000 +That’s awesome! \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_03.vtt b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_03.vtt new file mode 100644 index 0000000000000000000000000000000000000000..a4dc1291f37569c371ad9d7b1eaf31583e0da0b5 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_03.vtt @@ -0,0 +1,57 @@ +WEBVTT + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/15-0 +00:00:04.963 --> 00:00:08.571 +OK, +I think now we should be recording + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/15-1 +00:00:08.571 --> 00:00:09.403 +properly. + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/16-0 +00:00:10.683 --> 00:00:11.563 +Good. + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/17-0 +00:00:13.363 --> 00:00:13.803 +Yeah. + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/78-0 +00:00:49.603 --> 00:00:53.363 +I was also thinking. + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/113-0 +00:00:54.963 --> 00:01:02.072 +Would be maybe good to create items, + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/113-1 +00:01:02.072 --> 00:01:06.811 +some metadata, +some options that can be specific. + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/150-0 +00:01:10.243 --> 00:01:13.014 +Yeah, +I mean I think you went even more than + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/119-0 +00:01:10.563 --> 00:01:12.643 +But we preserved the atoms. + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/150-1 +00:01:13.014 --> 00:01:15.907 +than me. +I just opened the format. + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/197-1 +00:01:50.222 --> 00:01:51.643 +give it a try, yeah. + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/200-0 +00:01:52.043 --> 00:01:55.043 +Okay, talk to you later. + +62357a1d-d250-41d5-a1cf-6cc0eeceffcc/202-0 +00:01:54.603 --> 00:01:55.283 +See you. \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_04.vtt b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_04.vtt new file mode 100644 index 0000000000000000000000000000000000000000..86809a213ba050ad084222519c9f6ae90850b862 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_04.vtt @@ -0,0 +1,36 @@ +WEBVTT Danger of Nitrogen + +NOTE Copyright © 2019 World Wide Web Consortium. https://www.w3.org/TR/webvtt1/ + +STYLE +::cue { + background-image: linear-gradient(to bottom, dimgray, lightgray); + color: papayawhip; +} +/* Style blocks cannot use blank lines nor "dash dash greater than" */ + +REGION +id:editor-comments +width: 40% +regionanchor:0%,100% +viewportanchor:10%,90% + +REGION +id:scroll +width: 40% +regionanchor:100%,100% +viewportanchor:90%,90% +scroll:up + +00:01.000 --> 00:04.000 +Never drink liquid nitrogen. + +NOTE I’m not sure the timing is right on the following cue. + +00:05.000 --> 00:09.000 +— It will perforate your stomach. +— You could die. +This is true. + +00:10.000 --> 00:14.000 +the<00:10.389> quick<00:10.750> brown<00:11.110> fox \ No newline at end of file diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/doclang_validation.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/doclang_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..10810660b5d6cc020d6f4a46225c987512127d3d --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/doclang_validation.py @@ -0,0 +1,103 @@ +"""Helpers for validating DocLang XML against the reference doclang package.""" + +from __future__ import annotations + +import os +import tempfile +from pathlib import Path +from typing import Union + +import pytest + +try: + from doclang import ValidationError + from doclang import validate as doclang_validate +except ImportError: + doclang_validate = None # type: ignore[assignment,misc] + ValidationError = Exception # type: ignore[misc,assignment] + + +def doclang_validator_available() -> bool: + """Return True when the reference ``doclang`` package is importable.""" + return doclang_validate is not None + + +doclang_validator = pytest.mark.skipif( + not doclang_validator_available(), + reason="reference doclang package not installed (uv sync --extra doclang-validation)", +) + +xfail_invalid_dclg_xml = pytest.mark.xfail( + reason="Serializer output fails DocLang reference validation (known bug)", + raises=ValidationError, + strict=False, +) + + +def assert_valid_dclg_xml( + xml_text: str, + *, + allow_empty_namespace: bool = True, +) -> None: + """Validate DocLang XML; no-op when the reference validator is not installed.""" + if doclang_validate is None: + return + with tempfile.NamedTemporaryFile( + mode="w", + suffix=".dclg.xml", + delete=False, + encoding="utf-8", + ) as tmp: + tmp.write(xml_text) + path = tmp.name + try: + doclang_validate(path, allow_empty_namespace=allow_empty_namespace) + finally: + os.unlink(path) + + +def validate_dclg_xml( + xml_text: str, + *, + allow_empty_namespace: bool = True, +) -> None: + """Validate DocLang XML text; raises on failure when validator is available.""" + if doclang_validate is None: + pytest.skip("reference doclang package not installed") + + with tempfile.NamedTemporaryFile( + mode="w", + suffix=".dclg.xml", + delete=False, + encoding="utf-8", + ) as tmp: + tmp.write(xml_text) + path = tmp.name + + try: + doclang_validate(path, allow_empty_namespace=allow_empty_namespace) + finally: + os.unlink(path) + + +def validate_dclg_file( + path: str | Path, + *, + allow_empty_namespace: bool = True, +) -> None: + """Validate a DocLang XML file path.""" + if doclang_validate is None: + pytest.skip("reference doclang package not installed") + doclang_validate(Path(path), allow_empty_namespace=allow_empty_namespace) + + +def assert_invalid_dclg_xml( + xml_text: str, + *, + allow_empty_namespace: bool = True, +) -> None: + """Assert DocLang XML is rejected by the reference validator (known bad output).""" + if doclang_validate is None: + pytest.skip("reference doclang package not installed") + with pytest.raises(ValidationError): + validate_dclg_xml(xml_text, allow_empty_namespace=allow_empty_namespace) diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/tasksmith_behavior.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/tasksmith_behavior.py new file mode 100644 index 0000000000000000000000000000000000000000..61fa7b15515a09f46de96001735a83191d6e1e22 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/tasksmith_behavior.py @@ -0,0 +1,69 @@ +import pytest +from docling_core.types.doc.items.table.table_data import TableData, TableCell + + +def _make_table(num_rows: int = 4, num_cols: int = 2) -> TableData: + cells = [ + TableCell( + text=f"r{i}c{j}", + start_row_offset_idx=i, + end_row_offset_idx=i + 1, + start_col_offset_idx=j, + end_col_offset_idx=j + 1, + ) + for i in range(num_rows) + for j in range(num_cols) + ] + return TableData(num_rows=num_rows, num_cols=num_cols, table_cells=cells) + + +def test_remove_rows_empty_list_is_noop(): + data = _make_table() + result = data.remove_rows([]) + assert result == [] + assert data.num_rows == 4 + assert [c.text for row in data.grid for c in row] == [ + "r0c0", "r0c1", "r1c0", "r1c1", "r2c0", "r2c1", "r3c0", "r3c1" + ] + + +def test_remove_rows_out_of_bounds_raises(): + data = _make_table() + with pytest.raises(IndexError): + data.remove_rows([10]) + + +def test_remove_rows_negative_index_raises(): + data = _make_table() + with pytest.raises(IndexError): + data.remove_rows([-1]) + + +def test_remove_rows_distinct_indices(): + data = _make_table() + removed = data.remove_rows([0, 2]) + assert data.num_rows == 2 + remaining = [c.text for row in data.grid for c in row] + assert remaining == ["r1c0", "r1c1", "r3c0", "r3c1"] + # Two distinct rows were removed + all_removed_texts = [c.text for row in removed for c in row] + assert set(all_removed_texts) == {"r0c0", "r0c1", "r2c0", "r2c1"} + + +def test_remove_rows_duplicate_indices_removes_once(): + data = _make_table() + removed = data.remove_rows([1, 1]) + # Only one row removed + assert [[c.text for c in row] for row in removed] == [["r1c0", "r1c1"]] + assert data.num_rows == 3 + assert [c.text for row in data.grid for c in row] == [ + "r0c0", "r0c1", "r2c0", "r2c1", "r3c0", "r3c1" + ] + + +def test_remove_rows_many_duplicates(): + data = _make_table() + removed = data.remove_rows([2, 2, 2]) + assert len(removed) == 1 + assert [c.text for c in removed[0]] == ["r2c0", "r2c1"] + assert data.num_rows == 3 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_azure_serializer.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_azure_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..47a6a87673085ad84623e23f502127a91c46887f --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_azure_serializer.py @@ -0,0 +1,148 @@ +"""Tests for AzureDocSerializer.""" + +import json +from pathlib import Path +from typing import Any + +from docling_core.transforms.serializer.azure import AzureDocSerializer, AzureParams +from docling_core.types.doc.base import BoundingBox, CoordOrigin, Size +from docling_core.types.doc.document import ( + DocItemLabel, + DoclingDocument, + ProvenanceItem, +) + +from .test_data_gen_flag import GEN_TEST_DATA + + +def _assert_json_like_equal(a: Any, b: Any, eps: float = 1e-3, path: str = "$") -> None: + """Recursively assert two JSON-like structures are equal with float tolerance. + + Rules: + - Dicts: same keys; compare values recursively + - Lists: same length; compare elements in order + - Numbers: ints compare by ==; floats (or int-vs-float) compare within eps + - Strings/bools/null: compare by == + + The `path` argument is used to provide helpful assertion locations. + """ + # Handle dicts + if isinstance(a, dict) and isinstance(b, dict): + a_keys, b_keys = set(a.keys()), set(b.keys()) + assert a_keys == b_keys, f"Key mismatch at {path}: {a_keys ^ b_keys}" + for k in sorted(a_keys): + _assert_json_like_equal(a[k], b[k], eps=eps, path=f"{path}.{k}") + return + + # Handle lists + if isinstance(a, list) and isinstance(b, list): + assert len(a) == len(b), f"List length mismatch at {path}: {len(a)} != {len(b)}" + for i, (ai, bi) in enumerate(zip(a, b)): + _assert_json_like_equal(ai, bi, eps=eps, path=f"{path}[{i}]") + return + + # Handle numbers (int/float) + num_types = (int, float) + if isinstance(a, num_types) and isinstance(b, num_types): + # If either is float, compare with tolerance; if both int, exact match + if isinstance(a, float) or isinstance(b, float): + diff = abs(float(a) - float(b)) + assert diff <= eps, f"Float mismatch at {path}: {a} != {b} (diff={diff}, eps={eps})" + else: + assert a == b, f"Int mismatch at {path}: {a} != {b}" + return + + # Handle strings, bools, and None + if isinstance(a, (str, bool)) or a is None: + assert a == b, f"Value mismatch at {path}: {a!r} != {b!r}" + return + + # Fallback: types must match and then equality + assert type(a) is type(b), f"Type mismatch at {path}: {type(a)} != {type(b)}" + assert a == b, f"Mismatch at {path}: {a!r} != {b!r}" + + +def _verify_json(exp_file: Path, actual_json: str) -> None: + """Verify Azure JSON string against ground-truth file with generation support. + + Compares parsed JSON structures and tolerates tiny float differences. + """ + if GEN_TEST_DATA: + # Keep writing the canonical serialized string for determinism + exp_file.write_text(actual_json + "\n", encoding="utf-8") + else: + expected_text = exp_file.read_text(encoding="utf-8").rstrip() + expected_obj = json.loads(expected_text) + actual_obj = json.loads(actual_json) + _assert_json_like_equal(expected_obj, actual_obj, eps=1e-3) + + +def test_azure_serialize_activities_doc(): + """Serialize a GT document (activities.json) and verify Azure JSON output.""" + src = Path("./tests/data/doc/activities.json") + doc = DoclingDocument.load_from_json(src) + + ser = AzureDocSerializer(doc=doc, params=AzureParams(indent=2)) + actual_json = ser.serialize().text + + # Sanity-check the JSON structure + data = json.loads(actual_json) + assert isinstance(data, dict) + assert "pages" in data and isinstance(data["pages"], list) + assert "tables" in data and isinstance(data["tables"], list) + assert "figures" in data and isinstance(data["figures"], list) + assert "paragraphs" in data and isinstance(data["paragraphs"], list) + + _verify_json(exp_file=src.with_suffix(".gt.azure.json"), actual_json=actual_json) + + +def test_azure_serialize_construct_doc_minimal_prov(sample_doc: DoclingDocument): + """Serialize a constructed document with minimal provenance to Azure JSON. + + The sample_doc fixture does not attach provenance or pages; here we add a + single page and minimal bounding boxes to a subset of items to allow Azure JSON + output to include paragraphs/tables/pictures with boundingRegions. + """ + # Ensure at least one page is present + if not sample_doc.pages: + sample_doc.add_page(page_no=1, size=Size(width=600.0, height=800.0), image=None) + + # Helper to add a simple TOPLEFT bbox provenance if missing + def _ensure_prov(item, l=10.0, t=10.0, r=200.0, b=40.0): + if not item.prov: + item.prov = [ + ProvenanceItem( + page_no=min(sample_doc.pages.keys()), + bbox=BoundingBox(l=l, t=t, r=r, b=b, coord_origin=CoordOrigin.TOPLEFT), + charspan=(0, 0), + ) + ] + + # Add provenance for the title and a couple of paragraphs if present + for it in sample_doc.texts[:3]: + if it.label in { + DocItemLabel.TITLE, + DocItemLabel.TEXT, + DocItemLabel.SECTION_HEADER, + }: + _ensure_prov(it) + + # Add provenance for the first table if present + if sample_doc.tables: + _ensure_prov(sample_doc.tables[0], l=20.0, t=80.0, r=300.0, b=200.0) + + # Add provenance for the first picture if present + if sample_doc.pictures: + _ensure_prov(sample_doc.pictures[0], l=320.0, t=80.0, r=500.0, b=220.0) + + ser = AzureDocSerializer(doc=sample_doc, params=AzureParams(indent=2)) + actual_json = ser.serialize().text + + # Basic structure check + data = json.loads(actual_json) + assert isinstance(data, dict) + assert "pages" in data and isinstance(data["pages"], list) and len(data["pages"]) >= 1 + assert "paragraphs" in data and isinstance(data["paragraphs"], list) + + exp_file = Path("./tests/data/doc/constructed.gt.azure.json") + _verify_json(exp_file=exp_file, actual_json=actual_json) diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_base.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..716f6f2cd5dd4cb35f8ffb6d2c7299b2fef4b03f --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_base.py @@ -0,0 +1,40 @@ +"""Test the pydantic models in module data_types.base.py.""" + +from datetime import datetime, timezone + +import pytest +from pydantic import BaseModel, ValidationError + +from docling_core.types.base import StrictDateTime + + +def test_strict_date_time() -> None: + """Validate data with StrictDateTime model.""" + + class Model(BaseModel): + published: StrictDateTime + + # allowed formats + Model(published=datetime.now(tz=timezone.utc)) + + data = Model(published="2022-12-01T03:49:20.724435+00:00") + assert data.published.isoformat() == "2022-12-01T03:49:20.724435+00:00" + + data = Model(published="2022-12-01T03:49:20.724435+03:00") + assert data.published.isoformat() == "2022-12-01T03:49:20.724435+03:00" + + data = Model(published="2022-12-01T03:49:20.724435Z") + assert data.published.isoformat() == "2022-12-01T03:49:20.724435+00:00" + + data = Model(published="2022-12-01T03:49:20") + assert data.published.isoformat() == "2022-12-01T03:49:20" + + data = Model(published="2022-12-01") + assert data.published.isoformat() == "2022-12-01T00:00:00" + + # invalid formats + with pytest.raises(ValidationError, match="published"): + Model(published="03:49:20") + + with pytest.raises(ValidationError, match="published"): + Model(published=1679616000.0) diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_chunk_expander.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_chunk_expander.py new file mode 100644 index 0000000000000000000000000000000000000000..afd967c6c0e9495e647a9af1f160a48dac5554d8 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_chunk_expander.py @@ -0,0 +1,366 @@ +"""Tests for chunk expander classes.""" + +import pytest + +from docling_core.transforms.chunker.chunk_expander import PageChunkExpander, TreeChunkExpander +from docling_core.transforms.chunker.doc_chunk import DocChunk, DocMeta +from docling_core.transforms.chunker.hierarchical_chunker import ChunkingDocSerializer, ChunkingSerializerProvider +from docling_core.transforms.chunker.hybrid_chunker import HybridChunker +from docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizer +from docling_core.transforms.serializer.markdown import MarkdownTableSerializer +from docling_core.types.doc import DocItemLabel, DoclingDocument, Size +from docling_core.types.doc.document import TableData + +EMBED_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2" +MAX_TOKENS = 50 + + +def check_lines_equal_in_order(text_a: str, text_b: str) -> bool: + """Check if lines of string A are equal to lines of string B in the same order. + + This function splits both strings into lines and verifies that: + 1. All lines from A appear in B + 2. They appear in the same order + 3. Lines can be non-consecutive in B (other lines can appear between them) + + Args: + text_a: First string (subset) to check + text_b: Second string (superset) to check against + + Returns: + True if all lines of A appear in B in the same order, False otherwise + """ + if not isinstance(text_a, str) or not isinstance(text_b, str): + raise TypeError("Both inputs must be strings.") + + lines_a = [line for line in text_a.splitlines() if line.strip()] + lines_b = [line for line in text_b.splitlines() if line.strip()] + + # If A is empty, it's always contained in B + if not lines_a: + return True + + # If B is empty but A is not, A cannot be contained in B + if not lines_b: + return False + + # Track position in B + b_index = 0 + + # Try to find each line of A in B in order + for line_a in lines_a: + found = False + # Search for line_a starting from current position in B + while b_index < len(lines_b): + if lines_b[b_index] == line_a: + found = True + b_index += 1 # Move to next position in B + break + b_index += 1 + + # If we couldn't find this line of A in B, return False + if not found: + return False + + return True + + +@pytest.fixture +def sample_doc(): + """Create a comprehensive sample document for testing with pages and various content types. + + Content is associated with pages through ProvenanceItem which includes page_no. + When add_text/add_heading is called with prov parameter containing page_no, + that content is associated with that specific page. + """ + from docling_core.types.doc.document import BoundingBox, ProvenanceItem + + doc = DoclingDocument(name="test_doc") + + # Add pages + doc.add_page(size=Size(width=612, height=792), page_no=1) + doc.add_page(size=Size(width=612, height=792), page_no=2) + + # Section 1 on page 1 (explicitly set page_no in prov) + doc.add_heading( + text="Section 1", + level=1, + prov=ProvenanceItem(page_no=1, bbox=BoundingBox(l=50, t=50, r=550, b=80), charspan=(0, 9)), + ) + doc.add_text( + text="This is the first paragraph.", + label=DocItemLabel.PARAGRAPH, + prov=ProvenanceItem(page_no=1, bbox=BoundingBox(l=50, t=90, r=550, b=120), charspan=(10, 38)), + ) + doc.add_text( + text="This is the second paragraph.", + label=DocItemLabel.PARAGRAPH, + prov=ProvenanceItem(page_no=1, bbox=BoundingBox(l=50, t=130, r=550, b=160), charspan=(39, 68)), + ) + + # Section 2 on page 2 with list (explicitly set page_no=2 in prov) + doc.add_heading( + text="Section 2", + level=1, + prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=50, t=50, r=550, b=80), charspan=(69, 78)), + ) + doc.add_text( + text="Content in section 2.", + label=DocItemLabel.PARAGRAPH, + prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=50, t=90, r=550, b=120), charspan=(79, 100)), + ) + + # Add a list in section 2 on page 2 + list_group = doc.add_list_group() + doc.add_list_item( + text="First list item", + enumerated=False, + parent=list_group, + prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=70, t=130, r=550, b=150), charspan=(101, 116)), + ) + doc.add_list_item( + text="Second list item", + enumerated=False, + parent=list_group, + prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=70, t=160, r=550, b=180), charspan=(117, 133)), + ) + doc.add_list_item( + text="Third list item", + enumerated=False, + parent=list_group, + prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=70, t=190, r=550, b=210), charspan=(134, 149)), + ) + + # Add a table on page 2 + table_data = TableData(num_cols=2) + table_data.add_row(["Header 1", "Header 2"]) + table_data.add_row(["Value 1", "Value 2"]) + table_data.add_row(["Value 3", "Value 4"]) + table_data.add_row(["Value 5", "Value 6"]) + doc.add_table( + data=table_data, + prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=50, t=220, r=550, b=300), charspan=(150, 200)), + ) + + return doc + + +class MarkdownSerializerProvider(ChunkingSerializerProvider): + def get_serializer(self, doc: DoclingDocument): + return ChunkingDocSerializer( + doc=doc, + table_serializer=MarkdownTableSerializer(), + ) + + +@pytest.fixture +def hybrid_chunker(): + """Create a reusable HybridChunker instance.""" + return HybridChunker( + tokenizer=HuggingFaceTokenizer.from_pretrained( + model_name=EMBED_MODEL_ID, + max_tokens=MAX_TOKENS, + ), + serializer_provider=MarkdownSerializerProvider(), + repeat_table_header=True, + ) + + +@pytest.fixture +def sample_chunks(sample_doc, hybrid_chunker): + """Create chunks from sample_doc once and cache them.""" + chunks = list(hybrid_chunker.chunk(dl_doc=sample_doc)) + assert len(chunks) > 0, "Expected at least one chunk to be created" + return chunks + + +@pytest.fixture +def sample_serializer(sample_doc, hybrid_chunker): + """Create serializer for sample_doc once and cache it.""" + return hybrid_chunker.serializer_provider.get_serializer(sample_doc) + + +@pytest.fixture +def tree_expander(): + """Create a TreeChunkExpander instance.""" + return TreeChunkExpander() + + +@pytest.fixture +def page_expander(): + """Create a PageChunkExpander instance.""" + return PageChunkExpander() + + +class TestTreeChunkExpander: + """Tests for TreeChunkExpander class methods.""" + + # helper method: recursively traverse top item children to find chunk items + def _find_chunk_item_in_descendants(self, item, doc, target_refs): + """Recursively check if any target_refs are in item's descendants.""" + # Check if this item itself is a target + if item.self_ref in target_refs: + return True + + # Check children if item has them + if hasattr(item, "children") and item.children: + for child_ref in item.children: + child = child_ref.resolve(doc) + if self._find_chunk_item_in_descendants(child, doc, target_refs): + return True + + return False + + def test_get_top_items_basic(self, sample_doc, sample_chunks): + """Test getting top-level items from a chunk.""" + assert len(sample_chunks) > 0, "Should have at least one chunk" + + for chunk in sample_chunks: + if not isinstance(chunk, DocChunk): + continue + + top_items = TreeChunkExpander._get_top_containing_items(chunk.meta, sample_doc) + + assert top_items is not None, "Should return top items" + assert len(top_items) > 0, "Should have at least one top item" + + # Verify all returned items are direct children of body + for item in top_items: + assert item.parent == sample_doc.body.get_ref(), f"Item {item.self_ref} should be direct child of body" + + # Verify that at least one doc_item from the chunk is a descendant of a top item + chunk_item_refs = {item.self_ref for item in chunk.meta.doc_items} + + for top_item in top_items: + assert self._find_chunk_item_in_descendants(top_item, sample_doc, chunk_item_refs), ( + f"Could not find any chunk items in descendants of top item {top_item.self_ref}" + ) + + def test_get_top_items_maintains_order(self, sample_doc, sample_chunks): + """Test that top items maintain document reading order.""" + for chunk in sample_chunks: + if not isinstance(chunk, DocChunk): + continue + + top_items = TreeChunkExpander._get_top_containing_items(chunk.meta, sample_doc) + if top_items and len(top_items) > 1: + # Get the order in the document body + body_refs = [ref.cref for ref in sample_doc.body.children] + top_refs = [item.self_ref for item in top_items] + + # Verify order is maintained + prev_idx = -1 + for ref in top_refs: + curr_idx = body_refs.index(ref) + assert curr_idx > prev_idx, "Items should maintain reading order" + prev_idx = curr_idx + + def test_get_top_items_empty_chunk(self): + """Test _get_top_containing_items with chunk containing non-body items.""" + doc = DoclingDocument(name="empty_doc") + text_item = doc.add_text(text="Some text", label=DocItemLabel.PARAGRAPH) + + # Create a chunk with a doc item that doesn't have proper parent + # This simulates an edge case where get_top_containing_items might return None + meta = DocMeta(doc_items=[text_item]) + + # Should return the text item as top item since it's a direct child of body + result = TreeChunkExpander._get_top_containing_items(meta, doc) + assert result is not None, "Should return top items for valid doc_items" + assert len(result) > 0, "Should have at least one top item" + + def test_expand_basic(self, sample_doc, sample_serializer, sample_chunks, tree_expander): + """Test basic expansion to full items.""" + for chunk in sample_chunks: + if not isinstance(chunk, DocChunk): + continue + + expanded = tree_expander.expand(chunk=chunk, dl_doc=sample_doc, serializer=sample_serializer) + + assert expanded is not None, "Should return expanded chunk" + assert isinstance(expanded, DocChunk), "Should return DocChunk instance" + + # Expanded chunk should have content + assert len(expanded.text.strip()) > 0, "Expanded chunk should have text" + + # Expanded chunk text should contain original chunk text (or be a superset) + assert check_lines_equal_in_order(chunk.text, expanded.text), ( + f"Expanded chunk should contain original chunk text. original: {chunk.text} expanded: {expanded.text}" + ) + assert expanded.meta.origin == chunk.meta.origin, "Origin should be preserved" + + def test_expand_error_handling(self, sample_doc, tree_expander): + """Test error handling in expand when serialization fails.""" + + # Create a mock serializer that raises an exception + class FailingSerializer: + def serialize(self, item): + raise RuntimeError("Serialization failed") + + # Create a chunk with valid doc items + text_item = sample_doc.texts[0] + meta = DocMeta(doc_items=[text_item]) + chunk = DocChunk(text="original text", meta=meta) + + # Call expand with failing serializer + # Should catch the exception and return original chunk + with pytest.warns(UserWarning, match="did not yield any text"): + expanded = tree_expander.expand(chunk=chunk, dl_doc=sample_doc, serializer=FailingSerializer()) + + # Should return original chunk when serialization fails + assert expanded == chunk, "Should return original chunk when serialization fails" + + +class TestPageChunkExpander: + """Tests for PageChunkExpander.expand method.""" + + def test_expand_basic(self, sample_doc, sample_chunks, sample_serializer, page_expander): + """Test that page expansion includes all page content.""" + for chunk in sample_chunks: + if not isinstance(chunk, DocChunk): + continue + + # Get page numbers from chunk + page_ids = [i.page_no for item in chunk.meta.doc_items for i in item.prov] + + if page_ids: + expanded = page_expander.expand(chunk=chunk, dl_doc=sample_doc, serializer=sample_serializer) + assert expanded is not None, "Should return expanded chunk" + assert isinstance(expanded, DocChunk), "Should return DocChunk" + # Expanded text should contain page content + assert len(expanded.text) > 0, "Expanded chunk should have text" + + # Verify it contains original + assert check_lines_equal_in_order(chunk.text, expanded.text), "Expanded text should contain original" + + # Metadata fields should be updated with expanded content + assert expanded.meta.origin == chunk.meta.origin, "Expanded chunk should have metadata" + + def get_ref_items(chunk: DocChunk): + return [item.self_ref for item in chunk.meta.doc_items] + + assert set(get_ref_items(chunk)).issubset(get_ref_items(expanded)), ( + "Expanded chunk should have at least as many doc_items as original" + ) + + def test_expand_no_pages(self, hybrid_chunker, page_expander): + """Test expand when document has no pages for all chunks.""" + # Create a document without pages + doc_no_pages = DoclingDocument(name="no_pages_doc") + doc_no_pages.add_heading(text="Section 1", level=1) + doc_no_pages.add_text(text="Some content.", label=DocItemLabel.PARAGRAPH) + + chunks = list(hybrid_chunker.chunk(dl_doc=doc_no_pages)) + serializer = hybrid_chunker.serializer_provider.get_serializer(doc_no_pages) + + assert len(chunks) > 0, "Should have at least one chunk" + + for chunk in chunks: + if not isinstance(chunk, DocChunk): + continue + + with pytest.warns(UserWarning, match="Cannot expand to page"): + result = page_expander.expand(chunk=chunk, dl_doc=doc_no_pages, serializer=serializer) + + # Should return original chunk when no pages + assert result == chunk, "Should return original chunk when document has no pages" diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_cli_serialize.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_cli_serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..54d300e2b6e4d764a7cd57cc8c951dcd22982c9d --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_cli_serialize.py @@ -0,0 +1,53 @@ +"""Tests for the ``docling-serialize`` CLI.""" + +import zipfile +from pathlib import Path + +from click import unstyle +from typer.testing import CliRunner + +from docling_core.cli.serialize import app +from docling_core.types.doc import DoclingDocument + +DOC_LANG_ARCHIVE_FIXTURE = Path("tests/data/doc/doclang_archive/save/two_pages.json") + + +def test_serialize_json_to_dclx_packages_images(tmp_path: Path) -> None: + """DCLX output packages page rasters and picture assets.""" + output = tmp_path / "nested" / "two_pages.dclx" + + result = CliRunner().invoke( + app, + [str(DOC_LANG_ARCHIVE_FIXTURE), "--to", "dclx", "--output", str(output)], + ) + + assert result.exit_code == 0, result.output + assert output.is_file() + assert f"Wrote {output}" in result.output + + with zipfile.ZipFile(output) as archive: + names = archive.namelist() + assert "document.xml" in names + assert "pages/1.png" in names + assert "pages/2.png" in names + assert any(name.startswith("assets/") for name in names) + + loaded = DoclingDocument.load_from_doclang_archive( + output, + artifacts_dir=tmp_path / "loaded", + ) + assert len(loaded.pages) == 2 + assert loaded.pictures + assert loaded.pictures[0].image is not None + assert loaded.pictures[0].image.pil_image is not None + + +def test_serialize_dclx_requires_output_path() -> None: + """Binary DCLX output is not written to standard output.""" + result = CliRunner().invoke( + app, + [str(DOC_LANG_ARCHIVE_FIXTURE), "--to", "dclx"], + ) + + assert result.exit_code == 2 + assert "--output is required when --to dclx" in unstyle(result.output) diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunker.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunker.py new file mode 100644 index 0000000000000000000000000000000000000000..9dfb461fcf5d95d16483367b48f50e81425a9464 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunker.py @@ -0,0 +1,173 @@ +import glob +import hashlib +import json +import os +import pathlib +import sys +from typing import Optional + +import git +import pytest + +from docling_core.transforms.chunker.code_chunking._utils import _get_file_extensions +from docling_core.transforms.chunker.code_chunking.code_chunk import CodeChunk +from docling_core.transforms.chunker.code_chunking.standard_code_chunking_strategy import ( + StandardCodeChunkingStrategy, +) +from docling_core.transforms.chunker.hierarchical_chunker import HierarchicalChunker +from docling_core.types.doc import DoclingDocument, DocumentOrigin +from docling_core.types.doc.labels import CodeLanguageLabel, DocItemLabel + +from .test_data_gen_flag import GEN_TEST_DATA + + +def _create_hash(string: str) -> str: + """Return a SHA-256 hex digest of the given string.""" + hasher = hashlib.sha256(usedforsecurity=False) + hasher.update(string.encode("utf-8")) + return hasher.hexdigest() + + +def get_latest_commit_id(file_dir: str) -> str: + """Returns the latest commit ID in the given Git repository directory.""" + try: + repo = git.Repo(file_dir, search_parent_directories=True) + return repo.head.commit.hexsha + except Exception: + return "" + + +def create_documents_from_repository( + file_dir: str, + repo_url: str, + language: CodeLanguageLabel, + commit_id: str | None = None, +) -> list[DoclingDocument]: + """Build DoclingDocument objects from a local checkout, one per code file.""" + documents: list[DoclingDocument] = [] + if commit_id is None: + commit_id = get_latest_commit_id(file_dir) + + all_extensions = set() + for lang in [ + CodeLanguageLabel.PYTHON, + CodeLanguageLabel.TYPESCRIPT, + CodeLanguageLabel.JAVASCRIPT, + CodeLanguageLabel.C, + CodeLanguageLabel.JAVA, + ]: + all_extensions.update(_get_file_extensions(lang)) + + all_files = [] + for extension in all_extensions: + all_files.extend(sorted(glob.glob(f"{file_dir}/**/*{extension}", recursive=True))) + + all_files = sorted(set(all_files)) + + for file_path in all_files: + with open(file_path, encoding="utf-8") as f: + file_content = f.read() + + file_relative = os.path.relpath(file_path, start=file_dir).replace("\\", "/") + + origin = DocumentOrigin( + filename=file_relative, + uri=(f"{repo_url}/blob/{commit_id}/{file_relative}" if commit_id else f"{repo_url}/{file_relative}"), + mimetype="text/plain", + binary_hash=_create_hash(file_content), + ) + + doc = DoclingDocument(name=file_relative, origin=origin) + doc.add_code(text=file_content, code_language=language) + documents.append(doc) + + return documents + + +HERE = pathlib.Path(__file__).parent +DATA = HERE / "data" / "chunker_repo" +DATA.mkdir(parents=True, exist_ok=True) + +REPO_SPECS = [ + ( + "Java", + "/tests/data/chunker_repo/repos/acmeair", + "https://github.com/acmeair/acmeair", + lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)), + ), + ( + "TypeScript", + "/tests/data/chunker_repo/repos/outline", + "https://github.com/outline/outline", + lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)), + ), + ( + "JavaScript", + "/tests/data/chunker_repo/repos/jquery", + "https://github.com/jquery/jquery", + lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)), + ), + ( + "Python", + "/tests/data/chunker_repo/repos/docling", + "https://github.com/docling-project/docling", + lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)), + ), + ( + "C", + "/tests/data/chunker_repo/repos/json-c", + "https://github.com/json-c/json-c", + lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)), + ), +] + + +def _dump_or_assert(act_data: dict, out_path: pathlib.Path): + out_path.parent.mkdir(parents=True, exist_ok=True) + if GEN_TEST_DATA: + with out_path.open("w", encoding="utf-8") as f: + json.dump(act_data, fp=f, indent=4) + f.write("\n") + else: + with out_path.open(encoding="utf-8") as f: + exp_data = json.load(fp=f) + assert exp_data == act_data + + +@pytest.mark.parametrize("name,local_path,repo_url,chunker_factory", REPO_SPECS) +def test_function_chunkers_repo(name, local_path, repo_url, chunker_factory): + if name == "Java" and sys.version_info < (3, 10): + pytest.skip("Skipping Java tests on python < 3.10.") + + local_path_full = os.getcwd() + local_path + + if not os.path.isdir(local_path_full): + pytest.skip(f"Missing repo at {local_path_full}; skipping {name} test.") + + docs = create_documents_from_repository( + local_path_full, + repo_url, + language=CodeLanguageLabel(name), + commit_id="abc123def456", + ) + docs = [doc for doc in docs if any(text.label == DocItemLabel.CODE and text.text for text in doc.texts)] + if not docs: + pytest.skip(f"No documents found in {local_path_full} for {name}.") + + sample = docs[:3] + + chunker = chunker_factory() + all_chunks = [] + for doc in sample: + chunks_iter = chunker.chunk(dl_doc=doc) + chs = list(chunks_iter) + + chunks = [CodeChunk.model_validate(n) for n in chs] + all_chunks.extend(chunks) + assert chunks, f"Expected chunks for {doc.name}" + for c in chunks: + assert c.text and isinstance(c.text, str) + + act_data = {"root": [c.export_json_dict() for c in all_chunks]} + out_path = DATA / name / "repo_out_chunks.json" + _dump_or_assert(act_data, out_path) diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunking_strategy.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunking_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..7d4e889e998952de6b5f5b60993542fcc4b5a5e2 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunking_strategy.py @@ -0,0 +1,196 @@ +from pathlib import Path + +import pytest + +from docling_core.transforms.chunker import ( + CodeLanguageLabel, + HierarchicalChunker, + HybridChunker, + StandardCodeChunkingStrategy, +) +from docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizer +from docling_core.transforms.serializer.markdown import ( + MarkdownDocSerializer, + MarkdownParams, +) +from docling_core.types.doc.base import Size +from docling_core.types.doc.document import DoclingDocument, DocumentOrigin +from docling_core.types.doc.labels import DocItemLabel + + +@pytest.fixture +def test_data_dir(): + """Path to test data directory.""" + return Path(__file__).parent / "data" / "repo_chunking" + + +def test_code_chunking_strategies(): + """Test different code chunking strategies.""" + python_code = ''' +def fibonacci(n): + """Calculate the nth Fibonacci number.""" + if n <= 1: + return n + return fibonacci(n-1) + fibonacci(n-2) + +def factorial(n): + """Calculate factorial of n.""" + if n <= 1: + return 1 + return n * factorial(n-1) +''' + + doc = DoclingDocument(name="test") + code_item = doc.add_code(text=python_code, code_language=CodeLanguageLabel.PYTHON) + strategy = StandardCodeChunkingStrategy(min_chunk_size=10, max_tokens=100) + doc_ser = MarkdownDocSerializer( + doc=doc, + params=MarkdownParams( + format_code_blocks=False, + ), + ) + chunks = list(strategy.chunk_code_item(item=code_item, doc=doc, doc_serializer=doc_ser)) + + assert len(chunks) > 0 + for chunk in chunks: + assert hasattr(chunk, "text") + assert hasattr(chunk, "meta") + assert hasattr(chunk.meta, "chunk_type") + + +def test_hierarchical_chunker_integration(): + """Test HierarchicalChunker with and without code chunking strategy.""" + python_code = ''' +def fibonacci(n): + """Calculate the nth Fibonacci number.""" + if n <= 1: + return n + return fibonacci(n-1) + fibonacci(n-2) +''' + + doc = DoclingDocument(name="test") + doc.add_page(page_no=0, size=Size(width=612.0, height=792.0)) + doc.add_text( + label=DocItemLabel.TEXT, + text="Here's some Python code:", + orig="Here's some Python code:", + ) + doc.add_code(text=python_code, code_language=CodeLanguageLabel.PYTHON, orig=python_code) + doc.origin = DocumentOrigin(filename="test.py", mimetype="text/x-python", binary_hash=12345) + + strategy = StandardCodeChunkingStrategy(min_chunk_size=50, max_tokens=1000) + chunker_with_strategy = HierarchicalChunker(code_chunking_strategy=strategy) + chunks_with_strategy = list(chunker_with_strategy.chunk(doc)) + + assert len(chunks_with_strategy) > 0 + for chunk in chunks_with_strategy: + assert hasattr(chunk, "text") + assert hasattr(chunk, "meta") + + chunker_without_strategy = HierarchicalChunker() + chunks_without_strategy = list(chunker_without_strategy.chunk(doc)) + + assert len(chunks_without_strategy) > 0 + for chunk in chunks_without_strategy: + assert hasattr(chunk, "text") + assert hasattr(chunk, "meta") + + +def test_hybrid_chunker_with_code_files(test_data_dir): + """Test that HybridChunker can process code files.""" + tokenizer = HuggingFaceTokenizer.from_pretrained( + model_name="sentence-transformers/all-MiniLM-L6-v2", max_tokens=512 + ) + chunker = HybridChunker(tokenizer=tokenizer, merge_peers=True) + + python_file = test_data_dir / "sample.py" + if not python_file.exists(): + pytest.skip("Python test file not found") + + doc = DoclingDocument(name="sample.py") + doc.origin = DocumentOrigin(filename="sample.py", mimetype="text/x-python", binary_hash=12345) + + with open(python_file, encoding="utf-8") as f: + content = f.read() + doc.add_code(text=content) + + chunks = list(chunker.chunk(dl_doc=doc)) + + assert len(chunks) > 0 + for chunk in chunks: + assert hasattr(chunk, "text") + assert hasattr(chunk, "meta") + assert len(chunk.text) > 0 + + +def test_unsupported_language_fallback(test_data_dir): + """Test that unsupported languages fall back to regular text chunking.""" + tokenizer = HuggingFaceTokenizer.from_pretrained( + model_name="sentence-transformers/all-MiniLM-L6-v2", max_tokens=512 + ) + chunker = HybridChunker(tokenizer=tokenizer, merge_peers=True) + + go_file = test_data_dir / "sample.go" + if go_file.exists(): + doc = DoclingDocument(name="sample.go") + doc.origin = DocumentOrigin(filename="sample.go", mimetype="text/plain", binary_hash=12345) + + with open(go_file, encoding="utf-8") as f: + content = f.read() + doc.add_code(text=content) + + assert len(doc.texts) == 1 + assert doc.texts[0].code_language == CodeLanguageLabel.UNKNOWN + + chunks = list(chunker.chunk(dl_doc=doc)) + assert len(chunks) > 0 + + all_text = " ".join(chunk.text for chunk in chunks) + assert "package main" in all_text + assert "func fibonacci" in all_text + + md_file = test_data_dir / "sample.md" + if md_file.exists(): + doc = DoclingDocument(name="sample.md") + doc.origin = DocumentOrigin(filename="sample.md", mimetype="text/plain", binary_hash=12345) + + with open(md_file, encoding="utf-8") as f: + content = f.read() + doc.add_code(text=content) + + assert len(doc.texts) == 1 + assert doc.texts[0].code_language == CodeLanguageLabel.UNKNOWN + + chunks = list(chunker.chunk(dl_doc=doc)) + assert len(chunks) > 0 + + all_text = " ".join(chunk.text for chunk in chunks) + assert "Sample Markdown File" in all_text + assert "def hello()" in all_text + + +def test_repository_processing(test_data_dir): + """Test processing multiple files from a repository.""" + tokenizer = HuggingFaceTokenizer.from_pretrained( + model_name="sentence-transformers/all-MiniLM-L6-v2", max_tokens=512 + ) + chunker = HybridChunker(tokenizer=tokenizer, merge_peers=True) + + all_chunks = [] + for file_path in test_data_dir.glob("sample.*"): + doc = DoclingDocument(name=file_path.name) + doc.origin = DocumentOrigin(filename=file_path.name, mimetype="text/plain", binary_hash=12345) + + with open(file_path, encoding="utf-8") as f: + content = f.read() + doc.add_code(text=content) + + chunks = list(chunker.chunk(dl_doc=doc)) + all_chunks.extend(chunks) + + assert len(all_chunks) > 0 + + for chunk in all_chunks: + assert hasattr(chunk, "text") + assert hasattr(chunk, "meta") + assert len(chunk.text) > 0 diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_compat.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..070064594caa667067b290bac78be32e56e123c7 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_compat.py @@ -0,0 +1,658 @@ +"""Tests for docling_core.compat — server-side downgrade projectors. + +Test strategy +------------- +1. **Coverage enforcement** — assert that a projector is registered for every + minor-version step within the docling-core v2.x schema range + (1.FIRST_SUPPORTED_MINOR through 1.CURRENT_MINOR). + This is the primary CI gate: it will fail as soon as a schema bump lands + without a companion projector. + +2. **Unit tests per projector** — each registered projector is exercised with + a minimal synthetic dict that exercises the fields introduced in that minor + version. + +3. **Schema-snapshot validation** — every projector's output is validated + against the JSON Schema snapshot for the *target* version stored in + ``docs/schemas/DoclingDocument_1_{N}.json``. This is the correct oracle: + it describes exactly what the old client's Pydantic model accepted, without + requiring the old library to be installed. + +4. **Chain projection** — verify that ``project_to()`` can project from 1.10 + all the way down to 1.5 (the oldest supported v2.x schema) in a single + call, chaining all intermediate projectors. + +5. **No-op projection** — projecting to the *same* version (or newer) returns + the same document unchanged. + +6. **Error paths** — missing projector, incompatible major, bad version string, + and target below the v2.x baseline (1.5.0). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import jsonschema +import pytest + +from docling_core.compat import _projectors, list_projectors, project_to +from docling_core.types.doc.common.constants import ( + _CURRENT_MINOR, + CURRENT_VERSION, + FIRST_SUPPORTED_MINOR, + SCHEMA_VERSION_HISTORY, +) +from docling_core.types.doc.document import DoclingDocument + +# Root of the repository, used to locate docs/schemas/. +_REPO_ROOT = Path(__file__).parent.parent +_SCHEMAS_DIR = _REPO_ROOT / "docs" / "schemas" + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _minimal_doc_dict(version: str = CURRENT_VERSION) -> dict: + """Return the smallest possible valid DoclingDocument serialised dict.""" + return { + "schema_name": "DoclingDocument", + "version": version, + "name": "test_doc", + "origin": None, + "furniture": { + "self_ref": "#/furniture", + "parent": None, + "children": [], + "content_layer": "furniture", + "label": "unspecified", + "name": "_root_", + }, + "body": { + "self_ref": "#/body", + "parent": None, + "children": [], + "content_layer": "body", + "label": "unspecified", + "name": "_root_", + }, + "groups": [], + "texts": [], + "pictures": [], + "tables": [], + "key_value_items": [], + "form_items": [], + "pages": {}, + } + + +def _build_doc(version: str = CURRENT_VERSION) -> DoclingDocument: + """Build a minimal DoclingDocument at *version* by bypassing the validator.""" + doc = DoclingDocument.model_construct(**DoclingDocument.model_validate(_minimal_doc_dict()).model_dump()) + # Override the version to simulate a document at a different schema level. + object.__setattr__(doc, "version", version) + return doc + + +# --------------------------------------------------------------------------- +# 1. Coverage enforcement +# --------------------------------------------------------------------------- + + +class TestProjectorCoverage: + """Ensure a projector exists for every v2.x schema minor-version step.""" + + def test_projector_count_matches_expected(self): + """There must be exactly CURRENT_MINOR - FIRST_SUPPORTED_MINOR projectors. + + With CURRENT_MINOR=10 and FIRST_SUPPORTED_MINOR=5 that is 5 projectors: + 1.10->1.9, 1.9->1.8, 1.8->1.7, 1.7->1.6, 1.6->1.5 + + This test is the CI enforcement gate: it will fail automatically + when a contributor bumps CURRENT_VERSION without adding a projector. + """ + expected = _CURRENT_MINOR - FIRST_SUPPORTED_MINOR + actual = len(_projectors) + assert actual == expected, ( + f"Expected {expected} projector(s) (one per minor-version step from " + f"1.{_CURRENT_MINOR} down to 1.{FIRST_SUPPORTED_MINOR}), but found {actual}. " + f"Did you bump CURRENT_VERSION without adding a " + f"@register_projector to docling_core/compat.py?" + ) + + def test_all_expected_steps_registered(self): + """Every step (N->N-1) for N in [FIRST_SUPPORTED_MINOR+1, CURRENT_MINOR] must be registered.""" + missing = [] + for n in range(FIRST_SUPPORTED_MINOR + 1, _CURRENT_MINOR + 1): + if (n, n - 1) not in _projectors: + missing.append(f"1.{n} -> 1.{n - 1}") + assert not missing, f"Missing projectors for: {missing}" + + def test_schema_version_history_length(self): + """SCHEMA_VERSION_HISTORY must have one entry per v2.x minor version.""" + expected = _CURRENT_MINOR - FIRST_SUPPORTED_MINOR + 1 + assert len(SCHEMA_VERSION_HISTORY) == expected, ( + f"SCHEMA_VERSION_HISTORY has {len(SCHEMA_VERSION_HISTORY)} entries; " + f"expected {expected} (one per schema version " + f"1.{FIRST_SUPPORTED_MINOR}..1.{_CURRENT_MINOR}). " + f"Did you forget to append an entry when bumping CURRENT_VERSION?" + ) + + def test_schema_version_history_is_sorted(self): + """Entries must be ordered from 1.0.0 up to CURRENT_VERSION.""" + versions = [e["schema"] for e in SCHEMA_VERSION_HISTORY] + assert versions[-1] == CURRENT_VERSION, ( + f"Last entry in SCHEMA_VERSION_HISTORY is {versions[-1]!r}, expected {CURRENT_VERSION!r}." + ) + + def test_list_projectors_returns_sorted_keys(self): + keys = list_projectors() + assert keys == sorted(keys) + + def test_projector_keys_are_sequential(self): + """Every registered key must satisfy key[0] == key[1] + 1.""" + for key in _projectors: + assert key[0] == key[1] + 1, f"Projector key {key} is not a single-step downgrade." + + @pytest.mark.parametrize("from_minor,to_minor", list(_projectors)) + def test_every_projector_produces_valid_output(self, from_minor: int, to_minor: int): + """Every projector's output must validate against the target version's JSON Schema snapshot. + + The snapshot at ``docs/schemas/DoclingDocument_1_{to_minor}.json`` is the + correct oracle: it describes exactly what the *target* version's Pydantic + model accepted, derived from ``DoclingDocument.model_json_schema()`` at + the moment that version was current. This avoids two failure modes of + using the *current* SDK's ``model_validate()``: + + - **False failure:** a future schema change removes a field; the current + model rejects the projected dict even though it is exactly right for + the old client. + - **False pass:** the current model is a superset and silently accepts + things the old model would have rejected. + + If the snapshot file is missing, the test fails with a clear message + directing the contributor to run ``scripts/check_compat_projectors.py`` + which auto-generates any missing snapshot from the live models. + """ + snapshot_path = _SCHEMAS_DIR / f"DoclingDocument_1_{to_minor}.json" + assert snapshot_path.exists(), ( + f"JSON Schema snapshot for schema 1.{to_minor} not found at {snapshot_path}.\n" + f"Run `python scripts/check_compat_projectors.py` to generate it." + ) + target_schema = json.loads(snapshot_path.read_text()) + + fn = _projectors[(from_minor, to_minor)] + # Build a minimal dict at the *source* version and apply the projector. + data = _minimal_doc_dict(f"1.{from_minor}.0") + try: + result = fn(data) + except Exception as exc: + raise AssertionError( + f"Projector 1.{from_minor}->1.{to_minor} raised an exception on a minimal input dict: {exc}" + ) from exc + + # The result must claim the target version. + assert result.get("version") == f"1.{to_minor}.0", ( + f"Projector 1.{from_minor}->1.{to_minor} did not set version to " + f"'1.{to_minor}.0' (got {result.get('version')!r})." + ) + + # Validate the projected dict against the target version's JSON Schema. + # jsonschema.validate raises jsonschema.ValidationError on any violation. + try: + jsonschema.validate(instance=result, schema=target_schema) + except jsonschema.ValidationError as exc: + raise AssertionError( + f"Projector 1.{from_minor}->1.{to_minor} produced a dict that " + f"fails validation against docs/schemas/DoclingDocument_1_{to_minor}.json:\n" + f" {exc.message}\n" + f" Path: {list(exc.absolute_path)}" + ) from exc + + def test_every_projector_has_a_test_class(self): + """Every registered projector must have a corresponding test class + named ``TestProjector_1_{from_minor}_to_1_{to_minor}`` in this module. + + This enforces step 6 of the contributor checklist (write a test for + the new projector). It does not prevent vacuous tests, but it does + force a contributor to explicitly author a class — making the gap + visible in code review. + + If you added a projector but not a test class, add a class with at + least one non-trivial test before merging. + """ + import sys + + this_module = sys.modules[__name__] + missing = [] + for from_minor, to_minor in _projectors: + class_name = f"TestProjector_1_{from_minor}_to_1_{to_minor}" + if not hasattr(this_module, class_name): + missing.append(f"{class_name} (projector 1.{from_minor}->1.{to_minor})") + assert not missing, ( + "The following projectors are missing a test class in test/test_compat.py:\n" + + "\n".join(f" • {m}" for m in missing) + + "\nAdd a test class for each projector as described in CONTRIBUTING.md." + ) + + +# --------------------------------------------------------------------------- +# 2. Unit tests per projector +# --------------------------------------------------------------------------- + + +class TestSchemaSnapshotRendering: + """The snapshot written for the current version must come from the models. + + Copying ``docs/DoclingDocument.json`` instead would snapshot whatever + schema that artefact last held -- which, in the pre-commit hook order, is + the *previous* version -- producing a file named for the new version but + describing the old one. + """ + + @staticmethod + def _render() -> str: + """Call ``_render_model_schema`` from the check script. + + ``scripts/`` is not an importable package, so load the file directly + rather than mutating ``sys.path``. + """ + import importlib.util + + path = Path(__file__).parent.parent / "scripts" / "check_compat_projectors.py" + spec = importlib.util.spec_from_file_location("_check_compat_projectors", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return str(module._render_model_schema()) + + def test_renderer_cannot_drift_from_the_docs_generator(self): + """The check script and generate_docs must emit identical bytes.""" + from docling_core.utils.generate_jsonschema import generate_json_schema + + # Exactly what generate_docs writes for DoclingDocument. + expected = json.dumps(generate_json_schema("DoclingDocument"), ensure_ascii=False, indent=2) + assert self._render() == expected + + def test_rendered_schema_describes_the_current_models(self): + """The renderer reports the live model, not a cached artefact.""" + from docling_core.types.doc.items.form import FieldItem + + schema = json.loads(self._render()) + assert set(schema["$defs"]["FieldItem"]["properties"]) == set(FieldItem.model_fields) + + +class TestProjector_1_10_to_1_9: + """Tests for the 1.10 → 1.9 downgrade projector.""" + + def _apply(self, data: dict) -> dict: + from docling_core.compat import _project_1_10_to_1_9 + + return _project_1_10_to_1_9(data) + + def test_strips_field_regions_and_field_items(self): + data = {**_minimal_doc_dict("1.10.0"), "field_regions": [{"some": "item"}], "field_items": [{"other": "item"}]} + result = self._apply(data) + assert "field_regions" not in result + assert "field_items" not in result + + def test_version_set_to_1_9(self): + result = self._apply(_minimal_doc_dict("1.10.0")) + assert result["version"] == "1.9.0" + + def test_converts_field_heading_to_text(self): + data = _minimal_doc_dict("1.10.0") + data["texts"] = [ + { + "self_ref": "#/texts/0", + "parent": None, + "children": [], + "content_layer": "body", + "label": "field_heading", + "orig": "Name", + "text": "Name", + "level": 1, + "prov": [], + } + ] + result = self._apply(data) + assert result["texts"][0]["label"] == "text" + + def test_drops_field_region_item_without_text(self): + """Items with field labels but no text payload must be dropped.""" + data = _minimal_doc_dict("1.10.0") + data["texts"] = [ + { + "self_ref": "#/texts/0", + "parent": None, + "children": [], + "content_layer": "body", + "label": "field_region", + "prov": [], + } + ] + result = self._apply(data) + assert result["texts"] == [] + + def test_strips_new_meta_keys(self): + data = _minimal_doc_dict("1.10.0") + data["texts"] = [ + { + "self_ref": "#/texts/0", + "parent": None, + "children": [], + "content_layer": "body", + "label": "text", + "orig": "hello", + "text": "hello", + "prov": [], + "meta": { + "language": {"predicted": "en"}, + "entities": [], + "keywords": [], + "topics": [], + }, + } + ] + result = self._apply(data) + assert result["texts"][0]["meta"] == {} + + def test_strips_orientation_from_table_data(self): + data = _minimal_doc_dict("1.10.0") + data["tables"] = [ + { + "self_ref": "#/tables/0", + "parent": None, + "children": [], + "content_layer": "body", + "label": "table", + "prov": [], + "data": { + "table_cells": [], + "num_rows": 0, + "num_cols": 0, + "orientation": "ROT_90", + }, + } + ] + result = self._apply(data) + assert "orientation" not in result["tables"][0]["data"] + + def test_remaps_unknown_code_language(self): + data = _minimal_doc_dict("1.10.0") + data["texts"] = [ + { + "self_ref": "#/texts/0", + "parent": None, + "children": [], + "content_layer": "body", + "label": "code", + "orig": "x=1", + "text": "x=1", + "prov": [], + "code_language": "doclang", + } + ] + result = self._apply(data) + assert result["texts"][0]["code_language"] == "unknown" + + +class TestProjector_1_9_to_1_8: + """Tests for the 1.9 → 1.8 downgrade projector.""" + + def _apply(self, data: dict) -> dict: + from docling_core.compat import _project_1_9_to_1_8 + + return _project_1_9_to_1_8(data) + + def test_version_set(self): + result = self._apply(_minimal_doc_dict("1.9.0")) + assert result["version"] == "1.8.0" + + def test_strips_comments_and_source(self): + data = _minimal_doc_dict("1.9.0") + data["texts"] = [ + { + "self_ref": "#/texts/0", + "parent": None, + "children": [], + "content_layer": "body", + "label": "text", + "orig": "hi", + "text": "hi", + "prov": [], + "comments": [{"$ref": "#/texts/1"}], + "source": [{"kind": "track", "ref": "#/texts/0"}], + } + ] + result = self._apply(data) + assert "comments" not in result["texts"][0] + assert "source" not in result["texts"][0] + + +class TestProjector_1_8_to_1_7: + """Tests for the 1.8 → 1.7 downgrade projector.""" + + def _apply(self, data: dict) -> dict: + from docling_core.compat import _project_1_8_to_1_7 + + return _project_1_8_to_1_7(data) + + def test_version_set(self): + result = self._apply(_minimal_doc_dict("1.8.0")) + assert result["version"] == "1.7.0" + + def test_strips_meta(self): + data = _minimal_doc_dict("1.8.0") + data["texts"] = [ + { + "self_ref": "#/texts/0", + "parent": None, + "children": [], + "content_layer": "body", + "label": "text", + "orig": "hi", + "text": "hi", + "prov": [], + "meta": {"some_prediction": {"confidence": 0.9}}, + } + ] + result = self._apply(data) + assert "meta" not in result["texts"][0] + + +class TestProjector_1_7_to_1_6: + """Tests for the 1.7 → 1.6 downgrade projector.""" + + def _apply(self, data: dict) -> dict: + from docling_core.compat import _project_1_7_to_1_6 + + return _project_1_7_to_1_6(data) + + def test_version_set(self): + result = self._apply(_minimal_doc_dict("1.7.0")) + assert result["version"] == "1.6.0" + + def test_strips_fillable_from_table_cells(self): + data = _minimal_doc_dict("1.7.0") + data["tables"] = [ + { + "self_ref": "#/tables/0", + "parent": None, + "children": [], + "content_layer": "body", + "label": "table", + "prov": [], + "data": { + "table_cells": [ + { + "row_span": 1, + "col_span": 1, + "start_row_offset_idx": 0, + "end_row_offset_idx": 1, + "start_col_offset_idx": 0, + "end_col_offset_idx": 1, + "text": "A", + "column_header": False, + "row_header": False, + "row_section": False, + "fillable": True, + }, + ], + "num_rows": 1, + "num_cols": 1, + }, + } + ] + result = self._apply(data) + cell = result["tables"][0]["data"]["table_cells"][0] + assert "fillable" not in cell + assert cell["text"] == "A" + + +class TestProjector_1_6_to_1_5: + """Tests for the 1.6 → 1.5 downgrade projector.""" + + def _apply(self, data: dict) -> dict: + from docling_core.compat import _project_1_6_to_1_5 + + return _project_1_6_to_1_5(data) + + def test_version_set(self): + result = self._apply(_minimal_doc_dict("1.6.0")) + assert result["version"] == "1.5.0" + + def test_strips_ref_from_rich_table_cell(self): + data = _minimal_doc_dict("1.6.0") + data["tables"] = [ + { + "self_ref": "#/tables/0", + "parent": None, + "children": [], + "content_layer": "body", + "label": "table", + "prov": [], + "data": { + "table_cells": [ + { + "row_span": 1, + "col_span": 1, + "start_row_offset_idx": 0, + "end_row_offset_idx": 1, + "start_col_offset_idx": 0, + "end_col_offset_idx": 1, + "text": "A", + "column_header": False, + "row_header": False, + "row_section": False, + "ref": "#/texts/0", + }, + ], + "num_rows": 1, + "num_cols": 1, + }, + } + ] + result = self._apply(data) + cell = result["tables"][0]["data"]["table_cells"][0] + assert "ref" not in cell + assert cell["text"] == "A" + + +# --------------------------------------------------------------------------- +# 3. Chain projection test +# --------------------------------------------------------------------------- + + +class TestChainProjection: + """Verify that project_to() correctly chains multiple projectors.""" + + def test_chain_1_10_to_1_5(self): + """project_to should apply 5 projectors in sequence (1.10->1.5).""" + doc = DoclingDocument(name="chain_test") + result = project_to(doc, target_version="1.5.0") + assert result.version == "1.5.0" + + def test_chain_1_10_to_1_9(self): + doc = DoclingDocument(name="chain_test") + result = project_to(doc, target_version="1.9.0") + assert result.version == "1.9.0" + + def test_chain_with_field_items(self): + """A document with field-related items projects cleanly to 1.9.""" + doc = DoclingDocument(name="field_doc") + # Add a FieldValueItem (new in 1.10). + from docling_core.types.doc.items.form import FieldValueItem + + item = FieldValueItem( + self_ref="#/texts/0", + orig="John", + text="John", + ) + doc.texts.append(item) # type: ignore[arg-type] + result = project_to(doc, target_version="1.9.0") + assert result.version == "1.9.0" + # The field_value item should have been converted to a generic text item. + assert all(t.label.value in ("text", "paragraph", "caption") or True for t in result.texts) + + +# --------------------------------------------------------------------------- +# 4. No-op projection +# --------------------------------------------------------------------------- + + +class TestNoOpProjection: + """Projecting to the same or newer version should be a no-op.""" + + def test_same_version_returns_same_doc(self): + doc = DoclingDocument(name="noop_test") + result = project_to(doc, target_version=CURRENT_VERSION) + # Same object returned when no projection needed. + assert result is doc + + def test_newer_target_returns_same_doc(self): + """If somehow target is newer than doc, return doc unchanged.""" + doc = DoclingDocument(name="noop_test") + # Patch version to 1.9.0 to simulate an "older" doc. + object.__setattr__(doc, "version", "1.9.0") + result = project_to(doc, target_version="1.10.0") + assert result is doc + + +# --------------------------------------------------------------------------- +# 5. Error paths +# --------------------------------------------------------------------------- + + +class TestErrorPaths: + """Verify error conditions are reported clearly.""" + + def test_incompatible_major_raises(self): + doc = DoclingDocument(name="err_test") + with pytest.raises(ValueError, match="major versions"): + project_to(doc, target_version="2.0.0") + + def test_bad_target_version_raises(self): + doc = DoclingDocument(name="err_test") + with pytest.raises(ValueError, match="Cannot parse target version"): + project_to(doc, target_version="not-a-version") + + def test_target_below_v2x_baseline_raises(self): + """Requesting a target in the v1.x schema range raises ValueError.""" + doc = DoclingDocument(name="err_test") + with pytest.raises(ValueError, match="oldest supported schema version"): + project_to(doc, target_version="1.4.0") + + def test_missing_projector_raises(self): + """If a projector is de-registered, project_to raises RuntimeError.""" + doc = DoclingDocument(name="err_test") + # Temporarily remove the 1.6->1.5 projector to test the error path. + removed = _projectors.pop((6, 5), None) + try: + with pytest.raises(RuntimeError, match="No projector registered"): + project_to(doc, target_version="1.5.0") + finally: + if removed is not None: + _projectors[(6, 5)] = removed diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_gen_flag.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_gen_flag.py new file mode 100644 index 0000000000000000000000000000000000000000..a4baff66ab5dbffa9d7a2839c5716886af99420e --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_gen_flag.py @@ -0,0 +1,9 @@ +import os + +from pydantic import TypeAdapter + +GEN_TEST_DATA = TypeAdapter(bool).validate_python(os.getenv("DOCLING_GEN_TEST_DATA", 0)) + + +def test_gen_test_data_flag(): + assert not GEN_TEST_DATA diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_lint.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_lint.py new file mode 100644 index 0000000000000000000000000000000000000000..d672dcc8aea5a96cb3707e0639f3ef0840244fbc --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_lint.py @@ -0,0 +1,332 @@ +"""Tests of the private data lint in ``scripts/`` (``_data_lint.py``).""" + +import sys +from pathlib import Path + +import pytest + +from docling_core.types.doc import DocItemLabel, DoclingDocument + +_SCRIPTS = Path(__file__).parent.parent / "scripts" + + +@pytest.fixture(scope="module") +def checks(): + sys.path.insert(0, str(_SCRIPTS)) + import _data_lint # type: ignore[import-not-found] + + return _data_lint + + +def _status(results): + return {r.check: r.status for r in results} + + +def test_check_json_flags_empty_list_wrapper(checks, tmp_path): + doc = DoclingDocument(name="") + lst = doc.add_list_group() + doc.add_list_item(text="a", marker="1.", parent=lst) + wrapper = doc.add_list_item(text="", marker="", parent=lst) + sub = doc.add_list_group(parent=wrapper) + doc.add_list_item(text="b", marker="a.", parent=sub) + path = tmp_path / "doc.json" + doc.save_as_json(path) + + status = _status(checks.check_json(path)) + assert status["json.load"] == "ok" + assert status["json.rules"] == "ok" + assert status["json.empty-list-wrapper"] == "warn" + + +def test_check_pair_roundtrip(checks, tmp_path): + doc = DoclingDocument(name="") + doc.add_text(label=DocItemLabel.TEXT, text="hello") + json_path, dclx_path = tmp_path / "doc.json", tmp_path / "doc.dclx" + doc.save_as_json(json_path) + doc.save_as_doclang_archive(dclx_path) + + status = _status(checks.check_pair(json_path, dclx_path)) + assert status["dclx/deserialize"] == "ok" + assert status["dclx/roundtrip"] == "ok" + assert status["pair.json-to-dclx"] == "ok" + assert status["pair.dclx-to-json"] == "ok" + assert "fail" not in status.values() + + +def test_check_dclx_reports_a_failing_roundtrip(checks, tmp_path): + # a field region in the furniture layer loses its layer on deserialization (known gap) + from docling_core.types.doc.document import ContentLayer + + doc = DoclingDocument(name="") + region = doc.add_field_region() + region.content_layer = ContentLayer.FURNITURE + item = doc.add_field_item(parent=region) + item.content_layer = ContentLayer.FURNITURE + doc.add_field_key(text="k", parent=item, content_layer=ContentLayer.FURNITURE) + doc.add_field_value(text="v", parent=item, content_layer=ContentLayer.FURNITURE) + path = tmp_path / "doc.dclx" + doc.save_as_doclang_archive(path) + + status = _status(checks.check_dclx(path)) + assert status["dclx.deserialize"] == "ok" + assert status["dclx.roundtrip"] == "fail" + + # the pair check sees the same loss from the JSON side: the layers differ after DCLX -> JSON + doc.save_as_json(tmp_path / "doc.json") + pair = {r.check: r for r in checks.check_pair(tmp_path / "doc.json", path)} + assert pair["pair.json-to-dclx"].status == "ok" + assert pair["pair.dclx-to-json"].status == "warn" # a diagnostic, not a failure + assert any("field_region [furniture]" in line for line in pair["pair.dclx-to-json"].details) + + +def test_cli_by_extension_and_check_pair(checks, tmp_path, capsys): + doc = DoclingDocument(name="") + doc.add_text(label=DocItemLabel.TEXT, text="hello") + doc.save_as_json(tmp_path / "doc.json") + doc.save_as_doclang_archive(tmp_path / "doc.dclx") + + assert checks.main([str(tmp_path / "doc.json")]) == 0 + assert checks.main([str(tmp_path / "doc.dclx"), "--pair", "-q"]) == 0 + assert "RESULT: OK" in capsys.readouterr().out + checks.main([str(tmp_path / "doc.json"), "--pair"]) + assert "pair.json-to-dclx" in capsys.readouterr().out + + (tmp_path / "doc.json").rename(tmp_path / "other.json") + with pytest.raises(SystemExit, match="counterpart not found"): + checks.main([str(tmp_path / "doc.dclx"), "--pair"]) + with pytest.raises(SystemExit, match="unsupported extension"): + checks.main([str(tmp_path / "x.txt")]) + + +def test_cli_result_line_reports_warnings(checks, tmp_path, capsys): + doc = DoclingDocument(name="") + lst = doc.add_list_group() + doc.add_list_item(text="a", marker="1.", parent=lst) + wrapper = doc.add_list_item(text="", marker="", parent=lst) + doc.add_list_item(text="b", marker="a.", parent=doc.add_list_group(parent=wrapper)) + doc.save_as_json(tmp_path / "doc.json") + + assert checks.main([str(tmp_path / "doc.json")]) == 0 # warnings do not change the exit code + assert "RESULT: WARN (1 warning(s))" in capsys.readouterr().out + + +def test_selection_and_list_checks(checks, tmp_path, capsys): + sel = checks.Selection(only=["dclx"], skip=["dclx.schematron"]) + assert sel.on("dclx.roundtrip") and sel.on("dclx.xsd") + assert not sel.on("dclx.schematron") and not sel.on("json.load") and not sel.on("pair.json-to-dclx") + assert checks.Selection(only=["json.empty-list-wrapper"]).on("json.empty-list-wrapper") + assert not checks.Selection(only=["json.empty-list-wrapper"]).on("json.load") + assert checks.Selection(only=["json"]).on("json.empty-list-wrapper") # a group prefix selects its checks + with pytest.raises(SystemExit, match=r"--only dclx\.roundtrip selects nothing"): + checks.Selection(only=["dclx.roundtrip"], skip=["dclx"]) + with pytest.raises(SystemExit, match="--only json selects nothing"): + checks.Selection(only=["json"], skip=["json"]) + with pytest.raises(SystemExit, match="unknown check: nope"): + checks.Selection(only=["nope"]) + + assert checks.main(["--list-checks"]) == 0 + out = capsys.readouterr().out + assert all(slug in out for slug in checks.CHECKS) + + doc = DoclingDocument(name="") + doc.add_text(label=DocItemLabel.TEXT, text="hello") + doc.save_as_json(tmp_path / "doc.json") + doc.save_as_doclang_archive(tmp_path / "doc.dclx") + capsys.readouterr() + checks.main([str(tmp_path / "doc.dclx"), "--pair", "--only", "dclx.roundtrip,pair"]) + printed = [line.split()[1] for line in capsys.readouterr().out.splitlines() if line[:2] in ("OK", "FA")] + assert printed == ["dclx/roundtrip", "pair.json-to-dclx", "pair.dclx-to-json"] + + +def test_diff_normalizes_indentation_but_not_content_whitespace(checks): + # indentation and blank lines outside do not matter ... + assert checks._diff("\n a\n", "\na\n\n") == [] + # ... but preserves whitespace, so any difference inside it is reported + assert checks._diff(" a\nb", "a\nb") + assert checks._diff("a\n b", "a\nb") + assert checks._diff("a\nb ", "a\nb") + assert checks._diff("a\nb", "a\nb") == [] + + +def test_pair_accepts_dclg_markup(checks, tmp_path, capsys): + doc = DoclingDocument(name="") + doc.add_text(label=DocItemLabel.TEXT, text="hello") + doc.save_as_json(tmp_path / "doc.json") + xml = checks.serialize(doc, (512, 512)) + (tmp_path / "doc.dclg").write_text(xml) + + assert checks.main([str(tmp_path / "doc.dclg"), "--pair", "-q"]) == 0 + assert checks.main([str(tmp_path / "doc.json"), "--pair", "-q"]) == 0 # found via .dclg + (tmp_path / "doc.dclg").rename(tmp_path / "doc.dclg.xml") + assert checks.main([str(tmp_path / "doc.dclg.xml"), "--pair", "-q"]) == 0 # X.dclg.xml -> X.json + capsys.readouterr() + (tmp_path / "doc.dclg.xml").rename(tmp_path / "gone.xml") + with pytest.raises(SystemExit, match="counterpart not found"): + checks.main([str(tmp_path / "doc.json"), "--pair"]) + + +# ---- failure paths ------------------------------------------------------------------------------------------------- +def _simple_doc(text: str = "hello") -> DoclingDocument: + doc = DoclingDocument(name="") + doc.add_text(label=DocItemLabel.TEXT, text=text) + return doc + + +def test_json_load_failure(checks, tmp_path): + (tmp_path / "bad.json").write_text('{"schema_name": "DoclingDocument", "texts": "not a list"}') + results = checks.check_json(tmp_path / "bad.json") + assert [(r.check, r.status) for r in results] == [("json.load", "fail")] + + (tmp_path / "broken.json").write_text("{not json") + assert [(r.check, r.status) for r in checks.check_json(tmp_path / "broken.json")] == [("json.load", "fail")] + + +def test_json_rules_failure_on_legacy_key_value_item(checks, tmp_path): + from docling_core.types.doc.document import GraphData + + doc = _simple_doc() + doc.add_key_values(graph=GraphData(cells=[], links=[])) + doc.save_as_json(tmp_path / "doc.json") + + status = {r.check: r for r in checks.check_json(tmp_path / "doc.json")} + assert status["json.rules"].status == "fail" + assert any("is to be migrated to a field region" in line for line in status["json.rules"].details) + + +def test_json_serialize_failure(checks, tmp_path, monkeypatch): + _simple_doc().save_as_json(tmp_path / "doc.json") + + def boom(doc, resolution): + raise RuntimeError("cannot serialize") + + monkeypatch.setattr(checks, "serialize", boom) + status = { + r.check: r for r in checks.check_json(tmp_path / "doc.json", sel=checks.Selection(only=["json.serialize"])) + } + assert status["json.serialize"].status == "fail" + assert "cannot serialize" in status["json.serialize"].message + + +def test_dclx_xsd_failure(checks, tmp_path): + (tmp_path / "bad.xml").write_text('') + status = {r.check: r for r in checks.check_dclx(tmp_path / "bad.xml", sel=checks.Selection(only=["dclx.xsd"]))} + assert status["dclx.xsd"].status == "fail" + assert status["dclx.xsd"].details + + +def test_dclx_schematron_fails_without_the_backend(checks, tmp_path, monkeypatch): + import doclang.validation + + _simple_doc().save_as_doclang_archive(tmp_path / "doc.dclx") + real = doclang.validation.validate + + def validate(path, **kwargs): + if kwargs.get("schematron_only"): + raise ImportError("no saxon") + return real(path, **kwargs) + + monkeypatch.setattr(doclang.validation, "validate", validate) + status = {r.check: r for r in checks.check_dclx(tmp_path / "doc.dclx", sel=checks.Selection(only=["dclx"]))} + assert status["dclx.schematron"].status == "fail" + assert "--skip dclx.schematron" in status["dclx.schematron"].message + assert status["dclx.xsd"].status == "ok" + + # skipping it explicitly runs without it + skipped = { + r.check: r.status + for r in checks.check_dclx(tmp_path / "doc.dclx", sel=checks.Selection(skip=["dclx.schematron"])) + } + assert "dclx.schematron" not in skipped and "fail" not in skipped.values() + + +def test_dclx_deserialize_failure(checks, tmp_path): + (tmp_path / "broken.xml").write_text("") + status = {r.check: r.status for r in checks.check_dclx(tmp_path / "broken.xml")} + assert status["dclx.deserialize"] == "fail" + assert "dclx.roundtrip" not in status # nothing to round trip + + +def test_dclx_rules_failure_when_the_deserialized_document_fails_model_validation(checks, tmp_path, monkeypatch): + # the deserializer builds documents through the API, so the lint re-validates the result through the model + _simple_doc().save_as_doclang_archive(tmp_path / "doc.dclx") + + def invalid(*args, **kwargs): + raise ValueError("not a valid document") + + monkeypatch.setattr(checks.DoclingDocument, "model_validate", invalid) + status = {r.check: r for r in checks.check_dclx(tmp_path / "doc.dclx")} + assert status["dclx.rules"].status == "fail" + assert any("not a valid document" in line for line in status["dclx.rules"].details) + + +def test_pair_json_to_dclx_failure_when_the_files_do_not_match(checks, tmp_path): + _simple_doc("one").save_as_json(tmp_path / "doc.json") + _simple_doc("two").save_as_doclang_archive(tmp_path / "doc.dclx") + + status = {r.check: r for r in checks.check_pair(tmp_path / "doc.json", tmp_path / "doc.dclx")} + assert status["pair.json-to-dclx"].status == "fail" + assert status["pair.dclx-to-json"].status == "warn" + assert status["dclx/roundtrip"].status == "ok" # each side is fine on its own + + +def test_cli_output_json_and_quiet(checks, tmp_path, capsys): + import json + + _simple_doc("one").save_as_json(tmp_path / "doc.json") + _simple_doc("two").save_as_doclang_archive(tmp_path / "doc.dclx") + + assert checks.main([str(tmp_path / "doc.json"), "--pair", "--output", "json"]) == 1 + data = json.loads(capsys.readouterr().out) + (label,) = data + by_check = {r["check"]: r for r in data[label]} + assert by_check["pair.json-to-dclx"]["status"] == "fail" and by_check["pair.json-to-dclx"]["details"] + + assert checks.main([str(tmp_path / "doc.json"), "--pair", "-q"]) == 1 + out = capsys.readouterr().out + assert "FAIL pair.json-to-dclx" in out and "OK " not in out and "WARN" not in out + assert out.rstrip().endswith("RESULT: FAILED") + + +def test_json_load_failure_on_model_validation_error(checks, tmp_path): + import json + + doc = _simple_doc() + doc.add_text(label=DocItemLabel.TEXT, text="again") + data = doc.model_dump(mode="json") + data["texts"][1]["self_ref"] = data["texts"][0]["self_ref"] # a duplicate ref is rejected by the model + (tmp_path / "doc.json").write_text(json.dumps(data)) + + results = checks.check_json(tmp_path / "doc.json") + assert [(r.check, r.status) for r in results] == [("json.load", "fail")] + assert "Duplicate ref" in results[0].message + + +def test_cli_report_modes(checks, tmp_path, capsys): + import json + + from docling_core.types.doc.document import ContentLayer + + _simple_doc().save_as_json(tmp_path / "good.json") + _simple_doc().save_as_doclang_archive(tmp_path / "good.dclx") + bad = DoclingDocument(name="") + region = bad.add_field_region() + region.content_layer = ContentLayer.FURNITURE # lost on deserialization: the round trip fails + bad.save_as_json(tmp_path / "bad.json") + bad.save_as_doclang_archive(tmp_path / "bad.dclx") + files = [str(tmp_path / "good.dclx"), str(tmp_path / "bad.dclx")] + + assert checks.main([*files, "--pair", "--report", "checks", "--only", "dclx.roundtrip"]) == 1 + out = capsys.readouterr().out + assert "PER CHECK (2 file(s))" in out + row = next(line for line in out.splitlines() if line.startswith("dclx.roundtrip")) + assert row.split()[1:] == ["1", "0", "1"] # ok, warn, fail + assert "bad.dclx" not in out # the files are only listed on request + + checks.main([*files, "--pair", "--report", "checks-with-files", "--only", "dclx.roundtrip"]) + out = capsys.readouterr().out + assert "FAIL dclx.roundtrip (1):" in out and "bad.json + bad.dclx" in out and "good.dclx" not in out + + checks.main([*files, "--pair", "--report", "checks-with-files", "--only", "dclx.roundtrip", "--output", "json"]) + data = json.loads(capsys.readouterr().out) + assert data["files"] == 2 and data["checks"]["dclx.roundtrip"] == {"ok": 1, "fail": 1} + assert data["flagged"]["dclx.roundtrip"] == [{"status": "fail", "file": "bad.json + bad.dclx"}] diff --git a/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_deserializer_doclang.py b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_deserializer_doclang.py new file mode 100644 index 0000000000000000000000000000000000000000..311e9118e28cfb2fd45d29c98ce2ab72dc1f1481 --- /dev/null +++ b/tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_deserializer_doclang.py @@ -0,0 +1,2884 @@ +import re +import xml.etree.ElementTree as ET +from collections.abc import Callable +from pathlib import Path + +import pytest + +from docling_core.transforms.deserializer.doclang import DocLangDocDeserializer +from docling_core.transforms.serializer.doclang import ( + DocLangDocSerializer, + DocLangParams, + EscapeMode, + LabelMode, +) +from docling_core.transforms.serializer.doctags import DocTagsDocSerializer +from docling_core.transforms.serializer.html import HTMLDocSerializer +from docling_core.transforms.serializer.latex import LaTeXDocSerializer +from docling_core.transforms.serializer.markdown import MarkdownDocSerializer +from docling_core.transforms.serializer.plain_text import PlainTextDocSerializer +from docling_core.types.doc import ( + BoundingBox, + ContentLayer, + CoordOrigin, + DescriptionMetaField, + DocItemLabel, + DoclingDocument, + Formatting, + ImageRefMode, + MoleculeMetaField, + PictureClassificationMetaField, + PictureClassificationPrediction, + PictureItem, + PictureMeta, + ProvenanceItem, + RichTableCell, + Script, + Size, + SummaryMetaField, + TableCell, + TableData, + TableItem, + TabularChartMetaField, + TextItem, +) +from docling_core.types.doc.document import GroupLabel +from docling_core.types.doc.labels import CodeLanguageLabel, PictureClassificationLabel +from tests.doclang_validation import assert_valid_dclg_xml, doclang_validator +from tests.test_data_gen_flag import GEN_TEST_DATA +from tests.test_serialization_doclang import ( + _doc_cross_column_list, + _doc_cross_page_list, + _doc_cross_page_paragraph, + _doc_cross_page_table, + _doc_multi_prov_text, + _verify_doc, + add_list_section, + add_texts_section, + verify_doclang, +) +from tests.test_serialization_doctag import verify + +DO_PRINT: bool = False + + +def _serialize(doc: DoclingDocument) -> str: + ser = DocLangDocSerializer( + doc=doc, + params=DocLangParams(include_version=False), + ) + text = ser.serialize().text + if not GEN_TEST_DATA: + assert_valid_dclg_xml(text) + return text + + +def _deserialize(text: str, *, validate: bool = True) -> DoclingDocument: + if validate and not GEN_TEST_DATA: + assert_valid_dclg_xml(text) + return DocLangDocDeserializer().deserialize_str(text) + + +def _add_default_page(doc: DoclingDocument): + doc.add_page(page_no=0, size=Size(width=1000, height=1000)) + + +def _default_prov() -> ProvenanceItem: + return ProvenanceItem( + page_no=0, + bbox=BoundingBox(l=100, t=100, r=300, b=200), + charspan=(0, 0), + ) + + +class _VirtualTextMixedBboxFactory: + """Assign distinct page bboxes for the virtual-text mixed fixture.""" + + def __init__(self, *, page_no: int = 0, page_w: float = 1000, page_h: float = 1000) -> None: + self.page_no = page_no + self.page_w = page_w + self.page_h = page_h + self._slot = 0 + + def next_prov(self) -> ProvenanceItem: + row, col = divmod(self._slot, 4) + self._slot += 1 + cell_w = self.page_w / 5 + cell_h = self.page_h / 20 + left = 20 + col * cell_w + top = self.page_h - 40 - row * cell_h + return ProvenanceItem( + page_no=self.page_no, + bbox=BoundingBox.from_tuple( + (left, top - cell_h, left + cell_w - 10, top), + origin=CoordOrigin.BOTTOMLEFT, + ), + charspan=(0, 0), + ) + + def next_bbox(self) -> BoundingBox: + return self.next_prov().bbox + + +def _serialize_virtual_text_mixed(doc: DoclingDocument, *, add_location: bool = True) -> str: + ser = DocLangDocSerializer( + doc=doc, + params=DocLangParams(include_version=False, add_table_cell_location=True, add_location=add_location), + ) + text = ser.serialize().text + if not GEN_TEST_DATA: + assert_valid_dclg_xml(text) + return text + + +def test_roundtrip_text(): + doc = DoclingDocument(name="t") + doc.add_text(label=DocItemLabel.TEXT, text="Hello world") + dt = _serialize(doc) + doc2 = _deserialize(dt) + dt2 = _serialize(doc2) + + exp_dt = """ + + Hello world + + """ + assert dt2.strip() == exp_dt.strip() + + +def test_deserialize_include_namespace_and_version(): + """Deserialize DocLang XML with namespace and version, then roundtrip.""" + exp_file = Path("./tests/data/doc/deserialize_include_namespace_and_version.gt.dclg.xml") + xml = exp_file.read_text(encoding="utf-8") + + doc = _deserialize(xml) + assert len(doc.texts) == 1 + assert doc.texts[0].text == "Hello world" + + reserialized = ( + DocLangDocSerializer( + doc=doc, + params=DocLangParams(include_namespace=True, include_version=True), + ) + .serialize() + .text + ) + verify_doclang(exp_file=exp_file, actual=reserialized) + + +def test_roundtrip_title(): + doc = DoclingDocument(name="t") + doc.add_title(text="My Title") + dt = _serialize(doc) + doc2 = _deserialize(dt) + dt2 = _serialize(doc2) + + exp_dt = """ + + My Title + + """ + assert dt2.strip() == exp_dt.strip() + + +def test_roundtrip_heading(): + doc = DoclingDocument(name="t") + doc.add_heading(text="Section A", level=2) + dt = _serialize(doc) + doc2 = _deserialize(dt) + dt2 = _serialize(doc2) + + exp_dt = """ + + Section A + + """ + assert dt2.strip() == exp_dt.strip() + + +def test_roundtrip_caption(): + doc = DoclingDocument(name="t") + doc.add_text(label=DocItemLabel.CAPTION, text="Cap text") + dt = _serialize(doc) + doc2 = _deserialize(dt) + dt2 = _serialize(doc2) + + exp_dt = """ + + Cap text + + """ + assert dt2.strip() == exp_dt.strip() + + +def test_roundtrip_footnote(): + doc = DoclingDocument(name="t") + doc.add_text(label=DocItemLabel.FOOTNOTE, text="Foot note") + dt = _serialize(doc) + if DO_PRINT: + print("\n", dt) + doc2 = _deserialize(dt) + assert len(doc2.texts) == 1 + assert doc2.texts[0].label == DocItemLabel.FOOTNOTE + assert doc2.texts[0].text == "Foot note" + + +def test_roundtrip_page_header(): + doc = DoclingDocument(name="t") + doc.add_text(label=DocItemLabel.PAGE_HEADER, text="Header") + dt = _serialize(doc) + if DO_PRINT: + print("\n", dt) + doc2 = _deserialize(dt) + assert len(doc2.texts) == 1 + assert doc2.texts[0].label == DocItemLabel.PAGE_HEADER + assert doc2.texts[0].text == "Header" + + +def test_roundtrip_page_footer(): + doc = DoclingDocument(name="t") + doc.add_text(label=DocItemLabel.PAGE_FOOTER, text="Footer") + dt = _serialize(doc) + if DO_PRINT: + print("\n", dt) + doc2 = _deserialize(dt) + assert len(doc2.texts) == 1 + assert doc2.texts[0].label == DocItemLabel.PAGE_FOOTER + assert doc2.texts[0].text == "Footer" + + +def test_roundtrip_code(): + doc = DoclingDocument(name="t") + doc.add_code(text="print('hi')", code_language=CodeLanguageLabel.PYTHON) + doc.add_code(text='disp("Hello world!")', code_language=CodeLanguageLabel.OCTAVE) + dt = _serialize(doc) + doc2 = _deserialize(dt) + dt2 = _serialize(doc2) + + exp_dt = """ + + + + + + + """ + assert dt2.strip() == exp_dt.strip() + + +def test_roundtrip_code_python_and_unknown(): + doc = DoclingDocument(name="t") + doc.add_code(text="x = 1", code_language=CodeLanguageLabel.PYTHON) + doc.add_code(text="y = 2") # CodeLanguageLabel.UNKNOWN by default + + xml = _serialize(doc) + assert ' + """ + doc = _deserialize(dt) + dt2 = _serialize(doc) + assert dt2.strip() == dt.strip() + + +def test_rich_table_cells(): + dt = """ + + + + foo + + + text in italic + + + +
+ + inner cell 0,0 + + inner cell 0,1 + + + inner cell 1,0 + + + inner cell 1,1 + in bold + + +
+ + bar + + +
+""" + doc = _deserialize(dt) + dt2 = _serialize(doc) + assert dt2.strip() == dt.strip() + + +def test_picture_tabular_chart_content_cdata_cells(): + """Deserializer must extract text from in OTSL cells.""" + doclang = """""" + doc = _deserialize(doclang) + first_cell_text = doc.pictures[0].meta.tabular_chart.chart_data.grid[0][0].text + assert first_cell_text == "Characteristic" + assert doc.pictures[0].meta.tabular_chart.chart_data.grid[0][1].text == "Player expenses in million U.S. dollars" + assert doc.pictures[0].meta.tabular_chart.chart_data.grid[1][0].text == "19/20" + assert doc.pictures[0].meta.tabular_chart.chart_data.grid[1][1].text == "111" + + +@pytest.mark.parametrize("escape_mode", [EscapeMode.AUTO, EscapeMode.ALWAYS]) +def test_roundtrip_otsl_xml_sensitive_cell_content(escape_mode: EscapeMode): + """OTSL cell text remains exact when DOM fragments are reparsed.""" + cell_texts = [ + 'Parsing (Structure&Semantic) "quoted"', + "ampersand & less < greater >", + "\"quotes\" and 'apostrophes'", + "literal entity-like text: &", + "CDATA terminator: ]]>", + "multiline code:\nif a < b:\n return a & b", + "Unicode and math: café ∀x ∈ ℝ, x² ≥ 0", # noqa: RUF001 + ] + doc = DoclingDocument(name="otsl-xml-sensitive") + table_data = TableData(num_rows=0, num_cols=1) + for text in cell_texts: + table_data.add_row([text]) + doc.add_table(data=table_data) + + serialized = ( + DocLangDocSerializer( + doc=doc, + params=DocLangParams(include_version=False, escape_mode=escape_mode), + ) + .serialize() + .text + ) + roundtripped = _deserialize(serialized) + + assert [row[0].text for row in roundtripped.tables[0].data.grid] == cell_texts + + +def test_otsl_xml_sensitive_virtual_and_explicit_text_cells(): + """Both virtual and explicit rich OTSL cell bodies preserve safe text.""" + doclang = """\ + + + "quoted" 'apostrophe']]> + ]]> bold & styled + +
+
+""" + doc = _deserialize(doclang) + + assert doc.tables[0].data.grid[0][0].text == "virtual & \"quoted\" 'apostrophe'" + assert doc.tables[0].data.grid[0][1].text == "nested & bold & styled" + assert isinstance(doc.tables[0].data.grid[0][1], RichTableCell) + + +@pytest.mark.parametrize( + "literal", + [ + "", + "", + "", + "not literal", + "", + ], +) +def test_otsl_angle_delimited_text_remains_text(literal: str) -> None: + xml = f'
' + assert_valid_dclg_xml(xml) + + cell = DocLangDocDeserializer().deserialize_str(xml).tables[0].data.grid[0][0] + + assert type(cell) is TableCell + assert cell.text == literal + + +def test_otsl_real_text_element_remains_rich() -> None: + xml = 'not literal
' + + cell = DocLangDocDeserializer().deserialize_str(xml).tables[0].data.grid[0][0] + + assert isinstance(cell, RichTableCell) + assert cell.text == "not literal" + + +def test_picture_body_table_is_semantic_content_not_chart_tabular(): + """```` after the preamble is nested picture content, not ``meta.tabular_chart``.""" + doclang = ( + '' + "Chart1" + "
NestedCell
" + "" + ) + doc = _deserialize(doclang) + pic = doc.pictures[0] + assert pic.meta is not None + assert pic.meta.tabular_chart.chart_data.grid[0][0].text == "Chart" + assert len(pic.children) == 1 + nested = pic.children[0].resolve(doc) + assert isinstance(nested, TableItem) + assert nested.data.grid[0][0].text == "Nested" + + +# SMILES from tests/data/doc/dummy_doc_with_meta.yaml (molecule_data annotation) +_EXAMPLE_MOLECULE_SMILES = "CC1=NNC(C2=CN3C=CN=C3C(CC3=CC(F)=CC(F)=C3)=N2)=N1" +_PICTURE_META_SUMMARY = "Picture meta summary" +_PICTURE_META_DESCRIPTION = "Picture meta description" +_PICTURE_META_CUSTOM_VALUE = "custom field on picture meta" +_CHART_TITLE = "Chart Title" + + +def _create_picture_molecule_doc() -> DoclingDocument: + doc = DoclingDocument(name="picture_molecule_meta") + pic = doc.add_picture() + pic.meta = PictureMeta( + summary=SummaryMetaField(text=_PICTURE_META_SUMMARY), + description=DescriptionMetaField(text=_PICTURE_META_DESCRIPTION), + classification=PictureClassificationMetaField( + predictions=[ + PictureClassificationPrediction( + class_name=PictureClassificationLabel.PIE_CHART.value, + confidence=1.0, + ) + ] + ), + molecule=MoleculeMetaField(smi=_EXAMPLE_MOLECULE_SMILES), + ) + pic.meta.set_custom_field( + namespace="my_corp", + name="note", + value=_PICTURE_META_CUSTOM_VALUE, + ) + # Tabular chart data (pattern from test_serialization_doclang._create_content_filtering_doc) + chart_data = TableData(num_cols=2) + chart_data.add_row(["Foo", "Bar"]) + chart_data.add_row(["One", "Two"]) + pic.meta.tabular_chart = TabularChartMetaField( + title=_CHART_TITLE, + chart_data=chart_data, + ) + return doc + + +_KV_ANNOT_ROOT = Path(__file__).parent / "data" / "doc" / "kv" + +# KV annot fixtures with lossless DocLang XML round-trip today. +_KV_ANNOT_XML_LOSSLESS = frozenset( + { + "01d07afe1cb54ecd23eedfe4d91b81dd88e61bf4e0dbe2467784db4177a6c691", + "08212053e2db1a70dd60a4f85650ceb33d7519af34f502e3ac894389d76663d6", + "1eac20e5ac5fac655a611343f86927d6a76277e170430c1eba741585437a2e90", + "ba4120cada21304563625490e9ad13911e96114d3f07df056a6bf62397a859e1", + } +) + + +def _kv_annot_fixture_dirs() -> list[Path]: + """Return migrated KV annot fixture dirs with serialized DocLang goldens.""" + return sorted( + p + for p in _KV_ANNOT_ROOT.iterdir() + if p.is_dir() and (p / "output.json").is_file() and (p / "output.dclg.xml").is_file() + ) + + +def _serialize_kv_annot_fixture(doc: DoclingDocument) -> str: + text = DocLangDocSerializer(doc=doc, params=DocLangParams(include_version=False)).serialize().text + if not GEN_TEST_DATA: + assert_valid_dclg_xml(text) + return text + + +@pytest.mark.parametrize( + "fixture_dir", + _kv_annot_fixture_dirs(), + ids=[p.name for p in _kv_annot_fixture_dirs()], +) +def test_kv_annot_doclang_roundtrip(fixture_dir: Path): + """Round-trip migrated KV annot fixtures through DocLang (see ``tests/data/doc/kv/``).""" + output_json = fixture_dir / "output.json" + serialized_dclg = fixture_dir / "output.dclg.xml" + deserialized_json = fixture_dir / "deserialized.json" + reserialized_dclg = fixture_dir / "reserialized.dclg.xml" + + doc = DoclingDocument.load_from_json(output_json) + + dt = _serialize_kv_annot_fixture(doc) + verify_doclang(exp_file=serialized_dclg, actual=dt) + + doc2 = _deserialize(dt) + _verify_doc(doc=doc2, exp_json=deserialized_json) + + dt2 = _serialize_kv_annot_fixture(doc2) + verify_doclang(exp_file=reserialized_dclg, actual=dt2) + + if fixture_dir.name in _KV_ANNOT_XML_LOSSLESS: + assert dt.strip() == dt2.strip() + + +def _serialize_field_region_fixture(doc: DoclingDocument, *, fixture_dir: str) -> str: + """Serialize a field-region fixture doc (invoice uses placeholder pictures).""" + params = ( + DocLangParams(include_version=False, image_mode=ImageRefMode.PLACEHOLDER) + if fixture_dir == "field_region_kv_invoice" + else DocLangParams(include_version=False) + ) + text = DocLangDocSerializer(doc=doc, params=params).serialize().text + if not GEN_TEST_DATA: + assert_valid_dclg_xml(text) + return text + + +@pytest.mark.parametrize( + "fixture_dir", + [ + "field_region_kv_migration", + "field_region_kv", + "field_region_kv_invoice", + ], +) +def test_field_region_doclang_roundtrip(fixture_dir: str): + """Round-trip field regions/items through DocLang deserialization.""" + data_dir = Path(__file__).parent / "data" / "doc" / fixture_dir + input_json = data_dir / "input.json" + serialized_dclg = data_dir / "serialized.dclg.xml" + deserialized_json = data_dir / "deserialized.json" + reserialized_dclg = data_dir / "reserialized.dclg.xml" + + doc = DoclingDocument.load_from_json(input_json) + _verify_doc(doc=doc, exp_json=input_json) + assert doc.field_regions + + dt = _serialize_field_region_fixture(doc, fixture_dir=fixture_dir) + verify_doclang(exp_file=serialized_dclg, actual=dt) + + doc2 = _deserialize(dt) + _verify_doc(doc=doc2, exp_json=deserialized_json) + assert doc2.field_regions + + dt2 = _serialize_field_region_fixture(doc2, fixture_dir=fixture_dir) + verify_doclang(exp_file=reserialized_dclg, actual=dt2) + assert dt.strip() == dt2.strip() + + +def test_picture_molecule_meta_roundtrip(): + """Round-trip picture meta (molecule, chart/tabular, summary, description, custom) through DocLang.""" + data_dir = Path(__file__).parent / "data" / "doc" / "picture_molecule_meta" + input_json = data_dir / "input.json" + serialized_dclg = data_dir / "serialized.dclg.xml" + deserialized_json = data_dir / "deserialized.json" + reserialized_dclg = data_dir / "reserialized.dclg.xml" + + doc = _create_picture_molecule_doc() + _verify_doc(doc=doc, exp_json=input_json) + + dt = _serialize(doc) + verify(serialized_dclg, dt) + assert f"{_PICTURE_META_SUMMARY}" in dt + assert f"{_PICTURE_META_DESCRIPTION}" in dt + assert f"{_EXAMPLE_MOLECULE_SMILES}" in dt + assert f"{_PICTURE_META_CUSTOM_VALUE}" in dt + assert 'class="chart"' in dt + assert 'value="pie_chart"' in dt + assert "" in dt + assert "Foo" in dt and "Bar" in dt and "One" in dt and "Two" in dt + + doc2 = _deserialize(dt) + _verify_doc(doc=doc2, exp_json=deserialized_json) + + dt2 = _serialize(doc2) + verify(reserialized_dclg, dt2) + + +def test_roundtrip_with_layers(): + """Test roundtrip with content layers.""" + from docling_core.types.doc import ContentLayer + + doc = DoclingDocument(name="t") + # Add items with different layers + doc.add_text(label=DocItemLabel.PAGE_HEADER, text="Header", content_layer=ContentLayer.FURNITURE) + doc.add_text(label=DocItemLabel.TEXT, text="Body text", content_layer=ContentLayer.BODY) + doc.add_text(label=DocItemLabel.PAGE_FOOTER, text="Footer", content_layer=ContentLayer.FURNITURE) + + # Serialize with ALWAYS mode to ensure layers are included + from docling_core.transforms.serializer.doclang import LayerMode + + ser = DocLangDocSerializer( + doc=doc, + params=DocLangParams(include_version=False, layer_mode=LayerMode.ALWAYS), + ) + dt = ser.serialize().text + + # Deserialize + doc2 = _deserialize(dt) + + # Verify layers are preserved + assert len(doc2.body.children) == 3 + items = [doc2.body.children[i].resolve(doc2) for i in range(3)] + assert items[0].content_layer == ContentLayer.FURNITURE + assert items[1].content_layer == ContentLayer.BODY + assert items[2].content_layer == ContentLayer.FURNITURE + + +def test_roundtrip_with_newlines(): + """Test that newlines in survive deserialization and reserialization.""" + doclang_str = """ + + + foo +bar + + + zoo + + zen + +""" + + doc = _deserialize(doclang_str) + dt2 = _serialize(doc) + assert dt2.strip() == doclang_str.strip() + + +def test_roundtrip_document_index_table(): + """Test that DOCUMENT_INDEX label is preserved through serialization/deserialization.""" + doc = DoclingDocument(name="test") + _add_default_page(doc) + + # Add a regular table + table_data = TableData(num_cols=2) + table_data.add_row(["Header 1", "Header 2"]) + table_data.grid[0][0].column_header = True + table_data.grid[0][1].column_header = True + table_data.add_row(["Data 1", "Data 2"]) + doc.add_table(data=table_data, label=DocItemLabel.TABLE, prov=_default_prov()) + + # Add a DOCUMENT_INDEX table + index_data = TableData(num_cols=2) + index_data.add_row(["Index 1", "Page 1"]) + index_data.add_row(["Index 2", "Page 2"]) + doc.add_table(data=index_data, label=DocItemLabel.DOCUMENT_INDEX, prov=_default_prov()) + + # Serialize + xml_str = _serialize(doc) + + assert "" in xml_str + + # Deserialize + doc2 = _deserialize(xml_str) + + # Verify we have 2 tables + assert len(doc2.tables) == 2 + + # Verify labels are preserved + assert doc2.tables[0].label == DocItemLabel.TABLE + assert doc2.tables[1].label == DocItemLabel.DOCUMENT_INDEX + + # Verify table data is preserved + assert doc2.tables[0].data.num_rows == 2 + assert doc2.tables[0].data.num_cols == 2 + assert doc2.tables[1].data.num_rows == 2 + assert doc2.tables[1].data.num_cols == 2 + + +def _thread_roundtrip( + *, + name: str, + doc_factory: Callable[[], DoclingDocument], + page_breaks: int = 0, +) -> None: + """Round-trip a threaded document fixture through serialize → deserialize → reserialize.""" + data_dir = Path(__file__).parent / "data" / "doc" / name + input_json = data_dir / "input.json" + serialized_dclg = data_dir / "serialized.dclg.xml" + deserialized_json = data_dir / "deserialized.json" + reserialized_dclg = data_dir / "reserialized.dclg.xml" + + doc = doc_factory() + _verify_doc(doc=doc, exp_json=input_json) + + dt = _serialize(doc) + verify(serialized_dclg, dt) + if page_breaks: + assert dt.count("`` is rejected (v0.5: use ```` for document indexes).""" + xml_str = """ + + + Data 1 + +
+
""" + + with pytest.raises(ValueError, match="table element must not have a class attribute"): + _deserialize(xml_str, validate=False) + + +def test_deserialize_rejects_oversize_xml() -> None: + """Huge DocLang markup must fail closed before DOM construction grows unchecked.""" + xml = "" + ("x" * 200) + "" + with pytest.raises(ValueError, match="exceeds size limit"): + DocLangDocDeserializer().deserialize_str(xml, max_xml_bytes=64) + + +def test_deserialize_rejects_over_deep_xml() -> None: + """Extreme element nesting must fail closed (defusedxml does not bound depth).""" + depth = 20 + xml = "".join(f"" for i in range(depth)) + "x" + "".join(f"" for i in reversed(range(depth))) + xml = f"{xml}" + with pytest.raises(ValueError, match="exceeds nesting depth limit"): + DocLangDocDeserializer().deserialize_str(xml, max_xml_depth=8) + + +def test_deserialize_rejects_too_many_elements() -> None: + """Element floods must fail closed even when total byte size is modest.""" + # 30 sibling elements under doclang — over a tight element budget. + children = "".join(f"t{i}" for i in range(30)) + xml = f"{children}" + with pytest.raises(ValueError, match="exceeds element count limit"): + DocLangDocDeserializer().deserialize_str(xml, max_xml_elements=10) + + +def test_deserialize_accepts_document_within_budgets() -> None: + xml = "hello" + doc = DocLangDocDeserializer().deserialize_str( + xml, + max_xml_bytes=1024, + max_xml_depth=16, + max_xml_elements=100, + ) + assert len(doc.texts) == 1 + assert doc.texts[0].text == "hello" + + +def _doc_with_named_groups() -> DoclingDocument: + doc = DoclingDocument(name="t") + _add_default_page(doc) + doc.add_text(label=DocItemLabel.TITLE, text="Masthead") + for index in (1, 2): + group = doc.add_group(label=GroupLabel.SECTION, name="article") + doc.add_heading(text=f"Headline {index}", level=2, parent=group) + doc.add_text(label=DocItemLabel.TEXT, text=f"Body {index}", parent=group) + return doc + + +def _serialize_named_groups(doc: DoclingDocument, *, add_named_groups: bool) -> str: + ser = DocLangDocSerializer( + doc=doc, + params=DocLangParams(include_version=False, add_named_groups=add_named_groups), + ) + return ser.serialize().text + + +def test_named_groups_are_off_by_default() -> None: + """A plain group stays transparent unless ``add_named_groups`` is set.""" + text = _serialize_named_groups(_doc_with_named_groups(), add_named_groups=False) + assert " None: + """``add_named_groups`` keeps the group, its name and its label across a roundtrip.""" + text = _serialize_named_groups(_doc_with_named_groups(), add_named_groups=True) + assert text.count('') == 2 + assert text.count('