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