File size: 5,673 Bytes
c6efd2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""
Statistics for UD Vietnamese Dataset (UDD-v0.1)
"""

from collections import Counter
from os.path import dirname, join


def parse_conllu(filepath):
    """Parse CoNLL-U file and return sentences."""
    sentences = []
    current_sentence = {
        'tokens': [],
        'upos': [],
        'deprel': [],
        'head': [],
        'metadata': {}
    }

    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                if current_sentence['tokens']:
                    sentences.append(current_sentence)
                    current_sentence = {
                        'tokens': [],
                        'upos': [],
                        'deprel': [],
                        'head': [],
                        'metadata': {}
                    }
            elif line.startswith('#'):
                # Metadata
                if '=' in line:
                    key, value = line[2:].split('=', 1)
                    current_sentence['metadata'][key.strip()] = value.strip()
            else:
                parts = line.split('\t')
                if len(parts) >= 10:
                    # Skip multi-word tokens (e.g., 1-2)
                    if '-' in parts[0] or '.' in parts[0]:
                        continue
                    current_sentence['tokens'].append(parts[1])
                    current_sentence['upos'].append(parts[3])
                    current_sentence['head'].append(parts[6])
                    current_sentence['deprel'].append(parts[7])

    # Add last sentence if exists
    if current_sentence['tokens']:
        sentences.append(current_sentence)

    return sentences


def compute_statistics(sentences):
    """Compute statistics from parsed sentences."""
    stats = {}

    # Basic counts
    stats['num_sentences'] = len(sentences)
    stats['num_tokens'] = sum(len(s['tokens']) for s in sentences)

    # Sentence length statistics
    sent_lengths = [len(s['tokens']) for s in sentences]
    stats['avg_sent_length'] = sum(sent_lengths) / len(sent_lengths) if sent_lengths else 0
    stats['min_sent_length'] = min(sent_lengths) if sent_lengths else 0
    stats['max_sent_length'] = max(sent_lengths) if sent_lengths else 0

    # UPOS distribution
    all_upos = []
    for s in sentences:
        all_upos.extend(s['upos'])
    stats['upos_counts'] = Counter(all_upos)

    # DEPREL distribution
    all_deprel = []
    for s in sentences:
        all_deprel.extend(s['deprel'])
    stats['deprel_counts'] = Counter(all_deprel)

    # Tree depth statistics
    depths = []
    for s in sentences:
        max_depth = compute_tree_depth(s['head'])
        depths.append(max_depth)
    stats['avg_tree_depth'] = sum(depths) / len(depths) if depths else 0
    stats['max_tree_depth'] = max(depths) if depths else 0

    # Root relation counts
    root_upos = []
    for s in sentences:
        for i, (upos, deprel) in enumerate(zip(s['upos'], s['deprel'])):
            if deprel == 'root':
                root_upos.append(upos)
    stats['root_upos_counts'] = Counter(root_upos)

    return stats


def compute_tree_depth(heads):
    """Compute maximum depth of dependency tree."""
    n = len(heads)
    if n == 0:
        return 0

    depths = [0] * n

    def get_depth(idx):
        if depths[idx] > 0:
            return depths[idx]
        head = int(heads[idx])
        if head == 0:
            depths[idx] = 1
        else:
            depths[idx] = get_depth(head - 1) + 1
        return depths[idx]

    for i in range(n):
        try:
            get_depth(i)
        except (RecursionError, IndexError):
            depths[i] = 1

    return max(depths) if depths else 0


def print_statistics(stats):
    """Print statistics in a nice format."""
    print("=" * 60)
    print("UD Vietnamese Dataset (UDD-v0.1) Statistics")
    print("=" * 60)

    print("\n## Basic Statistics")
    print(f"  Sentences:         {stats['num_sentences']:,}")
    print(f"  Tokens:            {stats['num_tokens']:,}")
    print(f"  Avg sent length:   {stats['avg_sent_length']:.2f}")
    print(f"  Min sent length:   {stats['min_sent_length']}")
    print(f"  Max sent length:   {stats['max_sent_length']}")
    print(f"  Avg tree depth:    {stats['avg_tree_depth']:.2f}")
    print(f"  Max tree depth:    {stats['max_tree_depth']}")

    print("\n## UPOS Distribution")
    print(f"  {'Tag':<10} {'Count':>8} {'Percent':>8}")
    print("  " + "-" * 28)
    total_tokens = stats['num_tokens']
    for tag, count in stats['upos_counts'].most_common():
        pct = count / total_tokens * 100
        print(f"  {tag:<10} {count:>8,} {pct:>7.2f}%")

    print("\n## DEPREL Distribution")
    print(f"  {'Relation':<20} {'Count':>8} {'Percent':>8}")
    print("  " + "-" * 38)
    for rel, count in stats['deprel_counts'].most_common():
        pct = count / total_tokens * 100
        print(f"  {rel:<20} {count:>8,} {pct:>7.2f}%")

    print("\n## Root UPOS Distribution")
    print(f"  {'UPOS':<10} {'Count':>8} {'Percent':>8}")
    print("  " + "-" * 28)
    total_roots = sum(stats['root_upos_counts'].values())
    for tag, count in stats['root_upos_counts'].most_common():
        pct = count / total_roots * 100
        print(f"  {tag:<10} {count:>8,} {pct:>7.2f}%")

    print("\n" + "=" * 60)


def main():
    # Find train.conllu file
    base_dir = dirname(dirname(__file__))
    conllu_file = join(base_dir, 'train.conllu')

    print(f"Reading: {conllu_file}")
    sentences = parse_conllu(conllu_file)

    stats = compute_statistics(sentences)
    print_statistics(stats)


if __name__ == "__main__":
    main()