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.
32 struct DatabaseNode *then;
35 typedef struct DatabaseNode {
38 unsigned match:1, defined:1, endsword:1, local:1;
55 #define FOR_EACH_CONTEXT(EACH) \
61 #define FEC_ENUM(Context) ct_##Context,
62 #define FEC_BIT(Context) ctf_##Context = 1 << ct_##Context,
64 FOR_EACH_CONTEXT(FEC_ENUM)
65 FOR_EACH_CONTEXT(FEC_BIT)
68 #define FEC_STRINGS(Context) #Context,
69 static const char *context_names[]= { FOR_EACH_CONTEXT(FEC_STRINGS) };
71 struct OcrCellTypeInfo {
72 /* bitmaps of indices into context_names: */
73 unsigned initial, nextword, midword;
76 int (*findchar_select)(const FindCharArgs *fca,
77 const FindCharResults results[]);
80 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
84 DatabaseNode contexts[NCONTEXTS];
87 OcrResultGlyph *results;
88 int aresults, nresults;
91 DEBUG_DEFINE_DEBUGF(ocr)
93 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
95 static void cleardb_node(DatabaseNode *n) {
97 free(n->str); n->str=0;
98 n->defined=n->match=n->endsword= 0;
99 for (i=0; i<n->nlinks; i++)
100 cleardb_node(n->links[i].then);
103 static void readdb1(OcrReader *rd, const char *which, int local);
105 static void readdb(OcrReader *rd) {
108 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
109 cleardb_node(&rd->contexts[ctxi]);
111 readdb1(rd, "master", 0);
112 readdb1(rd, "local", 1);
115 static void readdb1(OcrReader *rd, const char *which, int local) {
117 DatabaseNode *current, *additional;
124 char *dbfname= masprintf("%s/_%s-char%d.txt",
125 get_vardir(), which, rd->h);
127 if (!dbfile_open(dbfname))
131 o_flags |= ff_charset_havelocal;
134 dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v3 depth=" STRING(AADEPTH)));
136 dbassert( dbfile_scanf("%d", &h) == 1);
141 if (!lbuf[0] || lbuf[0]=='#') continue;
142 if (!strcmp(lbuf,".")) break;
144 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
145 if (!strcmp(lbuf,context_names[ctxi]))
147 /* not found, just skip */
148 for (;;) { FGETSLINE; if (!lbuf[0]) break; }
153 int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
154 if (c=='\n') break; /* forces no match */
155 dbassert(nchrs<sizeof(chrs));
159 if (nchrs>0 && chrs[nchrs-1]==' ') {
164 current= &rd->contexts[ctxi];
167 if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
168 dbassert( strlen(lbuf) == rd->h );
171 for (y=0; y<h; y++) {
176 unsigned pv= strtoul(pb,&ep,16); dbassert(!*ep);
177 pixcol_p_add(&cv, y, pv);
180 for (j=0; j<current->nlinks; j++)
181 if (!pixcol_cmp(&cv, ¤t->links[j].col)) {
182 current= current->links[j].then;
186 additional= mmalloc(sizeof(*additional));
188 additional->defined= 0;
189 additional->match= 0;
190 additional->endsword= 0;
191 additional->nlinks= additional->alinks= 0;
192 additional->links= 0;
193 if (current->nlinks==current->alinks) {
196 current->links= mrealloc(current->links,
197 sizeof(*current->links) * current->alinks);
199 current->links[current->nlinks].col= cv;
200 current->links[current->nlinks].then= additional;
207 if (!current->defined) {
212 current->local= local;
215 current->str= mmalloc(nchrs+1);
216 memcpy(current->str, chrs, nchrs);
217 current->str[nchrs]= 0;
219 current->endsword= endsword;
228 typedef struct Rejection Rejection;
230 struct Rejection *next;
236 Rejection *rejections;
238 static void load_rejections(const char *which) {
240 char *fname= masprintf("%s/_%s-reject.txt", get_vardir(), which);
244 if (!dbfile_open(fname)) { free(fname); return; }
246 while ((c= fgetc(dbfile))!=EOF) {
249 dbfile_getsline(lbuf,sizeof(lbuf),fname,lno);
251 if (!lbuf[0] || isspace(lbuf[0] || lbuf[0]=='#'))
254 rej= mmalloc(sizeof(*rej));
255 rej->next= rejections;
261 rej->re= pcre_compile(lbuf, PCRE_NO_AUTO_CAPTURE|PCRE_UTF8,
262 &err, &erroffset, 0);
264 char *what= masprintf("invalid regexp at offset %d: %s\n",
266 dbfile_assertfail(fname, lno, what);
268 debugf("OCR LOADED REJECTION %s:%d `%s' %p\n", fname,lno, lbuf, rej->re);
272 sysassert(feof(dbfile));
276 static int should_reject(OcrReader *rd) {
277 static int rejections_loaded;
280 if (!rejections_loaded) {
281 if (o_flags & ff_dict_fetch)
282 fetch_with_rsync("reject");
283 load_rejections("master");
284 load_rejections("local");
288 debugf("[OCR REJECTION `%s'%d", rd->result, rd->lresult);
290 for (rej=rejections; rej; rej=rej->next) {
291 debugf(" (%p)", rej);
293 int res= pcre_exec(rej->re, 0, rd->result,rd->lresult, 0,
294 0, ovector, ARRAYSIZE(ovector));
295 if (res==PCRE_ERROR_NOMATCH) continue;
299 fprintf(stderr,"Rejecting OCR result `%s' (due to %s:%d)\n",
300 rd->result, rej->fname,rej->lno);
307 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
308 fprintf(resolver,"{");
311 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
312 if (!(ctxmap & (1u << ctxi))) continue;
313 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
316 fprintf(resolver,"}");
319 static void callout_unknown(OcrReader *rd, int w, const Pixcol cols[],
320 int unk_l, int unk_r, unsigned unk_ctxmap) {
322 const OcrResultGlyph *s;
325 FILE *resolver= resolve_start();
327 !((o_flags & ff_charset_edit) ||
328 ((o_flags & ff_charset_allowedit) &&
329 (o_flags & ff_charset_havelocal))))
330 fatal("OCR failed - unrecognised characters or ligatures.\n"
331 "Character set database needs to be updated or augmented.\n"
332 "See README.charset.\n");
336 "%d %d ",unk_l,unk_r);
337 cu_pr_ctxmap(resolver,unk_ctxmap);
338 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
339 if (!strcmp(s->s," ")) continue;
340 fprintf(resolver," %d %d ",s->l,s->r);
341 cu_pr_ctxmap(resolver, 1u << s->match);
342 fprintf(resolver," ");
343 cu_pr_ctxmap(resolver, s->ctxmap);
344 fprintf(resolver," ");
345 for (p=s->s; (c= *p); p++) {
346 if (c=='\\') fprintf(resolver,"\\%c",c);
347 else if (c>=33 && c<=126) fputc(c,resolver);
348 else fprintf(resolver,"\\x%02x",(unsigned char)c);
351 fputc('\n',resolver);
354 "P2\n%d %d %d\n", w, rd->h, AAMAXVAL);
355 for (y=0; y<rd->h; y++) {
357 fprintf(resolver, " %d", pixcol_p_get(&cols[x], y));
358 fputc('\n',resolver);
365 static void add_result(OcrReader *rd, const char *s, int l, int r,
366 int match, unsigned ctxmap) {
367 if (rd->nresults >= rd->aresults) {
368 rd->aresults++; rd->aresults<<=1;
369 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
371 rd->results[rd->nresults].s= s;
372 rd->results[rd->nresults].l= l;
373 rd->results[rd->nresults].r= r;
374 rd->results[rd->nresults].match= match;
375 rd->results[rd->nresults].ctxmap= ctxmap;
378 if (!s) return; /* just the sentinel for the caller */
381 int newlresult= rd->lresult + sl;
382 if (newlresult >= rd->aresult) {
383 rd->aresult= (newlresult << 1) + 1;
384 rd->result= mrealloc(rd->result, rd->aresult);
386 memcpy(rd->result + rd->lresult, s, sl);
387 rd->lresult= newlresult;
388 rd->result[rd->lresult]= 0;
392 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
393 DatabaseNode *start, int *matchx_r) {
394 DatabaseNode *current= start;
395 DatabaseNode *bestmatch= 0;
400 if (DEBUGP(ocr)) debug_flush();
402 if (x > fca->w) break;
403 Pixcol cv= fca->cols[x];
404 debugf(" cv="PIXCOL_PRFMT, PIXCOL_PRVAL(cv));
405 for (i=0; i<current->nlinks; i++)
406 if (!pixcol_cmp(&cv, ¤t->links[i].col))
413 current= current->links[i].then;
414 if (current->match) {
415 debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
427 static DatabaseNode *findchar(const FindCharArgs *fca,
428 int *match_rx, int *match_rctxi) {
429 FindCharResults results[NCONTEXTS];
430 int ctxi, match=-1, nmatches=0;
432 debugf("OCR lx=%d ct_state=%x ", fca->x, fca->ctxmap);
433 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
434 results[ctxi].match= 0;
435 if (!(fca->ctxmap & (1u << ctxi))) continue;
436 debugf(" || %s",context_names[ctxi]);
438 results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
440 if (!results[ctxi].match) continue;
448 debugf(" ambiguous");
449 match= !fca->ct->findchar_select ? -1 :
450 fca->ct->findchar_select(fca,results);
451 debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
456 *match_rx= results[match].rx;
457 if (match_rctxi) *match_rctxi= match;
458 return results[match].match;
461 static int findchar_select_text(const FindCharArgs *fca,
462 const FindCharResults results[]) {
464 dbassert(! results[ct_Digit].match ); /* digits are supposedly unambiguous */
466 switch (fca->ctxmap) {
468 #define RETURN_IF_LONGER(this,that) do{ \
469 if (results[ct_##this].rx > results[ct_##that].rx) \
473 case ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word:
474 /* Start of word. Prefer Word match; failing that, take the longest */
475 if (results[ct_Word].match) return ct_Word;
476 RETURN_IF_LONGER(Lower,Upper);
477 RETURN_IF_LONGER(Upper,Lower);
480 case ctf_Digit | ctf_Upper | ctf_Lower:
481 /* Mid-word. Prefer longer match; failing that, match lower. */
482 RETURN_IF_LONGER(Upper,Lower);
490 const struct OcrCellTypeInfo ocr_celltype_number= {
491 ctf_Digit, ctf_Digit, ctf_Digit,
496 const struct OcrCellTypeInfo ocr_celltype_text= {
497 .initial= ctf_Digit | ctf_Upper,
498 .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
499 .midword= ctf_Digit | ctf_Upper | ctf_Lower,
502 .findchar_select= findchar_select_text
506 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
508 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w,
509 const Pixcol cols[]) {
523 fca.ctxmap= ct->initial;
527 debugf("OCR h=%d w=%d",rd->h,w);
528 for (x=0; x<w; x++) debugf(" "PIXCOL_PRFMT, PIXCOL_PRVAL(cols[x]));
534 if (DEBUGP(ocr)) debug_flush();
539 if (!pixcol_nonzero(&cols[x])) {
542 if (nspaces == ct->space_spaces) {
543 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
544 fca.ctxmap= ct->nextword;
549 /* something here, so we need to add the spaces */
550 if (nspaces >= ct->space_spaces)
551 add_result(rd," ",x-nspaces,x+1,-1,0);
558 DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
562 add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
563 if (should_reject(rd)) {
564 callout_unknown(rd, w,cols, match_rx+1,match_rx, 0);
568 if (match->match) fca.ctxmap= ct->midword;
569 else debugf(" (empty)");
570 if (match->endsword) {
571 nspaces= ct->space_spaces;
573 fca.ctxmap= ct->nextword;
578 debugf(" || UNKNOWN");
579 for (rx=x; rx<w && pixcol_nonzero(&cols[rx]); rx++);
580 debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
582 callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
587 add_result(rd, 0,-1,-1,-1,0);
588 debugf("OCR finished %d glyphs\n",rd->nresults);
593 OcrReader *ocr_init(int h) {
596 assert(h <= OCR_MAX_H);
598 if (o_flags & ff_dict_fetch) {
599 char *fetchfile= masprintf("char%d",h);
600 fetch_with_rsync(fetchfile);
604 rd= mmalloc(sizeof(*rd));
605 memset(rd,0,sizeof(*rd));
610 rd->result= mmalloc(rd->aresult);
616 /*---------- character set dump ----------*/
618 static void show_recurse(const DatabaseNode *t, int *count,
619 const DatabaseNode **store_ary) {
621 if (store_ary) store_ary[*count]= t;
625 for (l=0; l<t->nlinks; l++)
626 show_recurse(t->links[l].then, count,store_ary);
629 static int show_char_compar(const void *av, const void *bv) {
630 const DatabaseNode *const *ap= av; const DatabaseNode *a= *ap;
631 const DatabaseNode *const *bp= bv; const DatabaseNode *b= *bp;
632 return strcmp(a->str, b->str) ?:
633 ((int)a->match - (int)b->match) ?:
634 ((int)a->endsword - (int)b->endsword) ?:
635 ((int)a->local - (int)b->local) ?:
639 void ocr_showcharsets(void) {
642 char found[OCR_MAX_H];
646 const char *pcre_err;
649 memset(found,0,sizeof(found));
651 fnpat= pcre_compile("_(?:master|local)\\-char([1-9]\\d{0,2})\\.txt$",
652 PCRE_ANCHORED|PCRE_DOLLAR_ENDONLY,
653 &pcre_err,&pcre_erroffset, 0);
654 debugf("pcre_compile %p %s\n",fnpat,pcre_err);
657 sysassert( d= opendir(get_vardir()) );
659 errno=0; de= readdir(d); if (!de) break;
661 int rer= pcre_exec(fnpat,0, de->d_name,strlen(de->d_name), 0,0,
662 matchvec,ARRAYSIZE(matchvec));
663 debugf("pcre_exec `%s' => %d\n", de->d_name,rer);
665 if (rer==PCRE_ERROR_NOMATCH || rer==PCRE_ERROR_BADUTF8) continue;
668 rer= pcre_copy_substring(de->d_name,matchvec,rer, 1, hbuf,sizeof(hbuf));
669 debugf("pcre_copy_substring => %d\n", rer);
673 if (h >= ARRAYSIZE(found)) continue;
679 for (h=0; h<ARRAYSIZE(found); h++) {
680 if (!found[h]) continue;
682 OcrReader *rd= ocr_init(h); /* we leak this but never mind */
686 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
688 show_recurse(&rd->contexts[ctxi], &nchars, 0);
689 const DatabaseNode **chars= mmalloc(sizeof(*chars) * nchars);
691 show_recurse(&rd->contexts[ctxi], &chari, chars);
692 assert(chari==nchars);
693 qsort(chars, nchars, sizeof(*chars), show_char_compar);
696 for (local=0; local<2; local++) {
697 printf("%2d %-6s %-6s ", h, context_names[ctxi],
698 local?"local":"master");
699 for (chari=0; chari<nchars; chari++) {
700 const DatabaseNode *t= chars[chari];
701 static const char accept[]=
702 "abcdefghijklmnopqrstuvwxyz"
703 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
704 "0123456789" "'!&-+.,>";
706 if (t->local != local) continue;
709 printf(" [nomatch]");
710 else if (!t->endsword && strspn(t->str, accept) == strlen(t->str))
711 printf(" %s",t->str);
717 if (c=='"' || c=='\\') printf("\\%c",c);
718 else if (c>=' ' && c<=126) putchar(c);
719 else printf("\\x%02x", (unsigned char)c);
721 if (t->endsword) putchar(' ');