Bump year
[yaz-moved-to-github.git] / util / yaz-icu.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2013 Index Data
3  * See the file LICENSE for details.
4  */
5
6 #if HAVE_CONFIG_H
7 #include "config.h"
8 #endif
9
10 #include <string.h>
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <errno.h>
15
16 #include <yaz/options.h>
17
18 #if YAZ_HAVE_ICU
19
20 #include <unicode/ucnv.h>
21 #include <unicode/ustring.h>
22 #include <unicode/ucol.h>
23 #include <unicode/ubrk.h>
24 #include <unicode/utrans.h>
25 #include <unicode/uclean.h>
26
27 #include <yaz/icu.h>
28 #include <yaz/wrbuf.h>
29
30 /* commando line and config parameters */
31 struct config_t {
32     char conffile[1024];
33     char print[1024];
34     int xmloutput;
35     int sortoutput;
36     yaz_icu_chain_t chain;
37     FILE * infile;
38     FILE * outfile;
39 };
40
41 void print_option_error(const struct config_t *p_config)
42 {
43     fprintf(stderr, "yaz-icu [options] [infile]\n"
44             "Options:\n"
45             "   -c file         XML configuration\n"
46             "   -p a|c|l|t      Print ICU info \n"
47             "   -s              Show sort normalization key\n"
48             "   -x              XML output instread of text\n"
49             "\n"
50             "Examples:\n"
51             "cat hugetextfile.txt | ./yaz-icu -c config.xml \n"
52             "./yaz-icu -p c\n"
53             "./yaz-icu -p l -x\n"
54             "./yaz-icu -p t -x\n"
55             "\n"
56             "Example ICU chain XML configuration file:\n"
57             "<icu_chain locale=\"en\">\n"
58             "  <transform rule=\"[:Control:] Any-Remove\"/>\n"
59             "  <tokenize rule=\"l\"/>\n"
60             "  <transform rule=\"[[:WhiteSpace:][:Punctuation:]] Remove\"/>\n"
61             "  <casemap rule=\"l\"/>\n"
62             "</icu_chain>\n"
63           );
64     exit(1);
65 }
66
67 void read_params(int argc, char **argv, struct config_t *p_config)
68 {
69     char *arg;
70     int ret;
71
72     /* set default parameters */
73     p_config->conffile[0] = 0;
74     p_config->print[0] = 0;
75     p_config->xmloutput = 0;
76     p_config->sortoutput = 0;
77     p_config->chain = 0;
78     p_config->infile = 0;
79     p_config->outfile = stdout;
80
81     /* set up command line parameters */
82
83     while ((ret = options("c:p:xs", argv, argc, &arg)) != -2)
84     {
85         switch (ret)
86         {
87         case 'c':
88             strcpy(p_config->conffile, arg);
89             break;
90         case 'p':
91             strcpy(p_config->print, arg);
92             break;
93         case 's':
94             p_config->sortoutput = 1;
95             break;
96         case 'x':
97             p_config->xmloutput = 1;
98             break;
99         case 0:
100             if (p_config->infile)
101             {
102                 fprintf(stderr, "yaz-icu: only one input file may be given\n");
103                 print_option_error(p_config);
104             }
105             p_config->infile = fopen(arg, "r");
106             if (!p_config->infile)
107             {
108                 fprintf(stderr, "yaz-icu: cannot open %s : %s\n",
109                         arg, strerror(errno));
110                 exit(1);
111             }
112             break;
113         default:
114             fprintf(stderr, "yaz_icu: invalid option: %s\n", arg);
115             print_option_error(p_config);
116         }
117     }
118
119     if (p_config->infile == 0)
120         p_config->infile = stdin;
121
122     if (!strlen(p_config->conffile) && !strlen(p_config->print))
123         print_option_error(p_config);
124 }
125
126 static void print_icu_converters(const struct config_t *p_config)
127 {
128     int32_t count;
129     int32_t i;
130
131     count = ucnv_countAvailable();
132     if (p_config->xmloutput)
133         fprintf(p_config->outfile, "<converters count=\"%d\" default=\"%s\">\n",
134                 count, ucnv_getDefaultName());
135     else
136     {
137         fprintf(p_config->outfile, "Available ICU converters: %d\n", count);
138         fprintf(p_config->outfile, "Default ICU Converter is: '%s'\n",
139                 ucnv_getDefaultName());
140     }
141
142     for (i = 0; i < count; i++)
143     {
144         if (p_config->xmloutput)
145             fprintf(p_config->outfile, "<converter id=\"%s\"/>\n",
146                     ucnv_getAvailableName(i));
147         else
148             fprintf(p_config->outfile, "%s\n", ucnv_getAvailableName(i));
149     }
150
151     if (p_config->xmloutput)
152         fprintf(p_config->outfile, "</converters>\n");
153     else
154         fprintf(p_config->outfile, "\n");
155 }
156
157 static void print_icu_transliterators(const struct config_t *p_config)
158 {
159     UErrorCode status;
160     UEnumeration *en = utrans_openIDs(&status);
161     int32_t count = uenum_count(en, &status);
162     const char *name;
163     int32_t length;
164
165     if (p_config->xmloutput)
166         fprintf(p_config->outfile, "<transliterators count=\"%d\">\n",  count);
167     else
168         fprintf(p_config->outfile, "Available ICU transliterators: %d\n", count);
169
170     while ((name = uenum_next(en, &length, &status)))
171     {
172         if (p_config->xmloutput)
173             fprintf(p_config->outfile, "<transliterator id=\"%s\"/>\n", name);
174         else
175             fprintf(p_config->outfile, "%s\n", name);
176     }
177     uenum_close(en);
178     if (p_config->xmloutput)
179         fprintf(p_config->outfile, "</transliterators>\n");
180     else
181     {
182         fprintf(p_config->outfile, "\n\nUnicode Set Patterns:\n"
183                 "   Pattern         Description\n"
184                 "   Ranges          [a-z]       The lower case letters a through z\n"
185                 "   Named Chars     [abc123] The six characters a,b,c,1,2 and 3\n"
186                 "   String          [abc{def}] chars a, b and c, and string 'def'\n"
187                 "   Categories      [\\p{Letter}] Perl General Category 'Letter'.\n"
188                 "   Categories      [:Letter:] Posix General Category 'Letter'.\n"
189                 "\n"
190                 "   Combination     Example\n"
191                 "   Union           [[:Greek:] [:letter:]]\n"
192                 "   Intersection    [[:Greek:] & [:letter:]]\n"
193                 "   Set Complement  [[:Greek:] - [:letter:]]\n"
194                 "   Complement      [^[:Greek:] [:letter:]]\n"
195                 "\n"
196              "see: http://icu.sourceforge.net/userguide/unicodeSet.html\n"
197                 "\n"
198                 "Examples:\n"
199                 "   [:Punctuation:] Any-Remove\n"
200                 "   [:Cased-Letter:] Any-Upper\n"
201                 "   [:Control:] Any-Remove\n"
202                 "   [:Decimal_Number:] Any-Remove\n"
203                 "   [:Final_Punctuation:] Any-Remove\n"
204                 "   [:Georgian:] Any-Upper\n"
205                 "   [:Katakana:] Any-Remove\n"
206                 "   [:Arabic:] Any-Remove\n"
207                 "   [:Punctuation:] Remove\n"
208                 "   [[:Punctuation:]-[.,]] Remove\n"
209                 "   [:Line_Separator:] Any-Remove\n"
210                 "   [:Math_Symbol:] Any-Remove\n"
211                 "   Lower; [:^Letter:] Remove (word tokenization)\n"
212                 "   [:^Number:] Remove (numeric tokenization)\n"
213                 "   [:^Katagana:] Remove (remove everything except Katagana)\n"
214                 "   Lower;[[:WhiteSpace:][:Punctuation:]] Remove (word tokenization)\n"
215                 "   NFD; [:Nonspacing Mark:] Remove; NFC   (removes accents from characters)\n"
216                 "   [A-Za-z]; Lower(); Latin-Katakana; Katakana-Hiragana (transforms latin and katagana to hiragana)\n"
217                 "   [[:separator:][:start punctuation:][:initial punctuation:]] Remove \n"
218                 "\n"
219                 "see http://userguide.icu-project.org/transforms/general\n"
220                 "    http://www.unicode.org/reports/tr44/\n"
221             );
222
223
224         fprintf(p_config->outfile, "\n\n");
225
226     }
227 }
228
229 static void print_icu_xml_locales(const struct config_t *p_config)
230 {
231     int32_t count;
232     int32_t i;
233     UErrorCode status = U_ZERO_ERROR;
234
235     UChar keyword[64];
236     int32_t keyword_len = 0;
237     char keyword_str[128];
238     int32_t keyword_str_len = 0;
239
240     UChar language[64];
241     int32_t language_len = 0;
242     char lang_str[128];
243     int32_t lang_str_len = 0;
244
245     UChar script[64];
246     int32_t script_len = 0;
247     char script_str[128];
248     int32_t script_str_len = 0;
249
250     UChar location[64];
251     int32_t location_len = 0;
252     char location_str[128];
253     int32_t location_str_len = 0;
254
255     UChar variant[64];
256     int32_t variant_len = 0;
257     char variant_str[128];
258     int32_t variant_str_len = 0;
259
260     UChar name[64];
261     int32_t name_len = 0;
262     char name_str[128];
263     int32_t name_str_len = 0;
264
265     UChar localname[64];
266     int32_t localname_len = 0;
267     char localname_str[128];
268     int32_t localname_str_len = 0;
269
270     count = uloc_countAvailable() ;
271
272     if (p_config->xmloutput)
273     {
274         fprintf(p_config->outfile, "<locales count=\"%d\" default=\"%s\" collations=\"%d\">\n",
275                 count, uloc_getDefault(), ucol_countAvailable());
276     }
277     else
278     {
279         fprintf(p_config->outfile, "Available ICU locales: %d\n", count);
280         fprintf(p_config->outfile, "Default locale is: %s\n",  uloc_getDefault());
281     }
282
283     for (i = 0; i < count; i++)
284     {
285
286         keyword_len
287             = uloc_getDisplayKeyword(uloc_getAvailable(i), "en",
288                                      keyword, 64,
289                                      &status);
290
291         u_strToUTF8(keyword_str, 128, &keyword_str_len,
292                     keyword, keyword_len,
293                     &status);
294
295
296         language_len
297             = uloc_getDisplayLanguage(uloc_getAvailable(i), "en",
298                                       language, 64,
299                                       &status);
300
301         u_strToUTF8(lang_str, 128, &lang_str_len,
302                     language, language_len,
303                     &status);
304
305
306         script_len
307             = uloc_getDisplayScript(uloc_getAvailable(i), "en",
308                                     script, 64,
309                                     &status);
310
311         u_strToUTF8(script_str, 128, &script_str_len,
312                     script, script_len,
313                     &status);
314
315         location_len
316             = uloc_getDisplayCountry(uloc_getAvailable(i), "en",
317                                      location, 64,
318                                      &status);
319
320         u_strToUTF8(location_str, 128, &location_str_len,
321                     location, location_len,
322                     &status);
323
324         variant_len
325             = uloc_getDisplayVariant(uloc_getAvailable(i), "en",
326                                      variant, 64,
327                                      &status);
328
329         u_strToUTF8(variant_str, 128, &variant_str_len,
330                     variant, variant_len,
331                     &status);
332
333         name_len
334             = uloc_getDisplayName(uloc_getAvailable(i), "en",
335                                   name, 64,
336                                   &status);
337
338         u_strToUTF8(name_str, 128, &name_str_len,
339                     name, name_len,
340                     &status);
341
342         localname_len
343             = uloc_getDisplayName(uloc_getAvailable(i), uloc_getAvailable(i),
344                                   localname, 64,
345                                   &status);
346
347         u_strToUTF8(localname_str, 128, &localname_str_len,
348                     localname, localname_len,
349                     &status);
350
351
352         if (p_config->xmloutput)
353         {
354             fprintf(p_config->outfile, "<locale id=\"%s\"", uloc_getAvailable(i));
355             if (strlen(lang_str))
356                 fprintf(p_config->outfile, " language=\"%s\"", lang_str);
357             if (strlen(script_str))
358                 fprintf(p_config->outfile, " script=\"%s\"", script_str);
359             if (strlen(location_str))
360                 fprintf(p_config->outfile, " location=\"%s\"", location_str);
361             if (strlen(variant_str))
362                 fprintf(p_config->outfile, " variant=\"%s\"", variant_str);
363             if (strlen(name_str))
364                 fprintf(p_config->outfile, " name=\"%s\"", name_str);
365             if (strlen(localname_str))
366                 fprintf(p_config->outfile, " localname=\"%s\"", localname_str);
367             fprintf(p_config->outfile, ">");
368             if (strlen(localname_str))
369                 fprintf(p_config->outfile, "%s", localname_str);
370             fprintf(p_config->outfile, "</locale>\n");
371         }
372         else if (1 == p_config->xmloutput)
373         {
374             fprintf(p_config->outfile, "%s", uloc_getAvailable(i));
375             fprintf(p_config->outfile, " | ");
376             if (strlen(name_str))
377                 fprintf(p_config->outfile, "%s", name_str);
378             fprintf(p_config->outfile, " | ");
379             if (strlen(localname_str))
380                 fprintf(p_config->outfile, "%s", localname_str);
381             fprintf(p_config->outfile, "\n");
382         }
383         else
384             fprintf(p_config->outfile, "%s\n", uloc_getAvailable(i));
385     }
386     if (p_config->xmloutput)
387         fprintf(p_config->outfile, "</locales>\n");
388     else
389         fprintf(p_config->outfile, "\n");
390
391     if (U_FAILURE(status))
392     {
393         fprintf(stderr, "ICU Error: %d %s\n", status, u_errorName(status));
394         exit(2);
395     }
396 }
397
398
399 static void print_info(const struct config_t *p_config)
400 {
401     if (p_config->xmloutput)
402         fprintf(p_config->outfile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
403                 "<icu>\n");
404
405     if ('c' == p_config->print[0])
406         print_icu_converters(p_config);
407     else if ('l' == p_config->print[0])
408         print_icu_xml_locales(p_config);
409     else if ('t' == p_config->print[0])
410         print_icu_transliterators(p_config);
411     else {
412         print_icu_converters(p_config);
413         print_icu_xml_locales(p_config);
414         print_icu_transliterators(p_config);
415     }
416
417     if (p_config->xmloutput)
418         fprintf(p_config->outfile, "</icu>\n");
419
420     exit(0);
421 }
422
423
424
425 static void process_text_file(struct config_t *p_config)
426 {
427     char *line = 0;
428     char linebuf[1024];
429
430     xmlDoc *doc = xmlParseFile(p_config->conffile);
431     xmlNode *xml_node = xmlDocGetRootElement(doc);
432
433     long unsigned int token_count = 0;
434     long unsigned int line_count = 0;
435
436     UErrorCode status = U_ZERO_ERROR;
437
438     if (!xml_node)
439     {
440         printf("Could not parse XML config file '%s' \n",
441                 p_config->conffile);
442         exit(1);
443     }
444
445     p_config->chain = icu_chain_xml_config(xml_node, 1, &status);
446
447     if (!p_config->chain || !U_SUCCESS(status))
448     {
449         printf("Could not set up ICU chain from config file '%s' \n",
450                 p_config->conffile);
451         if (!U_SUCCESS(status))
452             printf("ICU Error: %d %s\n", status, u_errorName(status));
453         exit(1);
454     }
455
456     if (p_config->xmloutput)
457         fprintf(p_config->outfile,
458                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
459                 "<icu>\n"
460                 "<tokens>\n");
461
462     /* read input lines for processing */
463     while ((line=fgets(linebuf, sizeof(linebuf)-1, p_config->infile)))
464     {
465         WRBUF sw = wrbuf_alloc();
466         WRBUF cdata = wrbuf_alloc();
467         int success = icu_chain_assign_cstr(p_config->chain, line, &status);
468         line_count++;
469
470         while (success && icu_chain_next_token(p_config->chain, &status))
471         {
472             if (U_FAILURE(status))
473                 success = 0;
474             else
475             {
476                 const char *sortkey = icu_chain_token_sortkey(p_config->chain);
477                 wrbuf_rewind(sw);
478                 wrbuf_puts_escaped(sw, sortkey);
479                 token_count++;
480                 if (p_config->xmloutput)
481                 {
482                     fprintf(p_config->outfile,
483                             "<token id=\"%lu\" line=\"%lu\"",
484                             token_count, line_count);
485
486                     wrbuf_rewind(cdata);
487                     wrbuf_xmlputs(cdata, icu_chain_token_norm(p_config->chain));
488                     fprintf(p_config->outfile, " norm=\"%s\"",
489                             wrbuf_cstr(cdata));
490
491                     wrbuf_rewind(cdata);
492                     wrbuf_xmlputs(cdata, icu_chain_token_display(p_config->chain));
493                     fprintf(p_config->outfile, " display=\"%s\"",
494                             wrbuf_cstr(cdata));
495
496                     if (p_config->sortoutput)
497                     {
498                         wrbuf_rewind(cdata);
499                         wrbuf_xmlputs(cdata, wrbuf_cstr(sw));
500                         fprintf(p_config->outfile, " sortkey=\"%s\"",
501                                 wrbuf_cstr(cdata));
502                     }
503                     fprintf(p_config->outfile, "/>\n");
504                 }
505                 else
506                 {
507                     fprintf(p_config->outfile, "%lu %lu '%s' '%s'",
508                             token_count,
509                             line_count,
510                             icu_chain_token_norm(p_config->chain),
511                             icu_chain_token_display(p_config->chain));
512                     if (p_config->sortoutput)
513                     {
514                         fprintf(p_config->outfile, " '%s'", wrbuf_cstr(sw));
515                     }
516                     fprintf(p_config->outfile, "\n");
517                 }
518             }
519         }
520         wrbuf_destroy(sw);
521         wrbuf_destroy(cdata);
522     }
523
524     if (p_config->xmloutput)
525         fprintf(p_config->outfile,
526                 "</tokens>\n"
527                 "</icu>\n");
528
529     icu_chain_destroy(p_config->chain);
530     xmlFreeDoc(doc);
531     if (line)
532         free(line);
533 }
534
535 #endif /* YAZ_HAVE_ICU */
536
537
538 int main(int argc, char **argv)
539 {
540 #if YAZ_HAVE_ICU
541     struct config_t config;
542
543     read_params(argc, argv, &config);
544
545     if (config.conffile && strlen(config.conffile))
546         process_text_file(&config);
547
548     if (config.print && strlen(config.print))
549         print_info(&config);
550
551     u_cleanup();
552 #else /* YAZ_HAVE_ICU */
553
554     printf("ICU not available on your system.\n"
555            "Please install libicu-dev and icu-doc or similar, "
556            "re-configure and re-compile\n");
557
558
559     exit(3);
560 #endif /* YAZ_HAVE_ICU */
561
562     return 0;
563 }
564
565
566 /*
567  * Local variables:
568  * c-basic-offset: 4
569  * c-file-style: "Stroustrup"
570  * indent-tabs-mode: nil
571  * End:
572  * vim: shiftwidth=4 tabstop=8 expandtab
573  */
574