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 enum { ct_Lower, ct_Upper, ct_Word, ct_Digit };
57 static const char *context_names[]= {
58 "Lower", /* bit 0, value 001 */
59 "Upper", /* bit 1, value 002 */
60 "Word", /* bit 2, value 004 */
61 "Digit", /* bit 3, value 010 */
63 struct OcrCellTypeInfo {
64 /* bitmaps of indices into context_names: */
65 unsigned initial, nextword, midword;
68 int (*findchar_select)(const FindCharArgs *fca,
69 const FindCharResults results[]);
72 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
76 DatabaseNode contexts[NCONTEXTS];
77 OcrResultGlyph *results;
78 int aresults, nresults;
81 DEBUG_DEFINE_DEBUGF(ocr)
83 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
85 static void cleardb_node(DatabaseNode *n) {
87 free(n->str); n->str=0;
88 n->defined=n->match=n->endsword= 0;
89 for (i=0; i<n->nlinks; i++)
90 cleardb_node(n->links[i].then);
93 static void readdb1(OcrReader *rd, const char *which);
95 static void readdb(OcrReader *rd) {
98 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
99 cleardb_node(&rd->contexts[ctxi]);
101 readdb1(rd, "master");
102 readdb1(rd, "local");
105 static void readdb1(OcrReader *rd, const char *which) {
107 DatabaseNode *current, *additional;
114 char *dbfname= masprintf("%s/#%s-char%d#.txt",
115 get_vardir(), which, rd->h);
117 if (!dbfile_open(dbfname))
121 dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
123 dbassert( dbfile_scanf("%d", &h) == 1);
128 if (!lbuf[0] || lbuf[0]=='#') continue;
129 if (!strcmp(lbuf,".")) break;
131 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
132 if (!strcmp(lbuf,context_names[ctxi]))
134 /* not found, just skip */
135 for (;;) { FGETSLINE; if (!lbuf[0]) break; }
140 int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
141 if (c=='\n') break; /* forces no match */
142 dbassert(nchrs<sizeof(chrs));
146 if (nchrs>0 && chrs[nchrs-1]==' ') {
151 current= &rd->contexts[ctxi];
154 if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
156 cv= strtoul(lbuf,&ep,16); dbassert(!*ep);
157 dbassert(!(cv & ~((1UL << rd->h)-1)));
159 for (j=0; j<current->nlinks; j++)
160 if (current->links[j].col == cv) {
161 current= current->links[j].then;
165 additional= mmalloc(sizeof(*additional));
167 additional->defined= 0;
168 additional->match= 0;
169 additional->endsword= 0;
170 additional->nlinks= additional->alinks= 0;
171 additional->links= 0;
172 if (current->nlinks==current->alinks) {
175 current->links= mrealloc(current->links,
176 sizeof(*current->links) * current->alinks);
178 current->links[current->nlinks].col= cv;
179 current->links[current->nlinks].then= additional;
186 if (!current->defined) {
193 current->str= mmalloc(nchrs+1);
194 memcpy(current->str, chrs, nchrs);
195 current->str[nchrs]= 0;
197 current->endsword= endsword;
206 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
207 fprintf(resolver,"{");
210 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
211 if (!(ctxmap & (1u << ctxi))) continue;
212 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
215 fprintf(resolver,"}");
218 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
219 int unk_l, int unk_r, unsigned unk_ctxmap) {
221 const OcrResultGlyph *s;
225 FILE *resolver= resolve_start();
226 if (!resolver || !(o_flags & ff_editcharset))
227 fatal("OCR failed - unrecognised characters or ligatures.\n"
228 "Character set database needs to be updated or augmented.\n"
229 "See README.charset.\n");
233 "%d %d ",unk_l,unk_r);
234 cu_pr_ctxmap(resolver,unk_ctxmap);
235 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
236 if (!strcmp(s->s," ")) continue;
237 fprintf(resolver," %d %d ",s->l,s->r);
238 cu_pr_ctxmap(resolver, 1u << s->ctxi);
239 fprintf(resolver," ");
240 for (p=s->s; (c= *p); p++) {
241 if (c=='\\') fprintf(resolver,"\\%c",c);
242 else if (c>=33 && c<=126) fputc(c,resolver);
243 else fprintf(resolver,"\\x%02x",(unsigned char)c);
246 fputc('\n',resolver);
250 "static char *t[] = {\n"
251 "/* columns rows colors chars-per-pixel */\n"
256 for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
259 fputc(cols[x] & pv ? 'o' : ' ', resolver);
260 fputs("\",\n",resolver);
262 fputs("};\n",resolver);
268 static void add_result(OcrReader *rd, const char *s, int l, int r, int ctxi) {
269 if (rd->nresults >= rd->aresults) {
270 rd->aresults++; rd->aresults<<=1;
271 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
273 rd->results[rd->nresults].s= s;
274 rd->results[rd->nresults].l= l;
275 rd->results[rd->nresults].r= r;
276 rd->results[rd->nresults].ctxi= ctxi;
281 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
282 DatabaseNode *start, int *matchx_r) {
283 DatabaseNode *current= start;
284 DatabaseNode *bestmatch= 0;
291 if (x > fca->w) break;
292 Pixcol cv= fca->cols[x];
293 debugf(" cv=%"PSPIXCOL(PRIx),cv);
294 for (i=0; i<current->nlinks; i++)
295 if (current->links[i].col == cv)
302 current= current->links[i].then;
303 if (current->match) {
304 debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
316 static DatabaseNode *findchar(const FindCharArgs *fca,
317 int *match_rx, int *match_rctxi) {
318 FindCharResults results[NCONTEXTS];
319 int ctxi, match=-1, nmatches=0;
321 debugf("OCR lx=%d ct_state=%x ", fca->x, fca->ctxmap);
322 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
323 results[ctxi].match= 0;
324 if (!(fca->ctxmap & (1u << ctxi))) continue;
325 debugf(" || %s",context_names[ctxi]);
327 results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
329 if (!results[ctxi].match) continue;
337 debugf(" ambiguous");
338 match= !fca->ct->findchar_select ? -1 :
339 fca->ct->findchar_select(fca,results);
340 debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
345 *match_rx= results[match].rx;
346 if (match_rctxi) *match_rctxi= match;
347 return results[match].match;
350 static int findchar_select_text(const FindCharArgs *fca,
351 const FindCharResults results[]) {
352 if (fca->ctxmap != 017) return -1;
354 dbassert(! results[ct_Digit].match );
355 if (results[ct_Word].match) return ct_Word;
356 if (results[ct_Lower].rx > results[ct_Upper].rx) return ct_Lower;
357 if (results[ct_Upper].rx > results[ct_Lower].rx) return ct_Upper;
361 const struct OcrCellTypeInfo ocr_celltype_number= {
367 const struct OcrCellTypeInfo ocr_celltype_text= {
368 .initial= 012, /* Digit|Upper */
369 .nextword= 017, /* Digit|Upper|Lower|Word */
370 .midword= 011, /* Digit|Lower */
373 .findchar_select= findchar_select_text
377 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
379 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
393 fca.ctxmap= ct->initial;
395 debugf("OCR h=%d w=%d",rd->h,w);
396 for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
410 if (nspaces == ct->space_spaces) {
411 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
412 fca.ctxmap= ct->nextword;
417 /* something here, so we need to add the spaces */
418 if (nspaces >= ct->space_spaces)
419 add_result(rd," ",x-nspaces,x+1,-1);
426 DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
430 add_result(rd, match->str, x, match_rx, match_ctxi);
432 if (match->match) fca.ctxmap= ct->midword;
433 else debugf(" (empty)");
434 if (match->endsword) {
435 nspaces= ct->space_spaces;
437 fca.ctxmap= ct->nextword;
442 debugf(" || UNKNOWN");
443 for (rx=x; rx<w && cols[rx]; rx++);
444 debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
446 callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
451 add_result(rd, 0,-1,-1,-1);
452 debugf("OCR finished %d glyphs\n",rd->nresults);
457 OcrReader *ocr_init(int h) {
460 if (o_flags & ff_dict_fetch) {
461 char *fetchfile= masprintf("char%d",h);
462 progress("Updating %s...",fetchfile);
463 fetch_with_rsync(fetchfile);
467 rd= mmalloc(sizeof(*rd));
468 memset(rd,0,sizeof(*rd));