chiark / gitweb /
Recase findchar_unique as findchar
[ypp-sc-tools.db-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 typedef struct {
44   OcrReader *rd;
45   int w;
46   Pixcol *cols;
47   int x;
48   unsigned ctxmap;
49 } FindCharArgs;
50 typedef struct {
51   DatabaseNode *match;
52   int rx;
53 } FindCharResults;
54
55 static const char *context_names[]= {
56   "Lower",
57   "Upper",
58   "Digit"
59 };
60 struct OcrCellTypeInfo {
61   /* bitmaps of indices into context_names: */
62   unsigned initial, nextword, midword;
63   int space_spaces;
64   const char *name;
65 };
66 const struct OcrCellTypeInfo ocr_celltype_number= {
67   4,4,4,
68   .space_spaces= 5,
69   .name= "number"
70 };
71 const struct OcrCellTypeInfo ocr_celltype_text= {
72   .initial=2, /* Uppercase */
73   .nextword=3, /* Either */
74   .midword=1, /* Lower only */
75   .space_spaces= 4,
76   .name= "text"
77 };
78
79
80 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
81
82 struct OcrReader {
83   int h;
84   DatabaseNode contexts[NCONTEXTS];
85   OcrResultGlyph *results;
86   int aresults, nresults;
87 };
88
89 DEBUG_DEFINE_DEBUGF(ocr)
90
91 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
92
93 static void cleardb_node(DatabaseNode *n) {
94   int i;
95   free(n->str); n->str=0;
96   n->defined=n->match=n->endsword= 0;
97   for (i=0; i<n->nlinks; i++)
98     cleardb_node(n->links[i].then);
99 }
100
101 static void readdb1(OcrReader *rd, const char *which);
102
103 static void readdb(OcrReader *rd) {
104   int ctxi;
105   
106   for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
107     cleardb_node(&rd->contexts[ctxi]);
108
109   readdb1(rd, "master");
110   readdb1(rd, "local");
111 }
112
113 static void readdb1(OcrReader *rd, const char *which) {
114   int nchrs;
115   DatabaseNode *current, *additional;
116   char chrs[100];
117   Pixcol cv;
118   int j,ctxi;
119   int h, endsword;
120   char lbuf[100];
121
122   char *dbfname= masprintf("%s/#%s-char%d#.txt",
123                            get_vardir(), which, rd->h);
124   
125   if (!dbfile_open(dbfname))
126     goto x;
127
128   FGETSLINE;
129   dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
130
131   dbassert( dbfile_scanf("%d", &h) == 1);
132   dbassert(h==rd->h);
133
134   for (;;) {
135     FGETSLINE;
136     if (!lbuf[0] || lbuf[0]=='#') continue;
137     if (!strcmp(lbuf,".")) break;
138
139     for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
140       if (!strcmp(lbuf,context_names[ctxi]))
141         goto found_ctx;
142     /* not found, just skip */
143     for (;;) { FGETSLINE; if (!lbuf[0]) break; }
144     continue;
145
146   found_ctx:
147     for (nchrs=0;;) {
148       int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
149       if (c=='\n') break; /* forces no match */
150       dbassert(nchrs<sizeof(chrs));
151       chrs[nchrs++]= c;
152     }
153     endsword= 0;
154     if (nchrs>0 && chrs[nchrs-1]==' ') {
155       endsword= 1;
156       nchrs--;
157     }
158
159     current= &rd->contexts[ctxi];
160     for (;;) {
161       FGETSLINE;
162       if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
163       char *ep;
164       cv= strtoul(lbuf,&ep,16);  dbassert(!*ep);
165       dbassert(!(cv & ~((1UL << rd->h)-1)));
166       
167       for (j=0; j<current->nlinks; j++)
168         if (current->links[j].col == cv) {
169           current= current->links[j].then;
170           goto found_link;
171         }
172
173       additional= mmalloc(sizeof(*additional));
174       additional->str= 0;
175       additional->defined= 0;
176       additional->match= 0;
177       additional->endsword= 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     if (!current->defined) {
195       free(current->str);
196       current->str= 0;
197       current->defined= 1;
198       current->match= 0;
199
200       if (nchrs) {
201         current->str= mmalloc(nchrs+1);
202         memcpy(current->str, chrs, nchrs);
203         current->str[nchrs]= 0;
204         current->match= 1;
205         current->endsword= endsword;
206       }
207     }
208   }
209  x:
210   dbfile_close();
211   free(dbfname);
212 }
213
214 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
215   fprintf(resolver,"{");
216   const char *spc="";
217   int ctxi;
218   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
219     if (!(ctxmap & (1u << ctxi))) continue;
220     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
221     spc=" ";
222   }
223   fprintf(resolver,"}");
224 }
225
226 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
227                             int unk_l, int unk_r, unsigned unk_ctxmap) {
228   int c,i, x,y;
229   const OcrResultGlyph *s;
230   const char *p;
231   Pixcol pv;
232
233   FILE *resolver= resolve_start();
234   if (!resolver)
235     fatal("OCR failed - unrecognised characters or ligatures.\n"
236           "Character set database needs to be updated or augmented.\n"
237           "See README.charset.\n");
238   
239   fprintf(resolver,
240           "char\n"
241           "%d %d ",unk_l,unk_r);
242   cu_pr_ctxmap(resolver,unk_ctxmap);
243   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
244     if (!strcmp(s->s," ")) continue;
245     fprintf(resolver," %d %d ",s->l,s->r);
246     cu_pr_ctxmap(resolver,s->ctxmap);
247     fprintf(resolver," ");
248     for (p=s->s; (c= *p); p++) {
249       if (c=='\\') fprintf(resolver,"\\%c",c);
250       else if (c>=33 && c<=126) fputc(c,resolver);
251       else fprintf(resolver,"\\x%02x",(unsigned char)c);
252     }
253   }
254   fputc('\n',resolver);
255
256   fprintf(resolver,
257           "/* XPM */\n"
258           "static char *t[] = {\n"
259           "/* columns rows colors chars-per-pixel */\n"
260           "\"%d %d 2 1\",\n"
261           "\"  c black\",\n"
262           "\"o c white\",\n",
263           w,rd->h);
264   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
265     fputc('"',resolver);
266     for (x=0; x<w; x++)
267       fputc(cols[x] & pv ? 'o' : ' ', resolver);
268     fputs("\",\n",resolver);
269   }
270   fputs("};\n",resolver);
271
272   resolve_finish();
273   readdb(rd);
274 }
275
276 static void add_result(OcrReader *rd, const char *s, int l, int r,
277                        unsigned ctxmap) {
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].ctxmap= ctxmap;
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, int *match_rx) {
326   FindCharResults results[NCONTEXTS];
327   int ctxi, match=-1, nmatches=0;
328
329   debugf("OCR  lx=%d ct_state=%x  ", fca->x, fca->ctxmap);
330   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
331     results[ctxi].match= 0;
332     if (!(fca->ctxmap & (1u << ctxi))) continue;
333     debugf(" || %s",context_names[ctxi]);
334
335     results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
336                                        &results[ctxi].rx);
337     if (!results[ctxi].match) continue;
338
339     match= ctxi;
340     nmatches++;
341   }
342   if (nmatches==1) {
343     debugf( " unambiguous");
344   } else {
345     match=-1;
346   }
347   if (match<0)
348     return 0;
349   
350   *match_rx= results[ctxi].rx;
351   return results[ctxi].match;
352 }
353
354 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
355
356 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
357   int nspaces;
358   int x;
359
360   FindCharArgs fca;
361   fca.rd= rd;
362   fca.w= w;
363   fca.cols= cols;
364   fca.x= -1;
365
366  restart:
367
368   nspaces=- w;
369   fca.ctxmap= ct->initial;
370   rd->nresults=0;
371   debugf("OCR h=%d w=%d",rd->h,w);
372   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
373   debugf("\n");
374   debug_flush();
375
376   x=0;
377   for (;;) {
378     debug_flush();
379     /* skip spaces */
380     if (x>=w)
381       break;
382
383     if (!cols[x]) {
384       nspaces++;
385       x++;
386       if (nspaces == ct->space_spaces) {
387         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
388         fca.ctxmap= ct->nextword;
389       }
390       continue;
391     }
392
393     /* something here, so we need to add the spaces */
394     if (nspaces >= ct->space_spaces)
395       add_result(rd," ",x-nspaces,x+1,0);
396     nspaces=0;
397
398     fca.x= x;
399
400     int match_rx=-1;
401     DatabaseNode *match= findchar(&fca, &match_rx);
402     
403     if (match) {
404       debugf(" || YES");
405       add_result(rd, match->str, x, match_rx, fca.ctxmap);
406       x= match_rx+1;
407       if (match->match) fca.ctxmap= ct->midword;
408       else debugf(" (empty)");
409       if (match->endsword) {
410         nspaces= ct->space_spaces;
411         debugf("_");
412         fca.ctxmap= ct->nextword;
413       }
414       debugf("\n");
415     } else {
416       int rx;
417       debugf(" || UNKNOWN");
418       for (rx=x; rx<w && cols[rx]; rx++);
419       debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
420       debug_flush();
421       callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
422       goto restart;
423     }
424
425   }
426   add_result(rd, 0,-1,-1,0);
427   debugf("OCR  finished %d glyphs\n",rd->nresults);
428   debug_flush();
429   return rd->results;
430 }
431
432 OcrReader *ocr_init(int h) {
433   OcrReader *rd;
434
435   if (o_flags & ff_dict_fetch) {
436     char *fetchfile= masprintf("char%d",h);
437     progress("Updating %s...",fetchfile);
438     fetch_with_rsync(fetchfile);
439     free(fetchfile);
440   }
441
442   rd= mmalloc(sizeof(*rd));
443   memset(rd,0,sizeof(*rd));
444   rd->h= h;
445   readdb(rd);
446   return rd;
447 }