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