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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Convert sentences to Universal Dependencies format compatible with HuggingFace.
|
| 3 |
+
Structure follows: https://huggingface.co/datasets/commul/universal_dependencies/viewer/vi_vtb
|
| 4 |
+
Uses underthesea dependency_parse for proper annotations.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
from os.path import dirname, expanduser, join
|
| 9 |
+
|
| 10 |
+
from underthesea import dependency_parse, pos_tag
|
| 11 |
+
|
| 12 |
+
# Map Vietnamese POS tags to Universal POS tags
|
| 13 |
+
# Based on: https://universaldependencies.org/u/pos/
|
| 14 |
+
UPOS_MAP = {
|
| 15 |
+
'N': 'NOUN', # Noun
|
| 16 |
+
'Np': 'PROPN', # Proper noun
|
| 17 |
+
'Nc': 'NOUN', # Classifier noun
|
| 18 |
+
'Nu': 'NOUN', # Unit noun
|
| 19 |
+
'V': 'VERB', # Verb
|
| 20 |
+
'A': 'ADJ', # Adjective
|
| 21 |
+
'P': 'PRON', # Pronoun
|
| 22 |
+
'R': 'ADV', # Adverb
|
| 23 |
+
'L': 'DET', # Determiner/Quantifier
|
| 24 |
+
'M': 'NUM', # Numeral
|
| 25 |
+
'E': 'ADP', # Preposition
|
| 26 |
+
'C': 'CCONJ', # Coordinating conjunction
|
| 27 |
+
'CC': 'CCONJ', # Coordinating conjunction
|
| 28 |
+
'SC': 'SCONJ', # Subordinating conjunction
|
| 29 |
+
'I': 'INTJ', # Interjection
|
| 30 |
+
'T': 'PART', # Particle
|
| 31 |
+
'B': 'X', # Foreign word
|
| 32 |
+
'Y': 'X', # Abbreviation
|
| 33 |
+
'S': 'SYM', # Symbol
|
| 34 |
+
'X': 'X', # Other
|
| 35 |
+
'CH': 'PUNCT', # Punctuation
|
| 36 |
+
'Ny': 'NOUN', # Noun (variant)
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
# Vietnamese auxiliary verbs that should be tagged as AUX
|
| 40 |
+
# Based on UD Vietnamese validation data (data.json)
|
| 41 |
+
AUX_WORDS = {
|
| 42 |
+
'bị', 'chưa thể', 'chắc chắn', 'có thể', 'có vẻ', 'cần',
|
| 43 |
+
'giả', 'không thể', 'là', 'muốn', 'nghĩa là', 'nhằm',
|
| 44 |
+
'nên', 'phải', 'quyết', 'thôi', 'thể', 'xong', 'được', 'định'
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
# Vietnamese determiners - words that should be DET when used as 'det' relation
|
| 48 |
+
DET_WORDS = {
|
| 49 |
+
'các', 'những', 'mọi', 'mỗi', 'từng', 'bất kỳ', 'một', 'hai', 'ba',
|
| 50 |
+
'này', 'đó', 'kia', 'ấy', 'nọ', 'nào', 'đấy', 'cái', 'con', 'chiếc',
|
| 51 |
+
'người', 'cả', 'phá tán' # Words that appear as det in the data
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
# Words that can be ADV when used as 'advmod'
|
| 55 |
+
ADV_WORDS = {
|
| 56 |
+
'không', 'chưa', 'đã', 'đang', 'sẽ', 'còn', 'vẫn', 'cũng', 'rất',
|
| 57 |
+
'quá', 'lắm', 'hơn', 'nhất', 'luôn', 'thường', 'hay', 'ít', 'nhiều',
|
| 58 |
+
'tự', 'một cách', 'được', 'không thể', 'lại', 'cá biệt', 'dân sự'
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
# Invalid deprels that need to be mapped to valid ones
|
| 62 |
+
DEPREL_MAP = {
|
| 63 |
+
'acomp': 'xcomp', # Adjectival complement -> open clausal complement
|
| 64 |
+
'nmod:comp': 'nmod', # Invalid subtype
|
| 65 |
+
'nmod:agent': 'obl:agent', # Agent should be obl not nmod
|
| 66 |
+
'nmod:with': 'nmod', # Invalid subtype
|
| 67 |
+
'nmod:about': 'nmod', # Invalid subtype -> nmod
|
| 68 |
+
'compound:number': 'nummod', # Number compounds should be nummod
|
| 69 |
+
'compound:nmod': 'compound', # Invalid subtype
|
| 70 |
+
'obl:pcomp': 'obl', # Invalid subtype -> obl
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def to_upos(tag, token=None):
|
| 75 |
+
"""Convert Vietnamese POS tag to Universal POS tag."""
|
| 76 |
+
# Check if token is an auxiliary verb (case insensitive)
|
| 77 |
+
if token:
|
| 78 |
+
token_lower = token.lower()
|
| 79 |
+
if token_lower in AUX_WORDS:
|
| 80 |
+
return 'AUX'
|
| 81 |
+
# Also check if lowercased token matches
|
| 82 |
+
for aux in AUX_WORDS:
|
| 83 |
+
if token_lower == aux.lower():
|
| 84 |
+
return 'AUX'
|
| 85 |
+
return UPOS_MAP.get(tag, 'X')
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def fix_syntax_errors(tokens, upos, head, deprel):
|
| 89 |
+
"""
|
| 90 |
+
Post-process to fix common UD SYNTAX validation errors.
|
| 91 |
+
Returns fixed (upos, deprel) lists.
|
| 92 |
+
Run multiple passes to handle dependencies between fixes.
|
| 93 |
+
"""
|
| 94 |
+
n = len(tokens)
|
| 95 |
+
upos = list(upos)
|
| 96 |
+
deprel = list(deprel)
|
| 97 |
+
head = [int(h) for h in head]
|
| 98 |
+
|
| 99 |
+
# First pass: fix leaf nodes (aux/mark/case/punct should not have children)
|
| 100 |
+
# Need multiple passes to handle chains of leaf nodes
|
| 101 |
+
for _ in range(5): # Multiple passes to handle chains
|
| 102 |
+
changed = False
|
| 103 |
+
for i in range(n):
|
| 104 |
+
rel = deprel[i]
|
| 105 |
+
|
| 106 |
+
# Leaf nodes should not have children - redirect children to parent
|
| 107 |
+
# Include subtypes like aux:pass, mark:pcomp, etc.
|
| 108 |
+
# Also include det, nummod, clf which should be leaves
|
| 109 |
+
if rel.split(':')[0] in ('aux', 'cop', 'mark', 'case', 'punct', 'det', 'nummod', 'clf'):
|
| 110 |
+
has_children = any(head[j] == i + 1 for j in range(n))
|
| 111 |
+
if has_children:
|
| 112 |
+
my_head = head[i]
|
| 113 |
+
for j in range(n):
|
| 114 |
+
if head[j] == i + 1:
|
| 115 |
+
head[j] = my_head
|
| 116 |
+
changed = True
|
| 117 |
+
if not changed:
|
| 118 |
+
break
|
| 119 |
+
|
| 120 |
+
for i in range(n):
|
| 121 |
+
token_lower = tokens[i].lower()
|
| 122 |
+
rel = deprel[i]
|
| 123 |
+
pos = upos[i]
|
| 124 |
+
|
| 125 |
+
# Fix 0: Map invalid deprels to valid ones
|
| 126 |
+
if rel in DEPREL_MAP:
|
| 127 |
+
deprel[i] = DEPREL_MAP[rel]
|
| 128 |
+
rel = deprel[i]
|
| 129 |
+
|
| 130 |
+
# Fix 1: rel-upos-det - 'det' (including subtypes) should be DET or PRON
|
| 131 |
+
if rel.startswith('det') and pos not in ('DET', 'PRON'):
|
| 132 |
+
# Force all 'det' relations to have DET or PRON UPOS
|
| 133 |
+
upos[i] = 'DET'
|
| 134 |
+
|
| 135 |
+
# Fix 2: rel-upos-advmod - 'advmod' (including subtypes) should be ADV
|
| 136 |
+
if rel.startswith('advmod') and pos != 'ADV':
|
| 137 |
+
# For advmod, always prefer changing UPOS to ADV
|
| 138 |
+
upos[i] = 'ADV'
|
| 139 |
+
|
| 140 |
+
# Fix 2b: rel-upos-nummod - 'nummod' should be NUM
|
| 141 |
+
if rel.startswith('nummod') and upos[i] != 'NUM':
|
| 142 |
+
# If token is clearly not a number (e.g., VERB), change relation instead
|
| 143 |
+
if upos[i] == 'VERB':
|
| 144 |
+
deprel[i] = 'acl' # Adjectival clause for verbs
|
| 145 |
+
rel = 'acl' # Update local variable too
|
| 146 |
+
elif upos[i] == 'ADJ':
|
| 147 |
+
deprel[i] = 'amod' # Adjectival modifier
|
| 148 |
+
rel = 'amod'
|
| 149 |
+
else:
|
| 150 |
+
upos[i] = 'NUM'
|
| 151 |
+
|
| 152 |
+
# Fix 3: rel-upos-mark - 'mark' (including subtypes) should not be AUX
|
| 153 |
+
if rel.startswith('mark') and pos == 'AUX':
|
| 154 |
+
upos[i] = 'SCONJ'
|
| 155 |
+
|
| 156 |
+
# Fix 3b: rel-upos-punct - 'punct' must be PUNCT, and PUNCT must have 'punct' deprel
|
| 157 |
+
if rel == 'punct' and pos != 'PUNCT':
|
| 158 |
+
# Change relation to something appropriate based on POS
|
| 159 |
+
if pos in ('VERB', 'NOUN', 'ADJ'):
|
| 160 |
+
deprel[i] = 'dep' # Use generic dependency
|
| 161 |
+
else:
|
| 162 |
+
upos[i] = 'PUNCT'
|
| 163 |
+
|
| 164 |
+
# Fix 3b2: upos-rel-punct - PUNCT must have 'punct' deprel
|
| 165 |
+
if pos == 'PUNCT' and rel != 'punct':
|
| 166 |
+
deprel[i] = 'punct'
|
| 167 |
+
rel = 'punct'
|
| 168 |
+
|
| 169 |
+
# Fix 3c: rel-upos-case - 'case' should be ADP, not ADJ, AUX or PROPN
|
| 170 |
+
if rel == 'case' and pos in ('ADJ', 'AUX', 'PROPN', 'NOUN', 'VERB'):
|
| 171 |
+
upos[i] = 'ADP'
|
| 172 |
+
|
| 173 |
+
# Fix 3d: rel-upos-cc - 'cc' should be CCONJ or SCONJ
|
| 174 |
+
if rel == 'cc' and pos not in ('CCONJ', 'SCONJ'):
|
| 175 |
+
upos[i] = 'CCONJ'
|
| 176 |
+
|
| 177 |
+
# Fix 3e: rel-upos-aux - 'aux' should be AUX, but only for valid auxiliaries
|
| 178 |
+
is_valid_aux = token_lower in AUX_WORDS or any(token_lower == aux.lower() for aux in AUX_WORDS)
|
| 179 |
+
if rel.startswith('aux'):
|
| 180 |
+
if is_valid_aux:
|
| 181 |
+
upos[i] = 'AUX'
|
| 182 |
+
pos = 'AUX'
|
| 183 |
+
else:
|
| 184 |
+
# Not a valid auxiliary - change relation to advcl or xcomp
|
| 185 |
+
if pos == 'VERB' or upos[i] == 'VERB':
|
| 186 |
+
deprel[i] = 'advcl'
|
| 187 |
+
upos[i] = 'VERB'
|
| 188 |
+
elif pos == 'ADP' or upos[i] == 'ADP':
|
| 189 |
+
deprel[i] = 'mark'
|
| 190 |
+
upos[i] = 'ADP'
|
| 191 |
+
else:
|
| 192 |
+
deprel[i] = 'xcomp'
|
| 193 |
+
rel = deprel[i]
|
| 194 |
+
pos = upos[i]
|
| 195 |
+
# Also fix AUX UPOS that's not a valid auxiliary (MORPHO aux-lemma)
|
| 196 |
+
elif pos == 'AUX' and not is_valid_aux:
|
| 197 |
+
upos[i] = 'VERB' # Default to VERB for non-aux
|
| 198 |
+
pos = 'VERB'
|
| 199 |
+
|
| 200 |
+
# Fix 3f: rel-upos-cop - 'cop' should be AUX or PRON/DET, only 'là' is valid copula
|
| 201 |
+
if rel == 'cop':
|
| 202 |
+
if token_lower != 'là':
|
| 203 |
+
# Not a valid copula, change to xcomp
|
| 204 |
+
deprel[i] = 'xcomp'
|
| 205 |
+
rel = 'xcomp'
|
| 206 |
+
elif pos not in ('AUX', 'PRON', 'DET'):
|
| 207 |
+
upos[i] = 'AUX'
|
| 208 |
+
|
| 209 |
+
# Fix 4: obl-should-be-nmod - when parent is nominal, use nmod
|
| 210 |
+
if rel.startswith('obl') and head[i] > 0:
|
| 211 |
+
parent_idx = head[i] - 1
|
| 212 |
+
if parent_idx < n and upos[parent_idx] in ('NOUN', 'PROPN', 'PRON'):
|
| 213 |
+
# Preserve subtype if exists
|
| 214 |
+
if ':' in rel:
|
| 215 |
+
deprel[i] = 'nmod:' + rel.split(':')[1]
|
| 216 |
+
else:
|
| 217 |
+
deprel[i] = 'nmod'
|
| 218 |
+
|
| 219 |
+
# Fix 5: (handled in first pass above)
|
| 220 |
+
|
| 221 |
+
# Fix 5b: right-to-left relations - flat/conj/appos must be left-to-right
|
| 222 |
+
for i in range(n):
|
| 223 |
+
rel = deprel[i]
|
| 224 |
+
base_rel = rel.split(':')[0]
|
| 225 |
+
if base_rel in ('flat', 'conj', 'appos') and head[i] > 0:
|
| 226 |
+
parent_idx = head[i] - 1
|
| 227 |
+
if parent_idx > i: # Parent comes after child (wrong direction)
|
| 228 |
+
# Change to compound which allows both directions
|
| 229 |
+
if ':' in rel:
|
| 230 |
+
deprel[i] = 'compound:' + rel.split(':')[1]
|
| 231 |
+
else:
|
| 232 |
+
deprel[i] = 'compound'
|
| 233 |
+
|
| 234 |
+
# Fix 5c: Apply DEPREL_MAP again to catch any newly created invalid deprels
|
| 235 |
+
for i in range(n):
|
| 236 |
+
if deprel[i] in DEPREL_MAP:
|
| 237 |
+
deprel[i] = DEPREL_MAP[deprel[i]]
|
| 238 |
+
|
| 239 |
+
# Fix 5d: Final check for nummod with wrong UPOS
|
| 240 |
+
for i in range(n):
|
| 241 |
+
if deprel[i].startswith('nummod') and upos[i] != 'NUM':
|
| 242 |
+
if upos[i] == 'VERB':
|
| 243 |
+
deprel[i] = 'acl'
|
| 244 |
+
elif upos[i] == 'ADJ':
|
| 245 |
+
deprel[i] = 'amod'
|
| 246 |
+
elif upos[i] == 'NOUN':
|
| 247 |
+
deprel[i] = 'nmod'
|
| 248 |
+
else:
|
| 249 |
+
upos[i] = 'NUM'
|
| 250 |
+
|
| 251 |
+
# Fix 6: too-many-subjects - add :outer subtype for multiple subjects
|
| 252 |
+
# Group all subject types (nsubj, csubj) by predicate
|
| 253 |
+
predicates = {}
|
| 254 |
+
for i in range(n):
|
| 255 |
+
base_rel = deprel[i].split(':')[0]
|
| 256 |
+
if base_rel in ('nsubj', 'csubj') and head[i] > 0:
|
| 257 |
+
pred_idx = head[i]
|
| 258 |
+
if pred_idx not in predicates:
|
| 259 |
+
predicates[pred_idx] = []
|
| 260 |
+
predicates[pred_idx].append((i, base_rel))
|
| 261 |
+
|
| 262 |
+
for pred_idx, subj_list in predicates.items():
|
| 263 |
+
if len(subj_list) > 1:
|
| 264 |
+
# Sort by position to keep first subject as main
|
| 265 |
+
subj_list.sort(key=lambda x: x[0])
|
| 266 |
+
# Mark all but the first as :outer (only nsubj:outer is valid, not csubj:outer)
|
| 267 |
+
for idx, base_rel in subj_list[1:]:
|
| 268 |
+
if ':outer' not in deprel[idx]:
|
| 269 |
+
# csubj:outer is not a valid UD relation, use nsubj:outer instead
|
| 270 |
+
deprel[idx] = 'nsubj:outer'
|
| 271 |
+
|
| 272 |
+
# Fix 7: too-many-objects - add :pass or compound for multiple objects
|
| 273 |
+
predicates_obj = {}
|
| 274 |
+
for i in range(n):
|
| 275 |
+
if deprel[i] == 'obj' and head[i] > 0:
|
| 276 |
+
pred_idx = head[i]
|
| 277 |
+
if pred_idx not in predicates_obj:
|
| 278 |
+
predicates_obj[pred_idx] = []
|
| 279 |
+
predicates_obj[pred_idx].append(i)
|
| 280 |
+
|
| 281 |
+
for pred_idx, obj_indices in predicates_obj.items():
|
| 282 |
+
if len(obj_indices) > 1:
|
| 283 |
+
# Mark subsequent objects as compound
|
| 284 |
+
for idx in obj_indices[1:]:
|
| 285 |
+
# Check if it's adjacent to previous - likely compound
|
| 286 |
+
if idx > 0 and obj_indices[0] == idx - 1:
|
| 287 |
+
deprel[idx] = 'compound'
|
| 288 |
+
else:
|
| 289 |
+
deprel[idx] = 'iobj'
|
| 290 |
+
|
| 291 |
+
# Fix 8: punct-is-nonproj - attach punctuation to avoid non-projectivity
|
| 292 |
+
# Try to find the best attachment point that doesn't cross other edges
|
| 293 |
+
for i in range(n):
|
| 294 |
+
if upos[i] == 'PUNCT':
|
| 295 |
+
# Try candidates in order: previous token, next token, then expand outward
|
| 296 |
+
candidates = []
|
| 297 |
+
if i > 0:
|
| 298 |
+
candidates.append(i) # Previous token (1-based)
|
| 299 |
+
if i + 1 < n:
|
| 300 |
+
candidates.append(i + 2) # Next token (1-based)
|
| 301 |
+
|
| 302 |
+
# Expand to find more candidates
|
| 303 |
+
for dist in range(2, n):
|
| 304 |
+
if i - dist >= 0:
|
| 305 |
+
candidates.append(i - dist + 1) # 1-based
|
| 306 |
+
if i + dist < n:
|
| 307 |
+
candidates.append(i + dist + 1) # 1-based
|
| 308 |
+
|
| 309 |
+
# Find best attachment that doesn't cause crossing
|
| 310 |
+
best_head = candidates[0] if candidates else 1
|
| 311 |
+
for cand in candidates:
|
| 312 |
+
test_head = list(head)
|
| 313 |
+
test_head[i] = cand
|
| 314 |
+
if not punct_causes_crossing(i, cand - 1, test_head, n):
|
| 315 |
+
best_head = cand
|
| 316 |
+
break
|
| 317 |
+
|
| 318 |
+
head[i] = best_head
|
| 319 |
+
|
| 320 |
+
return upos, [str(h) for h in head], deprel
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def punct_causes_crossing(punct_idx, new_head_idx, head, n):
|
| 324 |
+
"""Check if attaching punct to new_head causes any edge crossing."""
|
| 325 |
+
if new_head_idx < 0 or new_head_idx >= n:
|
| 326 |
+
return False
|
| 327 |
+
|
| 328 |
+
p_low, p_high = min(punct_idx, new_head_idx), max(punct_idx, new_head_idx)
|
| 329 |
+
|
| 330 |
+
# Check all other edges for crossing with this punct edge
|
| 331 |
+
for j in range(n):
|
| 332 |
+
if j == punct_idx:
|
| 333 |
+
continue
|
| 334 |
+
if head[j] > 0 and head[j] != punct_idx + 1: # j has a head and it's not punct
|
| 335 |
+
j_head = head[j] - 1
|
| 336 |
+
if j_head < 0 or j_head >= n:
|
| 337 |
+
continue
|
| 338 |
+
j_low, j_high = min(j, j_head), max(j, j_head)
|
| 339 |
+
|
| 340 |
+
# Check if edges cross (one endpoint inside, one outside)
|
| 341 |
+
# Edges cross if: (p_low < j_low < p_high < j_high) or (j_low < p_low < j_high < p_high)
|
| 342 |
+
if (p_low < j_low < p_high < j_high) or (j_low < p_low < j_high < p_high):
|
| 343 |
+
return True
|
| 344 |
+
|
| 345 |
+
return False
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def compute_space_after(text, tokens):
|
| 349 |
+
"""Compute SpaceAfter=No for tokens based on original text."""
|
| 350 |
+
misc = []
|
| 351 |
+
pos = 0
|
| 352 |
+
for i, token in enumerate(tokens):
|
| 353 |
+
# Find token in text
|
| 354 |
+
token_start = text.find(token, pos)
|
| 355 |
+
if token_start == -1:
|
| 356 |
+
# Token not found, assume space after
|
| 357 |
+
misc.append("_")
|
| 358 |
+
continue
|
| 359 |
+
|
| 360 |
+
token_end = token_start + len(token)
|
| 361 |
+
pos = token_end
|
| 362 |
+
|
| 363 |
+
# Check if there's a space after this token
|
| 364 |
+
if token_end < len(text):
|
| 365 |
+
next_char = text[token_end]
|
| 366 |
+
if next_char in ' \t\n':
|
| 367 |
+
misc.append("_")
|
| 368 |
+
else:
|
| 369 |
+
misc.append("SpaceAfter=No")
|
| 370 |
+
else:
|
| 371 |
+
# End of text
|
| 372 |
+
misc.append("_")
|
| 373 |
+
|
| 374 |
+
return misc
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def load_sentences(filepath):
|
| 378 |
+
"""Load sentences from sentences.txt"""
|
| 379 |
+
sentences = []
|
| 380 |
+
with open(filepath, "r", encoding="utf-8") as f:
|
| 381 |
+
for line in f:
|
| 382 |
+
line = line.strip()
|
| 383 |
+
if line:
|
| 384 |
+
parts = line.split("\t", 1)
|
| 385 |
+
if len(parts) == 2:
|
| 386 |
+
sentences.append(parts[1])
|
| 387 |
+
return sentences
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def convert_to_ud_format(sentences):
|
| 391 |
+
"""Convert sentences to UD format using dependency_parse."""
|
| 392 |
+
data = []
|
| 393 |
+
|
| 394 |
+
for idx, text in enumerate(sentences, 1):
|
| 395 |
+
if idx % 100 == 0:
|
| 396 |
+
print(f" Processing sentence {idx}/{len(sentences)}...")
|
| 397 |
+
|
| 398 |
+
sent_id = f"s{idx}"
|
| 399 |
+
|
| 400 |
+
try:
|
| 401 |
+
# Use dependency_parse for tokens, heads, and deprels
|
| 402 |
+
parsed = dependency_parse(text)
|
| 403 |
+
# parsed is list of (token, head, deprel)
|
| 404 |
+
|
| 405 |
+
tokens = [t[0] for t in parsed]
|
| 406 |
+
head = [str(t[1]) for t in parsed]
|
| 407 |
+
deprel = [t[2] for t in parsed]
|
| 408 |
+
|
| 409 |
+
# Get POS tags
|
| 410 |
+
tagged = pos_tag(text)
|
| 411 |
+
# Align POS tags with dependency tokens
|
| 412 |
+
if len(tagged) == len(tokens):
|
| 413 |
+
xpos = [t[1] for t in tagged] # Original Vietnamese tags
|
| 414 |
+
upos = [to_upos(t[1], t[0]) for t in tagged] # Universal tags with token
|
| 415 |
+
else:
|
| 416 |
+
# Fallback: use 'X' for unknown
|
| 417 |
+
xpos = ['X'] * len(tokens)
|
| 418 |
+
upos = ['X'] * len(tokens)
|
| 419 |
+
|
| 420 |
+
except Exception as e:
|
| 421 |
+
print(f" Error parsing sentence {idx}: {e}")
|
| 422 |
+
# Fallback to pos_tag only
|
| 423 |
+
tagged = pos_tag(text)
|
| 424 |
+
tokens = [t[0] for t in tagged]
|
| 425 |
+
xpos = [t[1] for t in tagged]
|
| 426 |
+
upos = [to_upos(t[1], t[0]) for t in tagged]
|
| 427 |
+
head = ["0"] * len(tokens)
|
| 428 |
+
deprel = ["dep"] * len(tokens)
|
| 429 |
+
if len(tokens) > 0:
|
| 430 |
+
deprel[0] = "root"
|
| 431 |
+
|
| 432 |
+
# Apply syntax fixes
|
| 433 |
+
upos, head, deprel = fix_syntax_errors(tokens, upos, head, deprel)
|
| 434 |
+
|
| 435 |
+
# Create other fields
|
| 436 |
+
n = len(tokens)
|
| 437 |
+
lemmas = [t.lower() for t in tokens] # Vietnamese: lemma = lowercase token
|
| 438 |
+
feats = ["_"] * n
|
| 439 |
+
deps = ["_"] * n
|
| 440 |
+
misc = compute_space_after(text, tokens) # Compute SpaceAfter
|
| 441 |
+
|
| 442 |
+
row = {
|
| 443 |
+
"sent_id": sent_id,
|
| 444 |
+
"text": text,
|
| 445 |
+
"comments": [f"# sent_id = {sent_id}", f"# text = {text}"],
|
| 446 |
+
"tokens": tokens,
|
| 447 |
+
"lemmas": lemmas,
|
| 448 |
+
"upos": upos,
|
| 449 |
+
"xpos": xpos,
|
| 450 |
+
"feats": feats,
|
| 451 |
+
"head": head,
|
| 452 |
+
"deprel": deprel,
|
| 453 |
+
"deps": deps,
|
| 454 |
+
"misc": misc,
|
| 455 |
+
"mwt": [],
|
| 456 |
+
"empty_nodes": []
|
| 457 |
+
}
|
| 458 |
+
data.append(row)
|
| 459 |
+
|
| 460 |
+
return data
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def save_jsonl(data, filepath):
|
| 464 |
+
"""Save data as JSONL format."""
|
| 465 |
+
with open(filepath, "w", encoding="utf-8") as f:
|
| 466 |
+
for row in data:
|
| 467 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def save_conllu(data, filepath):
|
| 471 |
+
"""Save data as CoNLL-U format."""
|
| 472 |
+
with open(filepath, "w", encoding="utf-8") as f:
|
| 473 |
+
for row in data:
|
| 474 |
+
f.write(f"# sent_id = {row['sent_id']}\n")
|
| 475 |
+
f.write(f"# text = {row['text']}\n")
|
| 476 |
+
for i in range(len(row['tokens'])):
|
| 477 |
+
# ID FORM LEMMA UPOS XPOS FEATS HEAD DEPREL DEPS MISC
|
| 478 |
+
line = "\t".join([
|
| 479 |
+
str(i + 1),
|
| 480 |
+
row['tokens'][i],
|
| 481 |
+
row['lemmas'][i],
|
| 482 |
+
row['upos'][i],
|
| 483 |
+
row['xpos'][i],
|
| 484 |
+
row['feats'][i],
|
| 485 |
+
row['head'][i],
|
| 486 |
+
row['deprel'][i],
|
| 487 |
+
row['deps'][i],
|
| 488 |
+
row['misc'][i]
|
| 489 |
+
])
|
| 490 |
+
f.write(line + "\n")
|
| 491 |
+
f.write("\n")
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def main():
|
| 495 |
+
source_folder = expanduser("~/Downloads/UD_Vietnamese-UUD-v0.1")
|
| 496 |
+
sentences_file = join(source_folder, "sentences.txt")
|
| 497 |
+
|
| 498 |
+
print("Loading sentences...")
|
| 499 |
+
sentences = load_sentences(sentences_file)
|
| 500 |
+
print(f"Loaded {len(sentences)} sentences")
|
| 501 |
+
|
| 502 |
+
print("Converting to UD format...")
|
| 503 |
+
data = convert_to_ud_format(sentences)
|
| 504 |
+
|
| 505 |
+
# Save as JSONL (for HuggingFace)
|
| 506 |
+
jsonl_file = join(source_folder, "train.jsonl")
|
| 507 |
+
save_jsonl(data, jsonl_file)
|
| 508 |
+
print(f"Saved JSONL to: {jsonl_file}")
|
| 509 |
+
|
| 510 |
+
# Save as CoNLL-U (standard UD format)
|
| 511 |
+
conllu_file = join(source_folder, "train.conllu")
|
| 512 |
+
save_conllu(data, conllu_file)
|
| 513 |
+
print(f"Saved CoNLL-U to: {conllu_file}")
|
| 514 |
+
|
| 515 |
+
# Print sample
|
| 516 |
+
print("\nSample row:")
|
| 517 |
+
sample = data[0]
|
| 518 |
+
print(f" sent_id: {sample['sent_id']}")
|
| 519 |
+
print(f" text: {sample['text'][:60]}...")
|
| 520 |
+
print(f" tokens: {sample['tokens'][:5]}...")
|
| 521 |
+
print(f" upos: {sample['upos'][:5]}...")
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
if __name__ == "__main__":
|
| 525 |
+
main()
|