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