tesseract  4.0.0-1-g2a2b
lstmtester.cpp
Go to the documentation of this file.
1 // File: lstmtester.cpp
3 // Description: Top-level line evaluation class for LSTM-based networks.
4 // Author: Ray Smith
5 // Created: Wed Nov 23 11:18:06 PST 2016
6 //
7 // (C) Copyright 2016, 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.
18 
19 #include "lstmtester.h"
20 #include "genericvector.h"
21 
22 namespace tesseract {
23 
24 LSTMTester::LSTMTester(int64_t max_memory)
25  : test_data_(max_memory), total_pages_(0), async_running_(false) {}
26 
27 // Loads a set of lstmf files that were created using the lstm.train config to
28 // tesseract into memory ready for testing. Returns false if nothing was
29 // loaded. The arg is a filename of a file that lists the filenames.
30 bool LSTMTester::LoadAllEvalData(const STRING& filenames_file) {
31  GenericVector<STRING> filenames;
32  if (!LoadFileLinesToStrings(filenames_file, &filenames)) {
33  tprintf("Failed to load list of eval filenames from %s\n",
34  filenames_file.string());
35  return false;
36  }
37  return LoadAllEvalData(filenames);
38 }
39 
40 // Loads a set of lstmf files that were created using the lstm.train config to
41 // tesseract into memory ready for testing. Returns false if nothing was
42 // loaded.
44  test_data_.Clear();
45  bool result = test_data_.LoadDocuments(filenames, CS_SEQUENTIAL, nullptr);
46  total_pages_ = test_data_.TotalPages();
47  return result;
48 }
49 
50 // Runs an evaluation asynchronously on the stored data and returns a string
51 // describing the results of the previous test.
52 STRING LSTMTester::RunEvalAsync(int iteration, const double* training_errors,
53  const TessdataManager& model_mgr,
54  int training_stage) {
55  STRING result;
56  if (total_pages_ == 0) {
57  result.add_str_int("No test data at iteration", iteration);
58  return result;
59  }
60  if (!LockIfNotRunning()) {
61  result.add_str_int("Previous test incomplete, skipping test at iteration",
62  iteration);
63  return result;
64  }
65  // Save the args.
66  STRING prev_result = test_result_;
67  test_result_ = "";
68  if (training_errors != nullptr) {
69  test_iteration_ = iteration;
70  test_training_errors_ = training_errors;
71  test_model_mgr_ = model_mgr;
72  test_training_stage_ = training_stage;
73  SVSync::StartThread(&LSTMTester::ThreadFunc, this);
74  } else {
75  UnlockRunning();
76  }
77  return prev_result;
78 }
79 
80 // Runs an evaluation synchronously on the stored data and returns a string
81 // describing the results.
82 STRING LSTMTester::RunEvalSync(int iteration, const double* training_errors,
83  const TessdataManager& model_mgr,
84  int training_stage, int verbosity) {
85  LSTMTrainer trainer;
86  trainer.InitCharSet(model_mgr);
87  TFile fp;
88  if (!model_mgr.GetComponent(TESSDATA_LSTM, &fp) ||
89  !trainer.DeSerialize(&model_mgr, &fp)) {
90  return "Deserialize failed";
91  }
92  int eval_iteration = 0;
93  double char_error = 0.0;
94  double word_error = 0.0;
95  int error_count = 0;
96  while (error_count < total_pages_) {
97  const ImageData* trainingdata = test_data_.GetPageBySerial(eval_iteration);
98  trainer.SetIteration(++eval_iteration);
99  NetworkIO fwd_outputs, targets;
100  Trainability result =
101  trainer.PrepareForBackward(trainingdata, &fwd_outputs, &targets);
102  if (result != UNENCODABLE) {
103  char_error += trainer.NewSingleError(tesseract::ET_CHAR_ERROR);
104  word_error += trainer.NewSingleError(tesseract::ET_WORD_RECERR);
105  ++error_count;
106  if (verbosity > 1 || (verbosity > 0 && result != PERFECT)) {
107  tprintf("Truth:%s\n", trainingdata->transcription().string());
108  GenericVector<int> ocr_labels;
109  GenericVector<int> xcoords;
110  trainer.LabelsFromOutputs(fwd_outputs, &ocr_labels, &xcoords);
111  STRING ocr_text = trainer.DecodeLabels(ocr_labels);
112  tprintf("OCR :%s\n", ocr_text.string());
113  }
114  }
115  }
116  char_error *= 100.0 / total_pages_;
117  word_error *= 100.0 / total_pages_;
118  STRING result;
119  result.add_str_int("At iteration ", iteration);
120  result.add_str_int(", stage ", training_stage);
121  result.add_str_double(", Eval Char error rate=", char_error);
122  result.add_str_double(", Word error rate=", word_error);
123  return result;
124 }
125 
126 // Static helper thread function for RunEvalAsync, with a specific signature
127 // required by SVSync::StartThread. Actually a member function pretending to
128 // be static, its arg is a this pointer that it will cast back to LSTMTester*
129 // to call RunEvalSync using the stored args that RunEvalAsync saves in *this.
130 // LockIfNotRunning must have returned true before calling ThreadFunc, and
131 // it will call UnlockRunning to release the lock after RunEvalSync completes.
132 /* static */
133 void* LSTMTester::ThreadFunc(void* lstmtester_void) {
134  LSTMTester* lstmtester = static_cast<LSTMTester*>(lstmtester_void);
135  lstmtester->test_result_ = lstmtester->RunEvalSync(
136  lstmtester->test_iteration_, lstmtester->test_training_errors_,
137  lstmtester->test_model_mgr_, lstmtester->test_training_stage_,
138  /*verbosity*/ 0);
139  lstmtester->UnlockRunning();
140  return lstmtester_void;
141 }
142 
143 // Returns true if there is currently nothing running, and takes the lock
144 // if there is nothing running.
145 bool LSTMTester::LockIfNotRunning() {
146  SVAutoLock lock(&running_mutex_);
147  if (async_running_) return false;
148  async_running_ = true;
149  return true;
150 }
151 
152 // Releases the running lock.
153 void LSTMTester::UnlockRunning() {
154  SVAutoLock lock(&running_mutex_);
155  async_running_ = false;
156 }
157 
158 } // namespace tesseract
void InitCharSet(const std::string &traineddata_path)
Definition: lstmtrainer.h:109
bool GetComponent(TessdataType type, TFile *fp)
static void StartThread(void *(*func)(void *), void *arg)
Create new thread.
Definition: svutil.cpp:87
const char * string() const
Definition: strngs.cpp:196
STRING DecodeLabels(const GenericVector< int > &labels)
void SetIteration(int iteration)
const ImageData * GetPageBySerial(int serial)
Definition: imagedata.h:337
bool LoadAllEvalData(const STRING &filenames_file)
Definition: lstmtester.cpp:30
Trainability PrepareForBackward(const ImageData *trainingdata, NetworkIO *fwd_outputs, NetworkIO *targets)
LSTMTester(int64_t max_memory)
Definition: lstmtester.cpp:24
void add_str_double(const char *str, double number)
Definition: strngs.cpp:389
const STRING & transcription() const
Definition: imagedata.h:147
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
STRING RunEvalSync(int iteration, const double *training_errors, const TessdataManager &model_mgr, int training_stage, int verbosity)
Definition: lstmtester.cpp:82
double NewSingleError(ErrorTypes type) const
Definition: lstmtrainer.h:154
void add_str_int(const char *str, int number)
Definition: strngs.cpp:379
STRING RunEvalAsync(int iteration, const double *training_errors, const TessdataManager &model_mgr, int training_stage)
Definition: lstmtester.cpp:52
bool LoadFileLinesToStrings(const STRING &filename, GenericVector< STRING > *lines)
bool LoadDocuments(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, FileReader reader)
Definition: imagedata.cpp:572
Definition: strngs.h:45
bool DeSerialize(const TessdataManager *mgr, TFile *fp)
void LabelsFromOutputs(const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)