tesseract  4.0.0-1-g2a2b
boxread.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: boxread.cpp
3  * Description: Read data from a box file.
4  * Author: Ray Smith
5  * Created: Fri Aug 24 17:47:23 PDT 2007
6  *
7  * (C) Copyright 2007, Google Inc.
8  ** Licensed under the Apache License, Version 2.0 (the "License");
9  ** you may not use this file except in compliance with the License.
10  ** You may obtain a copy of the License at
11  ** http://www.apache.org/licenses/LICENSE-2.0
12  ** Unless required by applicable law or agreed to in writing, software
13  ** distributed under the License is distributed on an "AS IS" BASIS,
14  ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  ** See the License for the specific language governing permissions and
16  ** limitations under the License.
17  *
18  **********************************************************************/
19 
20 #include "boxread.h"
21 #include <cstring> // for strchr, strcmp, strrchr
22 #include "errcode.h" // for ERRCODE, TESSEXIT
23 #include "fileerr.h" // for CANTOPENFILE
24 #include "genericvector.h" // for GenericVector
25 #include "helpers.h" // for chomp_string
26 #include "rect.h" // for TBOX
27 #include "strngs.h" // for STRING
28 #include "tprintf.h" // for tprintf
29 #include "unichar.h" // for UNICHAR
30 
31 // Special char code used to identify multi-blob labels.
32 static const char* kMultiBlobLabelCode = "WordStr";
33 
34 // Open the boxfile based on the given image filename.
35 FILE* OpenBoxFile(const STRING& fname) {
36  STRING filename = BoxFileName(fname);
37  FILE* box_file = nullptr;
38  if (!(box_file = fopen(filename.string(), "rb"))) {
39  CANTOPENFILE.error("read_next_box", TESSEXIT, "Can't open box file %s",
40  filename.string());
41  }
42  return box_file;
43 }
44 
45 // Reads all boxes from the given filename.
46 // Reads a specific target_page number if >= 0, or all pages otherwise.
47 // Skips blanks if skip_blanks is true.
48 // The UTF-8 label of the box is put in texts, and the full box definition as
49 // a string is put in box_texts, with the corresponding page number in pages.
50 // Each of the output vectors is optional (may be nullptr).
51 // Returns false if no boxes are found.
52 bool ReadAllBoxes(int target_page, bool skip_blanks, const STRING& filename,
53  GenericVector<TBOX>* boxes,
54  GenericVector<STRING>* texts,
55  GenericVector<STRING>* box_texts,
56  GenericVector<int>* pages) {
57  GenericVector<char> box_data;
58  if (!tesseract::LoadDataFromFile(BoxFileName(filename), &box_data))
59  return false;
60  // Convert the array of bytes to a string, so it can be used by the parser.
61  box_data.push_back('\0');
62  return ReadMemBoxes(target_page, skip_blanks, &box_data[0],
63  /*continue_on_failure*/ true, boxes, texts, box_texts,
64  pages);
65 }
66 
67 // Reads all boxes from the string. Otherwise, as ReadAllBoxes.
68 bool ReadMemBoxes(int target_page, bool skip_blanks, const char* box_data,
69  bool continue_on_failure,
70  GenericVector<TBOX>* boxes,
71  GenericVector<STRING>* texts,
72  GenericVector<STRING>* box_texts,
73  GenericVector<int>* pages) {
74  STRING box_str(box_data);
76  box_str.split('\n', &lines);
77  if (lines.empty()) return false;
78  int num_boxes = 0;
79  for (int i = 0; i < lines.size(); ++i) {
80  int page = 0;
81  STRING utf8_str;
82  TBOX box;
83  if (!ParseBoxFileStr(lines[i].string(), &page, &utf8_str, &box)) {
84  if (continue_on_failure)
85  continue;
86  else
87  return false;
88  }
89  if (skip_blanks && (utf8_str == " " || utf8_str == "\t")) continue;
90  if (target_page >= 0 && page != target_page) continue;
91  if (boxes != nullptr) boxes->push_back(box);
92  if (texts != nullptr) texts->push_back(utf8_str);
93  if (box_texts != nullptr) {
94  STRING full_text;
95  MakeBoxFileStr(utf8_str.string(), box, target_page, &full_text);
96  box_texts->push_back(full_text);
97  }
98  if (pages != nullptr) pages->push_back(page);
99  ++num_boxes;
100  }
101  return num_boxes > 0;
102 }
103 
104 // Returns the box file name corresponding to the given image_filename.
105 STRING BoxFileName(const STRING& image_filename) {
106  STRING box_filename = image_filename;
107  const char *lastdot = strrchr(box_filename.string(), '.');
108  if (lastdot != nullptr)
109  box_filename.truncate_at(lastdot - box_filename.string());
110 
111  box_filename += ".box";
112  return box_filename;
113 }
114 
115 // TODO(rays) convert all uses of ReadNextBox to use the new ReadAllBoxes.
116 // Box files are used ONLY DURING TRAINING, but by both processes of
117 // creating tr files with tesseract, and unicharset_extractor.
118 // ReadNextBox factors out the code to interpret a line of a box
119 // file so that applybox and unicharset_extractor interpret the same way.
120 // This function returns the next valid box file utf8 string and coords
121 // and returns true, or false on eof (and closes the file).
122 // It ignores the utf8 file signature ByteOrderMark (U+FEFF=EF BB BF), checks
123 // for valid utf-8 and allows space or tab between fields.
124 // utf8_str is set with the unichar string, and bounding box with the box.
125 // If there are page numbers in the file, it reads them all.
126 bool ReadNextBox(int *line_number, FILE* box_file,
127  STRING* utf8_str, TBOX* bounding_box) {
128  return ReadNextBox(-1, line_number, box_file, utf8_str, bounding_box);
129 }
130 
131 // As ReadNextBox above, but get a specific page number. (0-based)
132 // Use -1 to read any page number. Files without page number all
133 // read as if they are page 0.
134 bool ReadNextBox(int target_page, int *line_number, FILE* box_file,
135  STRING* utf8_str, TBOX* bounding_box) {
136  int page = 0;
137  char buff[kBoxReadBufSize]; // boxfile read buffer
138  char *buffptr = buff;
139 
140  while (fgets(buff, sizeof(buff) - 1, box_file)) {
141  (*line_number)++;
142 
143  buffptr = buff;
144  const unsigned char *ubuf = reinterpret_cast<const unsigned char*>(buffptr);
145  if (ubuf[0] == 0xef && ubuf[1] == 0xbb && ubuf[2] == 0xbf)
146  buffptr += 3; // Skip unicode file designation.
147  // Check for blank lines in box file
148  if (*buffptr == '\n' || *buffptr == '\0') continue;
149  // Skip blank boxes.
150  if (*buffptr == ' ' || *buffptr == '\t') continue;
151  if (*buffptr != '\0') {
152  if (!ParseBoxFileStr(buffptr, &page, utf8_str, bounding_box)) {
153  tprintf("Box file format error on line %i; ignored\n", *line_number);
154  continue;
155  }
156  if (target_page >= 0 && target_page != page)
157  continue; // Not on the appropriate page.
158  return true; // Successfully read a box.
159  }
160  }
161  fclose(box_file);
162  return false; // EOF
163 }
164 
165 // Parses the given box file string into a page_number, utf8_str, and
166 // bounding_box. Returns true on a successful parse.
167 // The box file is assumed to contain box definitions, one per line, of the
168 // following format for blob-level boxes:
169 // <UTF8 str> <left> <bottom> <right> <top> <page id>
170 // and for word/line-level boxes:
171 // WordStr <left> <bottom> <right> <top> <page id> #<space-delimited word str>
172 // See applyybox.cpp for more information.
173 bool ParseBoxFileStr(const char* boxfile_str, int* page_number,
174  STRING* utf8_str, TBOX* bounding_box) {
175  *bounding_box = TBOX(); // Initialize it to empty.
176  *utf8_str = "";
177  char uch[kBoxReadBufSize];
178  const char *buffptr = boxfile_str;
179  // Read the unichar without messing up on Tibetan.
180  // According to issue 253 the utf-8 surrogates 85 and A0 are treated
181  // as whitespace by sscanf, so it is more reliable to just find
182  // ascii space and tab.
183  int uch_len = 0;
184  // Skip unicode file designation, if present.
185  const unsigned char *ubuf = reinterpret_cast<const unsigned char*>(buffptr);
186  if (ubuf[0] == 0xef && ubuf[1] == 0xbb && ubuf[2] == 0xbf)
187  buffptr += 3;
188  // Allow a single blank as the UTF-8 string. Check for empty string and
189  // then blindly eat the first character.
190  if (*buffptr == '\0') return false;
191  do {
192  uch[uch_len++] = *buffptr++;
193  } while (*buffptr != '\0' && *buffptr != ' ' && *buffptr != '\t' &&
194  uch_len < kBoxReadBufSize - 1);
195  uch[uch_len] = '\0';
196  if (*buffptr != '\0') ++buffptr;
197  int x_min, y_min, x_max, y_max;
198  *page_number = 0;
199  int count = sscanf(buffptr, "%d %d %d %d %d",
200  &x_min, &y_min, &x_max, &y_max, page_number);
201  if (count != 5 && count != 4) {
202  tprintf("Bad box coordinates in boxfile string! %s\n", ubuf);
203  return false;
204  }
205  // Test for long space-delimited string label.
206  if (strcmp(uch, kMultiBlobLabelCode) == 0 &&
207  (buffptr = strchr(buffptr, '#')) != nullptr) {
208  strncpy(uch, buffptr + 1, kBoxReadBufSize - 1);
209  uch[kBoxReadBufSize - 1] = '\0'; // Prevent buffer overrun.
210  chomp_string(uch);
211  uch_len = strlen(uch);
212  }
213  // Validate UTF8 by making unichars with it.
214  int used = 0;
215  while (used < uch_len) {
216  tesseract::UNICHAR ch(uch + used, uch_len - used);
217  int new_used = ch.utf8_len();
218  if (new_used == 0) {
219  tprintf("Bad UTF-8 str %s starts with 0x%02x at col %d\n",
220  uch + used, uch[used], used + 1);
221  return false;
222  }
223  used += new_used;
224  }
225  *utf8_str = uch;
226  if (x_min > x_max) Swap(&x_min, &x_max);
227  if (y_min > y_max) Swap(&y_min, &y_max);
228  bounding_box->set_to_given_coords(x_min, y_min, x_max, y_max);
229  return true; // Successfully read a box.
230 }
231 
232 // Creates a box file string from a unichar string, TBOX and page number.
233 void MakeBoxFileStr(const char* unichar_str, const TBOX& box, int page_num,
234  STRING* box_str) {
235  *box_str = unichar_str;
236  box_str->add_str_int(" ", box.left());
237  box_str->add_str_int(" ", box.bottom());
238  box_str->add_str_int(" ", box.right());
239  box_str->add_str_int(" ", box.top());
240  box_str->add_str_int(" ", page_num);
241 }
int size() const
Definition: genericvector.h:71
void Swap(T *p1, T *p2)
Definition: helpers.h:98
const char * string() const
Definition: strngs.cpp:196
int count(LIST var_list)
Definition: oldlist.cpp:98
FILE * OpenBoxFile(const STRING &fname)
Definition: boxread.cpp:35
const ERRCODE CANTOPENFILE
Definition: fileerr.h:25
Definition: rect.h:34
bool ReadAllBoxes(int target_page, bool skip_blanks, const STRING &filename, GenericVector< TBOX > *boxes, GenericVector< STRING > *texts, GenericVector< STRING > *box_texts, GenericVector< int > *pages)
Definition: boxread.cpp:52
void set_to_given_coords(int x_min, int y_min, int x_max, int y_max)
Definition: rect.h:271
void split(const char c, GenericVector< STRING > *splited)
Definition: strngs.cpp:284
int16_t left() const
Definition: rect.h:72
int16_t top() const
Definition: rect.h:58
void chomp_string(char *str)
Definition: helpers.h:83
bool empty() const
Definition: genericvector.h:90
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
void truncate_at(int32_t index)
Definition: strngs.cpp:267
int utf8_len() const
Definition: unichar.h:78
int push_back(T object)
void add_str_int(const char *str, int number)
Definition: strngs.cpp:379
STRING BoxFileName(const STRING &image_filename)
Definition: boxread.cpp:105
Definition: strngs.h:45
bool ReadNextBox(int *line_number, FILE *box_file, STRING *utf8_str, TBOX *bounding_box)
Definition: boxread.cpp:126
void MakeBoxFileStr(const char *unichar_str, const TBOX &box, int page_num, STRING *box_str)
Definition: boxread.cpp:233
int16_t right() const
Definition: rect.h:79
bool LoadDataFromFile(const char *filename, GenericVector< char > *data)
int16_t bottom() const
Definition: rect.h:65
const int kBoxReadBufSize
Definition: boxread.h:32
bool ReadMemBoxes(int target_page, bool skip_blanks, const char *box_data, bool continue_on_failure, GenericVector< TBOX > *boxes, GenericVector< STRING > *texts, GenericVector< STRING > *box_texts, GenericVector< int > *pages)
Definition: boxread.cpp:68
bool ParseBoxFileStr(const char *boxfile_str, int *page_number, STRING *utf8_str, TBOX *bounding_box)
Definition: boxread.cpp:173
void error(const char *caller, TessErrorLogCode action, const char *format,...) const
Definition: errcode.cpp:37