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];
88 OcrResultGlyph *results;
89 int aresults, nresults;
92 DEBUG_DEFINE_DEBUGF(ocr)
94 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
96 static void cleardb_node(DatabaseNode *n) {
98 free(n->str); n->str=0;
99 n->defined=n->match=n->endsword= 0;
100 for (i=0; i<n->nlinks; i++)
101 cleardb_node(n->links[i].then);
104 static void readdb1(OcrReader *rd, const char *which, int local);
106 static void readdb(OcrReader *rd) {
109 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
110 cleardb_node(&rd->contexts[ctxi]);
112 readdb1(rd, "master", 0);
113 readdb1(rd, "local", 1);
116 static void readdb1(OcrReader *rd, const char *which, int local) {
118 DatabaseNode *current, *additional;
125 char *dbfname= masprintf("%s/_%s-char%d.txt",
126 get_vardir(), which, rd->h);
128 if (!dbfile_open(dbfname))
132 o_flags |= ff_charset_havelocal;
135 dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v3 depth=" STRING(AADEPTH)));
137 dbassert( dbfile_scanf("%d", &h) == 1);
142 if (!lbuf[0] || lbuf[0]=='#') continue;
143 if (!strcmp(lbuf,".")) break;
145 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
146 if (!strcmp(lbuf,context_names[ctxi]))
148 /* not found, just skip */
149 for (;;) { FGETSLINE; if (!lbuf[0]) break; }
154 int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
155 if (c=='\n') break; /* forces no match */
156 dbassert(nchrs<sizeof(chrs));
160 if (nchrs>0 && chrs[nchrs-1]==' ') {
165 current= &rd->contexts[ctxi];
168 if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
169 dbassert( strlen(lbuf) == rd->h );
172 for (y=0; y<h; y++) {
177 unsigned pv= strtoul(pb,&ep,16); dbassert(!*ep);
178 pixcol_p_add(&cv, y, pv);
181 for (j=0; j<current->nlinks; j++)
182 if (!pixcol_cmp(&cv, ¤t->links[j].col)) {
183 current= current->links[j].then;
187 additional= mmalloc(sizeof(*additional));
189 additional->defined= 0;
190 additional->match= 0;
191 additional->endsword= 0;
192 additional->nlinks= additional->alinks= 0;
193 additional->links= 0;
194 if (current->nlinks==current->alinks) {
197 current->links= mrealloc(current->links,
198 sizeof(*current->links) * current->alinks);
200 current->links[current->nlinks].col= cv;
201 current->links[current->nlinks].then= additional;
208 if (!current->defined) {
213 current->local= local;
216 current->str= mmalloc(nchrs+1);
217 memcpy(current->str, chrs, nchrs);
218 current->str[nchrs]= 0;
220 current->endsword= endsword;
229 typedef struct Rejection Rejection;
231 struct Rejection *next;
237 Rejection *rejections;
239 static void load_rejections(const char *which) {
241 char *fname= masprintf("%s/_%s-reject.txt", get_vardir(), which);
245 if (!dbfile_open(fname)) { free(fname); return; }
247 while ((c= fgetc(dbfile))!=EOF) {
250 dbfile_getsline(lbuf,sizeof(lbuf),fname,lno);
252 if (!lbuf[0] || isspace(lbuf[0] || lbuf[0]=='#'))
255 rej= mmalloc(sizeof(*rej));
256 rej->next= rejections;
262 rej->re= pcre_compile(lbuf, PCRE_NO_AUTO_CAPTURE|PCRE_UTF8,
263 &err, &erroffset, 0);
265 char *what= masprintf("invalid regexp at offset %d: %s\n",
267 dbfile_assertfail(fname, lno, what);
269 debugf("OCR LOADED REJECTION %s:%d `%s' %p\n", fname,lno, lbuf, rej->re);
273 sysassert(feof(dbfile));
277 static int should_reject(OcrReader *rd) {
278 static int rejections_loaded;
281 if (!rejections_loaded) {
282 if (o_flags & ff_dict_fetch)
283 fetch_with_rsync("reject");
284 load_rejections("master");
285 load_rejections("local");
289 debugf("[OCR REJECTION `%s'%d", rd->result, rd->lresult);
291 for (rej=rejections; rej; rej=rej->next) {
292 debugf(" (%p)", rej);
294 int res= pcre_exec(rej->re, 0, rd->result,rd->lresult, 0,
295 0, ovector, ARRAYSIZE(ovector));
296 if (res==PCRE_ERROR_NOMATCH) continue;
300 fprintf(stderr,"Rejecting OCR result `%s' (due to %s:%d)\n",
301 rd->result, rej->fname,rej->lno);
308 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
309 fprintf(resolver,"{");
312 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
313 if (!(ctxmap & (1u << ctxi))) continue;
314 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
317 fprintf(resolver,"}");
320 static void callout_unknown(OcrReader *rd, int w, const Pixcol cols[],
321 int unk_l, int unk_r, unsigned unk_ctxmap) {
323 const OcrResultGlyph *s;
326 FILE *resolver= resolve_start();
328 !((o_flags & ff_charset_edit) ||
329 ((o_flags & ff_charset_allowedit) &&
330 (o_flags & ff_charset_havelocal))))
331 fatal("OCR failed - unrecognised characters or ligatures.\n"
332 "Character set database needs to be updated or augmented.\n"
333 "See README.charset.\n");
337 "%d %d ",unk_l,unk_r);
338 cu_pr_ctxmap(resolver,unk_ctxmap);
339 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
340 if (!strcmp(s->s," ")) continue;
341 fprintf(resolver," %d %d ",s->l,s->r);
342 cu_pr_ctxmap(resolver, 1u << s->match);
343 fprintf(resolver," ");
344 cu_pr_ctxmap(resolver, s->ctxmap);
345 fprintf(resolver," ");
346 for (p=s->s; (c= *p); p++) {
347 if (c=='\\') fprintf(resolver,"\\%c",c);
348 else if (c>=33 && c<=126) fputc(c,resolver);
349 else fprintf(resolver,"\\x%02x",(unsigned char)c);
352 fputc('\n',resolver);
355 "P2\n%d %d %d\n", w, rd->h, AAMAXVAL);
356 for (y=0; y<rd->h; y++) {
358 fprintf(resolver, " %d", pixcol_p_get(&cols[x], y));
359 fputc('\n',resolver);
366 static void add_result(OcrReader *rd, const char *s, int l, int r,
367 int match, unsigned ctxmap) {
368 if (rd->nresults >= rd->aresults) {
369 rd->aresults++; rd->aresults<<=1;
370 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
372 rd->results[rd->nresults].s= s;
373 rd->results[rd->nresults].l= l;
374 rd->results[rd->nresults].r= r;
375 rd->results[rd->nresults].match= match;
376 rd->results[rd->nresults].ctxmap= ctxmap;
379 if (!s) return; /* just the sentinel for the caller */
382 int newlresult= rd->lresult + sl;
383 if (newlresult >= rd->aresult) {
384 rd->aresult= (newlresult << 1) + 1;
385 rd->result= mrealloc(rd->result, rd->aresult);
387 memcpy(rd->result + rd->lresult, s, sl);
388 rd->lresult= newlresult;
389 rd->result[rd->lresult]= 0;
393 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
394 DatabaseNode *start, int *matchx_r) {
395 DatabaseNode *current= start;
396 DatabaseNode *bestmatch= 0;
401 if (DEBUGP(ocr)) debug_flush();
403 if (x > fca->w) break;
404 Pixcol cv= fca->cols[x];
405 debugf(" cv="PIXCOL_PRFMT, PIXCOL_PRVAL(cv));
406 for (i=0; i<current->nlinks; i++)
407 if (!pixcol_cmp(&cv, ¤t->links[i].col))
414 current= current->links[i].then;
415 if (current->match) {
416 debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
428 static DatabaseNode *findchar(const FindCharArgs *fca,
429 int *match_rx, int *match_rctxi) {
430 FindCharResults results[NCONTEXTS];
431 int ctxi, match=-1, nmatches=0;
433 debugf("OCR lx=%d ct_state=%x ", fca->x, fca->ctxmap);
434 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
435 results[ctxi].match= 0;
436 if (!(fca->ctxmap & (1u << ctxi))) continue;
437 debugf(" || %s",context_names[ctxi]);
439 results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
441 if (!results[ctxi].match) continue;
449 debugf(" ambiguous");
450 match= !fca->ct->findchar_select ? -1 :
451 fca->ct->findchar_select(fca,results);
452 debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
457 *match_rx= results[match].rx;
458 if (match_rctxi) *match_rctxi= match;
459 return results[match].match;
462 static int findchar_select_text(const FindCharArgs *fca,
463 const FindCharResults results[]) {
465 dbassert(! results[ct_Digit].match ); /* digits are supposedly unambiguous */
467 switch (fca->ctxmap) {
469 #define RETURN_IF_LONGER(this,that) do{ \
470 if (results[ct_##this].rx > results[ct_##that].rx) \
474 case ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word:
475 /* Start of word. Prefer Word match; failing that, take the longest */
476 if (results[ct_Word].match) return ct_Word;
477 RETURN_IF_LONGER(Lower,Upper);
478 RETURN_IF_LONGER(Upper,Lower);
481 case ctf_Digit | ctf_Upper | ctf_Lower:
482 /* Mid-word. Prefer longer match; failing that, match lower. */
483 RETURN_IF_LONGER(Upper,Lower);
491 const struct OcrCellTypeInfo ocr_celltype_number= {
492 ctf_Digit, ctf_Digit, ctf_Digit,
497 const struct OcrCellTypeInfo ocr_celltype_text= {
498 .initial= ctf_Digit | ctf_Upper,
499 .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
500 .midword= ctf_Digit | ctf_Upper | ctf_Lower,
503 .findchar_select= findchar_select_text
507 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
509 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w,
510 const Pixcol cols[]) {
524 fca.ctxmap= ct->initial;
528 debugf("OCR h=%d w=%d",rd->h,w);
529 for (x=0; x<w; x++) debugf(" "PIXCOL_PRFMT, PIXCOL_PRVAL(cols[x]));
535 if (DEBUGP(ocr)) debug_flush();
540 if (!pixcol_nonzero(&cols[x])) {
543 if (nspaces == ct->space_spaces) {
544 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
545 fca.ctxmap= ct->nextword;
550 /* something here, so we need to add the spaces */
551 if (nspaces >= ct->space_spaces)
552 add_result(rd," ",x-nspaces,x+1,-1,0);
559 DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
563 add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
564 if (should_reject(rd)) {
565 callout_unknown(rd, w,cols, match_rx+1,match_rx, 0);
569 if (match->match) fca.ctxmap= ct->midword;
570 else debugf(" (empty)");
571 if (match->endsword) {
572 nspaces= ct->space_spaces;
574 fca.ctxmap= ct->nextword;
579 debugf(" || UNKNOWN");
580 for (rx=x; rx<w && pixcol_nonzero(&cols[rx]); rx++);
581 debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
583 callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
588 add_result(rd, 0,-1,-1,-1,0);
589 debugf("OCR finished %d glyphs\n",rd->nresults);
594 OcrReader *ocr_init(int h) {
597 assert(h <= OCR_MAX_H);
599 if (o_flags & ff_dict_fetch) {
600 char *fetchfile= masprintf("char%d",h);
601 fetch_with_rsync(fetchfile);
605 rd= mmalloc(sizeof(*rd));
606 memset(rd,0,sizeof(*rd));
611 rd->result= mmalloc(rd->aresult);
617 /*---------- character set dump ----------*/
619 static void show_recurse(const DatabaseNode *t, int *count,
620 const DatabaseNode **store_ary) {
622 if (store_ary) store_ary[*count]= t;
626 for (l=0; l<t->nlinks; l++)
627 show_recurse(t->links[l].then, count,store_ary);
630 static int show_char_compar(const void *av, const void *bv) {
631 const DatabaseNode *const *ap= av; const DatabaseNode *a= *ap;
632 const DatabaseNode *const *bp= bv; const DatabaseNode *b= *bp;
633 return strcmp(a->str, b->str) ?:
634 ((int)a->match - (int)b->match) ?:
635 ((int)a->endsword - (int)b->endsword) ?:
636 ((int)a->local - (int)b->local) ?:
640 void ocr_showcharsets(void) {
643 char found[OCR_MAX_H];
647 const char *pcre_err;
650 memset(found,0,sizeof(found));
652 fnpat= pcre_compile("_(?:master|local)\\-char([1-9]\\d{0,2})\\.txt$",
653 PCRE_ANCHORED|PCRE_DOLLAR_ENDONLY,
654 &pcre_err,&pcre_erroffset, 0);
655 debugf("pcre_compile %p %s\n",fnpat,pcre_err);
658 sysassert( d= opendir(get_vardir()) );
660 errno=0; de= readdir(d); if (!de) break;
662 int rer= pcre_exec(fnpat,0, de->d_name,strlen(de->d_name), 0,0,
663 matchvec,ARRAYSIZE(matchvec));
664 debugf("pcre_exec `%s' => %d\n", de->d_name,rer);
666 if (rer==PCRE_ERROR_NOMATCH || rer==PCRE_ERROR_BADUTF8) continue;
669 rer= pcre_copy_substring(de->d_name,matchvec,rer, 1, hbuf,sizeof(hbuf));
670 debugf("pcre_copy_substring => %d\n", rer);
674 if (h >= ARRAYSIZE(found)) continue;
680 for (h=0; h<ARRAYSIZE(found); h++) {
681 if (!found[h]) continue;
683 OcrReader *rd= ocr_init(h); /* we leak this but never mind */
687 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
689 show_recurse(&rd->contexts[ctxi], &nchars, 0);
690 const DatabaseNode **chars= mmalloc(sizeof(*chars) * nchars);
692 show_recurse(&rd->contexts[ctxi], &chari, chars);
693 assert(chari==nchars);
694 qsort(chars, nchars, sizeof(*chars), show_char_compar);
697 for (local=0; local<2; local++) {
698 printf("%2d %-6s %-6s ", h, context_names[ctxi],
699 local?"local":"master");
700 for (chari=0; chari<nchars; chari++) {
701 const DatabaseNode *t= chars[chari];
702 static const char accept[]=
703 "abcdefghijklmnopqrstuvwxyz"
704 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
705 "0123456789" "'!&-+.,>";
707 if (t->local != local) continue;
710 printf(" [nomatch]");
711 else if (!t->endsword && strspn(t->str, accept) == strlen(t->str))
712 printf(" %s",t->str);
718 if (c=='"' || c=='\\') printf("\\%c",c);
719 else if (c>=' ' && c<=126) putchar(c);
720 else printf("\\x%02x", (unsigned char)c);
722 if (t->endsword) putchar(' ');