iiegn Claude Sonnet 4.5 commited on
Commit
8dd6802
·
verified ·
1 Parent(s): 39736b5

Refactor: Rename and simplify README generation script

Browse files

- Renamed 03_fill_universal_dependencies_tamplate.py to 03_generate_README.py
- Script now only generates README-{UD_VER}, not universal_dependencies-{UD_VER}
- Removed templates/universal_dependencies.tmpl (no longer needed)
- Updated docstring to reflect new focused purpose

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

tools/{03_fill_universal_dependencies_tamplate.py → 03_generate_README.py} RENAMED
@@ -8,7 +8,7 @@
8
  # ]
9
  # ///
10
  """
11
- FIXME
12
  """
13
 
14
  import json
@@ -54,22 +54,19 @@ if __name__ == '__main__':
54
  with Path(basepath, "etc", f"citation-{UD_VER}").open(mode='r') as fh:
55
  citation = (fh.read()).strip()
56
 
57
- templates = {
58
- Path(basepath, "templates", "universal_dependencies.tmpl"):
59
- Path(basepath, f"universal_dependencies-{UD_VER}"),
60
- Path(basepath, "templates", "README.tmpl"):
61
- Path(basepath, f"README-{UD_VER}"),
62
- }
63
- for template_fn, output_fn in templates.items():
64
- if args.override or not Path(output_fn).exists():
65
- with template_fn.open(mode='r') as fh:
66
- template = jinja2.Template(fh.read())
67
 
68
- with output_fn.open(mode='w') as fh:
69
- output = template.render(citation=citation,
70
- description=description,
71
- data=metadata, ud_ver=UD_VER,)
72
- fh.write(output)
73
- print(f"{output_fn} written")
74
- else:
75
- logging.info(f"Output {output_fn} already exists: Not overriding.")
 
 
 
 
 
8
  # ]
9
  # ///
10
  """
11
+ Generate README-{UD_VER} from templates/README.tmpl using metadata-{UD_VER}.json.
12
  """
13
 
14
  import json
 
54
  with Path(basepath, "etc", f"citation-{UD_VER}").open(mode='r') as fh:
55
  citation = (fh.read()).strip()
56
 
57
+ # Generate README from template
58
+ template_fn = Path(basepath, "templates", "README.tmpl")
59
+ output_fn = Path(basepath, f"README-{UD_VER}")
 
 
 
 
 
 
 
60
 
61
+ if args.override or not output_fn.exists():
62
+ with template_fn.open(mode='r') as fh:
63
+ template = jinja2.Template(fh.read())
64
+
65
+ with output_fn.open(mode='w') as fh:
66
+ output = template.render(citation=citation,
67
+ description=description,
68
+ data=metadata, ud_ver=UD_VER,)
69
+ fh.write(output)
70
+ print(f"{output_fn} written")
71
+ else:
72
+ logging.info(f"Output {output_fn} already exists: Not overriding.")
tools/templates/universal_dependencies.tmpl DELETED
@@ -1,683 +0,0 @@
1
- ### THIS IS A GENERATED FILE.
2
-
3
- from dataclasses import dataclass
4
- from typing import Dict, Optional
5
-
6
- import conllu
7
-
8
- import datasets
9
-
10
-
11
- # Helper functions for parsing CoNLL-U format fields
12
-
13
- def parse_feats(feats_str: Optional[str]) -> Dict[str, str]:
14
- """
15
- Parse CoNLL-U FEATS field string to dictionary.
16
-
17
- Args:
18
- feats_str: CoNLL-U format string like "Case=Nom|Number=Sing" or None
19
-
20
- Returns:
21
- Dictionary mapping feature names to values, empty dict if None
22
-
23
- Example:
24
- >>> parse_feats("Case=Nom|Number=Sing")
25
- {'Case': 'Nom', 'Number': 'Sing'}
26
- >>> parse_feats(None)
27
- {}
28
- """
29
- if feats_str is None:
30
- return {}
31
- return dict(kv.split('=', 1) for kv in feats_str.split('|'))
32
-
33
-
34
- def parse_deps(deps_str: Optional[str]) -> Dict[str, str]:
35
- """
36
- Parse CoNLL-U DEPS field string to dictionary.
37
-
38
- Args:
39
- deps_str: CoNLL-U enhanced dependencies format like "4:nsubj|6:nsubj" or None
40
-
41
- Returns:
42
- Dictionary mapping head indices to dependency relations, empty dict if None
43
-
44
- Example:
45
- >>> parse_deps("4:nsubj|6:nsubj")
46
- {'4': 'nsubj', '6': 'nsubj'}
47
- >>> parse_deps(None)
48
- {}
49
- """
50
- if deps_str is None:
51
- return {}
52
- return dict(kv.split(':', 1) for kv in deps_str.split('|'))
53
-
54
-
55
- def parse_misc(misc_str: Optional[str]) -> Dict[str, str]:
56
- """
57
- Parse CoNLL-U MISC field string to dictionary.
58
-
59
- Args:
60
- misc_str: CoNLL-U format string like "SpaceAfter=No|Translit=yes" or None
61
-
62
- Returns:
63
- Dictionary mapping misc attribute names to values, empty dict if None
64
-
65
- Example:
66
- >>> parse_misc("SpaceAfter=No")
67
- {'SpaceAfter': 'No'}
68
- >>> parse_misc(None)
69
- {}
70
- """
71
- if misc_str is None:
72
- return {}
73
- return dict(kv.split('=', 1) for kv in misc_str.split('|'))
74
-
75
-
76
- def example_to_conllu(example: Dict, upos_names: Optional[list] = None) -> str:
77
- """
78
- Convert a single dataset example back to CoNLL-U format.
79
-
80
- Args:
81
- example: Dataset example (sentence) with all fields
82
- upos_names: Optional list of UPOS label names for ClassLabel conversion
83
-
84
- Returns:
85
- CoNLL-U formatted string for this sentence
86
-
87
- Example:
88
- >>> from datasets import load_dataset
89
- >>> ds = load_dataset("commul/universal_dependencies", "en_ewt", split="train")
90
- >>> conllu_str = example_to_conllu(ds[0])
91
- >>> print(conllu_str)
92
- # newdoc id = ...
93
- # sent_id = ...
94
- # text = ...
95
- 1 The ...
96
- <BLANKLINE>
97
- """
98
- lines = []
99
-
100
- # Add metadata in original order (comments list contains markers for sent_id and text positions)
101
- for comment in example.get('comments', []):
102
- if comment == "__SENT_ID__":
103
- lines.append(f"# sent_id = {example['sent_id']}")
104
- elif comment == "__TEXT__":
105
- lines.append(f"# text = {example['text']}")
106
- else:
107
- lines.append(f"# {comment}")
108
-
109
- # Parse MWT ranges to know when to insert them
110
- mwt_ranges = {}
111
- for mwt in example.get('mwt', []):
112
- mwt_id = mwt['id'] # e.g., "1-2"
113
- if '-' in mwt_id:
114
- start, _ = mwt_id.split('-')
115
- mwt_ranges[int(start)] = mwt
116
-
117
- # Parse empty node positions
118
- empty_nodes_dict = {}
119
- for empty_node in example.get('empty_nodes', []):
120
- try:
121
- node_id = float(empty_node['id'])
122
- if node_id not in empty_nodes_dict:
123
- empty_nodes_dict[node_id] = []
124
- empty_nodes_dict[node_id].append(empty_node)
125
- except (ValueError, KeyError):
126
- pass
127
-
128
- def _get_en_fields(empty_node):
129
- en_fields = [
130
- empty_node.get('id', '_'),
131
- empty_node.get('form', '_'),
132
- empty_node.get('lemma', '_'),
133
- empty_node.get('upos', '_'),
134
- empty_node.get('xpos') or '_',
135
- empty_node.get('feats') or '_',
136
- empty_node.get('head', '_'),
137
- empty_node.get('deprel', '_'),
138
- empty_node.get('deps') or '_',
139
- empty_node.get('misc') or '_',
140
- ]
141
- return en_fields
142
-
143
- # Insert empty nodes that come before token 1 (e.g., 0.1, 0.2)
144
- for node_id in sorted(empty_nodes_dict.keys()):
145
- if node_id < 1:
146
- for empty_node in empty_nodes_dict[node_id]:
147
- en_fields = _get_en_fields(empty_node)
148
- lines.append('\t'.join(en_fields))
149
-
150
- # Build token lines
151
- token_idx = 1
152
- for i in range(len(example['tokens'])):
153
- # Insert MWT line before this token if needed
154
- if token_idx in mwt_ranges:
155
- mwt = mwt_ranges[token_idx]
156
- feats = mwt.get('feats') or '_'
157
- misc = mwt.get('misc') or '_'
158
- lines.append(f"{mwt['id']}\t{mwt['form']}\t_\t_\t_\t{feats}\t_\t_\t_\t{misc}")
159
-
160
- # Convert UPOS from ClassLabel index to string if needed
161
- upos_value = example['upos'][i]
162
- if isinstance(upos_value, int) and upos_names:
163
- upos_value = upos_names[upos_value]
164
-
165
- # Build token line
166
- fields = [
167
- str(token_idx),
168
- str(example['tokens'][i]),
169
- str(example['lemmas'][i]),
170
- str(upos_value),
171
- str(example['xpos'][i] or '_'),
172
- str(example['feats'][i] or '_'),
173
- str(example['head'][i]),
174
- str(example['deprel'][i]),
175
- str(example['deps'][i] or '_'),
176
- str(example['misc'][i] or '_'),
177
- ]
178
- lines.append('\t'.join(fields))
179
-
180
- # Insert empty nodes after this token if needed (e.g., 22.1 after token 22)
181
- for node_id in sorted(empty_nodes_dict.keys()):
182
- if int(node_id) == token_idx:
183
- for empty_node in empty_nodes_dict[node_id]:
184
- en_fields = _get_en_fields(empty_node)
185
- lines.append('\t'.join(en_fields))
186
-
187
- token_idx += 1
188
-
189
- # Add blank line after sentence per UD spec
190
- return '\n'.join(lines) + '\n\n'
191
-
192
-
193
- def write_conllu(dataset, output=None, split=None):
194
- """
195
- Write dataset back to CoNLL-U format.
196
-
197
- Args:
198
- dataset: Dataset or DatasetDict to write
199
- output: Output destination (default: stdout):
200
- - None: write to stdout
201
- - str/Path: write to file path
202
- - file-like object: write to buffer/stream
203
- split: For DatasetDict, which split to write (default: all splits)
204
-
205
- Returns:
206
- None
207
-
208
- Example:
209
- >>> from datasets import load_dataset
210
- >>> ds = load_dataset("commul/universal_dependencies", "en_ewt", split="train")
211
- >>>
212
- >>> # Write to stdout
213
- >>> write_conllu(ds)
214
- >>>
215
- >>> # Write to file
216
- >>> write_conllu(ds, "output.conllu")
217
- >>>
218
- >>> # Write to buffer
219
- >>> import io
220
- >>> buffer = io.StringIO()
221
- >>> write_conllu(ds, buffer)
222
- >>> conllu_text = buffer.getvalue()
223
- """
224
- import sys
225
- from pathlib import Path
226
-
227
- # Handle DatasetDict
228
- if hasattr(dataset, 'keys'): # DatasetDict
229
- if split:
230
- # Write specific split
231
- if split not in dataset:
232
- raise ValueError(f"Split '{split}' not found. Available: {list(dataset.keys())}")
233
- dataset = dataset[split]
234
- else:
235
- # Write all splits
236
- for split_name, split_dataset in dataset.items():
237
- if output is None:
238
- print(f"# Split: {split_name}", file=sys.stderr)
239
- write_conllu(split_dataset, output, split=None)
240
- return
241
-
242
- # Get UPOS names if available
243
- upos_names = None
244
- if hasattr(dataset, 'features') and 'upos' in dataset.features:
245
- upos_feature = dataset.features['upos']
246
- if hasattr(upos_feature, 'feature') and hasattr(upos_feature.feature, 'names'):
247
- upos_names = upos_feature.feature.names
248
-
249
- # Determine output stream
250
- if output is None:
251
- # Write to stdout
252
- stream = sys.stdout
253
- close_after = False
254
- elif isinstance(output, (str, Path)):
255
- # Write to file
256
- stream = open(output, 'w', encoding='utf-8')
257
- close_after = True
258
- else:
259
- # Assume file-like object
260
- stream = output
261
- close_after = False
262
-
263
- try:
264
- # Write each example
265
- for example in dataset:
266
- conllu_str = example_to_conllu(example, upos_names=upos_names)
267
- stream.write(conllu_str)
268
- stream.write('\n') # Extra newline between sentences
269
- finally:
270
- if close_after:
271
- stream.close()
272
-
273
-
274
- _CITATION = r"""\
275
- {{ citation }}
276
- """ # noqa: W605
277
-
278
- _DESCRIPTION = """\
279
- {{ description }}
280
- """
281
-
282
- _NAMES = [
283
- {%- for name,metadata in data.items()|sort(attribute='1.dirname') %}
284
- "{{ name }}",
285
- {%- endfor %}
286
- ]
287
-
288
- _DESCRIPTIONS = {
289
- {%- for name,metadata in data.items()|sort(attribute='1.dirname') %}
290
- "{{ name }}": """{{ metadata.summary }}""",
291
- {%- endfor %}
292
- }
293
-
294
- _LICENSES = {
295
- {%- for name,metadata in data.items()|sort(attribute='1.dirname') %}
296
- "{{ name }}": "{{ metadata.license }}",
297
- {%- endfor %}
298
- }
299
-
300
- _PREFIX = "https://raw.githubusercontent.com/UniversalDependencies/"
301
- _UD_DATASETS = {
302
- {%- for name,metadata in data.items()|sort(attribute='1.dirname') %}
303
- "{{ name }}": {
304
- {%- for fileset_split_name,fileset_split_data in metadata.splits.items() %}
305
- "{{ fileset_split_name }}": {{ fileset_split_data.files }},
306
- {%- endfor %}
307
- },
308
- {%- endfor %}
309
- }
310
-
311
-
312
- @dataclass
313
- class UniversalDependenciesConfig(datasets.BuilderConfig):
314
- """BuilderConfig for Universal Dependencies"""
315
-
316
- def __init__(self, name: str, **kwargs):
317
- super().__init__(name, version=datasets.Version("{{ ud_ver }}.0"), **kwargs)
318
-
319
-
320
- class UniversalDependencies(datasets.GeneratorBasedBuilder):
321
- """Universal Dependencies Datasets"""
322
-
323
- BUILDER_CONFIGS = [
324
- UniversalDependenciesConfig(
325
- name=name,
326
- )
327
- for name in _NAMES
328
- ]
329
- BUILDER_CONFIG_CLASS = UniversalDependenciesConfig
330
-
331
- def _info(self):
332
- return datasets.DatasetInfo(
333
- homepage=f"https://github.com/UniversalDependencies/" + _UD_DATASETS[self.config.name]["test"][0].split("/")[0],
334
- description=_DESCRIPTIONS[self.config.name],
335
- citation=None, # would need to be the dataset specific citation
336
- license=_LICENSES[self.config.name],
337
- features=datasets.Features(
338
- {
339
- "sent_id": datasets.Value("string"),
340
- "text": datasets.Value("string"),
341
- "comments": datasets.Sequence(datasets.Value("string")),
342
- "tokens": datasets.Sequence(datasets.Value("string")),
343
- "lemmas": datasets.Sequence(datasets.Value("string")),
344
- "upos": datasets.Sequence(
345
- datasets.features.ClassLabel(
346
- names=[
347
- "NOUN",
348
- "PUNCT",
349
- "ADP",
350
- "NUM",
351
- "SYM",
352
- "SCONJ",
353
- "ADJ",
354
- "PART",
355
- "DET",
356
- "CCONJ",
357
- "PROPN",
358
- "PRON",
359
- "X",
360
- "_",
361
- "ADV",
362
- "INTJ",
363
- "VERB",
364
- "AUX",
365
- ]
366
- )
367
- ),
368
- "xpos": datasets.Sequence(datasets.Value("string")),
369
- "feats": datasets.Sequence(datasets.Value("string")),
370
- "head": datasets.Sequence(datasets.Value("string")),
371
- "deprel": datasets.Sequence(datasets.Value("string")),
372
- "deps": datasets.Sequence(datasets.Value("string")),
373
- "misc": datasets.Sequence(datasets.Value("string")),
374
- "mwt": datasets.Sequence(
375
- {
376
- "id": datasets.Value("string"),
377
- "form": datasets.Value("string"),
378
- "feats": datasets.Value("string"),
379
- "misc": datasets.Value("string"),
380
- }
381
- ),
382
- "empty_nodes": datasets.Sequence(
383
- {
384
- "id": datasets.Value("string"),
385
- "form": datasets.Value("string"),
386
- "lemma": datasets.Value("string"),
387
- "upos": datasets.Value("string"),
388
- "xpos": datasets.Value("string"),
389
- "feats": datasets.Value("string"),
390
- "head": datasets.Value("string"),
391
- "deprel": datasets.Value("string"),
392
- "deps": datasets.Value("string"),
393
- "misc": datasets.Value("string"),
394
- }
395
- ),
396
- }
397
- ),
398
- supervised_keys=None,
399
- )
400
-
401
- def _split_generators(self, dl_manager):
402
- """Returns SplitGenerators."""
403
- urls_to_download = {}
404
- for split, address in _UD_DATASETS[self.config.name].items():
405
- urls_to_download[split] = []
406
- if isinstance(address, list):
407
- for add in address:
408
- urls_to_download[split].append(_PREFIX + add)
409
- else:
410
- urls_to_download[split].append(_PREFIX + address)
411
-
412
- downloaded_files = dl_manager.download_and_extract(urls_to_download)
413
- splits = []
414
-
415
- if "train" in downloaded_files:
416
- splits.append(
417
- datasets.SplitGenerator(
418
- name=datasets.Split.TRAIN, gen_kwargs={"filepath": downloaded_files["train"]})
419
- )
420
-
421
- if "dev" in downloaded_files:
422
- splits.append(
423
- datasets.SplitGenerator(
424
- name=datasets.Split("dev"), gen_kwargs={"filepath": downloaded_files["dev"]}
425
- )
426
- )
427
-
428
- if "test" in downloaded_files:
429
- splits.append(
430
- datasets.SplitGenerator(
431
- name=datasets.Split.TEST, gen_kwargs={"filepath": downloaded_files["test"]})
432
- )
433
-
434
- return splits
435
-
436
- def _conllu_dict_to_string(self, value):
437
- """
438
- Convert CoNLL-U field value to standard CoNLL-U string format.
439
- Used for reconstruction/output.
440
- """
441
- if value is None:
442
- return "_"
443
- if isinstance(value, dict):
444
- if not value:
445
- return "_"
446
- # Convert dict to CoNLL-U format: Key=Value|Key2=Value2
447
- items = [f"{k}={v}" for k, v in sorted(value.items())]
448
- return "|".join(items)
449
- s = str(value)
450
- if s == "None":
451
- return "_"
452
- return s
453
-
454
- def _conllu_optional_field(self, value):
455
- """
456
- Convert CoNLL-U optional field value to Python representation.
457
- Returns None for unspecified values (_), proper format otherwise.
458
-
459
- Use for: XPOS, FEATS, DEPS, MISC (optional fields per UD spec)
460
- """
461
- if value is None:
462
- return None
463
- if isinstance(value, dict):
464
- if not value:
465
- return None # Empty dict = no features
466
- # Convert dict to CoNLL-U format: Key=Value|Key2=Value2
467
- items = [f"{k}={v}" for k, v in sorted(value.items())]
468
- return "|".join(items)
469
- # String value
470
- s = str(value)
471
- if s == "None" or s == "_" or s == "":
472
- return None
473
- return s
474
-
475
- def _extract_raw_fields(self, sentence_text):
476
- """Extract raw FEATS, XPOS, DEPS, and MISC fields to bypass conllu parsing bugs."""
477
- raw_fields = {}
478
-
479
- for line in sentence_text.split('\n'):
480
- line = line.strip()
481
- if not line or line.startswith('#'):
482
- continue
483
-
484
- fields = line.split('\t')
485
- if len(fields) < 10:
486
- continue
487
-
488
- token_id = fields[0]
489
- xpos = fields[4] if fields[4] != '_' else None
490
- feats = fields[5] if fields[5] != '_' else None
491
- deps = fields[8] if fields[8] != '_' else None
492
- misc = fields[9] if fields[9] != '_' else None
493
-
494
- raw_fields[token_id] = {
495
- 'xpos': xpos,
496
- 'feats': feats,
497
- 'deps': deps,
498
- 'misc': misc
499
- }
500
-
501
- return raw_fields
502
-
503
- def _extract_raw_comments(self, sentence_text):
504
- """Extract raw comment lines to preserve duplicates and empty values."""
505
- comments = []
506
- sent_id = None
507
- text = None
508
-
509
- for line in sentence_text.split('\n'):
510
- line = line.strip()
511
- if not line.startswith('#'):
512
- continue
513
-
514
- comment_content = line[1:].strip()
515
- if not comment_content:
516
- continue
517
-
518
- if ' = ' in comment_content:
519
- key, value = comment_content.split(' = ', 1)
520
- key = key.strip()
521
- value = value.strip()
522
-
523
- if key == 'sent_id':
524
- sent_id = value
525
- comments.append("__SENT_ID__")
526
- elif key == 'text':
527
- text = value
528
- comments.append("__TEXT__")
529
- else:
530
- # Preserve raw format including empty values
531
- if value:
532
- comments.append(f"{key} = {value}")
533
- else:
534
- comments.append(f"{key} =")
535
- else:
536
- # Comment without = (like "newpar" or "# newpar")
537
- comments.append(comment_content)
538
-
539
- return comments, sent_id, text
540
-
541
- def _generate_examples(self, filepath):
542
- id = 0
543
- for path in filepath:
544
- # Read raw file for comment extraction
545
- with open(path, "r", encoding="utf-8") as f:
546
- file_content = f.read()
547
- sentence_blocks = file_content.split('\n\n')
548
-
549
- with open(path, "r", encoding="utf-8") as data_file:
550
- tokenlist = list(conllu.parse_incr(data_file))
551
- for idx, sent in enumerate(tokenlist):
552
- # Extract raw comments and fields from original text
553
- if idx < len(sentence_blocks):
554
- comments, sent_id, text = self._extract_raw_comments(sentence_blocks[idx])
555
- raw_fields = self._extract_raw_fields(sentence_blocks[idx])
556
- else:
557
- comments = []
558
- sent_id = None
559
- text = None
560
- raw_fields = {}
561
-
562
- # Fallback to conllu metadata if needed
563
- if sent_id is None:
564
- if "sent_id" in sent.metadata:
565
- sent_id = sent.metadata["sent_id"]
566
- else:
567
- sent_id = str(id)
568
-
569
- if text is None and "text" in sent.metadata:
570
- text = sent.metadata["text"]
571
-
572
- # Note: comments and raw fields extracted from raw file, bypassing conllu bugs
573
-
574
- # Extract Multi-Word Tokens (MWTs) - tokens with tuple IDs like (1, '-', 2)
575
- # Note: Exclude empty nodes which have '.' as middle element: (22, '.', 1)
576
- # Per UD spec: MWTs can have ID, FORM, MISC, and optionally FEATS (for "Typo=Yes")
577
- mwts = []
578
- for token in sent:
579
- if isinstance(token["id"], tuple) and len(token["id"]) == 3 and token["id"][1] == '-':
580
- # MWT line (e.g., (1, '-', 2) for "1-2")
581
- mwt_id = f"{token['id'][0]}-{token['id'][2]}"
582
-
583
- # Use raw fields if available (bypasses conllu parsing bugs)
584
- if mwt_id in raw_fields:
585
- feats = raw_fields[mwt_id]['feats']
586
- misc = raw_fields[mwt_id]['misc']
587
- else:
588
- # Fallback to conllu parsed values
589
- feats = self._conllu_optional_field(token["feats"])
590
- misc = self._conllu_optional_field(token["misc"])
591
-
592
- mwts.append({
593
- "id": mwt_id,
594
- "form": token["form"],
595
- "feats": feats,
596
- "misc": misc
597
- })
598
-
599
- # Extract Empty Nodes - tokens with decimal IDs like 22.1
600
- # These are represented as tuples: (22, '.', 1)
601
- empty_nodes = []
602
- for token in sent:
603
- if isinstance(token["id"], tuple) and len(token["id"]) == 3 and token["id"][1] == '.':
604
- # Empty node (e.g., (22, '.', 1) for ID "22.1")
605
- empty_node_id = f"{token['id'][0]}.{token['id'][2]}"
606
-
607
- # Use raw fields if available (bypasses conllu parsing bugs)
608
- if empty_node_id in raw_fields:
609
- xpos = raw_fields[empty_node_id]['xpos']
610
- feats = raw_fields[empty_node_id]['feats']
611
- deps = raw_fields[empty_node_id]['deps']
612
- misc = raw_fields[empty_node_id]['misc']
613
- else:
614
- # Fallback to conllu parsed values
615
- xpos = token["xpos"] or None
616
- feats = self._conllu_dict_to_string(token["feats"])
617
- deps = self._conllu_dict_to_string(token["deps"])
618
- misc = self._conllu_dict_to_string(token["misc"])
619
-
620
- empty_nodes.append({
621
- "id": empty_node_id,
622
- "form": token["form"],
623
- "lemma": token["lemma"] or "_",
624
- "upos": token["upos"] or "_",
625
- "xpos": xpos or "_",
626
- "feats": feats,
627
- "head": str(token["head"]) if token["head"] is not None else "_",
628
- "deprel": str(token["deprel"]) if token["deprel"] else "_",
629
- "deps": deps,
630
- "misc": misc
631
- })
632
-
633
- # Filter to syntactic words only (exclude MWTs and empty nodes)
634
- sent_filtered = sent.filter(id=lambda x: type(x) is int)
635
-
636
- tokens = [token["form"] for token in sent_filtered]
637
-
638
- # If text wasn't in metadata, reconstruct from tokens
639
- if text is None:
640
- text = " ".join(tokens)
641
-
642
- # Extract fields for regular tokens, using raw fields when available
643
- xpos_list = []
644
- feats_list = []
645
- deps_list = []
646
- misc_list = []
647
-
648
- for token in sent_filtered:
649
- token_id = str(token["id"])
650
-
651
- # Use raw fields if available (bypasses conllu parsing bugs)
652
- if token_id in raw_fields:
653
- xpos_list.append(raw_fields[token_id]['xpos'])
654
- feats_list.append(raw_fields[token_id]['feats'])
655
- deps_list.append(raw_fields[token_id]['deps'])
656
- misc_list.append(raw_fields[token_id]['misc'])
657
- else:
658
- # Fallback to conllu parsed values
659
- xpos_list.append(self._conllu_optional_field(token["xpos"]))
660
- feats_list.append(self._conllu_optional_field(token["feats"]))
661
- deps_list.append(self._conllu_optional_field(token["deps"]))
662
- misc_list.append(self._conllu_optional_field(token["misc"]))
663
-
664
- # Yield example with proper types per UD specification:
665
- # - Required fields (FORM, LEMMA, UPOS, HEAD, DEPREL): always string
666
- # - Optional fields (XPOS, FEATS, DEPS, MISC): None when unspecified
667
- yield id, {
668
- "sent_id": sent_id,
669
- "text": text,
670
- "comments": comments,
671
- "tokens": tokens,
672
- "lemmas": [token["lemma"] for token in sent_filtered],
673
- "upos": [token["upos"] for token in sent_filtered],
674
- "xpos": xpos_list,
675
- "feats": feats_list,
676
- "head": [str(token["head"]) if token["head"] is not None else "_" for token in sent_filtered],
677
- "deprel": [str(token["deprel"]) if token["deprel"] else "_" for token in sent_filtered],
678
- "deps": deps_list,
679
- "misc": misc_list,
680
- "mwt": mwts,
681
- "empty_nodes": empty_nodes,
682
- }
683
- id += 1