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;
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);
104 static void readdb(OcrReader *rd) {
107 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
108 cleardb_node(&rd->contexts[ctxi]);
110 readdb1(rd, "master");
111 readdb1(rd, "local");
114 static void readdb1(OcrReader *rd, const char *which) {
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) {
202 current->str= mmalloc(nchrs+1);
203 memcpy(current->str, chrs, nchrs);
204 current->str[nchrs]= 0;
206 current->endsword= endsword;
215 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
216 fprintf(resolver,"{");
219 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
220 if (!(ctxmap & (1u << ctxi))) continue;
221 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
224 fprintf(resolver,"}");
227 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
228 int unk_l, int unk_r, unsigned unk_ctxmap) {
230 const OcrResultGlyph *s;
234 FILE *resolver= resolve_start();
235 if (!resolver || !(o_flags & ff_editcharset))
236 fatal("OCR failed - unrecognised characters or ligatures.\n"
237 "Character set database needs to be updated or augmented.\n"
238 "See README.charset.\n");
242 "%d %d ",unk_l,unk_r);
243 cu_pr_ctxmap(resolver,unk_ctxmap);
244 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
245 if (!strcmp(s->s," ")) continue;
246 fprintf(resolver," %d %d ",s->l,s->r);
247 cu_pr_ctxmap(resolver, 1u << s->match);
248 fprintf(resolver," ");
249 cu_pr_ctxmap(resolver, s->ctxmap);
250 fprintf(resolver," ");
251 for (p=s->s; (c= *p); p++) {
252 if (c=='\\') fprintf(resolver,"\\%c",c);
253 else if (c>=33 && c<=126) fputc(c,resolver);
254 else fprintf(resolver,"\\x%02x",(unsigned char)c);
257 fputc('\n',resolver);
261 "static char *t[] = {\n"
262 "/* columns rows colors chars-per-pixel */\n"
267 for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
270 fputc(cols[x] & pv ? 'o' : ' ', resolver);
271 fputs("\",\n",resolver);
273 fputs("};\n",resolver);
279 static void add_result(OcrReader *rd, const char *s, int l, int r,
280 int match, unsigned ctxmap) {
281 if (rd->nresults >= rd->aresults) {
282 rd->aresults++; rd->aresults<<=1;
283 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
285 rd->results[rd->nresults].s= s;
286 rd->results[rd->nresults].l= l;
287 rd->results[rd->nresults].r= r;
288 rd->results[rd->nresults].match= match;
289 rd->results[rd->nresults].ctxmap= ctxmap;
294 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
295 DatabaseNode *start, int *matchx_r) {
296 DatabaseNode *current= start;
297 DatabaseNode *bestmatch= 0;
304 if (x > fca->w) break;
305 Pixcol cv= fca->cols[x];
306 debugf(" cv=%"PSPIXCOL(PRIx),cv);
307 for (i=0; i<current->nlinks; i++)
308 if (current->links[i].col == cv)
315 current= current->links[i].then;
316 if (current->match) {
317 debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
329 static DatabaseNode *findchar(const FindCharArgs *fca,
330 int *match_rx, int *match_rctxi) {
331 FindCharResults results[NCONTEXTS];
332 int ctxi, match=-1, nmatches=0;
334 debugf("OCR lx=%d ct_state=%x ", fca->x, fca->ctxmap);
335 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
336 results[ctxi].match= 0;
337 if (!(fca->ctxmap & (1u << ctxi))) continue;
338 debugf(" || %s",context_names[ctxi]);
340 results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
342 if (!results[ctxi].match) continue;
350 debugf(" ambiguous");
351 match= !fca->ct->findchar_select ? -1 :
352 fca->ct->findchar_select(fca,results);
353 debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
358 *match_rx= results[match].rx;
359 if (match_rctxi) *match_rctxi= match;
360 return results[match].match;
363 static int findchar_select_text(const FindCharArgs *fca,
364 const FindCharResults results[]) {
365 if (fca->ctxmap != 017) return -1;
367 dbassert(! results[ct_Digit].match );
368 if (results[ct_Word].match) return ct_Word;
369 if (results[ct_Lower].rx > results[ct_Upper].rx) return ct_Lower;
370 if (results[ct_Upper].rx > results[ct_Lower].rx) return ct_Upper;
374 const struct OcrCellTypeInfo ocr_celltype_number= {
375 ctf_Digit, ctf_Digit, ctf_Digit,
380 const struct OcrCellTypeInfo ocr_celltype_text= {
381 .initial= ctf_Digit | ctf_Upper,
382 .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
383 .midword= ctf_Digit | ctf_Lower,
386 .findchar_select= findchar_select_text
390 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
392 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
406 fca.ctxmap= ct->initial;
408 debugf("OCR h=%d w=%d",rd->h,w);
409 for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
423 if (nspaces == ct->space_spaces) {
424 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
425 fca.ctxmap= ct->nextword;
430 /* something here, so we need to add the spaces */
431 if (nspaces >= ct->space_spaces)
432 add_result(rd," ",x-nspaces,x+1,-1,0);
439 DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
443 add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
445 if (match->match) fca.ctxmap= ct->midword;
446 else debugf(" (empty)");
447 if (match->endsword) {
448 nspaces= ct->space_spaces;
450 fca.ctxmap= ct->nextword;
455 debugf(" || UNKNOWN");
456 for (rx=x; rx<w && cols[rx]; rx++);
457 debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
459 callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
464 add_result(rd, 0,-1,-1,-1,0);
465 debugf("OCR finished %d glyphs\n",rd->nresults);
470 OcrReader *ocr_init(int h) {
473 if (o_flags & ff_dict_fetch) {
474 char *fetchfile= masprintf("char%d",h);
475 progress("Updating %s...",fetchfile);
476 fetch_with_rsync(fetchfile);
480 rd= mmalloc(sizeof(*rd));
481 memset(rd,0,sizeof(*rd));