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