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 dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
132 dbassert( dbfile_scanf("%d", &h) == 1);
137 if (!lbuf[0] || lbuf[0]=='#') continue;
138 if (!strcmp(lbuf,".")) break;
140 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
141 if (!strcmp(lbuf,context_names[ctxi]))
143 /* not found, just skip */
144 for (;;) { FGETSLINE; if (!lbuf[0]) break; }
149 int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
150 if (c=='\n') break; /* forces no match */
151 dbassert(nchrs<sizeof(chrs));
155 if (nchrs>0 && chrs[nchrs-1]==' ') {
160 current= &rd->contexts[ctxi];
163 if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
165 cv= strtoul(lbuf,&ep,16); dbassert(!*ep);
166 dbassert(!(cv & ~((1UL << rd->h)-1)));
168 for (j=0; j<current->nlinks; j++)
169 if (current->links[j].col == cv) {
170 current= current->links[j].then;
174 additional= mmalloc(sizeof(*additional));
176 additional->defined= 0;
177 additional->match= 0;
178 additional->endsword= 0;
179 additional->nlinks= additional->alinks= 0;
180 additional->links= 0;
181 if (current->nlinks==current->alinks) {
184 current->links= mrealloc(current->links,
185 sizeof(*current->links) * current->alinks);
187 current->links[current->nlinks].col= cv;
188 current->links[current->nlinks].then= additional;
195 if (!current->defined) {
200 current->local= local;
203 current->str= mmalloc(nchrs+1);
204 memcpy(current->str, chrs, nchrs);
205 current->str[nchrs]= 0;
207 current->endsword= endsword;
216 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
217 fprintf(resolver,"{");
220 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
221 if (!(ctxmap & (1u << ctxi))) continue;
222 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
225 fprintf(resolver,"}");
228 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
229 int unk_l, int unk_r, unsigned unk_ctxmap) {
231 const OcrResultGlyph *s;
235 FILE *resolver= resolve_start();
236 if (!resolver || !(o_flags & ff_editcharset))
237 fatal("OCR failed - unrecognised characters or ligatures.\n"
238 "Character set database needs to be updated or augmented.\n"
239 "See README.charset.\n");
243 "%d %d ",unk_l,unk_r);
244 cu_pr_ctxmap(resolver,unk_ctxmap);
245 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
246 if (!strcmp(s->s," ")) continue;
247 fprintf(resolver," %d %d ",s->l,s->r);
248 cu_pr_ctxmap(resolver, 1u << s->match);
249 fprintf(resolver," ");
250 cu_pr_ctxmap(resolver, s->ctxmap);
251 fprintf(resolver," ");
252 for (p=s->s; (c= *p); p++) {
253 if (c=='\\') fprintf(resolver,"\\%c",c);
254 else if (c>=33 && c<=126) fputc(c,resolver);
255 else fprintf(resolver,"\\x%02x",(unsigned char)c);
258 fputc('\n',resolver);
262 "static char *t[] = {\n"
263 "/* columns rows colors chars-per-pixel */\n"
268 for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
271 fputc(cols[x] & pv ? 'o' : ' ', resolver);
272 fputs("\",\n",resolver);
274 fputs("};\n",resolver);
280 static void add_result(OcrReader *rd, const char *s, int l, int r,
281 int match, unsigned ctxmap) {
282 if (rd->nresults >= rd->aresults) {
283 rd->aresults++; rd->aresults<<=1;
284 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
286 rd->results[rd->nresults].s= s;
287 rd->results[rd->nresults].l= l;
288 rd->results[rd->nresults].r= r;
289 rd->results[rd->nresults].match= match;
290 rd->results[rd->nresults].ctxmap= ctxmap;
295 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
296 DatabaseNode *start, int *matchx_r) {
297 DatabaseNode *current= start;
298 DatabaseNode *bestmatch= 0;
305 if (x > fca->w) break;
306 Pixcol cv= fca->cols[x];
307 debugf(" cv=%"PSPIXCOL(PRIx),cv);
308 for (i=0; i<current->nlinks; i++)
309 if (current->links[i].col == cv)
316 current= current->links[i].then;
317 if (current->match) {
318 debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
330 static DatabaseNode *findchar(const FindCharArgs *fca,
331 int *match_rx, int *match_rctxi) {
332 FindCharResults results[NCONTEXTS];
333 int ctxi, match=-1, nmatches=0;
335 debugf("OCR lx=%d ct_state=%x ", fca->x, fca->ctxmap);
336 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
337 results[ctxi].match= 0;
338 if (!(fca->ctxmap & (1u << ctxi))) continue;
339 debugf(" || %s",context_names[ctxi]);
341 results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
343 if (!results[ctxi].match) continue;
351 debugf(" ambiguous");
352 match= !fca->ct->findchar_select ? -1 :
353 fca->ct->findchar_select(fca,results);
354 debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
359 *match_rx= results[match].rx;
360 if (match_rctxi) *match_rctxi= match;
361 return results[match].match;
364 static int findchar_select_text(const FindCharArgs *fca,
365 const FindCharResults results[]) {
367 dbassert(! results[ct_Digit].match ); /* digits are supposedly unambiguous */
369 switch (fca->ctxmap) {
371 #define RETURN_IF_LONGER(this,that) do{ \
372 if (results[ct_##this].rx > results[ct_##that].rx) \
376 case ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word:
377 /* Start of word. Prefer Word match; failing that, take the longest */
378 if (results[ct_Word].match) return ct_Word;
379 RETURN_IF_LONGER(Lower,Upper);
380 RETURN_IF_LONGER(Upper,Lower);
383 case ctf_Digit | ctf_Upper | ctf_Lower:
384 /* Mid-word. Prefer longer match; failing that, match lower. */
385 RETURN_IF_LONGER(Upper,Lower);
393 const struct OcrCellTypeInfo ocr_celltype_number= {
394 ctf_Digit, ctf_Digit, ctf_Digit,
399 const struct OcrCellTypeInfo ocr_celltype_text= {
400 .initial= ctf_Digit | ctf_Upper,
401 .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
402 .midword= ctf_Digit | ctf_Upper | ctf_Lower,
405 .findchar_select= findchar_select_text
409 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
411 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
425 fca.ctxmap= ct->initial;
427 debugf("OCR h=%d w=%d",rd->h,w);
428 for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
442 if (nspaces == ct->space_spaces) {
443 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
444 fca.ctxmap= ct->nextword;
449 /* something here, so we need to add the spaces */
450 if (nspaces >= ct->space_spaces)
451 add_result(rd," ",x-nspaces,x+1,-1,0);
458 DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
462 add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
464 if (match->match) fca.ctxmap= ct->midword;
465 else debugf(" (empty)");
466 if (match->endsword) {
467 nspaces= ct->space_spaces;
469 fca.ctxmap= ct->nextword;
474 debugf(" || UNKNOWN");
475 for (rx=x; rx<w && cols[rx]; rx++);
476 debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
478 callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
483 add_result(rd, 0,-1,-1,-1,0);
484 debugf("OCR finished %d glyphs\n",rd->nresults);
489 OcrReader *ocr_init(int h) {
492 if (o_flags & ff_dict_fetch) {
493 char *fetchfile= masprintf("char%d",h);
494 progress("Updating %s...",fetchfile);
495 fetch_with_rsync(fetchfile);
499 rd= mmalloc(sizeof(*rd));
500 memset(rd,0,sizeof(*rd));
506 /*---------- character set dump ----------*/
508 static void show_recurse(const DatabaseNode *t, int *count,
509 const DatabaseNode **store_ary) {
511 if (store_ary) store_ary[*count]= t;
515 for (l=0; l<t->nlinks; l++)
516 show_recurse(t->links[l].then, count,store_ary);
519 static int show_char_compar(const void *av, const void *bv) {
520 const DatabaseNode *const *ap= av; const DatabaseNode *a= *ap;
521 const DatabaseNode *const *bp= bv; const DatabaseNode *b= *bp;
522 return strcmp(a->str, b->str) ?:
523 ((int)a->match - (int)b->match) ?:
524 ((int)a->endsword - (int)b->endsword) ?:
525 ((int)a->local - (int)b->local) ?:
529 void ocr_showcharsets(void) {
536 const char *pcre_err;
539 memset(found,0,sizeof(found));
541 fnpat= pcre_compile("\\#(?:master|local)\\-char([1-9]\\d{0,2})\\#\\.txt$",
542 PCRE_ANCHORED|PCRE_DOLLAR_ENDONLY,
543 &pcre_err,&pcre_erroffset, 0);
544 debugf("pcre_compile %p %s\n",fnpat,pcre_err);
547 sysassert( d= opendir(get_vardir()) );
549 errno=0; de= readdir(d); if (!de) break;
551 int rer= pcre_exec(fnpat,0, de->d_name,strlen(de->d_name), 0,0,
552 matchvec,ARRAYSIZE(matchvec));
553 debugf("pcre_exec `%s' => %d\n", de->d_name,rer);
555 if (rer==PCRE_ERROR_NOMATCH || rer==PCRE_ERROR_BADUTF8) continue;
558 rer= pcre_copy_substring(de->d_name,matchvec,rer, 1, hbuf,sizeof(hbuf));
559 debugf("pcre_copy_substring => %d\n", rer);
563 if (h >= ARRAYSIZE(found)) continue;
569 for (h=0; h<ARRAYSIZE(found); h++) {
570 if (!found[h]) continue;
572 OcrReader *rd= ocr_init(h); /* we leak this but never mind */
576 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
578 show_recurse(&rd->contexts[ctxi], &nchars, 0);
579 const DatabaseNode **chars= mmalloc(sizeof(*chars) * nchars);
581 show_recurse(&rd->contexts[ctxi], &chari, chars);
582 assert(chari==nchars);
583 qsort(chars, nchars, sizeof(*chars), show_char_compar);
586 for (local=0; local<2; local++) {
587 printf("%2d %-6s %-6s ", h, context_names[ctxi],
588 local?"local":"master");
589 for (chari=0; chari<nchars; chari++) {
590 const DatabaseNode *t= chars[chari];
591 static const char accept[]=
592 "abcdefghijklmnopqrstuvwxyz"
593 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
594 "0123456789" "'!&-+.,>";
596 if (t->local != local) continue;
599 printf(" [nomatch]");
600 else if (!t->endsword && strspn(t->str, accept) == strlen(t->str))
601 printf(" %s",t->str);
607 if (c=='"' || c=='\\') printf("\\%c",c);
608 else if (c>=' ' && c<=126) putchar(c);
609 else printf("\\x%02x", (unsigned char)c);
611 if (t->endsword) putchar(' ');