chiark / gitweb /
WIP new dictionary arrangements
[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 #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 static const char *context_names[]= {
44   "Lower",
45   "Upper",
46   "Digit"
47 };
48 struct OcrCellTypeInfo {
49   /* bitmaps of indices into context_names: */
50   unsigned initial, nextword, midword;
51   int space_spaces;
52   const char *name;
53 };
54 const struct OcrCellTypeInfo ocr_celltype_number= {
55   4,4,4,
56   .space_spaces= 5,
57   .name= "number"
58 };
59 const struct OcrCellTypeInfo ocr_celltype_text= {
60   .initial=2, /* Uppercase */
61   .nextword=3, /* Either */
62   .midword=1, /* Lower only */
63   .space_spaces= 4,
64   .name= "text"
65 };
66
67
68 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
69
70 struct OcrReader {
71   int h;
72   DatabaseNode contexts[NCONTEXTS];
73   OcrResultGlyph *results;
74   int aresults, nresults;
75 };
76
77 DEBUG_DEFINE_DEBUGF(ocr)
78
79 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
80
81 static void cleardb_node(DatabaseNode *n) {
82   int i;
83   free(n->str); n->str=0;
84   n->defined=n->match=n->endsword= 0;
85   for (i=0; i<n->nlinks; i++)
86     cleardb_node(n->links[i].then);
87 }
88
89 static void readdb1(OcrReader *rd, const char *which);
90
91 static void readdb(OcrReader *rd) {
92   int ctxi;
93   
94   for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
95     cleardb_node(&rd->contexts[ctxi]);
96
97   readdb1(rd, "master");
98   readdb1(rd, "local");
99 }
100
101 static void readdb1(OcrReader *rd, const char *which) {
102   int nchrs;
103   DatabaseNode *current, *additional;
104   char chrs[100];
105   Pixcol cv;
106   int j,ctxi;
107   int h, endsword;
108   char lbuf[100];
109
110   char *dbfname= masprintf("%s/#%s-char%d#.txt",
111                            get_vardir(), which, rd->h);
112   
113   if (!dbfile_open(dbfname))
114     goto x;
115
116   FGETSLINE;
117   dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
118
119   dbassert( dbfile_scanf("%d", &h) == 1);
120   dbassert(h==rd->h);
121
122   for (;;) {
123     FGETSLINE;
124     if (!lbuf[0] || 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; if (!lbuf[0]) break; }
132     continue;
133
134   found_ctx:
135     for (nchrs=0;;) {
136       int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
137       if (c=='\n') break; /* forces no match */
138       dbassert(nchrs<sizeof(chrs));
139       chrs[nchrs++]= c;
140     }
141     endsword= 0;
142     if (nchrs>0 && chrs[nchrs-1]==' ') {
143       endsword= 1;
144       nchrs--;
145     }
146
147     current= &rd->contexts[ctxi];
148     for (;;) {
149       FGETSLINE;
150       if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
151       char *ep;
152       cv= strtoul(lbuf,&ep,16);  dbassert(!*ep);
153       dbassert(!(cv & ~((1UL << rd->h)-1)));
154       
155       for (j=0; j<current->nlinks; j++)
156         if (current->links[j].col == cv) {
157           current= current->links[j].then;
158           goto found_link;
159         }
160
161       additional= mmalloc(sizeof(*additional));
162       additional->str= 0;
163       additional->defined= 0;
164       additional->match= 0;
165       additional->endsword= 0;
166       additional->nlinks= additional->alinks= 0;
167       additional->links= 0;
168       if (current->nlinks==current->alinks) {
169         current->alinks++;
170         current->alinks<<=1;
171         current->links= mrealloc(current->links,
172                                  sizeof(*current->links) * current->alinks);
173       }
174       current->links[current->nlinks].col= cv;
175       current->links[current->nlinks].then= additional;
176       current->nlinks++;
177       current= additional;
178
179     found_link:;
180     }
181
182     if (!current->defined) {
183       free(current->str);
184       current->str= 0;
185       current->defined= 1;
186       current->match= 0;
187
188       if (nchrs) {
189         current->str= mmalloc(nchrs+1);
190         memcpy(current->str, chrs, nchrs);
191         current->str[nchrs]= 0;
192         current->match= 1;
193         current->endsword= endsword;
194       }
195     }
196   }
197  x:
198   dbfile_close();
199   free(dbfname);
200 }
201
202 static void cu_pr_ctxmap(FILE *resolver, 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 c,i, x,y;
217   const OcrResultGlyph *s;
218   const char *p;
219   Pixcol pv;
220
221   FILE *resolver= resolve_start();
222   if (!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   fprintf(resolver,
228           "char\n"
229           "%d %d ",unk_l,unk_r);
230   cu_pr_ctxmap(resolver,unk_ctxmap);
231   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
232     if (!strcmp(s->s," ")) continue;
233     fprintf(resolver," %d %d ",s->l,s->r);
234     cu_pr_ctxmap(resolver,s->ctxmap);
235     fprintf(resolver," ");
236     for (p=s->s; (c= *p); p++) {
237       if (c=='\\') fprintf(resolver,"\\%c",c);
238       else if (c>=33 && c<=126) fputc(c,resolver);
239       else fprintf(resolver,"\\x%02x",(unsigned char)c);
240     }
241   }
242   fputc('\n',resolver);
243
244   fprintf(resolver,
245           "/* XPM */\n"
246           "static char *t[] = {\n"
247           "/* columns rows colors chars-per-pixel */\n"
248           "\"%d %d 2 1\",\n"
249           "\"  c black\",\n"
250           "\"o c white\",\n",
251           w,rd->h);
252   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
253     fputc('"',resolver);
254     for (x=0; x<w; x++)
255       fputc(cols[x] & pv ? 'o' : ' ', resolver);
256     fputs("\",\n",resolver);
257   }
258   fputs("};\n",resolver);
259
260   resolve_finish();
261   readdb(rd);
262 }
263
264 static void add_result(OcrReader *rd, const char *s, int l, int r,
265                        unsigned ctxmap) {
266   if (rd->nresults >= rd->aresults) {
267     rd->aresults++; rd->aresults<<=1;
268     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
269   }
270   rd->results[rd->nresults].s= s;
271   rd->results[rd->nresults].l= l;
272   rd->results[rd->nresults].r= r;
273   rd->results[rd->nresults].ctxmap= ctxmap;
274   rd->nresults++;
275 }
276
277
278 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
279
280 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
281   int nspaces;
282   unsigned ctxmap;
283   int ctxi, i, x;
284
285  restart:
286
287   nspaces=- w;
288   ctxmap= ct->initial;
289   rd->nresults=0;
290   debugf("OCR h=%d w=%d",rd->h,w);
291   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
292   debugf("\n");
293   debug_flush();
294
295   x=0;
296   for (;;) {
297     debug_flush();
298     /* skip spaces */
299     if (x>=w)
300       break;
301
302     if (!cols[x]) {
303       nspaces++;
304       x++;
305       if (nspaces == ct->space_spaces) {
306         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
307         ctxmap= ct->nextword;
308       }
309       continue;
310     }
311
312     /* something here, so we need to add the spaces */
313     if (nspaces >= ct->space_spaces)
314       add_result(rd," ",x-nspaces,x+1,0);
315     nspaces=0;
316
317     /* find character */
318     int lx=x;
319
320     DatabaseNode *uniquematch= 0;
321     int uniquematch_rx=-1;
322     
323     debugf("OCR  lx=%d ctxmap=%x  ",lx,ctxmap);
324
325     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
326       DatabaseNode *current= &rd->contexts[ctxi];;
327       DatabaseNode *bestmatch= 0;
328       int bestmatch_rx=-1;
329
330       x= lx;
331       if (!(ctxmap & (1u << ctxi))) continue;
332       debugf(" || %s",context_names[ctxi]);
333
334       for (;;) {
335         debug_flush();
336         debugf(" | x=%d",x);
337         if (x>w) break;
338         Pixcol cv= cols[x];
339         debugf(" cv=%"PSPIXCOL(PRIx),cv);
340         for (i=0; i<current->nlinks; i++)
341           if (current->links[i].col == cv)
342             goto found;
343         /* not found */
344         debugf(" ?");
345         break;
346
347       found:
348         current= current->links[i].then;
349         if (current->match) {
350           debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
351           bestmatch= current;
352           bestmatch_rx= x;
353         } else {
354           debugf(" ...");
355         }
356
357         x++;
358       }
359       
360       if (bestmatch) {
361         if (uniquematch && strcmp(bestmatch->str, uniquematch->str)) {
362           debugf( " ambiguous");
363           uniquematch= 0;
364           break;
365         }
366         uniquematch= bestmatch;
367         uniquematch_rx= bestmatch_rx;
368       }
369     }
370
371     if (uniquematch) {
372       debugf(" || YES");
373       add_result(rd, uniquematch->str, lx, uniquematch_rx, ctxmap);
374       x= uniquematch_rx+1;
375       if (uniquematch->match) ctxmap= ct->midword;
376       else debugf(" (empty)");
377       if (uniquematch->endsword) {
378         nspaces= ct->space_spaces;
379         debugf("_");
380         ctxmap= ct->nextword;
381       }
382       debugf("\n");
383     } else {
384       int rx;
385       debugf(" || UNKNOWN");
386       for (rx=lx; rx<w && cols[rx]; rx++);
387       debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
388       debug_flush();
389       callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
390       goto restart;
391     }
392   }
393   add_result(rd, 0,-1,-1,0);
394   debugf("OCR  finished %d glyphs\n",rd->nresults);
395   debug_flush();
396   return rd->results;
397 }
398
399 OcrReader *ocr_init(int h) {
400   OcrReader *rd;
401
402   if (o_flags & ff_dict_fetch) {
403     char *fetchfile= masprintf("char%d",h);
404     progress("Updating %s...",fetchfile);
405     fetch_with_rsync(fetchfile);
406     free(fetchfile);
407   }
408
409   rd= mmalloc(sizeof(*rd));
410   memset(rd,0,sizeof(*rd));
411   rd->h= h;
412   readdb(rd);
413   return rd;
414 }