30 #include "allheaders.h" 56 bool replicate_samples,
58 : norm_mode_(norm_mode), samples_(fontinfo_table_),
59 junk_samples_(fontinfo_table_), verify_samples_(fontinfo_table_),
61 enable_shape_anaylsis_(shape_analysis),
62 enable_replication_(replicate_samples),
63 fragments_(NULL), prev_unichar_id_(-1), debug_level_(debug_level) {
68 for (
int p = 0; p < page_images_.
size(); ++p)
69 pixDestroy(&page_images_[p]);
76 if (fwrite(&norm_mode_,
sizeof(norm_mode_), 1, fp) != 1)
return false;
78 if (!feature_space_.
Serialize(fp))
return false;
79 if (!samples_.
Serialize(fp))
return false;
80 if (!junk_samples_.
Serialize(fp))
return false;
81 if (!verify_samples_.
Serialize(fp))
return false;
82 if (!master_shapes_.
Serialize(fp))
return false;
83 if (!flat_shapes_.
Serialize(fp))
return false;
84 if (!fontinfo_table_.
Serialize(fp))
return false;
85 if (!xheights_.
Serialize(fp))
return false;
92 if (fread(&norm_mode_,
sizeof(norm_mode_), 1, fp) != 1)
return false;
94 ReverseN(&norm_mode_,
sizeof(norm_mode_));
97 charsetsize_ = unicharset_.
size();
98 if (!feature_space_.
DeSerialize(swap, fp))
return false;
99 feature_map_.
Init(feature_space_);
101 if (!junk_samples_.
DeSerialize(swap, fp))
return false;
102 if (!verify_samples_.
DeSerialize(swap, fp))
return false;
103 if (!master_shapes_.
DeSerialize(swap, fp))
return false;
104 if (!flat_shapes_.
DeSerialize(swap, fp))
return false;
105 if (!fontinfo_table_.
DeSerialize(swap, fp))
return false;
106 if (!xheights_.
DeSerialize(swap, fp))
return false;
113 tprintf(
"Failed to load unicharset from file %s\n" 114 "Building unicharset for training from scratch...\n",
122 charsetsize_ = unicharset_.
size();
123 delete [] fragments_;
124 fragments_ =
new int[charsetsize_];
125 memset(fragments_, 0,
sizeof(*fragments_) * charsetsize_);
145 FILE* fp =
Efopen(page_name,
"rb");
147 tprintf(
"Failed to open tr file: %s\n", page_name);
151 while (fgets(buffer,
sizeof(buffer), fp) != NULL) {
152 if (buffer[0] ==
'\n')
155 char* space = strchr(buffer,
' ');
157 tprintf(
"Bad format in tr file, reading fontname, unichar\n");
162 if (font_id < 0) font_id = 0;
167 tprintf(
"Bad format in tr file, reading box coords\n");
172 sample->set_font_id(font_id);
173 sample->set_page_num(page_number + page_images_.
size());
174 sample->set_bounding_box(bounding_box);
175 sample->ExtractCharDesc(int_feature_type, micro_feature_type,
176 cn_feature_type, geo_feature_type, char_desc);
180 charsetsize_ = unicharset_.
size();
190 prev_unichar_id_ = -1;
192 if (prev_unichar_id_ >= 0)
193 fragments_[prev_unichar_id_] = -1;
199 if (prev_unichar_id_ >= 0) {
202 if (fragments_[prev_unichar_id_] == 0)
203 fragments_[prev_unichar_id_] = junk_id;
204 else if (fragments_[prev_unichar_id_] != junk_id)
205 fragments_[prev_unichar_id_] = -1;
209 prev_unichar_id_ = -1;
220 for (page = 0; ; page++) {
221 pix = pixReadFromMultipageTiff(
filename, &offset);
235 if (debug_level_ > 0)
236 tprintf(
"PostLoadCleanup...\n");
237 if (enable_shape_anaylsis_)
238 ReplaceFragmentedSamples();
240 sample_it.
Init(NULL, NULL,
true, &verify_samples_);
249 if (debug_level_ > 0)
250 tprintf(
"ComputeCanonicalSamples...\n");
258 if (debug_level_ > 0)
259 tprintf(
"PreTrainingSetup...\n");
262 if (debug_level_ > 0)
263 tprintf(
"ComputeCloudFeatures...\n");
270 tprintf(
"Building master shape table\n");
271 int num_fonts = samples_.
NumFonts();
278 for (
int f = 0; f < num_fonts; ++f) {
286 if (fragment == NULL)
287 char_shapes.AppendMasterShapes(shapes, NULL);
289 char_shapes_begin_fragment.AppendMasterShapes(shapes, NULL);
291 char_shapes_end_fragment.AppendMasterShapes(shapes, NULL);
293 char_shapes.AppendMasterShapes(shapes, NULL);
297 char_shapes.AppendMasterShapes(char_shapes_begin_fragment, NULL);
300 char_shapes.AppendMasterShapes(char_shapes_end_fragment, NULL);
323 tprintf(
"Moving %d junk samples to master sample set.\n", num_junks);
324 for (
int s = 0; s < num_junks; ++s) {
326 int junk_id =
sample->class_id();
329 if (sample_id == INVALID_UNICHAR_ID)
331 sample->set_class_id(sample_id);
345 if (enable_replication_) {
346 if (debug_level_ > 0)
347 tprintf(
"ReplicateAndRandomize...\n");
359 fprintf(stderr,
"Failed to load font_properties from %s\n",
filename);
362 int italic, bold, fixed, serif, fraktur;
365 char* font_name =
new char[1024];
366 fontinfo.
name = font_name;
369 if (
tfscanf(fp,
"%1024s %i %i %i %i %i\n", font_name, &italic, &bold,
370 &fixed, &serif, &fraktur) != 6) {
380 if (!fontinfo_table_.
contains(fontinfo)) {
393 tprintf(
"fontinfo table is of size %d\n", fontinfo_table_.
size());
398 fprintf(stderr,
"Failed to load font xheights from %s\n",
filename);
407 int total_xheight = 0;
408 int xheight_count = 0;
410 if (
tfscanf(f,
"%1023s %d\n", buffer, &xht) != 2)
413 fontinfo.
name = buffer;
414 if (!fontinfo_table_.
contains(fontinfo))
continue;
415 int fontinfo_id = fontinfo_table_.
get_index(fontinfo);
416 xheights_[fontinfo_id] = xht;
417 total_xheight += xht;
420 if (xheight_count == 0) {
421 fprintf(stderr,
"No valid xheights in %s!\n",
filename);
425 int mean_xheight =
DivRounded(total_xheight, xheight_count);
426 for (
int i = 0; i < fontinfo_table_.
size(); ++i) {
427 if (xheights_[i] < 0)
428 xheights_[i] = mean_xheight;
436 FILE* fontinfo_file = fopen(
filename,
"rb");
437 if (fontinfo_file == NULL)
441 if (fontinfo_id < 0) {
443 fclose(fontinfo_file);
446 tprintf(
"Reading spacing from %s for font %d...\n",
filename, fontinfo_id);
453 int x_gap, x_gap_before, x_gap_after, num_kerned;
458 for (
int l = 0; l < num_unichars; ++l) {
459 if (
tfscanf(fontinfo_file,
"%s %d %d %d",
460 uch, &x_gap_before, &x_gap_after, &num_kerned) != 4) {
462 fclose(fontinfo_file);
471 for (
int k = 0; k < num_kerned; ++k) {
472 if (
tfscanf(fontinfo_file,
"%s %d", kerned_uch, &x_gap) != 2) {
474 fclose(fontinfo_file);
485 fclose(fontinfo_file);
494 fontinfo.
name =
const_cast<char*
>(font_name);
497 return fontinfo_table_.
get_index(fontinfo);
503 int fontinfo_id = -1;
505 for (
int f = 0; f < fontinfo_table_.
size(); ++f) {
506 if (strstr(
filename, fontinfo_table_.
get(f).name) != NULL) {
507 int len = strlen(fontinfo_table_.
get(f).name);
509 if (len > best_len) {
525 int num_shapes = flat_shapes_.
NumShapes();
526 for (
int s = 0; s < num_shapes; ++s) {
527 int font = flat_shapes_.
GetShape(s)[0].font_ids[0];
529 for (f = 0; f < active_fonts.
size(); ++f) {
530 if (active_fonts[f] == font)
533 if (f == active_fonts.
size())
537 int num_fonts = active_fonts.
size();
538 for (
int f = 0; f < num_fonts; ++f) {
539 for (
int s = num_shapes - 1; s >= 0; --s) {
540 int font = flat_shapes_.
GetShape(s)[0].font_ids[0];
541 if (font == active_fonts[f]) {
565 shape_map.
SetMap(shape_id,
true);
570 it.
Init(&shape_map, &shape_table,
false, &samples_);
575 for (
int i = sample_ptrs.
size() - 1; i >= 0; --i) {
577 int num_features =
sample->num_micro_features();
578 for (
int f = 0; f < num_features; ++f)
582 *num_samples = sample_id;
594 const char* inttemp_file,
595 const char* pffmtable_file) {
601 FILE* fp = fopen(inttemp_file,
"wb");
614 for (
int i = 0; i < int_templates->
NumClasses; ++i) {
619 for (
int config_id = 0; config_id < Class->
NumConfigs; config_id++) {
623 if (length > max_length)
625 int shape_id = float_classes[i].
font_set.
get(config_id);
627 for (
int c = 0; c < shape.
size(); ++c) {
628 int unichar_id = shape[c].unichar_id;
629 if (length > unichar_cutoffs[unichar_id])
630 unichar_cutoffs[unichar_id] = length;
633 shapetable_cutoffs.
push_back(max_length);
635 fp = fopen(pffmtable_file,
"wb");
639 if (strcmp(unichar,
" ") == 0) {
642 fprintf(fp,
"%s %d\n", unichar, unichar_cutoffs[c]);
652 const char* unichar_str2) {
655 if (class_id2 == INVALID_UNICHAR_ID)
656 class_id2 = class_id1;
657 if (class_id1 == INVALID_UNICHAR_ID) {
658 tprintf(
"No unicharset entry found for %s\n", unichar_str1);
661 tprintf(
"Font ambiguities for unichar %d = %s and %d = %s\n",
662 class_id1, unichar_str1, class_id2, unichar_str2);
664 int num_fonts = samples_.
NumFonts();
669 for (
int f = 0; f < num_fonts; ++f) {
675 for (
int f1 = 0; f1 < num_fonts; ++f1) {
680 for (
int f2 = 0; f2 < num_fonts; ++f2) {
691 for (
int f = 0; f < num_fonts; ++f) {
694 if (class_id1 != class_id2 &&
700 #ifndef GRAPHICS_DISABLED 712 const char* unichar_str2,
713 int canonical_font) {
720 if (class_id2 != INVALID_UNICHAR_ID && canonical_font >= 0) {
723 for (
int f = 0; f <
sample->num_features(); ++f) {
728 if (class_id1 != INVALID_UNICHAR_ID && cloud_font >= 0) {
730 for (
int f = 0; f < cloud.
size(); ++f) {
748 if (feature_index >= 0) {
762 #endif // GRAPHICS_DISABLED 768 sample_it.
Init(NULL, NULL, replicate_samples, &samples_);
771 page_images_, &sample_it);
778 bool replicate_samples,
781 TestClassifier(error_mode, report_level, replicate_samples, &samples_,
782 test_classifier, report_string);
800 bool replicate_samples,
805 sample_it.
Init(NULL, NULL, replicate_samples, samples);
806 if (report_level > 0) {
810 tprintf(
"Iterator has charset size of %d/%d, %d shapes, %d samples\n",
813 tprintf(
"Testing %sREPLICATED:\n", replicate_samples ?
"" :
"NON-");
815 double unichar_error = 0.0;
817 error_mode, fontinfo_table_,
818 page_images_, &sample_it, &unichar_error,
819 NULL, report_string);
820 return unichar_error;
829 int num_chars1 = shape1.
size();
830 int num_chars2 = shape2.
size();
831 float dist_sum = 0.0f;
833 if (num_chars1 > 1 || num_chars2 > 1) {
836 for (
int c1 = 0; c1 < num_chars1; ++c1) {
837 for (
int c2 = 0; c2 < num_chars2; ++c2) {
850 return dist_sum / dist_count;
855 void MasterTrainer::ReplaceFragmentedSamples() {
856 if (fragments_ == NULL)
return;
860 for (
int s = 0; s < num_samples; ++s) {
862 if (fragments_[
sample->class_id()] > 0)
874 bool* good_junk =
new bool[frag_set.
size()];
875 memset(good_junk, 0,
sizeof(*good_junk) * frag_set.
size());
876 for (
int dead_ch = 1; dead_ch < unicharset_.
size(); ++dead_ch) {
877 int frag_ch = fragments_[dead_ch];
878 if (frag_ch <= 0)
continue;
882 for (
int part = 0; part < frag->
get_total(); ++part) {
885 if (good_ch != INVALID_UNICHAR_ID)
886 good_junk[good_ch] =
true;
894 for (
int s = 0; s < num_junks; ++s) {
896 int junk_id =
sample->class_id();
912 delete [] fragments_;
922 void MasterTrainer::ClusterShapes(
int min_shapes,
int max_shape_unichars,
925 int max_merges = num_shapes - min_shapes;
931 tprintf(
"Computing shape distances...");
932 for (
int s1 = 0; s1 < num_shapes; ++s1) {
933 for (
int s2 = s1 + 1; s2 < num_shapes; ++s2) {
946 while (num_merged < max_merges && min_dist < max_dist) {
947 tprintf(
"Distance = %f: ", min_dist);
949 shape_dists[min_s1][min_s2 - min_s1 - 1].distance =
kInfiniteDist;
950 if (num_unichars > max_shape_unichars) {
951 tprintf(
"Merge of %d and %d with %d would exceed max of %d unichars\n",
952 min_s1, min_s2, num_unichars, max_shape_unichars);
955 shape_dists[min_s2].
clear();
958 for (
int s = 0; s < min_s1; ++s) {
959 if (!shape_dists[s].empty()) {
960 shape_dists[s][min_s1 - s - 1].distance =
965 for (
int s2 = min_s1 + 1; s2 < num_shapes; ++s2) {
966 if (shape_dists[min_s1][s2 - min_s1 - 1].distance <
kInfiniteDist)
967 shape_dists[min_s1][s2 - min_s1 - 1].distance =
970 for (
int s = min_s1 + 1; s < min_s2; ++s) {
971 if (!shape_dists[s].empty()) {
977 for (
int s1 = 0; s1 < num_shapes; ++s1) {
978 for (
int i = 0; i < shape_dists[s1].
size(); ++i) {
979 if (shape_dists[s1][i].distance < min_dist) {
980 min_dist = shape_dists[s1][i].distance;
987 tprintf(
"Stopped with %d merged, min dist %f\n", num_merged, min_dist);
988 delete [] shape_dists;
989 if (debug_level_ > 1) {
990 for (
int s1 = 0; s1 < num_shapes; ++s1) {
ScrollView * CreateFeatureSpaceWindow(const char *name, int xpos, int ypos)
int NumClassSamples(int font_id, int class_id, bool randomize) const
FEATURE_DEFS_STRUCT feature_defs
SAMPLE * MakeSample(CLUSTERER *Clusterer, const FLOAT32 *Feature, inT32 CharID)
double NormalizeSamples()
void init_spacing(int unicharset_size)
void LoadUnicharset(const char *filename)
bool DeSerialize(bool swap, FILE *fp)
int ShortNameToFeatureType(const FEATURE_DEFS_STRUCT &FeatureDefs, const char *ShortName)
const float kFontMergeDistance
int XYToFeatureIndex(int x, int y) const
CLUSTERER * MakeClusterer(inT16 SampleSize, const PARAM_DESC ParamDesc[])
void Init(const IndexMapBiDi *charset_map, const ShapeTable *shape_table, bool randomize, TrainingSampleSet *sample_set)
void AppendOtherUnicharset(const UNICHARSET &src)
GenericVector< UNICHAR_ID > kerned_unichar_ids
bool DeSerialize(bool swap, FILE *fp)
const TrainingSample & GetSample() const
void DisplaySamplesWithFeature(int f_index, const Shape &shape, const IntFeatureSpace &feature_space, ScrollView::Color color, ScrollView *window) const
bool TESS_API contains_unichar(const char *const unichar_repr) const
void RenderIntFeature(ScrollView *window, const INT_FEATURE_STRUCT *Feature, ScrollView::Color color)
const float kInfiniteDist
int FindShape(int unichar_id, int font_id) const
int MasterDestinationIndex(int shape_id) const
void OrganizeByFontAndClass()
bool AddSpacingInfo(const char *filename)
void LoadUnicharset(const char *filename)
MasterTrainer(NormalizationMode norm_mode, bool shape_analysis, bool replicate_samples, int debug_level)
bool Serialize(FILE *fp) const
UnicityTableEqEq< int > font_set
const FEATURE_DESC_STRUCT * FeatureDesc[NUM_FEATURE_TYPES]
bool contains(T object) const
bool save_to_file(const char *const filename) const
int GetBestMatchingFontInfoId(const char *filename)
const UNICHARSET & unicharset() const
int tfscanf(FILE *stream, const char *format,...)
int get_index(T object) const
bool Serialize(FILE *fp) const
double TestClassifier(CountTypes error_mode, int report_level, bool replicate_samples, TrainingSampleSet *samples, ShapeClassifier *test_classifier, STRING *report_string)
static double ComputeErrorRate(ShapeClassifier *classifier, int report_level, CountTypes boosting_mode, const FontInfoTable &fontinfo_table, const GenericVector< Pix *> &page_images, SampleIterator *it, double *unichar_error, double *scaled_error, STRING *fonts_report)
bool LoadFontInfo(const char *filename)
void TestClassifierOnSamples(CountTypes error_mode, int report_level, bool replicate_samples, ShapeClassifier *test_classifier, STRING *report_string)
void AppendMasterShapes(const ShapeTable &other, GenericVector< int > *shape_map)
const TrainingSample * GetCanonicalSample(int font_id, int class_id) const
STRING SummaryStr() const
void IndexFeatures(const IntFeatureSpace &feature_space)
bool Serialize(FILE *fp) const
bool LoadXHeights(const char *filename)
#define ClassForClassId(T, c)
int AddShape(int unichar_id, int font_id)
int MergedUnicharCount(int shape_id1, int shape_id2) const
void AddSample(bool verification, const char *unichar_str, TrainingSample *sample)
const char * string() const
float UnicharDistance(const UnicharAndFonts &uf1, const UnicharAndFonts &uf2, bool matched_fonts, const IntFeatureMap &feature_map)
int CompactCharsetSize() const
bool Serialize(FILE *fp) const
const int kMinClusteredShapes
void ComputeCanonicalSamples(const IntFeatureMap &map, bool debug)
void ReadTrainingSamples(const char *page_name, const FEATURE_DEFS_STRUCT &feature_defs, bool verification)
float ShapeDistance(const ShapeTable &shapes, int s1, int s2)
void MoveTo(UnicityTable< FontInfo > *target)
void ReplicateAndRandomizeSamplesIfRequired()
bool DeSerialize(bool swap, FILE *fp)
const BitVector & GetCloudFeatures(int font_id, int class_id) const
const char * kMicroFeatureType
int AddSample(const char *unichar, TrainingSample *sample)
bool DeSerialize(bool swap, FILE *fp)
static void DebugNewErrors(ShapeClassifier *new_classifier, ShapeClassifier *old_classifier, CountTypes boosting_mode, const FontInfoTable &fontinfo_table, const GenericVector< Pix *> &page_images, SampleIterator *it)
const PARAM_DESC * ParamDesc
TrainingSample * mutable_sample(int index)
const IntFeatureSpace & feature_space() const
void TestClassifierVOld(bool replicate_samples, ShapeClassifier *test_classifier, ShapeClassifier *old_classifier)
virtual const ShapeTable * GetShapeTable() const =0
SVEvent * AwaitEvent(SVEventType type)
void MergeShapes(int shape_id1, int shape_id2)
void ClearFeatureSpaceWindow(NORM_METHOD norm_method, ScrollView *window)
INT_FEATURE_STRUCT InverseIndexFeature(int index_feature) const
FILE * Efopen(const char *Name, const char *Mode)
void DebugCanonical(const char *unichar_str1, const char *unichar_str2)
void free_int_templates(INT_TEMPLATES templates)
const char * kGeoFeatureType
void WriteInttempAndPFFMTable(const UNICHARSET &unicharset, const UNICHARSET &shape_set, const ShapeTable &shape_table, CLASS_STRUCT *float_classes, const char *inttemp_file, const char *pffmtable_file)
bool load_from_file(const char *const filename, bool skip_fragments)
static STRING to_string(const char *unichar, int pos, int total, bool natural)
UNICHAR_ID TESS_API unichar_to_id(const char *const unichar_repr) const
bool ParseBoxFileStr(const char *boxfile_str, int *page_number, STRING *utf8_str, TBOX *bounding_box)
void KillSample(TrainingSample *sample)
TrainingSample * extract_sample(int index)
void Init(int size, bool all_mapped)
void WriteIntTemplates(FILE *File, INT_TEMPLATES Templates, const UNICHARSET &target_unicharset)
void AddToShape(int unichar_id, int font_id)
bool Serialize(FILE *fp) const
const int kMaxUnicharsPerCluster
void ReplicateAndRandomizeSamples()
const Shape & GetShape(int shape_id) const
void SetupFlatShapeTable(ShapeTable *shape_table)
int GetFontInfoId(const char *font_name)
bool is_beginning() const
bool Serialize(FILE *fp) const
int DivRounded(int a, int b)
bool DeSerialize(bool swap, FILE *fp)
float ClusterDistance(int font_id1, int class_id1, int font_id2, int class_id2, const IntFeatureMap &feature_map)
GenericVector< inT16 > kerned_x_gaps
void LoadPageImages(const char *filename)
void TESS_API Init(const IntFeatureSpace &feature_space)
int SparseCharsetSize() const
const T & get(int id) const
Return the object from an id.
void FreeCharDescription(CHAR_DESC CharDesc)
UnicityTable< FontInfo > & get_fontinfo_table()
const char * kIntFeatureType
const char * id_to_unichar(UNICHAR_ID id) const
uinT16 ConfigLengths[MAX_NUM_CONFIGS]
void ComputeCloudFeatures(int feature_space_size)
void ComputeCanonicalFeatures()
STRING DebugStr(int shape_id) const
void ReverseN(void *ptr, int num_bytes)
void init_to_size(int size, T t)
void SetMap(int sparse_index, bool mapped)
const CHAR_FRAGMENT * get_fragment(UNICHAR_ID unichar_id) const
CHAR_DESC ReadCharDescription(const FEATURE_DEFS_STRUCT &FeatureDefs, FILE *File)
static CHAR_FRAGMENT * parse_from_string(const char *str)
void add_spacing(UNICHAR_ID uch_id, FontSpacingInfo *spacing_info)
void DisplaySamples(const char *unichar_str1, int cloud_font, const char *unichar_str2, int canonical_font)
const UNICHARSET & unicharset() const
const char * kCNFeatureType
CLUSTERER * SetupForClustering(const ShapeTable &shape_table, const FEATURE_DEFS_STRUCT &feature_defs, int shape_id, int *num_samples)
bool DeSerialize(bool swap, FILE *fp)
INT_TEMPLATES CreateIntTemplates(CLASSES FloatProtos, const UNICHARSET &target_unicharset)