Debian Codegraph @

plugins/tokenizers/mecab.c

raw symbols SCIP
1 /*
2 Copyright (C) 2009-2018 Brazil
3 Copyright (C) 2018-2022 Sutou Kouhei <[email protected]>
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 #ifdef GRN_EMBEDDED
21 # define GRN_PLUGIN_FUNCTION_TAG tokenizers_mecab
22 #endif
23
24 #include <grn_str.h>
25
26 #include <groonga.h>
27 #include <groonga/tokenizer.h>
28
29 #include <grn_encoding.h>
30
31 #include <mecab.h>
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <ctype.h>
36
37 #ifdef _MSC_VER
38 # include <fcntl.h>
39 #endif
40
41 typedef struct {
42 mecab_model_t *mecab_model;
43 mecab_t *mecab;
44 grn_plugin_mutex *mutex;
45 grn_encoding encoding;
46 } grn_mecab;
47
48 static const char *grn_mecab_lattice_variable_name = "TokenMecab.lattice";
49
50 static grn_mecab mecab_default;
51 static grn_mecab mecab_newline;
52
53 static bool grn_mecab_chunked_tokenize_enabled = false;
54 static int32_t grn_mecab_chunk_size_threshold = 8192;
55
56 static const size_t GRN_MECAB_FEATURE_LOCATION_CLASS = 0;
57 static const size_t GRN_MECAB_FEATURE_LOCATION_SUBCLASS0 = 1;
58 static const size_t GRN_MECAB_FEATURE_LOCATION_SUBCLASS1 = 2;
59 static const size_t GRN_MECAB_FEATURE_LOCATION_SUBCLASS2 = 3;
60 static const size_t GRN_MECAB_FEATURE_LOCATION_BASE_FORM = 6;
61 static const size_t GRN_MECAB_FEATURE_LOCATION_READING = 7;
62
63 typedef struct {
64 bool chunked_tokenize;
65 int32_t chunk_size_threshold;
66 bool include_class;
67 bool include_reading;
68 bool include_form;
69 bool use_reading;
70 bool use_base_form;
71 grn_obj target_classes;
72 } grn_mecab_tokenizer_options;
73
74 typedef struct {
75 grn_mecab_tokenizer_options *options;
76 grn_mecab *mecab;
77 mecab_lattice_t *lattice;
78 grn_obj buf;
79 const char *next;
80 const char *end;
81 grn_tokenizer_query *query;
82 grn_obj feature_locations;
83 } grn_mecab_tokenizer;
84
85 static const char *
86 mecab_global_error_message(void)
87 {
88 double version;
89
90 version = atof(mecab_version());
91 /* MeCab <= 0.993 doesn't support mecab_strerror(NULL). */
92 if (version <= 0.993) {
93 return "Unknown";
94 }
95
96 return mecab_strerror(NULL);
97 }
98
99 static grn_encoding
100 translate_mecab_charset_to_grn_encoding(const char *charset)
101 {
102 if (grn_strcasecmp(charset, "euc-jp") == 0) {
103 return GRN_ENC_EUC_JP;
104 } else if (grn_strcasecmp(charset, "utf-8") == 0 ||
105 grn_strcasecmp(charset, "utf8") == 0) {
106 return GRN_ENC_UTF8;
107 } else if (grn_strcasecmp(charset, "shift_jis") == 0 ||
108 grn_strcasecmp(charset, "shift-jis") == 0 ||
109 grn_strcasecmp(charset, "sjis") == 0) {
110 return GRN_ENC_SJIS;
111 }
112 return GRN_ENC_NONE;
113 }
114
115 static void
116 grn_mecab_init(grn_ctx *ctx, grn_mecab *mecab, const char *tag)
117 {
118 mecab->mecab_model = NULL;
119 mecab->mecab = NULL;
120 mecab->mutex = grn_plugin_mutex_open(ctx);
121 if (!mecab->mutex) {
122 GRN_PLUGIN_ERROR(ctx,
123 GRN_NO_MEMORY_AVAILABLE,
124 "[plugin][tokenizer][mecab][init]%s "
125 "failed to initialize mutex",
126 tag);
127 return;
128 }
129 mecab->encoding = GRN_ENC_NONE;
130 }
131
132 static void
133 grn_mecab_fin(grn_ctx *ctx, grn_mecab *mecab)
134 {
135 if (mecab->mecab) {
136 mecab_destroy(mecab->mecab);
137 mecab->mecab = NULL;
138 }
139 if (mecab->mecab_model) {
140 mecab_model_destroy(mecab->mecab_model);
141 mecab->mecab_model = NULL;
142 }
143 if (mecab->mutex) {
144 grn_plugin_mutex_close(ctx, mecab->mutex);
145 mecab->mutex = NULL;
146 }
147 mecab->encoding = GRN_ENC_NONE;
148 }
149
150 static grn_encoding
151 get_mecab_encoding(mecab_t *mecab)
152 {
153 grn_encoding encoding = GRN_ENC_NONE;
154 const mecab_dictionary_info_t *dictionary_info;
155 dictionary_info = mecab_dictionary_info(mecab);
156 if (dictionary_info) {
157 const char *charset = dictionary_info->charset;
158 encoding = translate_mecab_charset_to_grn_encoding(charset);
159 }
160 return encoding;
161 }
162
163 static void
164 mecab_tokenizer_options_init(grn_mecab_tokenizer_options *options)
165 {
166 options->chunked_tokenize = grn_mecab_chunked_tokenize_enabled;
167 options->chunk_size_threshold = grn_mecab_chunk_size_threshold;
168 options->include_class = false;
169 options->include_reading = false;
170 options->include_form = false;
171 options->use_reading = false;
172 options->use_base_form = false;
173 GRN_TEXT_INIT(&(options->target_classes), GRN_OBJ_VECTOR);
174 }
175
176 static bool
177 mecab_tokenizer_options_need_default_output(
178 grn_ctx *ctx, grn_mecab_tokenizer_options *options)
179 {
180 if (!options) {
181 return false;
182 }
183
184 if (options->include_class) {
185 return true;
186 }
187
188 if (options->include_reading) {
189 return true;
190 }
191
192 if (options->include_form) {
193 return true;
194 }
195
196 if (options->use_reading) {
197 return true;
198 }
199
200 if (options->use_base_form) {
201 return true;
202 }
203
204 if (grn_vector_size(ctx, &(options->target_classes)) > 0) {
205 return true;
206 }
207
208 return false;
209 }
210
211 static void *
212 mecab_tokenizer_options_open(grn_ctx *ctx,
213 grn_obj *lexicon,
214 grn_obj *raw_options,
215 void *user_data)
216 {
217 grn_mecab_tokenizer_options *options;
218
219 options = GRN_PLUGIN_MALLOC(ctx, sizeof(grn_mecab_tokenizer_options));
220 if (!options) {
221 GRN_PLUGIN_ERROR(ctx,
222 GRN_NO_MEMORY_AVAILABLE,
223 "[tokenizer][mecab] "
224 "failed to allocate memory for options");
225 return NULL;
226 }
227
228 mecab_tokenizer_options_init(options);
229
230 GRN_OPTION_VALUES_EACH_BEGIN(ctx, raw_options, i, name, name_length)
231 {
232 grn_raw_string name_raw;
233 name_raw.value = name;
234 name_raw.length = name_length;
235
236 if (GRN_RAW_STRING_EQUAL_CSTRING(name_raw, "chunked_tokenize")) {
237 options->chunked_tokenize =
238 grn_vector_get_element_bool(ctx,
239 raw_options,
240 i,
241 options->chunked_tokenize);
242 } else if (GRN_RAW_STRING_EQUAL_CSTRING(name_raw, "chunk_size_threshold")) {
243 options->chunk_size_threshold =
244 grn_vector_get_element_int32(ctx,
245 raw_options,
246 i,
247 options->chunk_size_threshold);
248 } else if (GRN_RAW_STRING_EQUAL_CSTRING(name_raw, "include_class")) {
249 options->include_class =
250 grn_vector_get_element_bool(ctx,
251 raw_options,
252 i,
253 options->include_class);
254 } else if (GRN_RAW_STRING_EQUAL_CSTRING(name_raw, "include_reading")) {
255 options->include_reading =
256 grn_vector_get_element_bool(ctx,
257 raw_options,
258 i,
259 options->include_reading);
260 } else if (GRN_RAW_STRING_EQUAL_CSTRING(name_raw, "include_form")) {
261 options->include_form =
262 grn_vector_get_element_bool(ctx, raw_options, i, options->include_form);
263 } else if (GRN_RAW_STRING_EQUAL_CSTRING(name_raw, "use_reading")) {
264 options->use_reading =
265 grn_vector_get_element_bool(ctx, raw_options, i, options->use_reading);
266 } else if (GRN_RAW_STRING_EQUAL_CSTRING(name_raw, "use_base_form")) {
267 options->use_base_form =
268 grn_vector_get_element_bool(ctx,
269 raw_options,
270 i,
271 options->use_base_form);
272 } else if (GRN_RAW_STRING_EQUAL_CSTRING(name_raw, "target_class")) {
273 const char *target_class = NULL;
274 unsigned int target_class_length;
275 grn_id domain;
276
277 target_class_length = grn_vector_get_element(ctx,
278 raw_options,
279 i,
280 &target_class,
281 NULL,
282 &domain);
283 if (grn_type_id_is_text_family(ctx, domain) && target_class_length > 0) {
284 grn_vector_add_element(ctx,
285 &(options->target_classes),
286 target_class,
287 target_class_length,
288 0,
289 GRN_DB_TEXT);
290 }
291 }
292 }
293 GRN_OPTION_VALUES_EACH_END();
294
295 return options;
296 }
297
298 static void
299 mecab_tokenizer_options_close(grn_ctx *ctx, void *data)
300 {
301 grn_mecab_tokenizer_options *options = data;
302 GRN_OBJ_FIN(ctx, &(options->target_classes));
303 GRN_PLUGIN_FREE(ctx, options);
304 }
305
306 static inline bool
307 is_delimiter_character(grn_ctx *ctx, const char *character, int character_bytes)
308 {
309 switch (character_bytes) {
310 case 1:
311 switch (character[0]) {
312 case ',':
313 case '.':
314 case '!':
315 case '?':
316 return true;
317 default:
318 return false;
319 }
320 case 3:
321 switch ((unsigned char)(character[0])) {
322 case 0xE3:
323 switch ((unsigned char)(character[1])) {
324 case 0x80:
325 switch ((unsigned char)(character[2])) {
326 case 0x81: /* U+3001 (0xE3 0x80 0x81 in UTF-8) IDEOGRAPHIC COMMA */
327 case 0x82: /* U+3002 (0xE3 0x80 0x82 in UTF-8) IDEOGRAPHIC FULL STOP */
328 return true;
329 default:
330 return false;
331 }
332 default:
333 return false;
334 }
335 return false;
336 case 0xEF:
337 switch ((unsigned char)(character[1])) {
338 case 0xBC:
339 switch ((unsigned char)(character[2])) {
340 case 0x81:
341 /* U+FF01 (0xEF 0xBC 0x81 in UTF-8) FULLWIDTH EXCLAMATION MARK */
342 case 0x9F:
343 /* U+FF1F (0xEF 0xBC 0x9F in UTF-8) FULLWIDTH QUESTION MARK */
344 return true;
345 default:
346 return false;
347 }
348 default:
349 return false;
350 }
351 return false;
352 default:
353 return false;
354 }
355 default:
356 return false;
357 }
358 }
359
360 static bool
361 chunked_tokenize_utf8_chunk(grn_ctx *ctx,
362 grn_mecab_tokenizer *tokenizer,
363 const char *chunk,
364 size_t chunk_bytes)
365 {
366 const char *tokenized_chunk;
367 size_t tokenized_chunk_length;
368 mecab_lattice_set_sentence2(tokenizer->lattice, chunk, chunk_bytes);
369 if (!mecab_parse_lattice(tokenizer->mecab->mecab, tokenizer->lattice)) {
370 GRN_PLUGIN_ERROR(ctx,
371 GRN_TOKENIZER_ERROR,
372 "[tokenizer][mecab][chunk] "
373 "mecab_parse_lattice() failed "
374 "len=%" GRN_FMT_SIZE " err=%s",
375 chunk_bytes,
376 mecab_lattice_strerror(tokenizer->lattice));
377 return false;
378 }
379 tokenized_chunk = mecab_lattice_tostr(tokenizer->lattice);
380 if (!tokenized_chunk) {
381 GRN_PLUGIN_ERROR(ctx,
382 GRN_TOKENIZER_ERROR,
383 "[tokenizer][mecab][chunk] "
384 "mecab_sparse_tostr2() failed "
385 "len=%" GRN_FMT_SIZE " err=%s",
386 chunk_bytes,
387 mecab_lattice_strerror(tokenizer->lattice));
388 return false;
389 }
390
391 if (GRN_TEXT_LEN(&(tokenizer->buf)) > 0) {
392 GRN_TEXT_PUTS(ctx, &(tokenizer->buf), "\n");
393 }
394
395 tokenized_chunk_length = strlen(tokenized_chunk);
396 if (tokenized_chunk_length >= 1 &&
397 isspace((unsigned char)tokenized_chunk[tokenized_chunk_length - 1])) {
398 GRN_TEXT_PUT(ctx,
399 &(tokenizer->buf),
400 tokenized_chunk,
401 tokenized_chunk_length - 1);
402 } else {
403 GRN_TEXT_PUT(ctx,
404 &(tokenizer->buf),
405 tokenized_chunk,
406 tokenized_chunk_length);
407 }
408
409 return true;
410 }
411
412 static bool
413 chunked_tokenize_utf8(grn_ctx *ctx,
414 grn_mecab_tokenizer *tokenizer,
415 const char *string,
416 unsigned int string_bytes)
417 {
418 const char *chunk_start;
419 const char *current;
420 const char *last_delimiter;
421 const char *string_end = string + string_bytes;
422 grn_encoding encoding =
423 grn_tokenizer_query_get_encoding(ctx, tokenizer->query);
424
425 if ((int32_t)string_bytes < tokenizer->options->chunk_size_threshold) {
426 return chunked_tokenize_utf8_chunk(ctx, tokenizer, string, string_bytes);
427 }
428
429 chunk_start = current = string;
430 last_delimiter = NULL;
431 while (current < string_end) {
432 int space_bytes;
433 int character_bytes;
434 const char *current_character;
435
436 space_bytes = grn_isspace(current, encoding);
437 if (space_bytes > 0) {
438 if (chunk_start != current) {
439 bool succeeded =
440 chunked_tokenize_utf8_chunk(ctx,
441 tokenizer,
442 chunk_start,
443 (size_t)(current - chunk_start));
444 if (!succeeded) {
445 return succeeded;
446 }
447 }
448 current += space_bytes;
449 chunk_start = current;
450 last_delimiter = NULL;
451 continue;
452 }
453
454 character_bytes = grn_charlen_(ctx, current, string_end, encoding);
455 if (character_bytes == 0) {
456 GRN_PLUGIN_ERROR(ctx,
457 GRN_TOKENIZER_ERROR,
458 "[tokenizer][mecab][chunk] "
459 "invalid byte sequence: position=%d",
460 (int)(current - string));
461 return false;
462 }
463
464 current_character = current;
465 current += character_bytes;
466 if (is_delimiter_character(ctx, current_character, character_bytes)) {
467 last_delimiter = current;
468 }
469
470 if ((current - chunk_start) >= tokenizer->options->chunk_size_threshold) {
471 bool succeeded;
472 if (last_delimiter) {
473 succeeded =
474 chunked_tokenize_utf8_chunk(ctx,
475 tokenizer,
476 chunk_start,
477 (size_t)(last_delimiter - chunk_start));
478 chunk_start = last_delimiter;
479 } else {
480 succeeded =
481 chunked_tokenize_utf8_chunk(ctx,
482 tokenizer,
483 chunk_start,
484 (size_t)(current - chunk_start));
485 chunk_start = current;
486 }
487 if (!succeeded) {
488 return succeeded;
489 }
490 last_delimiter = NULL;
491 }
492 }
493
494 if (current == chunk_start) {
495 return true;
496 } else {
497 return chunked_tokenize_utf8_chunk(ctx,
498 tokenizer,
499 chunk_start,
500 (size_t)(current - chunk_start));
501 }
502 }
503
504 static mecab_model_t *
505 mecab_model_create(grn_ctx *ctx, grn_mecab_tokenizer_options *options)
506 {
507 mecab_model_t *mecab_model;
508 int argc = 0;
509 const char *argv[5];
510 const char *tag;
511
512 bool need_default_output =
513 mecab_tokenizer_options_need_default_output(ctx, options);
514
515 if (need_default_output) {
516 tag = "[default]";
517 } else {
518 tag = "[newline]";
519 }
520
521 argv[argc++] = "Groonga";
522 if (!need_default_output) {
523 argv[argc++] = "-F%m\n";
524 argv[argc++] = "-E\n";
525 }
526 #ifdef GRN_WITH_BUNDLED_MECAB
527 argv[argc++] = "--rcfile";
528 # ifdef WIN32
529 {
530 static char windows_mecab_rc_file[PATH_MAX];
531 const char *utf8_base_dir;
532
533 utf8_base_dir =
534 grn_encoding_convert_to_utf8_from_locale(ctx,
535 grn_plugin_windows_base_dir(),
536 -1,
537 NULL);
538 grn_strcpy(windows_mecab_rc_file, PATH_MAX, utf8_base_dir);
539 grn_encoding_converted_free(ctx, utf8_base_dir);
540 grn_strcat(windows_mecab_rc_file, PATH_MAX, "/");
541 grn_strcat(windows_mecab_rc_file,
542 PATH_MAX,
543 GRN_BUNDLED_MECAB_RELATIVE_RC_PATH);
544 {
545 char *c;
546 for (c = windows_mecab_rc_file; *c != '\0'; c++) {
547 if (*c == '/') {
548 *c = '\\';
549 }
550 }
551 }
552 argv[argc++] = windows_mecab_rc_file;
553 }
554 # else /* WIN32 */
555 argv[argc++] = GRN_BUNDLED_MECAB_RC_PATH;
556 # endif /* WIN32 */
557 #endif /* GRN_WITH_BUNDLED_MECAB */
558
559 #if _MSC_VER
560 /* This is a workaround for MariaDB 10.9 or later and MeCab.
561 *
562 * MariaDB 10.9 or later calls _set_fmode(_O_BINARY) in
563 * initialization process on Windows.
564 *
565 * See also:
566 * https://github.com/MariaDB/server/commit/016dd21371961700f1324f204acbc7252a8c1e76
567 *
568 * But mecab_model_new() doesn't work with _O_BINARY on Windows
569 * because "\r" in mecab.rc is processed as a line content. This
570 * causes a parse error.
571 *
572 * We change restore the default file translation mode to _O_TEXT
573 * temporary here. But this is not safe. If some files are open in
574 * other threads, these threads open a file with _O_TEXT not
575 * _O_BINARY.
576 *
577 * MariaDB should not use _set_fmode() because it changes the
578 * default file translation mode globally. But this is the MariaDB's
579 * decision. So we need this workaround. */
580 int current_file_translation_mode = _O_TEXT;
581 _get_fmode(&current_file_translation_mode);
582 _set_fmode(_O_TEXT);
583 #endif
584 mecab_model = mecab_model_new(argc, (char **)argv);
585 #if __MSC_VER
586 _set_fmode(current_file_translation_mode);
587 #endif
588
589 if (!mecab_model) {
590 #ifdef GRN_WITH_BUNDLED_MECAB
591 {
592 const char *grn_encoding_rc_file;
593 grn_encoding_rc_file =
594 grn_encoding_convert_from_locale(ctx, argv[argc - 1], -1, NULL);
595 if (need_default_output) {
596 GRN_PLUGIN_ERROR(ctx,
597 GRN_TOKENIZER_ERROR,
598 "[tokenizer][mecab][create]%s "
599 "failed to create mecab_model_t: %s: "
600 "mecab_model_new(\"%s\", \"%s\", \"%s\")",
601 tag,
602 mecab_global_error_message(),
603 argv[0],
604 argv[1],
605 grn_encoding_rc_file);
606 } else {
607 GRN_PLUGIN_ERROR(ctx,
608 GRN_TOKENIZER_ERROR,
609 "[tokenizer][mecab][create]%s "
610 "failed to create mecab_model_t: %s: "
611 "mecab_model_new(\"%s\", \"%s\", \"%s\", \"%s\")",
612 tag,
613 mecab_global_error_message(),
614 argv[0],
615 argv[1],
616 argv[2],
617 grn_encoding_rc_file);
618 }
619 grn_encoding_converted_free(ctx, grn_encoding_rc_file);
620 }
621 #else /* GRN_WITH_BUNDLED_MECAB */
622 if (need_default_output) {
623 GRN_PLUGIN_ERROR(ctx,
624 GRN_TOKENIZER_ERROR,
625 "[tokenizer][mecab][create]%s "
626 "failed to create mecab_model_t: %s: "
627 "mecab_model_new(\"%s\")",
628 tag,
629 mecab_global_error_message(),
630 argv[0]);
631 } else {
632 GRN_PLUGIN_ERROR(ctx,
633 GRN_TOKENIZER_ERROR,
634 "[tokenizer][mecab][create]%s "
635 "failed to create mecab_model_t: %s: "
636 "mecab_model_new(\"%s\", \"%s\")",
637 tag,
638 mecab_global_error_message(),
639 argv[0],
640 argv[1]);
641 }
642 #endif /* GRN_WITH_BUNDLED_MECAB */
643 }
644
645 return mecab_model;
646 }
647
648 static void
649 mecab_init_mecab(grn_ctx *ctx, grn_mecab_tokenizer *tokenizer)
650 {
651 if (mecab_tokenizer_options_need_default_output(ctx, tokenizer->options)) {
652 tokenizer->mecab = &mecab_default;
653 } else {
654 tokenizer->mecab = &mecab_newline;
655 }
656
657 if (!tokenizer->mecab->mecab) {
658 grn_plugin_mutex_lock(ctx, tokenizer->mecab->mutex);
659 if (!tokenizer->mecab->mecab) {
660 tokenizer->mecab->mecab_model =
661 mecab_model_create(ctx, tokenizer->options);
662 if (tokenizer->mecab->mecab_model) {
663 tokenizer->mecab->mecab =
664 mecab_model_new_tagger(tokenizer->mecab->mecab_model);
665 if (tokenizer->mecab->mecab) {
666 tokenizer->mecab->encoding =
667 get_mecab_encoding(tokenizer->mecab->mecab);
668 }
669 }
670 }
671 grn_plugin_mutex_unlock(ctx, tokenizer->mecab->mutex);
672 }
673 }
674
675 static void
676 mecab_next_default_format_skip_eos(grn_ctx *ctx, grn_mecab_tokenizer *tokenizer)
677 {
678 if (tokenizer->next + 4 < tokenizer->end) {
679 return;
680 }
681
682 if (strncmp(tokenizer->next, "EOS", 3) == 0) {
683 const char *current = tokenizer->next + 3;
684 if (current < tokenizer->end && current[0] == '\r') {
685 current++;
686 }
687 if (current < tokenizer->end && current[0] == '\n') {
688 current++;
689 tokenizer->next = current;
690 }
691 }
692 }
693
694 typedef struct {
695 grn_token *token;
696 grn_obj *feature_locations;
697 bool ignore_empty_value;
698 bool ignore_asterisk_value;
699 } add_feature_data;
700
701 static size_t
702 mecab_get_feature(grn_ctx *ctx,
703 grn_obj *feature_locations,
704 size_t i,
705 const char **value)
706 {
707 size_t n_locations = GRN_BULK_VSIZE(feature_locations) / sizeof(uint64_t);
708 const char *start;
709 const char *end;
710
711 if (i + 2 > n_locations) {
712 *value = NULL;
713 return 0;
714 }
715
716 start = (const char *)(GRN_UINT64_VALUE_AT(feature_locations, i));
717 end = ((const char *)(GRN_UINT64_VALUE_AT(feature_locations, i + 1))) - 1;
718 *value = start;
719 return (size_t)(end - start);
720 }
721
722 static void
723 mecab_next_default_format_add_feature(grn_ctx *ctx,
724 add_feature_data *data,
725 const char *name,
726 size_t i)
727 {
728 grn_token *token = data->token;
729 grn_obj *feature_locations = data->feature_locations;
730 const char *feature = NULL;
731 size_t feature_length;
732 grn_obj value;
733
734 feature_length = mecab_get_feature(ctx, feature_locations, i, &feature);
735 if (data->ignore_empty_value && feature_length == 0) {
736 return;
737 }
738 if (data->ignore_asterisk_value && feature_length == 1 && feature[0] == '*') {
739 return;
740 }
741
742 GRN_TEXT_INIT(&value, GRN_OBJ_DO_SHALLOW_COPY);
743 GRN_TEXT_SET(ctx, &value, feature, feature_length);
744 grn_token_metadata_add(ctx,
745 grn_token_get_metadata(ctx, token),
746 name,
747 -1,
748 &value);
749 GRN_OBJ_FIN(ctx, &value);
750 }
751
752 static size_t
753 mecab_next_default_format_consume_token(grn_ctx *ctx,
754 grn_mecab_tokenizer *tokenizer,
755 const char **surface_output)
756 {
757 grn_encoding encoding = tokenizer->query->encoding;
758 grn_obj *feature_locations = &(tokenizer->feature_locations);
759 const char *start;
760 const char *current;
761 const char *end = tokenizer->end;
762 const char *surface = NULL;
763 int length = 0;
764 size_t surface_length = 0;
765
766 if (surface_output) {
767 *surface_output = NULL;
768 }
769
770 GRN_BULK_REWIND(feature_locations);
771 mecab_next_default_format_skip_eos(ctx, tokenizer);
772 start = surface = tokenizer->next;
773 for (current = start; current < end; current += length) {
774 length = grn_charlen_(ctx, current, end, encoding);
775 if (length == 0) {
776 if (surface_output) {
777 *surface_output = NULL;
778 }
779 return 0;
780 }
781
782 if (length == 1) {
783 if (current[0] == '\r') {
784 if (surface_length == 0) {
785 surface_length = (size_t)(current - surface);
786 } else {
787 GRN_UINT64_PUT(ctx, feature_locations, current);
788 }
789 current++;
790 if (current < end && grn_charlen_(ctx, current, end, encoding) == 1 &&
791 current[0] == '\n') {
792 current++;
793 }
794 break;
795 } else if (current[0] == '\n') {
796 if (surface_length == 0) {
797 surface_length = (size_t)(current - surface);
798 } else {
799 GRN_UINT64_PUT(ctx, feature_locations, current);
800 }
801 current++;
802 break;
803 }
804 }
805
806 if (surface_length == 0) {
807 if (length == 1 && current[0] == '\t') {
808 surface_length = (size_t)(current - surface);
809 if (current + 1 < end) {
810 GRN_UINT64_PUT(ctx, feature_locations, current + 1);
811 }
812 }
813 } else {
814 if (length == 1 && current[0] == ',' && current + 1 < end) {
815 GRN_UINT64_PUT(ctx, feature_locations, current + 1);
816 }
817 }
818 }
819 tokenizer->next = current;
820 mecab_next_default_format_skip_eos(ctx, tokenizer);
821
822 if (surface_output) {
823 *surface_output = surface;
824 }
825 return surface_length;
826 }
827
828 static bool
829 mecab_next_default_format_match_class(grn_ctx *ctx,
830 const char *target_class,
831 size_t target_class_length,
832 const char *class,
833 size_t class_length)
834 {
835 if (class_length == 0) {
836 return false;
837 }
838
839 if (target_class_length < class_length) {
840 return false;
841 }
842
843 return memcmp(target_class, class, class_length) == 0;
844 }
845
846 static void
847 mecab_next_default_format_consume_needless_tokens(
848 grn_ctx *ctx, grn_mecab_tokenizer *tokenizer)
849 {
850 grn_obj *target_classes = &(tokenizer->options->target_classes);
851 unsigned int n_target_classes;
852 const char *last_next = tokenizer->next;
853 bool is_target = false;
854
855 n_target_classes = grn_vector_size(ctx, target_classes);
856
857 if (n_target_classes == 0) {
858 return;
859 }
860
861 while (tokenizer->next != tokenizer->end && !is_target) {
862 const char *surface = NULL;
863 size_t surface_length = 0;
864 unsigned int i;
865 grn_obj *feature_locations;
866 const size_t n_classes = 4;
867 const char *classes[4];
868 size_t class_lengths[4];
869
870 last_next = tokenizer->next;
871 surface_length =
872 mecab_next_default_format_consume_token(ctx, tokenizer, &surface);
873
874 if (surface_length == 0) {
875 break;
876 }
877
878 feature_locations = &(tokenizer->feature_locations);
879 class_lengths[0] = mecab_get_feature(ctx,
880 feature_locations,
881 GRN_MECAB_FEATURE_LOCATION_CLASS,
882 &(classes[0]));
883 class_lengths[1] = mecab_get_feature(ctx,
884 feature_locations,
885 GRN_MECAB_FEATURE_LOCATION_SUBCLASS0,
886 &(classes[1]));
887 class_lengths[2] = mecab_get_feature(ctx,
888 feature_locations,
889 GRN_MECAB_FEATURE_LOCATION_SUBCLASS1,
890 &(classes[2]));
891 class_lengths[3] = mecab_get_feature(ctx,
892 feature_locations,
893 GRN_MECAB_FEATURE_LOCATION_SUBCLASS2,
894 &(classes[3]));
895 for (i = 0; i < n_target_classes; i++) {
896 const char *target_class;
897 size_t target_class_length;
898 bool positive = true;
899 size_t j;
900 bool matched = false;
901
902 target_class_length = grn_vector_get_element(ctx,
903 target_classes,
904 i,
905 &target_class,
906 NULL,
907 NULL);
908 if (target_class_length > 0) {
909 switch (target_class[0]) {
910 case '+':
911 target_class++;
912 target_class_length--;
913 break;
914 case '-':
915 positive = false;
916 target_class++;
917 target_class_length--;
918 break;
919 default:
920 break;
921 }
922 }
923
924 for (j = 0; j < n_classes; j++) {
925 const size_t class_length = class_lengths[j];
926
927 if (target_class_length == 0) {
928 is_target = positive;
929 matched = true;
930 break;
931 }
932
933 if (!mecab_next_default_format_match_class(ctx,
934 target_class,
935 target_class_length,
936 classes[j],
937 class_length)) {
938 break;
939 }
940 target_class += class_length;
941 target_class_length -= class_length;
942 if (target_class_length == 0) {
943 is_target = positive;
944 matched = true;
945 break;
946 }
947 if (target_class[0] != '/') {
948 break;
949 }
950 target_class++;
951 target_class_length--;
952 }
953 if (matched) {
954 break;
955 }
956 }
957 }
958
959 if (is_target) {
960 tokenizer->next = last_next;
961 }
962 }
963
964 static void
965 mecab_next_default_format(grn_ctx *ctx,
966 grn_mecab_tokenizer *tokenizer,
967 grn_token *token)
968 {
969 const char *surface;
970 size_t surface_length = 0;
971
972 surface_length =
973 mecab_next_default_format_consume_token(ctx, tokenizer, &surface);
974 if (tokenizer->options->use_reading) {
975 grn_obj *feature_locations = &(tokenizer->feature_locations);
976 const char *reading = NULL;
977 size_t reading_length;
978 reading_length = mecab_get_feature(ctx,
979 feature_locations,
980 GRN_MECAB_FEATURE_LOCATION_READING,
981 &reading);
982 if (reading_length > 0) {
983 grn_token_set_data(ctx, token, reading, (int)reading_length);
984 } else {
985 grn_token_set_data(ctx, token, surface, (int)surface_length);
986 }
987 } else if (tokenizer->options->use_base_form) {
988 grn_obj *feature_locations = &(tokenizer->feature_locations);
989 const char *base_form = NULL;
990 size_t base_form_length;
991 base_form_length = mecab_get_feature(ctx,
992 feature_locations,
993 GRN_MECAB_FEATURE_LOCATION_BASE_FORM,
994 &base_form);
995 if (base_form_length > 0) {
996 grn_token_set_data(ctx, token, base_form, (int)base_form_length);
997 } else {
998 grn_token_set_data(ctx, token, surface, (int)surface_length);
999 }
1000 } else {
1001 grn_token_set_data(ctx, token, surface, (int)surface_length);
1002 }
1003 if (tokenizer->options->include_class) {
1004 add_feature_data data;
1005 data.token = token;
1006 data.feature_locations = &(tokenizer->feature_locations);
1007 data.ignore_empty_value = true;
1008 data.ignore_asterisk_value = true;
1009 mecab_next_default_format_add_feature(ctx,
1010 &data,
1011 "class",
1012 GRN_MECAB_FEATURE_LOCATION_CLASS);
1013 mecab_next_default_format_add_feature(ctx,
1014 &data,
1015 "subclass0",
1016 GRN_MECAB_FEATURE_LOCATION_SUBCLASS0);
1017 mecab_next_default_format_add_feature(ctx,
1018 &data,
1019 "subclass1",
1020 GRN_MECAB_FEATURE_LOCATION_SUBCLASS1);
1021 mecab_next_default_format_add_feature(ctx,
1022 &data,
1023 "subclass2",
1024 GRN_MECAB_FEATURE_LOCATION_SUBCLASS2);
1025 }
1026 if (tokenizer->options->include_reading) {
1027 add_feature_data data;
1028 data.token = token;
1029 data.feature_locations = &(tokenizer->feature_locations);
1030 data.ignore_empty_value = true;
1031 data.ignore_asterisk_value = false;
1032 mecab_next_default_format_add_feature(ctx,
1033 &data,
1034 "reading",
1035 GRN_MECAB_FEATURE_LOCATION_READING);
1036 }
1037 if (tokenizer->options->include_form) {
1038 add_feature_data data;
1039 data.token = token;
1040 data.feature_locations = &(tokenizer->feature_locations);
1041 data.ignore_empty_value = true;
1042 data.ignore_asterisk_value = true;
1043 mecab_next_default_format_add_feature(ctx, &data, "inflected_type", 4);
1044 mecab_next_default_format_add_feature(ctx, &data, "inflected_form", 5);
1045 mecab_next_default_format_add_feature(ctx,
1046 &data,
1047 "base_form",
1048 GRN_MECAB_FEATURE_LOCATION_BASE_FORM);
1049 }
1050 {
1051 grn_tokenizer_status status;
1052 if (surface_length == 0) {
1053 /* Error */
1054 status = GRN_TOKEN_LAST;
1055 } else {
1056 mecab_next_default_format_consume_needless_tokens(ctx, tokenizer);
1057 if (tokenizer->next == tokenizer->end) {
1058 status = GRN_TOKEN_LAST;
1059 } else {
1060 status = GRN_TOKEN_CONTINUE;
1061 }
1062 }
1063 grn_token_set_status(ctx, token, status);
1064 }
1065 }
1066
1067 static void
1068 mecab_next_newline_format(grn_ctx *ctx,
1069 grn_mecab_tokenizer *tokenizer,
1070 grn_token *token)
1071 {
1072 grn_encoding encoding = tokenizer->query->encoding;
1073 int cl;
1074 const char *p = tokenizer->next, *r;
1075 const char *e = tokenizer->end;
1076 grn_tokenizer_status status;
1077
1078 for (r = p; r < e; r += cl) {
1079 int space_len;
1080
1081 space_len = grn_isspace(r, encoding);
1082 if (space_len > 0 && r == p) {
1083 cl = space_len;
1084 p = r + cl;
1085 continue;
1086 }
1087
1088 if (!(cl = grn_charlen_(ctx, r, e, encoding))) {
1089 tokenizer->next = e;
1090 break;
1091 }
1092
1093 if (cl == 1 && r[0] == '\n') {
1094 tokenizer->next = r + cl;
1095 break;
1096 }
1097 }
1098
1099 if (r == e || tokenizer->next == e) {
1100 status = GRN_TOKEN_LAST;
1101 } else {
1102 status = GRN_TOKEN_CONTINUE;
1103 }
1104 grn_token_set_data(ctx, token, p, (int)(r - p));
1105 grn_token_set_status(ctx, token, status);
1106 }
1107
1108 static void
1109 grn_mecab_lattice_close(grn_ctx *ctx, void *data)
1110 {
1111 mecab_lattice_t *lattice = data;
1112 mecab_lattice_destroy(lattice);
1113 }
1114
1115 /*
1116 This function is called for a full text search query or a document to be
1117 indexed. This means that both short/long strings are given.
1118 The return value of this function is ignored. When an error occurs in this
1119 function, `ctx->rc' is overwritten with an error code (not GRN_SUCCESS).
1120 */
1121 static void *
1122 mecab_init(grn_ctx *ctx, grn_tokenizer_query *query)
1123 {
1124 grn_obj *lexicon;
1125 grn_mecab_tokenizer *tokenizer;
1126
1127 lexicon = grn_tokenizer_query_get_lexicon(ctx, query);
1128
1129 if (!(tokenizer = GRN_PLUGIN_MALLOC(ctx, sizeof(grn_mecab_tokenizer)))) {
1130 GRN_PLUGIN_ERROR(ctx,
1131 GRN_NO_MEMORY_AVAILABLE,
1132 "[tokenizer][mecab] "
1133 "memory allocation to grn_mecab_tokenizer failed");
1134 return NULL;
1135 }
1136
1137 tokenizer->options =
1138 grn_table_cache_default_tokenizer_options(ctx,
1139 lexicon,
1140 mecab_tokenizer_options_open,
1141 mecab_tokenizer_options_close,
1142 NULL);
1143 if (ctx->rc != GRN_SUCCESS) {
1144 GRN_PLUGIN_FREE(ctx, tokenizer);
1145 return NULL;
1146 }
1147
1148 mecab_init_mecab(ctx, tokenizer);
1149 if (!tokenizer->mecab->mecab) {
1150 GRN_PLUGIN_FREE(ctx, tokenizer);
1151 return NULL;
1152 }
1153 tokenizer->lattice =
1154 grn_ctx_get_variable(ctx, grn_mecab_lattice_variable_name, -1);
1155 if (!tokenizer->lattice) {
1156 tokenizer->lattice = mecab_model_new_lattice(tokenizer->mecab->mecab_model);
1157 if (!tokenizer->lattice) {
1158 GRN_PLUGIN_FREE(ctx, tokenizer);
1159 return NULL;
1160 }
1161 grn_ctx_set_variable(ctx,
1162 grn_mecab_lattice_variable_name,
1163 -1,
1164 tokenizer->lattice,
1165 grn_mecab_lattice_close);
1166 }
1167
1168 {
1169 grn_encoding encoding = grn_tokenizer_query_get_encoding(ctx, query);
1170 if (encoding != tokenizer->mecab->encoding) {
1171 GRN_PLUGIN_ERROR(ctx,
1172 GRN_TOKENIZER_ERROR,
1173 "[tokenizer][mecab] "
1174 "MeCab dictionary charset (%s) does not match "
1175 "the table encoding: <%s>",
1176 grn_encoding_to_string(tokenizer->mecab->encoding),
1177 grn_encoding_to_string(encoding));
1178 GRN_PLUGIN_FREE(ctx, tokenizer);
1179 return NULL;
1180 }
1181 }
1182
1183 tokenizer->query = query;
1184
1185 {
1186 grn_obj *string;
1187 const char *normalized_string;
1188 unsigned int normalized_string_length;
1189
1190 string = grn_tokenizer_query_get_normalized_string(ctx, query);
1191 grn_string_get_normalized(ctx,
1192 string,
1193 &normalized_string,
1194 &normalized_string_length,
1195 NULL);
1196 GRN_TEXT_INIT(&(tokenizer->buf), 0);
1197 if (grn_tokenizer_query_have_tokenized_delimiter(ctx, query)) {
1198 tokenizer->next = normalized_string;
1199 tokenizer->end = tokenizer->next + normalized_string_length;
1200 } else if (normalized_string_length == 0) {
1201 tokenizer->next = "";
1202 tokenizer->end = tokenizer->next;
1203 } else {
1204 if (tokenizer->options->chunked_tokenize &&
1205 ctx->encoding == GRN_ENC_UTF8) {
1206 if (!chunked_tokenize_utf8(ctx,
1207 tokenizer,
1208 normalized_string,
1209 normalized_string_length)) {
1210 GRN_PLUGIN_FREE(ctx, tokenizer);
1211 return NULL;
1212 }
1213 } else {
1214 const char *s;
1215 mecab_lattice_set_sentence2(tokenizer->lattice,
1216 normalized_string,
1217 normalized_string_length);
1218 if (!mecab_parse_lattice(tokenizer->mecab->mecab, tokenizer->lattice)) {
1219 GRN_PLUGIN_ERROR(ctx,
1220 GRN_TOKENIZER_ERROR,
1221 "[tokenizer][mecab] "
1222 "mecab_parse_lattice() failed len=%d err=%s",
1223 normalized_string_length,
1224 mecab_lattice_strerror(tokenizer->lattice));
1225 GRN_PLUGIN_FREE(ctx, tokenizer);
1226 return NULL;
1227 }
1228 s = mecab_lattice_tostr(tokenizer->lattice);
1229 if (!s) {
1230 GRN_PLUGIN_ERROR(ctx,
1231 GRN_TOKENIZER_ERROR,
1232 "[tokenizer][mecab] "
1233 "mecab_sparse_tostr() failed len=%d err=%s",
1234 normalized_string_length,
1235 mecab_lattice_strerror(tokenizer->lattice));
1236 GRN_PLUGIN_FREE(ctx, tokenizer);
1237 return NULL;
1238 }
1239 GRN_TEXT_PUTS(ctx, &(tokenizer->buf), s);
1240 }
1241 if (mecab_tokenizer_options_need_default_output(ctx,
1242 tokenizer->options)) {
1243 tokenizer->next = GRN_TEXT_VALUE(&(tokenizer->buf));
1244 tokenizer->end = tokenizer->next + GRN_TEXT_LEN(&(tokenizer->buf));
1245 } else {
1246 char *buf, *p;
1247 size_t bufsize;
1248
1249 buf = GRN_TEXT_VALUE(&(tokenizer->buf));
1250 bufsize = GRN_TEXT_LEN(&(tokenizer->buf));
1251 /* A certain version of mecab returns trailing lf or spaces. */
1252 for (p = buf + bufsize - 2; buf <= p && isspace(*(unsigned char *)p);
1253 p--) {
1254 *p = '\0';
1255 }
1256 tokenizer->next = buf;
1257 tokenizer->end = p + 1;
1258 }
1259 }
1260 }
1261
1262 GRN_UINT64_INIT(&(tokenizer->feature_locations), GRN_OBJ_VECTOR);
1263
1264 mecab_next_default_format_consume_needless_tokens(ctx, tokenizer);
1265
1266 return tokenizer;
1267 }
1268
1269 /*
1270 This function returns tokens one by one.
1271 */
1272 static void
1273 mecab_next(grn_ctx *ctx,
1274 grn_tokenizer_query *query,
1275 grn_token *token,
1276 void *user_data)
1277 {
1278 grn_mecab_tokenizer *tokenizer = user_data;
1279
1280 if (grn_tokenizer_query_have_tokenized_delimiter(ctx, tokenizer->query)) {
1281 grn_encoding encoding = tokenizer->query->encoding;
1282 tokenizer->next = grn_tokenizer_next_by_tokenized_delimiter(
1283 ctx,
1284 token,
1285 tokenizer->next,
1286 (unsigned int)(tokenizer->end - tokenizer->next),
1287 encoding);
1288 } else if (mecab_tokenizer_options_need_default_output(ctx,
1289 tokenizer->options)) {
1290 mecab_next_default_format(ctx, tokenizer, token);
1291 } else {
1292 mecab_next_newline_format(ctx, tokenizer, token);
1293 }
1294 }
1295
1296 /*
1297 This function finalizes a tokenization.
1298 */
1299 static void
1300 mecab_fin(grn_ctx *ctx, void *user_data)
1301 {
1302 grn_mecab_tokenizer *tokenizer = user_data;
1303 if (!tokenizer) {
1304 return;
1305 }
1306 GRN_OBJ_FIN(ctx, &(tokenizer->feature_locations));
1307 GRN_OBJ_FIN(ctx, &(tokenizer->buf));
1308 GRN_PLUGIN_FREE(ctx, tokenizer);
1309 }
1310
1311 static void
1312 check_mecab_dictionary_encoding(grn_ctx *ctx)
1313 {
1314 #ifdef HAVE_MECAB_DICTIONARY_INFO_T
1315 mecab_model_t *mecab_model;
1316 mecab_t *mecab;
1317 grn_encoding encoding;
1318 bool have_same_encoding_dictionary;
1319
1320 mecab_model = mecab_model_create(ctx, NULL);
1321 if (!mecab_model) {
1322 return;
1323 }
1324 mecab = mecab_model_new_tagger(mecab_model);
1325 if (!mecab) {
1326 return;
1327 }
1328
1329 encoding = GRN_CTX_GET_ENCODING(ctx);
1330 have_same_encoding_dictionary = (encoding == get_mecab_encoding(mecab));
1331 mecab_destroy(mecab);
1332
1333 if (!have_same_encoding_dictionary) {
1334 GRN_PLUGIN_ERROR(ctx,
1335 GRN_TOKENIZER_ERROR,
1336 "[tokenizer][mecab] "
1337 "MeCab has no dictionary that uses the context encoding"
1338 ": <%s>",
1339 grn_encoding_to_string(encoding));
1340 }
1341 #endif
1342 }
1343
1344 /*
1345 This function initializes a plugin. This function fails if there is no
1346 dictionary that uses the context encoding of groonga.
1347 */
1348 grn_rc
1349 GRN_PLUGIN_INIT(grn_ctx *ctx)
1350 {
1351 {
1352 char env[GRN_ENV_BUFFER_SIZE];
1353
1354 grn_getenv("GRN_MECAB_CHUNKED_TOKENIZE_ENABLED", env, GRN_ENV_BUFFER_SIZE);
1355 grn_mecab_chunked_tokenize_enabled = (env[0] && strcmp(env, "yes") == 0);
1356 }
1357
1358 {
1359 char env[GRN_ENV_BUFFER_SIZE];
1360
1361 grn_getenv("GRN_MECAB_CHUNK_SIZE_THRESHOLD", env, GRN_ENV_BUFFER_SIZE);
1362 if (env[0]) {
1363 int threshold = -1;
1364 const char *end;
1365 const char *rest;
1366
1367 end = env + strlen(env);
1368 threshold = grn_atoi(env, end, &rest);
1369 if (end > env && end == rest) {
1370 grn_mecab_chunk_size_threshold = threshold;
1371 }
1372 }
1373 }
1374
1375 grn_mecab_init(ctx, &mecab_default, "[default]");
1376 grn_mecab_init(ctx, &mecab_newline, "[newline]");
1377 if (ctx->rc != GRN_SUCCESS) {
1378 return ctx->rc;
1379 }
1380
1381 check_mecab_dictionary_encoding(ctx);
1382 if (ctx->rc != GRN_SUCCESS) {
1383 grn_mecab_fin(ctx, &mecab_default);
1384 grn_mecab_fin(ctx, &mecab_newline);
1385 }
1386
1387 return ctx->rc;
1388 }
1389
1390 /*
1391 This function registers a plugin to a database.
1392 */
1393 grn_rc
1394 GRN_PLUGIN_REGISTER(grn_ctx *ctx)
1395 {
1396 grn_rc rc = GRN_SUCCESS;
1397 grn_obj *tokenizer;
1398
1399 tokenizer = grn_tokenizer_create(ctx, "TokenMecab", -1);
1400 if (tokenizer) {
1401 grn_tokenizer_set_init_func(ctx, tokenizer, mecab_init);
1402 grn_tokenizer_set_next_func(ctx, tokenizer, mecab_next);
1403 grn_tokenizer_set_fin_func(ctx, tokenizer, mecab_fin);
1404
1405 /* Just for backward compatibility. TokenMecab was built-in not plugin. */
1406 if (grn_obj_id(ctx, tokenizer) != GRN_DB_MECAB) {
1407 rc = GRN_FILE_CORRUPT;
1408 }
1409 }
1410
1411 return rc;
1412 }
1413
1414 /*
1415 This function finalizes a plugin.
1416 */
1417 grn_rc
1418 GRN_PLUGIN_FIN(grn_ctx *ctx)
1419 {
1420 grn_unset_variable(grn_mecab_lattice_variable_name, -1);
1421
1422 grn_mecab_fin(ctx, &mecab_default);
1423 grn_mecab_fin(ctx, &mecab_newline);
1424
1425 return GRN_SUCCESS;
1426 }