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