ybelkada HF Staff commited on
Commit
0bfbb42
·
verified ·
1 Parent(s): 4954c75

Harbor format: 14 coding_additions tasks (part 4)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FieldValueItem.yaml +12 -0
  2. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FloatingItem.yaml +11 -0
  3. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormItem.yaml +32 -0
  4. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormulaItem.yaml +11 -0
  5. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/KeyValueItem.yaml +32 -0
  6. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/ListItem.yaml +13 -0
  7. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/PictureItem.yaml +12 -0
  8. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/SectionHeaderItem.yaml +12 -0
  9. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TableItem.yaml +198 -0
  10. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TextItem.yaml +11 -0
  11. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TitleItem.yaml +11 -0
  12. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.c +22 -0
  13. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.go +23 -0
  14. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.java +25 -0
  15. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.js +23 -0
  16. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.md +23 -0
  17. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.py +25 -0
  18. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.ts +20 -0
  19. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-01.json +33 -0
  20. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-02.json +39 -0
  21. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-03.json +12 -0
  22. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-01.json +38 -0
  23. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-02.json +32 -0
  24. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-03.json +29 -0
  25. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-04.json +17 -0
  26. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched.dt_viz_p2.png +3 -0
  27. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5.png +3 -0
  28. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_table_viz_wout_lbl_p5_rows_and_cols.png +3 -0
  29. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p1.png +3 -0
  30. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p2.png +3 -0
  31. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_p3.png +3 -0
  32. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p1.png +3 -0
  33. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p2.png +3 -0
  34. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched_viz_wout_lbl_p3.png +3 -0
  35. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p1.png +3 -0
  36. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/cross_page_lists_p2.png +3 -0
  37. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_01.vtt +42 -0
  38. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_02.vtt +15 -0
  39. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_03.vtt +57 -0
  40. tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_04.vtt +36 -0
  41. tasks/tasksmith-0ba04a338dbb/tests/source/tests/doclang_validation.py +103 -0
  42. tasks/tasksmith-0ba04a338dbb/tests/source/tests/tasksmith_behavior.py +69 -0
  43. tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_azure_serializer.py +148 -0
  44. tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_base.py +40 -0
  45. tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_chunk_expander.py +366 -0
  46. tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_cli_serialize.py +53 -0
  47. tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunker.py +173 -0
  48. tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunking_strategy.py +196 -0
  49. tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_compat.py +658 -0
  50. tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_gen_flag.py +9 -0
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FieldValueItem.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ children: []
2
+ content_layer: body
3
+ formatting: null
4
+ hyperlink: null
5
+ kind: fillable
6
+ label: field_value
7
+ meta: null
8
+ orig: whatever
9
+ parent: null
10
+ prov: []
11
+ self_ref: '#'
12
+ text: whatever
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FloatingItem.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ captions: []
2
+ children: []
3
+ footnotes: []
4
+ image: null
5
+ label: text
6
+ parent: null
7
+ prov: []
8
+ references: []
9
+ self_ref: '#'
10
+ content_layer: body
11
+ meta: null
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormItem.yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ captions: []
2
+ children: []
3
+ content_layer: body
4
+ footnotes: []
5
+ graph:
6
+ cells:
7
+ - cell_id: 0
8
+ item_ref: null
9
+ label: key
10
+ orig: '#'
11
+ prov: null
12
+ text: number
13
+ - cell_id: 1
14
+ item_ref: null
15
+ label: value
16
+ orig: '1'
17
+ prov: null
18
+ text: '1'
19
+ links:
20
+ - label: to_value
21
+ source_cell_id: 0
22
+ target_cell_id: 1
23
+ - label: to_key
24
+ source_cell_id: 1
25
+ target_cell_id: 0
26
+ image: null
27
+ label: form
28
+ meta: null
29
+ parent: null
30
+ prov: []
31
+ references: []
32
+ self_ref: '#'
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/FormulaItem.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ children: []
2
+ label: formula
3
+ orig: whatever
4
+ parent: null
5
+ prov: []
6
+ self_ref: '#'
7
+ text: E=mc^2
8
+ content_layer: body
9
+ formatting: null
10
+ hyperlink: null
11
+ meta: null
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/KeyValueItem.yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ captions: []
2
+ children: []
3
+ content_layer: body
4
+ footnotes: []
5
+ graph:
6
+ cells:
7
+ - cell_id: 0
8
+ item_ref: null
9
+ label: key
10
+ orig: '#'
11
+ prov: null
12
+ text: number
13
+ - cell_id: 1
14
+ item_ref: null
15
+ label: value
16
+ orig: '1'
17
+ prov: null
18
+ text: '1'
19
+ links:
20
+ - label: to_value
21
+ source_cell_id: 0
22
+ target_cell_id: 1
23
+ - label: to_key
24
+ source_cell_id: 1
25
+ target_cell_id: 0
26
+ image: null
27
+ label: key_value_region
28
+ meta: null
29
+ parent: null
30
+ prov: []
31
+ references: []
32
+ self_ref: '#'
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/ListItem.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ children: []
2
+ enumerated: true
3
+ label: list_item
4
+ marker: (1)
5
+ orig: whatever
6
+ parent: null
7
+ prov: []
8
+ self_ref: '#'
9
+ text: whatever
10
+ content_layer: body
11
+ formatting: null
12
+ hyperlink: null
13
+ meta: null
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/PictureItem.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ annotations: []
2
+ captions: []
3
+ children: []
4
+ footnotes: []
5
+ image: null
6
+ label: picture
7
+ parent: null
8
+ prov: []
9
+ references: []
10
+ self_ref: '#'
11
+ content_layer: body
12
+ meta: null
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/SectionHeaderItem.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ children: []
2
+ label: section_header
3
+ level: 2
4
+ orig: whatever
5
+ parent: null
6
+ prov: []
7
+ self_ref: '#'
8
+ text: whatever
9
+ content_layer: body
10
+ formatting: null
11
+ hyperlink: null
12
+ meta: null
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TableItem.yaml ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ captions: []
2
+ children: []
3
+ data:
4
+ grid:
5
+ - - bbox: null
6
+ col_span: 1
7
+ column_header: false
8
+ end_col_offset_idx: 1
9
+ end_row_offset_idx: 1
10
+ fillable: false
11
+ row_header: false
12
+ row_section: false
13
+ row_span: 1
14
+ start_col_offset_idx: 0
15
+ start_row_offset_idx: 0
16
+ text: ''
17
+ - bbox: null
18
+ col_span: 1
19
+ column_header: false
20
+ end_col_offset_idx: 2
21
+ end_row_offset_idx: 1
22
+ fillable: false
23
+ row_header: false
24
+ row_section: false
25
+ row_span: 1
26
+ start_col_offset_idx: 1
27
+ start_row_offset_idx: 0
28
+ text: ''
29
+ - bbox: null
30
+ col_span: 1
31
+ column_header: false
32
+ end_col_offset_idx: 3
33
+ end_row_offset_idx: 1
34
+ fillable: false
35
+ row_header: false
36
+ row_section: false
37
+ row_span: 1
38
+ start_col_offset_idx: 2
39
+ start_row_offset_idx: 0
40
+ text: ''
41
+ - bbox: null
42
+ col_span: 1
43
+ column_header: false
44
+ end_col_offset_idx: 4
45
+ end_row_offset_idx: 1
46
+ fillable: false
47
+ row_header: false
48
+ row_section: false
49
+ row_span: 1
50
+ start_col_offset_idx: 3
51
+ start_row_offset_idx: 0
52
+ text: ''
53
+ - bbox: null
54
+ col_span: 1
55
+ column_header: false
56
+ end_col_offset_idx: 5
57
+ end_row_offset_idx: 1
58
+ fillable: false
59
+ row_header: false
60
+ row_section: false
61
+ row_span: 1
62
+ start_col_offset_idx: 4
63
+ start_row_offset_idx: 0
64
+ text: ''
65
+ - - bbox: null
66
+ col_span: 1
67
+ column_header: false
68
+ end_col_offset_idx: 1
69
+ end_row_offset_idx: 2
70
+ fillable: false
71
+ row_header: false
72
+ row_section: false
73
+ row_span: 1
74
+ start_col_offset_idx: 0
75
+ start_row_offset_idx: 1
76
+ text: ''
77
+ - bbox: null
78
+ col_span: 1
79
+ column_header: false
80
+ end_col_offset_idx: 2
81
+ end_row_offset_idx: 2
82
+ fillable: false
83
+ row_header: false
84
+ row_section: false
85
+ row_span: 1
86
+ start_col_offset_idx: 1
87
+ start_row_offset_idx: 1
88
+ text: ''
89
+ - bbox: null
90
+ col_span: 1
91
+ column_header: false
92
+ end_col_offset_idx: 3
93
+ end_row_offset_idx: 2
94
+ fillable: false
95
+ row_header: false
96
+ row_section: false
97
+ row_span: 1
98
+ start_col_offset_idx: 2
99
+ start_row_offset_idx: 1
100
+ text: ''
101
+ - bbox: null
102
+ col_span: 1
103
+ column_header: false
104
+ end_col_offset_idx: 4
105
+ end_row_offset_idx: 2
106
+ fillable: false
107
+ row_header: false
108
+ row_section: false
109
+ row_span: 1
110
+ start_col_offset_idx: 3
111
+ start_row_offset_idx: 1
112
+ text: ''
113
+ - bbox: null
114
+ col_span: 1
115
+ column_header: false
116
+ end_col_offset_idx: 5
117
+ end_row_offset_idx: 2
118
+ fillable: false
119
+ row_header: false
120
+ row_section: false
121
+ row_span: 1
122
+ start_col_offset_idx: 4
123
+ start_row_offset_idx: 1
124
+ text: ''
125
+ - - bbox: null
126
+ col_span: 1
127
+ column_header: false
128
+ end_col_offset_idx: 1
129
+ end_row_offset_idx: 3
130
+ fillable: false
131
+ row_header: false
132
+ row_section: false
133
+ row_span: 1
134
+ start_col_offset_idx: 0
135
+ start_row_offset_idx: 2
136
+ text: ''
137
+ - bbox: null
138
+ col_span: 1
139
+ column_header: false
140
+ end_col_offset_idx: 2
141
+ end_row_offset_idx: 3
142
+ fillable: false
143
+ row_header: false
144
+ row_section: false
145
+ row_span: 1
146
+ start_col_offset_idx: 1
147
+ start_row_offset_idx: 2
148
+ text: ''
149
+ - bbox: null
150
+ col_span: 1
151
+ column_header: false
152
+ end_col_offset_idx: 3
153
+ end_row_offset_idx: 3
154
+ fillable: false
155
+ row_header: false
156
+ row_section: false
157
+ row_span: 1
158
+ start_col_offset_idx: 2
159
+ start_row_offset_idx: 2
160
+ text: ''
161
+ - bbox: null
162
+ col_span: 1
163
+ column_header: false
164
+ end_col_offset_idx: 4
165
+ end_row_offset_idx: 3
166
+ fillable: false
167
+ row_header: false
168
+ row_section: false
169
+ row_span: 1
170
+ start_col_offset_idx: 3
171
+ start_row_offset_idx: 2
172
+ text: ''
173
+ - bbox: null
174
+ col_span: 1
175
+ column_header: false
176
+ end_col_offset_idx: 5
177
+ end_row_offset_idx: 3
178
+ fillable: false
179
+ row_header: false
180
+ row_section: false
181
+ row_span: 1
182
+ start_col_offset_idx: 4
183
+ start_row_offset_idx: 2
184
+ text: ''
185
+ num_cols: 5
186
+ num_rows: 3
187
+ orientation: rot_0
188
+ table_cells: []
189
+ footnotes: []
190
+ image: null
191
+ label: table
192
+ parent: null
193
+ prov: []
194
+ references: []
195
+ self_ref: '#'
196
+ content_layer: body
197
+ annotations: []
198
+ meta: null
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TextItem.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ children: []
2
+ label: text
3
+ orig: whatever
4
+ parent: null
5
+ prov: []
6
+ self_ref: '#'
7
+ text: whatever
8
+ content_layer: body
9
+ formatting: null
10
+ hyperlink: null
11
+ meta: null
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/docling_document/unit/TitleItem.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ children: []
2
+ label: title
3
+ orig: whatever
4
+ parent: null
5
+ prov: []
6
+ self_ref: '#'
7
+ text: whatever
8
+ content_layer: body
9
+ formatting: null
10
+ hyperlink: null
11
+ meta: null
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.c ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+ #include <math.h>
3
+
4
+ double circle_area(double radius) {
5
+ return M_PI * radius * radius;
6
+ }
7
+
8
+ double circle_circumference(double radius) {
9
+ return 2 * M_PI * radius;
10
+ }
11
+
12
+ int fibonacci(int n) {
13
+ if (n <= 1) {
14
+ return n;
15
+ }
16
+ return fibonacci(n - 1) + fibonacci(n - 2);
17
+ }
18
+
19
+ int main() {
20
+ printf("Hello, World!\n");
21
+ return 0;
22
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.go ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "fmt"
4
+
5
+ func main() {
6
+ fmt.Println("Hello, World!")
7
+ }
8
+
9
+ func fibonacci(n int) int {
10
+ if n <= 1 {
11
+ return n
12
+ }
13
+ return fibonacci(n-1) + fibonacci(n-2)
14
+ }
15
+
16
+ type Person struct {
17
+ Name string
18
+ Age int
19
+ }
20
+
21
+ func (p Person) String() string {
22
+ return fmt.Sprintf("%s is %d years old", p.Name, p.Age)
23
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.java ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ public class Calculator {
2
+ private double result;
3
+
4
+ public Calculator() {
5
+ this.result = 0.0;
6
+ }
7
+
8
+ public double add(double a, double b) {
9
+ this.result = a + b;
10
+ return this.result;
11
+ }
12
+
13
+ public double subtract(double a, double b) {
14
+ this.result = a - b;
15
+ return this.result;
16
+ }
17
+
18
+ public double getResult() {
19
+ return this.result;
20
+ }
21
+
22
+ public void reset() {
23
+ this.result = 0.0;
24
+ }
25
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function multiply(a, b) {
2
+ return a * b;
3
+ }
4
+
5
+ function divide(a, b) {
6
+ return b !== 0 ? a / b : 0;
7
+ }
8
+
9
+ function greet(name) {
10
+ return `Hello, ${name}!`;
11
+ }
12
+
13
+ class Calculator {
14
+ constructor() {
15
+ this.history = [];
16
+ }
17
+
18
+ add(a, b) {
19
+ const result = a + b;
20
+ this.history.push(`${a} + ${b} = ${result}`);
21
+ return result;
22
+ }
23
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sample Markdown File
2
+
3
+ This is a sample markdown file for testing repository chunking.
4
+
5
+ ## Code Example
6
+
7
+ Here's some Python code:
8
+
9
+ ```python
10
+ def hello():
11
+ print("Hello, World!")
12
+ ```
13
+
14
+ ## Features
15
+
16
+ - Lists
17
+ - **Bold text**
18
+ - *Italic text*
19
+ - [Links](https://example.com)
20
+
21
+ ## Conclusion
22
+
23
+ This file should be processed as text content, not as code.
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def fibonacci(n):
2
+ """Calculate the nth Fibonacci number using recursion."""
3
+ if n <= 1:
4
+ return n
5
+ return fibonacci(n - 1) + fibonacci(n - 2)
6
+
7
+
8
+ class MathUtils:
9
+ """Utility class for mathematical operations."""
10
+
11
+ def __init__(self):
12
+ self.pi = 3.14159
13
+
14
+ def circle_area(self, radius):
15
+ """Calculate the area of a circle."""
16
+ return self.pi * radius**2
17
+
18
+ def circle_circumference(self, radius):
19
+ """Calculate the circumference of a circle."""
20
+ return 2 * self.pi * radius
21
+
22
+
23
+ def hello():
24
+ """A simple hello function."""
25
+ return "Hello, World!"
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/repo_chunking/sample.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ interface Point {
2
+ x: number;
3
+ y: number;
4
+ }
5
+
6
+ function distance(p1: Point, p2: Point): number {
7
+ return Math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2);
8
+ }
9
+
10
+ class Vector {
11
+ constructor(public x: number, public y: number) {}
12
+
13
+ magnitude(): number {
14
+ return Math.sqrt(this.x ** 2 + this.y ** 2);
15
+ }
16
+
17
+ add(other: Vector): Vector {
18
+ return new Vector(this.x + other.x, this.y + other.y);
19
+ }
20
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-01.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "aliases": [
3
+ ".production",
4
+ "arxiv"
5
+ ],
6
+ "created": "2022-08-15T14:10:32.768+00:00",
7
+ "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.",
8
+ "source": "https://arxiv.org",
9
+ "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-arxiv-data",
10
+ "display_name": "arXiv full documents",
11
+ "type": "Reference",
12
+ "classification": [
13
+ "Public",
14
+ "PI"
15
+ ],
16
+ "license": "https://arxiv.org/about",
17
+ "filename": "arxiv-gs.json",
18
+ "domain": [
19
+ "Science",
20
+ "Literature"
21
+ ],
22
+ "$ref": "ccs:schemas#/Document",
23
+ "ccs_s3_data": {
24
+ "endpoint": "s3.eu-de.cloud-object-storage.appdomain.cloud",
25
+ "paths": [
26
+ {
27
+ "bucket": "foc-deepsearch-s3-elastic",
28
+ "prefix": "deepsearch-elastic-dataplatform",
29
+ "infix": "cxs-8a1925c96f7b49508855ab270d0f3281"
30
+ }
31
+ ]
32
+ }
33
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-02.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "aliases": [
3
+ ".production",
4
+ "arxiv"
5
+ ],
6
+ "created": "2022-08-15T14:10:32.768+00:00",
7
+ "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.",
8
+ "source": "https://arxiv.org",
9
+ "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-arxiv-data",
10
+ "display_name": "arXiv full documents",
11
+ "type": "Document",
12
+ "classification": [
13
+ "Public",
14
+ "PI"
15
+ ],
16
+ "version": [
17
+ {
18
+ "name": "docling-core",
19
+ "version": "beta"
20
+ }
21
+ ],
22
+ "license": "https://arxiv.org/about",
23
+ "filename": "arxiv-gs.json",
24
+ "domain": [
25
+ "Science",
26
+ "Banking & Finance"
27
+ ],
28
+ "$ref": "cps:schemas#/Record",
29
+ "ccs_s3_data": {
30
+ "endpoint": "s3.eu-de.cloud-object-storage.appdomain.cloud",
31
+ "paths": [
32
+ {
33
+ "bucket": "foc-deepsearch-s3-elastic",
34
+ "prefix": "deepsearch-elastic-dataplatform",
35
+ "infix": "cxs-8a1925c96f7b49508855ab270d0f3281"
36
+ }
37
+ ]
38
+ }
39
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/error-meta-03.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "created": "2022-08-15T14:10:32.768+00:00",
3
+ "version": [
4
+ {
5
+ "name": "docling-core",
6
+ "version": "1.0.0"
7
+ }
8
+ ],
9
+ "type": "Record",
10
+ "$ref": "cps:schemas#/Record",
11
+ "extra": "an extra field"
12
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-01.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "aliases": [
3
+ ".production",
4
+ "arxiv"
5
+ ],
6
+ "created": "2022-08-15T14:10:32.768+00:00",
7
+ "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.",
8
+ "source": "https://arxiv.org",
9
+ "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-arxiv-data",
10
+ "display_name": "arXiv full documents",
11
+ "type": "Document",
12
+ "classification": [
13
+ "Public",
14
+ "PI"
15
+ ],
16
+ "version": [
17
+ {
18
+ "name": "docling-core",
19
+ "version": "1.0.1"
20
+ }
21
+ ],
22
+ "license": "https://arxiv.org/about",
23
+ "filename": "arxiv-gs.json",
24
+ "domain": [
25
+ "Science"
26
+ ],
27
+ "$ref": "ccs:schemas#/Document",
28
+ "ccs_s3_data": {
29
+ "endpoint": "s3.eu-de.cloud-object-storage.appdomain.cloud",
30
+ "paths": [
31
+ {
32
+ "bucket": "foc-deepsearch-s3-elastic",
33
+ "prefix": "deepsearch-elastic-dataplatform",
34
+ "infix": "cxs-8a1925c96f7b49508855ab270d0f3281"
35
+ }
36
+ ]
37
+ }
38
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-02.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "aliases": [
3
+ ".production",
4
+ "patent-uspto"
5
+ ],
6
+ "created": "2022-10-09T20:57:06.860+00:00",
7
+ "description": "Patents from the US Patent and Trade Office (USPTO)",
8
+ "source": "https://www.uspto.gov/",
9
+ "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-uspto-data",
10
+ "display_name": "Patents from USPTO",
11
+ "type": "Document",
12
+ "classification": [
13
+ "Public",
14
+ "PI"
15
+ ],
16
+ "version": [
17
+ {
18
+ "name": "docling-core",
19
+ "version": "1.0.1"
20
+ },
21
+ {
22
+ "name": "deepsearch-cxs",
23
+ "version": "1.0.0-alpha0.valid"
24
+ }
25
+ ],
26
+ "license": "https://www.uspto.gov/terms-use-uspto-websites",
27
+ "domain": [
28
+ "Science",
29
+ "Technology"
30
+ ],
31
+ "$ref": "ccs:schemas#/Document"
32
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-03.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "aliases": [
3
+ ".production",
4
+ "osm"
5
+ ],
6
+ "created": "2022-10-09T20:57:06.860+00:00",
7
+ "description": "OpenStreetMap dsata",
8
+ "source": "https://www.openstreetmap.org",
9
+ "storage": "crn:v1:bluemix:public:cloud-object-storage:global:a/a01ec3a49b79bf6abe91ea574f0f4715:fbb68e6e-2371-48e0-bfe3-4960a445df21:bucket:foc-deepsearch-osm-data",
10
+ "display_name": "OpenStreetMap",
11
+ "type": "Document",
12
+ "classification": [
13
+ "Public"
14
+ ],
15
+ "version": [
16
+ {
17
+ "name": "docling-core",
18
+ "version": "1.0.1"
19
+ },
20
+ {
21
+ "name": "deepsearch-cxs",
22
+ "version": "1.0.0-alpha0.valid"
23
+ }
24
+ ],
25
+ "license": "https://www.openstreetmap.org/copyright",
26
+ "domain": [
27
+ "Geography"
28
+ ]
29
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/search/meta-04.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "license": "",
3
+ "index_key": "07a32fab8e3cf827a1d6691fd530941485282dd7",
4
+ "created": "2023-11-28T15:10:08.226942+00:00",
5
+ "project_key": "9cd28d76ca3d0cc853edb23976f32b44f5739839",
6
+ "description": "",
7
+ "source": "",
8
+ "display_name": "",
9
+ "type": "Document",
10
+ "version": [
11
+ {
12
+ "name": "docling-core",
13
+ "version": "1.4.0"
14
+ }
15
+ ],
16
+ "$ref": "ccs:schemas#/Document"
17
+ }
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/viz/2408.09869v3_enriched.dt_viz_p2.png ADDED

Git LFS 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.png ADDED

Git LFS 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.png ADDED

Git LFS 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.png ADDED

Git LFS 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.png ADDED

Git LFS 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.png ADDED

Git LFS 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.png ADDED

Git LFS 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.png ADDED

Git LFS 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.png ADDED

Git LFS 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.png ADDED

Git LFS 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.png ADDED

Git LFS Details

  • SHA256: 3dd83855b42c1b6fd82cea824c41cf66bcdfd4f8f3a3cffded96c0dd65dc90c2
  • Pointer size: 131 Bytes
  • Size of remote file: 364 kB
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_01.vtt ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ WEBVTT
2
+
3
+ NOTE Copyright © 2019 World Wide Web Consortium. https://www.w3.org/TR/webvtt1/
4
+
5
+ 00:11.000 --> 00:13.000
6
+ <v Roger Bingham>We are in New York City
7
+
8
+ 00:13.000 --> 00:16.000
9
+ <v Roger Bingham>We’re actually at the Lucern Hotel, just down the street
10
+
11
+ 00:16.000 --> 00:18.000
12
+ <v Roger Bingham>from the American Museum of Natural History
13
+
14
+ 00:18.000 --> 00:20.000
15
+ <v Roger Bingham>And with me is Neil deGrasse Tyson
16
+
17
+ 00:20.000 --> 00:22.000
18
+ <v Roger Bingham>Astrophysicist, Director of the Hayden Planetarium
19
+
20
+ 00:22.000 --> 00:24.000
21
+ <v Roger Bingham>at the AMNH.
22
+
23
+ 00:24.000 --> 00:26.000
24
+ <v Roger Bingham>Thank you for walking down here.
25
+
26
+ 00:27.000 --> 00:30.000
27
+ <v Roger Bingham>And I want to do a follow-up on the last conversation we did.
28
+
29
+ 00:30.000 --> 00:31.500 align:right size:50%
30
+ <v Roger Bingham>When we e-mailed—
31
+
32
+ 00:30.500 --> 00:32.500 align:left size:50%
33
+ <v Neil deGrasse Tyson>Didn’t we talk about enough in that conversation?
34
+
35
+ 00:32.000 --> 00:35.500 align:right size:50%
36
+ <v Roger Bingham>No! No no no no; 'cos 'cos obviously 'cos
37
+
38
+ 00:32.500 --> 00:33.500 align:left size:50%
39
+ <v Neil deGrasse Tyson><i>Laughs</i>
40
+
41
+ 00:35.500 --> 00:38.000
42
+ <v Roger Bingham>You know I’m so excited my glasses are falling off here.
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_02.vtt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ WEBVTT
2
+
3
+ NOTE Copyright © 2019 World Wide Web Consortium. https://www.w3.org/TR/webvtt1/
4
+
5
+ 00:00.000 --> 00:02.000
6
+ <v.first.loud Esme>It’s a blue apple tree!
7
+
8
+ 00:02.000 --> 00:04.000
9
+ <v Mary>No way!
10
+
11
+ 00:04.000 --> 00:06.000
12
+ <v Esme>Hee!</v> <i>laughter</i>
13
+
14
+ 00:06.000 --> 00:08.000
15
+ <v.loud Mary>That’s awesome!
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_03.vtt ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ WEBVTT
2
+
3
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/15-0
4
+ 00:00:04.963 --> 00:00:08.571
5
+ <v Speaker A>OK,
6
+ I think now we should be recording</v>
7
+
8
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/15-1
9
+ 00:00:08.571 --> 00:00:09.403
10
+ <v Speaker A>properly.</v>
11
+
12
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/16-0
13
+ 00:00:10.683 --> 00:00:11.563
14
+ Good.
15
+
16
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/17-0
17
+ 00:00:13.363 --> 00:00:13.803
18
+ <v Speaker A>Yeah.</v>
19
+
20
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/78-0
21
+ 00:00:49.603 --> 00:00:53.363
22
+ <v Speaker B>I was also thinking.</v>
23
+
24
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/113-0
25
+ 00:00:54.963 --> 00:01:02.072
26
+ <v Speaker B>Would be maybe good to create items,</v>
27
+
28
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/113-1
29
+ 00:01:02.072 --> 00:01:06.811
30
+ <v Speaker B>some metadata,
31
+ some options that can be specific.</v>
32
+
33
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/150-0
34
+ 00:01:10.243 --> 00:01:13.014
35
+ <v Speaker A>Yeah,
36
+ I mean I think you went even more than</v>
37
+
38
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/119-0
39
+ 00:01:10.563 --> 00:01:12.643
40
+ <v Speaker B>But we preserved the atoms.</v>
41
+
42
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/150-1
43
+ 00:01:13.014 --> 00:01:15.907
44
+ <v Speaker A>than me.
45
+ I just opened the format.</v>
46
+
47
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/197-1
48
+ 00:01:50.222 --> 00:01:51.643
49
+ <v Speaker A>give it a try, yeah.</v>
50
+
51
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/200-0
52
+ 00:01:52.043 --> 00:01:55.043
53
+ <v Speaker B>Okay, talk to you later.</v>
54
+
55
+ 62357a1d-d250-41d5-a1cf-6cc0eeceffcc/202-0
56
+ 00:01:54.603 --> 00:01:55.283
57
+ <v Speaker A>See you.</v>
tasks/tasksmith-0ba04a338dbb/tests/source/tests/data/webvtt/webvtt_example_04.vtt ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ WEBVTT Danger of Nitrogen
2
+
3
+ NOTE Copyright © 2019 World Wide Web Consortium. https://www.w3.org/TR/webvtt1/
4
+
5
+ STYLE
6
+ ::cue {
7
+ background-image: linear-gradient(to bottom, dimgray, lightgray);
8
+ color: papayawhip;
9
+ }
10
+ /* Style blocks cannot use blank lines nor "dash dash greater than" */
11
+
12
+ REGION
13
+ id:editor-comments
14
+ width: 40%
15
+ regionanchor:0%,100%
16
+ viewportanchor:10%,90%
17
+
18
+ REGION
19
+ id:scroll
20
+ width: 40%
21
+ regionanchor:100%,100%
22
+ viewportanchor:90%,90%
23
+ scroll:up
24
+
25
+ 00:01.000 --> 00:04.000
26
+ Never drink liquid nitrogen.
27
+
28
+ NOTE I’m not sure the timing is right on the following cue.
29
+
30
+ 00:05.000 --> 00:09.000
31
+ — It will perforate your stomach.
32
+ — You could <b.loud>die</b>.
33
+ <v John>This is true.</v>
34
+
35
+ 00:10.000 --> 00:14.000
36
+ the<00:10.389> quick<00:10.750> brown<00:11.110> fox
tasks/tasksmith-0ba04a338dbb/tests/source/tests/doclang_validation.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers for validating DocLang XML against the reference doclang package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import Union
9
+
10
+ import pytest
11
+
12
+ try:
13
+ from doclang import ValidationError
14
+ from doclang import validate as doclang_validate
15
+ except ImportError:
16
+ doclang_validate = None # type: ignore[assignment,misc]
17
+ ValidationError = Exception # type: ignore[misc,assignment]
18
+
19
+
20
+ def doclang_validator_available() -> bool:
21
+ """Return True when the reference ``doclang`` package is importable."""
22
+ return doclang_validate is not None
23
+
24
+
25
+ doclang_validator = pytest.mark.skipif(
26
+ not doclang_validator_available(),
27
+ reason="reference doclang package not installed (uv sync --extra doclang-validation)",
28
+ )
29
+
30
+ xfail_invalid_dclg_xml = pytest.mark.xfail(
31
+ reason="Serializer output fails DocLang reference validation (known bug)",
32
+ raises=ValidationError,
33
+ strict=False,
34
+ )
35
+
36
+
37
+ def assert_valid_dclg_xml(
38
+ xml_text: str,
39
+ *,
40
+ allow_empty_namespace: bool = True,
41
+ ) -> None:
42
+ """Validate DocLang XML; no-op when the reference validator is not installed."""
43
+ if doclang_validate is None:
44
+ return
45
+ with tempfile.NamedTemporaryFile(
46
+ mode="w",
47
+ suffix=".dclg.xml",
48
+ delete=False,
49
+ encoding="utf-8",
50
+ ) as tmp:
51
+ tmp.write(xml_text)
52
+ path = tmp.name
53
+ try:
54
+ doclang_validate(path, allow_empty_namespace=allow_empty_namespace)
55
+ finally:
56
+ os.unlink(path)
57
+
58
+
59
+ def validate_dclg_xml(
60
+ xml_text: str,
61
+ *,
62
+ allow_empty_namespace: bool = True,
63
+ ) -> None:
64
+ """Validate DocLang XML text; raises on failure when validator is available."""
65
+ if doclang_validate is None:
66
+ pytest.skip("reference doclang package not installed")
67
+
68
+ with tempfile.NamedTemporaryFile(
69
+ mode="w",
70
+ suffix=".dclg.xml",
71
+ delete=False,
72
+ encoding="utf-8",
73
+ ) as tmp:
74
+ tmp.write(xml_text)
75
+ path = tmp.name
76
+
77
+ try:
78
+ doclang_validate(path, allow_empty_namespace=allow_empty_namespace)
79
+ finally:
80
+ os.unlink(path)
81
+
82
+
83
+ def validate_dclg_file(
84
+ path: str | Path,
85
+ *,
86
+ allow_empty_namespace: bool = True,
87
+ ) -> None:
88
+ """Validate a DocLang XML file path."""
89
+ if doclang_validate is None:
90
+ pytest.skip("reference doclang package not installed")
91
+ doclang_validate(Path(path), allow_empty_namespace=allow_empty_namespace)
92
+
93
+
94
+ def assert_invalid_dclg_xml(
95
+ xml_text: str,
96
+ *,
97
+ allow_empty_namespace: bool = True,
98
+ ) -> None:
99
+ """Assert DocLang XML is rejected by the reference validator (known bad output)."""
100
+ if doclang_validate is None:
101
+ pytest.skip("reference doclang package not installed")
102
+ with pytest.raises(ValidationError):
103
+ validate_dclg_xml(xml_text, allow_empty_namespace=allow_empty_namespace)
tasks/tasksmith-0ba04a338dbb/tests/source/tests/tasksmith_behavior.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from docling_core.types.doc.items.table.table_data import TableData, TableCell
3
+
4
+
5
+ def _make_table(num_rows: int = 4, num_cols: int = 2) -> TableData:
6
+ cells = [
7
+ TableCell(
8
+ text=f"r{i}c{j}",
9
+ start_row_offset_idx=i,
10
+ end_row_offset_idx=i + 1,
11
+ start_col_offset_idx=j,
12
+ end_col_offset_idx=j + 1,
13
+ )
14
+ for i in range(num_rows)
15
+ for j in range(num_cols)
16
+ ]
17
+ return TableData(num_rows=num_rows, num_cols=num_cols, table_cells=cells)
18
+
19
+
20
+ def test_remove_rows_empty_list_is_noop():
21
+ data = _make_table()
22
+ result = data.remove_rows([])
23
+ assert result == []
24
+ assert data.num_rows == 4
25
+ assert [c.text for row in data.grid for c in row] == [
26
+ "r0c0", "r0c1", "r1c0", "r1c1", "r2c0", "r2c1", "r3c0", "r3c1"
27
+ ]
28
+
29
+
30
+ def test_remove_rows_out_of_bounds_raises():
31
+ data = _make_table()
32
+ with pytest.raises(IndexError):
33
+ data.remove_rows([10])
34
+
35
+
36
+ def test_remove_rows_negative_index_raises():
37
+ data = _make_table()
38
+ with pytest.raises(IndexError):
39
+ data.remove_rows([-1])
40
+
41
+
42
+ def test_remove_rows_distinct_indices():
43
+ data = _make_table()
44
+ removed = data.remove_rows([0, 2])
45
+ assert data.num_rows == 2
46
+ remaining = [c.text for row in data.grid for c in row]
47
+ assert remaining == ["r1c0", "r1c1", "r3c0", "r3c1"]
48
+ # Two distinct rows were removed
49
+ all_removed_texts = [c.text for row in removed for c in row]
50
+ assert set(all_removed_texts) == {"r0c0", "r0c1", "r2c0", "r2c1"}
51
+
52
+
53
+ def test_remove_rows_duplicate_indices_removes_once():
54
+ data = _make_table()
55
+ removed = data.remove_rows([1, 1])
56
+ # Only one row removed
57
+ assert [[c.text for c in row] for row in removed] == [["r1c0", "r1c1"]]
58
+ assert data.num_rows == 3
59
+ assert [c.text for row in data.grid for c in row] == [
60
+ "r0c0", "r0c1", "r2c0", "r2c1", "r3c0", "r3c1"
61
+ ]
62
+
63
+
64
+ def test_remove_rows_many_duplicates():
65
+ data = _make_table()
66
+ removed = data.remove_rows([2, 2, 2])
67
+ assert len(removed) == 1
68
+ assert [c.text for c in removed[0]] == ["r2c0", "r2c1"]
69
+ assert data.num_rows == 3
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_azure_serializer.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for AzureDocSerializer."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from docling_core.transforms.serializer.azure import AzureDocSerializer, AzureParams
8
+ from docling_core.types.doc.base import BoundingBox, CoordOrigin, Size
9
+ from docling_core.types.doc.document import (
10
+ DocItemLabel,
11
+ DoclingDocument,
12
+ ProvenanceItem,
13
+ )
14
+
15
+ from .test_data_gen_flag import GEN_TEST_DATA
16
+
17
+
18
+ def _assert_json_like_equal(a: Any, b: Any, eps: float = 1e-3, path: str = "$") -> None:
19
+ """Recursively assert two JSON-like structures are equal with float tolerance.
20
+
21
+ Rules:
22
+ - Dicts: same keys; compare values recursively
23
+ - Lists: same length; compare elements in order
24
+ - Numbers: ints compare by ==; floats (or int-vs-float) compare within eps
25
+ - Strings/bools/null: compare by ==
26
+
27
+ The `path` argument is used to provide helpful assertion locations.
28
+ """
29
+ # Handle dicts
30
+ if isinstance(a, dict) and isinstance(b, dict):
31
+ a_keys, b_keys = set(a.keys()), set(b.keys())
32
+ assert a_keys == b_keys, f"Key mismatch at {path}: {a_keys ^ b_keys}"
33
+ for k in sorted(a_keys):
34
+ _assert_json_like_equal(a[k], b[k], eps=eps, path=f"{path}.{k}")
35
+ return
36
+
37
+ # Handle lists
38
+ if isinstance(a, list) and isinstance(b, list):
39
+ assert len(a) == len(b), f"List length mismatch at {path}: {len(a)} != {len(b)}"
40
+ for i, (ai, bi) in enumerate(zip(a, b)):
41
+ _assert_json_like_equal(ai, bi, eps=eps, path=f"{path}[{i}]")
42
+ return
43
+
44
+ # Handle numbers (int/float)
45
+ num_types = (int, float)
46
+ if isinstance(a, num_types) and isinstance(b, num_types):
47
+ # If either is float, compare with tolerance; if both int, exact match
48
+ if isinstance(a, float) or isinstance(b, float):
49
+ diff = abs(float(a) - float(b))
50
+ assert diff <= eps, f"Float mismatch at {path}: {a} != {b} (diff={diff}, eps={eps})"
51
+ else:
52
+ assert a == b, f"Int mismatch at {path}: {a} != {b}"
53
+ return
54
+
55
+ # Handle strings, bools, and None
56
+ if isinstance(a, (str, bool)) or a is None:
57
+ assert a == b, f"Value mismatch at {path}: {a!r} != {b!r}"
58
+ return
59
+
60
+ # Fallback: types must match and then equality
61
+ assert type(a) is type(b), f"Type mismatch at {path}: {type(a)} != {type(b)}"
62
+ assert a == b, f"Mismatch at {path}: {a!r} != {b!r}"
63
+
64
+
65
+ def _verify_json(exp_file: Path, actual_json: str) -> None:
66
+ """Verify Azure JSON string against ground-truth file with generation support.
67
+
68
+ Compares parsed JSON structures and tolerates tiny float differences.
69
+ """
70
+ if GEN_TEST_DATA:
71
+ # Keep writing the canonical serialized string for determinism
72
+ exp_file.write_text(actual_json + "\n", encoding="utf-8")
73
+ else:
74
+ expected_text = exp_file.read_text(encoding="utf-8").rstrip()
75
+ expected_obj = json.loads(expected_text)
76
+ actual_obj = json.loads(actual_json)
77
+ _assert_json_like_equal(expected_obj, actual_obj, eps=1e-3)
78
+
79
+
80
+ def test_azure_serialize_activities_doc():
81
+ """Serialize a GT document (activities.json) and verify Azure JSON output."""
82
+ src = Path("./tests/data/doc/activities.json")
83
+ doc = DoclingDocument.load_from_json(src)
84
+
85
+ ser = AzureDocSerializer(doc=doc, params=AzureParams(indent=2))
86
+ actual_json = ser.serialize().text
87
+
88
+ # Sanity-check the JSON structure
89
+ data = json.loads(actual_json)
90
+ assert isinstance(data, dict)
91
+ assert "pages" in data and isinstance(data["pages"], list)
92
+ assert "tables" in data and isinstance(data["tables"], list)
93
+ assert "figures" in data and isinstance(data["figures"], list)
94
+ assert "paragraphs" in data and isinstance(data["paragraphs"], list)
95
+
96
+ _verify_json(exp_file=src.with_suffix(".gt.azure.json"), actual_json=actual_json)
97
+
98
+
99
+ def test_azure_serialize_construct_doc_minimal_prov(sample_doc: DoclingDocument):
100
+ """Serialize a constructed document with minimal provenance to Azure JSON.
101
+
102
+ The sample_doc fixture does not attach provenance or pages; here we add a
103
+ single page and minimal bounding boxes to a subset of items to allow Azure JSON
104
+ output to include paragraphs/tables/pictures with boundingRegions.
105
+ """
106
+ # Ensure at least one page is present
107
+ if not sample_doc.pages:
108
+ sample_doc.add_page(page_no=1, size=Size(width=600.0, height=800.0), image=None)
109
+
110
+ # Helper to add a simple TOPLEFT bbox provenance if missing
111
+ def _ensure_prov(item, l=10.0, t=10.0, r=200.0, b=40.0):
112
+ if not item.prov:
113
+ item.prov = [
114
+ ProvenanceItem(
115
+ page_no=min(sample_doc.pages.keys()),
116
+ bbox=BoundingBox(l=l, t=t, r=r, b=b, coord_origin=CoordOrigin.TOPLEFT),
117
+ charspan=(0, 0),
118
+ )
119
+ ]
120
+
121
+ # Add provenance for the title and a couple of paragraphs if present
122
+ for it in sample_doc.texts[:3]:
123
+ if it.label in {
124
+ DocItemLabel.TITLE,
125
+ DocItemLabel.TEXT,
126
+ DocItemLabel.SECTION_HEADER,
127
+ }:
128
+ _ensure_prov(it)
129
+
130
+ # Add provenance for the first table if present
131
+ if sample_doc.tables:
132
+ _ensure_prov(sample_doc.tables[0], l=20.0, t=80.0, r=300.0, b=200.0)
133
+
134
+ # Add provenance for the first picture if present
135
+ if sample_doc.pictures:
136
+ _ensure_prov(sample_doc.pictures[0], l=320.0, t=80.0, r=500.0, b=220.0)
137
+
138
+ ser = AzureDocSerializer(doc=sample_doc, params=AzureParams(indent=2))
139
+ actual_json = ser.serialize().text
140
+
141
+ # Basic structure check
142
+ data = json.loads(actual_json)
143
+ assert isinstance(data, dict)
144
+ assert "pages" in data and isinstance(data["pages"], list) and len(data["pages"]) >= 1
145
+ assert "paragraphs" in data and isinstance(data["paragraphs"], list)
146
+
147
+ exp_file = Path("./tests/data/doc/constructed.gt.azure.json")
148
+ _verify_json(exp_file=exp_file, actual_json=actual_json)
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_base.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test the pydantic models in module data_types.base.py."""
2
+
3
+ from datetime import datetime, timezone
4
+
5
+ import pytest
6
+ from pydantic import BaseModel, ValidationError
7
+
8
+ from docling_core.types.base import StrictDateTime
9
+
10
+
11
+ def test_strict_date_time() -> None:
12
+ """Validate data with StrictDateTime model."""
13
+
14
+ class Model(BaseModel):
15
+ published: StrictDateTime
16
+
17
+ # allowed formats
18
+ Model(published=datetime.now(tz=timezone.utc))
19
+
20
+ data = Model(published="2022-12-01T03:49:20.724435+00:00")
21
+ assert data.published.isoformat() == "2022-12-01T03:49:20.724435+00:00"
22
+
23
+ data = Model(published="2022-12-01T03:49:20.724435+03:00")
24
+ assert data.published.isoformat() == "2022-12-01T03:49:20.724435+03:00"
25
+
26
+ data = Model(published="2022-12-01T03:49:20.724435Z")
27
+ assert data.published.isoformat() == "2022-12-01T03:49:20.724435+00:00"
28
+
29
+ data = Model(published="2022-12-01T03:49:20")
30
+ assert data.published.isoformat() == "2022-12-01T03:49:20"
31
+
32
+ data = Model(published="2022-12-01")
33
+ assert data.published.isoformat() == "2022-12-01T00:00:00"
34
+
35
+ # invalid formats
36
+ with pytest.raises(ValidationError, match="published"):
37
+ Model(published="03:49:20")
38
+
39
+ with pytest.raises(ValidationError, match="published"):
40
+ Model(published=1679616000.0)
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_chunk_expander.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for chunk expander classes."""
2
+
3
+ import pytest
4
+
5
+ from docling_core.transforms.chunker.chunk_expander import PageChunkExpander, TreeChunkExpander
6
+ from docling_core.transforms.chunker.doc_chunk import DocChunk, DocMeta
7
+ from docling_core.transforms.chunker.hierarchical_chunker import ChunkingDocSerializer, ChunkingSerializerProvider
8
+ from docling_core.transforms.chunker.hybrid_chunker import HybridChunker
9
+ from docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizer
10
+ from docling_core.transforms.serializer.markdown import MarkdownTableSerializer
11
+ from docling_core.types.doc import DocItemLabel, DoclingDocument, Size
12
+ from docling_core.types.doc.document import TableData
13
+
14
+ EMBED_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"
15
+ MAX_TOKENS = 50
16
+
17
+
18
+ def check_lines_equal_in_order(text_a: str, text_b: str) -> bool:
19
+ """Check if lines of string A are equal to lines of string B in the same order.
20
+
21
+ This function splits both strings into lines and verifies that:
22
+ 1. All lines from A appear in B
23
+ 2. They appear in the same order
24
+ 3. Lines can be non-consecutive in B (other lines can appear between them)
25
+
26
+ Args:
27
+ text_a: First string (subset) to check
28
+ text_b: Second string (superset) to check against
29
+
30
+ Returns:
31
+ True if all lines of A appear in B in the same order, False otherwise
32
+ """
33
+ if not isinstance(text_a, str) or not isinstance(text_b, str):
34
+ raise TypeError("Both inputs must be strings.")
35
+
36
+ lines_a = [line for line in text_a.splitlines() if line.strip()]
37
+ lines_b = [line for line in text_b.splitlines() if line.strip()]
38
+
39
+ # If A is empty, it's always contained in B
40
+ if not lines_a:
41
+ return True
42
+
43
+ # If B is empty but A is not, A cannot be contained in B
44
+ if not lines_b:
45
+ return False
46
+
47
+ # Track position in B
48
+ b_index = 0
49
+
50
+ # Try to find each line of A in B in order
51
+ for line_a in lines_a:
52
+ found = False
53
+ # Search for line_a starting from current position in B
54
+ while b_index < len(lines_b):
55
+ if lines_b[b_index] == line_a:
56
+ found = True
57
+ b_index += 1 # Move to next position in B
58
+ break
59
+ b_index += 1
60
+
61
+ # If we couldn't find this line of A in B, return False
62
+ if not found:
63
+ return False
64
+
65
+ return True
66
+
67
+
68
+ @pytest.fixture
69
+ def sample_doc():
70
+ """Create a comprehensive sample document for testing with pages and various content types.
71
+
72
+ Content is associated with pages through ProvenanceItem which includes page_no.
73
+ When add_text/add_heading is called with prov parameter containing page_no,
74
+ that content is associated with that specific page.
75
+ """
76
+ from docling_core.types.doc.document import BoundingBox, ProvenanceItem
77
+
78
+ doc = DoclingDocument(name="test_doc")
79
+
80
+ # Add pages
81
+ doc.add_page(size=Size(width=612, height=792), page_no=1)
82
+ doc.add_page(size=Size(width=612, height=792), page_no=2)
83
+
84
+ # Section 1 on page 1 (explicitly set page_no in prov)
85
+ doc.add_heading(
86
+ text="Section 1",
87
+ level=1,
88
+ prov=ProvenanceItem(page_no=1, bbox=BoundingBox(l=50, t=50, r=550, b=80), charspan=(0, 9)),
89
+ )
90
+ doc.add_text(
91
+ text="This is the first paragraph.",
92
+ label=DocItemLabel.PARAGRAPH,
93
+ prov=ProvenanceItem(page_no=1, bbox=BoundingBox(l=50, t=90, r=550, b=120), charspan=(10, 38)),
94
+ )
95
+ doc.add_text(
96
+ text="This is the second paragraph.",
97
+ label=DocItemLabel.PARAGRAPH,
98
+ prov=ProvenanceItem(page_no=1, bbox=BoundingBox(l=50, t=130, r=550, b=160), charspan=(39, 68)),
99
+ )
100
+
101
+ # Section 2 on page 2 with list (explicitly set page_no=2 in prov)
102
+ doc.add_heading(
103
+ text="Section 2",
104
+ level=1,
105
+ prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=50, t=50, r=550, b=80), charspan=(69, 78)),
106
+ )
107
+ doc.add_text(
108
+ text="Content in section 2.",
109
+ label=DocItemLabel.PARAGRAPH,
110
+ prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=50, t=90, r=550, b=120), charspan=(79, 100)),
111
+ )
112
+
113
+ # Add a list in section 2 on page 2
114
+ list_group = doc.add_list_group()
115
+ doc.add_list_item(
116
+ text="First list item",
117
+ enumerated=False,
118
+ parent=list_group,
119
+ prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=70, t=130, r=550, b=150), charspan=(101, 116)),
120
+ )
121
+ doc.add_list_item(
122
+ text="Second list item",
123
+ enumerated=False,
124
+ parent=list_group,
125
+ prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=70, t=160, r=550, b=180), charspan=(117, 133)),
126
+ )
127
+ doc.add_list_item(
128
+ text="Third list item",
129
+ enumerated=False,
130
+ parent=list_group,
131
+ prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=70, t=190, r=550, b=210), charspan=(134, 149)),
132
+ )
133
+
134
+ # Add a table on page 2
135
+ table_data = TableData(num_cols=2)
136
+ table_data.add_row(["Header 1", "Header 2"])
137
+ table_data.add_row(["Value 1", "Value 2"])
138
+ table_data.add_row(["Value 3", "Value 4"])
139
+ table_data.add_row(["Value 5", "Value 6"])
140
+ doc.add_table(
141
+ data=table_data,
142
+ prov=ProvenanceItem(page_no=2, bbox=BoundingBox(l=50, t=220, r=550, b=300), charspan=(150, 200)),
143
+ )
144
+
145
+ return doc
146
+
147
+
148
+ class MarkdownSerializerProvider(ChunkingSerializerProvider):
149
+ def get_serializer(self, doc: DoclingDocument):
150
+ return ChunkingDocSerializer(
151
+ doc=doc,
152
+ table_serializer=MarkdownTableSerializer(),
153
+ )
154
+
155
+
156
+ @pytest.fixture
157
+ def hybrid_chunker():
158
+ """Create a reusable HybridChunker instance."""
159
+ return HybridChunker(
160
+ tokenizer=HuggingFaceTokenizer.from_pretrained(
161
+ model_name=EMBED_MODEL_ID,
162
+ max_tokens=MAX_TOKENS,
163
+ ),
164
+ serializer_provider=MarkdownSerializerProvider(),
165
+ repeat_table_header=True,
166
+ )
167
+
168
+
169
+ @pytest.fixture
170
+ def sample_chunks(sample_doc, hybrid_chunker):
171
+ """Create chunks from sample_doc once and cache them."""
172
+ chunks = list(hybrid_chunker.chunk(dl_doc=sample_doc))
173
+ assert len(chunks) > 0, "Expected at least one chunk to be created"
174
+ return chunks
175
+
176
+
177
+ @pytest.fixture
178
+ def sample_serializer(sample_doc, hybrid_chunker):
179
+ """Create serializer for sample_doc once and cache it."""
180
+ return hybrid_chunker.serializer_provider.get_serializer(sample_doc)
181
+
182
+
183
+ @pytest.fixture
184
+ def tree_expander():
185
+ """Create a TreeChunkExpander instance."""
186
+ return TreeChunkExpander()
187
+
188
+
189
+ @pytest.fixture
190
+ def page_expander():
191
+ """Create a PageChunkExpander instance."""
192
+ return PageChunkExpander()
193
+
194
+
195
+ class TestTreeChunkExpander:
196
+ """Tests for TreeChunkExpander class methods."""
197
+
198
+ # helper method: recursively traverse top item children to find chunk items
199
+ def _find_chunk_item_in_descendants(self, item, doc, target_refs):
200
+ """Recursively check if any target_refs are in item's descendants."""
201
+ # Check if this item itself is a target
202
+ if item.self_ref in target_refs:
203
+ return True
204
+
205
+ # Check children if item has them
206
+ if hasattr(item, "children") and item.children:
207
+ for child_ref in item.children:
208
+ child = child_ref.resolve(doc)
209
+ if self._find_chunk_item_in_descendants(child, doc, target_refs):
210
+ return True
211
+
212
+ return False
213
+
214
+ def test_get_top_items_basic(self, sample_doc, sample_chunks):
215
+ """Test getting top-level items from a chunk."""
216
+ assert len(sample_chunks) > 0, "Should have at least one chunk"
217
+
218
+ for chunk in sample_chunks:
219
+ if not isinstance(chunk, DocChunk):
220
+ continue
221
+
222
+ top_items = TreeChunkExpander._get_top_containing_items(chunk.meta, sample_doc)
223
+
224
+ assert top_items is not None, "Should return top items"
225
+ assert len(top_items) > 0, "Should have at least one top item"
226
+
227
+ # Verify all returned items are direct children of body
228
+ for item in top_items:
229
+ assert item.parent == sample_doc.body.get_ref(), f"Item {item.self_ref} should be direct child of body"
230
+
231
+ # Verify that at least one doc_item from the chunk is a descendant of a top item
232
+ chunk_item_refs = {item.self_ref for item in chunk.meta.doc_items}
233
+
234
+ for top_item in top_items:
235
+ assert self._find_chunk_item_in_descendants(top_item, sample_doc, chunk_item_refs), (
236
+ f"Could not find any chunk items in descendants of top item {top_item.self_ref}"
237
+ )
238
+
239
+ def test_get_top_items_maintains_order(self, sample_doc, sample_chunks):
240
+ """Test that top items maintain document reading order."""
241
+ for chunk in sample_chunks:
242
+ if not isinstance(chunk, DocChunk):
243
+ continue
244
+
245
+ top_items = TreeChunkExpander._get_top_containing_items(chunk.meta, sample_doc)
246
+ if top_items and len(top_items) > 1:
247
+ # Get the order in the document body
248
+ body_refs = [ref.cref for ref in sample_doc.body.children]
249
+ top_refs = [item.self_ref for item in top_items]
250
+
251
+ # Verify order is maintained
252
+ prev_idx = -1
253
+ for ref in top_refs:
254
+ curr_idx = body_refs.index(ref)
255
+ assert curr_idx > prev_idx, "Items should maintain reading order"
256
+ prev_idx = curr_idx
257
+
258
+ def test_get_top_items_empty_chunk(self):
259
+ """Test _get_top_containing_items with chunk containing non-body items."""
260
+ doc = DoclingDocument(name="empty_doc")
261
+ text_item = doc.add_text(text="Some text", label=DocItemLabel.PARAGRAPH)
262
+
263
+ # Create a chunk with a doc item that doesn't have proper parent
264
+ # This simulates an edge case where get_top_containing_items might return None
265
+ meta = DocMeta(doc_items=[text_item])
266
+
267
+ # Should return the text item as top item since it's a direct child of body
268
+ result = TreeChunkExpander._get_top_containing_items(meta, doc)
269
+ assert result is not None, "Should return top items for valid doc_items"
270
+ assert len(result) > 0, "Should have at least one top item"
271
+
272
+ def test_expand_basic(self, sample_doc, sample_serializer, sample_chunks, tree_expander):
273
+ """Test basic expansion to full items."""
274
+ for chunk in sample_chunks:
275
+ if not isinstance(chunk, DocChunk):
276
+ continue
277
+
278
+ expanded = tree_expander.expand(chunk=chunk, dl_doc=sample_doc, serializer=sample_serializer)
279
+
280
+ assert expanded is not None, "Should return expanded chunk"
281
+ assert isinstance(expanded, DocChunk), "Should return DocChunk instance"
282
+
283
+ # Expanded chunk should have content
284
+ assert len(expanded.text.strip()) > 0, "Expanded chunk should have text"
285
+
286
+ # Expanded chunk text should contain original chunk text (or be a superset)
287
+ assert check_lines_equal_in_order(chunk.text, expanded.text), (
288
+ f"Expanded chunk should contain original chunk text. original: {chunk.text} expanded: {expanded.text}"
289
+ )
290
+ assert expanded.meta.origin == chunk.meta.origin, "Origin should be preserved"
291
+
292
+ def test_expand_error_handling(self, sample_doc, tree_expander):
293
+ """Test error handling in expand when serialization fails."""
294
+
295
+ # Create a mock serializer that raises an exception
296
+ class FailingSerializer:
297
+ def serialize(self, item):
298
+ raise RuntimeError("Serialization failed")
299
+
300
+ # Create a chunk with valid doc items
301
+ text_item = sample_doc.texts[0]
302
+ meta = DocMeta(doc_items=[text_item])
303
+ chunk = DocChunk(text="original text", meta=meta)
304
+
305
+ # Call expand with failing serializer
306
+ # Should catch the exception and return original chunk
307
+ with pytest.warns(UserWarning, match="did not yield any text"):
308
+ expanded = tree_expander.expand(chunk=chunk, dl_doc=sample_doc, serializer=FailingSerializer())
309
+
310
+ # Should return original chunk when serialization fails
311
+ assert expanded == chunk, "Should return original chunk when serialization fails"
312
+
313
+
314
+ class TestPageChunkExpander:
315
+ """Tests for PageChunkExpander.expand method."""
316
+
317
+ def test_expand_basic(self, sample_doc, sample_chunks, sample_serializer, page_expander):
318
+ """Test that page expansion includes all page content."""
319
+ for chunk in sample_chunks:
320
+ if not isinstance(chunk, DocChunk):
321
+ continue
322
+
323
+ # Get page numbers from chunk
324
+ page_ids = [i.page_no for item in chunk.meta.doc_items for i in item.prov]
325
+
326
+ if page_ids:
327
+ expanded = page_expander.expand(chunk=chunk, dl_doc=sample_doc, serializer=sample_serializer)
328
+ assert expanded is not None, "Should return expanded chunk"
329
+ assert isinstance(expanded, DocChunk), "Should return DocChunk"
330
+ # Expanded text should contain page content
331
+ assert len(expanded.text) > 0, "Expanded chunk should have text"
332
+
333
+ # Verify it contains original
334
+ assert check_lines_equal_in_order(chunk.text, expanded.text), "Expanded text should contain original"
335
+
336
+ # Metadata fields should be updated with expanded content
337
+ assert expanded.meta.origin == chunk.meta.origin, "Expanded chunk should have metadata"
338
+
339
+ def get_ref_items(chunk: DocChunk):
340
+ return [item.self_ref for item in chunk.meta.doc_items]
341
+
342
+ assert set(get_ref_items(chunk)).issubset(get_ref_items(expanded)), (
343
+ "Expanded chunk should have at least as many doc_items as original"
344
+ )
345
+
346
+ def test_expand_no_pages(self, hybrid_chunker, page_expander):
347
+ """Test expand when document has no pages for all chunks."""
348
+ # Create a document without pages
349
+ doc_no_pages = DoclingDocument(name="no_pages_doc")
350
+ doc_no_pages.add_heading(text="Section 1", level=1)
351
+ doc_no_pages.add_text(text="Some content.", label=DocItemLabel.PARAGRAPH)
352
+
353
+ chunks = list(hybrid_chunker.chunk(dl_doc=doc_no_pages))
354
+ serializer = hybrid_chunker.serializer_provider.get_serializer(doc_no_pages)
355
+
356
+ assert len(chunks) > 0, "Should have at least one chunk"
357
+
358
+ for chunk in chunks:
359
+ if not isinstance(chunk, DocChunk):
360
+ continue
361
+
362
+ with pytest.warns(UserWarning, match="Cannot expand to page"):
363
+ result = page_expander.expand(chunk=chunk, dl_doc=doc_no_pages, serializer=serializer)
364
+
365
+ # Should return original chunk when no pages
366
+ assert result == chunk, "Should return original chunk when document has no pages"
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_cli_serialize.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``docling-serialize`` CLI."""
2
+
3
+ import zipfile
4
+ from pathlib import Path
5
+
6
+ from click import unstyle
7
+ from typer.testing import CliRunner
8
+
9
+ from docling_core.cli.serialize import app
10
+ from docling_core.types.doc import DoclingDocument
11
+
12
+ DOC_LANG_ARCHIVE_FIXTURE = Path("tests/data/doc/doclang_archive/save/two_pages.json")
13
+
14
+
15
+ def test_serialize_json_to_dclx_packages_images(tmp_path: Path) -> None:
16
+ """DCLX output packages page rasters and picture assets."""
17
+ output = tmp_path / "nested" / "two_pages.dclx"
18
+
19
+ result = CliRunner().invoke(
20
+ app,
21
+ [str(DOC_LANG_ARCHIVE_FIXTURE), "--to", "dclx", "--output", str(output)],
22
+ )
23
+
24
+ assert result.exit_code == 0, result.output
25
+ assert output.is_file()
26
+ assert f"Wrote {output}" in result.output
27
+
28
+ with zipfile.ZipFile(output) as archive:
29
+ names = archive.namelist()
30
+ assert "document.xml" in names
31
+ assert "pages/1.png" in names
32
+ assert "pages/2.png" in names
33
+ assert any(name.startswith("assets/") for name in names)
34
+
35
+ loaded = DoclingDocument.load_from_doclang_archive(
36
+ output,
37
+ artifacts_dir=tmp_path / "loaded",
38
+ )
39
+ assert len(loaded.pages) == 2
40
+ assert loaded.pictures
41
+ assert loaded.pictures[0].image is not None
42
+ assert loaded.pictures[0].image.pil_image is not None
43
+
44
+
45
+ def test_serialize_dclx_requires_output_path() -> None:
46
+ """Binary DCLX output is not written to standard output."""
47
+ result = CliRunner().invoke(
48
+ app,
49
+ [str(DOC_LANG_ARCHIVE_FIXTURE), "--to", "dclx"],
50
+ )
51
+
52
+ assert result.exit_code == 2
53
+ assert "--output is required when --to dclx" in unstyle(result.output)
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunker.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import pathlib
6
+ import sys
7
+ from typing import Optional
8
+
9
+ import git
10
+ import pytest
11
+
12
+ from docling_core.transforms.chunker.code_chunking._utils import _get_file_extensions
13
+ from docling_core.transforms.chunker.code_chunking.code_chunk import CodeChunk
14
+ from docling_core.transforms.chunker.code_chunking.standard_code_chunking_strategy import (
15
+ StandardCodeChunkingStrategy,
16
+ )
17
+ from docling_core.transforms.chunker.hierarchical_chunker import HierarchicalChunker
18
+ from docling_core.types.doc import DoclingDocument, DocumentOrigin
19
+ from docling_core.types.doc.labels import CodeLanguageLabel, DocItemLabel
20
+
21
+ from .test_data_gen_flag import GEN_TEST_DATA
22
+
23
+
24
+ def _create_hash(string: str) -> str:
25
+ """Return a SHA-256 hex digest of the given string."""
26
+ hasher = hashlib.sha256(usedforsecurity=False)
27
+ hasher.update(string.encode("utf-8"))
28
+ return hasher.hexdigest()
29
+
30
+
31
+ def get_latest_commit_id(file_dir: str) -> str:
32
+ """Returns the latest commit ID in the given Git repository directory."""
33
+ try:
34
+ repo = git.Repo(file_dir, search_parent_directories=True)
35
+ return repo.head.commit.hexsha
36
+ except Exception:
37
+ return ""
38
+
39
+
40
+ def create_documents_from_repository(
41
+ file_dir: str,
42
+ repo_url: str,
43
+ language: CodeLanguageLabel,
44
+ commit_id: str | None = None,
45
+ ) -> list[DoclingDocument]:
46
+ """Build DoclingDocument objects from a local checkout, one per code file."""
47
+ documents: list[DoclingDocument] = []
48
+ if commit_id is None:
49
+ commit_id = get_latest_commit_id(file_dir)
50
+
51
+ all_extensions = set()
52
+ for lang in [
53
+ CodeLanguageLabel.PYTHON,
54
+ CodeLanguageLabel.TYPESCRIPT,
55
+ CodeLanguageLabel.JAVASCRIPT,
56
+ CodeLanguageLabel.C,
57
+ CodeLanguageLabel.JAVA,
58
+ ]:
59
+ all_extensions.update(_get_file_extensions(lang))
60
+
61
+ all_files = []
62
+ for extension in all_extensions:
63
+ all_files.extend(sorted(glob.glob(f"{file_dir}/**/*{extension}", recursive=True)))
64
+
65
+ all_files = sorted(set(all_files))
66
+
67
+ for file_path in all_files:
68
+ with open(file_path, encoding="utf-8") as f:
69
+ file_content = f.read()
70
+
71
+ file_relative = os.path.relpath(file_path, start=file_dir).replace("\\", "/")
72
+
73
+ origin = DocumentOrigin(
74
+ filename=file_relative,
75
+ uri=(f"{repo_url}/blob/{commit_id}/{file_relative}" if commit_id else f"{repo_url}/{file_relative}"),
76
+ mimetype="text/plain",
77
+ binary_hash=_create_hash(file_content),
78
+ )
79
+
80
+ doc = DoclingDocument(name=file_relative, origin=origin)
81
+ doc.add_code(text=file_content, code_language=language)
82
+ documents.append(doc)
83
+
84
+ return documents
85
+
86
+
87
+ HERE = pathlib.Path(__file__).parent
88
+ DATA = HERE / "data" / "chunker_repo"
89
+ DATA.mkdir(parents=True, exist_ok=True)
90
+
91
+ REPO_SPECS = [
92
+ (
93
+ "Java",
94
+ "/tests/data/chunker_repo/repos/acmeair",
95
+ "https://github.com/acmeair/acmeair",
96
+ lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)),
97
+ ),
98
+ (
99
+ "TypeScript",
100
+ "/tests/data/chunker_repo/repos/outline",
101
+ "https://github.com/outline/outline",
102
+ lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)),
103
+ ),
104
+ (
105
+ "JavaScript",
106
+ "/tests/data/chunker_repo/repos/jquery",
107
+ "https://github.com/jquery/jquery",
108
+ lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)),
109
+ ),
110
+ (
111
+ "Python",
112
+ "/tests/data/chunker_repo/repos/docling",
113
+ "https://github.com/docling-project/docling",
114
+ lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)),
115
+ ),
116
+ (
117
+ "C",
118
+ "/tests/data/chunker_repo/repos/json-c",
119
+ "https://github.com/json-c/json-c",
120
+ lambda: HierarchicalChunker(code_chunking_strategy=StandardCodeChunkingStrategy(max_tokens=5000)),
121
+ ),
122
+ ]
123
+
124
+
125
+ def _dump_or_assert(act_data: dict, out_path: pathlib.Path):
126
+ out_path.parent.mkdir(parents=True, exist_ok=True)
127
+ if GEN_TEST_DATA:
128
+ with out_path.open("w", encoding="utf-8") as f:
129
+ json.dump(act_data, fp=f, indent=4)
130
+ f.write("\n")
131
+ else:
132
+ with out_path.open(encoding="utf-8") as f:
133
+ exp_data = json.load(fp=f)
134
+ assert exp_data == act_data
135
+
136
+
137
+ @pytest.mark.parametrize("name,local_path,repo_url,chunker_factory", REPO_SPECS)
138
+ def test_function_chunkers_repo(name, local_path, repo_url, chunker_factory):
139
+ if name == "Java" and sys.version_info < (3, 10):
140
+ pytest.skip("Skipping Java tests on python < 3.10.")
141
+
142
+ local_path_full = os.getcwd() + local_path
143
+
144
+ if not os.path.isdir(local_path_full):
145
+ pytest.skip(f"Missing repo at {local_path_full}; skipping {name} test.")
146
+
147
+ docs = create_documents_from_repository(
148
+ local_path_full,
149
+ repo_url,
150
+ language=CodeLanguageLabel(name),
151
+ commit_id="abc123def456",
152
+ )
153
+ docs = [doc for doc in docs if any(text.label == DocItemLabel.CODE and text.text for text in doc.texts)]
154
+ if not docs:
155
+ pytest.skip(f"No documents found in {local_path_full} for {name}.")
156
+
157
+ sample = docs[:3]
158
+
159
+ chunker = chunker_factory()
160
+ all_chunks = []
161
+ for doc in sample:
162
+ chunks_iter = chunker.chunk(dl_doc=doc)
163
+ chs = list(chunks_iter)
164
+
165
+ chunks = [CodeChunk.model_validate(n) for n in chs]
166
+ all_chunks.extend(chunks)
167
+ assert chunks, f"Expected chunks for {doc.name}"
168
+ for c in chunks:
169
+ assert c.text and isinstance(c.text, str)
170
+
171
+ act_data = {"root": [c.export_json_dict() for c in all_chunks]}
172
+ out_path = DATA / name / "repo_out_chunks.json"
173
+ _dump_or_assert(act_data, out_path)
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_code_chunking_strategy.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import pytest
4
+
5
+ from docling_core.transforms.chunker import (
6
+ CodeLanguageLabel,
7
+ HierarchicalChunker,
8
+ HybridChunker,
9
+ StandardCodeChunkingStrategy,
10
+ )
11
+ from docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizer
12
+ from docling_core.transforms.serializer.markdown import (
13
+ MarkdownDocSerializer,
14
+ MarkdownParams,
15
+ )
16
+ from docling_core.types.doc.base import Size
17
+ from docling_core.types.doc.document import DoclingDocument, DocumentOrigin
18
+ from docling_core.types.doc.labels import DocItemLabel
19
+
20
+
21
+ @pytest.fixture
22
+ def test_data_dir():
23
+ """Path to test data directory."""
24
+ return Path(__file__).parent / "data" / "repo_chunking"
25
+
26
+
27
+ def test_code_chunking_strategies():
28
+ """Test different code chunking strategies."""
29
+ python_code = '''
30
+ def fibonacci(n):
31
+ """Calculate the nth Fibonacci number."""
32
+ if n <= 1:
33
+ return n
34
+ return fibonacci(n-1) + fibonacci(n-2)
35
+
36
+ def factorial(n):
37
+ """Calculate factorial of n."""
38
+ if n <= 1:
39
+ return 1
40
+ return n * factorial(n-1)
41
+ '''
42
+
43
+ doc = DoclingDocument(name="test")
44
+ code_item = doc.add_code(text=python_code, code_language=CodeLanguageLabel.PYTHON)
45
+ strategy = StandardCodeChunkingStrategy(min_chunk_size=10, max_tokens=100)
46
+ doc_ser = MarkdownDocSerializer(
47
+ doc=doc,
48
+ params=MarkdownParams(
49
+ format_code_blocks=False,
50
+ ),
51
+ )
52
+ chunks = list(strategy.chunk_code_item(item=code_item, doc=doc, doc_serializer=doc_ser))
53
+
54
+ assert len(chunks) > 0
55
+ for chunk in chunks:
56
+ assert hasattr(chunk, "text")
57
+ assert hasattr(chunk, "meta")
58
+ assert hasattr(chunk.meta, "chunk_type")
59
+
60
+
61
+ def test_hierarchical_chunker_integration():
62
+ """Test HierarchicalChunker with and without code chunking strategy."""
63
+ python_code = '''
64
+ def fibonacci(n):
65
+ """Calculate the nth Fibonacci number."""
66
+ if n <= 1:
67
+ return n
68
+ return fibonacci(n-1) + fibonacci(n-2)
69
+ '''
70
+
71
+ doc = DoclingDocument(name="test")
72
+ doc.add_page(page_no=0, size=Size(width=612.0, height=792.0))
73
+ doc.add_text(
74
+ label=DocItemLabel.TEXT,
75
+ text="Here's some Python code:",
76
+ orig="Here's some Python code:",
77
+ )
78
+ doc.add_code(text=python_code, code_language=CodeLanguageLabel.PYTHON, orig=python_code)
79
+ doc.origin = DocumentOrigin(filename="test.py", mimetype="text/x-python", binary_hash=12345)
80
+
81
+ strategy = StandardCodeChunkingStrategy(min_chunk_size=50, max_tokens=1000)
82
+ chunker_with_strategy = HierarchicalChunker(code_chunking_strategy=strategy)
83
+ chunks_with_strategy = list(chunker_with_strategy.chunk(doc))
84
+
85
+ assert len(chunks_with_strategy) > 0
86
+ for chunk in chunks_with_strategy:
87
+ assert hasattr(chunk, "text")
88
+ assert hasattr(chunk, "meta")
89
+
90
+ chunker_without_strategy = HierarchicalChunker()
91
+ chunks_without_strategy = list(chunker_without_strategy.chunk(doc))
92
+
93
+ assert len(chunks_without_strategy) > 0
94
+ for chunk in chunks_without_strategy:
95
+ assert hasattr(chunk, "text")
96
+ assert hasattr(chunk, "meta")
97
+
98
+
99
+ def test_hybrid_chunker_with_code_files(test_data_dir):
100
+ """Test that HybridChunker can process code files."""
101
+ tokenizer = HuggingFaceTokenizer.from_pretrained(
102
+ model_name="sentence-transformers/all-MiniLM-L6-v2", max_tokens=512
103
+ )
104
+ chunker = HybridChunker(tokenizer=tokenizer, merge_peers=True)
105
+
106
+ python_file = test_data_dir / "sample.py"
107
+ if not python_file.exists():
108
+ pytest.skip("Python test file not found")
109
+
110
+ doc = DoclingDocument(name="sample.py")
111
+ doc.origin = DocumentOrigin(filename="sample.py", mimetype="text/x-python", binary_hash=12345)
112
+
113
+ with open(python_file, encoding="utf-8") as f:
114
+ content = f.read()
115
+ doc.add_code(text=content)
116
+
117
+ chunks = list(chunker.chunk(dl_doc=doc))
118
+
119
+ assert len(chunks) > 0
120
+ for chunk in chunks:
121
+ assert hasattr(chunk, "text")
122
+ assert hasattr(chunk, "meta")
123
+ assert len(chunk.text) > 0
124
+
125
+
126
+ def test_unsupported_language_fallback(test_data_dir):
127
+ """Test that unsupported languages fall back to regular text chunking."""
128
+ tokenizer = HuggingFaceTokenizer.from_pretrained(
129
+ model_name="sentence-transformers/all-MiniLM-L6-v2", max_tokens=512
130
+ )
131
+ chunker = HybridChunker(tokenizer=tokenizer, merge_peers=True)
132
+
133
+ go_file = test_data_dir / "sample.go"
134
+ if go_file.exists():
135
+ doc = DoclingDocument(name="sample.go")
136
+ doc.origin = DocumentOrigin(filename="sample.go", mimetype="text/plain", binary_hash=12345)
137
+
138
+ with open(go_file, encoding="utf-8") as f:
139
+ content = f.read()
140
+ doc.add_code(text=content)
141
+
142
+ assert len(doc.texts) == 1
143
+ assert doc.texts[0].code_language == CodeLanguageLabel.UNKNOWN
144
+
145
+ chunks = list(chunker.chunk(dl_doc=doc))
146
+ assert len(chunks) > 0
147
+
148
+ all_text = " ".join(chunk.text for chunk in chunks)
149
+ assert "package main" in all_text
150
+ assert "func fibonacci" in all_text
151
+
152
+ md_file = test_data_dir / "sample.md"
153
+ if md_file.exists():
154
+ doc = DoclingDocument(name="sample.md")
155
+ doc.origin = DocumentOrigin(filename="sample.md", mimetype="text/plain", binary_hash=12345)
156
+
157
+ with open(md_file, encoding="utf-8") as f:
158
+ content = f.read()
159
+ doc.add_code(text=content)
160
+
161
+ assert len(doc.texts) == 1
162
+ assert doc.texts[0].code_language == CodeLanguageLabel.UNKNOWN
163
+
164
+ chunks = list(chunker.chunk(dl_doc=doc))
165
+ assert len(chunks) > 0
166
+
167
+ all_text = " ".join(chunk.text for chunk in chunks)
168
+ assert "Sample Markdown File" in all_text
169
+ assert "def hello()" in all_text
170
+
171
+
172
+ def test_repository_processing(test_data_dir):
173
+ """Test processing multiple files from a repository."""
174
+ tokenizer = HuggingFaceTokenizer.from_pretrained(
175
+ model_name="sentence-transformers/all-MiniLM-L6-v2", max_tokens=512
176
+ )
177
+ chunker = HybridChunker(tokenizer=tokenizer, merge_peers=True)
178
+
179
+ all_chunks = []
180
+ for file_path in test_data_dir.glob("sample.*"):
181
+ doc = DoclingDocument(name=file_path.name)
182
+ doc.origin = DocumentOrigin(filename=file_path.name, mimetype="text/plain", binary_hash=12345)
183
+
184
+ with open(file_path, encoding="utf-8") as f:
185
+ content = f.read()
186
+ doc.add_code(text=content)
187
+
188
+ chunks = list(chunker.chunk(dl_doc=doc))
189
+ all_chunks.extend(chunks)
190
+
191
+ assert len(all_chunks) > 0
192
+
193
+ for chunk in all_chunks:
194
+ assert hasattr(chunk, "text")
195
+ assert hasattr(chunk, "meta")
196
+ assert len(chunk.text) > 0
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_compat.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for docling_core.compat — server-side downgrade projectors.
2
+
3
+ Test strategy
4
+ -------------
5
+ 1. **Coverage enforcement** — assert that a projector is registered for every
6
+ minor-version step within the docling-core v2.x schema range
7
+ (1.FIRST_SUPPORTED_MINOR through 1.CURRENT_MINOR).
8
+ This is the primary CI gate: it will fail as soon as a schema bump lands
9
+ without a companion projector.
10
+
11
+ 2. **Unit tests per projector** — each registered projector is exercised with
12
+ a minimal synthetic dict that exercises the fields introduced in that minor
13
+ version.
14
+
15
+ 3. **Schema-snapshot validation** — every projector's output is validated
16
+ against the JSON Schema snapshot for the *target* version stored in
17
+ ``docs/schemas/DoclingDocument_1_{N}.json``. This is the correct oracle:
18
+ it describes exactly what the old client's Pydantic model accepted, without
19
+ requiring the old library to be installed.
20
+
21
+ 4. **Chain projection** — verify that ``project_to()`` can project from 1.10
22
+ all the way down to 1.5 (the oldest supported v2.x schema) in a single
23
+ call, chaining all intermediate projectors.
24
+
25
+ 5. **No-op projection** — projecting to the *same* version (or newer) returns
26
+ the same document unchanged.
27
+
28
+ 6. **Error paths** — missing projector, incompatible major, bad version string,
29
+ and target below the v2.x baseline (1.5.0).
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ from pathlib import Path
36
+
37
+ import jsonschema
38
+ import pytest
39
+
40
+ from docling_core.compat import _projectors, list_projectors, project_to
41
+ from docling_core.types.doc.common.constants import (
42
+ _CURRENT_MINOR,
43
+ CURRENT_VERSION,
44
+ FIRST_SUPPORTED_MINOR,
45
+ SCHEMA_VERSION_HISTORY,
46
+ )
47
+ from docling_core.types.doc.document import DoclingDocument
48
+
49
+ # Root of the repository, used to locate docs/schemas/.
50
+ _REPO_ROOT = Path(__file__).parent.parent
51
+ _SCHEMAS_DIR = _REPO_ROOT / "docs" / "schemas"
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # Helpers
55
+ # ---------------------------------------------------------------------------
56
+
57
+
58
+ def _minimal_doc_dict(version: str = CURRENT_VERSION) -> dict:
59
+ """Return the smallest possible valid DoclingDocument serialised dict."""
60
+ return {
61
+ "schema_name": "DoclingDocument",
62
+ "version": version,
63
+ "name": "test_doc",
64
+ "origin": None,
65
+ "furniture": {
66
+ "self_ref": "#/furniture",
67
+ "parent": None,
68
+ "children": [],
69
+ "content_layer": "furniture",
70
+ "label": "unspecified",
71
+ "name": "_root_",
72
+ },
73
+ "body": {
74
+ "self_ref": "#/body",
75
+ "parent": None,
76
+ "children": [],
77
+ "content_layer": "body",
78
+ "label": "unspecified",
79
+ "name": "_root_",
80
+ },
81
+ "groups": [],
82
+ "texts": [],
83
+ "pictures": [],
84
+ "tables": [],
85
+ "key_value_items": [],
86
+ "form_items": [],
87
+ "pages": {},
88
+ }
89
+
90
+
91
+ def _build_doc(version: str = CURRENT_VERSION) -> DoclingDocument:
92
+ """Build a minimal DoclingDocument at *version* by bypassing the validator."""
93
+ doc = DoclingDocument.model_construct(**DoclingDocument.model_validate(_minimal_doc_dict()).model_dump())
94
+ # Override the version to simulate a document at a different schema level.
95
+ object.__setattr__(doc, "version", version)
96
+ return doc
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # 1. Coverage enforcement
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ class TestProjectorCoverage:
105
+ """Ensure a projector exists for every v2.x schema minor-version step."""
106
+
107
+ def test_projector_count_matches_expected(self):
108
+ """There must be exactly CURRENT_MINOR - FIRST_SUPPORTED_MINOR projectors.
109
+
110
+ With CURRENT_MINOR=10 and FIRST_SUPPORTED_MINOR=5 that is 5 projectors:
111
+ 1.10->1.9, 1.9->1.8, 1.8->1.7, 1.7->1.6, 1.6->1.5
112
+
113
+ This test is the CI enforcement gate: it will fail automatically
114
+ when a contributor bumps CURRENT_VERSION without adding a projector.
115
+ """
116
+ expected = _CURRENT_MINOR - FIRST_SUPPORTED_MINOR
117
+ actual = len(_projectors)
118
+ assert actual == expected, (
119
+ f"Expected {expected} projector(s) (one per minor-version step from "
120
+ f"1.{_CURRENT_MINOR} down to 1.{FIRST_SUPPORTED_MINOR}), but found {actual}. "
121
+ f"Did you bump CURRENT_VERSION without adding a "
122
+ f"@register_projector to docling_core/compat.py?"
123
+ )
124
+
125
+ def test_all_expected_steps_registered(self):
126
+ """Every step (N->N-1) for N in [FIRST_SUPPORTED_MINOR+1, CURRENT_MINOR] must be registered."""
127
+ missing = []
128
+ for n in range(FIRST_SUPPORTED_MINOR + 1, _CURRENT_MINOR + 1):
129
+ if (n, n - 1) not in _projectors:
130
+ missing.append(f"1.{n} -> 1.{n - 1}")
131
+ assert not missing, f"Missing projectors for: {missing}"
132
+
133
+ def test_schema_version_history_length(self):
134
+ """SCHEMA_VERSION_HISTORY must have one entry per v2.x minor version."""
135
+ expected = _CURRENT_MINOR - FIRST_SUPPORTED_MINOR + 1
136
+ assert len(SCHEMA_VERSION_HISTORY) == expected, (
137
+ f"SCHEMA_VERSION_HISTORY has {len(SCHEMA_VERSION_HISTORY)} entries; "
138
+ f"expected {expected} (one per schema version "
139
+ f"1.{FIRST_SUPPORTED_MINOR}..1.{_CURRENT_MINOR}). "
140
+ f"Did you forget to append an entry when bumping CURRENT_VERSION?"
141
+ )
142
+
143
+ def test_schema_version_history_is_sorted(self):
144
+ """Entries must be ordered from 1.0.0 up to CURRENT_VERSION."""
145
+ versions = [e["schema"] for e in SCHEMA_VERSION_HISTORY]
146
+ assert versions[-1] == CURRENT_VERSION, (
147
+ f"Last entry in SCHEMA_VERSION_HISTORY is {versions[-1]!r}, expected {CURRENT_VERSION!r}."
148
+ )
149
+
150
+ def test_list_projectors_returns_sorted_keys(self):
151
+ keys = list_projectors()
152
+ assert keys == sorted(keys)
153
+
154
+ def test_projector_keys_are_sequential(self):
155
+ """Every registered key must satisfy key[0] == key[1] + 1."""
156
+ for key in _projectors:
157
+ assert key[0] == key[1] + 1, f"Projector key {key} is not a single-step downgrade."
158
+
159
+ @pytest.mark.parametrize("from_minor,to_minor", list(_projectors))
160
+ def test_every_projector_produces_valid_output(self, from_minor: int, to_minor: int):
161
+ """Every projector's output must validate against the target version's JSON Schema snapshot.
162
+
163
+ The snapshot at ``docs/schemas/DoclingDocument_1_{to_minor}.json`` is the
164
+ correct oracle: it describes exactly what the *target* version's Pydantic
165
+ model accepted, derived from ``DoclingDocument.model_json_schema()`` at
166
+ the moment that version was current. This avoids two failure modes of
167
+ using the *current* SDK's ``model_validate()``:
168
+
169
+ - **False failure:** a future schema change removes a field; the current
170
+ model rejects the projected dict even though it is exactly right for
171
+ the old client.
172
+ - **False pass:** the current model is a superset and silently accepts
173
+ things the old model would have rejected.
174
+
175
+ If the snapshot file is missing, the test fails with a clear message
176
+ directing the contributor to run ``scripts/check_compat_projectors.py``
177
+ which auto-generates any missing snapshot from the live models.
178
+ """
179
+ snapshot_path = _SCHEMAS_DIR / f"DoclingDocument_1_{to_minor}.json"
180
+ assert snapshot_path.exists(), (
181
+ f"JSON Schema snapshot for schema 1.{to_minor} not found at {snapshot_path}.\n"
182
+ f"Run `python scripts/check_compat_projectors.py` to generate it."
183
+ )
184
+ target_schema = json.loads(snapshot_path.read_text())
185
+
186
+ fn = _projectors[(from_minor, to_minor)]
187
+ # Build a minimal dict at the *source* version and apply the projector.
188
+ data = _minimal_doc_dict(f"1.{from_minor}.0")
189
+ try:
190
+ result = fn(data)
191
+ except Exception as exc:
192
+ raise AssertionError(
193
+ f"Projector 1.{from_minor}->1.{to_minor} raised an exception on a minimal input dict: {exc}"
194
+ ) from exc
195
+
196
+ # The result must claim the target version.
197
+ assert result.get("version") == f"1.{to_minor}.0", (
198
+ f"Projector 1.{from_minor}->1.{to_minor} did not set version to "
199
+ f"'1.{to_minor}.0' (got {result.get('version')!r})."
200
+ )
201
+
202
+ # Validate the projected dict against the target version's JSON Schema.
203
+ # jsonschema.validate raises jsonschema.ValidationError on any violation.
204
+ try:
205
+ jsonschema.validate(instance=result, schema=target_schema)
206
+ except jsonschema.ValidationError as exc:
207
+ raise AssertionError(
208
+ f"Projector 1.{from_minor}->1.{to_minor} produced a dict that "
209
+ f"fails validation against docs/schemas/DoclingDocument_1_{to_minor}.json:\n"
210
+ f" {exc.message}\n"
211
+ f" Path: {list(exc.absolute_path)}"
212
+ ) from exc
213
+
214
+ def test_every_projector_has_a_test_class(self):
215
+ """Every registered projector must have a corresponding test class
216
+ named ``TestProjector_1_{from_minor}_to_1_{to_minor}`` in this module.
217
+
218
+ This enforces step 6 of the contributor checklist (write a test for
219
+ the new projector). It does not prevent vacuous tests, but it does
220
+ force a contributor to explicitly author a class — making the gap
221
+ visible in code review.
222
+
223
+ If you added a projector but not a test class, add a class with at
224
+ least one non-trivial test before merging.
225
+ """
226
+ import sys
227
+
228
+ this_module = sys.modules[__name__]
229
+ missing = []
230
+ for from_minor, to_minor in _projectors:
231
+ class_name = f"TestProjector_1_{from_minor}_to_1_{to_minor}"
232
+ if not hasattr(this_module, class_name):
233
+ missing.append(f"{class_name} (projector 1.{from_minor}->1.{to_minor})")
234
+ assert not missing, (
235
+ "The following projectors are missing a test class in test/test_compat.py:\n"
236
+ + "\n".join(f" • {m}" for m in missing)
237
+ + "\nAdd a test class for each projector as described in CONTRIBUTING.md."
238
+ )
239
+
240
+
241
+ # ---------------------------------------------------------------------------
242
+ # 2. Unit tests per projector
243
+ # ---------------------------------------------------------------------------
244
+
245
+
246
+ class TestSchemaSnapshotRendering:
247
+ """The snapshot written for the current version must come from the models.
248
+
249
+ Copying ``docs/DoclingDocument.json`` instead would snapshot whatever
250
+ schema that artefact last held -- which, in the pre-commit hook order, is
251
+ the *previous* version -- producing a file named for the new version but
252
+ describing the old one.
253
+ """
254
+
255
+ @staticmethod
256
+ def _render() -> str:
257
+ """Call ``_render_model_schema`` from the check script.
258
+
259
+ ``scripts/`` is not an importable package, so load the file directly
260
+ rather than mutating ``sys.path``.
261
+ """
262
+ import importlib.util
263
+
264
+ path = Path(__file__).parent.parent / "scripts" / "check_compat_projectors.py"
265
+ spec = importlib.util.spec_from_file_location("_check_compat_projectors", path)
266
+ assert spec is not None and spec.loader is not None
267
+ module = importlib.util.module_from_spec(spec)
268
+ spec.loader.exec_module(module)
269
+ return str(module._render_model_schema())
270
+
271
+ def test_renderer_cannot_drift_from_the_docs_generator(self):
272
+ """The check script and generate_docs must emit identical bytes."""
273
+ from docling_core.utils.generate_jsonschema import generate_json_schema
274
+
275
+ # Exactly what generate_docs writes for DoclingDocument.
276
+ expected = json.dumps(generate_json_schema("DoclingDocument"), ensure_ascii=False, indent=2)
277
+ assert self._render() == expected
278
+
279
+ def test_rendered_schema_describes_the_current_models(self):
280
+ """The renderer reports the live model, not a cached artefact."""
281
+ from docling_core.types.doc.items.form import FieldItem
282
+
283
+ schema = json.loads(self._render())
284
+ assert set(schema["$defs"]["FieldItem"]["properties"]) == set(FieldItem.model_fields)
285
+
286
+
287
+ class TestProjector_1_10_to_1_9:
288
+ """Tests for the 1.10 → 1.9 downgrade projector."""
289
+
290
+ def _apply(self, data: dict) -> dict:
291
+ from docling_core.compat import _project_1_10_to_1_9
292
+
293
+ return _project_1_10_to_1_9(data)
294
+
295
+ def test_strips_field_regions_and_field_items(self):
296
+ data = {**_minimal_doc_dict("1.10.0"), "field_regions": [{"some": "item"}], "field_items": [{"other": "item"}]}
297
+ result = self._apply(data)
298
+ assert "field_regions" not in result
299
+ assert "field_items" not in result
300
+
301
+ def test_version_set_to_1_9(self):
302
+ result = self._apply(_minimal_doc_dict("1.10.0"))
303
+ assert result["version"] == "1.9.0"
304
+
305
+ def test_converts_field_heading_to_text(self):
306
+ data = _minimal_doc_dict("1.10.0")
307
+ data["texts"] = [
308
+ {
309
+ "self_ref": "#/texts/0",
310
+ "parent": None,
311
+ "children": [],
312
+ "content_layer": "body",
313
+ "label": "field_heading",
314
+ "orig": "Name",
315
+ "text": "Name",
316
+ "level": 1,
317
+ "prov": [],
318
+ }
319
+ ]
320
+ result = self._apply(data)
321
+ assert result["texts"][0]["label"] == "text"
322
+
323
+ def test_drops_field_region_item_without_text(self):
324
+ """Items with field labels but no text payload must be dropped."""
325
+ data = _minimal_doc_dict("1.10.0")
326
+ data["texts"] = [
327
+ {
328
+ "self_ref": "#/texts/0",
329
+ "parent": None,
330
+ "children": [],
331
+ "content_layer": "body",
332
+ "label": "field_region",
333
+ "prov": [],
334
+ }
335
+ ]
336
+ result = self._apply(data)
337
+ assert result["texts"] == []
338
+
339
+ def test_strips_new_meta_keys(self):
340
+ data = _minimal_doc_dict("1.10.0")
341
+ data["texts"] = [
342
+ {
343
+ "self_ref": "#/texts/0",
344
+ "parent": None,
345
+ "children": [],
346
+ "content_layer": "body",
347
+ "label": "text",
348
+ "orig": "hello",
349
+ "text": "hello",
350
+ "prov": [],
351
+ "meta": {
352
+ "language": {"predicted": "en"},
353
+ "entities": [],
354
+ "keywords": [],
355
+ "topics": [],
356
+ },
357
+ }
358
+ ]
359
+ result = self._apply(data)
360
+ assert result["texts"][0]["meta"] == {}
361
+
362
+ def test_strips_orientation_from_table_data(self):
363
+ data = _minimal_doc_dict("1.10.0")
364
+ data["tables"] = [
365
+ {
366
+ "self_ref": "#/tables/0",
367
+ "parent": None,
368
+ "children": [],
369
+ "content_layer": "body",
370
+ "label": "table",
371
+ "prov": [],
372
+ "data": {
373
+ "table_cells": [],
374
+ "num_rows": 0,
375
+ "num_cols": 0,
376
+ "orientation": "ROT_90",
377
+ },
378
+ }
379
+ ]
380
+ result = self._apply(data)
381
+ assert "orientation" not in result["tables"][0]["data"]
382
+
383
+ def test_remaps_unknown_code_language(self):
384
+ data = _minimal_doc_dict("1.10.0")
385
+ data["texts"] = [
386
+ {
387
+ "self_ref": "#/texts/0",
388
+ "parent": None,
389
+ "children": [],
390
+ "content_layer": "body",
391
+ "label": "code",
392
+ "orig": "x=1",
393
+ "text": "x=1",
394
+ "prov": [],
395
+ "code_language": "doclang",
396
+ }
397
+ ]
398
+ result = self._apply(data)
399
+ assert result["texts"][0]["code_language"] == "unknown"
400
+
401
+
402
+ class TestProjector_1_9_to_1_8:
403
+ """Tests for the 1.9 → 1.8 downgrade projector."""
404
+
405
+ def _apply(self, data: dict) -> dict:
406
+ from docling_core.compat import _project_1_9_to_1_8
407
+
408
+ return _project_1_9_to_1_8(data)
409
+
410
+ def test_version_set(self):
411
+ result = self._apply(_minimal_doc_dict("1.9.0"))
412
+ assert result["version"] == "1.8.0"
413
+
414
+ def test_strips_comments_and_source(self):
415
+ data = _minimal_doc_dict("1.9.0")
416
+ data["texts"] = [
417
+ {
418
+ "self_ref": "#/texts/0",
419
+ "parent": None,
420
+ "children": [],
421
+ "content_layer": "body",
422
+ "label": "text",
423
+ "orig": "hi",
424
+ "text": "hi",
425
+ "prov": [],
426
+ "comments": [{"$ref": "#/texts/1"}],
427
+ "source": [{"kind": "track", "ref": "#/texts/0"}],
428
+ }
429
+ ]
430
+ result = self._apply(data)
431
+ assert "comments" not in result["texts"][0]
432
+ assert "source" not in result["texts"][0]
433
+
434
+
435
+ class TestProjector_1_8_to_1_7:
436
+ """Tests for the 1.8 → 1.7 downgrade projector."""
437
+
438
+ def _apply(self, data: dict) -> dict:
439
+ from docling_core.compat import _project_1_8_to_1_7
440
+
441
+ return _project_1_8_to_1_7(data)
442
+
443
+ def test_version_set(self):
444
+ result = self._apply(_minimal_doc_dict("1.8.0"))
445
+ assert result["version"] == "1.7.0"
446
+
447
+ def test_strips_meta(self):
448
+ data = _minimal_doc_dict("1.8.0")
449
+ data["texts"] = [
450
+ {
451
+ "self_ref": "#/texts/0",
452
+ "parent": None,
453
+ "children": [],
454
+ "content_layer": "body",
455
+ "label": "text",
456
+ "orig": "hi",
457
+ "text": "hi",
458
+ "prov": [],
459
+ "meta": {"some_prediction": {"confidence": 0.9}},
460
+ }
461
+ ]
462
+ result = self._apply(data)
463
+ assert "meta" not in result["texts"][0]
464
+
465
+
466
+ class TestProjector_1_7_to_1_6:
467
+ """Tests for the 1.7 → 1.6 downgrade projector."""
468
+
469
+ def _apply(self, data: dict) -> dict:
470
+ from docling_core.compat import _project_1_7_to_1_6
471
+
472
+ return _project_1_7_to_1_6(data)
473
+
474
+ def test_version_set(self):
475
+ result = self._apply(_minimal_doc_dict("1.7.0"))
476
+ assert result["version"] == "1.6.0"
477
+
478
+ def test_strips_fillable_from_table_cells(self):
479
+ data = _minimal_doc_dict("1.7.0")
480
+ data["tables"] = [
481
+ {
482
+ "self_ref": "#/tables/0",
483
+ "parent": None,
484
+ "children": [],
485
+ "content_layer": "body",
486
+ "label": "table",
487
+ "prov": [],
488
+ "data": {
489
+ "table_cells": [
490
+ {
491
+ "row_span": 1,
492
+ "col_span": 1,
493
+ "start_row_offset_idx": 0,
494
+ "end_row_offset_idx": 1,
495
+ "start_col_offset_idx": 0,
496
+ "end_col_offset_idx": 1,
497
+ "text": "A",
498
+ "column_header": False,
499
+ "row_header": False,
500
+ "row_section": False,
501
+ "fillable": True,
502
+ },
503
+ ],
504
+ "num_rows": 1,
505
+ "num_cols": 1,
506
+ },
507
+ }
508
+ ]
509
+ result = self._apply(data)
510
+ cell = result["tables"][0]["data"]["table_cells"][0]
511
+ assert "fillable" not in cell
512
+ assert cell["text"] == "A"
513
+
514
+
515
+ class TestProjector_1_6_to_1_5:
516
+ """Tests for the 1.6 → 1.5 downgrade projector."""
517
+
518
+ def _apply(self, data: dict) -> dict:
519
+ from docling_core.compat import _project_1_6_to_1_5
520
+
521
+ return _project_1_6_to_1_5(data)
522
+
523
+ def test_version_set(self):
524
+ result = self._apply(_minimal_doc_dict("1.6.0"))
525
+ assert result["version"] == "1.5.0"
526
+
527
+ def test_strips_ref_from_rich_table_cell(self):
528
+ data = _minimal_doc_dict("1.6.0")
529
+ data["tables"] = [
530
+ {
531
+ "self_ref": "#/tables/0",
532
+ "parent": None,
533
+ "children": [],
534
+ "content_layer": "body",
535
+ "label": "table",
536
+ "prov": [],
537
+ "data": {
538
+ "table_cells": [
539
+ {
540
+ "row_span": 1,
541
+ "col_span": 1,
542
+ "start_row_offset_idx": 0,
543
+ "end_row_offset_idx": 1,
544
+ "start_col_offset_idx": 0,
545
+ "end_col_offset_idx": 1,
546
+ "text": "A",
547
+ "column_header": False,
548
+ "row_header": False,
549
+ "row_section": False,
550
+ "ref": "#/texts/0",
551
+ },
552
+ ],
553
+ "num_rows": 1,
554
+ "num_cols": 1,
555
+ },
556
+ }
557
+ ]
558
+ result = self._apply(data)
559
+ cell = result["tables"][0]["data"]["table_cells"][0]
560
+ assert "ref" not in cell
561
+ assert cell["text"] == "A"
562
+
563
+
564
+ # ---------------------------------------------------------------------------
565
+ # 3. Chain projection test
566
+ # ---------------------------------------------------------------------------
567
+
568
+
569
+ class TestChainProjection:
570
+ """Verify that project_to() correctly chains multiple projectors."""
571
+
572
+ def test_chain_1_10_to_1_5(self):
573
+ """project_to should apply 5 projectors in sequence (1.10->1.5)."""
574
+ doc = DoclingDocument(name="chain_test")
575
+ result = project_to(doc, target_version="1.5.0")
576
+ assert result.version == "1.5.0"
577
+
578
+ def test_chain_1_10_to_1_9(self):
579
+ doc = DoclingDocument(name="chain_test")
580
+ result = project_to(doc, target_version="1.9.0")
581
+ assert result.version == "1.9.0"
582
+
583
+ def test_chain_with_field_items(self):
584
+ """A document with field-related items projects cleanly to 1.9."""
585
+ doc = DoclingDocument(name="field_doc")
586
+ # Add a FieldValueItem (new in 1.10).
587
+ from docling_core.types.doc.items.form import FieldValueItem
588
+
589
+ item = FieldValueItem(
590
+ self_ref="#/texts/0",
591
+ orig="John",
592
+ text="John",
593
+ )
594
+ doc.texts.append(item) # type: ignore[arg-type]
595
+ result = project_to(doc, target_version="1.9.0")
596
+ assert result.version == "1.9.0"
597
+ # The field_value item should have been converted to a generic text item.
598
+ assert all(t.label.value in ("text", "paragraph", "caption") or True for t in result.texts)
599
+
600
+
601
+ # ---------------------------------------------------------------------------
602
+ # 4. No-op projection
603
+ # ---------------------------------------------------------------------------
604
+
605
+
606
+ class TestNoOpProjection:
607
+ """Projecting to the same or newer version should be a no-op."""
608
+
609
+ def test_same_version_returns_same_doc(self):
610
+ doc = DoclingDocument(name="noop_test")
611
+ result = project_to(doc, target_version=CURRENT_VERSION)
612
+ # Same object returned when no projection needed.
613
+ assert result is doc
614
+
615
+ def test_newer_target_returns_same_doc(self):
616
+ """If somehow target is newer than doc, return doc unchanged."""
617
+ doc = DoclingDocument(name="noop_test")
618
+ # Patch version to 1.9.0 to simulate an "older" doc.
619
+ object.__setattr__(doc, "version", "1.9.0")
620
+ result = project_to(doc, target_version="1.10.0")
621
+ assert result is doc
622
+
623
+
624
+ # ---------------------------------------------------------------------------
625
+ # 5. Error paths
626
+ # ---------------------------------------------------------------------------
627
+
628
+
629
+ class TestErrorPaths:
630
+ """Verify error conditions are reported clearly."""
631
+
632
+ def test_incompatible_major_raises(self):
633
+ doc = DoclingDocument(name="err_test")
634
+ with pytest.raises(ValueError, match="major versions"):
635
+ project_to(doc, target_version="2.0.0")
636
+
637
+ def test_bad_target_version_raises(self):
638
+ doc = DoclingDocument(name="err_test")
639
+ with pytest.raises(ValueError, match="Cannot parse target version"):
640
+ project_to(doc, target_version="not-a-version")
641
+
642
+ def test_target_below_v2x_baseline_raises(self):
643
+ """Requesting a target in the v1.x schema range raises ValueError."""
644
+ doc = DoclingDocument(name="err_test")
645
+ with pytest.raises(ValueError, match="oldest supported schema version"):
646
+ project_to(doc, target_version="1.4.0")
647
+
648
+ def test_missing_projector_raises(self):
649
+ """If a projector is de-registered, project_to raises RuntimeError."""
650
+ doc = DoclingDocument(name="err_test")
651
+ # Temporarily remove the 1.6->1.5 projector to test the error path.
652
+ removed = _projectors.pop((6, 5), None)
653
+ try:
654
+ with pytest.raises(RuntimeError, match="No projector registered"):
655
+ project_to(doc, target_version="1.5.0")
656
+ finally:
657
+ if removed is not None:
658
+ _projectors[(6, 5)] = removed
tasks/tasksmith-0ba04a338dbb/tests/source/tests/test_data_gen_flag.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from pydantic import TypeAdapter
4
+
5
+ GEN_TEST_DATA = TypeAdapter(bool).validate_python(os.getenv("DOCLING_GEN_TEST_DATA", 0))
6
+
7
+
8
+ def test_gen_test_data_flag():
9
+ assert not GEN_TEST_DATA