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)
84 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
86 static void cleardb_node(DatabaseNode *n) {
89 for (i=0; i<n->nlinks; i++)
90 cleardb_node(n->links[i].then);
93 static void readdb(OcrReader *rd) {
95 DatabaseNode *current, *additional;
96 char chrs[MAXGLYPHCHRS+1];
102 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
103 cleardb_node(&rd->contexts[ctxi]);
106 asprintf(&dbfname,"%s/charset-%d.txt",get_vardir(),rd->h);
109 if (!dbfile_open(dbfname))
113 dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
115 dbassert( dbfile_scanf("%d", &h) == 1);
120 if (!lbuf[0] || lbuf[0]=='#') continue;
121 if (!strcmp(lbuf,".")) break;
123 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
124 if (!strcmp(lbuf,context_names[ctxi]))
126 /* not found, just skip */
127 for (;;) { FGETSLINE; if (!lbuf[0]) break; }
132 int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
133 if (c=='\n') { dbassert(nchrs); break; }
134 dbassert(nchrs<MAXGLYPHCHRS);
137 c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c=='x');
138 dbassert( dbfile_scanf("%2x", &cr) == 1);
139 assert(cr>0 && cr<=255);
145 if (nchrs>1 && 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->nlinks= additional->alinks= 0;
168 additional->links= 0;
169 if (current->nlinks==current->alinks) {
172 current->links= mrealloc(current->links,
173 sizeof(*current->links) * current->alinks);
175 current->links[current->nlinks].col= cv;
176 current->links[current->nlinks].then= additional;
183 dbassert(!current->s[0]);
184 strcpy(current->s, chrs);
185 current->endsword= endsword;
192 static void cu_pr_ctxmap(unsigned ctxmap) {
193 fprintf(resolver,"{");
196 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
197 if (!(ctxmap & (1u << ctxi))) continue;
198 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
201 fprintf(resolver,"}");
204 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
205 int unk_l, int unk_r, unsigned unk_ctxmap) {
206 int jobpipe[2],donepipe[2], c,i, x,y;
207 const OcrResultGlyph *s;
213 fatal("OCR failed - unrecognised characters or ligatures.\n"
214 "Character set database needs to be updated or augmented.\n"
215 "See README.charset.\n");
218 sysassert(! pipe(jobpipe) );
219 sysassert(! pipe(donepipe) );
220 resolver_pid= fork();
221 sysassert(resolver_pid!=-1);
223 sysassert( dup2(jobpipe[0],0) ==0 );
224 sysassert(! close(jobpipe[1]) );
225 sysassert(! close(donepipe[0]) );
226 /* we know donepipe[1] is >= 4 and we have dealt with all the others
227 * so we aren't in any danger of overwriting some other fd 4: */
228 sysassert( dup2(donepipe[1],4) ==4 );
229 execlp(o_resolver, o_resolver,
230 DEBUGP(callout) ? "--debug" : "--noop-arg",
233 sysassert(!"execlp ocr-resolver failed");
235 sysassert(! close(jobpipe[0]) );
236 sysassert(! close(donepipe[1]) );
237 resolver= fdopen(jobpipe[1],"w"); sysassert(resolver);
238 resolver_done= donepipe[0];
240 fprintf(resolver,"%d %d ",unk_l,unk_r);
241 cu_pr_ctxmap(unk_ctxmap);
242 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
243 if (!strcmp(s->s," ")) continue;
244 fprintf(resolver," %d %d ",s->l,s->r);
245 cu_pr_ctxmap(s->ctxmap);
246 fprintf(resolver," ");
247 for (p=s->s; (c= *p); p++) {
248 if (c=='\\') fprintf(resolver,"\\%c",c);
249 else if (c>=33 && c<=126) fputc(c,resolver);
250 else fprintf(resolver,"\\x%02x",(unsigned char)c);
253 fputc('\n',resolver);
257 "static char *t[] = {\n"
258 "/* columns rows colors chars-per-pixel */\n"
263 for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
266 fputc(cols[x] & pv ? 'o' : ' ', resolver);
267 fputs("\",\n",resolver);
269 fputs("};\n",resolver);
270 sysassert(!ferror(resolver));
271 sysassert(!fflush(resolver));
277 r= read(resolver_done,&cb,1);
278 if (r==-1) { sysassert(errno==EINTR); continue; }
283 waitpid_check_exitstatus(resolver_pid, "character resolver");
285 close(resolver_done);
295 static void add_result(OcrReader *rd, const char *s, int l, int r,
297 if (rd->nresults >= rd->aresults) {
298 rd->aresults++; rd->aresults<<=1;
299 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
301 rd->results[rd->nresults].s= s;
302 rd->results[rd->nresults].l= l;
303 rd->results[rd->nresults].r= r;
304 rd->results[rd->nresults].ctxmap= ctxmap;
309 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
311 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
321 debugf("OCR h=%d w=%d",rd->h,w);
322 for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
336 if (nspaces == ct->space_spaces) {
337 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
338 ctxmap= ct->nextword;
343 /* something here, so we need to add the spaces */
344 if (nspaces >= ct->space_spaces)
345 add_result(rd," ",x-nspaces,x+1,0);
351 DatabaseNode *uniquematch= 0;
352 int uniquematch_rx=-1;
354 debugf("OCR lx=%d ctxmap=%x ",lx,ctxmap);
356 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
357 DatabaseNode *current= &rd->contexts[ctxi];;
358 DatabaseNode *bestmatch= 0;
362 if (!(ctxmap & (1u << ctxi))) continue;
363 debugf(" || %s",context_names[ctxi]);
370 debugf(" cv=%"PSPIXCOL(PRIx),cv);
371 for (i=0; i<current->nlinks; i++)
372 if (current->links[i].col == cv)
379 current= current->links[i].then;
381 debugf(" \"%s\"%s",current->s,current->endsword?"_":"");
392 if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
393 debugf( " ambiguous");
397 uniquematch= bestmatch;
398 uniquematch_rx= bestmatch_rx;
404 add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
406 if (uniquematch->s[0]) ctxmap= ct->midword;
407 else debugf(" (empty)");
408 if (uniquematch->endsword) {
409 nspaces= ct->space_spaces;
411 ctxmap= ct->nextword;
416 debugf(" || UNKNOWN");
417 for (rx=lx; rx<w && cols[rx]; rx++);
418 debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
420 callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
424 add_result(rd, 0,-1,-1,0);
425 debugf("OCR finished %d glyphs\n",rd->nresults);
430 OcrReader *ocr_init(int h) {
433 rd= mmalloc(sizeof(*rd));
434 memset(rd,0,sizeof(*rd));