tesseract  4.00.00dev
dict.cpp
Go to the documentation of this file.
1 // File: dict.cpp
3 // Description: dict class.
4 // Author: Samuel Charron
5 //
6 // (C) Copyright 2006, Google Inc.
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
18 
19 #include <stdio.h>
20 
21 #include "dict.h"
22 #include "unicodes.h"
23 
24 #ifdef _MSC_VER
25 #pragma warning(disable:4244) // Conversion warnings
26 #endif
27 #include "tprintf.h"
28 
29 namespace tesseract {
30 
31 class Image;
32 
34  : letter_is_okay_(&tesseract::Dict::def_letter_is_okay),
35  probability_in_context_(&tesseract::Dict::def_probability_in_context),
36  params_model_classify_(NULL),
37  ccutil_(ccutil),
38  STRING_MEMBER(user_words_file, "", "A filename of user-provided words.",
39  getCCUtil()->params()),
40  STRING_INIT_MEMBER(user_words_suffix, "",
41  "A suffix of user-provided words located in tessdata.",
42  getCCUtil()->params()),
43  STRING_MEMBER(user_patterns_file, "",
44  "A filename of user-provided patterns.",
45  getCCUtil()->params()),
46  STRING_INIT_MEMBER(user_patterns_suffix, "",
47  "A suffix of user-provided patterns located in "
48  "tessdata.",
49  getCCUtil()->params()),
50  BOOL_INIT_MEMBER(load_system_dawg, true, "Load system word dawg.",
51  getCCUtil()->params()),
52  BOOL_INIT_MEMBER(load_freq_dawg, true, "Load frequent word dawg.",
53  getCCUtil()->params()),
54  BOOL_INIT_MEMBER(load_unambig_dawg, true, "Load unambiguous word dawg.",
55  getCCUtil()->params()),
56  BOOL_INIT_MEMBER(load_punc_dawg, true,
57  "Load dawg with punctuation"
58  " patterns.",
59  getCCUtil()->params()),
60  BOOL_INIT_MEMBER(load_number_dawg, true,
61  "Load dawg with number"
62  " patterns.",
63  getCCUtil()->params()),
64  BOOL_INIT_MEMBER(load_bigram_dawg, true,
65  "Load dawg with special word "
66  "bigrams.",
67  getCCUtil()->params()),
68  double_MEMBER(xheight_penalty_subscripts, 0.125,
69  "Score penalty (0.1 = 10%) added if there are subscripts "
70  "or superscripts in a word, but it is otherwise OK.",
71  getCCUtil()->params()),
72  double_MEMBER(xheight_penalty_inconsistent, 0.25,
73  "Score penalty (0.1 = 10%) added if an xheight is "
74  "inconsistent.",
75  getCCUtil()->params()),
76  double_MEMBER(segment_penalty_dict_frequent_word, 1.0,
77  "Score multiplier for word matches which have good case and"
78  " are frequent in the given language (lower is better).",
79  getCCUtil()->params()),
80  double_MEMBER(segment_penalty_dict_case_ok, 1.1,
81  "Score multiplier for word matches that have good case "
82  "(lower is better).",
83  getCCUtil()->params()),
84  double_MEMBER(segment_penalty_dict_case_bad, 1.3125,
85  "Default score multiplier for word matches, which may have "
86  "case issues (lower is better).",
87  getCCUtil()->params()),
88  double_MEMBER(segment_penalty_ngram_best_choice, 1.24,
89  "Multipler to for the best choice from the ngram model.",
90  getCCUtil()->params()),
91  double_MEMBER(segment_penalty_dict_nonword, 1.25,
92  "Score multiplier for glyph fragment segmentations which "
93  "do not match a dictionary word (lower is better).",
94  getCCUtil()->params()),
95  double_MEMBER(segment_penalty_garbage, 1.50,
96  "Score multiplier for poorly cased strings that are not in"
97  " the dictionary and generally look like garbage (lower is"
98  " better).",
99  getCCUtil()->params()),
100  STRING_MEMBER(output_ambig_words_file, "",
101  "Output file for ambiguities found in the dictionary",
102  getCCUtil()->params()),
103  INT_MEMBER(dawg_debug_level, 0,
104  "Set to 1 for general debug info"
105  ", to 2 for more details, to 3 to see all the debug messages",
106  getCCUtil()->params()),
107  INT_MEMBER(hyphen_debug_level, 0, "Debug level for hyphenated words.",
108  getCCUtil()->params()),
109  INT_MEMBER(max_viterbi_list_size, 10, "Maximum size of viterbi list.",
110  getCCUtil()->params()),
111  BOOL_MEMBER(use_only_first_uft8_step, false,
112  "Use only the first UTF8 step of the given string"
113  " when computing log probabilities.",
114  getCCUtil()->params()),
115  double_MEMBER(certainty_scale, 20.0, "Certainty scaling factor",
116  getCCUtil()->params()),
117  double_MEMBER(stopper_nondict_certainty_base, -2.50,
118  "Certainty threshold for non-dict words",
119  getCCUtil()->params()),
120  double_MEMBER(stopper_phase2_certainty_rejection_offset, 1.0,
121  "Reject certainty offset", getCCUtil()->params()),
122  INT_MEMBER(stopper_smallword_size, 2,
123  "Size of dict word to be treated as non-dict word",
124  getCCUtil()->params()),
125  double_MEMBER(stopper_certainty_per_char, -0.50,
126  "Certainty to add"
127  " for each dict char above small word size.",
128  getCCUtil()->params()),
129  double_MEMBER(stopper_allowable_character_badness, 3.0,
130  "Max certaintly variation allowed in a word (in sigma)",
131  getCCUtil()->params()),
132  INT_MEMBER(stopper_debug_level, 0, "Stopper debug level",
133  getCCUtil()->params()),
134  BOOL_MEMBER(stopper_no_acceptable_choices, false,
135  "Make AcceptableChoice() always return false. Useful"
136  " when there is a need to explore all segmentations",
137  getCCUtil()->params()),
138  BOOL_MEMBER(save_raw_choices, false,
139  "Deprecated- backward compatibility only",
140  getCCUtil()->params()),
141  INT_MEMBER(tessedit_truncate_wordchoice_log, 10,
142  "Max words to keep in list", getCCUtil()->params()),
143  STRING_MEMBER(word_to_debug, "",
144  "Word for which stopper debug"
145  " information should be printed to stdout",
146  getCCUtil()->params()),
147  STRING_MEMBER(word_to_debug_lengths, "",
148  "Lengths of unichars in word_to_debug",
149  getCCUtil()->params()),
150  INT_MEMBER(fragments_debug, 0, "Debug character fragments",
151  getCCUtil()->params()),
152  BOOL_MEMBER(segment_nonalphabetic_script, false,
153  "Don't use any alphabetic-specific tricks."
154  " Set to true in the traineddata config file for"
155  " scripts that are cursive or inherently fixed-pitch",
156  getCCUtil()->params()),
157  BOOL_MEMBER(save_doc_words, 0, "Save Document Words",
158  getCCUtil()->params()),
159  double_MEMBER(doc_dict_pending_threshold, 0.0,
160  "Worst certainty for using pending dictionary",
161  getCCUtil()->params()),
162  double_MEMBER(doc_dict_certainty_threshold, -2.25,
163  "Worst certainty for words that can be inserted into the"
164  " document dictionary",
165  getCCUtil()->params()),
166  INT_MEMBER(max_permuter_attempts, 10000,
167  "Maximum number of different"
168  " character choices to consider during permutation."
169  " This limit is especially useful when user patterns"
170  " are specified, since overly generic patterns can result in"
171  " dawg search exploring an overly large number of options.",
172  getCCUtil()->params()) {
173  dang_ambigs_table_ = NULL;
174  replace_ambigs_table_ = NULL;
175  reject_offset_ = 0.0;
176  go_deeper_fxn_ = NULL;
177  hyphen_word_ = NULL;
178  last_word_on_line_ = false;
179  hyphen_unichar_id_ = INVALID_UNICHAR_ID;
180  document_words_ = NULL;
181  dawg_cache_ = NULL;
182  dawg_cache_is_ours_ = false;
183  pending_words_ = NULL;
184  bigram_dawg_ = NULL;
185  freq_dawg_ = NULL;
186  punc_dawg_ = NULL;
187  unambig_dawg_ = NULL;
188  wordseg_rating_adjust_factor_ = -1.0f;
189  output_ambig_words_file_ = NULL;
190 }
191 
193  End();
194  delete hyphen_word_;
195  if (output_ambig_words_file_ != NULL) fclose(output_ambig_words_file_);
196 }
197 
199  // This global cache (a singleton) will outlive every Tesseract instance
200  // (even those that someone else might declare as global statics).
201  static DawgCache cache;
202  return &cache;
203 }
204 
205 // Sets up ready for a Load or LoadLSTM.
206 void Dict::SetupForLoad(DawgCache *dawg_cache) {
207  if (dawgs_.length() != 0) this->End();
208 
209  apostrophe_unichar_id_ = getUnicharset().unichar_to_id(kApostropheSymbol);
210  question_unichar_id_ = getUnicharset().unichar_to_id(kQuestionSymbol);
211  slash_unichar_id_ = getUnicharset().unichar_to_id(kSlashSymbol);
212  hyphen_unichar_id_ = getUnicharset().unichar_to_id(kHyphenSymbol);
213 
214  if (dawg_cache != NULL) {
215  dawg_cache_ = dawg_cache;
216  dawg_cache_is_ours_ = false;
217  } else {
218  dawg_cache_ = new DawgCache();
219  dawg_cache_is_ours_ = true;
220  }
221 }
222 
223 // Loads the dawgs needed by Tesseract. Call FinishLoad() after.
224 void Dict::Load(const STRING &lang, TessdataManager *data_file) {
225  // Load dawgs_.
226  if (load_punc_dawg) {
227  punc_dawg_ = dawg_cache_->GetSquishedDawg(lang, TESSDATA_PUNC_DAWG,
228  dawg_debug_level, data_file);
229  if (punc_dawg_) dawgs_ += punc_dawg_;
230  }
231  if (load_system_dawg) {
232  Dawg *system_dawg = dawg_cache_->GetSquishedDawg(
233  lang, TESSDATA_SYSTEM_DAWG, dawg_debug_level, data_file);
234  if (system_dawg) dawgs_ += system_dawg;
235  }
236  if (load_number_dawg) {
237  Dawg *number_dawg = dawg_cache_->GetSquishedDawg(
238  lang, TESSDATA_NUMBER_DAWG, dawg_debug_level, data_file);
239  if (number_dawg) dawgs_ += number_dawg;
240  }
241  if (load_bigram_dawg) {
242  bigram_dawg_ = dawg_cache_->GetSquishedDawg(lang, TESSDATA_BIGRAM_DAWG,
243  dawg_debug_level, data_file);
244  // The bigram_dawg_ is NOT used like the other dawgs! DO NOT add to the
245  // dawgs_!!
246  }
247  if (load_freq_dawg) {
248  freq_dawg_ = dawg_cache_->GetSquishedDawg(lang, TESSDATA_FREQ_DAWG,
249  dawg_debug_level, data_file);
250  if (freq_dawg_) dawgs_ += freq_dawg_;
251  }
252  if (load_unambig_dawg) {
253  unambig_dawg_ = dawg_cache_->GetSquishedDawg(lang, TESSDATA_UNAMBIG_DAWG,
254  dawg_debug_level, data_file);
255  if (unambig_dawg_) dawgs_ += unambig_dawg_;
256  }
257 
258  STRING name;
259  if (((STRING &)user_words_suffix).length() > 0 ||
260  ((STRING &)user_words_file).length() > 0) {
261  Trie *trie_ptr = new Trie(DAWG_TYPE_WORD, lang, USER_DAWG_PERM,
262  getUnicharset().size(), dawg_debug_level);
263  if (((STRING &)user_words_file).length() > 0) {
264  name = user_words_file;
265  } else {
267  name += user_words_suffix;
268  }
269  if (!trie_ptr->read_and_add_word_list(name.string(), getUnicharset(),
271  tprintf("Error: failed to load %s\n", name.string());
272  delete trie_ptr;
273  } else {
274  dawgs_ += trie_ptr;
275  }
276  }
277 
278  if (((STRING &)user_patterns_suffix).length() > 0 ||
279  ((STRING &)user_patterns_file).length() > 0) {
280  Trie *trie_ptr = new Trie(DAWG_TYPE_PATTERN, lang, USER_PATTERN_PERM,
281  getUnicharset().size(), dawg_debug_level);
282  trie_ptr->initialize_patterns(&(getUnicharset()));
283  if (((STRING &)user_patterns_file).length() > 0) {
284  name = user_patterns_file;
285  } else {
287  name += user_patterns_suffix;
288  }
289  if (!trie_ptr->read_pattern_list(name.string(), getUnicharset())) {
290  tprintf("Error: failed to load %s\n", name.string());
291  delete trie_ptr;
292  } else {
293  dawgs_ += trie_ptr;
294  }
295  }
296 
297  document_words_ = new Trie(DAWG_TYPE_WORD, lang, DOC_DAWG_PERM,
298  getUnicharset().size(), dawg_debug_level);
299  dawgs_ += document_words_;
300 
301  // This dawg is temporary and should not be searched by letter_is_ok.
302  pending_words_ = new Trie(DAWG_TYPE_WORD, lang, NO_PERM,
303  getUnicharset().size(), dawg_debug_level);
304 }
305 
306 // Loads the dawgs needed by the LSTM model. Call FinishLoad() after.
307 void Dict::LoadLSTM(const STRING &lang, TessdataManager *data_file) {
308  // Load dawgs_.
309  if (load_punc_dawg) {
310  punc_dawg_ = dawg_cache_->GetSquishedDawg(lang, TESSDATA_LSTM_PUNC_DAWG,
311  dawg_debug_level, data_file);
312  if (punc_dawg_) dawgs_ += punc_dawg_;
313  }
314  if (load_system_dawg) {
315  Dawg *system_dawg = dawg_cache_->GetSquishedDawg(
316  lang, TESSDATA_LSTM_SYSTEM_DAWG, dawg_debug_level, data_file);
317  if (system_dawg) dawgs_ += system_dawg;
318  }
319  if (load_number_dawg) {
320  Dawg *number_dawg = dawg_cache_->GetSquishedDawg(
321  lang, TESSDATA_LSTM_NUMBER_DAWG, dawg_debug_level, data_file);
322  if (number_dawg) dawgs_ += number_dawg;
323  }
324 }
325 
326 // Completes the loading process after Load() and/or LoadLSTM().
327 // Returns false if no dictionaries were loaded.
329  if (dawgs_.empty()) return false;
330  // Construct a list of corresponding successors for each dawg. Each entry, i,
331  // in the successors_ vector is a vector of integers that represent the
332  // indices into the dawgs_ vector of the successors for dawg i.
333  successors_.reserve(dawgs_.length());
334  for (int i = 0; i < dawgs_.length(); ++i) {
335  const Dawg *dawg = dawgs_[i];
336  SuccessorList *lst = new SuccessorList();
337  for (int j = 0; j < dawgs_.length(); ++j) {
338  const Dawg *other = dawgs_[j];
339  if (dawg != NULL && other != NULL &&
340  (dawg->lang() == other->lang()) &&
341  kDawgSuccessors[dawg->type()][other->type()]) *lst += j;
342  }
343  successors_ += lst;
344  }
345  return true;
346 }
347 
348 void Dict::End() {
349  if (dawgs_.length() == 0)
350  return; // Not safe to call twice.
351  for (int i = 0; i < dawgs_.size(); i++) {
352  if (!dawg_cache_->FreeDawg(dawgs_[i])) {
353  delete dawgs_[i];
354  }
355  }
356  dawg_cache_->FreeDawg(bigram_dawg_);
357  if (dawg_cache_is_ours_) {
358  delete dawg_cache_;
359  dawg_cache_ = NULL;
360  }
361  successors_.delete_data_pointers();
362  dawgs_.clear();
363  successors_.clear();
364  document_words_ = NULL;
365  delete pending_words_;
366  pending_words_ = NULL;
367 }
368 
369 // Returns true if in light of the current state unichar_id is allowed
370 // according to at least one of the dawgs in the dawgs_ vector.
371 // See more extensive comments in dict.h where this function is declared.
372 int Dict::def_letter_is_okay(void* void_dawg_args,
373  UNICHAR_ID unichar_id,
374  bool word_end) const {
375  DawgArgs *dawg_args = static_cast<DawgArgs *>(void_dawg_args);
376 
377  if (dawg_debug_level >= 3) {
378  tprintf("def_letter_is_okay: current unichar=%s word_end=%d"
379  " num active dawgs=%d\n",
380  getUnicharset().debug_str(unichar_id).string(), word_end,
381  dawg_args->active_dawgs->length());
382  }
383 
384  // Do not accept words that contain kPatternUnicharID.
385  // (otherwise pattern dawgs would not function correctly).
386  // Do not accept words containing INVALID_UNICHAR_IDs.
387  if (unichar_id == Dawg::kPatternUnicharID ||
388  unichar_id == INVALID_UNICHAR_ID) {
389  dawg_args->permuter = NO_PERM;
390  return NO_PERM;
391  }
392 
393  // Initialization.
394  PermuterType curr_perm = NO_PERM;
395  dawg_args->updated_dawgs->clear();
396  dawg_args->valid_end = false;
397 
398  // Go over the active_dawgs vector and insert DawgPosition records
399  // with the updated ref (an edge with the corresponding unichar id) into
400  // dawg_args->updated_pos.
401  for (int a = 0; a < dawg_args->active_dawgs->length(); ++a) {
402  const DawgPosition &pos = (*dawg_args->active_dawgs)[a];
403  const Dawg *punc_dawg = pos.punc_index >= 0 ? dawgs_[pos.punc_index] : NULL;
404  const Dawg *dawg = pos.dawg_index >= 0 ? dawgs_[pos.dawg_index] : NULL;
405 
406  if (!dawg && !punc_dawg) {
407  // shouldn't happen.
408  tprintf("Received DawgPosition with no dawg or punc_dawg. wth?\n");
409  continue;
410  }
411  if (!dawg) {
412  // We're in the punctuation dawg. A core dawg has not been chosen.
413  NODE_REF punc_node = GetStartingNode(punc_dawg, pos.punc_ref);
414  EDGE_REF punc_transition_edge = punc_dawg->edge_char_of(
415  punc_node, Dawg::kPatternUnicharID, word_end);
416  if (punc_transition_edge != NO_EDGE) {
417  // Find all successors, and see which can transition.
418  const SuccessorList &slist = *(successors_[pos.punc_index]);
419  for (int s = 0; s < slist.length(); ++s) {
420  int sdawg_index = slist[s];
421  const Dawg *sdawg = dawgs_[sdawg_index];
422  UNICHAR_ID ch = char_for_dawg(unichar_id, sdawg);
423  EDGE_REF dawg_edge = sdawg->edge_char_of(0, ch, word_end);
424  if (dawg_edge != NO_EDGE) {
425  if (dawg_debug_level >=3) {
426  tprintf("Letter found in dawg %d\n", sdawg_index);
427  }
428  dawg_args->updated_dawgs->add_unique(
429  DawgPosition(sdawg_index, dawg_edge,
430  pos.punc_index, punc_transition_edge, false),
431  dawg_debug_level > 0,
432  "Append transition from punc dawg to current dawgs: ");
433  if (sdawg->permuter() > curr_perm) curr_perm = sdawg->permuter();
434  if (sdawg->end_of_word(dawg_edge) &&
435  punc_dawg->end_of_word(punc_transition_edge))
436  dawg_args->valid_end = true;
437  }
438  }
439  }
440  EDGE_REF punc_edge = punc_dawg->edge_char_of(punc_node, unichar_id,
441  word_end);
442  if (punc_edge != NO_EDGE) {
443  if (dawg_debug_level >=3) {
444  tprintf("Letter found in punctuation dawg\n");
445  }
446  dawg_args->updated_dawgs->add_unique(
447  DawgPosition(-1, NO_EDGE, pos.punc_index, punc_edge, false),
448  dawg_debug_level > 0,
449  "Extend punctuation dawg: ");
450  if (PUNC_PERM > curr_perm) curr_perm = PUNC_PERM;
451  if (punc_dawg->end_of_word(punc_edge)) dawg_args->valid_end = true;
452  }
453  continue;
454  }
455 
456  if (punc_dawg && dawg->end_of_word(pos.dawg_ref)) {
457  // We can end the main word here.
458  // If we can continue on the punc ref, add that possibility.
459  NODE_REF punc_node = GetStartingNode(punc_dawg, pos.punc_ref);
460  EDGE_REF punc_edge = punc_node == NO_EDGE ? NO_EDGE
461  : punc_dawg->edge_char_of(punc_node, unichar_id, word_end);
462  if (punc_edge != NO_EDGE) {
463  dawg_args->updated_dawgs->add_unique(
465  pos.punc_index, punc_edge, true),
466  dawg_debug_level > 0,
467  "Return to punctuation dawg: ");
468  if (dawg->permuter() > curr_perm) curr_perm = dawg->permuter();
469  if (punc_dawg->end_of_word(punc_edge)) dawg_args->valid_end = true;
470  }
471  }
472 
473  if (pos.back_to_punc) continue;
474 
475  // If we are dealing with the pattern dawg, look up all the
476  // possible edges, not only for the exact unichar_id, but also
477  // for all its character classes (alpha, digit, etc).
478  if (dawg->type() == DAWG_TYPE_PATTERN) {
479  ProcessPatternEdges(dawg, pos, unichar_id, word_end, dawg_args,
480  &curr_perm);
481  // There can't be any successors to dawg that is of type
482  // DAWG_TYPE_PATTERN, so we are done examining this DawgPosition.
483  continue;
484  }
485 
486  // Find the edge out of the node for the unichar_id.
487  NODE_REF node = GetStartingNode(dawg, pos.dawg_ref);
488  EDGE_REF edge = (node == NO_EDGE) ? NO_EDGE
489  : dawg->edge_char_of(node, char_for_dawg(unichar_id, dawg), word_end);
490 
491  if (dawg_debug_level >= 3) {
492  tprintf("Active dawg: [%d, " REFFORMAT "] edge=" REFFORMAT "\n",
493  pos.dawg_index, node, edge);
494  }
495 
496  if (edge != NO_EDGE) { // the unichar was found in the current dawg
497  if (dawg_debug_level >=3) {
498  tprintf("Letter found in dawg %d\n", pos.dawg_index);
499  }
500  if (word_end && punc_dawg && !punc_dawg->end_of_word(pos.punc_ref)) {
501  if (dawg_debug_level >= 3) {
502  tprintf("Punctuation constraint not satisfied at end of word.\n");
503  }
504  continue;
505  }
506  if (dawg->permuter() > curr_perm) curr_perm = dawg->permuter();
507  if (dawg->end_of_word(edge) &&
508  (punc_dawg == NULL || punc_dawg->end_of_word(pos.punc_ref)))
509  dawg_args->valid_end = true;
510  dawg_args->updated_dawgs->add_unique(
511  DawgPosition(pos.dawg_index, edge, pos.punc_index, pos.punc_ref,
512  false),
513  dawg_debug_level > 0,
514  "Append current dawg to updated active dawgs: ");
515  }
516  } // end for
517  // Update dawg_args->permuter if it used to be NO_PERM or became NO_PERM
518  // or if we found the current letter in a non-punctuation dawg. This
519  // allows preserving information on which dawg the "core" word came from.
520  // Keep the old value of dawg_args->permuter if it is COMPOUND_PERM.
521  if (dawg_args->permuter == NO_PERM || curr_perm == NO_PERM ||
522  (curr_perm != PUNC_PERM && dawg_args->permuter != COMPOUND_PERM)) {
523  dawg_args->permuter = curr_perm;
524  }
525  if (dawg_debug_level >= 2) {
526  tprintf("Returning %d for permuter code for this character.\n",
527  dawg_args->permuter);
528  }
529  return dawg_args->permuter;
530 }
531 
532 void Dict::ProcessPatternEdges(const Dawg *dawg, const DawgPosition &pos,
533  UNICHAR_ID unichar_id, bool word_end,
534  DawgArgs *dawg_args,
535  PermuterType *curr_perm) const {
536  NODE_REF node = GetStartingNode(dawg, pos.dawg_ref);
537  // Try to find the edge corresponding to the exact unichar_id and to all the
538  // edges corresponding to the character class of unichar_id.
539  GenericVector<UNICHAR_ID> unichar_id_patterns;
540  unichar_id_patterns.push_back(unichar_id);
541  dawg->unichar_id_to_patterns(unichar_id, getUnicharset(),
542  &unichar_id_patterns);
543  for (int i = 0; i < unichar_id_patterns.size(); ++i) {
544  // On the first iteration check all the outgoing edges.
545  // On the second iteration check all self-loops.
546  for (int k = 0; k < 2; ++k) {
547  EDGE_REF edge = (k == 0)
548  ? dawg->edge_char_of(node, unichar_id_patterns[i], word_end)
549  : dawg->pattern_loop_edge(pos.dawg_ref, unichar_id_patterns[i], word_end);
550  if (edge == NO_EDGE) continue;
551  if (dawg_debug_level >= 3) {
552  tprintf("Pattern dawg: [%d, " REFFORMAT "] edge=" REFFORMAT "\n",
553  pos.dawg_index, node, edge);
554  tprintf("Letter found in pattern dawg %d\n", pos.dawg_index);
555  }
556  if (dawg->permuter() > *curr_perm) *curr_perm = dawg->permuter();
557  if (dawg->end_of_word(edge)) dawg_args->valid_end = true;
558  dawg_args->updated_dawgs->add_unique(
559  DawgPosition(pos.dawg_index, edge, pos.punc_index, pos.punc_ref,
560  pos.back_to_punc),
561  dawg_debug_level > 0,
562  "Append current dawg to updated active dawgs: ");
563  }
564  }
565 }
566 
567 // Fill the given active_dawgs vector with dawgs that could contain the
568 // beginning of the word. If hyphenated() returns true, copy the entries
569 // from hyphen_active_dawgs_ instead.
571  bool ambigs_mode) const {
572  int i;
573  if (hyphenated()) {
574  *active_dawgs = hyphen_active_dawgs_;
575  if (dawg_debug_level >= 3) {
576  for (i = 0; i < hyphen_active_dawgs_.size(); ++i) {
577  tprintf("Adding hyphen beginning dawg [%d, " REFFORMAT "]\n",
578  hyphen_active_dawgs_[i].dawg_index,
579  hyphen_active_dawgs_[i].dawg_ref);
580  }
581  }
582  } else {
583  default_dawgs(active_dawgs, ambigs_mode);
584  }
585 }
586 
588  bool suppress_patterns) const {
589  bool punc_dawg_available =
590  (punc_dawg_ != NULL) &&
591  punc_dawg_->edge_char_of(0, Dawg::kPatternUnicharID, true) != NO_EDGE;
592 
593  for (int i = 0; i < dawgs_.length(); i++) {
594  if (dawgs_[i] != NULL &&
595  !(suppress_patterns && (dawgs_[i])->type() == DAWG_TYPE_PATTERN)) {
596  int dawg_ty = dawgs_[i]->type();
597  bool subsumed_by_punc = kDawgSuccessors[DAWG_TYPE_PUNCTUATION][dawg_ty];
598  if (dawg_ty == DAWG_TYPE_PUNCTUATION) {
599  *dawg_pos_vec += DawgPosition(-1, NO_EDGE, i, NO_EDGE, false);
600  if (dawg_debug_level >= 3) {
601  tprintf("Adding beginning punc dawg [%d, " REFFORMAT "]\n", i,
602  NO_EDGE);
603  }
604  } else if (!punc_dawg_available || !subsumed_by_punc) {
605  *dawg_pos_vec += DawgPosition(i, NO_EDGE, -1, NO_EDGE, false);
606  if (dawg_debug_level >= 3) {
607  tprintf("Adding beginning dawg [%d, " REFFORMAT "]\n", i, NO_EDGE);
608  }
609  }
610  }
611  }
612 }
613 
614 void Dict::add_document_word(const WERD_CHOICE &best_choice) {
615  // Do not add hyphenated word parts to the document dawg.
616  // hyphen_word_ will be non-NULL after the set_hyphen_word() is
617  // called when the first part of the hyphenated word is
618  // discovered and while the second part of the word is recognized.
619  // hyphen_word_ is cleared in cc_recg() before the next word on
620  // the line is recognized.
621  if (hyphen_word_) return;
622 
623  char filename[CHARS_PER_LINE];
624  FILE *doc_word_file;
625  int stringlen = best_choice.length();
626 
627  if (valid_word(best_choice) || stringlen < 2)
628  return;
629 
630  // Discard words that contain >= kDocDictMaxRepChars repeating unichars.
631  if (best_choice.length() >= kDocDictMaxRepChars) {
632  int num_rep_chars = 1;
633  UNICHAR_ID uch_id = best_choice.unichar_id(0);
634  for (int i = 1; i < best_choice.length(); ++i) {
635  if (best_choice.unichar_id(i) != uch_id) {
636  num_rep_chars = 1;
637  uch_id = best_choice.unichar_id(i);
638  } else {
639  ++num_rep_chars;
640  if (num_rep_chars == kDocDictMaxRepChars) return;
641  }
642  }
643  }
644 
645  if (best_choice.certainty() < doc_dict_certainty_threshold ||
646  stringlen == 2) {
647  if (best_choice.certainty() < doc_dict_pending_threshold)
648  return;
649 
650  if (!pending_words_->word_in_dawg(best_choice)) {
651  if (stringlen > 2 ||
652  (stringlen == 2 &&
653  getUnicharset().get_isupper(best_choice.unichar_id(0)) &&
654  getUnicharset().get_isupper(best_choice.unichar_id(1)))) {
655  pending_words_->add_word_to_dawg(best_choice);
656  }
657  return;
658  }
659  }
660 
661  if (save_doc_words) {
662  strcpy(filename, getCCUtil()->imagefile.string());
663  strcat(filename, ".doc");
664  doc_word_file = open_file (filename, "a");
665  fprintf(doc_word_file, "%s\n",
666  best_choice.debug_string().string());
667  fclose(doc_word_file);
668  }
669  document_words_->add_word_to_dawg(best_choice);
670 }
671 
673  bool nonword,
674  XHeightConsistencyEnum xheight_consistency,
675  float additional_adjust,
676  bool modify_rating,
677  bool debug) {
678  bool is_han = (getUnicharset().han_sid() != getUnicharset().null_sid() &&
679  word->GetTopScriptID() == getUnicharset().han_sid());
680  bool case_is_ok = (is_han || case_ok(*word, getUnicharset()));
681  bool punc_is_ok = (is_han || !nonword || valid_punctuation(*word));
682 
683  float adjust_factor = additional_adjust;
684  float new_rating = word->rating();
685  new_rating += kRatingPad;
686  const char *xheight_triggered = "";
687  if (word->length() > 1) {
688  // Calculate x-height and y-offset consistency penalties.
689  switch (xheight_consistency) {
690  case XH_INCONSISTENT:
691  adjust_factor += xheight_penalty_inconsistent;
692  xheight_triggered = ", xhtBAD";
693  break;
694  case XH_SUBNORMAL:
695  adjust_factor += xheight_penalty_subscripts;
696  xheight_triggered = ", xhtSUB";
697  break;
698  case XH_GOOD:
699  // leave the factor alone - all good!
700  break;
701  }
702  // TODO(eger): if nonword is true, but there is a "core" thats' a dict
703  // word, negate nonword status.
704  } else {
705  if (debug) {
706  tprintf("Consistency could not be calculated.\n");
707  }
708  }
709  if (debug) {
710  tprintf("%sWord: %s %4.2f%s", nonword ? "Non-" : "",
711  word->unichar_string().string(), word->rating(),
712  xheight_triggered);
713  }
714 
715  if (nonword) { // non-dictionary word
716  if (case_is_ok && punc_is_ok) {
717  adjust_factor += segment_penalty_dict_nonword;
718  new_rating *= adjust_factor;
719  if (debug) tprintf(", W");
720  } else {
721  adjust_factor += segment_penalty_garbage;
722  new_rating *= adjust_factor;
723  if (debug) {
724  if (!case_is_ok) tprintf(", C");
725  if (!punc_is_ok) tprintf(", P");
726  }
727  }
728  } else { // dictionary word
729  if (case_is_ok) {
730  if (!is_han && freq_dawg_ != NULL && freq_dawg_->word_in_dawg(*word)) {
732  adjust_factor += segment_penalty_dict_frequent_word;
733  new_rating *= adjust_factor;
734  if (debug) tprintf(", F");
735  } else {
736  adjust_factor += segment_penalty_dict_case_ok;
737  new_rating *= adjust_factor;
738  if (debug) tprintf(", ");
739  }
740  } else {
741  adjust_factor += segment_penalty_dict_case_bad;
742  new_rating *= adjust_factor;
743  if (debug) tprintf(", C");
744  }
745  }
746  new_rating -= kRatingPad;
747  if (modify_rating) word->set_rating(new_rating);
748  if (debug) tprintf(" %4.2f --> %4.2f\n", adjust_factor, new_rating);
749  word->set_adjust_factor(adjust_factor);
750 }
751 
752 int Dict::valid_word(const WERD_CHOICE &word, bool numbers_ok) const {
753  const WERD_CHOICE *word_ptr = &word;
754  WERD_CHOICE temp_word(word.unicharset());
755  if (hyphenated() && hyphen_word_->unicharset() == word.unicharset()) {
756  copy_hyphen_info(&temp_word);
757  temp_word += word;
758  word_ptr = &temp_word;
759  }
760  if (word_ptr->length() == 0) return NO_PERM;
761  // Allocate vectors for holding current and updated
762  // active_dawgs and initialize them.
763  DawgPositionVector *active_dawgs = new DawgPositionVector[2];
764  init_active_dawgs(&(active_dawgs[0]), false);
765  DawgArgs dawg_args(&(active_dawgs[0]), &(active_dawgs[1]), NO_PERM);
766  int last_index = word_ptr->length() - 1;
767  // Call leter_is_okay for each letter in the word.
768  for (int i = hyphen_base_size(); i <= last_index; ++i) {
769  if (!((this->*letter_is_okay_)(&dawg_args, word_ptr->unichar_id(i),
770  i == last_index))) break;
771  // Swap active_dawgs, constraints with the corresponding updated vector.
772  if (dawg_args.updated_dawgs == &(active_dawgs[1])) {
773  dawg_args.updated_dawgs = &(active_dawgs[0]);
774  ++(dawg_args.active_dawgs);
775  } else {
776  ++(dawg_args.updated_dawgs);
777  dawg_args.active_dawgs = &(active_dawgs[0]);
778  }
779  }
780  delete[] active_dawgs;
781  return valid_word_permuter(dawg_args.permuter, numbers_ok) ?
782  dawg_args.permuter : NO_PERM;
783 }
784 
785 bool Dict::valid_bigram(const WERD_CHOICE &word1,
786  const WERD_CHOICE &word2) const {
787  if (bigram_dawg_ == NULL) return false;
788 
789  // Extract the core word from the middle of each word with any digits
790  // replaced with question marks.
791  int w1start, w1end, w2start, w2end;
792  word1.punct_stripped(&w1start, &w1end);
793  word2.punct_stripped(&w2start, &w2end);
794 
795  // We don't want to penalize a single guillemet, hyphen, etc.
796  // But our bigram list doesn't have any information about punctuation.
797  if (w1start >= w1end) return word1.length() < 3;
798  if (w2start >= w2end) return word2.length() < 3;
799 
800  const UNICHARSET& uchset = getUnicharset();
801  GenericVector<UNICHAR_ID> bigram_string;
802  bigram_string.reserve(w1end + w2end + 1);
803  for (int i = w1start; i < w1end; i++) {
804  const GenericVector<UNICHAR_ID>& normed_ids =
805  getUnicharset().normed_ids(word1.unichar_id(i));
806  if (normed_ids.size() == 1 && uchset.get_isdigit(normed_ids[0]))
807  bigram_string.push_back(question_unichar_id_);
808  else
809  bigram_string += normed_ids;
810  }
811  bigram_string.push_back(UNICHAR_SPACE);
812  for (int i = w2start; i < w2end; i++) {
813  const GenericVector<UNICHAR_ID>& normed_ids =
814  getUnicharset().normed_ids(word2.unichar_id(i));
815  if (normed_ids.size() == 1 && uchset.get_isdigit(normed_ids[0]))
816  bigram_string.push_back(question_unichar_id_);
817  else
818  bigram_string += normed_ids;
819  }
820  WERD_CHOICE normalized_word(&uchset, bigram_string.size());
821  for (int i = 0; i < bigram_string.size(); ++i) {
822  normalized_word.append_unichar_id_space_allocated(bigram_string[i], 1,
823  0.0f, 0.0f);
824  }
825  return bigram_dawg_->word_in_dawg(normalized_word);
826 }
827 
829  if (word.length() == 0) return NO_PERM;
830  int i;
831  WERD_CHOICE new_word(word.unicharset());
832  int last_index = word.length() - 1;
833  int new_len = 0;
834  for (i = 0; i <= last_index; ++i) {
835  UNICHAR_ID unichar_id = (word.unichar_id(i));
836  if (getUnicharset().get_ispunctuation(unichar_id)) {
837  new_word.append_unichar_id(unichar_id, 1, 0.0, 0.0);
838  } else if (!getUnicharset().get_isalpha(unichar_id) &&
839  !getUnicharset().get_isdigit(unichar_id)) {
840  return false; // neither punc, nor alpha, nor digit
841  } else if ((new_len = new_word.length()) == 0 ||
842  new_word.unichar_id(new_len-1) != Dawg::kPatternUnicharID) {
843  new_word.append_unichar_id(Dawg::kPatternUnicharID, 1, 0.0, 0.0);
844  }
845  }
846  for (i = 0; i < dawgs_.size(); ++i) {
847  if (dawgs_[i] != NULL &&
848  dawgs_[i]->type() == DAWG_TYPE_PUNCTUATION &&
849  dawgs_[i]->word_in_dawg(new_word)) return true;
850  }
851  return false;
852 }
853 
856  const UNICHARSET &u_set = getUnicharset();
857  if (u_set.han_sid() > 0) return false;
858  if (u_set.katakana_sid() > 0) return false;
859  if (u_set.thai_sid() > 0) return false;
860  return true;
861 }
862 
863 } // namespace tesseract
void reserve(int size)
bool load_unambig_dawg
Definition: dict.h:566
GenericVector< int > SuccessorList
Definition: dawg.h:69
bool empty() const
Definition: genericvector.h:91
bool load_freq_dawg
Definition: dict.h:565
void SetupForLoad(DawgCache *dawg_cache)
Definition: dict.cpp:206
int case_ok(const WERD_CHOICE &word, const UNICHARSET &unicharset) const
Check a string to see if it matches a set of lexical rules.
Definition: context.cpp:52
void add_document_word(const WERD_CHOICE &best_choice)
Adds a word found on this document to the document specific dictionary.
Definition: dict.cpp:614
PermuterType permuter() const
Definition: dawg.h:130
void init_active_dawgs(DawgPositionVector *active_dawgs, bool ambigs_mode) const
Definition: dict.cpp:570
int han_sid() const
Definition: unicharset.h:887
void adjust_word(WERD_CHOICE *word, bool nonword, XHeightConsistencyEnum xheight_consistency, float additional_adjust, bool modify_rating, bool debug)
Adjusts the rating of the given word.
Definition: dict.cpp:672
EDGE_REF punc_ref
Definition: dawg.h:376
#define REFFORMAT
Definition: dawg.h:93
virtual void unichar_id_to_patterns(UNICHAR_ID unichar_id, const UNICHARSET &unicharset, GenericVector< UNICHAR_ID > *vec) const
Definition: dawg.h:185
int hyphen_base_size() const
Size of the base word (the part on the line before) of a hyphenated word.
Definition: dict.h:130
bool FinishLoad()
Definition: dict.cpp:328
bool get_ispunctuation(UNICHAR_ID unichar_id) const
Definition: unicharset.h:518
Dict(CCUtil *image_ptr)
Definition: dict.cpp:33
static bool valid_word_permuter(uinT8 perm, bool numbers_ok)
Check all the DAWGs to see if this word is in any of them.
Definition: dict.h:455
bool get_isdigit(UNICHAR_ID unichar_id) const
Definition: unicharset.h:511
int GetTopScriptID() const
Definition: ratngs.cpp:656
void set_rating(float new_val)
Definition: ratngs.h:365
virtual bool end_of_word(EDGE_REF edge_ref) const =0
bool valid_bigram(const WERD_CHOICE &word1, const WERD_CHOICE &word2) const
Definition: dict.cpp:785
bool load_bigram_dawg
Definition: dict.h:571
bool valid_punctuation(const WERD_CHOICE &word)
Definition: dict.cpp:828
double segment_penalty_dict_case_bad
Definition: dict.h:588
XHeightConsistencyEnum
Definition: dict.h:74
DawgType type() const
Definition: dawg.h:128
PermuterType
Definition: ratngs.h:238
const UNICHARSET * unicharset() const
Definition: ratngs.h:296
DawgPositionVector * updated_dawgs
Definition: dict.h:81
int katakana_sid() const
Definition: unicharset.h:889
inT64 NODE_REF
Definition: dawg.h:56
FILE * open_file(const char *filename, const char *mode)
Definition: cutil.cpp:82
float rating() const
Definition: ratngs.h:323
float certainty() const
Definition: ratngs.h:326
int size() const
Definition: genericvector.h:72
const STRING debug_string() const
Definition: ratngs.h:501
inT64 EDGE_REF
Definition: dawg.h:55
UNICHAR_ID unichar_id(int index) const
Definition: ratngs.h:311
double doc_dict_certainty_threshold
Definition: dict.h:642
char * user_words_file
Definition: dict.h:557
int(Dict::* letter_is_okay_)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
Definition: dict.h:356
void delete_data_pointers()
bool hyphenated() const
Returns true if we&#39;ve recorded the beginning of a hyphenated word.
Definition: dict.h:126
#define tprintf(...)
Definition: tprintf.h:31
PermuterType permuter
Definition: dict.h:82
const STRING & lang() const
Definition: dawg.h:129
bool load_number_dawg
Definition: dict.h:569
DawgPositionVector * active_dawgs
Definition: dict.h:80
double segment_penalty_dict_frequent_word
Definition: dict.h:580
double segment_penalty_garbage
Definition: dict.h:601
const char * string() const
Definition: strngs.cpp:198
int push_back(T object)
void ProcessPatternEdges(const Dawg *dawg, const DawgPosition &info, UNICHAR_ID unichar_id, bool word_end, DawgArgs *dawg_args, PermuterType *current_permuter) const
Definition: dict.cpp:532
void End()
Definition: dict.cpp:348
int def_letter_is_okay(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
Definition: dict.cpp:372
#define STRING_MEMBER(name, val, comment, vec)
Definition: params.h:306
static DawgCache * GlobalDawgCache()
Definition: dict.cpp:198
#define STRING_INIT_MEMBER(name, val, comment, vec)
Definition: params.h:318
int thai_sid() const
Definition: unicharset.h:890
void Load(const STRING &lang, TessdataManager *data_file)
Definition: dict.cpp:224
void append_unichar_id_space_allocated(UNICHAR_ID unichar_id, int blob_count, float rating, float certainty)
Definition: ratngs.h:448
int length() const
Definition: genericvector.h:86
static const UNICHAR_ID kPatternUnicharID
Definition: dawg.h:126
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:207
Definition: strngs.h:45
void set_permuter(uinT8 perm)
Definition: ratngs.h:371
const CCUtil * getCCUtil() const
Definition: dict.h:91
bool add_word_to_dawg(const WERD_CHOICE &word, const GenericVector< bool > *repetitions)
Definition: trie.cpp:177
static NODE_REF GetStartingNode(const Dawg *dawg, EDGE_REF edge_ref)
Returns the appropriate next node given the EDGE_REF.
Definition: dict.h:420
bool save_doc_words
Definition: dict.h:638
char * user_words_suffix
Definition: dict.h:559
bool get_isupper(UNICHAR_ID unichar_id) const
Definition: unicharset.h:504
double xheight_penalty_subscripts
Definition: dict.h:574
void(Dict::* go_deeper_fxn_)(const char *debug, const BLOB_CHOICE_LIST_VECTOR &char_choices, int char_choice_index, const CHAR_FRAGMENT_INFO *prev_char_frag_info, bool word_ending, WERD_CHOICE *word, float certainties[], float *limit, WERD_CHOICE *best_choice, int *attempts_left, void *void_more_args)
Pointer to go_deeper function.
Definition: dict.h:204
#define BOOL_INIT_MEMBER(name, val, comment, vec)
Definition: params.h:315
bool load_system_dawg
Definition: dict.h:564
bool read_pattern_list(const char *filename, const UNICHARSET &unicharset)
Definition: trie.cpp:402
bool add_unique(const DawgPosition &new_pos, bool debug, const char *debug_msg)
Definition: dawg.h:389
bool word_in_dawg(const WERD_CHOICE &word) const
Returns true if the given word is in the Dawg.
Definition: dawg.cpp:69
char * user_patterns_file
Definition: dict.h:561
virtual EDGE_REF edge_char_of(NODE_REF node, UNICHAR_ID unichar_id, bool word_end) const =0
Returns the edge that corresponds to the letter out of this node.
bool IsSpaceDelimitedLang() const
Returns true if the language is space-delimited (not CJ, or T).
Definition: dict.cpp:855
bool read_and_add_word_list(const char *filename, const UNICHARSET &unicharset, Trie::RTLReversePolicy reverse)
Definition: trie.cpp:289
char * user_patterns_suffix
Definition: dict.h:563
bool valid_end
Definition: dict.h:84
void set_adjust_factor(float factor)
Definition: ratngs.h:305
CCUtil ccutil
#define BOOL_MEMBER(name, val, comment, vec)
Definition: params.h:303
int valid_word(const WERD_CHOICE &word, bool numbers_ok) const
Definition: dict.cpp:752
const GenericVector< UNICHAR_ID > & normed_ids(UNICHAR_ID unichar_id) const
Definition: unicharset.h:834
#define INT_MEMBER(name, val, comment, vec)
Definition: params.h:300
virtual EDGE_REF pattern_loop_edge(EDGE_REF edge_ref, UNICHAR_ID unichar_id, bool word_end) const
Definition: dawg.h:196
int length() const
Definition: ratngs.h:299
void punct_stripped(int *start_core, int *end_core) const
Definition: ratngs.cpp:364
EDGE_REF dawg_ref
Definition: dawg.h:374
#define double_MEMBER(name, val, comment, vec)
Definition: params.h:309
double segment_penalty_dict_nonword
Definition: dict.h:596
UNICHAR_ID char_for_dawg(UNICHAR_ID ch, const Dawg *dawg) const
Definition: dict.h:430
Dawg * GetSquishedDawg(const STRING &lang, TessdataType tessdata_dawg_type, int debug_level, TessdataManager *data_file)
Definition: dawg_cache.cpp:45
double xheight_penalty_inconsistent
Definition: dict.h:577
bool load_punc_dawg
Definition: dict.h:568
double doc_dict_pending_threshold
Definition: dict.h:640
void copy_hyphen_info(WERD_CHOICE *word) const
Definition: dict.h:136
const UNICHARSET & getUnicharset() const
Definition: dict.h:97
void default_dawgs(DawgPositionVector *anylength_dawgs, bool suppress_patterns) const
Definition: dict.cpp:587
double segment_penalty_dict_case_ok
Definition: dict.h:584
int null_sid() const
Definition: unicharset.h:882
int dawg_debug_level
Definition: dict.h:605
#define CHARS_PER_LINE
Definition: cutil.h:57
STRING language_data_path_prefix
Definition: ccutil.h:67
int UNICHAR_ID
Definition: unichar.h:35
void initialize_patterns(UNICHARSET *unicharset)
Definition: trie.cpp:345
void LoadLSTM(const STRING &lang, TessdataManager *data_file)
Definition: dict.cpp:307
bool FreeDawg(Dawg *dawg)
Definition: dawg_cache.h:38
const STRING & unichar_string() const
Definition: ratngs.h:537