Harbor format: 14 coding_additions tasks (part 4)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FieldValueItem.yamlAdded+12
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FloatingItem.yamlAdded+11
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormItem.yamlAdded+32
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormulaItem.yamlAdded+11
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/KeyValueItem.yamlAdded+32
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/ListItem.yamlAdded+13
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/PictureItem.yamlAdded+12
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/SectionHeaderItem.yamlAdded+12
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TableItem.yamlAdded+198
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TextItem.yamlAdded+11
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TitleItem.yamlAdded+11
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.cAdded+22
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.goAdded+23
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.javaAdded+25
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.jsAdded+23
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.mdAdded+23
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.pyAdded+25
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.tsAdded+20
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-01.jsonAdded+33
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-02.jsonAdded+39
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-03.jsonAdded+12
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-01.jsonAdded+38
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-02.jsonAdded+32
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-03.jsonAdded+29
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-04.jsonAdded+17
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched.dt_viz_p2.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5_rows_and_cols.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p1.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p2.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p3.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p1.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p2.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p3.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p1.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p2.pngAdded
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_01.vttAdded+42
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_02.vttAdded+15
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_03.vttAdded+57
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_04.vttAdded+36
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/doclang_validation.pyAdded+103
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/tasksmith_behavior.pyAdded+69
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_azure_serializer.pyAdded+148
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_base.pyAdded+40
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_chunk_expander.pyAdded+366
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_cli_serialize.pyAdded+53
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunker.pyAdded+173
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunking_strategy.pyAdded+196
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_compat.pyAdded+658
- tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_gen_flag.pyAdded+9
123456789101112children: []content_layer: bodyformatting: nullhyperlink: nullkind: fillablelabel: field_valuemeta: nullorig: whateverparent: nullprov: []self_ref: '#'text: whatever1234567891011captions: []children: []footnotes: []image: nulllabel: textparent: nullprov: []references: []self_ref: '#'content_layer: bodymeta: null1234567891011121314151617181920212223242526272829303132captions: []children: []content_layer: bodyfootnotes: []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: 0image: nulllabel: formmeta: nullparent: nullprov: []references: []self_ref: '#'1234567891011children: []label: formulaorig: whateverparent: nullprov: []self_ref: '#'text: E=mc^2content_layer: bodyformatting: nullhyperlink: nullmeta: null1234567891011121314151617181920212223242526272829303132captions: []children: []content_layer: bodyfootnotes: []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: 0image: nulllabel: key_value_regionmeta: nullparent: nullprov: []references: []self_ref: '#'12345678910111213children: []enumerated: truelabel: list_itemmarker: (1)orig: whateverparent: nullprov: []self_ref: '#'text: whatevercontent_layer: bodyformatting: nullhyperlink: nullmeta: null123456789101112annotations: []captions: []children: []footnotes: []image: nulllabel: pictureparent: nullprov: []references: []self_ref: '#'content_layer: bodymeta: null123456789101112children: []label: section_headerlevel: 2orig: whateverparent: nullprov: []self_ref: '#'text: whatevercontent_layer: bodyformatting: nullhyperlink: nullmeta: null123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198captions: []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: nulllabel: tableparent: nullprov: []references: []self_ref: '#'content_layer: bodyannotations: []meta: null1234567891011children: []label: textorig: whateverparent: nullprov: []self_ref: '#'text: whatevercontent_layer: bodyformatting: nullhyperlink: nullmeta: null1234567891011children: []label: titleorig: whateverparent: nullprov: []self_ref: '#'text: whatevercontent_layer: bodyformatting: nullhyperlink: nullmeta: null12345678910111213141516171819202122#include <stdio.h>#include <math.h>
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;}1234567891011121314151617181920212223package 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)}12345678910111213141516171819202122232425public 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; }}1234567891011121314151617181920212223function 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; }}1234567891011121314151617181920212223# Sample Markdown File
This is a sample markdown file for testing repository chunking.
## Code Example
Here's some Python code:
```pythondef 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.12345678910111213141516171819202122232425def 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!"1234567891011121314151617181920interface 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); }}123456789101112131415161718192021222324252627282930313233{ "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" } ] }}123456789101112131415161718192021222324252627282930313233343536373839{ "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" } ] }}123456789101112{ "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"}1234567891011121314151617181920212223242526272829303132333435363738{ "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" } ] }}1234567891011121314151617181920212223242526272829303132{ "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"}1234567891011121314151617181920212223242526272829{ "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" ]}1234567891011121314151617{ "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"}123456789101112131415161718192021222324252627282930313233343536373839404142WEBVTT
NOTE Copyright © 2019 World Wide Web Consortium. https://www.w3.org/TR/webvtt1/
00:11.000 --> 00:13.000<v Roger Bingham>We are in New York City
00:13.000 --> 00:16.000<v Roger Bingham>We’re actually at the Lucern Hotel, just down the street
00:16.000 --> 00:18.000<v Roger Bingham>from the American Museum of Natural History
00:18.000 --> 00:20.000<v Roger Bingham>And with me is Neil deGrasse Tyson
00:20.000 --> 00:22.000<v Roger Bingham>Astrophysicist, Director of the Hayden Planetarium
00:22.000 --> 00:24.000<v Roger Bingham>at the AMNH.
00:24.000 --> 00:26.000<v Roger Bingham>Thank you for walking down here.
00:27.000 --> 00:30.000<v Roger Bingham>And I want to do a follow-up on the last conversation we did.
00:30.000 --> 00:31.500 align:right size:50%<v Roger Bingham>When we e-mailed—
00:30.500 --> 00:32.500 align:left size:50%<v Neil deGrasse Tyson>Didn’t we talk about enough in that conversation?
00:32.000 --> 00:35.500 align:right size:50%<v Roger Bingham>No! No no no no; 'cos 'cos obviously 'cos
00:32.500 --> 00:33.500 align:left size:50%<v Neil deGrasse Tyson><i>Laughs</i>
00:35.500 --> 00:38.000<v Roger Bingham>You know I’m so excited my glasses are falling off here.123456789101112131415WEBVTT
NOTE Copyright © 2019 World Wide Web Consortium. https://www.w3.org/TR/webvtt1/
00:00.000 --> 00:02.000<v.first.loud Esme>It’s a blue apple tree!
00:02.000 --> 00:04.000<v Mary>No way!
00:04.000 --> 00:06.000<v Esme>Hee!</v> <i>laughter</i>
00:06.000 --> 00:08.000<v.loud Mary>That’s awesome!123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657WEBVTT
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/15-000:00:04.963 --> 00:00:08.571<v Speaker A>OK,I think now we should be recording</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/15-100:00:08.571 --> 00:00:09.403<v Speaker A>properly.</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/16-000:00:10.683 --> 00:00:11.563Good.
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/17-000:00:13.363 --> 00:00:13.803<v Speaker A>Yeah.</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/78-000:00:49.603 --> 00:00:53.363<v Speaker B>I was also thinking.</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/113-000:00:54.963 --> 00:01:02.072<v Speaker B>Would be maybe good to create items,</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/113-100:01:02.072 --> 00:01:06.811<v Speaker B>some metadata,some options that can be specific.</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/150-000:01:10.243 --> 00:01:13.014<v Speaker A>Yeah,I mean I think you went even more than</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/119-000:01:10.563 --> 00:01:12.643<v Speaker B>But we preserved the atoms.</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/150-100:01:13.014 --> 00:01:15.907<v Speaker A>than me.I just opened the format.</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/197-100:01:50.222 --> 00:01:51.643<v Speaker A>give it a try, yeah.</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/200-000:01:52.043 --> 00:01:55.043<v Speaker B>Okay, talk to you later.</v>
62357a1d-d250-41d5-a1cf-6cc0eeceffcc/202-000:01:54.603 --> 00:01:55.283<v Speaker A>See you.</v>123456789101112131415161718192021222324252627282930313233343536WEBVTT 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" */
REGIONid:editor-commentswidth: 40%regionanchor:0%,100%viewportanchor:10%,90%
REGIONid:scrollwidth: 40%regionanchor:100%,100%viewportanchor:90%,90%scroll:up
00:01.000 --> 00:04.000Never 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 <b.loud>die</b>.<v John>This is true.</v>
00:10.000 --> 00:14.000the<00:10.389> quick<00:10.750> brown<00:11.110> fox123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Helpers for validating DocLang XML against the reference doclang package."""
from __future__ import annotations
import osimport tempfilefrom pathlib import Pathfrom typing import Union
import pytest
try: from doclang import ValidationError from doclang import validate as doclang_validateexcept 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import pytestfrom 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 == 3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Tests for AzureDocSerializer."""
import jsonfrom pathlib import Pathfrom typing import Any
from docling_core.transforms.serializer.azure import AzureDocSerializer, AzureParamsfrom docling_core.types.doc.base import BoundingBox, CoordOrigin, Sizefrom 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)12345678910111213141516171819202122232425262728293031323334353637383940"""Test the pydantic models in module data_types.base.py."""
from datetime import datetime, timezone
import pytestfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366"""Tests for chunk expander classes."""
import pytest
from docling_core.transforms.chunker.chunk_expander import PageChunkExpander, TreeChunkExpanderfrom docling_core.transforms.chunker.doc_chunk import DocChunk, DocMetafrom docling_core.transforms.chunker.hierarchical_chunker import ChunkingDocSerializer, ChunkingSerializerProviderfrom docling_core.transforms.chunker.hybrid_chunker import HybridChunkerfrom docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizerfrom docling_core.transforms.serializer.markdown import MarkdownTableSerializerfrom docling_core.types.doc import DocItemLabel, DoclingDocument, Sizefrom 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.fixturedef 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.fixturedef 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.fixturedef 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.fixturedef 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.fixturedef tree_expander(): """Create a TreeChunkExpander instance.""" return TreeChunkExpander()
@pytest.fixturedef 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"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Tests for the ``docling-serialize`` CLI."""
import zipfilefrom pathlib import Path
from click import unstylefrom typer.testing import CliRunner
from docling_core.cli.serialize import appfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173import globimport hashlibimport jsonimport osimport pathlibimport sysfrom typing import Optional
import gitimport pytest
from docling_core.transforms.chunker.code_chunking._utils import _get_file_extensionsfrom docling_core.transforms.chunker.code_chunking.code_chunk import CodeChunkfrom docling_core.transforms.chunker.code_chunking.standard_code_chunking_strategy import ( StandardCodeChunkingStrategy,)from docling_core.transforms.chunker.hierarchical_chunker import HierarchicalChunkerfrom docling_core.types.doc import DoclingDocument, DocumentOriginfrom 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__).parentDATA = 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196from pathlib import Path
import pytest
from docling_core.transforms.chunker import ( CodeLanguageLabel, HierarchicalChunker, HybridChunker, StandardCodeChunkingStrategy,)from docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizerfrom docling_core.transforms.serializer.markdown import ( MarkdownDocSerializer, MarkdownParams,)from docling_core.types.doc.base import Sizefrom docling_core.types.doc.document import DoclingDocument, DocumentOriginfrom docling_core.types.doc.labels import DocItemLabel
@pytest.fixturedef 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) > 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658"""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 jsonfrom pathlib import Path
import jsonschemaimport pytest
from docling_core.compat import _projectors, list_projectors, project_tofrom 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)] = removed123456789import 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_DATAtasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FieldValueItem.yamlAdded+12
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FloatingItem.yamlAdded+11
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormItem.yamlAdded+32
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormulaItem.yamlAdded+11
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/KeyValueItem.yamlAdded+32
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/ListItem.yamlAdded+13
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/PictureItem.yamlAdded+12
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/SectionHeaderItem.yamlAdded+12
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TableItem.yamlAdded+198
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TextItem.yamlAdded+11
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TitleItem.yamlAdded+11
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.cAdded+22
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.goAdded+23
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.javaAdded+25
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.jsAdded+23
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.mdAdded+23
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.pyAdded+25
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.tsAdded+20
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-01.jsonAdded+33
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-02.jsonAdded+39
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-03.jsonAdded+12
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-01.jsonAdded+38
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-02.jsonAdded+32
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-03.jsonAdded+29
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-04.jsonAdded+17
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched.dt_viz_p2.pngAdded

Large File Pointer Details
- SHA256: 103d27d70cc2b52b891a709097a9c1777131cf648d61968be1f3c69d70bc36e7
- Pointer size: 131 Bytes
- Size of remote file: 533 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5.pngAdded

Large File Pointer Details
- SHA256: 60863252174f1a327a15c14c28b890ab5c6be14becfcc3f6a64ab69b8d5ebf93
- Pointer size: 131 Bytes
- Size of remote file: 582 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5_rows_and_cols.pngAdded

Large File Pointer Details
- SHA256: 50e076c2e9a82fde20fd8d53ada2ef64ec7214a89aa21ad7d609d92f951d8c23
- Pointer size: 131 Bytes
- Size of remote file: 582 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p1.pngAdded

Large File Pointer Details
- SHA256: a6c47693821bb54ec1924d437bbcc6895d2943b18ad41ea93027b08cced41e2b
- Pointer size: 131 Bytes
- Size of remote file: 421 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p2.pngAdded

Large File Pointer Details
- SHA256: fee077e0f0ec722a5450d580777a5dbe733dc7f83e352184f7a0de7a3cee18f3
- Pointer size: 131 Bytes
- Size of remote file: 532 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p3.pngAdded

Large File Pointer Details
- SHA256: bef96e1282bc1d964ca31d23fcf40bdb92ace63f0b55ab4c24bfee20d8b359bf
- Pointer size: 131 Bytes
- Size of remote file: 504 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p1.pngAdded

Large File Pointer Details
- SHA256: f09738ce29cb6cc0bce4b998fb1aaa15da1d84e2209f5358769125b485abb6f2
- Pointer size: 131 Bytes
- Size of remote file: 412 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p2.pngAdded

Large File Pointer Details
- SHA256: 9f6c02e7638eaf644c7c4f4a9cd0bbda1b62d21eb5bd8d10d2dcc10d8e66a6c2
- Pointer size: 131 Bytes
- Size of remote file: 520 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p3.pngAdded

Large File Pointer Details
- SHA256: e264067d8d7d7472a26600ae40aed8d7e726fc6ef135e91719206e3ad59825a9
- Pointer size: 131 Bytes
- Size of remote file: 493 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p1.pngAdded

Large File Pointer Details
- SHA256: 0d65b2c1bda7c14a58ee1b67c04aa697267694ab9fdf515e25c0269b8028ff13
- Pointer size: 131 Bytes
- Size of remote file: 289 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p2.pngAdded

Large File Pointer Details
- SHA256: 3dd83855b42c1b6fd82cea824c41cf66bcdfd4f8f3a3cffded96c0dd65dc90c2
- Pointer size: 131 Bytes
- Size of remote file: 364 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_01.vttAdded+42
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_02.vttAdded+15
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_03.vttAdded+57
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_04.vttAdded+36
tasks/tasksmith-0ba04a338dbb/tests/source/tests/doclang_validation.pyAdded+103
tasks/tasksmith-0ba04a338dbb/tests/source/tests/tasksmith_behavior.pyAdded+69
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_azure_serializer.pyAdded+148
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_base.pyAdded+40
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_chunk_expander.pyAdded+366
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_cli_serialize.pyAdded+53
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunker.pyAdded+173
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunking_strategy.pyAdded+196
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_compat.pyAdded+658
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_gen_flag.pyAdded+9