2 * Core OCR algorithm (first exact bitmap match)
5 * This is part of ypp-sc-tools, a set of third-party tools for assisting
6 * players of Yohoho Puzzle Pirates.
8 * Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 * Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24 * are used without permission. This program is not endorsed or
25 * sponsored by Three Rings.
33 struct DatabaseNode *then;
36 typedef struct DatabaseNode {
39 unsigned match:1, defined:1, endsword:1, local:1;
56 #define FOR_EACH_CONTEXT(EACH) \
62 #define FEC_ENUM(Context) ct_##Context,
63 #define FEC_BIT(Context) ctf_##Context = 1 << ct_##Context,
65 FOR_EACH_CONTEXT(FEC_ENUM)
66 FOR_EACH_CONTEXT(FEC_BIT)
69 #define FEC_STRINGS(Context) #Context,
70 static const char *context_names[]= { FOR_EACH_CONTEXT(FEC_STRINGS) };
72 struct OcrCellTypeInfo {
73 /* bitmaps of indices into context_names: */
74 unsigned initial, nextword, midword;
77 int (*findchar_select)(const FindCharArgs *fca,
78 const FindCharResults results[]);
81 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
85 DatabaseNode contexts[NCONTEXTS];
86 OcrResultGlyph *results;
87 int aresults, nresults;
90 DEBUG_DEFINE_DEBUGF(ocr)
92 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
94 static void cleardb_node(DatabaseNode *n) {
96 free(n->str); n->str=0;
97 n->defined=n->match=n->endsword= 0;
98 for (i=0; i<n->nlinks; i++)
99 cleardb_node(n->links[i].then);
102 static void readdb1(OcrReader *rd, const char *which, int local);
104 static void readdb(OcrReader *rd) {
107 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
108 cleardb_node(&rd->contexts[ctxi]);
110 readdb1(rd, "master", 0);
111 readdb1(rd, "local", 1);
114 static void readdb1(OcrReader *rd, const char *which, int local) {
116 DatabaseNode *current, *additional;
123 char *dbfname= masprintf("%s/#%s-char%d#.txt",
124 get_vardir(), which, rd->h);
126 if (!dbfile_open(dbfname))
130 o_flags |= ff_charset_havelocal;
133 dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v2"));
135 dbassert( dbfile_scanf("%d", &h) == 1);
140 if (!lbuf[0] || lbuf[0]=='#') continue;
141 if (!strcmp(lbuf,".")) break;
143 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
144 if (!strcmp(lbuf,context_names[ctxi]))
146 /* not found, just skip */
147 for (;;) { FGETSLINE; if (!lbuf[0]) break; }
152 int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
153 if (c=='\n') break; /* forces no match */
154 dbassert(nchrs<sizeof(chrs));
158 if (nchrs>0 && chrs[nchrs-1]==' ') {
163 current= &rd->contexts[ctxi];
166 if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
167 dbassert( strlen(lbuf) == rd->h );
170 for (y=0; y<h; y++) {
175 unsigned pv= strtoul(pb,&ep,16); dbassert(!*ep);
176 pixcol_p_add(&cv, y, pv);
179 for (j=0; j<current->nlinks; j++)
180 if (!pixcol_cmp(&cv, ¤t->links[j].col)) {
181 current= current->links[j].then;
185 additional= mmalloc(sizeof(*additional));
187 additional->defined= 0;
188 additional->match= 0;
189 additional->endsword= 0;
190 additional->nlinks= additional->alinks= 0;
191 additional->links= 0;
192 if (current->nlinks==current->alinks) {
195 current->links= mrealloc(current->links,
196 sizeof(*current->links) * current->alinks);
198 current->links[current->nlinks].col= cv;
199 current->links[current->nlinks].then= additional;
206 if (!current->defined) {
211 current->local= local;
214 current->str= mmalloc(nchrs+1);
215 memcpy(current->str, chrs, nchrs);
216 current->str[nchrs]= 0;
218 current->endsword= endsword;
227 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
228 fprintf(resolver,"{");
231 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
232 if (!(ctxmap & (1u << ctxi))) continue;
233 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
236 fprintf(resolver,"}");
239 static void callout_unknown(OcrReader *rd, int w, const Pixcol cols[],
240 int unk_l, int unk_r, unsigned unk_ctxmap) {
242 const OcrResultGlyph *s;
245 FILE *resolver= resolve_start();
246 if (!resolver || !(o_flags & ff_editcharset))
247 fatal("OCR failed - unrecognised characters or ligatures.\n"
248 "Character set database needs to be updated or augmented.\n"
249 "See README.charset.\n");
253 "%d %d ",unk_l,unk_r);
254 cu_pr_ctxmap(resolver,unk_ctxmap);
255 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
256 if (!strcmp(s->s," ")) continue;
257 fprintf(resolver," %d %d ",s->l,s->r);
258 cu_pr_ctxmap(resolver, 1u << s->match);
259 fprintf(resolver," ");
260 cu_pr_ctxmap(resolver, s->ctxmap);
261 fprintf(resolver," ");
262 for (p=s->s; (c= *p); p++) {
263 if (c=='\\') fprintf(resolver,"\\%c",c);
264 else if (c>=33 && c<=126) fputc(c,resolver);
265 else fprintf(resolver,"\\x%02x",(unsigned char)c);
268 fputc('\n',resolver);
271 "P2\n%d %d %d\n", w, rd->h, AAMAXVAL);
272 for (y=0; y<rd->h; y++) {
274 fprintf(resolver, " %d", pixcol_p_get(&cols[x], y));
275 fputc('\n',resolver);
282 static void add_result(OcrReader *rd, const char *s, int l, int r,
283 int match, unsigned ctxmap) {
284 if (rd->nresults >= rd->aresults) {
285 rd->aresults++; rd->aresults<<=1;
286 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
288 rd->results[rd->nresults].s= s;
289 rd->results[rd->nresults].l= l;
290 rd->results[rd->nresults].r= r;
291 rd->results[rd->nresults].match= match;
292 rd->results[rd->nresults].ctxmap= ctxmap;
297 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
298 DatabaseNode *start, int *matchx_r) {
299 DatabaseNode *current= start;
300 DatabaseNode *bestmatch= 0;
307 if (x > fca->w) break;
308 Pixcol cv= fca->cols[x];
309 debugf(" cv="PIXCOL_PRFMT, PIXCOL_PRVAL(cv));
310 for (i=0; i<current->nlinks; i++)
311 if (!pixcol_cmp(&cv, ¤t->links[i].col))
318 current= current->links[i].then;
319 if (current->match) {
320 debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
332 static DatabaseNode *findchar(const FindCharArgs *fca,
333 int *match_rx, int *match_rctxi) {
334 FindCharResults results[NCONTEXTS];
335 int ctxi, match=-1, nmatches=0;
337 debugf("OCR lx=%d ct_state=%x ", fca->x, fca->ctxmap);
338 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
339 results[ctxi].match= 0;
340 if (!(fca->ctxmap & (1u << ctxi))) continue;
341 debugf(" || %s",context_names[ctxi]);
343 results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
345 if (!results[ctxi].match) continue;
353 debugf(" ambiguous");
354 match= !fca->ct->findchar_select ? -1 :
355 fca->ct->findchar_select(fca,results);
356 debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
361 *match_rx= results[match].rx;
362 if (match_rctxi) *match_rctxi= match;
363 return results[match].match;
366 static int findchar_select_text(const FindCharArgs *fca,
367 const FindCharResults results[]) {
369 dbassert(! results[ct_Digit].match ); /* digits are supposedly unambiguous */
371 switch (fca->ctxmap) {
373 #define RETURN_IF_LONGER(this,that) do{ \
374 if (results[ct_##this].rx > results[ct_##that].rx) \
378 case ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word:
379 /* Start of word. Prefer Word match; failing that, take the longest */
380 if (results[ct_Word].match) return ct_Word;
381 RETURN_IF_LONGER(Lower,Upper);
382 RETURN_IF_LONGER(Upper,Lower);
385 case ctf_Digit | ctf_Upper | ctf_Lower:
386 /* Mid-word. Prefer longer match; failing that, match lower. */
387 RETURN_IF_LONGER(Upper,Lower);
395 const struct OcrCellTypeInfo ocr_celltype_number= {
396 ctf_Digit, ctf_Digit, ctf_Digit,
401 const struct OcrCellTypeInfo ocr_celltype_text= {
402 .initial= ctf_Digit | ctf_Upper,
403 .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
404 .midword= ctf_Digit | ctf_Upper | ctf_Lower,
407 .findchar_select= findchar_select_text
411 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
413 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w,
414 const Pixcol cols[]) {
428 fca.ctxmap= ct->initial;
430 debugf("OCR h=%d w=%d",rd->h,w);
431 for (x=0; x<w; x++) debugf(" "PIXCOL_PRFMT, PIXCOL_PRVAL(cols[x]));
442 if (!pixcol_nonzero(&cols[x])) {
445 if (nspaces == ct->space_spaces) {
446 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
447 fca.ctxmap= ct->nextword;
452 /* something here, so we need to add the spaces */
453 if (nspaces >= ct->space_spaces)
454 add_result(rd," ",x-nspaces,x+1,-1,0);
461 DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
465 add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
467 if (match->match) fca.ctxmap= ct->midword;
468 else debugf(" (empty)");
469 if (match->endsword) {
470 nspaces= ct->space_spaces;
472 fca.ctxmap= ct->nextword;
477 debugf(" || UNKNOWN");
478 for (rx=x; rx<w && pixcol_nonzero(&cols[rx]); rx++);
479 debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
481 callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
486 add_result(rd, 0,-1,-1,-1,0);
487 debugf("OCR finished %d glyphs\n",rd->nresults);
492 OcrReader *ocr_init(int h) {
495 assert(h <= OCR_MAX_H);
497 if (o_flags & ff_dict_fetch) {
498 char *fetchfile= masprintf("char%d",h);
499 progress("Updating %s...",fetchfile);
500 fetch_with_rsync(fetchfile);
504 rd= mmalloc(sizeof(*rd));
505 memset(rd,0,sizeof(*rd));
511 /*---------- character set dump ----------*/
513 static void show_recurse(const DatabaseNode *t, int *count,
514 const DatabaseNode **store_ary) {
516 if (store_ary) store_ary[*count]= t;
520 for (l=0; l<t->nlinks; l++)
521 show_recurse(t->links[l].then, count,store_ary);
524 static int show_char_compar(const void *av, const void *bv) {
525 const DatabaseNode *const *ap= av; const DatabaseNode *a= *ap;
526 const DatabaseNode *const *bp= bv; const DatabaseNode *b= *bp;
527 return strcmp(a->str, b->str) ?:
528 ((int)a->match - (int)b->match) ?:
529 ((int)a->endsword - (int)b->endsword) ?:
530 ((int)a->local - (int)b->local) ?:
534 void ocr_showcharsets(void) {
537 char found[OCR_MAX_H];
541 const char *pcre_err;
544 memset(found,0,sizeof(found));
546 fnpat= pcre_compile("\\#(?:master|local)\\-char([1-9]\\d{0,2})\\#\\.txt$",
547 PCRE_ANCHORED|PCRE_DOLLAR_ENDONLY,
548 &pcre_err,&pcre_erroffset, 0);
549 debugf("pcre_compile %p %s\n",fnpat,pcre_err);
552 sysassert( d= opendir(get_vardir()) );
554 errno=0; de= readdir(d); if (!de) break;
556 int rer= pcre_exec(fnpat,0, de->d_name,strlen(de->d_name), 0,0,
557 matchvec,ARRAYSIZE(matchvec));
558 debugf("pcre_exec `%s' => %d\n", de->d_name,rer);
560 if (rer==PCRE_ERROR_NOMATCH || rer==PCRE_ERROR_BADUTF8) continue;
563 rer= pcre_copy_substring(de->d_name,matchvec,rer, 1, hbuf,sizeof(hbuf));
564 debugf("pcre_copy_substring => %d\n", rer);
568 if (h >= ARRAYSIZE(found)) continue;
574 for (h=0; h<ARRAYSIZE(found); h++) {
575 if (!found[h]) continue;
577 OcrReader *rd= ocr_init(h); /* we leak this but never mind */
581 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
583 show_recurse(&rd->contexts[ctxi], &nchars, 0);
584 const DatabaseNode **chars= mmalloc(sizeof(*chars) * nchars);
586 show_recurse(&rd->contexts[ctxi], &chari, chars);
587 assert(chari==nchars);
588 qsort(chars, nchars, sizeof(*chars), show_char_compar);
591 for (local=0; local<2; local++) {
592 printf("%2d %-6s %-6s ", h, context_names[ctxi],
593 local?"local":"master");
594 for (chari=0; chari<nchars; chari++) {
595 const DatabaseNode *t= chars[chari];
596 static const char accept[]=
597 "abcdefghijklmnopqrstuvwxyz"
598 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
599 "0123456789" "'!&-+.,>";
601 if (t->local != local) continue;
604 printf(" [nomatch]");
605 else if (!t->endsword && strspn(t->str, accept) == strlen(t->str))
606 printf(" %s",t->str);
612 if (c=='"' || c=='\\') printf("\\%c",c);
613 else if (c>=' ' && c<=126) putchar(c);
614 else printf("\\x%02x", (unsigned char)c);
616 if (t->endsword) putchar(' ');