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