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 #define MAXGLYPHCHRS 7
37 typedef struct DatabaseNode {
38 char s[MAXGLYPHCHRS+1]; /* null-terminated; "" means no match here */
44 static const char *context_names[]= {
49 struct OcrCellTypeInfo {
50 /* bitmaps of indices into context_names: */
51 unsigned initial, nextword, midword;
55 const struct OcrCellTypeInfo ocr_celltype_number= {
60 const struct OcrCellTypeInfo ocr_celltype_text= {
61 .initial=2, /* Uppercase */
62 .nextword=3, /* Either */
63 .midword=1, /* Lower only */
69 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
73 DatabaseNode contexts[NCONTEXTS];
74 OcrResultGlyph *results;
75 int aresults, nresults;
78 static FILE *resolver;
79 static pid_t resolver_pid;
80 static int resolver_done;
82 DEBUG_DEFINE_DEBUGF(ocr)
86 fatal("Error in character set database.\n" \
87 " Requirement not met: %s:%d: %s", __FILE__,__LINE__, #x))
89 #define FGETSLINE (fgetsline(db,lbuf,sizeof(lbuf)))
91 static void cleardb_node(DatabaseNode *n) {
94 for (i=0; i<n->nlinks; i++)
95 cleardb_node(n->links[i].then);
98 static void readdb(OcrReader *rd) {
100 DatabaseNode *current, *additional;
101 char chrs[MAXGLYPHCHRS+1];
108 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
109 cleardb_node(&rd->contexts[ctxi]);
112 asprintf(&dbfname,"%s/charset-%d.txt",get_vardir(),rd->h);
115 db= fopen(dbfname,"r");
118 sysassert(errno==ENOENT);
123 dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
125 r= fscanf(db, "%d", &h);
131 if (!lbuf || lbuf[0]=='#') continue;
132 if (!strcmp(lbuf,".")) break;
134 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
135 if (!strcmp(lbuf,context_names[ctxi]))
137 /* not found, just skip */
138 for (;;) { FGETSLINE; if (!lbuf[0]) break; }
143 int c= fgetc(db); sysassert(!ferror(db)); dbassert(c!=EOF);
144 if (c=='\n') { dbassert(nchrs); break; }
145 dbassert(nchrs<MAXGLYPHCHRS);
148 c= fgetc(db); sysassert(!ferror(db)); dbassert(c=='x');
149 r= fscanf(db, "%2x", &cr); sysassert(!ferror(db)); dbassert(r==1);
150 assert(cr>0 && cr<=255);
156 if (nchrs>1 && chrs[nchrs-1]==' ') {
162 current= &rd->contexts[ctxi];
165 if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
167 cv= strtoul(lbuf,&ep,16); dbassert(!*ep);
168 dbassert(!(cv & ~((1UL << rd->h)-1)));
170 for (j=0; j<current->nlinks; j++)
171 if (current->links[j].col == cv) {
172 current= current->links[j].then;
176 additional= mmalloc(sizeof(*additional));
178 additional->nlinks= additional->alinks= 0;
179 additional->links= 0;
180 if (current->nlinks==current->alinks) {
183 current->links= mrealloc(current->links,
184 sizeof(*current->links) * current->alinks);
186 current->links[current->nlinks].col= cv;
187 current->links[current->nlinks].then= additional;
194 dbassert(!current->s[0]);
195 strcpy(current->s, chrs);
196 current->endsword= endsword;
198 sysassert(!ferror(db));
199 sysassert(!fclose(db));
202 static void cu_pr_ctxmap(unsigned ctxmap) {
203 fprintf(resolver,"{");
206 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
207 if (!(ctxmap & (1u << ctxi))) continue;
208 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
211 fprintf(resolver,"}");
214 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
215 int unk_l, int unk_r, unsigned unk_ctxmap) {
216 int jobpipe[2],donepipe[2], c,i, x,y;
217 const OcrResultGlyph *s;
223 fatal("OCR failed - unrecognised characters or ligatures.\n"
224 "Character set database needs to be updated or augmented.\n"
225 "See README.charset.\n");
228 sysassert(! pipe(jobpipe) );
229 sysassert(! pipe(donepipe) );
230 resolver_pid= fork();
231 sysassert(resolver_pid!=-1);
233 sysassert( dup2(jobpipe[0],0) ==0 );
234 sysassert(! close(jobpipe[1]) );
235 sysassert(! close(donepipe[0]) );
236 /* we know donepipe[1] is >= 4 and we have dealt with all the others
237 * so we aren't in any danger of overwriting some other fd 4: */
238 sysassert( dup2(donepipe[1],4) ==4 );
239 execlp(o_resolver, o_resolver,
240 DEBUGP(callout) ? "--debug" : "--noop-arg",
243 sysassert(!"execlp ocr-resolver failed");
245 sysassert(! close(jobpipe[0]) );
246 sysassert(! close(donepipe[1]) );
247 resolver= fdopen(jobpipe[1],"w"); sysassert(resolver);
248 resolver_done= donepipe[0];
250 fprintf(resolver,"%d %d ",unk_l,unk_r);
251 cu_pr_ctxmap(unk_ctxmap);
252 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
253 if (!strcmp(s->s," ")) continue;
254 fprintf(resolver," %d %d ",s->l,s->r);
255 cu_pr_ctxmap(s->ctxmap);
256 fprintf(resolver," ");
257 for (p=s->s; (c= *p); p++) {
258 if (c=='\\') fprintf(resolver,"\\%c",c);
259 else if (c>=33 && c<=126) fputc(c,resolver);
260 else fprintf(resolver,"\\x%02x",(unsigned char)c);
263 fputc('\n',resolver);
267 "static char *t[] = {\n"
268 "/* columns rows colors chars-per-pixel */\n"
273 for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
276 fputc(cols[x] & pv ? 'o' : ' ', resolver);
277 fputs("\",\n",resolver);
279 fputs("};\n",resolver);
280 sysassert(!ferror(resolver));
281 sysassert(!fflush(resolver));
287 r= read(resolver_done,&cb,1);
288 if (r==-1) { sysassert(errno==EINTR); continue; }
293 waitpid_check_exitstatus(resolver_pid, "character resolver");
295 close(resolver_done);
305 static void add_result(OcrReader *rd, const char *s, int l, int r,
307 if (rd->nresults >= rd->aresults) {
308 rd->aresults++; rd->aresults<<=1;
309 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
311 rd->results[rd->nresults].s= s;
312 rd->results[rd->nresults].l= l;
313 rd->results[rd->nresults].r= r;
314 rd->results[rd->nresults].ctxmap= ctxmap;
319 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
321 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
331 debugf("OCR h=%d w=%d",rd->h,w);
332 for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
346 if (nspaces == ct->space_spaces) {
347 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
348 ctxmap= ct->nextword;
353 /* something here, so we need to add the spaces */
354 if (nspaces >= ct->space_spaces)
355 add_result(rd," ",x-nspaces,x+1,0);
361 DatabaseNode *uniquematch= 0;
362 int uniquematch_rx=-1;
364 debugf("OCR lx=%d ctxmap=%x ",lx,ctxmap);
366 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
367 DatabaseNode *current= &rd->contexts[ctxi];;
368 DatabaseNode *bestmatch= 0;
372 if (!(ctxmap & (1u << ctxi))) continue;
373 debugf(" || %s",context_names[ctxi]);
380 debugf(" cv=%"PSPIXCOL(PRIx),cv);
381 for (i=0; i<current->nlinks; i++)
382 if (current->links[i].col == cv)
389 current= current->links[i].then;
391 debugf(" \"%s\"%s",current->s,current->endsword?"_":"");
402 if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
403 debugf( " ambiguous");
407 uniquematch= bestmatch;
408 uniquematch_rx= bestmatch_rx;
414 add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
416 if (uniquematch->s[0]) ctxmap= ct->midword;
417 else debugf(" (empty)");
418 if (uniquematch->endsword) {
419 nspaces= ct->space_spaces;
421 ctxmap= ct->nextword;
426 debugf(" || UNKNOWN");
427 for (rx=lx; rx<w && cols[rx]; rx++);
428 debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
430 callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
434 add_result(rd, 0,-1,-1,0);
435 debugf("OCR finished %d glyphs\n",rd->nresults);
440 OcrReader *ocr_init(int h) {
443 rd= mmalloc(sizeof(*rd));
444 memset(rd,0,sizeof(*rd));