chiark / gitweb /
d12218f39fd2953eef1f892c9bb7fbd360e3b64c
[ypp-sc-tools.db-test.git] / pctb / ocr.c
1 /*
2  * Core OCR algorithm (first exact bitmap match)
3  */
4 /*
5  *  This is part of ypp-sc-tools, a set of third-party tools for assisting
6  *  players of Yohoho Puzzle Pirates.
7  * 
8  *  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9  * 
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.
14  * 
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.
19  * 
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/>.
22  * 
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.
26  */
27
28 #include "ocr.h"
29
30 typedef struct {
31   Pixcol col;
32   struct DatabaseNode *then;
33 } DatabaseLink;
34
35 #define MAXGLYPHCHRS 7
36
37 typedef struct DatabaseNode {
38   char s[MAXGLYPHCHRS+1]; /* null-terminated; "" means no match here */
39   int nlinks, alinks;
40   unsigned endsword:1;
41   DatabaseLink *links;
42 } DatabaseNode;
43
44 static const char *context_names[]= {
45   "Lower",
46   "Upper",
47   "Digit"
48 };
49 struct OcrCellTypeInfo {
50   /* bitmaps of indices into context_names: */
51   unsigned initial, nextword, midword;
52   int space_spaces;
53   const char *name;
54 };
55 const struct OcrCellTypeInfo ocr_celltype_number= {
56   4,4,4,
57   .space_spaces= 5,
58   .name= "number"
59 };
60 const struct OcrCellTypeInfo ocr_celltype_text= {
61   .initial=2, /* Uppercase */
62   .nextword=3, /* Either */
63   .midword=1, /* Lower only */
64   .space_spaces= 4,
65   .name= "text"
66 };
67
68
69 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
70
71 struct OcrReader {
72   int h;
73   DatabaseNode contexts[NCONTEXTS];
74   OcrResultGlyph *results;
75   int aresults, nresults;
76 };
77
78 static FILE *resolver;
79 static pid_t resolver_pid;
80 static int resolver_done;
81
82 DEBUG_DEFINE_DEBUGF(ocr)
83
84 #define dbassert(x)                                                     \
85   ((x) ? (void)0 :                                                      \
86      fatal("Error in character set database.\n"                         \
87            " Requirement not met: %s:%d: %s", __FILE__,__LINE__, #x))
88
89 static void fgetsline(FILE *f, char *lbuf, size_t lbufsz) {
90   errno=0;
91   char *s= fgets(lbuf,lbufsz,f);
92   sysassert(!ferror(f));
93   dbassert(!feof(f));
94   assert(s);
95   int l= strlen(lbuf);
96   dbassert(l>0);  dbassert(lbuf[--l]='\n');
97   lbuf[l]= 0;
98 }
99 #define FGETSLINE(f,buf) (fgetsline(f,buf,sizeof(buf)))
100
101 static void cleardb_node(DatabaseNode *n) {
102   int i;
103   n->s[0]= 0;
104   for (i=0; i<n->nlinks; i++)
105     cleardb_node(n->links[i].then);
106 }
107
108 static void readdb(OcrReader *rd) {
109   int nchrs;
110   DatabaseNode *current, *additional;
111   char chrs[MAXGLYPHCHRS+1];
112   Pixcol cv;
113   int r,j,ctxi;
114   int h, endsword;
115   char lbuf[100];
116   FILE *db;
117
118   for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
119     cleardb_node(&rd->contexts[ctxi]);
120
121   char *dbfname=0;
122   asprintf(&dbfname,"%s/charset-%d.txt",get_vardir(),rd->h);
123   sysassert(dbfname);
124   
125   db= fopen(dbfname,"r");
126   free(dbfname);
127   if (!db) {
128     sysassert(errno==ENOENT);
129     return;
130   }
131
132   FGETSLINE(db,lbuf);
133   dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
134
135   r= fscanf(db, "%d", &h);
136   dbassert(r==1);
137   dbassert(h==rd->h);
138
139   for (;;) {
140     FGETSLINE(db,lbuf);
141     if (!lbuf || lbuf[0]=='#') continue;
142     if (!strcmp(lbuf,".")) break;
143
144     for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
145       if (!strcmp(lbuf,context_names[ctxi]))
146         goto found_ctx;
147     /* not found, just skip */
148     for (;;) { FGETSLINE(db,lbuf); if (!lbuf[0]) break; }
149     continue;
150
151   found_ctx:
152     for (nchrs=0;;) {
153       int c= fgetc(db); sysassert(!ferror(db)); dbassert(c!=EOF);
154       if (c=='\n') { dbassert(nchrs); break; }
155       dbassert(nchrs<MAXGLYPHCHRS);
156       if (c=='\\') {
157         unsigned cr;
158         c= fgetc(db); sysassert(!ferror(db)); dbassert(c=='x');
159         r= fscanf(db, "%2x", &cr); sysassert(!ferror(db)); dbassert(r==1);
160         assert(cr>0 && cr<=255);
161         c= cr;
162       }
163       chrs[nchrs++]= c;
164     }
165     endsword= 0;
166     if (nchrs>1 && chrs[nchrs-1]==' ') {
167       endsword= 1;
168       nchrs--;
169     }
170     chrs[nchrs]= 0;
171
172     current= &rd->contexts[ctxi];
173     for (;;) {
174       FGETSLINE(db,lbuf);
175       if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
176       char *ep;
177       cv= strtoul(lbuf,&ep,16);  dbassert(!*ep);
178       dbassert(!(cv & ~((1UL << rd->h)-1)));
179       
180       for (j=0; j<current->nlinks; j++)
181         if (current->links[j].col == cv) {
182           current= current->links[j].then;
183           goto found_link;
184         }
185
186       additional= mmalloc(sizeof(*additional));
187       additional->s[0]= 0;
188       additional->nlinks= additional->alinks= 0;
189       additional->links= 0;
190       if (current->nlinks==current->alinks) {
191         current->alinks++;
192         current->alinks<<=1;
193         current->links= mrealloc(current->links,
194                                  sizeof(*current->links) * current->alinks);
195       }
196       current->links[current->nlinks].col= cv;
197       current->links[current->nlinks].then= additional;
198       current->nlinks++;
199       current= additional;
200
201     found_link:;
202     }
203
204     dbassert(!current->s[0]);
205     strcpy(current->s, chrs);
206     current->endsword= endsword;
207   }
208   sysassert(!ferror(db));
209   sysassert(!fclose(db));
210 }
211
212 static void cu_pr_ctxmap(unsigned ctxmap) {
213   fprintf(resolver,"{");
214   const char *spc="";
215   int ctxi;
216   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
217     if (!(ctxmap & (1u << ctxi))) continue;
218     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
219     spc=" ";
220   }
221   fprintf(resolver,"}");
222 }
223
224 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
225                             int unk_l, int unk_r, unsigned unk_ctxmap) {
226   int jobpipe[2],donepipe[2], c,i, x,y;
227   const OcrResultGlyph *s;
228   const char *p;
229   char cb;
230   Pixcol pv;
231   
232   if (!resolver) {
233     sysassert(! pipe(jobpipe) );
234     sysassert(! pipe(donepipe) );
235     resolver_pid= fork();
236     sysassert(resolver_pid!=-1);
237     if (!resolver_pid) {
238       sysassert( dup2(jobpipe[0],0) ==0 );
239       sysassert(! close(jobpipe[1]) );
240       sysassert(! close(donepipe[0]) );
241       /* we know donepipe[1] is >= 4 and we have dealt with all the others
242        * so we aren't in any danger of overwriting some other fd 4: */
243       sysassert( dup2(donepipe[1],4) ==4 );
244       execlp("./yppsc-ocr-resolver", "yppsc-ocr-resolver",
245              DEBUGP(callout) ? "--debug" : "--noop-arg",
246              "--automatic-1",
247              (char*)0);
248       sysassert(!"execlp failed");
249     }
250     sysassert(! close(jobpipe[0]) );
251     sysassert(! close(donepipe[1]) );
252     resolver= fdopen(jobpipe[1],"w"); sysassert(resolver);
253     resolver_done= donepipe[0];
254   }
255   fprintf(resolver,"%d %d ",unk_l,unk_r);
256   cu_pr_ctxmap(unk_ctxmap);
257   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
258     if (!strcmp(s->s," ")) continue;
259     fprintf(resolver," %d %d ",s->l,s->r);
260     cu_pr_ctxmap(s->ctxmap);
261     fprintf(resolver," ");
262     for (p=s->s; (c= *p); p++) {
263       if (c=='\\') fprintf(resolver,"\\%c",c);
264       else if (c>=33 && c<=126) fputc(c,resolver);
265       else fprintf(resolver,"\\x%02x",(unsigned char)c);
266     }
267   }
268   fputc('\n',resolver);
269
270   fprintf(resolver,
271           "/* XPM */\n"
272           "static char *t[] = {\n"
273           "/* columns rows colors chars-per-pixel */\n"
274           "\"%d %d 2 1\",\n"
275           "\"  c black\",\n"
276           "\"o c white\",\n",
277           w,rd->h);
278   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
279     fputc('"',resolver);
280     for (x=0; x<w; x++)
281       fputc(cols[x] & pv ? 'o' : ' ', resolver);
282     fputs("\",\n",resolver);
283   }
284   fputs("};\n",resolver);
285   sysassert(!ferror(resolver));
286   sysassert(!fflush(resolver));
287
288   sysassert(resolver);
289
290   int r;
291   for (;;) {
292     r= read(resolver_done,&cb,1);
293     if (r==-1) { sysassert(errno==EINTR); continue; }
294     break;
295   }
296
297   if (r==0) {
298     pid_t pid;
299     int st;
300     for (;;) {
301       pid= waitpid(resolver_pid, &st, 0);
302       if (pid==-1) { sysassert(errno==EINTR); continue; }
303       break;
304     }
305     sysassert(pid==resolver_pid);
306     if (WIFEXITED(st)) {
307       if (WEXITSTATUS(st))
308         fatal("character resolver failed with nonzero exit status %d",
309               WEXITSTATUS(st));
310       fclose(resolver);
311       close(resolver_done);
312       resolver= 0;
313     } else if (WIFSIGNALED(st)) {
314       fatal("character resolver died due to signal %s%s",
315             strsignal(WTERMSIG(st)), WCOREDUMP(st)?" (core dumped)":"");
316     } else {
317       fatal("character resolver gave strange wait status %d",st);
318     }
319   } else {
320     assert(r==1);
321     sysassert(cb==0);
322   }
323
324   readdb(rd);
325 }
326
327 static void add_result(OcrReader *rd, const char *s, int l, int r,
328                        unsigned ctxmap) {
329   if (rd->nresults >= rd->aresults) {
330     rd->aresults++; rd->aresults<<=1;
331     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
332   }
333   rd->results[rd->nresults].s= s;
334   rd->results[rd->nresults].l= l;
335   rd->results[rd->nresults].r= r;
336   rd->results[rd->nresults].ctxmap= ctxmap;
337   rd->nresults++;
338 }
339
340
341 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
342
343 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
344   int nspaces;
345   unsigned ctxmap;
346   int ctxi, i, x;
347
348  restart:
349
350   nspaces=- w;
351   ctxmap= ct->initial;
352   rd->nresults=0;
353   debugf("OCR h=%d w=%d",rd->h,w);
354   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
355   debugf("\n");
356   debug_flush();
357
358   x=0;
359   for (;;) {
360     debug_flush();
361     /* skip spaces */
362     if (x>=w)
363       break;
364
365     if (!cols[x]) {
366       nspaces++;
367       x++;
368       if (nspaces == ct->space_spaces) {
369         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
370         ctxmap= ct->nextword;
371       }
372       continue;
373     }
374
375     /* something here, so we need to add the spaces */
376     if (nspaces >= ct->space_spaces)
377       add_result(rd," ",x-nspaces,x+1,0);
378     nspaces=0;
379
380     /* find character */
381     int lx=x;
382
383     DatabaseNode *uniquematch= 0;
384     int uniquematch_rx=-1;
385     
386     debugf("OCR  lx=%d ctxmap=%x  ",lx,ctxmap);
387
388     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
389       DatabaseNode *current= &rd->contexts[ctxi];;
390       DatabaseNode *bestmatch= 0;
391       int bestmatch_rx=-1;
392
393       x= lx;
394       if (!(ctxmap & (1u << ctxi))) continue;
395       debugf(" || %s",context_names[ctxi]);
396
397       for (;;) {
398         debug_flush();
399         debugf(" | x=%d",x);
400         if (x>w) break;
401         Pixcol cv= cols[x];
402         debugf(" cv=%"PSPIXCOL(PRIx),cv);
403         for (i=0; i<current->nlinks; i++)
404           if (current->links[i].col == cv)
405             goto found;
406         /* not found */
407         debugf(" ?");
408         break;
409
410       found:
411         current= current->links[i].then;
412         if (current->s[0]) {
413           debugf(" \"%s\"%s",current->s,current->endsword?"_":"");
414           bestmatch= current;
415           bestmatch_rx= x;
416         } else {
417           debugf(" ...");
418         }
419
420         x++;
421       }
422       
423       if (bestmatch) {
424         if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
425           debugf( " ambiguous");
426           uniquematch= 0;
427           break;
428         }
429         uniquematch= bestmatch;
430         uniquematch_rx= bestmatch_rx;
431       }
432     }
433
434     if (uniquematch) {
435       debugf(" || YES");
436       add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
437       x= uniquematch_rx+1;
438       if (uniquematch->s[0]) ctxmap= ct->midword;
439       else debugf(" (empty)");
440       if (uniquematch->endsword) {
441         nspaces= ct->space_spaces;
442         debugf("_");
443         ctxmap= ct->nextword;
444       }
445       debugf("\n");
446     } else {
447       int rx;
448       debugf(" || UNKNOWN");
449       for (rx=lx; rx<w && cols[rx]; rx++);
450       debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
451       debug_flush();
452       callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
453       goto restart;
454     }
455   }
456   add_result(rd, 0,-1,-1,0);
457   debugf("OCR  finished %d glyphs\n",rd->nresults);
458   debug_flush();
459   return rd->results;
460 }
461
462 OcrReader *ocr_init(int h) {
463   OcrReader *rd;
464
465   rd= mmalloc(sizeof(*rd));
466   memset(rd,0,sizeof(*rd));
467   rd->h= h;
468   readdb(rd);
469   return rd;
470 }