tesseract  4.0.0-1-g2a2b
unicharcompress.cpp
Go to the documentation of this file.
1 // File: unicharcompress.cpp
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 #include "unicharcompress.h"
23 #include <algorithm>
24 #include <memory>
25 #include "tprintf.h"
26 
27 namespace tesseract {
28 
29 // String used to represent the null_id in direct_set.
30 const char* kNullChar = "<nul>";
31 // Radix to make unique values from the stored radical codes.
32 const int kRadicalRadix = 29;
33 
34 // "Hash" function for const std::vector<int> computes the sum of elements.
35 // Build a unique number for each code sequence that we can use as the index in
36 // a hash map of ints instead of trying to hash the vectors.
37 static int RadicalPreHash(const std::vector<int>& rs) {
38  size_t result = 0;
39  for (int radical : rs) {
40  result *= kRadicalRadix;
41  result += radical;
42  }
43  return result;
44 }
45 
46 // A hash map to convert unicodes to radical encoding.
47 using RSMap = std::unordered_map<int, std::unique_ptr<std::vector<int>>>;
48 // A hash map to count occurrences of each radical encoding.
49 using RSCounts = std::unordered_map<int, int>;
50 
51 static bool DecodeRadicalLine(STRING* radical_data_line, RSMap* radical_map) {
52  if (radical_data_line->length() == 0 || (*radical_data_line)[0] == '#')
53  return true;
54  GenericVector<STRING> entries;
55  radical_data_line->split(' ', &entries);
56  if (entries.size() < 2) return false;
57  char* end = nullptr;
58  int unicode = strtol(&entries[0][0], &end, 10);
59  if (*end != '\0') return false;
60  std::unique_ptr<std::vector<int>> radicals(new std::vector<int>);
61  for (int i = 1; i < entries.size(); ++i) {
62  int radical = strtol(&entries[i][0], &end, 10);
63  if (*end != '\0') return false;
64  radicals->push_back(radical);
65  }
66  (*radical_map)[unicode] = std::move(radicals);
67  return true;
68 }
69 
70 // Helper function builds the RSMap from the radical-stroke file, which has
71 // already been read into a STRING. Returns false on error.
72 // The radical_stroke_table is non-const because it gets split and the caller
73 // is unlikely to want to use it again.
74 static bool DecodeRadicalTable(STRING* radical_data, RSMap* radical_map) {
76  radical_data->split('\n', &lines);
77  for (int i = 0; i < lines.size(); ++i) {
78  if (!DecodeRadicalLine(&lines[i], radical_map)) {
79  tprintf("Invalid format in radical table at line %d: %s\n", i,
80  lines[i].string());
81  return false;
82  }
83  }
84  return true;
85 }
86 
87 UnicharCompress::UnicharCompress() : code_range_(0) {}
91  Cleanup();
92  encoder_ = src.encoder_;
93  code_range_ = src.code_range_;
94  SetupDecoder();
95  return *this;
96 }
97 
98 // Computes the encoding for the given unicharset. It is a requirement that
99 // the file training/langdata/radical-stroke.txt have been read into the
100 // input string radical_stroke_table.
101 // Returns false if the encoding cannot be constructed.
102 bool UnicharCompress::ComputeEncoding(const UNICHARSET& unicharset, int null_id,
103  STRING* radical_stroke_table) {
104  RSMap radical_map;
105  if (radical_stroke_table != nullptr &&
106  !DecodeRadicalTable(radical_stroke_table, &radical_map))
107  return false;
108  encoder_.clear();
109  UNICHARSET direct_set;
110  // To avoid unused codes, clear the special codes from the direct_set.
111  direct_set.clear();
112  // Always keep space as 0;
113  direct_set.unichar_insert(" ", OldUncleanUnichars::kTrue);
114  // Null char is next if we have one.
115  if (null_id >= 0) {
116  direct_set.unichar_insert(kNullChar);
117  }
118  RSCounts radical_counts;
119  // In the initial map, codes [0, unicharset.size()) are
120  // reserved for non-han/hangul sequences of 1 or more unicodes.
121  int hangul_offset = unicharset.size();
122  // Hangul takes the next range [hangul_offset, hangul_offset + kTotalJamos).
123  const int kTotalJamos = kLCount + kVCount + kTCount;
124  // Han takes the codes beyond hangul_offset + kTotalJamos. Since it is hard
125  // to measure the number of radicals and strokes, initially we use the same
126  // code range for all 3 Han code positions, and fix them after.
127  int han_offset = hangul_offset + kTotalJamos;
128  for (int u = 0; u <= unicharset.size(); ++u) {
129  // We special-case allow null_id to be equal to unicharset.size() in case
130  // there is no space in unicharset for it.
131  if (u == unicharset.size() && u != null_id) break; // Finished
132  RecodedCharID code;
133  // Convert to unicodes.
134  std::vector<char32> unicodes;
135  std::string cleaned;
136  if (u < unicharset.size())
137  cleaned = UNICHARSET::CleanupString(unicharset.id_to_unichar(u));
138  if (u < unicharset.size() &&
139  (unicodes = UNICHAR::UTF8ToUTF32(cleaned.c_str())).size() == 1) {
140  // Check single unicodes for Hangul/Han and encode if so.
141  int unicode = unicodes[0];
142  int leading, vowel, trailing;
143  auto it = radical_map.find(unicode);
144  if (it != radical_map.end()) {
145  // This is Han. Use the radical codes directly.
146  int num_radicals = it->second->size();
147  for (int c = 0; c < num_radicals; ++c) {
148  code.Set(c, han_offset + (*it->second)[c]);
149  }
150  int pre_hash = RadicalPreHash(*it->second);
151  int num_samples = radical_counts[pre_hash]++;
152  if (num_samples > 0)
153  code.Set(num_radicals, han_offset + num_samples + kRadicalRadix);
154  } else if (DecomposeHangul(unicode, &leading, &vowel, &trailing)) {
155  // This is Hangul. Since we know the exact size of each part at compile
156  // time, it gets the bottom set of codes.
157  code.Set3(leading + hangul_offset, vowel + kLCount + hangul_offset,
158  trailing + kLCount + kVCount + hangul_offset);
159  }
160  }
161  // If the code is still empty, it wasn't Han or Hangul.
162  if (code.length() == 0) {
163  // Special cases.
164  if (u == UNICHAR_SPACE) {
165  code.Set(0, 0); // Space.
166  } else if (u == null_id || (unicharset.has_special_codes() &&
168  code.Set(0, direct_set.unichar_to_id(kNullChar));
169  } else {
170  // Add the direct_set unichar-ids of the unicodes in sequence to the
171  // code.
172  for (int i = 0; i < unicodes.size(); ++i) {
173  int position = code.length();
174  if (position >= RecodedCharID::kMaxCodeLen) {
175  tprintf("Unichar %d=%s is too long to encode!!\n", u,
176  unicharset.id_to_unichar(u));
177  return false;
178  }
179  int uni = unicodes[i];
180  UNICHAR unichar(uni);
181  char* utf8 = unichar.utf8_str();
182  if (!direct_set.contains_unichar(utf8))
183  direct_set.unichar_insert(utf8);
184  code.Set(position, direct_set.unichar_to_id(utf8));
185  delete[] utf8;
186  if (direct_set.size() >
187  unicharset.size() + !unicharset.has_special_codes()) {
188  // Code space got bigger!
189  tprintf("Code space expanded from original unicharset!!\n");
190  return false;
191  }
192  }
193  }
194  }
195  encoder_.push_back(code);
196  }
197  // Now renumber Han to make all codes unique. We already added han_offset to
198  // all Han. Now separate out the radical, stroke, and count codes for Han.
199  int code_offset = 0;
200  for (int i = 0; i < RecodedCharID::kMaxCodeLen; ++i) {
201  int max_offset = 0;
202  for (int u = 0; u < unicharset.size(); ++u) {
203  RecodedCharID* code = &encoder_[u];
204  if (code->length() <= i) continue;
205  max_offset = std::max(max_offset, (*code)(i)-han_offset);
206  code->Set(i, (*code)(i) + code_offset);
207  }
208  if (max_offset == 0) break;
209  code_offset += max_offset + 1;
210  }
211  DefragmentCodeValues(null_id >= 0 ? 1 : -1);
212  SetupDecoder();
213  return true;
214 }
215 
216 // Sets up an encoder that doesn't change the unichars at all, so it just
217 // passes them through unchanged.
220  for (int u = 0; u < unicharset.size(); ++u) {
221  RecodedCharID code;
222  code.Set(0, u);
223  codes.push_back(code);
224  }
225  if (!unicharset.has_special_codes()) {
226  RecodedCharID code;
227  code.Set(0, unicharset.size());
228  codes.push_back(code);
229  }
230  SetupDirect(codes);
231 }
232 
233 // Sets up an encoder directly using the given encoding vector, which maps
234 // unichar_ids to the given codes.
236  encoder_ = codes;
237  ComputeCodeRange();
238  SetupDecoder();
239 }
240 
241 // Renumbers codes to eliminate unused values.
242 void UnicharCompress::DefragmentCodeValues(int encoded_null) {
243  // There may not be any Hangul, but even if there is, it is possible that not
244  // all codes are used. Likewise with the Han encoding, it is possible that not
245  // all numbers of strokes are used.
246  ComputeCodeRange();
247  GenericVector<int> offsets;
248  offsets.init_to_size(code_range_, 0);
249  // Find which codes are used
250  for (int c = 0; c < encoder_.size(); ++c) {
251  const RecodedCharID& code = encoder_[c];
252  for (int i = 0; i < code.length(); ++i) {
253  offsets[code(i)] = 1;
254  }
255  }
256  // Compute offsets based on code use.
257  int offset = 0;
258  for (int i = 0; i < offsets.size(); ++i) {
259  // If not used, decrement everything above here.
260  // We are moving encoded_null to the end, so it is not "used".
261  if (offsets[i] == 0 || i == encoded_null) {
262  --offset;
263  } else {
264  offsets[i] = offset;
265  }
266  }
267  if (encoded_null >= 0) {
268  // The encoded_null is moving to the end, for the benefit of TensorFlow,
269  // which is offsets.size() + offsets.back().
270  offsets[encoded_null] = offsets.size() + offsets.back() - encoded_null;
271  }
272  // Now apply the offsets.
273  for (int c = 0; c < encoder_.size(); ++c) {
274  RecodedCharID* code = &encoder_[c];
275  for (int i = 0; i < code->length(); ++i) {
276  int value = (*code)(i);
277  code->Set(i, value + offsets[value]);
278  }
279  }
280  ComputeCodeRange();
281 }
282 
283 // Encodes a single unichar_id. Returns the length of the code, or zero if
284 // invalid input, and the encoding itself
285 int UnicharCompress::EncodeUnichar(int unichar_id, RecodedCharID* code) const {
286  if (unichar_id < 0 || unichar_id >= encoder_.size()) return 0;
287  *code = encoder_[unichar_id];
288  return code->length();
289 }
290 
291 // Decodes code, returning the original unichar-id, or
292 // INVALID_UNICHAR_ID if the input is invalid.
294  int len = code.length();
295  if (len <= 0 || len > RecodedCharID::kMaxCodeLen) return INVALID_UNICHAR_ID;
296  auto it = decoder_.find(code);
297  if (it == decoder_.end()) return INVALID_UNICHAR_ID;
298  return it->second;
299 }
300 
301 // Writes to the given file. Returns false in case of error.
303  return encoder_.SerializeClasses(fp);
304 }
305 
306 // Reads from the given file. Returns false in case of error.
308  if (!encoder_.DeSerializeClasses(fp)) return false;
309  ComputeCodeRange();
310  SetupDecoder();
311  return true;
312 }
313 
314 // Returns a STRING containing a text file that describes the encoding thus:
315 // <index>[,<index>]*<tab><UTF8-str><newline>
316 // In words, a comma-separated list of one or more indices, followed by a tab
317 // and the UTF-8 string that the code represents per line. Most simple scripts
318 // will encode a single index to a UTF8-string, but Chinese, Japanese, Korean
319 // and the Indic scripts will contain a many-to-many mapping.
320 // See the class comment above for details.
322  const UNICHARSET& unicharset) const {
323  STRING encoding;
324  for (int c = 0; c < encoder_.size(); ++c) {
325  const RecodedCharID& code = encoder_[c];
326  if (0 < c && c < SPECIAL_UNICHAR_CODES_COUNT && code == encoder_[c - 1]) {
327  // Don't show the duplicate entry.
328  continue;
329  }
330  encoding.add_str_int("", code(0));
331  for (int i = 1; i < code.length(); ++i) {
332  encoding.add_str_int(",", code(i));
333  }
334  encoding += "\t";
335  if (c >= unicharset.size() || (0 < c && c < SPECIAL_UNICHAR_CODES_COUNT &&
336  unicharset.has_special_codes())) {
337  encoding += kNullChar;
338  } else {
339  encoding += unicharset.id_to_unichar(c);
340  }
341  encoding += "\n";
342  }
343  return encoding;
344 }
345 
346 // Helper decomposes a Hangul unicode to 3 parts, leading, vowel, trailing.
347 // Note that the returned values are 0-based indices, NOT unicode Jamo.
348 // Returns false if the input is not in the Hangul unicode range.
349 /* static */
350 bool UnicharCompress::DecomposeHangul(int unicode, int* leading, int* vowel,
351  int* trailing) {
352  if (unicode < kFirstHangul) return false;
353  int offset = unicode - kFirstHangul;
354  if (offset >= kNumHangul) return false;
355  const int kNCount = kVCount * kTCount;
356  *leading = offset / kNCount;
357  *vowel = (offset % kNCount) / kTCount;
358  *trailing = offset % kTCount;
359  return true;
360 }
361 
362 // Computes the value of code_range_ from the encoder_.
363 void UnicharCompress::ComputeCodeRange() {
364  code_range_ = -1;
365  for (int c = 0; c < encoder_.size(); ++c) {
366  const RecodedCharID& code = encoder_[c];
367  for (int i = 0; i < code.length(); ++i) {
368  if (code(i) > code_range_) code_range_ = code(i);
369  }
370  }
371  ++code_range_;
372 }
373 
374 // Initializes the decoding hash_map from the encoding array.
375 void UnicharCompress::SetupDecoder() {
376  Cleanup();
377  is_valid_start_.init_to_size(code_range_, false);
378  for (int c = 0; c < encoder_.size(); ++c) {
379  const RecodedCharID& code = encoder_[c];
380  decoder_[code] = c;
381  is_valid_start_[code(0)] = true;
382  RecodedCharID prefix = code;
383  int len = code.length() - 1;
384  prefix.Truncate(len);
385  auto final_it = final_codes_.find(prefix);
386  if (final_it == final_codes_.end()) {
388  code_list->push_back(code(len));
389  final_codes_[prefix] = code_list;
390  while (--len >= 0) {
391  prefix.Truncate(len);
392  auto next_it = next_codes_.find(prefix);
393  if (next_it == next_codes_.end()) {
395  code_list->push_back(code(len));
396  next_codes_[prefix] = code_list;
397  } else {
398  // We still have to search the list as we may get here via multiple
399  // lengths of code.
400  if (!next_it->second->contains(code(len)))
401  next_it->second->push_back(code(len));
402  break; // This prefix has been processed.
403  }
404  }
405  } else {
406  if (!final_it->second->contains(code(len)))
407  final_it->second->push_back(code(len));
408  }
409  }
410 }
411 
412 // Frees allocated memory.
413 void UnicharCompress::Cleanup() {
414  decoder_.clear();
415  is_valid_start_.clear();
416  for (auto it = next_codes_.begin(); it != next_codes_.end(); ++it) {
417  delete it->second;
418  }
419  for (auto it = final_codes_.begin(); it != final_codes_.end(); ++it) {
420  delete it->second;
421  }
422  next_codes_.clear();
423  final_codes_.clear();
424 }
425 
426 } // namespace tesseract.
static const int kMaxCodeLen
int size() const
Definition: genericvector.h:71
int DecodeUnichar(const RecodedCharID &code) const
int EncodeUnichar(int unichar_id, RecodedCharID *code) const
void SetupDirect(const GenericVector< RecodedCharID > &codes)
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:209
T & back() const
bool ComputeEncoding(const UNICHARSET &unicharset, int null_id, STRING *radical_stroke_table)
void Set(int index, int value)
int size() const
Definition: unicharset.h:336
const int kRadicalRadix
void unichar_insert(const char *const unichar_repr, OldUncleanUnichars old_style)
Definition: unicharset.cpp:625
UnicharCompress & operator=(const UnicharCompress &src)
static const int kFirstHangul
void split(const char c, GenericVector< STRING > *splited)
Definition: strngs.cpp:284
STRING GetEncodingAsString(const UNICHARSET &unicharset) const
bool contains_unichar(const char *const unichar_repr) const
Definition: unicharset.cpp:670
void init_to_size(int size, const T &t)
char * utf8_str() const
Definition: unichar.cpp:127
int length() const
Definition: genericvector.h:85
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
const char * kNullChar
std::unordered_map< int, int > RSCounts
void SetupPassThrough(const UNICHARSET &unicharset)
static std::string CleanupString(const char *utf8_str)
Definition: unicharset.h:241
int push_back(T object)
static std::vector< char32 > UTF8ToUTF32(const char *utf8_str)
Definition: unichar.cpp:213
void add_str_int(const char *str, int number)
Definition: strngs.cpp:379
static bool DecomposeHangul(int unicode, int *leading, int *vowel, int *trailing)
Definition: strngs.h:45
const char * id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:290
void clear()
Definition: unicharset.h:301
std::unordered_map< int, std::unique_ptr< std::vector< int > >> RSMap
bool has_special_codes() const
Definition: unicharset.h:717
int32_t length() const
Definition: strngs.cpp:191
bool Serialize(TFile *fp) const
void Set3(int code0, int code1, int code2)