chiark / gitweb /
WIP island determination; pixmap handling in progress
[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 #define FGETSLINE (fgetsline(db,lbuf,sizeof(lbuf)))
90
91 static void cleardb_node(DatabaseNode *n) {
92   int i;
93   n->s[0]= 0;
94   for (i=0; i<n->nlinks; i++)
95     cleardb_node(n->links[i].then);
96 }
97
98 static void readdb(OcrReader *rd) {
99   int nchrs;
100   DatabaseNode *current, *additional;
101   char chrs[MAXGLYPHCHRS+1];
102   Pixcol cv;
103   int r,j,ctxi;
104   int h, endsword;
105   char lbuf[100];
106   FILE *db;
107
108   for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
109     cleardb_node(&rd->contexts[ctxi]);
110
111   char *dbfname=0;
112   asprintf(&dbfname,"%s/charset-%d.txt",get_vardir(),rd->h);
113   sysassert(dbfname);
114   
115   db= fopen(dbfname,"r");
116   free(dbfname);
117   if (!db) {
118     sysassert(errno==ENOENT);
119     return;
120   }
121
122   FGETSLINE;
123   dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
124
125   r= fscanf(db, "%d", &h);
126   dbassert(r==1);
127   dbassert(h==rd->h);
128
129   for (;;) {
130     FGETSLINE;
131     if (!lbuf || lbuf[0]=='#') continue;
132     if (!strcmp(lbuf,".")) break;
133
134     for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
135       if (!strcmp(lbuf,context_names[ctxi]))
136         goto found_ctx;
137     /* not found, just skip */
138     for (;;) { FGETSLINE; if (!lbuf[0]) break; }
139     continue;
140
141   found_ctx:
142     for (nchrs=0;;) {
143       int c= fgetc(db); sysassert(!ferror(db)); dbassert(c!=EOF);
144       if (c=='\n') { dbassert(nchrs); break; }
145       dbassert(nchrs<MAXGLYPHCHRS);
146       if (c=='\\') {
147         unsigned cr;
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);
151         c= cr;
152       }
153       chrs[nchrs++]= c;
154     }
155     endsword= 0;
156     if (nchrs>1 && chrs[nchrs-1]==' ') {
157       endsword= 1;
158       nchrs--;
159     }
160     chrs[nchrs]= 0;
161
162     current= &rd->contexts[ctxi];
163     for (;;) {
164       FGETSLINE;
165       if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
166       char *ep;
167       cv= strtoul(lbuf,&ep,16);  dbassert(!*ep);
168       dbassert(!(cv & ~((1UL << rd->h)-1)));
169       
170       for (j=0; j<current->nlinks; j++)
171         if (current->links[j].col == cv) {
172           current= current->links[j].then;
173           goto found_link;
174         }
175
176       additional= mmalloc(sizeof(*additional));
177       additional->s[0]= 0;
178       additional->nlinks= additional->alinks= 0;
179       additional->links= 0;
180       if (current->nlinks==current->alinks) {
181         current->alinks++;
182         current->alinks<<=1;
183         current->links= mrealloc(current->links,
184                                  sizeof(*current->links) * current->alinks);
185       }
186       current->links[current->nlinks].col= cv;
187       current->links[current->nlinks].then= additional;
188       current->nlinks++;
189       current= additional;
190
191     found_link:;
192     }
193
194     dbassert(!current->s[0]);
195     strcpy(current->s, chrs);
196     current->endsword= endsword;
197   }
198   sysassert(!ferror(db));
199   sysassert(!fclose(db));
200 }
201
202 static void cu_pr_ctxmap(unsigned ctxmap) {
203   fprintf(resolver,"{");
204   const char *spc="";
205   int ctxi;
206   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
207     if (!(ctxmap & (1u << ctxi))) continue;
208     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
209     spc=" ";
210   }
211   fprintf(resolver,"}");
212 }
213
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;
218   const char *p;
219   char cb;
220   Pixcol pv;
221
222   if (!o_resolver)
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");
226   
227   if (!resolver) {
228     sysassert(! pipe(jobpipe) );
229     sysassert(! pipe(donepipe) );
230     resolver_pid= fork();
231     sysassert(resolver_pid!=-1);
232     if (!resolver_pid) {
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",
241              "--automatic-1",
242              (char*)0);
243       sysassert(!"execlp ocr-resolver failed");
244     }
245     sysassert(! close(jobpipe[0]) );
246     sysassert(! close(donepipe[1]) );
247     resolver= fdopen(jobpipe[1],"w"); sysassert(resolver);
248     resolver_done= donepipe[0];
249   }
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);
261     }
262   }
263   fputc('\n',resolver);
264
265   fprintf(resolver,
266           "/* XPM */\n"
267           "static char *t[] = {\n"
268           "/* columns rows colors chars-per-pixel */\n"
269           "\"%d %d 2 1\",\n"
270           "\"  c black\",\n"
271           "\"o c white\",\n",
272           w,rd->h);
273   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
274     fputc('"',resolver);
275     for (x=0; x<w; x++)
276       fputc(cols[x] & pv ? 'o' : ' ', resolver);
277     fputs("\",\n",resolver);
278   }
279   fputs("};\n",resolver);
280   sysassert(!ferror(resolver));
281   sysassert(!fflush(resolver));
282
283   sysassert(resolver);
284
285   int r;
286   for (;;) {
287     r= read(resolver_done,&cb,1);
288     if (r==-1) { sysassert(errno==EINTR); continue; }
289     break;
290   }
291
292   if (r==0) {
293     waitpid_check_exitstatus(resolver_pid, "character resolver");
294     fclose(resolver);
295     close(resolver_done);
296     resolver= 0;
297   } else {
298     assert(r==1);
299     sysassert(cb==0);
300   }
301
302   readdb(rd);
303 }
304
305 static void add_result(OcrReader *rd, const char *s, int l, int r,
306                        unsigned ctxmap) {
307   if (rd->nresults >= rd->aresults) {
308     rd->aresults++; rd->aresults<<=1;
309     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
310   }
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;
315   rd->nresults++;
316 }
317
318
319 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
320
321 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
322   int nspaces;
323   unsigned ctxmap;
324   int ctxi, i, x;
325
326  restart:
327
328   nspaces=- w;
329   ctxmap= ct->initial;
330   rd->nresults=0;
331   debugf("OCR h=%d w=%d",rd->h,w);
332   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
333   debugf("\n");
334   debug_flush();
335
336   x=0;
337   for (;;) {
338     debug_flush();
339     /* skip spaces */
340     if (x>=w)
341       break;
342
343     if (!cols[x]) {
344       nspaces++;
345       x++;
346       if (nspaces == ct->space_spaces) {
347         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
348         ctxmap= ct->nextword;
349       }
350       continue;
351     }
352
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);
356     nspaces=0;
357
358     /* find character */
359     int lx=x;
360
361     DatabaseNode *uniquematch= 0;
362     int uniquematch_rx=-1;
363     
364     debugf("OCR  lx=%d ctxmap=%x  ",lx,ctxmap);
365
366     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
367       DatabaseNode *current= &rd->contexts[ctxi];;
368       DatabaseNode *bestmatch= 0;
369       int bestmatch_rx=-1;
370
371       x= lx;
372       if (!(ctxmap & (1u << ctxi))) continue;
373       debugf(" || %s",context_names[ctxi]);
374
375       for (;;) {
376         debug_flush();
377         debugf(" | x=%d",x);
378         if (x>w) break;
379         Pixcol cv= cols[x];
380         debugf(" cv=%"PSPIXCOL(PRIx),cv);
381         for (i=0; i<current->nlinks; i++)
382           if (current->links[i].col == cv)
383             goto found;
384         /* not found */
385         debugf(" ?");
386         break;
387
388       found:
389         current= current->links[i].then;
390         if (current->s[0]) {
391           debugf(" \"%s\"%s",current->s,current->endsword?"_":"");
392           bestmatch= current;
393           bestmatch_rx= x;
394         } else {
395           debugf(" ...");
396         }
397
398         x++;
399       }
400       
401       if (bestmatch) {
402         if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
403           debugf( " ambiguous");
404           uniquematch= 0;
405           break;
406         }
407         uniquematch= bestmatch;
408         uniquematch_rx= bestmatch_rx;
409       }
410     }
411
412     if (uniquematch) {
413       debugf(" || YES");
414       add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
415       x= uniquematch_rx+1;
416       if (uniquematch->s[0]) ctxmap= ct->midword;
417       else debugf(" (empty)");
418       if (uniquematch->endsword) {
419         nspaces= ct->space_spaces;
420         debugf("_");
421         ctxmap= ct->nextword;
422       }
423       debugf("\n");
424     } else {
425       int rx;
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);
429       debug_flush();
430       callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
431       goto restart;
432     }
433   }
434   add_result(rd, 0,-1,-1,0);
435   debugf("OCR  finished %d glyphs\n",rd->nresults);
436   debug_flush();
437   return rd->results;
438 }
439
440 OcrReader *ocr_init(int h) {
441   OcrReader *rd;
442
443   rd= mmalloc(sizeof(*rd));
444   memset(rd,0,sizeof(*rd));
445   rd->h= h;
446   readdb(rd);
447   return rd;
448 }