chiark / gitweb /
b7934c983e2f407a362183c0e5aad6756653165c
[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 #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 typedef struct {
279   OcrReader *rd;
280   int w;
281   Pixcol *cols;
282   int x;
283   unsigned ctxmap;
284 } FindCharArgs;
285
286 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
287                                    DatabaseNode *start, int *matchx_r) {
288   DatabaseNode *current= start;
289   DatabaseNode *bestmatch= 0;
290   int i;
291   int x= fca->x;
292
293   for (;;) {
294     debug_flush();
295     debugf(" | x=%d",x);
296     if (x > fca->w) break;
297     Pixcol cv= fca->cols[x];
298     debugf(" cv=%"PSPIXCOL(PRIx),cv);
299     for (i=0; i<current->nlinks; i++)
300       if (current->links[i].col == cv)
301         goto found;
302     /* not found */
303     debugf(" ?");
304     break;
305
306   found:
307     current= current->links[i].then;
308     if (current->match) {
309       debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
310       bestmatch= current;
311       *matchx_r= x;
312     } else {
313       debugf(" ...");
314     }
315
316     x++;
317   }
318   return bestmatch;
319 }  
320
321 static DatabaseNode *findchar_unique(const FindCharArgs *fca, int *match_rx) {
322   DatabaseNode *uniquematch= 0;
323   int ctxi;
324     
325   debugf("OCR  lx=%d ct_state=%x  ", fca->x, fca->ctxmap);
326   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
327     if (!(fca->ctxmap & (1u << ctxi))) continue;
328     debugf(" || %s",context_names[ctxi]);
329
330     DatabaseNode *match=
331       findchar_1ctx(fca, &fca->rd->contexts[ctxi], match_rx);
332     if (!match) continue;
333
334     if (uniquematch && strcmp(match->str, uniquematch->str)) {
335       debugf( " ambiguous");
336       uniquematch= 0;
337     } else {
338       uniquematch= match;
339     }
340   }
341
342   return uniquematch;
343 }
344
345 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
346
347 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
348   int nspaces;
349   int x;
350
351   FindCharArgs fca;
352   fca.rd= rd;
353   fca.w= w;
354   fca.cols= cols;
355   fca.x= -1;
356
357  restart:
358
359   nspaces=- w;
360   fca.ctxmap= ct->initial;
361   rd->nresults=0;
362   debugf("OCR h=%d w=%d",rd->h,w);
363   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
364   debugf("\n");
365   debug_flush();
366
367   x=0;
368   for (;;) {
369     debug_flush();
370     /* skip spaces */
371     if (x>=w)
372       break;
373
374     if (!cols[x]) {
375       nspaces++;
376       x++;
377       if (nspaces == ct->space_spaces) {
378         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
379         fca.ctxmap= ct->nextword;
380       }
381       continue;
382     }
383
384     /* something here, so we need to add the spaces */
385     if (nspaces >= ct->space_spaces)
386       add_result(rd," ",x-nspaces,x+1,0);
387     nspaces=0;
388
389     fca.x= x;
390
391     int match_rx=-1;
392     DatabaseNode *match= findchar_unique(&fca, &match_rx);
393     
394     if (match) {
395       debugf(" || YES");
396       add_result(rd, match->str, x, match_rx, fca.ctxmap);
397       x= match_rx+1;
398       if (match->match) fca.ctxmap= ct->midword;
399       else debugf(" (empty)");
400       if (match->endsword) {
401         nspaces= ct->space_spaces;
402         debugf("_");
403         fca.ctxmap= ct->nextword;
404       }
405       debugf("\n");
406     } else {
407       int rx;
408       debugf(" || UNKNOWN");
409       for (rx=x; rx<w && cols[rx]; rx++);
410       debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
411       debug_flush();
412       callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
413       goto restart;
414     }
415
416   }
417   add_result(rd, 0,-1,-1,0);
418   debugf("OCR  finished %d glyphs\n",rd->nresults);
419   debug_flush();
420   return rd->results;
421 }
422
423 OcrReader *ocr_init(int h) {
424   OcrReader *rd;
425
426   if (o_flags & ff_dict_fetch) {
427     char *fetchfile= masprintf("char%d",h);
428     progress("Updating %s...",fetchfile);
429     fetch_with_rsync(fetchfile);
430     free(fetchfile);
431   }
432
433   rd= mmalloc(sizeof(*rd));
434   memset(rd,0,sizeof(*rd));
435   rd->h= h;
436   readdb(rd);
437   return rd;
438 }