22 #include "config_auto.h" 28 #include "allheaders.h" 53 bool replicate_samples,
55 : norm_mode_(norm_mode), samples_(fontinfo_table_),
56 junk_samples_(fontinfo_table_), verify_samples_(fontinfo_table_),
58 enable_shape_analysis_(shape_analysis),
59 enable_replication_(replicate_samples),
60 fragments_(nullptr), prev_unichar_id_(-1), debug_level_(debug_level) {
65 for (
int p = 0; p < page_images_.
size(); ++p)
66 pixDestroy(&page_images_[p]);
73 uint32_t value = norm_mode_;
76 if (!feature_space_.
Serialize(fp))
return false;
77 if (!samples_.
Serialize(fp))
return false;
78 if (!junk_samples_.
Serialize(fp))
return false;
79 if (!verify_samples_.
Serialize(fp))
return false;
80 if (!master_shapes_.
Serialize(fp))
return false;
81 if (!flat_shapes_.
Serialize(fp))
return false;
82 if (!fontinfo_table_.
Serialize(fp))
return false;
83 if (!xheights_.
Serialize(fp))
return false;
90 tprintf(
"Failed to load unicharset from file %s\n" 91 "Building unicharset for training from scratch...\n",
99 charsetsize_ = unicharset_.
size();
100 delete [] fragments_;
101 fragments_ =
new int[charsetsize_];
102 memset(fragments_, 0,
sizeof(*fragments_) * charsetsize_);
122 FILE* fp = fopen(page_name,
"rb");
124 tprintf(
"Failed to open tr file: %s\n", page_name);
128 while (fgets(buffer,
sizeof(buffer), fp) !=
nullptr) {
129 if (buffer[0] ==
'\n')
132 char* space = strchr(buffer,
' ');
133 if (space ==
nullptr) {
134 tprintf(
"Bad format in tr file, reading fontname, unichar\n");
139 if (font_id < 0) font_id = 0;
144 tprintf(
"Bad format in tr file, reading box coords\n");
149 sample->set_font_id(font_id);
150 sample->set_page_num(page_number + page_images_.
size());
151 sample->set_bounding_box(bounding_box);
152 sample->ExtractCharDesc(int_feature_type, micro_feature_type,
153 cn_feature_type, geo_feature_type, char_desc);
157 charsetsize_ = unicharset_.
size();
167 prev_unichar_id_ = -1;
169 if (prev_unichar_id_ >= 0)
170 fragments_[prev_unichar_id_] = -1;
176 if (prev_unichar_id_ >= 0) {
179 if (fragments_[prev_unichar_id_] == 0)
180 fragments_[prev_unichar_id_] = junk_id;
181 else if (fragments_[prev_unichar_id_] != junk_id)
182 fragments_[prev_unichar_id_] = -1;
186 prev_unichar_id_ = -1;
197 for (page = 0;; page++) {
198 pix = pixReadFromMultipageTiff(filename, &offset);
203 tprintf(
"Loaded %d page images from %s\n", page, filename);
212 if (debug_level_ > 0)
213 tprintf(
"PostLoadCleanup...\n");
214 if (enable_shape_analysis_)
215 ReplaceFragmentedSamples();
217 sample_it.
Init(
nullptr,
nullptr,
true, &verify_samples_);
226 if (debug_level_ > 0)
227 tprintf(
"ComputeCanonicalSamples...\n");
235 if (debug_level_ > 0)
236 tprintf(
"PreTrainingSetup...\n");
239 if (debug_level_ > 0)
240 tprintf(
"ComputeCloudFeatures...\n");
247 tprintf(
"Building master shape table\n");
248 const int num_fonts = samples_.
NumFonts();
255 for (
int f = 0; f < num_fonts; ++f) {
263 if (fragment ==
nullptr)
264 char_shapes.AppendMasterShapes(shapes,
nullptr);
266 char_shapes_begin_fragment.AppendMasterShapes(shapes,
nullptr);
268 char_shapes_end_fragment.AppendMasterShapes(shapes,
nullptr);
270 char_shapes.AppendMasterShapes(shapes,
nullptr);
274 char_shapes.AppendMasterShapes(char_shapes_begin_fragment,
nullptr);
277 char_shapes.AppendMasterShapes(char_shapes_end_fragment,
nullptr);
300 tprintf(
"Moving %d junk samples to master sample set.\n", num_junks);
301 for (
int s = 0; s < num_junks; ++s) {
303 int junk_id =
sample->class_id();
306 if (sample_id == INVALID_UNICHAR_ID)
308 sample->set_class_id(sample_id);
322 if (enable_replication_) {
323 if (debug_level_ > 0)
324 tprintf(
"ReplicateAndRandomize...\n");
334 FILE* fp = fopen(filename,
"rb");
336 fprintf(stderr,
"Failed to load font_properties from %s\n", filename);
339 int italic, bold, fixed, serif, fraktur;
342 char* font_name =
new char[1024];
343 fontinfo.
name = font_name;
346 if (
tfscanf(fp,
"%1024s %i %i %i %i %i\n", font_name, &italic, &bold,
347 &fixed, &serif, &fraktur) != 6) {
357 if (!fontinfo_table_.
contains(fontinfo)) {
370 tprintf(
"fontinfo table is of size %d\n", fontinfo_table_.
size());
372 if (filename ==
nullptr)
return true;
373 FILE *f = fopen(filename,
"rb");
375 fprintf(stderr,
"Failed to load font xheights from %s\n", filename);
378 tprintf(
"Reading x-heights from %s ...\n", filename);
384 int total_xheight = 0;
385 int xheight_count = 0;
387 if (
tfscanf(f,
"%1023s %d\n", buffer, &xht) != 2)
390 fontinfo.
name = buffer;
391 if (!fontinfo_table_.
contains(fontinfo))
continue;
392 int fontinfo_id = fontinfo_table_.
get_index(fontinfo);
393 xheights_[fontinfo_id] = xht;
394 total_xheight += xht;
397 if (xheight_count == 0) {
398 fprintf(stderr,
"No valid xheights in %s!\n", filename);
402 int mean_xheight =
DivRounded(total_xheight, xheight_count);
403 for (
int i = 0; i < fontinfo_table_.
size(); ++i) {
404 if (xheights_[i] < 0)
405 xheights_[i] = mean_xheight;
413 FILE* fontinfo_file = fopen(filename,
"rb");
414 if (fontinfo_file ==
nullptr)
418 if (fontinfo_id < 0) {
419 tprintf(
"No font found matching fontinfo filename %s\n", filename);
420 fclose(fontinfo_file);
423 tprintf(
"Reading spacing from %s for font %d...\n", filename, fontinfo_id);
430 int x_gap, x_gap_before, x_gap_after, num_kerned;
435 for (
int l = 0; l < num_unichars; ++l) {
436 if (
tfscanf(fontinfo_file,
"%s %d %d %d",
437 uch, &x_gap_before, &x_gap_after, &num_kerned) != 4) {
438 tprintf(
"Bad format of font spacing file %s\n", filename);
439 fclose(fontinfo_file);
445 spacing->
x_gap_before =
static_cast<int16_t
>(x_gap_before * scale);
446 spacing->
x_gap_after =
static_cast<int16_t
>(x_gap_after * scale);
448 for (
int k = 0; k < num_kerned; ++k) {
449 if (
tfscanf(fontinfo_file,
"%s %d", kerned_uch, &x_gap) != 2) {
450 tprintf(
"Bad format of font spacing file %s\n", filename);
451 fclose(fontinfo_file);
462 fclose(fontinfo_file);
471 fontinfo.
name =
const_cast<char*
>(font_name);
474 return fontinfo_table_.
get_index(fontinfo);
480 int fontinfo_id = -1;
482 for (
int f = 0; f < fontinfo_table_.
size(); ++f) {
483 if (strstr(filename, fontinfo_table_.
get(f).name) !=
nullptr) {
484 int len = strlen(fontinfo_table_.
get(f).name);
486 if (len > best_len) {
502 int num_shapes = flat_shapes_.
NumShapes();
503 for (
int s = 0; s < num_shapes; ++s) {
504 int font = flat_shapes_.
GetShape(s)[0].font_ids[0];
506 for (f = 0; f < active_fonts.
size(); ++f) {
507 if (active_fonts[f] == font)
510 if (f == active_fonts.
size())
514 int num_fonts = active_fonts.
size();
515 for (
int f = 0; f < num_fonts; ++f) {
516 for (
int s = num_shapes - 1; s >= 0; --s) {
517 int font = flat_shapes_.
GetShape(s)[0].font_ids[0];
518 if (font == active_fonts[f]) {
542 shape_map.
SetMap(shape_id,
true);
547 it.
Init(&shape_map, &shape_table,
false, &samples_);
552 for (
int i = sample_ptrs.
size() - 1; i >= 0; --i) {
554 uint32_t num_features =
sample->num_micro_features();
555 for (uint32_t f = 0; f < num_features; ++f)
559 *num_samples = sample_id;
571 const char* inttemp_file,
572 const char* pffmtable_file) {
578 FILE* fp = fopen(inttemp_file,
"wb");
580 tprintf(
"Error, failed to open file \"%s\"\n", inttemp_file);
595 for (
int i = 0; i < int_templates->
NumClasses; ++i) {
599 uint16_t max_length = 0;
600 for (
int config_id = 0; config_id < Class->
NumConfigs; config_id++) {
604 if (length > max_length)
606 int shape_id = float_classes[i].
font_set.
get(config_id);
608 for (
int c = 0; c < shape.
size(); ++c) {
609 int unichar_id = shape[c].unichar_id;
610 if (length > unichar_cutoffs[unichar_id])
611 unichar_cutoffs[unichar_id] = length;
614 shapetable_cutoffs.
push_back(max_length);
616 fp = fopen(pffmtable_file,
"wb");
618 tprintf(
"Error, failed to open file \"%s\"\n", pffmtable_file);
623 if (strcmp(unichar,
" ") == 0) {
626 fprintf(fp,
"%s %d\n", unichar, unichar_cutoffs[c]);
637 const char* unichar_str2) {
640 if (class_id2 == INVALID_UNICHAR_ID)
641 class_id2 = class_id1;
642 if (class_id1 == INVALID_UNICHAR_ID) {
643 tprintf(
"No unicharset entry found for %s\n", unichar_str1);
646 tprintf(
"Font ambiguities for unichar %d = %s and %d = %s\n",
647 class_id1, unichar_str1, class_id2, unichar_str2);
649 int num_fonts = samples_.
NumFonts();
654 for (
int f = 0; f < num_fonts; ++f) {
660 for (
int f1 = 0; f1 < num_fonts; ++f1) {
665 for (
int f2 = 0; f2 < num_fonts; ++f2) {
676 for (
int f = 0; f < num_fonts; ++f) {
679 if (class_id1 != class_id2 &&
685 #ifndef GRAPHICS_DISABLED 697 const char* unichar_str2,
698 int canonical_font) {
705 if (class_id2 != INVALID_UNICHAR_ID && canonical_font >= 0) {
708 for (uint32_t f = 0; f <
sample->num_features(); ++f) {
713 if (class_id1 != INVALID_UNICHAR_ID && cloud_font >= 0) {
715 for (
int f = 0; f < cloud.
size(); ++f) {
733 if (feature_index >= 0) {
747 #endif // GRAPHICS_DISABLED 753 sample_it.
Init(
nullptr,
nullptr, replicate_samples, &samples_);
756 page_images_, &sample_it);
763 bool replicate_samples,
766 TestClassifier(error_mode, report_level, replicate_samples, &samples_,
767 test_classifier, report_string);
785 bool replicate_samples,
790 sample_it.
Init(
nullptr,
nullptr, replicate_samples, samples);
791 if (report_level > 0) {
795 tprintf(
"Iterator has charset size of %d/%d, %d shapes, %d samples\n",
798 tprintf(
"Testing %sREPLICATED:\n", replicate_samples ?
"" :
"NON-");
800 double unichar_error = 0.0;
802 error_mode, fontinfo_table_,
803 page_images_, &sample_it, &unichar_error,
804 nullptr, report_string);
805 return unichar_error;
814 int num_chars1 = shape1.
size();
815 int num_chars2 = shape2.
size();
816 float dist_sum = 0.0f;
818 if (num_chars1 > 1 || num_chars2 > 1) {
821 for (
int c1 = 0; c1 < num_chars1; ++c1) {
822 for (
int c2 = 0; c2 < num_chars2; ++c2) {
835 return dist_sum / dist_count;
840 void MasterTrainer::ReplaceFragmentedSamples() {
841 if (fragments_ ==
nullptr)
return;
845 for (
int s = 0; s < num_samples; ++s) {
847 if (fragments_[
sample->class_id()] > 0)
859 bool* good_junk =
new bool[frag_set.
size()];
860 memset(good_junk, 0,
sizeof(*good_junk) * frag_set.
size());
861 for (
int dead_ch = 1; dead_ch < unicharset_.
size(); ++dead_ch) {
862 int frag_ch = fragments_[dead_ch];
863 if (frag_ch <= 0)
continue;
867 for (
int part = 0; part < frag->
get_total(); ++part) {
870 if (good_ch != INVALID_UNICHAR_ID)
871 good_junk[good_ch] =
true;
879 for (
int s = 0; s < num_junks; ++s) {
881 int junk_id =
sample->class_id();
897 delete [] fragments_;
898 fragments_ =
nullptr;
907 void MasterTrainer::ClusterShapes(
int min_shapes,
int max_shape_unichars,
910 int max_merges = num_shapes - min_shapes;
916 tprintf(
"Computing shape distances...");
917 for (
int s1 = 0; s1 < num_shapes; ++s1) {
918 for (
int s2 = s1 + 1; s2 < num_shapes; ++s2) {
931 while (num_merged < max_merges && min_dist < max_dist) {
932 tprintf(
"Distance = %f: ", min_dist);
934 shape_dists[min_s1][min_s2 - min_s1 - 1].distance =
kInfiniteDist;
935 if (num_unichars > max_shape_unichars) {
936 tprintf(
"Merge of %d and %d with %d would exceed max of %d unichars\n",
937 min_s1, min_s2, num_unichars, max_shape_unichars);
940 shape_dists[min_s2].
clear();
943 for (
int s = 0; s < min_s1; ++s) {
944 if (!shape_dists[s].empty()) {
945 shape_dists[s][min_s1 - s - 1].distance =
950 for (
int s2 = min_s1 + 1; s2 < num_shapes; ++s2) {
951 if (shape_dists[min_s1][s2 - min_s1 - 1].distance <
kInfiniteDist)
952 shape_dists[min_s1][s2 - min_s1 - 1].distance =
955 for (
int s = min_s1 + 1; s < min_s2; ++s) {
956 if (!shape_dists[s].empty()) {
962 for (
int s1 = 0; s1 < num_shapes; ++s1) {
963 for (
int i = 0; i < shape_dists[s1].
size(); ++i) {
964 if (shape_dists[s1][i].distance < min_dist) {
965 min_dist = shape_dists[s1][i].distance;
972 tprintf(
"Stopped with %d merged, min dist %f\n", num_merged, min_dist);
973 delete [] shape_dists;
974 if (debug_level_ > 1) {
975 for (
int s1 = 0; s1 < num_shapes; ++s1) {
void MoveTo(UnicityTable< FontInfo > *target)
bool is_beginning() const
void add_spacing(UNICHAR_ID uch_id, FontSpacingInfo *spacing_info)
bool LoadXHeights(const char *filename)
void KillSample(TrainingSample *sample)
int CompactCharsetSize() const
const IntFeatureSpace & feature_space() const
int tfscanf(FILE *stream, const char *format,...)
void LoadUnicharset(const char *filename)
void DisplaySamples(const char *unichar_str1, int cloud_font, const char *unichar_str2, int canonical_font)
void FreeCharDescription(CHAR_DESC CharDesc)
STRING SummaryStr() const
bool Serialize(FILE *fp) const
float UnicharDistance(const UnicharAndFonts &uf1, const UnicharAndFonts &uf2, bool matched_fonts, const IntFeatureMap &feature_map)
void ClearFeatureSpaceWindow(NORM_METHOD norm_method, ScrollView *window)
void free_int_templates(INT_TEMPLATES templates)
const UNICHARSET & unicharset() const
void SetMap(int sparse_index, bool mapped)
bool save_to_file(const char *const filename) const
bool AddSpacingInfo(const char *filename)
UnicityTable< FontInfo > & get_fontinfo_table()
void LoadUnicharset(const char *filename)
void AppendOtherUnicharset(const UNICHARSET &src)
double NormalizeSamples()
void ComputeCloudFeatures(int feature_space_size)
CHAR_DESC ReadCharDescription(const FEATURE_DEFS_STRUCT &FeatureDefs, FILE *File)
void AddSample(bool verification, const char *unichar_str, TrainingSample *sample)
STRING DebugStr(int shape_id) const
const char * string() const
float ShapeDistance(const ShapeTable &shapes, int s1, int s2)
void TestClassifierVOld(bool replicate_samples, ShapeClassifier *test_classifier, ShapeClassifier *old_classifier)
int SparseCharsetSize() const
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
GenericVector< int16_t > kerned_x_gaps
static STRING to_string(const char *unichar, int pos, int total, bool natural)
bool Serialize(FILE *fp, const char *data, size_t n)
MasterTrainer(NormalizationMode norm_mode, bool shape_analysis, bool replicate_samples, int debug_level)
SAMPLE * MakeSample(CLUSTERER *Clusterer, const float *Feature, int32_t CharID)
int AddSample(const char *unichar, TrainingSample *sample)
bool contains(const T &object) const
bool Serialize(FILE *fp) const
TrainingSample * extract_sample(int index)
INT_TEMPLATES CreateIntTemplates(CLASSES FloatProtos, const UNICHARSET &target_unicharset)
void DebugCanonical(const char *unichar_str1, const char *unichar_str2)
double TestClassifier(CountTypes error_mode, int report_level, bool replicate_samples, TrainingSampleSet *samples, ShapeClassifier *test_classifier, STRING *report_string)
UnicityTableEqEq< int > font_set
CLUSTERER * SetupForClustering(const ShapeTable &shape_table, const FEATURE_DEFS_STRUCT &feature_defs, int shape_id, int *num_samples)
void LoadPageImages(const char *filename)
FEATURE_DEFS_STRUCT feature_defs
void TestClassifierOnSamples(CountTypes error_mode, int report_level, bool replicate_samples, ShapeClassifier *test_classifier, STRING *report_string)
int FindShape(int unichar_id, int font_id) const
const char * kGeoFeatureType
bool Serialize(FILE *fp) const
GenericVector< UNICHAR_ID > kerned_unichar_ids
const PARAM_DESC * ParamDesc
int get_index(const T &object) const
void init_spacing(int unicharset_size)
void Init(const IndexMapBiDi *charset_map, const ShapeTable *shape_table, bool randomize, TrainingSampleSet *sample_set)
static void DebugNewErrors(ShapeClassifier *new_classifier, ShapeClassifier *old_classifier, CountTypes boosting_mode, const FontInfoTable &fontinfo_table, const GenericVector< Pix *> &page_images, SampleIterator *it)
void ReplicateAndRandomizeSamplesIfRequired()
void AppendMasterShapes(const ShapeTable &other, GenericVector< int > *shape_map)
SVEvent * AwaitEvent(SVEventType type)
const int kMinClusteredShapes
bool contains_unichar(const char *const unichar_repr) const
const int kMaxUnicharsPerCluster
void init_to_size(int size, const T &t)
const float kInfiniteDist
int GetFontInfoId(const char *font_name)
void ComputeCanonicalFeatures()
void ComputeCanonicalSamples(const IntFeatureMap &map, bool debug)
bool LoadFontInfo(const char *filename)
void WriteIntTemplates(FILE *File, INT_TEMPLATES Templates, const UNICHARSET &target_unicharset)
uint16_t ConfigLengths[MAX_NUM_CONFIGS]
void RenderIntFeature(ScrollView *window, const INT_FEATURE_STRUCT *Feature, ScrollView::Color color)
int NumClassSamples(int font_id, int class_id, bool randomize) const
void IndexFeatures(const IntFeatureSpace &feature_space)
const BitVector & GetCloudFeatures(int font_id, int class_id) const
DLLSYM void tprintf(const char *format,...)
int MasterDestinationIndex(int shape_id) const
INT_FEATURE_STRUCT InverseIndexFeature(int index_feature) const
const char * kMicroFeatureType
const Shape & GetShape(int shape_id) const
const UNICHARSET & unicharset() const
const CHAR_FRAGMENT * get_fragment(UNICHAR_ID unichar_id) const
virtual const ShapeTable * GetShapeTable() const =0
const T & get(int id) const
Return the object from an id.
bool Serialize(FILE *fp) const
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 Serialize(FILE *fp) const
ScrollView * CreateFeatureSpaceWindow(const char *name, int xpos, int ypos)
const FEATURE_DESC_STRUCT * FeatureDesc[NUM_FEATURE_TYPES]
const float kFontMergeDistance
const TrainingSample * GetCanonicalSample(int font_id, int class_id) const
const char * id_to_unichar(UNICHAR_ID id) const
bool Serialize(FILE *fp) const
void DisplaySamplesWithFeature(int f_index, const Shape &shape, const IntFeatureSpace &feature_space, ScrollView::Color color, ScrollView *window) const
int AddShape(int unichar_id, int font_id)
void ReadTrainingSamples(const char *page_name, const FEATURE_DEFS_STRUCT &feature_defs, bool verification)
uint32_t ShortNameToFeatureType(const FEATURE_DEFS_STRUCT &FeatureDefs, const char *ShortName)
void SetupFlatShapeTable(ShapeTable *shape_table)
const char * kCNFeatureType
void MergeShapes(int shape_id1, int shape_id2)
const TrainingSample & GetSample() const
TrainingSample * mutable_sample(int index)
float ClusterDistance(int font_id1, int class_id1, int font_id2, int class_id2, const IntFeatureMap &feature_map)
int DivRounded(int a, int b)
#define ClassForClassId(T, c)
int MergedUnicharCount(int shape_id1, int shape_id2) const
void ReplicateAndRandomizeSamples()
bool load_from_file(const char *const filename, bool skip_fragments)
void OrganizeByFontAndClass()
const char * kIntFeatureType
int GetBestMatchingFontInfoId(const char *filename)
void AddToShape(int unichar_id, int font_id)
CLUSTERER * MakeClusterer(int16_t SampleSize, const PARAM_DESC ParamDesc[])
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)
void Init(int size, bool all_mapped)
static CHAR_FRAGMENT * parse_from_string(const char *str)
bool ParseBoxFileStr(const char *boxfile_str, int *page_number, STRING *utf8_str, TBOX *bounding_box)
int XYToFeatureIndex(int x, int y) const