tesseract  4.00.00dev
unicharcompress.h
Go to the documentation of this file.
1 // File: unicharcompress.h
3 // Description: Unicode re-encoding using a sequence of smaller numbers in
4 // place of a single large code for CJK, similarly for Indic,
5 // and dissection of ligatures for other scripts.
6 // Author: Ray Smith
7 // Created: Wed Mar 04 14:45:01 PST 2015
8 //
9 // (C) Copyright 2015, Google Inc.
10 // Licensed under the Apache License, Version 2.0 (the "License");
11 // you may not use this file except in compliance with the License.
12 // You may obtain a copy of the License at
13 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
19 //
21 
22 #ifndef TESSERACT_CCUTIL_UNICHARCOMPRESS_H_
23 #define TESSERACT_CCUTIL_UNICHARCOMPRESS_H_
24 
25 #include <unordered_map>
26 
27 #include "serialis.h"
28 #include "strngs.h"
29 #include "unicharset.h"
30 
31 namespace tesseract {
32 
33 // Trivial class to hold the code for a recoded unichar-id.
35  public:
36  // The maximum length of a code.
37  static const int kMaxCodeLen = 9;
38 
39  RecodedCharID() : self_normalized_(1), length_(0) {
40  memset(code_, 0, sizeof(code_));
41  }
42  void Truncate(int length) { length_ = length; }
43  // Sets the code value at the given index in the code.
44  void Set(int index, int value) {
45  code_[index] = value;
46  if (length_ <= index) length_ = index + 1;
47  }
48  // Shorthand for setting codes of length 3, as all Hangul and Han codes are
49  // length 3.
50  void Set3(int code0, int code1, int code2) {
51  length_ = 3;
52  code_[0] = code0;
53  code_[1] = code1;
54  code_[2] = code2;
55  }
56  // Accessors
57  int length() const { return length_; }
58  int operator()(int index) const { return code_[index]; }
59 
60  // Writes to the given file. Returns false in case of error.
61  bool Serialize(TFile* fp) const {
62  if (fp->FWrite(&self_normalized_, sizeof(self_normalized_), 1) != 1)
63  return false;
64  if (fp->FWrite(&length_, sizeof(length_), 1) != 1) return false;
65  if (fp->FWrite(code_, sizeof(code_[0]), length_) != length_) return false;
66  return true;
67  }
68  // Reads from the given file. Returns false in case of error.
69  // If swap is true, assumes a big/little-endian swap is needed.
70  bool DeSerialize(TFile* fp) {
71  if (fp->FRead(&self_normalized_, sizeof(self_normalized_), 1) != 1)
72  return false;
73  if (fp->FReadEndian(&length_, sizeof(length_), 1) != 1) return false;
74  if (fp->FReadEndian(code_, sizeof(code_[0]), length_) != length_)
75  return false;
76  return true;
77  }
78  bool operator==(const RecodedCharID& other) const {
79  if (length_ != other.length_) return false;
80  for (int i = 0; i < length_; ++i) {
81  if (code_[i] != other.code_[i]) return false;
82  }
83  return true;
84  }
85  // Hash functor for RecodedCharID.
87  size_t operator()(const RecodedCharID& code) const {
88  size_t result = 0;
89  for (int i = 0; i < code.length_; ++i) {
90  result ^= code(i) << (7 * i);
91  }
92  return result;
93  }
94  };
95 
96  private:
97  // True if this code is self-normalizing, ie is the master entry for indices
98  // that map to the same code. Has boolean value, but inT8 for serialization.
99  inT8 self_normalized_;
100  // The number of elements in use in code_;
101  inT32 length_;
102  // The re-encoded form of the unichar-id to which this RecodedCharID relates.
103  inT32 code_[kMaxCodeLen];
104 };
105 
106 // Class holds a "compression" of a unicharset to simplify the learning problem
107 // for a neural-network-based classifier.
108 // Objectives:
109 // 1 (CJK): Ids of a unicharset with a large number of classes are expressed as
110 // a sequence of 3 codes with much fewer values.
111 // This is achieved using the Jamo coding for Hangul and the Unicode
112 // Radical-Stroke-index for Han.
113 // 2 (Indic): Instead of thousands of codes with one for each grapheme, re-code
114 // as the unicode sequence (but coded in a more compact space).
115 // 3 (the rest): Eliminate multi-path problems with ligatures and fold confusing
116 // and not significantly distinct shapes (quotes) togther, ie
117 // represent the fi ligature as the f-i pair, and fold u+2019 and
118 // friends all onto ascii single '
119 // 4 The null character and mapping to target activations:
120 // To save horizontal coding space, the compressed codes are generally mapped
121 // to target network activations without intervening null characters, BUT
122 // in the case of ligatures, such as ff, null characters have to be included
123 // so existence of repeated codes is detected at codebook-building time, and
124 // null characters are embedded directly into the codes, so the rest of the
125 // system doesn't need to worry about the problem (much). There is still an
126 // effect on the range of ways in which the target activations can be
127 // generated.
128 //
129 // The computed code values are compact (no unused values), and, for CJK,
130 // unique (each code position uses a disjoint set of values from each other code
131 // position). For non-CJK, the same code value CAN be used in multiple
132 // positions, eg the ff ligature is converted to <f> <nullchar> <f>, where <f>
133 // is the same code as is used for the single f.
135  public:
136  UnicharCompress();
137  UnicharCompress(const UnicharCompress& src);
138  ~UnicharCompress();
139  UnicharCompress& operator=(const UnicharCompress& src);
140 
141  // The 1st Hangul unicode.
142  static const int kFirstHangul = 0xac00;
143  // The number of Hangul unicodes.
144  static const int kNumHangul = 11172;
145  // The number of Jamos for each of the 3 parts of a Hangul character, being
146  // the Leading consonant, Vowel and Trailing consonant.
147  static const int kLCount = 19;
148  static const int kVCount = 21;
149  static const int kTCount = 28;
150 
151  // Computes the encoding for the given unicharset. It is a requirement that
152  // the file training/langdata/radical-stroke.txt have been read into the
153  // input string radical_stroke_table.
154  // Returns false if the encoding cannot be constructed.
155  bool ComputeEncoding(const UNICHARSET& unicharset, int null_id,
156  STRING* radical_stroke_table);
157  // Sets up an encoder that doesn't change the unichars at all, so it just
158  // passes them through unchanged.
159  void SetupPassThrough(const UNICHARSET& unicharset);
160  // Sets up an encoder directly using the given encoding vector, which maps
161  // unichar_ids to the given codes.
162  void SetupDirect(const GenericVector<RecodedCharID>& codes);
163 
164  // Returns the number of different values that can be used in a code, ie
165  // 1 + the maximum value that will ever be used by an RecodedCharID code in
166  // any position in its array.
167  int code_range() const { return code_range_; }
168 
169  // Encodes a single unichar_id. Returns the length of the code, (or zero if
170  // invalid input), and the encoding itself in code.
171  int EncodeUnichar(int unichar_id, RecodedCharID* code) const;
172  // Decodes code, returning the original unichar-id, or
173  // INVALID_UNICHAR_ID if the input is invalid.
174  int DecodeUnichar(const RecodedCharID& code) const;
175  // Returns true if the given code is a valid start or single code.
176  bool IsValidFirstCode(int code) const { return is_valid_start_[code]; }
177  // Returns a list of valid non-final next codes for a given prefix code,
178  // which may be empty.
179  const GenericVector<int>* GetNextCodes(const RecodedCharID& code) const {
180  auto it = next_codes_.find(code);
181  return it == next_codes_.end() ? NULL : it->second;
182  }
183  // Returns a list of valid final codes for a given prefix code, which may
184  // be empty.
185  const GenericVector<int>* GetFinalCodes(const RecodedCharID& code) const {
186  auto it = final_codes_.find(code);
187  return it == final_codes_.end() ? NULL : it->second;
188  }
189 
190  // Writes to the given file. Returns false in case of error.
191  bool Serialize(TFile* fp) const;
192  // Reads from the given file. Returns false in case of error.
193 
194  bool DeSerialize(TFile* fp);
195 
196  // Returns a STRING containing a text file that describes the encoding thus:
197  // <index>[,<index>]*<tab><UTF8-str><newline>
198  // In words, a comma-separated list of one or more indices, followed by a tab
199  // and the UTF-8 string that the code represents per line. Most simple scripts
200  // will encode a single index to a UTF8-string, but Chinese, Japanese, Korean
201  // and the Indic scripts will contain a many-to-many mapping.
202  // See the class comment above for details.
203  STRING GetEncodingAsString(const UNICHARSET& unicharset) const;
204 
205  // Helper decomposes a Hangul unicode to 3 parts, leading, vowel, trailing.
206  // Note that the returned values are 0-based indices, NOT unicode Jamo.
207  // Returns false if the input is not in the Hangul unicode range.
208  static bool DecomposeHangul(int unicode, int* leading, int* vowel,
209  int* trailing);
210 
211  private:
212  // Renumbers codes to eliminate unused values.
213  void DefragmentCodeValues(int encoded_null);
214  // Computes the value of code_range_ from the encoder_.
215  void ComputeCodeRange();
216  // Initializes the decoding hash_map from the encoder_ array.
217  void SetupDecoder();
218  // Frees allocated memory.
219  void Cleanup();
220 
221  // The encoder that maps a unichar-id to a sequence of small codes.
222  // encoder_ is the only part that is serialized. The rest is computed on load.
224  // Decoder converts the output of encoder back to a unichar-id.
225  std::unordered_map<RecodedCharID, int, RecodedCharID::RecodedCharIDHash>
226  decoder_;
227  // True if the index is a valid single or start code.
228  GenericVector<bool> is_valid_start_;
229  // Maps a prefix code to a list of valid next codes.
230  // The map owns the vectors.
231  std::unordered_map<RecodedCharID, GenericVectorEqEq<int>*,
233  next_codes_;
234  // Maps a prefix code to a list of valid final codes.
235  // The map owns the vectors.
236  std::unordered_map<RecodedCharID, GenericVectorEqEq<int>*,
238  final_codes_;
239  // Max of any value in encoder_ + 1.
240  int code_range_;
241 };
242 
243 } // namespace tesseract.
244 
245 #endif // TESSERACT_CCUTIL_UNICHARCOMPRESS_H_
const GenericVector< int > * GetFinalCodes(const RecodedCharID &code) const
int FWrite(const void *buffer, int size, int count)
Definition: serialis.cpp:148
bool DeSerialize(TFile *fp)
bool operator==(const RecodedCharID &other) const
int operator()(int index) const
static const int kMaxCodeLen
int8_t inT8
Definition: host.h:34
size_t operator()(const RecodedCharID &code) const
Definition: strngs.h:45
int32_t inT32
Definition: host.h:38
void Set(int index, int value)
void Truncate(int length)
const GenericVector< int > * GetNextCodes(const RecodedCharID &code) const
int FReadEndian(void *buffer, int size, int count)
Definition: serialis.cpp:97
void Set3(int code0, int code1, int code2)
bool Serialize(TFile *fp) const
bool IsValidFirstCode(int code) const
int FRead(void *buffer, int size, int count)
Definition: serialis.cpp:108