chiark / gitweb /
Merge branch 'master' of chiark:/home/ijackson/things/ypp-sc-tools
[ypp-sc-tools.web-live.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 (!o_resolver)
233     fatal("OCR failed - unrecognised characters or ligatures.\n"
234           "Character set database needs to be updated or augmented.\n"
235           "See README.charset.\n");
236   
237   if (!resolver) {
238     sysassert(! pipe(jobpipe) );
239     sysassert(! pipe(donepipe) );
240     resolver_pid= fork();
241     sysassert(resolver_pid!=-1);
242     if (!resolver_pid) {
243       sysassert( dup2(jobpipe[0],0) ==0 );
244       sysassert(! close(jobpipe[1]) );
245       sysassert(! close(donepipe[0]) );
246       /* we know donepipe[1] is >= 4 and we have dealt with all the others
247        * so we aren't in any danger of overwriting some other fd 4: */
248       sysassert( dup2(donepipe[1],4) ==4 );
249       execlp(o_resolver, o_resolver,
250              DEBUGP(callout) ? "--debug" : "--noop-arg",
251              "--automatic-1",
252              (char*)0);
253       sysassert(!"execlp ocr-resolver failed");
254     }
255     sysassert(! close(jobpipe[0]) );
256     sysassert(! close(donepipe[1]) );
257     resolver= fdopen(jobpipe[1],"w"); sysassert(resolver);
258     resolver_done= donepipe[0];
259   }
260   fprintf(resolver,"%d %d ",unk_l,unk_r);
261   cu_pr_ctxmap(unk_ctxmap);
262   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
263     if (!strcmp(s->s," ")) continue;
264     fprintf(resolver," %d %d ",s->l,s->r);
265     cu_pr_ctxmap(s->ctxmap);
266     fprintf(resolver," ");
267     for (p=s->s; (c= *p); p++) {
268       if (c=='\\') fprintf(resolver,"\\%c",c);
269       else if (c>=33 && c<=126) fputc(c,resolver);
270       else fprintf(resolver,"\\x%02x",(unsigned char)c);
271     }
272   }
273   fputc('\n',resolver);
274
275   fprintf(resolver,
276           "/* XPM */\n"
277           "static char *t[] = {\n"
278           "/* columns rows colors chars-per-pixel */\n"
279           "\"%d %d 2 1\",\n"
280           "\"  c black\",\n"
281           "\"o c white\",\n",
282           w,rd->h);
283   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
284     fputc('"',resolver);
285     for (x=0; x<w; x++)
286       fputc(cols[x] & pv ? 'o' : ' ', resolver);
287     fputs("\",\n",resolver);
288   }
289   fputs("};\n",resolver);
290   sysassert(!ferror(resolver));
291   sysassert(!fflush(resolver));
292
293   sysassert(resolver);
294
295   int r;
296   for (;;) {
297     r= read(resolver_done,&cb,1);
298     if (r==-1) { sysassert(errno==EINTR); continue; }
299     break;
300   }
301
302   if (r==0) {
303     waitpid_check_exitstatus(resolver_pid, "character resolver");
304     fclose(resolver);
305     close(resolver_done);
306     resolver= 0;
307   } else {
308     assert(r==1);
309     sysassert(cb==0);
310   }
311
312   readdb(rd);
313 }
314
315 static void add_result(OcrReader *rd, const char *s, int l, int r,
316                        unsigned ctxmap) {
317   if (rd->nresults >= rd->aresults) {
318     rd->aresults++; rd->aresults<<=1;
319     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
320   }
321   rd->results[rd->nresults].s= s;
322   rd->results[rd->nresults].l= l;
323   rd->results[rd->nresults].r= r;
324   rd->results[rd->nresults].ctxmap= ctxmap;
325   rd->nresults++;
326 }
327
328
329 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
330
331 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
332   int nspaces;
333   unsigned ctxmap;
334   int ctxi, i, x;
335
336  restart:
337
338   nspaces=- w;
339   ctxmap= ct->initial;
340   rd->nresults=0;
341   debugf("OCR h=%d w=%d",rd->h,w);
342   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
343   debugf("\n");
344   debug_flush();
345
346   x=0;
347   for (;;) {
348     debug_flush();
349     /* skip spaces */
350     if (x>=w)
351       break;
352
353     if (!cols[x]) {
354       nspaces++;
355       x++;
356       if (nspaces == ct->space_spaces) {
357         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
358         ctxmap= ct->nextword;
359       }
360       continue;
361     }
362
363     /* something here, so we need to add the spaces */
364     if (nspaces >= ct->space_spaces)
365       add_result(rd," ",x-nspaces,x+1,0);
366     nspaces=0;
367
368     /* find character */
369     int lx=x;
370
371     DatabaseNode *uniquematch= 0;
372     int uniquematch_rx=-1;
373     
374     debugf("OCR  lx=%d ctxmap=%x  ",lx,ctxmap);
375
376     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
377       DatabaseNode *current= &rd->contexts[ctxi];;
378       DatabaseNode *bestmatch= 0;
379       int bestmatch_rx=-1;
380
381       x= lx;
382       if (!(ctxmap & (1u << ctxi))) continue;
383       debugf(" || %s",context_names[ctxi]);
384
385       for (;;) {
386         debug_flush();
387         debugf(" | x=%d",x);
388         if (x>w) break;
389         Pixcol cv= cols[x];
390         debugf(" cv=%"PSPIXCOL(PRIx),cv);
391         for (i=0; i<current->nlinks; i++)
392           if (current->links[i].col == cv)
393             goto found;
394         /* not found */
395         debugf(" ?");
396         break;
397
398       found:
399         current= current->links[i].then;
400         if (current->s[0]) {
401           debugf(" \"%s\"%s",current->s,current->endsword?"_":"");
402           bestmatch= current;
403           bestmatch_rx= x;
404         } else {
405           debugf(" ...");
406         }
407
408         x++;
409       }
410       
411       if (bestmatch) {
412         if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
413           debugf( " ambiguous");
414           uniquematch= 0;
415           break;
416         }
417         uniquematch= bestmatch;
418         uniquematch_rx= bestmatch_rx;
419       }
420     }
421
422     if (uniquematch) {
423       debugf(" || YES");
424       add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
425       x= uniquematch_rx+1;
426       if (uniquematch->s[0]) ctxmap= ct->midword;
427       else debugf(" (empty)");
428       if (uniquematch->endsword) {
429         nspaces= ct->space_spaces;
430         debugf("_");
431         ctxmap= ct->nextword;
432       }
433       debugf("\n");
434     } else {
435       int rx;
436       debugf(" || UNKNOWN");
437       for (rx=lx; rx<w && cols[rx]; rx++);
438       debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
439       debug_flush();
440       callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
441       goto restart;
442     }
443   }
444   add_result(rd, 0,-1,-1,0);
445   debugf("OCR  finished %d glyphs\n",rd->nresults);
446   debug_flush();
447   return rd->results;
448 }
449
450 OcrReader *ocr_init(int h) {
451   OcrReader *rd;
452
453   rd= mmalloc(sizeof(*rd));
454   memset(rd,0,sizeof(*rd));
455   rd->h= h;
456   readdb(rd);
457   return rd;
458 }