]> git.openstreetmap.org Git - rails.git/blob - script/locale/merge-from-translatewiki
Add support for viewing a list of your friends' changesets
[rails.git] / script / locale / merge-from-translatewiki
1 #!/usr/bin/env perl
2 use feature ':5.10';
3 use strict;
4 use warnings;
5 use File::Slurp qw(slurp);
6 use YAML::Syck qw(Dump Load LoadFile DumpFile);
7 BEGIN {
8     $YAML::Syck::Headless = 1;
9     $YAML::Syck::SortKeys = 1;
10 }
11 use WWW::Mechanize;
12 use HTML::TableParser::Grid;
13 use Pod::Usage ();
14 use Getopt::Long ();
15 use Data::Dump 'dump';
16 use File::Spec::Functions qw(catfile);
17 use Storable;
18 use autodie;
19
20 =head1 NAME
21
22 merge-from-translatewiki - Get new translations from L<http://translatewiki.net> and selectively merge them with ours
23
24 =head1 SYNOPSIS
25
26     # Run this normally, hopefully...
27     merge-from-translatewiki --locales-dir=config/locales
28
29     # Diff the existing files:
30     config/locales$ for i in $(ls *yml | grep -v en.yml); do perl ../../script/locale/diff --dump-flat $i > $i.0 ;done
31
32     # Merge and find out what changed:
33     rails_port$ perl script/locale/merge-from-translatewiki --locales-dir config/locales
34
35     # Or, more complexy:
36     rails_port$ for i in $(svn st config/locales/ | egrep '^M|\\?' | awk '{print $2}' | grep 'yml$'); do rm -v $i; done && svn up config/locales && perl script/locale/merge-from-translatewiki --locales-dir config/locales && svn st config/locales
37  
38     # Diff:
39     config/locales$ for i in $(ls *yml | grep -v en.yml); do perl ../../script/locale/diff --dump-flat $i > $i.1 ;done && for i in $(ls *yml | grep -v en.yml); do diff -ru $i.*; done
40
41 =head1 DESCRIPTION
42
43 Translatewiki's export process L<is
44 broken|http://trac.openstreetmap.org/ticket/2305>. This script imports
45 new messages from it while tiptoeing around known bugs.
46
47 =head1 OPTIONS
48
49 =over
50
51 =item -h, --help
52
53 Print this help message.
54
55 =item --locales-dir
56
57 The locales dir we'll merge stuff into. F<config/locales> by default.
58
59 =item --only-new
60
61 Only import translations that don't exists for us yet.
62
63 =item --cache
64
65 Write a L<Storable> cache for things downloaded from Translatewiki and
66 use it if it exists.
67
68 =back
69
70 =head1 AUTHOR
71
72 E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason <avarab@gmail.com>
73
74 =cut
75
76 # Get the command-line options
77 Getopt::Long::Parser->new(
78     config => [ qw< bundling no_ignore_case no_require_order pass_through > ],
79 )->getoptions(
80     'h|help' => \my $help,
81     'locales-dir=s' => \(my $locales_dir = 'config/locales'),
82     'only-new' => \my $only_new,
83     'cache' => \my $cache,
84 ) or help();
85
86 # On --help
87 help() if $help;
88
89 help() unless $locales_dir and -d $locales_dir;
90
91 ###
92 ### Main
93 ###
94
95 ### Get Translatewiki data
96 my %translatewiki_languages = translatewiki_languages();
97
98 # Don't process English from Translatewiki
99 delete $translatewiki_languages{en};
100
101 #say Dump \%translatewiki_languages;
102
103 my @translatewiki_languages_codes = keys %translatewiki_languages;
104 my %translatewiki_translations = get_translatewiki_translations(@translatewiki_languages_codes);
105
106 #say Dump \%translatewiki_translations;
107
108 ### Get our existing data
109 my %my_translations;
110 my @my_yaml_files = glob catfile($locales_dir, '*.yml');
111 for my $my_yaml_file (@my_yaml_files) {
112     my $basename = basename($my_yaml_file);
113     my $tw_lang = lc $basename;
114
115     say STDERR "Loading my translation $tw_lang ($my_yaml_file)";
116     $my_translations{$tw_lang} = load_and_flatten_yaml(scalar slurp($my_yaml_file));
117 }
118
119 say "loaded my translations";
120
121 ## Write out merged data
122 for my $translatewiki_lang (sort @translatewiki_languages_codes) {
123     my $rails_lang = $translatewiki_lang; $rails_lang =~ s/(?<=-)(\w+)/\U$1\E/;
124     my $out_file = catfile($locales_dir, $rails_lang . '.yml');
125
126     unless (-f $out_file) {
127         # No translation like this exists
128         say STDERR "$rails_lang has no existing translation. Importing as-is from Translatewiki to $out_file";
129         my $expanded = expand_hash($translatewiki_translations{$translatewiki_lang});
130         my $out = +{ $rails_lang => $expanded };
131         spit_out($out_file, $out);
132     } elsif (ref $my_translations{$translatewiki_lang} eq 'HASH' and not $only_new) {
133         say STDERR "$rails_lang has existing translations. Merging the old translation with the new Translatewiki one";
134
135         # Get the data
136         my %tw = %{ $translatewiki_translations{$translatewiki_lang} };
137         my %me = %{ $my_translations{$translatewiki_lang} };
138         my %en = %{ $my_translations{en} };
139         # Use %tw to start with
140         my %new = %tw;
141
142         ### Merge stuff
143
144         ## These keys shouldn't be removed but are due to
145         ## Translatewiki fail (they were missing in the original
146         ## import)
147         my @url_keys = qw(
148                              browse.relation_member.entry
149                              changeset.changeset.id
150                              geocoder.search_osm_namefinder.suffix_suburb
151                              html.dir
152                              layouts.intro_3_bytemark
153                              layouts.intro_3_ucl
154                              layouts.project_name.h1
155                              layouts.project_name.title
156                              printable_name.with_version
157                              site.edit.anon_edits
158                              layouts.help_wiki_url
159                              layouts.shop_url
160                              notifier.gpx_notification.failure.import_failures_url
161                              notifier.signup_confirm_plain.the_wiki_url
162                              notifier.signup_confirm_plain.wiki_signup_url
163                              trace.edit.visibility_help_url
164                              trace.trace_form.help_url
165                              trace.trace_form.visibility_help_url
166                      );
167
168         for my $key (@url_keys) {
169             if ( exists $me{$key} and not exists $new{$key} ) {
170                 $new{$key} = $me{$key} if $me{$key} ne $en{$key};
171             }
172         }
173
174         ## When foo exists in this file but only foo.one, foo,other
175         ## etc in English or the original file we don't want to throw away what we have
176         my @plural_keys = qw( zero one many few other two );
177
178         while (my ($me_k, $me_v) = each %me) {
179             if (not exists $tw{ $me_k } and 
180                 not exists $en{ $me_k } and
181                 (
182                     exists $en{ $me_k . '.zero' } or
183                     exists $en{ $me_k . '.one' } or
184                     exists $en{ $me_k . '.many' } or
185                     exists $en{ $me_k . '.few' } or
186                     exists $en{ $me_k . '.other' } or
187                     exists $en{ $me_k . '.two' })) {
188                 #say STDERR "Bringing back nuked plural form '$me_k' Setting it to '$me{ $me_k }'";
189                 $new{ $me_k } = $me{ $me_k };
190             }
191         }
192
193         # Both arrays and strings are supported in the site key. Avoid removing e.g.:
194         #   -site.key.table.entry.school: 學校;大學
195         # Just because en.yml has site.key.table.entry.school.0 and site.key.table.entry.school.1
196         while (my ($me_k, $me_v) = each %me) {
197             next unless $me_k =~ /^site\.key\.table\.entry/;
198             next if $me_k =~ /\.\d+$/;
199
200             if (ref $en{ $me_k } eq 'ARRAY' and not ref $me{ $me_k }) {
201                 $new{ $me_k } = $me{ $me_k };
202             }
203         }
204
205         # There are a bunch of keys on Translatewiki that are
206         # equivalent to English for some reason. Probably because they
207         # were there at import time. Nuke them.
208         while (my ($new_k, $new_v) = each %new) {
209             if (exists $en{ $new_k } and $en{ $new_k } eq $new_v) {
210                 #say "Purging dupe in $rails_lang: $new_k=$new_v";
211                 delete $new{ $new_k };
212             }
213         }
214
215         my $expanded = expand_hash( \%new );
216         my $out = +{ $rails_lang => $expanded };
217         spit_out($out_file, $out);
218     } elsif (not $only_new) {
219         die "Internal error on $translatewiki_lang";
220     }
221 }
222
223 sub spit_out
224 {
225     my ($file, $data) = @_;
226     my $yaml_out = Dump $data;
227     
228     open my $fh, ">", $file;
229     print $fh $yaml_out;
230     close $fh;
231 }
232
233 #
234 # YAML stuff
235 #
236
237 sub mark_utf8
238 {
239     my ($hash) = @_;
240
241     # Mark as UTF-8
242     map { if (ref $_ eq 'ARRAY') { map { utf8::decode($_) } @$_ } else {  utf8::decode($_) } } values %$hash;
243 }
244
245 sub iterate
246 {
247     my ($hash, @path) = @_;
248     my @ret;
249         
250     while (my ($k, $v) = each %$hash)
251     {
252         if (ref $v eq 'HASH')
253         {
254              push @ret => iterate($v, @path, $k);
255         }
256         else
257         {
258             push @ret => join(".",@path, $k), $v;
259         }
260     }
261
262     return @ret;
263 }
264
265 sub expand_hash
266 {
267     my ($flat_hash) = @_;
268     my %new_hash;
269     while (my ($k, $v) = each %$flat_hash) {
270         #say "Inserting $k=$v";
271         insert_string_deep(\%new_hash, $k, $v);
272     }
273
274     \%new_hash;
275 }
276
277 # Fails under strict in certain cases:
278 ## Inserting browse.start_rjs.object_list.history.type.way=Vía [[id]]
279 ## Inserting activerecord.models.relation_tag=Etiqueta de la relación
280 ## Inserting browse.changeset_details.has_nodes.one=Tiene el siguiente {{count}} nodo:
281 ## Can't use string ("Tiene {{count}} nodos:") as a HASH ref while "strict refs" in use at script/locale/merge-from-translatewiki line 234.
282 # Line 234 = my $p = \$h; $p = \$$p->{$_} for split /\./, $ks;
283
284 # sub insert_string_deep_X {
285 #     my ($h, $ks, $v) = @_;
286 #     my $p = \$h; $p = \$$p->{$_} for split /\./, $ks;
287 #     $$p = $v;
288 # }
289
290 sub insert_string_deep
291 {
292     my ($hash, $key, $value) = @_;
293
294     my @key = split /\./, $key;
295     my $h = $hash;
296
297     my $i = 0;
298     for my $k (@key) {
299         $i ++;
300         if ($i == @key) {
301             $h->{$k} = $value;
302         } else {
303             if (ref $h->{$k}) {
304                 $h = $h->{$k};
305             } else {
306                 $h = $h->{$k} = {};
307             }
308         }
309     }
310 }
311
312 #
313 # Get language from Translatewiki
314 #
315
316 sub get_translatewiki_translations
317 {
318     my @languages = @_;
319
320     my $cache_file = "/tmp/merge-from-translatewiki.storable";
321     if ($cache) {
322         if (-f $cache_file) {
323             my $c = retrieve($cache_file);
324             return %$c;
325         }
326     }
327
328     my %translatewiki_languages;
329     my $all_count = scalar @languages;
330     say "Translatewiki has $all_count languages I'm about to get";
331     my $count = 0;
332     for my $lang (@languages) {
333         $count ++;
334         say STDERR "Getting language $count/$all_count ($lang) from Translatewiki";
335         my $yaml = get_language_from_translatewiki($lang);
336
337         my $flat_data = load_and_flatten_yaml($yaml);
338
339         $translatewiki_languages{$lang} = $flat_data;
340     }
341
342     if ($cache) {
343         store \%translatewiki_languages, $cache_file;
344     }
345
346     return %translatewiki_languages;
347 }
348
349 sub get_language_from_translatewiki
350 {
351     my ($lang) = @_;
352     my $mech = WWW::Mechanize->new;
353
354     $mech->get("http://translatewiki.net/w/i.php?title=Special%3ATranslate&task=export-to-file&group=out-osm-site&language=$lang");
355
356     die "Couldn't get lang $lang lang from Translatewiki" unless $mech->success;
357
358     return $mech->content;
359 }
360
361 #
362 # from language list
363 #
364
365 sub translatewiki_languages
366 {
367     my $mech = WWW::Mechanize->new;
368
369     $mech->get('http://translatewiki.net/wiki/Translating:OpenStreetMap/stats/trunk/site');
370
371     die "Couldn't get translatewiki table" unless $mech->success;
372
373     my $content = $mech->content;
374     my ($sortable) = $content =~ m[(<table class="sortable.*</table>)]s;
375
376     my @table = parse_language_table($sortable);
377
378     # Just get the codes
379     map { $_->{code} => $_->{language} } @table;
380 }
381
382 sub parse_language_table
383 {
384     my ($table) = @_;
385
386     my $parser = HTML::TableParser::Grid->new($table);
387     my @rows;
388     for my $n (0 .. $parser->num_rows - 1) {
389         my %row;
390         @row{qw(code language done fuzzy)} = $parser->row($n);
391         mark_utf8(\%row);
392
393         push @rows => \%row;
394     }
395
396     @rows;
397 }
398
399 #
400 # Misc
401 #
402
403 sub basename
404 {
405     my $name = shift;
406     $name =~ s[\..*?$][];
407     $name =~ s[.*/][];
408     $name;
409 }
410
411 sub load_and_flatten_yaml
412 {
413     my ($yaml) = @_;
414
415     my $data = Load($yaml);
416
417     # Remove the root $lang => key
418     my @keys = keys %$data;
419     die "YAML data had more than 1 root key" if @keys != 1;
420     $data = $data->{$keys[0]};
421
422     # Flatten it
423     my $flat_data = { iterate($data) };
424
425     mark_utf8($flat_data);
426
427     $flat_data;
428 }
429
430 #
431 # Help
432 #
433
434 sub help
435 {
436     my %arg = @_;
437
438     Pod::Usage::pod2usage(
439         -verbose => $arg{ verbose },
440         -exitval => $arg{ exitval } || 0,
441     );
442 }