Coverage Report

Created: 2026-10-28 06:29

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