chiark / gitweb /
1a8ac9a771e0104206ab6ff0454f3f813d6c373b
[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 #include "convert.h"
30
31 typedef struct {
32   Pixcol col;
33   struct DatabaseNode *then;
34 } DatabaseLink;
35
36 typedef struct DatabaseNode {
37   char *str;
38   int nlinks, alinks;
39   unsigned match:1, defined:1, endsword:1;
40   DatabaseLink *links;
41 } DatabaseNode;
42
43 typedef struct {
44   OcrReader *rd;
45   OcrCellType ct;
46   int w;
47   Pixcol *cols;
48   int x;
49   unsigned ctxmap;
50 } FindCharArgs;
51 typedef struct {
52   DatabaseNode *match;
53   int rx;
54 } FindCharResults;
55
56 #define FOR_EACH_CONTEXT(EACH)                  \
57   EACH(Word)                                    \
58   EACH(Upper)                                   \
59   EACH(Lower)                                   \
60   EACH(Digit)
61
62 #define FEC_ENUM(Context) ct_##Context,
63 #define FEC_BIT(Context) ctf_##Context = 1 << ct_##Context,
64 enum {
65   FOR_EACH_CONTEXT(FEC_ENUM)
66   FOR_EACH_CONTEXT(FEC_BIT)
67 };
68
69 #define FEC_STRINGS(Context) #Context,
70 static const char *context_names[]= { FOR_EACH_CONTEXT(FEC_STRINGS) };
71
72 struct OcrCellTypeInfo {
73   /* bitmaps of indices into context_names: */
74   unsigned initial, nextword, midword;
75   int space_spaces;
76   const char *name;
77   int (*findchar_select)(const FindCharArgs *fca,
78                          const FindCharResults results[]);
79 };
80
81 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
82
83 struct OcrReader {
84   int h;
85   DatabaseNode contexts[NCONTEXTS];
86   OcrResultGlyph *results;
87   int aresults, nresults;
88 };
89
90 DEBUG_DEFINE_DEBUGF(ocr)
91
92 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
93
94 static void cleardb_node(DatabaseNode *n) {
95   int i;
96   free(n->str); n->str=0;
97   n->defined=n->match=n->endsword= 0;
98   for (i=0; i<n->nlinks; i++)
99     cleardb_node(n->links[i].then);
100 }
101
102 static void readdb1(OcrReader *rd, const char *which);
103
104 static void readdb(OcrReader *rd) {
105   int ctxi;
106   
107   for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
108     cleardb_node(&rd->contexts[ctxi]);
109
110   readdb1(rd, "master");
111   readdb1(rd, "local");
112 }
113
114 static void readdb1(OcrReader *rd, const char *which) {
115   int nchrs;
116   DatabaseNode *current, *additional;
117   char chrs[100];
118   Pixcol cv;
119   int j,ctxi;
120   int h, endsword;
121   char lbuf[100];
122
123   char *dbfname= masprintf("%s/#%s-char%d#.txt",
124                            get_vardir(), which, rd->h);
125   
126   if (!dbfile_open(dbfname))
127     goto x;
128
129   FGETSLINE;
130   dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
131
132   dbassert( dbfile_scanf("%d", &h) == 1);
133   dbassert(h==rd->h);
134
135   for (;;) {
136     FGETSLINE;
137     if (!lbuf[0] || lbuf[0]=='#') continue;
138     if (!strcmp(lbuf,".")) break;
139
140     for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
141       if (!strcmp(lbuf,context_names[ctxi]))
142         goto found_ctx;
143     /* not found, just skip */
144     for (;;) { FGETSLINE; if (!lbuf[0]) break; }
145     continue;
146
147   found_ctx:
148     for (nchrs=0;;) {
149       int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
150       if (c=='\n') break; /* forces no match */
151       dbassert(nchrs<sizeof(chrs));
152       chrs[nchrs++]= c;
153     }
154     endsword= 0;
155     if (nchrs>0 && chrs[nchrs-1]==' ') {
156       endsword= 1;
157       nchrs--;
158     }
159
160     current= &rd->contexts[ctxi];
161     for (;;) {
162       FGETSLINE;
163       if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
164       char *ep;
165       cv= strtoul(lbuf,&ep,16);  dbassert(!*ep);
166       dbassert(!(cv & ~((1UL << rd->h)-1)));
167       
168       for (j=0; j<current->nlinks; j++)
169         if (current->links[j].col == cv) {
170           current= current->links[j].then;
171           goto found_link;
172         }
173
174       additional= mmalloc(sizeof(*additional));
175       additional->str= 0;
176       additional->defined= 0;
177       additional->match= 0;
178       additional->endsword= 0;
179       additional->nlinks= additional->alinks= 0;
180       additional->links= 0;
181       if (current->nlinks==current->alinks) {
182         current->alinks++;
183         current->alinks<<=1;
184         current->links= mrealloc(current->links,
185                                  sizeof(*current->links) * current->alinks);
186       }
187       current->links[current->nlinks].col= cv;
188       current->links[current->nlinks].then= additional;
189       current->nlinks++;
190       current= additional;
191
192     found_link:;
193     }
194
195     if (!current->defined) {
196       free(current->str);
197       current->str= 0;
198       current->defined= 1;
199       current->match= 0;
200
201       if (nchrs) {
202         current->str= mmalloc(nchrs+1);
203         memcpy(current->str, chrs, nchrs);
204         current->str[nchrs]= 0;
205         current->match= 1;
206         current->endsword= endsword;
207       }
208     }
209   }
210  x:
211   dbfile_close();
212   free(dbfname);
213 }
214
215 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
216   fprintf(resolver,"{");
217   const char *spc="";
218   int ctxi;
219   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
220     if (!(ctxmap & (1u << ctxi))) continue;
221     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
222     spc=" ";
223   }
224   fprintf(resolver,"}");
225 }
226
227 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
228                             int unk_l, int unk_r, unsigned unk_ctxmap) {
229   int c,i, x,y;
230   const OcrResultGlyph *s;
231   const char *p;
232   Pixcol pv;
233
234   FILE *resolver= resolve_start();
235   if (!resolver || !(o_flags & ff_editcharset))
236     fatal("OCR failed - unrecognised characters or ligatures.\n"
237           "Character set database needs to be updated or augmented.\n"
238           "See README.charset.\n");
239   
240   fprintf(resolver,
241           "char\n"
242           "%d %d ",unk_l,unk_r);
243   cu_pr_ctxmap(resolver,unk_ctxmap);
244   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
245     if (!strcmp(s->s," ")) continue;
246     fprintf(resolver," %d %d ",s->l,s->r);
247     cu_pr_ctxmap(resolver, 1u << s->ctxi);
248     fprintf(resolver," ");
249     for (p=s->s; (c= *p); p++) {
250       if (c=='\\') fprintf(resolver,"\\%c",c);
251       else if (c>=33 && c<=126) fputc(c,resolver);
252       else fprintf(resolver,"\\x%02x",(unsigned char)c);
253     }
254   }
255   fputc('\n',resolver);
256
257   fprintf(resolver,
258           "/* XPM */\n"
259           "static char *t[] = {\n"
260           "/* columns rows colors chars-per-pixel */\n"
261           "\"%d %d 2 1\",\n"
262           "\"  c black\",\n"
263           "\"o c white\",\n",
264           w,rd->h);
265   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
266     fputc('"',resolver);
267     for (x=0; x<w; x++)
268       fputc(cols[x] & pv ? 'o' : ' ', resolver);
269     fputs("\",\n",resolver);
270   }
271   fputs("};\n",resolver);
272
273   resolve_finish();
274   readdb(rd);
275 }
276
277 static void add_result(OcrReader *rd, const char *s, int l, int r, int ctxi) {
278   if (rd->nresults >= rd->aresults) {
279     rd->aresults++; rd->aresults<<=1;
280     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
281   }
282   rd->results[rd->nresults].s= s;
283   rd->results[rd->nresults].l= l;
284   rd->results[rd->nresults].r= r;
285   rd->results[rd->nresults].ctxi= ctxi;
286   rd->nresults++;
287 }
288
289
290 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
291                                    DatabaseNode *start, int *matchx_r) {
292   DatabaseNode *current= start;
293   DatabaseNode *bestmatch= 0;
294   int i;
295   int x= fca->x;
296
297   for (;;) {
298     debug_flush();
299     debugf(" | x=%d",x);
300     if (x > fca->w) break;
301     Pixcol cv= fca->cols[x];
302     debugf(" cv=%"PSPIXCOL(PRIx),cv);
303     for (i=0; i<current->nlinks; i++)
304       if (current->links[i].col == cv)
305         goto found;
306     /* not found */
307     debugf(" ?");
308     break;
309
310   found:
311     current= current->links[i].then;
312     if (current->match) {
313       debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
314       bestmatch= current;
315       *matchx_r= x;
316     } else {
317       debugf(" ...");
318     }
319
320     x++;
321   }
322   return bestmatch;
323 }  
324
325 static DatabaseNode *findchar(const FindCharArgs *fca,
326                               int *match_rx, int *match_rctxi) {
327   FindCharResults results[NCONTEXTS];
328   int ctxi, match=-1, nmatches=0;
329
330   debugf("OCR  lx=%d ct_state=%x  ", fca->x, fca->ctxmap);
331   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
332     results[ctxi].match= 0;
333     if (!(fca->ctxmap & (1u << ctxi))) continue;
334     debugf(" || %s",context_names[ctxi]);
335
336     results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
337                                        &results[ctxi].rx);
338     if (!results[ctxi].match) continue;
339
340     match= ctxi;
341     nmatches++;
342   }
343   if (nmatches==1) {
344     debugf(" unique");
345   } else {
346     debugf(" ambiguous");
347     match= !fca->ct->findchar_select ? -1 :
348       fca->ct->findchar_select(fca,results);
349     debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
350   }
351   if (match<0)
352     return 0;
353   
354   *match_rx= results[match].rx;
355   if (match_rctxi) *match_rctxi= match;
356   return results[match].match;
357 }
358
359 static int findchar_select_text(const FindCharArgs *fca,
360                                 const FindCharResults results[]) {
361   if (fca->ctxmap != 017) return -1;
362
363   dbassert(! results[ct_Digit].match );
364   if (results[ct_Word].match) return ct_Word;
365   if (results[ct_Lower].rx > results[ct_Upper].rx) return ct_Lower;
366   if (results[ct_Upper].rx > results[ct_Lower].rx) return ct_Upper;
367   return -1;
368 }
369
370 const struct OcrCellTypeInfo ocr_celltype_number= {
371   ctf_Digit, ctf_Digit, ctf_Digit,
372   .space_spaces= 5,
373   .name= "number",
374   .findchar_select= 0
375 };
376 const struct OcrCellTypeInfo ocr_celltype_text= {
377   .initial=  ctf_Digit | ctf_Upper,
378   .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
379   .midword=  ctf_Digit | ctf_Lower,
380   .space_spaces= 4,
381   .name= "text",
382   .findchar_select= findchar_select_text
383 };
384
385
386 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
387
388 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
389   int nspaces;
390   int x;
391
392   FindCharArgs fca;
393   fca.rd= rd;
394   fca.ct= ct;
395   fca.w= w;
396   fca.cols= cols;
397   fca.x= -1;
398
399  restart:
400
401   nspaces=- w;
402   fca.ctxmap= ct->initial;
403   rd->nresults=0;
404   debugf("OCR h=%d w=%d",rd->h,w);
405   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
406   debugf("\n");
407   debug_flush();
408
409   x=0;
410   for (;;) {
411     debug_flush();
412     /* skip spaces */
413     if (x>=w)
414       break;
415
416     if (!cols[x]) {
417       nspaces++;
418       x++;
419       if (nspaces == ct->space_spaces) {
420         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
421         fca.ctxmap= ct->nextword;
422       }
423       continue;
424     }
425
426     /* something here, so we need to add the spaces */
427     if (nspaces >= ct->space_spaces)
428       add_result(rd," ",x-nspaces,x+1,-1);
429     nspaces=0;
430
431     fca.x= x;
432
433     int match_rx=-1;
434     int match_ctxi=-1;
435     DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
436     
437     if (match) {
438       debugf(" || YES");
439       add_result(rd, match->str, x, match_rx, match_ctxi);
440       x= match_rx+1;
441       if (match->match) fca.ctxmap= ct->midword;
442       else debugf(" (empty)");
443       if (match->endsword) {
444         nspaces= ct->space_spaces;
445         debugf("_");
446         fca.ctxmap= ct->nextword;
447       }
448       debugf("\n");
449     } else {
450       int rx;
451       debugf(" || UNKNOWN");
452       for (rx=x; rx<w && cols[rx]; rx++);
453       debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
454       debug_flush();
455       callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
456       goto restart;
457     }
458
459   }
460   add_result(rd, 0,-1,-1,-1);
461   debugf("OCR  finished %d glyphs\n",rd->nresults);
462   debug_flush();
463   return rd->results;
464 }
465
466 OcrReader *ocr_init(int h) {
467   OcrReader *rd;
468
469   if (o_flags & ff_dict_fetch) {
470     char *fetchfile= masprintf("char%d",h);
471     progress("Updating %s...",fetchfile);
472     fetch_with_rsync(fetchfile);
473     free(fetchfile);
474   }
475
476   rd= mmalloc(sizeof(*rd));
477   memset(rd,0,sizeof(*rd));
478   rd->h= h;
479   readdb(rd);
480   return rd;
481 }