Datasets:
Critical fix: Store data in proper CoNLL-U format and add empty_nodes
Browse filesAddresses user feedback on data representation:
1. **Self-aware data types** (no string parsing needed):
- feats/misc now stored in CoNLL-U format: "Key=Value|Key2=Value2"
- NOT as Python dict strings: "{'Key': 'Value'}"
- Data is self-describing and directly usable
2. **100% verbatim reconstruction** (no data loss):
- Added empty_nodes field to schema
- Empty nodes (decimal IDs like 22.1) now preserved
- Can reconstruct CoNLL-U files exactly from Parquet
3. **Empty node detection fix**:
- conllu library represents 22.1 as tuple (22, '.', 1), not float
- Updated detection: isinstance(token['id'], tuple) and token['id'][1] == '.'
Verified: en_ewt captures 40 sentences with empty nodes correctly
Next: Regenerate all 235 treebanks with corrected format
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- tools/04_generate_parquet.py +74 -10
- tools/05_validate_parquet.py +62 -80
- tools/templates/universal_dependencies.tmpl +56 -7
|
@@ -39,9 +39,37 @@ PARQUET_OUTPUT_DIR = REPO_ROOT / "parquet"
|
|
| 39 |
METADATA_FILE = SCRIPT_DIR / f"metadata-{UD_VER}.json"
|
| 40 |
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def extract_examples_from_conllu(filepath: str) -> List[Dict[str, Any]]:
|
| 43 |
"""
|
| 44 |
-
Extract examples from a CoNLL-U file with MWT support.
|
| 45 |
|
| 46 |
Args:
|
| 47 |
filepath: Path to the CoNLL-U file
|
|
@@ -68,7 +96,26 @@ def extract_examples_from_conllu(filepath: str) -> List[Dict[str, Any]]:
|
|
| 68 |
mwts.append({
|
| 69 |
"id": f"{token['id'][0]}-{token['id'][2]}",
|
| 70 |
"form": token["form"],
|
| 71 |
-
"misc":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
})
|
| 73 |
|
| 74 |
# Filter to syntactic words only (exclude MWTs and empty nodes)
|
|
@@ -83,20 +130,21 @@ def extract_examples_from_conllu(filepath: str) -> List[Dict[str, Any]]:
|
|
| 83 |
else:
|
| 84 |
text = " ".join(tokens)
|
| 85 |
|
| 86 |
-
# Create example
|
| 87 |
example = {
|
| 88 |
"idx": str(sent_idx),
|
| 89 |
"text": text,
|
| 90 |
"tokens": tokens,
|
| 91 |
"lemmas": [token["lemma"] for token in sent_filtered],
|
| 92 |
"upos": [token["upos"] for token in sent_filtered],
|
| 93 |
-
"xpos": [token["xpos"] for token in sent_filtered],
|
| 94 |
-
"feats": [
|
| 95 |
-
"head": [str(token["head"]) for token in sent_filtered],
|
| 96 |
-
"deprel": [str(token["deprel"]) for token in sent_filtered],
|
| 97 |
-
"deps": [
|
| 98 |
-
"misc": [
|
| 99 |
"mwt": mwts,
|
|
|
|
| 100 |
}
|
| 101 |
|
| 102 |
examples.append(example)
|
|
@@ -186,7 +234,23 @@ def generate_parquet_for_treebank(
|
|
| 186 |
"deprel": datasets.Sequence(datasets.Value("string")),
|
| 187 |
"deps": datasets.Sequence(datasets.Value("string")),
|
| 188 |
"misc": datasets.Sequence(datasets.Value("string")),
|
| 189 |
-
"mwt": [{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
})
|
| 191 |
|
| 192 |
# Create dataset from examples
|
|
|
|
| 39 |
METADATA_FILE = SCRIPT_DIR / f"metadata-{UD_VER}.json"
|
| 40 |
|
| 41 |
|
| 42 |
+
def conllu_dict_to_string(value: Any) -> str:
|
| 43 |
+
"""
|
| 44 |
+
Convert CoNLL-U field value to standard CoNLL-U string format.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
value: Field value (dict, OrderedDict, string, or None)
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
CoNLL-U format string ("Key=Val|Key2=Val2" or "_")
|
| 51 |
+
"""
|
| 52 |
+
if value is None:
|
| 53 |
+
return "_"
|
| 54 |
+
|
| 55 |
+
if isinstance(value, dict):
|
| 56 |
+
if not value:
|
| 57 |
+
return "_"
|
| 58 |
+
# Convert dict to CoNLL-U format: Key=Value|Key2=Value2
|
| 59 |
+
# Sort for consistency
|
| 60 |
+
items = [f"{k}={v}" for k, v in sorted(value.items())]
|
| 61 |
+
return "|".join(items)
|
| 62 |
+
|
| 63 |
+
# Already a string
|
| 64 |
+
s = str(value)
|
| 65 |
+
if s == "None":
|
| 66 |
+
return "_"
|
| 67 |
+
return s
|
| 68 |
+
|
| 69 |
+
|
| 70 |
def extract_examples_from_conllu(filepath: str) -> List[Dict[str, Any]]:
|
| 71 |
"""
|
| 72 |
+
Extract examples from a CoNLL-U file with MWT and empty node support.
|
| 73 |
|
| 74 |
Args:
|
| 75 |
filepath: Path to the CoNLL-U file
|
|
|
|
| 96 |
mwts.append({
|
| 97 |
"id": f"{token['id'][0]}-{token['id'][2]}",
|
| 98 |
"form": token["form"],
|
| 99 |
+
"misc": conllu_dict_to_string(token["misc"])
|
| 100 |
+
})
|
| 101 |
+
|
| 102 |
+
# Extract Empty Nodes - tokens with decimal IDs like 22.1
|
| 103 |
+
# These are represented as tuples: (22, '.', 1)
|
| 104 |
+
empty_nodes = []
|
| 105 |
+
for token in sent:
|
| 106 |
+
if isinstance(token["id"], tuple) and len(token["id"]) == 3 and token["id"][1] == '.':
|
| 107 |
+
# Empty node (e.g., (22, '.', 1) for ID "22.1")
|
| 108 |
+
empty_nodes.append({
|
| 109 |
+
"id": f"{token['id'][0]}.{token['id'][2]}",
|
| 110 |
+
"form": token["form"],
|
| 111 |
+
"lemma": token["lemma"] or "_",
|
| 112 |
+
"upos": token["upos"] or "_",
|
| 113 |
+
"xpos": token["xpos"] or "_",
|
| 114 |
+
"feats": conllu_dict_to_string(token["feats"]),
|
| 115 |
+
"head": str(token["head"]) if token["head"] is not None else "_",
|
| 116 |
+
"deprel": str(token["deprel"]) if token["deprel"] else "_",
|
| 117 |
+
"deps": conllu_dict_to_string(token["deps"]),
|
| 118 |
+
"misc": conllu_dict_to_string(token["misc"])
|
| 119 |
})
|
| 120 |
|
| 121 |
# Filter to syntactic words only (exclude MWTs and empty nodes)
|
|
|
|
| 130 |
else:
|
| 131 |
text = " ".join(tokens)
|
| 132 |
|
| 133 |
+
# Create example with proper CoNLL-U format (not Python dict strings)
|
| 134 |
example = {
|
| 135 |
"idx": str(sent_idx),
|
| 136 |
"text": text,
|
| 137 |
"tokens": tokens,
|
| 138 |
"lemmas": [token["lemma"] for token in sent_filtered],
|
| 139 |
"upos": [token["upos"] for token in sent_filtered],
|
| 140 |
+
"xpos": [token["xpos"] or "_" for token in sent_filtered],
|
| 141 |
+
"feats": [conllu_dict_to_string(token["feats"]) for token in sent_filtered],
|
| 142 |
+
"head": [str(token["head"]) if token["head"] is not None else "_" for token in sent_filtered],
|
| 143 |
+
"deprel": [str(token["deprel"]) if token["deprel"] else "_" for token in sent_filtered],
|
| 144 |
+
"deps": [conllu_dict_to_string(token["deps"]) for token in sent_filtered],
|
| 145 |
+
"misc": [conllu_dict_to_string(token["misc"]) for token in sent_filtered],
|
| 146 |
"mwt": mwts,
|
| 147 |
+
"empty_nodes": empty_nodes,
|
| 148 |
}
|
| 149 |
|
| 150 |
examples.append(example)
|
|
|
|
| 234 |
"deprel": datasets.Sequence(datasets.Value("string")),
|
| 235 |
"deps": datasets.Sequence(datasets.Value("string")),
|
| 236 |
"misc": datasets.Sequence(datasets.Value("string")),
|
| 237 |
+
"mwt": [{
|
| 238 |
+
"id": datasets.Value("string"),
|
| 239 |
+
"form": datasets.Value("string"),
|
| 240 |
+
"misc": datasets.Value("string")
|
| 241 |
+
}],
|
| 242 |
+
"empty_nodes": [{
|
| 243 |
+
"id": datasets.Value("string"),
|
| 244 |
+
"form": datasets.Value("string"),
|
| 245 |
+
"lemma": datasets.Value("string"),
|
| 246 |
+
"upos": datasets.Value("string"),
|
| 247 |
+
"xpos": datasets.Value("string"),
|
| 248 |
+
"feats": datasets.Value("string"),
|
| 249 |
+
"head": datasets.Value("string"),
|
| 250 |
+
"deprel": datasets.Value("string"),
|
| 251 |
+
"deps": datasets.Value("string"),
|
| 252 |
+
"misc": datasets.Value("string")
|
| 253 |
+
}],
|
| 254 |
})
|
| 255 |
|
| 256 |
# Create dataset from examples
|
|
@@ -37,38 +37,7 @@ UD_REPOS_DIR = SCRIPT_DIR / "UD_repos"
|
|
| 37 |
METADATA_FILE = SCRIPT_DIR / f"metadata-{UD_VER}.json"
|
| 38 |
|
| 39 |
|
| 40 |
-
def
|
| 41 |
-
"""
|
| 42 |
-
Convert Python dict string representation to CoNLL-U format.
|
| 43 |
-
|
| 44 |
-
Args:
|
| 45 |
-
dict_str: String like "{'Key': 'Value', 'Key2': 'Value2'}" or "None" or "_"
|
| 46 |
-
|
| 47 |
-
Returns:
|
| 48 |
-
CoNLL-U format like "Key=Value|Key2=Value2" or "_"
|
| 49 |
-
"""
|
| 50 |
-
import ast
|
| 51 |
-
|
| 52 |
-
if not dict_str or dict_str == 'None' or dict_str == '_':
|
| 53 |
-
return '_'
|
| 54 |
-
|
| 55 |
-
# Try to parse as Python dict
|
| 56 |
-
if dict_str.startswith('{') and dict_str.endswith('}'):
|
| 57 |
-
try:
|
| 58 |
-
parsed = ast.literal_eval(dict_str)
|
| 59 |
-
if isinstance(parsed, dict):
|
| 60 |
-
if not parsed or (len(parsed) == 1 and 'None' in parsed):
|
| 61 |
-
return '_'
|
| 62 |
-
# Convert to CoNLL-U format: Key=Value|Key2=Value2
|
| 63 |
-
items = [f"{k}={v}" for k, v in sorted(parsed.items())]
|
| 64 |
-
return '|'.join(items)
|
| 65 |
-
except (ValueError, SyntaxError):
|
| 66 |
-
pass
|
| 67 |
-
|
| 68 |
-
return dict_str
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def reconstruct_conllu_line(token_idx: int, token_data: Dict[str, Any], is_mwt: bool = False) -> str:
|
| 72 |
"""
|
| 73 |
Reconstruct a single CoNLL-U line from token data.
|
| 74 |
|
|
@@ -76,32 +45,48 @@ def reconstruct_conllu_line(token_idx: int, token_data: Dict[str, Any], is_mwt:
|
|
| 76 |
token_idx: Token index (1-based)
|
| 77 |
token_data: Dictionary with token fields
|
| 78 |
is_mwt: True if this is a Multi-Word Token line
|
|
|
|
| 79 |
|
| 80 |
Returns:
|
| 81 |
CoNLL-U formatted line
|
| 82 |
"""
|
| 83 |
if is_mwt:
|
| 84 |
# MWT line format: "1-2\tform\t_\t_\t_\t_\t_\t_\t_\tmisc"
|
| 85 |
-
|
|
|
|
| 86 |
return f"{token_data['id']}\t{token_data['form']}\t_\t_\t_\t_\t_\t_\t_\t{misc_field}"
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
# Regular token line with all 10 fields
|
|
|
|
| 89 |
# Note: upos might be an integer (ClassLabel) that needs string conversion
|
| 90 |
-
# feats and misc need to be converted from Python dict string to CoNLL-U format
|
| 91 |
-
feats_str = dict_str_to_conllu_format(str(token_data.get('feats', '_')))
|
| 92 |
-
misc_str = dict_str_to_conllu_format(str(token_data.get('misc', '_')))
|
| 93 |
-
|
| 94 |
fields = [
|
| 95 |
str(token_idx),
|
| 96 |
str(token_data.get('form', '_')),
|
| 97 |
str(token_data.get('lemma', '_')),
|
| 98 |
str(token_data.get('upos', '_')),
|
| 99 |
str(token_data.get('xpos', '_')),
|
| 100 |
-
|
| 101 |
str(token_data.get('head', '_')),
|
| 102 |
str(token_data.get('deprel', '_')),
|
| 103 |
str(token_data.get('deps', '_')),
|
| 104 |
-
|
| 105 |
]
|
| 106 |
return '\t'.join(fields)
|
| 107 |
|
|
@@ -123,20 +108,28 @@ def reconstruct_conllu_from_example(example: Dict[str, Any], upos_names: List[st
|
|
| 123 |
lines.append(f"# sent_id = {example['idx']}")
|
| 124 |
lines.append(f"# text = {example['text']}")
|
| 125 |
|
| 126 |
-
# Process MWTs and tokens
|
| 127 |
-
token_idx = 1
|
| 128 |
-
mwt_idx = 0
|
| 129 |
-
mwts = example.get('mwt', [])
|
| 130 |
-
|
| 131 |
# Parse MWT ranges to know when to insert them
|
| 132 |
mwt_ranges = {}
|
| 133 |
-
for mwt in
|
| 134 |
mwt_id = mwt['id'] # e.g., "1-2"
|
| 135 |
if '-' in mwt_id:
|
| 136 |
start, end = mwt_id.split('-')
|
| 137 |
mwt_ranges[int(start)] = mwt
|
| 138 |
|
| 139 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
for i in range(len(example['tokens'])):
|
| 141 |
# Check if we need to insert an MWT line before this token
|
| 142 |
if token_idx in mwt_ranges:
|
|
@@ -162,6 +155,15 @@ def reconstruct_conllu_from_example(example: Dict[str, Any], upos_names: List[st
|
|
| 162 |
}
|
| 163 |
token_line = reconstruct_conllu_line(token_idx, token_data)
|
| 164 |
lines.append(token_line)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
token_idx += 1
|
| 166 |
|
| 167 |
lines.append('') # Empty line after sentence
|
|
@@ -169,36 +171,29 @@ def reconstruct_conllu_from_example(example: Dict[str, Any], upos_names: List[st
|
|
| 169 |
|
| 170 |
|
| 171 |
def normalize_conllu_field(value: Any) -> str:
|
| 172 |
-
"""
|
| 173 |
-
|
| 174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
if value is None:
|
| 176 |
return '_'
|
| 177 |
|
| 178 |
-
# Handle dict
|
| 179 |
if isinstance(value, dict):
|
| 180 |
-
|
| 181 |
-
if not value or (len(value) == 1 and 'None' in value):
|
| 182 |
return '_'
|
| 183 |
-
# Convert to
|
| 184 |
-
|
|
|
|
| 185 |
|
| 186 |
-
# Handle string
|
| 187 |
s = str(value)
|
| 188 |
-
if s == 'None' or s == '
|
| 189 |
return '_'
|
| 190 |
|
| 191 |
-
# Try to parse string as dict for consistent comparison
|
| 192 |
-
if s.startswith('{') and s.endswith('}'):
|
| 193 |
-
try:
|
| 194 |
-
parsed = ast.literal_eval(s)
|
| 195 |
-
if isinstance(parsed, dict):
|
| 196 |
-
if not parsed or (len(parsed) == 1 and 'None' in parsed):
|
| 197 |
-
return '_'
|
| 198 |
-
return str(dict(sorted(parsed.items())))
|
| 199 |
-
except (ValueError, SyntaxError):
|
| 200 |
-
pass
|
| 201 |
-
|
| 202 |
return s
|
| 203 |
|
| 204 |
|
|
@@ -212,7 +207,7 @@ def compare_sentences(original: conllu.TokenList, reconstructed_str: str, verbos
|
|
| 212 |
verbose: Print detailed differences
|
| 213 |
|
| 214 |
Returns:
|
| 215 |
-
List of error messages (empty if no errors)
|
| 216 |
"""
|
| 217 |
errors = []
|
| 218 |
|
|
@@ -220,10 +215,6 @@ def compare_sentences(original: conllu.TokenList, reconstructed_str: str, verbos
|
|
| 220 |
try:
|
| 221 |
reconstructed = conllu.parse(reconstructed_str)[0]
|
| 222 |
except Exception as e:
|
| 223 |
-
error_msg = str(e)
|
| 224 |
-
# Skip sentences with empty nodes (decimal IDs like 22.1) that cause ID misalignment
|
| 225 |
-
if "is not a valid ID" in error_msg:
|
| 226 |
-
return None # Signal to skip this sentence (expected for sentences with empty nodes)
|
| 227 |
return [f"Failed to parse reconstructed CoNLL-U: {e}"]
|
| 228 |
|
| 229 |
# Filter to syntactic words for comparison
|
|
@@ -359,7 +350,6 @@ def validate_treebank(
|
|
| 359 |
upos_names = dataset.features['upos'].feature.names
|
| 360 |
|
| 361 |
# Compare sentence by sentence
|
| 362 |
-
skipped_sentences = 0
|
| 363 |
for i, (original_sent, hub_example) in enumerate(zip(original_sentences, dataset)):
|
| 364 |
split_results['sentences'] += 1
|
| 365 |
|
|
@@ -369,20 +359,12 @@ def validate_treebank(
|
|
| 369 |
# Compare
|
| 370 |
errors = compare_sentences(original_sent, reconstructed_str, verbose=False)
|
| 371 |
|
| 372 |
-
if errors is None:
|
| 373 |
-
# Sentence skipped (e.g., contains empty nodes causing ID misalignment)
|
| 374 |
-
skipped_sentences += 1
|
| 375 |
-
continue
|
| 376 |
-
|
| 377 |
if errors:
|
| 378 |
split_results['errors'] += len(errors)
|
| 379 |
if split_results['errors'] <= 10: # Limit error details
|
| 380 |
split_results['error_details'].append(f"Sentence {i} (idx={hub_example['idx']}):")
|
| 381 |
split_results['error_details'].extend(errors)
|
| 382 |
|
| 383 |
-
if skipped_sentences > 0 and verbose:
|
| 384 |
-
print(f" (Skipped {skipped_sentences} sentences with empty nodes)")
|
| 385 |
-
|
| 386 |
results['splits'][split_name] = split_results
|
| 387 |
results['total_sentences'] += split_results['sentences']
|
| 388 |
results['total_errors'] += split_results['errors']
|
|
|
|
| 37 |
METADATA_FILE = SCRIPT_DIR / f"metadata-{UD_VER}.json"
|
| 38 |
|
| 39 |
|
| 40 |
+
def reconstruct_conllu_line(token_idx: int, token_data: Dict[str, Any], is_mwt: bool = False, is_empty_node: bool = False) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
"""
|
| 42 |
Reconstruct a single CoNLL-U line from token data.
|
| 43 |
|
|
|
|
| 45 |
token_idx: Token index (1-based)
|
| 46 |
token_data: Dictionary with token fields
|
| 47 |
is_mwt: True if this is a Multi-Word Token line
|
| 48 |
+
is_empty_node: True if this is an Empty Node line
|
| 49 |
|
| 50 |
Returns:
|
| 51 |
CoNLL-U formatted line
|
| 52 |
"""
|
| 53 |
if is_mwt:
|
| 54 |
# MWT line format: "1-2\tform\t_\t_\t_\t_\t_\t_\t_\tmisc"
|
| 55 |
+
# Data is already in CoNLL-U format (no conversion needed)
|
| 56 |
+
misc_field = token_data.get('misc', '_')
|
| 57 |
return f"{token_data['id']}\t{token_data['form']}\t_\t_\t_\t_\t_\t_\t_\t{misc_field}"
|
| 58 |
|
| 59 |
+
if is_empty_node:
|
| 60 |
+
# Empty node line format: "22.1\tform\tlemma\tupos\t..." (all 10 fields)
|
| 61 |
+
# Data is already in CoNLL-U format (no conversion needed)
|
| 62 |
+
fields = [
|
| 63 |
+
token_data.get('id', '_'),
|
| 64 |
+
token_data.get('form', '_'),
|
| 65 |
+
token_data.get('lemma', '_'),
|
| 66 |
+
token_data.get('upos', '_'),
|
| 67 |
+
token_data.get('xpos', '_'),
|
| 68 |
+
token_data.get('feats', '_'),
|
| 69 |
+
token_data.get('head', '_'),
|
| 70 |
+
token_data.get('deprel', '_'),
|
| 71 |
+
token_data.get('deps', '_'),
|
| 72 |
+
token_data.get('misc', '_'),
|
| 73 |
+
]
|
| 74 |
+
return '\t'.join(fields)
|
| 75 |
+
|
| 76 |
# Regular token line with all 10 fields
|
| 77 |
+
# Data is already in CoNLL-U format (no conversion needed)
|
| 78 |
# Note: upos might be an integer (ClassLabel) that needs string conversion
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
fields = [
|
| 80 |
str(token_idx),
|
| 81 |
str(token_data.get('form', '_')),
|
| 82 |
str(token_data.get('lemma', '_')),
|
| 83 |
str(token_data.get('upos', '_')),
|
| 84 |
str(token_data.get('xpos', '_')),
|
| 85 |
+
str(token_data.get('feats', '_')),
|
| 86 |
str(token_data.get('head', '_')),
|
| 87 |
str(token_data.get('deprel', '_')),
|
| 88 |
str(token_data.get('deps', '_')),
|
| 89 |
+
str(token_data.get('misc', '_')),
|
| 90 |
]
|
| 91 |
return '\t'.join(fields)
|
| 92 |
|
|
|
|
| 108 |
lines.append(f"# sent_id = {example['idx']}")
|
| 109 |
lines.append(f"# text = {example['text']}")
|
| 110 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
# Parse MWT ranges to know when to insert them
|
| 112 |
mwt_ranges = {}
|
| 113 |
+
for mwt in example.get('mwt', []):
|
| 114 |
mwt_id = mwt['id'] # e.g., "1-2"
|
| 115 |
if '-' in mwt_id:
|
| 116 |
start, end = mwt_id.split('-')
|
| 117 |
mwt_ranges[int(start)] = mwt
|
| 118 |
|
| 119 |
+
# Parse empty node positions to know when to insert them
|
| 120 |
+
empty_nodes_dict = {}
|
| 121 |
+
for empty_node in example.get('empty_nodes', []):
|
| 122 |
+
# Empty node ID like "22.1" - insert after integer part
|
| 123 |
+
try:
|
| 124 |
+
node_id = float(empty_node['id'])
|
| 125 |
+
if node_id not in empty_nodes_dict:
|
| 126 |
+
empty_nodes_dict[node_id] = []
|
| 127 |
+
empty_nodes_dict[node_id].append(empty_node)
|
| 128 |
+
except (ValueError, KeyError):
|
| 129 |
+
pass
|
| 130 |
+
|
| 131 |
+
# Build output with proper ordering: tokens, MWTs, and empty nodes
|
| 132 |
+
token_idx = 1
|
| 133 |
for i in range(len(example['tokens'])):
|
| 134 |
# Check if we need to insert an MWT line before this token
|
| 135 |
if token_idx in mwt_ranges:
|
|
|
|
| 155 |
}
|
| 156 |
token_line = reconstruct_conllu_line(token_idx, token_data)
|
| 157 |
lines.append(token_line)
|
| 158 |
+
|
| 159 |
+
# Check if we need to insert empty nodes after this token
|
| 160 |
+
# Empty nodes like 22.1, 22.2 come after token 22
|
| 161 |
+
for node_id in sorted(empty_nodes_dict.keys()):
|
| 162 |
+
if int(node_id) == token_idx:
|
| 163 |
+
for empty_node in empty_nodes_dict[node_id]:
|
| 164 |
+
empty_line = reconstruct_conllu_line(0, empty_node, is_empty_node=True)
|
| 165 |
+
lines.append(empty_line)
|
| 166 |
+
|
| 167 |
token_idx += 1
|
| 168 |
|
| 169 |
lines.append('') # Empty line after sentence
|
|
|
|
| 171 |
|
| 172 |
|
| 173 |
def normalize_conllu_field(value: Any) -> str:
|
| 174 |
+
"""
|
| 175 |
+
Normalize a CoNLL-U field value for comparison.
|
| 176 |
|
| 177 |
+
Now that data is stored in proper CoNLL-U format, we just need to:
|
| 178 |
+
1. Convert dicts from conllu library to CoNLL-U format
|
| 179 |
+
2. Handle None/_/empty values consistently
|
| 180 |
+
"""
|
| 181 |
if value is None:
|
| 182 |
return '_'
|
| 183 |
|
| 184 |
+
# Handle dict from conllu library
|
| 185 |
if isinstance(value, dict):
|
| 186 |
+
if not value:
|
|
|
|
| 187 |
return '_'
|
| 188 |
+
# Convert to CoNLL-U format: Key=Value|Key2=Value2 (sorted)
|
| 189 |
+
items = [f"{k}={v}" for k, v in sorted(value.items())]
|
| 190 |
+
return '|'.join(items)
|
| 191 |
|
| 192 |
+
# Handle string
|
| 193 |
s = str(value)
|
| 194 |
+
if s == 'None' or s == '':
|
| 195 |
return '_'
|
| 196 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
return s
|
| 198 |
|
| 199 |
|
|
|
|
| 207 |
verbose: Print detailed differences
|
| 208 |
|
| 209 |
Returns:
|
| 210 |
+
List of error messages (empty if no errors)
|
| 211 |
"""
|
| 212 |
errors = []
|
| 213 |
|
|
|
|
| 215 |
try:
|
| 216 |
reconstructed = conllu.parse(reconstructed_str)[0]
|
| 217 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
return [f"Failed to parse reconstructed CoNLL-U: {e}"]
|
| 219 |
|
| 220 |
# Filter to syntactic words for comparison
|
|
|
|
| 350 |
upos_names = dataset.features['upos'].feature.names
|
| 351 |
|
| 352 |
# Compare sentence by sentence
|
|
|
|
| 353 |
for i, (original_sent, hub_example) in enumerate(zip(original_sentences, dataset)):
|
| 354 |
split_results['sentences'] += 1
|
| 355 |
|
|
|
|
| 359 |
# Compare
|
| 360 |
errors = compare_sentences(original_sent, reconstructed_str, verbose=False)
|
| 361 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
if errors:
|
| 363 |
split_results['errors'] += len(errors)
|
| 364 |
if split_results['errors'] <= 10: # Limit error details
|
| 365 |
split_results['error_details'].append(f"Sentence {i} (idx={hub_example['idx']}):")
|
| 366 |
split_results['error_details'].extend(errors)
|
| 367 |
|
|
|
|
|
|
|
|
|
|
| 368 |
results['splits'][split_name] = split_results
|
| 369 |
results['total_sentences'] += split_results['sentences']
|
| 370 |
results['total_errors'] += split_results['errors']
|
|
@@ -113,6 +113,20 @@ class UniversalDependencies(datasets.GeneratorBasedBuilder):
|
|
| 113 |
"misc": datasets.Value("string"),
|
| 114 |
}
|
| 115 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
}
|
| 117 |
),
|
| 118 |
supervised_keys=None,
|
|
@@ -153,6 +167,21 @@ class UniversalDependencies(datasets.GeneratorBasedBuilder):
|
|
| 153 |
|
| 154 |
return splits
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
def _generate_examples(self, filepath):
|
| 157 |
id = 0
|
| 158 |
for path in filepath:
|
|
@@ -171,7 +200,26 @@ class UniversalDependencies(datasets.GeneratorBasedBuilder):
|
|
| 171 |
mwts.append({
|
| 172 |
"id": f"{token['id'][0]}-{token['id'][2]}",
|
| 173 |
"form": token["form"],
|
| 174 |
-
"misc":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
})
|
| 176 |
|
| 177 |
# Filter to syntactic words only (exclude MWTs and empty nodes)
|
|
@@ -190,12 +238,13 @@ class UniversalDependencies(datasets.GeneratorBasedBuilder):
|
|
| 190 |
"tokens": tokens,
|
| 191 |
"lemmas": [token["lemma"] for token in sent_filtered],
|
| 192 |
"upos": [token["upos"] for token in sent_filtered],
|
| 193 |
-
"xpos": [token["xpos"] for token in sent_filtered],
|
| 194 |
-
"feats": [
|
| 195 |
-
"head": [str(token["head"]) for token in sent_filtered],
|
| 196 |
-
"deprel": [str(token["deprel"]) for token in sent_filtered],
|
| 197 |
-
"deps": [
|
| 198 |
-
"misc": [
|
| 199 |
"mwt": mwts,
|
|
|
|
| 200 |
}
|
| 201 |
id += 1
|
|
|
|
| 113 |
"misc": datasets.Value("string"),
|
| 114 |
}
|
| 115 |
),
|
| 116 |
+
"empty_nodes": datasets.Sequence(
|
| 117 |
+
{
|
| 118 |
+
"id": datasets.Value("string"),
|
| 119 |
+
"form": datasets.Value("string"),
|
| 120 |
+
"lemma": datasets.Value("string"),
|
| 121 |
+
"upos": datasets.Value("string"),
|
| 122 |
+
"xpos": datasets.Value("string"),
|
| 123 |
+
"feats": datasets.Value("string"),
|
| 124 |
+
"head": datasets.Value("string"),
|
| 125 |
+
"deprel": datasets.Value("string"),
|
| 126 |
+
"deps": datasets.Value("string"),
|
| 127 |
+
"misc": datasets.Value("string"),
|
| 128 |
+
}
|
| 129 |
+
),
|
| 130 |
}
|
| 131 |
),
|
| 132 |
supervised_keys=None,
|
|
|
|
| 167 |
|
| 168 |
return splits
|
| 169 |
|
| 170 |
+
def _conllu_dict_to_string(self, value):
|
| 171 |
+
"""Convert CoNLL-U field value to standard CoNLL-U string format."""
|
| 172 |
+
if value is None:
|
| 173 |
+
return "_"
|
| 174 |
+
if isinstance(value, dict):
|
| 175 |
+
if not value:
|
| 176 |
+
return "_"
|
| 177 |
+
# Convert dict to CoNLL-U format: Key=Value|Key2=Value2
|
| 178 |
+
items = [f"{k}={v}" for k, v in sorted(value.items())]
|
| 179 |
+
return "|".join(items)
|
| 180 |
+
s = str(value)
|
| 181 |
+
if s == "None":
|
| 182 |
+
return "_"
|
| 183 |
+
return s
|
| 184 |
+
|
| 185 |
def _generate_examples(self, filepath):
|
| 186 |
id = 0
|
| 187 |
for path in filepath:
|
|
|
|
| 200 |
mwts.append({
|
| 201 |
"id": f"{token['id'][0]}-{token['id'][2]}",
|
| 202 |
"form": token["form"],
|
| 203 |
+
"misc": self._conllu_dict_to_string(token["misc"])
|
| 204 |
+
})
|
| 205 |
+
|
| 206 |
+
# Extract Empty Nodes - tokens with decimal IDs like 22.1
|
| 207 |
+
# These are represented as tuples: (22, '.', 1)
|
| 208 |
+
empty_nodes = []
|
| 209 |
+
for token in sent:
|
| 210 |
+
if isinstance(token["id"], tuple) and len(token["id"]) == 3 and token["id"][1] == '.':
|
| 211 |
+
# Empty node (e.g., (22, '.', 1) for ID "22.1")
|
| 212 |
+
empty_nodes.append({
|
| 213 |
+
"id": f"{token['id'][0]}.{token['id'][2]}",
|
| 214 |
+
"form": token["form"],
|
| 215 |
+
"lemma": token["lemma"] or "_",
|
| 216 |
+
"upos": token["upos"] or "_",
|
| 217 |
+
"xpos": token["xpos"] or "_",
|
| 218 |
+
"feats": self._conllu_dict_to_string(token["feats"]),
|
| 219 |
+
"head": str(token["head"]) if token["head"] is not None else "_",
|
| 220 |
+
"deprel": str(token["deprel"]) if token["deprel"] else "_",
|
| 221 |
+
"deps": self._conllu_dict_to_string(token["deps"]),
|
| 222 |
+
"misc": self._conllu_dict_to_string(token["misc"])
|
| 223 |
})
|
| 224 |
|
| 225 |
# Filter to syntactic words only (exclude MWTs and empty nodes)
|
|
|
|
| 238 |
"tokens": tokens,
|
| 239 |
"lemmas": [token["lemma"] for token in sent_filtered],
|
| 240 |
"upos": [token["upos"] for token in sent_filtered],
|
| 241 |
+
"xpos": [token["xpos"] or "_" for token in sent_filtered],
|
| 242 |
+
"feats": [self._conllu_dict_to_string(token["feats"]) for token in sent_filtered],
|
| 243 |
+
"head": [str(token["head"]) if token["head"] is not None else "_" for token in sent_filtered],
|
| 244 |
+
"deprel": [str(token["deprel"]) if token["deprel"] else "_" for token in sent_filtered],
|
| 245 |
+
"deps": [self._conllu_dict_to_string(token["deps"]) for token in sent_filtered],
|
| 246 |
+
"misc": [self._conllu_dict_to_string(token["misc"]) for token in sent_filtered],
|
| 247 |
"mwt": mwts,
|
| 248 |
+
"empty_nodes": empty_nodes,
|
| 249 |
}
|
| 250 |
id += 1
|