public
Last active

Script that generates various datafiles used for RTH website

  • Download Gist
hanzi.pl
Perl
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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
#!/usr/bin/perl
#
# USAGE
#
# Help:
# $ perl data/scripts/hanzi.pl
#
# Output tab delimited data that will be imported in the database:
# $ perl data/scripts/hanzi.pl -v -t -o data/generated/table_hanzi.utf8
#
# Output a hash of lesson numbers and character counts:
# $ perl data/scripts/hanzi.pl -v -l
#
# Output the javascript data for the study page search box:
# $ perl data/scripts/hanzi.pl -k -o web/revtk/study/keywords-rth.js
#
# FORMAT OF OUTPUT DATA
# Fields are separated by tabs.
# UCS: unicode code point.
# Character: single utf8 character.
# Pinyin readings: comma separated readings with tone numbers.
#
# <ucs> <keyword> <character> <pinyin readings> <frame number> <lesson number> <stroke count>
#
#
# Character selection format returned by get_character_selection():
#
# <ucs_id> => (
#
# 'chr' => <utf8_character>
# 'ucs' => <ucs_id>
#
# Properties added by merge_rtx_data():
#
# 'kwd' => <keyword> String
# 'num' => <frame number> Number, starts at 1
# 'les' => <lesson number> Number, starts at 1
#
# Properties added by merge_unihan_data():
#
# 'prn' => <pinyin readings> Comma separated tone marks, ie. "yuo1,yuo2"
# 'skc' => <stroke count>
#
# );
#
 
use utf8;
use strict;
use warnings;
use Cwd;
use Encode;
use File::Basename;
use Getopt::Long;
use Data::Dumper;
 
my $DIRNAME = dirname(Cwd::abs_path($0));
my $TONES_MANDARIN = $DIRNAME.'/../datafiles/__tones_mandarin.utf8';
my $RTH_VS_RSH_DATA = $DIRNAME.'/../datafiles/__rth-vs-rsh-data.utf8';
my $UNIHAN_DATAFILES = $DIRNAME.'/../datafiles/download/Unihan/';
 
my $opt_verbose = '';
my $opt_lessons = '';
my $opt_table = '';
my $opt_outfile = '';
my $opt_keywords = '';
 
my %tones_m_nd; # Tones Mandarin map Number to Diacritic
my %tones_m_dn; # ... ... ... Diacritic to Number
 
 
Getopt::Long::Configure ("bundling");
my $result = GetOptions(
"k|keywords" => \$opt_keywords,
"l|lessons" => \$opt_lessons,
"o|outfile=s" => \$opt_outfile,
"t|table" => \$opt_table,
"v|verbose" => \$opt_verbose);
 
if (!$result)
{
&show_help();
exit;
}
 
# Create table of hanzi data for RevTH website.
if ($opt_table)
{
my %chrsel;
 
get_tones('mandarin', \%tones_m_nd, \%tones_m_dn);
#print Dumper(%tones_m_nd);exit;
 
get_character_selection(\%chrsel);
merge_rtx_data(\%chrsel);
merge_unihan_data(\%chrsel);
output_table_hanzi(\%chrsel, $opt_outfile);
 
verbose("Done.");
}
# Output hash of lesson numbers and character counts.
elsif ($opt_lessons)
{
my $fh = open_file('<', $RTH_VS_RSH_DATA);
my %rthLessons;
my $lineNr = 0;
# Parse lesson numbers.
while (<$fh>)
{
chomp;
last if ($_ eq '');
$lineNr++;
my ($rshNr, $rshHan, $rthNr, $rthHan, $rthKeyw, $rshKeyw, $rshLess, $rthLess) = split(/\t/);
if ($rthLess =~/^[0-9]+$/)
{
$rthLessons{scalar($rthLess)}++;
}
}
close ($fh);
# Output hash array for use in php code
my $lessNr;
my @items;
foreach $lessNr (sort { $a <=> $b } keys %rthLessons)
{
push @items, "$lessNr => $rthLessons{$lessNr}";
}
print join(', ', @items) . "\n";
}
# Output keyword data for javascript auto complete dropdown.
elsif ($opt_keywords)
{
my %chrsel;
get_character_selection(\%chrsel);
merge_rtx_data(\%chrsel);
output_keyword_list(\%chrsel, $opt_outfile);
}
else
{
&show_help();
exit;
}
 
 
# Creates a tab delimited datafile in UTF-8 format, for import in MySQL database.
#
sub output_table_hanzi
{
my ($pChrSel, $outfile) = @_;
 
verbose("Writing hanzi table".($outfile ? " to file: $outfile " : '')."...");
 
# Open output file, defaults to STDOUT
my $fh = $outfile ? open_file('>', $outfile) : *STDOUT;
binmode $fh, ":utf8";
 
# We don't have to sort the table data on frame number because of MySQL keys
# but it is helpful for debugging to have the rows ordered.
my %ordered = get_chrsel_by_framenum($pChrSel);
 
my $count = 0;
foreach (sort keys %ordered)
{
my $pChr = $ordered{$_};
my $ucs = $pChr->{'ucs'};
my @cols;
 
# Find missing data
my @check_cols = ('kwd', 'chr', 'prn', 'num', 'les', 'skc');
#if (!check_empty_values(\@check_cols, $pChr, $_))
#{
#print STDERR Dumper(%$pChr);
#exit;
#}
printf STDERR (" No pinyin for U+%x (%s)\n", $ucs, $pChr->{'chr'}) if !exists($pChr->{'prn'});
printf STDERR (" No strokecount for U+%x (%s)\n", $ucs, $pChr->{'chr'}) if !exists($pChr->{'skc'});
 
@cols = (
$ucs, # UCS id
$pChr->{'kwd'}, # Keyword
$pChr->{'chr'}, # Character (utf-8)
$pChr->{'prn'}, # Pronunciation
$pChr->{'num'}, # Frame number
$pChr->{'les'}, # Lesson number
$pChr->{'skc'} # Stroke count
);
 
print $fh join("\t", @cols), "\n";
}
}
 
# Outputs javascript data for the Study page auto-complete search box.
#
sub output_keyword_list
{
my ($pChrSel, $outfile) = @_;
 
my $fh = $outfile ? open_file('>', $outfile) : *STDOUT;
binmode $fh, ":utf8";
 
my @kwlist;
my @kklist;
my $s;
my $col = 0;
 
my %ordered = get_chrsel_by_framenum($pChrSel);
 
foreach (sort keys %ordered)
{
my $pChr = $ordered{$_};
 
$s = "\"$pChr->{'kwd'}\",";
$col += length($s);
if ($col > 128)
{
$col = 0;
$s = $s . "\n";
}
push @kwlist, $s;
 
push @kklist, $pChr->{'chr'};
}
 
$s = "var kwlist=[\n" . join('', @kwlist) . "];\n";
$s =~ s/",\n?\];$/"\n];/;
 
print $fh $s;
 
print $fh "var kklist='" . join('', @kklist) . "';\n";
}
 
# Creates the selection of characters to be included in the output data.
#
# Returns character selection (hash):
#
# <ucs_id> => ('chr' => <utf8_char>)
#
sub get_character_selection
{
my ($pChrSel) = @_;
 
verbose("Parsing character selection...");
 
# Select all characters from RTH Vol.1
#
my $fh = open_file('<', $RTH_VS_RSH_DATA);
while (<$fh>)
{
chomp;
last if ($_ eq '');
my ($rshNr, $rshHan, $rthNr, $rthHan, $rthKeyw, $rshKeyw, $rshLess, $rthLess) = split(/\t/, decode_utf8($_));
 
$rthHan = trim($rthHan);
 
# if non empty RTH frame number
if ($rthNr =~/^[0-9]+$/)
{
my $ucsId = ord($rthHan);
my %data = ('chr' => $rthHan, 'ucs' => $ucsId);
#print "y $ucsId $data{'char'}\n";
$pChrSel->{$ucsId} = \%data;
}
}
close ($fh);
}
 
# Returns hash of character data ordered by frame number.
#
sub get_chrsel_by_framenum
{
my ($pChrSel) = @_;
my ($ucs, $pChr, %ordered);
 
while (($ucs, $pChr) = each %$pChrSel)
{
my $frameNum = sprintf('%04d', $pChr->{'num'});
$ordered{$frameNum} = $pChr;
}
 
return %ordered;
}
 
# Merge Heisig data: keywords, frame numbers, ...
#
sub merge_rtx_data
{
my ($pChrSel) = @_;
my $fh = open_file('<', $RTH_VS_RSH_DATA);
my %dupCheck;
 
verbose("Merging RTH data...");
 
while (<$fh>)
{
chomp;
last if ($_ eq '');
my ($rshNr, $rshHan, $rthNr, $rthHan, $rthKeyw, $rshKeyw, $rshLess, $rthLess) = split(/\t/, decode_utf8($_));
 
$rthNr = trim($rthNr);
$rthLess = trim($rthLess);
$rthKeyw = trim($rthKeyw);
 
# if non empty RTH frame number
if ($rthNr =~ /^[0-9]+$/)
{
my $ucsId = ord($rthHan);
 
verbose(" Duplicate? $rthNr $rthKeyw") if ($dupCheck{$rthNr}++ > 0);
 
$pChrSel->{$ucsId}->{'kwd'} = $rthKeyw; # keyword
$pChrSel->{$ucsId}->{'num'} = $rthNr; # frame number
$pChrSel->{$ucsId}->{'les'} = $rthLess; # lesson number
}
}
close ($fh);
}
 
# Merge data from the UNIHAN datafiles.
#
sub merge_unihan_data
{
my ($pChrSel) = @_;
my $fh;
 
verbose("Merging Unihan_Readings.txt ...");
 
$fh = open_file('<', $UNIHAN_DATAFILES.'Unihan_Readings.txt');
while (<$fh>)
{
my ($ucsId, $fld, $data) = parse_unihan_row($_);
my $pChr;
 
next if $ucsId == 0;
next if (!exists($pChrSel->{$ucsId}));
 
$pChr = $pChrSel->{$ucsId};
 
if ($fld eq 'kHanyuPinyin')
{
# Remove HDZ indexes: "10585.010:kuáng 10589.110:chéng,chěng" => "kuáng,chéng,chěng"
$data =~ s/([0-9.]+,)*[0-9.]+://g;
$data =~ s/ /,/g;
# Split the HanyuPinyin, then map diacritics to tone marks
my @py_n;
my @py_split = split /,/, $data;
foreach my $py_d (@py_split)
{
verbose(sprintf(" No tone mapping for $py_d in character %x", $ucsId)) if (!exists($tones_m_dn{$py_d}));
#my $py = $tones_m_dn{$py_d};
 
# remove double readings eg: "U+5F97 kHanyuPinyin 20828.030:dé,děi,dé,de" or "U+62FC kHanyuPinyin 31875.080:pīn,bìng 31898.020:bìng,pīn"
#if (exists($py_n{$py})) {
#verbose(sprintf(" Double reading for for $py_d in character %x", $ucsId));
#}else { $py_n{$py} = 1; }
push @py_n, $tones_m_dn{$py_d};
}
$pChr->{'prn'} = join(',', @py_n); # ex: yǔ,yú,zhù
 
}
elsif ($fld eq 'kMandarin' && !exists($pChr->{'prn'}))
{
# use kMandarin if kHanyuPinyin is not available
$pChr->{'prn'} = $data; # ex: TUO1
}
}
close ($fh);
 
 
verbose("Merging Unihan_DictionaryLikeData.txt ...");
 
$fh = open_file('<', $UNIHAN_DATAFILES.'Unihan_DictionaryLikeData.txt');
while (<$fh>)
{
my ($ucsId, $fld, $data) = parse_unihan_row($_);
my $pChr;
 
next if $ucsId == 0;
next if (!exists($pChrSel->{$ucsId}));
 
$pChr = $pChrSel->{$ucsId};
 
if ($fld eq 'kTotalStrokes')
{
$pChr->{'skc'} = $data;
}
}
close ($fh);
}
 
# Parse one row of a UNIHAN datafile.
#
# @return The unicode codepoint (decimal), column name and column data.
# Returns 0 if no data (eg. comment line)
sub parse_unihan_row
{
my ($row) = @_;
 
chomp($row);
 
# Skip comment lines
return 0 if $row =~ /^#/;
 
# Skip empty lines
return 0 if $row eq '';
 
my ($ucs_s, $fld, $data) = split(/\t/, decode_utf8($row));
# Get the UCS key for our hash
$ucs_s =~ /U\+(\w+)/;
my $ucs_i = hex($1);
 
return ($ucs_i, $fld, $data);
}
 
# Check hash for undefined keys or empty valus in existing keys.
#
# @param array Array of key names
#
sub check_empty_values
{
my ($pKeys, $pHash, $id) = @_;
 
foreach my $key (@$pKeys)
{
if (!exists $pHash->{$key})
{
verbose(" $id: Missing key '$key'");
return 0;
}
elsif ($pHash->{$key} eq '')
{
verbose(" $id: Empty data for key '$key'");
return 0;
}
}
 
return 1;
}
 
# Read tones datafile into hash that allows mapping between diacritics and tone
# numbers notation.
#
# Row format:
#
# bei2 <tab> béi <newline>
#
sub get_tones
{
my ($tMode, $hNumToDia, $hDiaToNum) = @_;
 
my $fh = open_file('<', $TONES_MANDARIN);
while (<$fh>)
{
chomp;
last if ($_ eq '');
my ($py_n, $py_d) = split(/\t/, decode_utf8($_));
$hNumToDia->{$py_n} = $py_d;
$hDiaToNum->{$py_d} = $py_n;
}
close ($fh);
 
verbose("Reading tones mapping file... ".(keys %$hNumToDia));
}
 
sub show_help
{
print <<EOD;
Usage: $0 [COMMAND]...
 
Commands:
-k Output javascript data for the Study page search.
-t Create the hanzi table data for use in RevTH website.
-l Create a hash of lesson numbers and character counts.
-o Output file name (options -t).
-v Verbose.
 
EOD
}
 
sub trim
{
my $s = shift;
$s =~ s/^\s+//;
$s =~ s/\s+$//;
return $s;
}
 
sub open_file
{
my ($mode, $filename) = @_;
local *FH;
open (FH, $mode, $filename) or die "Cannot open file '$filename' (mode: $mode) !";
return *FH;
}
 
# Print message to STDERR (with a newline character) if verbose flag is set.
#
sub verbose
{
my ($msg) = @_;
print STDERR "$msg\n" if $opt_verbose;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.