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