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  if (bigram_dawg_) dawgs_ += bigram_dawg_;
245  }
246  if (load_freq_dawg) {
247  freq_dawg_ = dawg_cache_->GetSquishedDawg(lang, TESSDATA_FREQ_DAWG,
248  dawg_debug_level, data_file);
249  if (freq_dawg_) dawgs_ += freq_dawg_;
250  }
251  if (load_unambig_dawg) {
252  unambig_dawg_ = dawg_cache_->GetSquishedDawg(lang, TESSDATA_UNAMBIG_DAWG,
253  dawg_debug_level, data_file);
254  if (unambig_dawg_) dawgs_ += unambig_dawg_;
255  }
256 
257  STRING name;
258  if (((STRING &)user_words_suffix).length() > 0 ||
259  ((STRING &)user_words_file).length() > 0) {
260  Trie *trie_ptr = new Trie(DAWG_TYPE_WORD, lang, USER_DAWG_PERM,
262  if (((STRING &)user_words_file).length() > 0) {
263  name = user_words_file;
264  } else {
266  name += user_words_suffix;
267  }
268  if (!trie_ptr->read_and_add_word_list(name.string(), getUnicharset(),
270  tprintf("Error: failed to load %s\n", name.string());
271  delete trie_ptr;
272  } else {
273  dawgs_ += trie_ptr;
274  }
275  }
276 
277  if (((STRING &)user_patterns_suffix).length() > 0 ||
278  ((STRING &)user_patterns_file).length() > 0) {
279  Trie *trie_ptr = new Trie(DAWG_TYPE_PATTERN, lang, USER_PATTERN_PERM,
281  trie_ptr->initialize_patterns(&(getUnicharset()));
282  if (((STRING &)user_patterns_file).length() > 0) {
283  name = user_patterns_file;
284  } else {
286  name += user_patterns_suffix;
287  }
288  if (!trie_ptr->read_pattern_list(name.string(), getUnicharset())) {
289  tprintf("Error: failed to load %s\n", name.string());
290  delete trie_ptr;
291  } else {
292  dawgs_ += trie_ptr;
293  }
294  }
295 
296  document_words_ = new Trie(DAWG_TYPE_WORD, lang, DOC_DAWG_PERM,
298  dawgs_ += document_words_;
299 
300  // This dawg is temporary and should not be searched by letter_is_ok.
301  pending_words_ = new Trie(DAWG_TYPE_WORD, lang, NO_PERM,
303 }
304 
305 // Loads the dawgs needed by the LSTM model. Call FinishLoad() after.
306 void Dict::LoadLSTM(const STRING &lang, TessdataManager *data_file) {
307  // Load dawgs_.
308  if (load_punc_dawg) {
309  punc_dawg_ = dawg_cache_->GetSquishedDawg(lang, TESSDATA_LSTM_PUNC_DAWG,
310  dawg_debug_level, data_file);
311  if (punc_dawg_) dawgs_ += punc_dawg_;
312  }
313  if (load_system_dawg) {
314  Dawg *system_dawg = dawg_cache_->GetSquishedDawg(
315  lang, TESSDATA_LSTM_SYSTEM_DAWG, dawg_debug_level, data_file);
316  if (system_dawg) dawgs_ += system_dawg;
317  }
318  if (load_number_dawg) {
319  Dawg *number_dawg = dawg_cache_->GetSquishedDawg(
320  lang, TESSDATA_LSTM_NUMBER_DAWG, dawg_debug_level, data_file);
321  if (number_dawg) dawgs_ += number_dawg;
322  }
323 }
324 
325 // Completes the loading process after Load() and/or LoadLSTM().
326 // Returns false if no dictionaries were loaded.
328  if (dawgs_.empty()) return false;
329  // Construct a list of corresponding successors for each dawg. Each entry, i,
330  // in the successors_ vector is a vector of integers that represent the
331  // indices into the dawgs_ vector of the successors for dawg i.
332  successors_.reserve(dawgs_.length());
333  for (int i = 0; i < dawgs_.length(); ++i) {
334  const Dawg *dawg = dawgs_[i];
335  SuccessorList *lst = new SuccessorList();
336  for (int j = 0; j < dawgs_.length(); ++j) {
337  const Dawg *other = dawgs_[j];
338  if (dawg != NULL && other != NULL &&
339  (dawg->lang() == other->lang()) &&
340  kDawgSuccessors[dawg->type()][other->type()]) *lst += j;
341  }
342  successors_ += lst;
343  }
344  return true;
345 }
346 
347 void Dict::End() {
348  if (dawgs_.length() == 0)
349  return; // Not safe to call twice.
350  for (int i = 0; i < dawgs_.size(); i++) {
351  if (!dawg_cache_->FreeDawg(dawgs_[i])) {
352  delete dawgs_[i];
353  }
354  }
355  if (dawg_cache_is_ours_) {
356  delete dawg_cache_;
357  dawg_cache_ = NULL;
358  }
359  successors_.delete_data_pointers();
360  dawgs_.clear();
361  successors_.clear();
362  document_words_ = NULL;
363  delete pending_words_;
364  pending_words_ = NULL;
365 }
366 
367 // Returns true if in light of the current state unichar_id is allowed
368 // according to at least one of the dawgs in the dawgs_ vector.
369 // See more extensive comments in dict.h where this function is declared.
370 int Dict::def_letter_is_okay(void* void_dawg_args,
371  UNICHAR_ID unichar_id,
372  bool word_end) const {
373  DawgArgs *dawg_args = static_cast<DawgArgs*>(void_dawg_args);
374 
375  if (dawg_debug_level >= 3) {
376  tprintf("def_letter_is_okay: current unichar=%s word_end=%d"
377  " num active dawgs=%d\n",
378  getUnicharset().debug_str(unichar_id).string(), word_end,
379  dawg_args->active_dawgs->length());
380  }
381 
382  // Do not accept words that contain kPatternUnicharID.
383  // (otherwise pattern dawgs would not function correctly).
384  // Do not accept words containing INVALID_UNICHAR_IDs.
385  if (unichar_id == Dawg::kPatternUnicharID ||
386  unichar_id == INVALID_UNICHAR_ID) {
387  dawg_args->permuter = NO_PERM;
388  return NO_PERM;
389  }
390 
391  // Initialization.
392  PermuterType curr_perm = NO_PERM;
393  dawg_args->updated_dawgs->clear();
394  dawg_args->valid_end = false;
395 
396  // Go over the active_dawgs vector and insert DawgPosition records
397  // with the updated ref (an edge with the corresponding unichar id) into
398  // dawg_args->updated_pos.
399  for (int a = 0; a < dawg_args->active_dawgs->length(); ++a) {
400  const DawgPosition &pos = (*dawg_args->active_dawgs)[a];
401  const Dawg *punc_dawg = pos.punc_index >= 0 ? dawgs_[pos.punc_index] : NULL;
402  const Dawg *dawg = pos.dawg_index >= 0 ? dawgs_[pos.dawg_index] : NULL;
403 
404  if (!dawg && !punc_dawg) {
405  // shouldn't happen.
406  tprintf("Received DawgPosition with no dawg or punc_dawg. wth?\n");
407  continue;
408  }
409  if (!dawg) {
410  // We're in the punctuation dawg. A core dawg has not been chosen.
411  NODE_REF punc_node = GetStartingNode(punc_dawg, pos.punc_ref);
412  EDGE_REF punc_transition_edge = punc_dawg->edge_char_of(
413  punc_node, Dawg::kPatternUnicharID, word_end);
414  if (punc_transition_edge != NO_EDGE) {
415  // Find all successors, and see which can transition.
416  const SuccessorList &slist = *(successors_[pos.punc_index]);
417  for (int s = 0; s < slist.length(); ++s) {
418  int sdawg_index = slist[s];
419  const Dawg *sdawg = dawgs_[sdawg_index];
420  UNICHAR_ID ch = char_for_dawg(unichar_id, sdawg);
421  EDGE_REF dawg_edge = sdawg->edge_char_of(0, ch, word_end);
422  if (dawg_edge != NO_EDGE) {
423  if (dawg_debug_level >=3) {
424  tprintf("Letter found in dawg %d\n", sdawg_index);
425  }
426  dawg_args->updated_dawgs->add_unique(
427  DawgPosition(sdawg_index, dawg_edge,
428  pos.punc_index, punc_transition_edge, false),
429  dawg_debug_level > 0,
430  "Append transition from punc dawg to current dawgs: ");
431  if (sdawg->permuter() > curr_perm) curr_perm = sdawg->permuter();
432  if (sdawg->end_of_word(dawg_edge) &&
433  punc_dawg->end_of_word(punc_transition_edge))
434  dawg_args->valid_end = true;
435  }
436  }
437  }
438  EDGE_REF punc_edge = punc_dawg->edge_char_of(punc_node, unichar_id,
439  word_end);
440  if (punc_edge != NO_EDGE) {
441  if (dawg_debug_level >=3) {
442  tprintf("Letter found in punctuation dawg\n");
443  }
444  dawg_args->updated_dawgs->add_unique(
445  DawgPosition(-1, NO_EDGE, pos.punc_index, punc_edge, false),
446  dawg_debug_level > 0,
447  "Extend punctuation dawg: ");
448  if (PUNC_PERM > curr_perm) curr_perm = PUNC_PERM;
449  if (punc_dawg->end_of_word(punc_edge)) dawg_args->valid_end = true;
450  }
451  continue;
452  }
453 
454  if (punc_dawg && dawg->end_of_word(pos.dawg_ref)) {
455  // We can end the main word here.
456  // If we can continue on the punc ref, add that possibility.
457  NODE_REF punc_node = GetStartingNode(punc_dawg, pos.punc_ref);
458  EDGE_REF punc_edge = punc_node == NO_EDGE ? NO_EDGE
459  : punc_dawg->edge_char_of(punc_node, unichar_id, word_end);
460  if (punc_edge != NO_EDGE) {
461  dawg_args->updated_dawgs->add_unique(
463  pos.punc_index, punc_edge, true),
464  dawg_debug_level > 0,
465  "Return to punctuation dawg: ");
466  if (dawg->permuter() > curr_perm) curr_perm = dawg->permuter();
467  if (punc_dawg->end_of_word(punc_edge)) dawg_args->valid_end = true;
468  }
469  }
470 
471  if (pos.back_to_punc) continue;
472 
473  // If we are dealing with the pattern dawg, look up all the
474  // possible edges, not only for the exact unichar_id, but also
475  // for all its character classes (alpha, digit, etc).
476  if (dawg->type() == DAWG_TYPE_PATTERN) {
477  ProcessPatternEdges(dawg, pos, unichar_id, word_end, dawg_args,
478  &curr_perm);
479  // There can't be any successors to dawg that is of type
480  // DAWG_TYPE_PATTERN, so we are done examining this DawgPosition.
481  continue;
482  }
483 
484  // Find the edge out of the node for the unichar_id.
485  NODE_REF node = GetStartingNode(dawg, pos.dawg_ref);
486  EDGE_REF edge = (node == NO_EDGE) ? NO_EDGE
487  : dawg->edge_char_of(node, char_for_dawg(unichar_id, dawg), word_end);
488 
489  if (dawg_debug_level >= 3) {
490  tprintf("Active dawg: [%d, " REFFORMAT "] edge=" REFFORMAT "\n",
491  pos.dawg_index, node, edge);
492  }
493 
494  if (edge != NO_EDGE) { // the unichar was found in the current dawg
495  if (dawg_debug_level >=3) {
496  tprintf("Letter found in dawg %d\n", pos.dawg_index);
497  }
498  if (word_end && punc_dawg && !punc_dawg->end_of_word(pos.punc_ref)) {
499  if (dawg_debug_level >= 3) {
500  tprintf("Punctuation constraint not satisfied at end of word.\n");
501  }
502  continue;
503  }
504  if (dawg->permuter() > curr_perm) curr_perm = dawg->permuter();
505  if (dawg->end_of_word(edge) &&
506  (punc_dawg == NULL || punc_dawg->end_of_word(pos.punc_ref)))
507  dawg_args->valid_end = true;
508  dawg_args->updated_dawgs->add_unique(
509  DawgPosition(pos.dawg_index, edge, pos.punc_index, pos.punc_ref,
510  false),
511  dawg_debug_level > 0,
512  "Append current dawg to updated active dawgs: ");
513  }
514  } // end for
515  // Update dawg_args->permuter if it used to be NO_PERM or became NO_PERM
516  // or if we found the current letter in a non-punctuation dawg. This
517  // allows preserving information on which dawg the "core" word came from.
518  // Keep the old value of dawg_args->permuter if it is COMPOUND_PERM.
519  if (dawg_args->permuter == NO_PERM || curr_perm == NO_PERM ||
520  (curr_perm != PUNC_PERM && dawg_args->permuter != COMPOUND_PERM)) {
521  dawg_args->permuter = curr_perm;
522  }
523  if (dawg_debug_level >= 2) {
524  tprintf("Returning %d for permuter code for this character.\n",
525  dawg_args->permuter);
526  }
527  return dawg_args->permuter;
528 }
529 
530 void Dict::ProcessPatternEdges(const Dawg *dawg, const DawgPosition &pos,
531  UNICHAR_ID unichar_id, bool word_end,
532  DawgArgs *dawg_args,
533  PermuterType *curr_perm) const {
534  NODE_REF node = GetStartingNode(dawg, pos.dawg_ref);
535  // Try to find the edge corresponding to the exact unichar_id and to all the
536  // edges corresponding to the character class of unichar_id.
537  GenericVector<UNICHAR_ID> unichar_id_patterns;
538  unichar_id_patterns.push_back(unichar_id);
539  dawg->unichar_id_to_patterns(unichar_id, getUnicharset(),
540  &unichar_id_patterns);
541  for (int i = 0; i < unichar_id_patterns.size(); ++i) {
542  // On the first iteration check all the outgoing edges.
543  // On the second iteration check all self-loops.
544  for (int k = 0; k < 2; ++k) {
545  EDGE_REF edge = (k == 0)
546  ? dawg->edge_char_of(node, unichar_id_patterns[i], word_end)
547  : dawg->pattern_loop_edge(pos.dawg_ref, unichar_id_patterns[i], word_end);
548  if (edge == NO_EDGE) continue;
549  if (dawg_debug_level >= 3) {
550  tprintf("Pattern dawg: [%d, " REFFORMAT "] edge=" REFFORMAT "\n",
551  pos.dawg_index, node, edge);
552  tprintf("Letter found in pattern dawg %d\n", pos.dawg_index);
553  }
554  if (dawg->permuter() > *curr_perm) *curr_perm = dawg->permuter();
555  if (dawg->end_of_word(edge)) dawg_args->valid_end = true;
556  dawg_args->updated_dawgs->add_unique(
557  DawgPosition(pos.dawg_index, edge, pos.punc_index, pos.punc_ref,
558  pos.back_to_punc),
559  dawg_debug_level > 0,
560  "Append current dawg to updated active dawgs: ");
561  }
562  }
563 }
564 
565 // Fill the given active_dawgs vector with dawgs that could contain the
566 // beginning of the word. If hyphenated() returns true, copy the entries
567 // from hyphen_active_dawgs_ instead.
569  bool ambigs_mode) const {
570  int i;
571  if (hyphenated()) {
572  *active_dawgs = hyphen_active_dawgs_;
573  if (dawg_debug_level >= 3) {
574  for (i = 0; i < hyphen_active_dawgs_.size(); ++i) {
575  tprintf("Adding hyphen beginning dawg [%d, " REFFORMAT "]\n",
576  hyphen_active_dawgs_[i].dawg_index,
577  hyphen_active_dawgs_[i].dawg_ref);
578  }
579  }
580  } else {
581  default_dawgs(active_dawgs, ambigs_mode);
582  }
583 }
584 
586  bool suppress_patterns) const {
587  bool punc_dawg_available =
588  (punc_dawg_ != NULL) &&
589  punc_dawg_->edge_char_of(0, Dawg::kPatternUnicharID, true) != NO_EDGE;
590 
591  for (int i = 0; i < dawgs_.length(); i++) {
592  if (dawgs_[i] != NULL &&
593  !(suppress_patterns && (dawgs_[i])->type() == DAWG_TYPE_PATTERN)) {
594  int dawg_ty = dawgs_[i]->type();
595  bool subsumed_by_punc = kDawgSuccessors[DAWG_TYPE_PUNCTUATION][dawg_ty];
596  if (dawg_ty == DAWG_TYPE_PUNCTUATION) {
597  *dawg_pos_vec += DawgPosition(-1, NO_EDGE, i, NO_EDGE, false);
598  if (dawg_debug_level >= 3) {
599  tprintf("Adding beginning punc dawg [%d, " REFFORMAT "]\n", i,
600  NO_EDGE);
601  }
602  } else if (!punc_dawg_available || !subsumed_by_punc) {
603  *dawg_pos_vec += DawgPosition(i, NO_EDGE, -1, NO_EDGE, false);
604  if (dawg_debug_level >= 3) {
605  tprintf("Adding beginning dawg [%d, " REFFORMAT "]\n", i, NO_EDGE);
606  }
607  }
608  }
609  }
610 }
611 
612 void Dict::add_document_word(const WERD_CHOICE &best_choice) {
613  // Do not add hyphenated word parts to the document dawg.
614  // hyphen_word_ will be non-NULL after the set_hyphen_word() is
615  // called when the first part of the hyphenated word is
616  // discovered and while the second part of the word is recognized.
617  // hyphen_word_ is cleared in cc_recg() before the next word on
618  // the line is recognized.
619  if (hyphen_word_) return;
620 
621  char filename[CHARS_PER_LINE];
622  FILE *doc_word_file;
623  int stringlen = best_choice.length();
624 
625  if (valid_word(best_choice) || stringlen < 2)
626  return;
627 
628  // Discard words that contain >= kDocDictMaxRepChars repeating unichars.
629  if (best_choice.length() >= kDocDictMaxRepChars) {
630  int num_rep_chars = 1;
631  UNICHAR_ID uch_id = best_choice.unichar_id(0);
632  for (int i = 1; i < best_choice.length(); ++i) {
633  if (best_choice.unichar_id(i) != uch_id) {
634  num_rep_chars = 1;
635  uch_id = best_choice.unichar_id(i);
636  } else {
637  ++num_rep_chars;
638  if (num_rep_chars == kDocDictMaxRepChars) return;
639  }
640  }
641  }
642 
643  if (best_choice.certainty() < doc_dict_certainty_threshold ||
644  stringlen == 2) {
645  if (best_choice.certainty() < doc_dict_pending_threshold)
646  return;
647 
648  if (!pending_words_->word_in_dawg(best_choice)) {
649  if (stringlen > 2 ||
650  (stringlen == 2 &&
651  getUnicharset().get_isupper(best_choice.unichar_id(0)) &&
652  getUnicharset().get_isupper(best_choice.unichar_id(1)))) {
653  pending_words_->add_word_to_dawg(best_choice);
654  }
655  return;
656  }
657  }
658 
659  if (save_doc_words) {
660  strcpy(filename, getCCUtil()->imagefile.string());
661  strcat(filename, ".doc");
662  doc_word_file = open_file (filename, "a");
663  fprintf(doc_word_file, "%s\n",
664  best_choice.debug_string().string());
665  fclose(doc_word_file);
666  }
667  document_words_->add_word_to_dawg(best_choice);
668 }
669 
671  bool nonword,
672  XHeightConsistencyEnum xheight_consistency,
673  float additional_adjust,
674  bool modify_rating,
675  bool debug) {
676  bool is_han = (getUnicharset().han_sid() != getUnicharset().null_sid() &&
677  word->GetTopScriptID() == getUnicharset().han_sid());
678  bool case_is_ok = (is_han || case_ok(*word, getUnicharset()));
679  bool punc_is_ok = (is_han || !nonword || valid_punctuation(*word));
680 
681  float adjust_factor = additional_adjust;
682  float new_rating = word->rating();
683  new_rating += kRatingPad;
684  const char *xheight_triggered = "";
685  if (word->length() > 1) {
686  // Calculate x-height and y-offset consistency penalties.
687  switch (xheight_consistency) {
688  case XH_INCONSISTENT:
689  adjust_factor += xheight_penalty_inconsistent;
690  xheight_triggered = ", xhtBAD";
691  break;
692  case XH_SUBNORMAL:
693  adjust_factor += xheight_penalty_subscripts;
694  xheight_triggered = ", xhtSUB";
695  break;
696  case XH_GOOD:
697  // leave the factor alone - all good!
698  break;
699  }
700  // TODO(eger): if nonword is true, but there is a "core" thats' a dict
701  // word, negate nonword status.
702  } else {
703  if (debug) {
704  tprintf("Consistency could not be calculated.\n");
705  }
706  }
707  if (debug) {
708  tprintf("%sWord: %s %4.2f%s", nonword ? "Non-" : "",
709  word->unichar_string().string(), word->rating(),
710  xheight_triggered);
711  }
712 
713  if (nonword) { // non-dictionary word
714  if (case_is_ok && punc_is_ok) {
715  adjust_factor += segment_penalty_dict_nonword;
716  new_rating *= adjust_factor;
717  if (debug) tprintf(", W");
718  } else {
719  adjust_factor += segment_penalty_garbage;
720  new_rating *= adjust_factor;
721  if (debug) {
722  if (!case_is_ok) tprintf(", C");
723  if (!punc_is_ok) tprintf(", P");
724  }
725  }
726  } else { // dictionary word
727  if (case_is_ok) {
728  if (!is_han && freq_dawg_ != NULL && freq_dawg_->word_in_dawg(*word)) {
730  adjust_factor += segment_penalty_dict_frequent_word;
731  new_rating *= adjust_factor;
732  if (debug) tprintf(", F");
733  } else {
734  adjust_factor += segment_penalty_dict_case_ok;
735  new_rating *= adjust_factor;
736  if (debug) tprintf(", ");
737  }
738  } else {
739  adjust_factor += segment_penalty_dict_case_bad;
740  new_rating *= adjust_factor;
741  if (debug) tprintf(", C");
742  }
743  }
744  new_rating -= kRatingPad;
745  if (modify_rating) word->set_rating(new_rating);
746  if (debug) tprintf(" %4.2f --> %4.2f\n", adjust_factor, new_rating);
747  word->set_adjust_factor(adjust_factor);
748 }
749 
750 int Dict::valid_word(const WERD_CHOICE &word, bool numbers_ok) const {
751  const WERD_CHOICE *word_ptr = &word;
752  WERD_CHOICE temp_word(word.unicharset());
753  if (hyphenated() && hyphen_word_->unicharset() == word.unicharset()) {
754  copy_hyphen_info(&temp_word);
755  temp_word += word;
756  word_ptr = &temp_word;
757  }
758  if (word_ptr->length() == 0) return NO_PERM;
759  // Allocate vectors for holding current and updated
760  // active_dawgs and initialize them.
761  DawgPositionVector *active_dawgs = new DawgPositionVector[2];
762  init_active_dawgs(&(active_dawgs[0]), false);
763  DawgArgs dawg_args(&(active_dawgs[0]), &(active_dawgs[1]), NO_PERM);
764  int last_index = word_ptr->length() - 1;
765  // Call leter_is_okay for each letter in the word.
766  for (int i = hyphen_base_size(); i <= last_index; ++i) {
767  if (!((this->*letter_is_okay_)(&dawg_args, word_ptr->unichar_id(i),
768  i == last_index))) break;
769  // Swap active_dawgs, constraints with the corresponding updated vector.
770  if (dawg_args.updated_dawgs == &(active_dawgs[1])) {
771  dawg_args.updated_dawgs = &(active_dawgs[0]);
772  ++(dawg_args.active_dawgs);
773  } else {
774  ++(dawg_args.updated_dawgs);
775  dawg_args.active_dawgs = &(active_dawgs[0]);
776  }
777  }
778  delete[] active_dawgs;
779  return valid_word_permuter(dawg_args.permuter, numbers_ok) ?
780  dawg_args.permuter : NO_PERM;
781 }
782 
783 bool Dict::valid_bigram(const WERD_CHOICE &word1,
784  const WERD_CHOICE &word2) const {
785  if (bigram_dawg_ == NULL) return false;
786 
787  // Extract the core word from the middle of each word with any digits
788  // replaced with question marks.
789  int w1start, w1end, w2start, w2end;
790  word1.punct_stripped(&w1start, &w1end);
791  word2.punct_stripped(&w2start, &w2end);
792 
793  // We don't want to penalize a single guillemet, hyphen, etc.
794  // But our bigram list doesn't have any information about punctuation.
795  if (w1start >= w1end) return word1.length() < 3;
796  if (w2start >= w2end) return word2.length() < 3;
797 
798  const UNICHARSET& uchset = getUnicharset();
799  GenericVector<UNICHAR_ID> bigram_string;
800  bigram_string.reserve(w1end + w2end + 1);
801  for (int i = w1start; i < w1end; i++) {
802  const GenericVector<UNICHAR_ID>& normed_ids =
803  getUnicharset().normed_ids(word1.unichar_id(i));
804  if (normed_ids.size() == 1 && uchset.get_isdigit(normed_ids[0]))
805  bigram_string.push_back(question_unichar_id_);
806  else
807  bigram_string += normed_ids;
808  }
809  bigram_string.push_back(UNICHAR_SPACE);
810  for (int i = w2start; i < w2end; i++) {
811  const GenericVector<UNICHAR_ID>& normed_ids =
812  getUnicharset().normed_ids(word2.unichar_id(i));
813  if (normed_ids.size() == 1 && uchset.get_isdigit(normed_ids[0]))
814  bigram_string.push_back(question_unichar_id_);
815  else
816  bigram_string += normed_ids;
817  }
818  WERD_CHOICE normalized_word(&uchset, bigram_string.size());
819  for (int i = 0; i < bigram_string.size(); ++i) {
820  normalized_word.append_unichar_id_space_allocated(bigram_string[i], 1,
821  0.0f, 0.0f);
822  }
823  return bigram_dawg_->word_in_dawg(normalized_word);
824 }
825 
827  if (word.length() == 0) return NO_PERM;
828  int i;
829  WERD_CHOICE new_word(word.unicharset());
830  int last_index = word.length() - 1;
831  int new_len = 0;
832  for (i = 0; i <= last_index; ++i) {
833  UNICHAR_ID unichar_id = (word.unichar_id(i));
834  if (getUnicharset().get_ispunctuation(unichar_id)) {
835  new_word.append_unichar_id(unichar_id, 1, 0.0, 0.0);
836  } else if (!getUnicharset().get_isalpha(unichar_id) &&
837  !getUnicharset().get_isdigit(unichar_id)) {
838  return false; // neither punc, nor alpha, nor digit
839  } else if ((new_len = new_word.length()) == 0 ||
840  new_word.unichar_id(new_len-1) != Dawg::kPatternUnicharID) {
841  new_word.append_unichar_id(Dawg::kPatternUnicharID, 1, 0.0, 0.0);
842  }
843  }
844  for (i = 0; i < dawgs_.size(); ++i) {
845  if (dawgs_[i] != NULL &&
846  dawgs_[i]->type() == DAWG_TYPE_PUNCTUATION &&
847  dawgs_[i]->word_in_dawg(new_word)) return true;
848  }
849  return false;
850 }
851 
854  const UNICHARSET &u_set = getUnicharset();
855  if (u_set.han_sid() > 0) return false;
856  if (u_set.katakana_sid() > 0) return false;
857  if (u_set.thai_sid() > 0) return false;
858  return true;
859 }
860 
861 } // namespace tesseract
bool valid_punctuation(const WERD_CHOICE &word)
Definition: dict.cpp:826
static NODE_REF GetStartingNode(const Dawg *dawg, EDGE_REF edge_ref)
Returns the appropriate next node given the EDGE_REF.
Definition: dict.h:420
Dict(CCUtil *image_ptr)
Definition: dict.cpp:33
const UNICHARSET & getUnicharset() const
Definition: dict.h:97
bool add_unique(const DawgPosition &new_pos, bool debug, const char *debug_msg)
Definition: dawg.h:388
bool load_punc_dawg
Definition: dict.h:568
EDGE_REF dawg_ref
Definition: dawg.h:373
UNICHAR_ID unichar_id(int index) const
Definition: ratngs.h:313
const GenericVector< UNICHAR_ID > & normed_ids(UNICHAR_ID unichar_id) const
Definition: unicharset.h:795
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.
UNICHAR_ID char_for_dawg(UNICHAR_ID ch, const Dawg *dawg) const
Definition: dict.h:430
bool add_word_to_dawg(const WERD_CHOICE &word, const GenericVector< bool > *repetitions)
Definition: trie.cpp:177
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:670
int UNICHAR_ID
Definition: unichar.h:33
void reserve(int size)
bool get_ispunctuation(UNICHAR_ID unichar_id) const
Definition: unicharset.h:479
int length() const
Definition: ratngs.h:301
DawgType type() const
Definition: dawg.h:127
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
#define double_MEMBER(name, val, comment, vec)
Definition: params.h:309
bool valid_end
Definition: dict.h:84
voidpf void uLong size
Definition: ioapi.h:39
int dawg_debug_level
Definition: dict.h:605
void init_active_dawgs(DawgPositionVector *active_dawgs, bool ambigs_mode) const
Definition: dict.cpp:568
double doc_dict_pending_threshold
Definition: dict.h:640
int push_back(T object)
bool load_bigram_dawg
Definition: dict.h:571
double segment_penalty_dict_case_ok
Definition: dict.h:584
int def_letter_is_okay(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
Definition: dict.cpp:370
const STRING debug_string() const
Definition: ratngs.h:503
#define tprintf(...)
Definition: tprintf.h:31
GenericVector< int > SuccessorList
Definition: dawg.h:68
const char * string() const
Definition: strngs.cpp:198
bool load_number_dawg
Definition: dict.h:569
bool save_doc_words
Definition: dict.h:638
STRING language_data_path_prefix
Definition: ccutil.h:67
bool empty() const
Definition: genericvector.h:90
double segment_penalty_dict_frequent_word
Definition: dict.h:580
int size() const
Definition: genericvector.h:72
#define REFFORMAT
Definition: dawg.h:92
int han_sid() const
Definition: unicharset.h:848
bool word_in_dawg(const WERD_CHOICE &word) const
Returns true if the given word is in the Dawg.
Definition: dawg.cpp:69
int thai_sid() const
Definition: unicharset.h:851
bool IsSpaceDelimitedLang() const
Returns true if the language is space-delimited (not CJ, or T).
Definition: dict.cpp:853
bool read_and_add_word_list(const char *filename, const UNICHARSET &unicharset, Trie::RTLReversePolicy reverse)
Definition: trie.cpp:289
virtual bool end_of_word(EDGE_REF edge_ref) const =0
void LoadLSTM(const STRING &lang, TessdataManager *data_file)
Definition: dict.cpp:306
FILE * open_file(const char *filename, const char *mode)
Definition: cutil.cpp:82
int hyphen_base_size() const
Size of the base word (the part on the line before) of a hyphenated word.
Definition: dict.h:130
inT64 NODE_REF
Definition: dawg.h:55
bool valid_bigram(const WERD_CHOICE &word1, const WERD_CHOICE &word2) const
Definition: dict.cpp:783
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
bool load_freq_dawg
Definition: dict.h:565
const CCUtil * getCCUtil() const
Definition: dict.h:91
char * user_words_file
Definition: dict.h:557
PermuterType permuter() const
Definition: dawg.h:129
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:530
bool get_isdigit(UNICHAR_ID unichar_id) const
Definition: unicharset.h:472
XHeightConsistencyEnum
Definition: dict.h:74
double segment_penalty_garbage
Definition: dict.h:601
virtual EDGE_REF pattern_loop_edge(EDGE_REF edge_ref, UNICHAR_ID unichar_id, bool word_end) const
Definition: dawg.h:195
char * user_patterns_suffix
Definition: dict.h:563
Definition: strngs.h:45
const STRING & lang() const
Definition: dawg.h:128
bool load_unambig_dawg
Definition: dict.h:566
double segment_penalty_dict_case_bad
Definition: dict.h:588
DawgPositionVector * updated_dawgs
Definition: dict.h:81
int valid_word(const WERD_CHOICE &word, bool numbers_ok) const
Definition: dict.cpp:750
double xheight_penalty_inconsistent
Definition: dict.h:577
EDGE_REF punc_ref
Definition: dawg.h:375
void initialize_patterns(UNICHARSET *unicharset)
Definition: trie.cpp:350
void copy_hyphen_info(WERD_CHOICE *word) const
Definition: dict.h:136
float certainty() const
Definition: ratngs.h:328
int length() const
Definition: genericvector.h:85
bool hyphenated() const
Returns true if we&#39;ve recorded the beginning of a hyphenated word.
Definition: dict.h:126
const UNICHARSET * unicharset() const
Definition: ratngs.h:298
int katakana_sid() const
Definition: unicharset.h:850
#define STRING_MEMBER(name, val, comment, vec)
Definition: params.h:306
const STRING & unichar_string() const
Definition: ratngs.h:539
#define STRING_INIT_MEMBER(name, val, comment, vec)
Definition: params.h:318
void set_rating(float new_val)
Definition: ratngs.h:367
void End()
Definition: dict.cpp:347
void punct_stripped(int *start_core, int *end_core) const
Definition: ratngs.cpp:361
void append_unichar_id_space_allocated(UNICHAR_ID unichar_id, int blob_count, float rating, float certainty)
Definition: ratngs.h:450
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
double doc_dict_certainty_threshold
Definition: dict.h:642
Dawg * GetSquishedDawg(const STRING &lang, TessdataType tessdata_dawg_type, int debug_level, TessdataManager *data_file)
Definition: dawg_cache.cpp:45
bool load_system_dawg
Definition: dict.h:564
void default_dawgs(DawgPositionVector *anylength_dawgs, bool suppress_patterns) const
Definition: dict.cpp:585
const char * filename
Definition: ioapi.h:38
DawgPositionVector * active_dawgs
Definition: dict.h:80
char * user_words_suffix
Definition: dict.h:559
double segment_penalty_dict_nonword
Definition: dict.h:596
PermuterType permuter
Definition: dict.h:82
int GetTopScriptID() const
Definition: ratngs.cpp:653
virtual void unichar_id_to_patterns(UNICHAR_ID unichar_id, const UNICHARSET &unicharset, GenericVector< UNICHAR_ID > *vec) const
Definition: dawg.h:184
CCUtil ccutil
void add_document_word(const WERD_CHOICE &best_choice)
Adds a word found on this document to the document specific dictionary.
Definition: dict.cpp:612
#define BOOL_INIT_MEMBER(name, val, comment, vec)
Definition: params.h:315
int null_sid() const
Definition: unicharset.h:843
char * user_patterns_file
Definition: dict.h:561
static DawgCache * GlobalDawgCache()
Definition: dict.cpp:198
bool get_isupper(UNICHAR_ID unichar_id) const
Definition: unicharset.h:465
double xheight_penalty_subscripts
Definition: dict.h:574
#define CHARS_PER_LINE
Definition: cutil.h:57
void SetupForLoad(DawgCache *dawg_cache)
Definition: dict.cpp:206
static const UNICHAR_ID kPatternUnicharID
Definition: dawg.h:125
void Load(const STRING &lang, TessdataManager *data_file)
Definition: dict.cpp:224
bool read_pattern_list(const char *filename, const UNICHARSET &unicharset)
Definition: trie.cpp:407
inT64 EDGE_REF
Definition: dawg.h:54
void delete_data_pointers()
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:194
bool FreeDawg(Dawg *dawg)
Definition: dawg_cache.h:38
void set_permuter(uinT8 perm)
Definition: ratngs.h:373
#define BOOL_MEMBER(name, val, comment, vec)
Definition: params.h:303
#define INT_MEMBER(name, val, comment, vec)
Definition: params.h:300
int(Dict::* letter_is_okay_)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
Definition: dict.h:356
PermuterType
Definition: ratngs.h:240
bool FinishLoad()
Definition: dict.cpp:327
float rating() const
Definition: ratngs.h:325
void set_adjust_factor(float factor)
Definition: ratngs.h:307