chiark / gitweb /
break out char_start_define_text into a proc
[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 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->match);
248     fprintf(resolver," ");
249     cu_pr_ctxmap(resolver, s->ctxmap);
250     fprintf(resolver," ");
251     for (p=s->s; (c= *p); p++) {
252       if (c=='\\') fprintf(resolver,"\\%c",c);
253       else if (c>=33 && c<=126) fputc(c,resolver);
254       else fprintf(resolver,"\\x%02x",(unsigned char)c);
255     }
256   }
257   fputc('\n',resolver);
258
259   fprintf(resolver,
260           "/* XPM */\n"
261           "static char *t[] = {\n"
262           "/* columns rows colors chars-per-pixel */\n"
263           "\"%d %d 2 1\",\n"
264           "\"  c black\",\n"
265           "\"o c white\",\n",
266           w,rd->h);
267   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
268     fputc('"',resolver);
269     for (x=0; x<w; x++)
270       fputc(cols[x] & pv ? 'o' : ' ', resolver);
271     fputs("\",\n",resolver);
272   }
273   fputs("};\n",resolver);
274
275   resolve_finish();
276   readdb(rd);
277 }
278
279 static void add_result(OcrReader *rd, const char *s, int l, int r,
280                        int match, unsigned ctxmap) {
281   if (rd->nresults >= rd->aresults) {
282     rd->aresults++; rd->aresults<<=1;
283     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
284   }
285   rd->results[rd->nresults].s= s;
286   rd->results[rd->nresults].l= l;
287   rd->results[rd->nresults].r= r;
288   rd->results[rd->nresults].match= match;
289   rd->results[rd->nresults].ctxmap= ctxmap;
290   rd->nresults++;
291 }
292
293
294 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
295                                    DatabaseNode *start, int *matchx_r) {
296   DatabaseNode *current= start;
297   DatabaseNode *bestmatch= 0;
298   int i;
299   int x= fca->x;
300
301   for (;;) {
302     debug_flush();
303     debugf(" | x=%d",x);
304     if (x > fca->w) break;
305     Pixcol cv= fca->cols[x];
306     debugf(" cv=%"PSPIXCOL(PRIx),cv);
307     for (i=0; i<current->nlinks; i++)
308       if (current->links[i].col == cv)
309         goto found;
310     /* not found */
311     debugf(" ?");
312     break;
313
314   found:
315     current= current->links[i].then;
316     if (current->match) {
317       debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
318       bestmatch= current;
319       *matchx_r= x;
320     } else {
321       debugf(" ...");
322     }
323
324     x++;
325   }
326   return bestmatch;
327 }  
328
329 static DatabaseNode *findchar(const FindCharArgs *fca,
330                               int *match_rx, int *match_rctxi) {
331   FindCharResults results[NCONTEXTS];
332   int ctxi, match=-1, nmatches=0;
333
334   debugf("OCR  lx=%d ct_state=%x  ", fca->x, fca->ctxmap);
335   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
336     results[ctxi].match= 0;
337     if (!(fca->ctxmap & (1u << ctxi))) continue;
338     debugf(" || %s",context_names[ctxi]);
339
340     results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
341                                        &results[ctxi].rx);
342     if (!results[ctxi].match) continue;
343
344     match= ctxi;
345     nmatches++;
346   }
347   if (nmatches==1) {
348     debugf(" unique");
349   } else {
350     debugf(" ambiguous");
351     match= !fca->ct->findchar_select ? -1 :
352       fca->ct->findchar_select(fca,results);
353     debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
354   }
355   if (match<0)
356     return 0;
357   
358   *match_rx= results[match].rx;
359   if (match_rctxi) *match_rctxi= match;
360   return results[match].match;
361 }
362
363 static int findchar_select_text(const FindCharArgs *fca,
364                                 const FindCharResults results[]) {
365   if (fca->ctxmap != 017) return -1;
366
367   dbassert(! results[ct_Digit].match );
368   if (results[ct_Word].match) return ct_Word;
369   if (results[ct_Lower].rx > results[ct_Upper].rx) return ct_Lower;
370   if (results[ct_Upper].rx > results[ct_Lower].rx) return ct_Upper;
371   return -1;
372 }
373
374 const struct OcrCellTypeInfo ocr_celltype_number= {
375   ctf_Digit, ctf_Digit, ctf_Digit,
376   .space_spaces= 5,
377   .name= "number",
378   .findchar_select= 0
379 };
380 const struct OcrCellTypeInfo ocr_celltype_text= {
381   .initial=  ctf_Digit | ctf_Upper,
382   .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
383   .midword=  ctf_Digit | ctf_Lower,
384   .space_spaces= 4,
385   .name= "text",
386   .findchar_select= findchar_select_text
387 };
388
389
390 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
391
392 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
393   int nspaces;
394   int x;
395
396   FindCharArgs fca;
397   fca.rd= rd;
398   fca.ct= ct;
399   fca.w= w;
400   fca.cols= cols;
401   fca.x= -1;
402
403  restart:
404
405   nspaces=- w;
406   fca.ctxmap= ct->initial;
407   rd->nresults=0;
408   debugf("OCR h=%d w=%d",rd->h,w);
409   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
410   debugf("\n");
411   debug_flush();
412
413   x=0;
414   for (;;) {
415     debug_flush();
416     /* skip spaces */
417     if (x>=w)
418       break;
419
420     if (!cols[x]) {
421       nspaces++;
422       x++;
423       if (nspaces == ct->space_spaces) {
424         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
425         fca.ctxmap= ct->nextword;
426       }
427       continue;
428     }
429
430     /* something here, so we need to add the spaces */
431     if (nspaces >= ct->space_spaces)
432       add_result(rd," ",x-nspaces,x+1,-1,0);
433     nspaces=0;
434
435     fca.x= x;
436
437     int match_rx=-1;
438     int match_ctxi=-1;
439     DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
440     
441     if (match) {
442       debugf(" || YES");
443       add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
444       x= match_rx+1;
445       if (match->match) fca.ctxmap= ct->midword;
446       else debugf(" (empty)");
447       if (match->endsword) {
448         nspaces= ct->space_spaces;
449         debugf("_");
450         fca.ctxmap= ct->nextword;
451       }
452       debugf("\n");
453     } else {
454       int rx;
455       debugf(" || UNKNOWN");
456       for (rx=x; rx<w && cols[rx]; rx++);
457       debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
458       debug_flush();
459       callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
460       goto restart;
461     }
462
463   }
464   add_result(rd, 0,-1,-1,-1,0);
465   debugf("OCR  finished %d glyphs\n",rd->nresults);
466   debug_flush();
467   return rd->results;
468 }
469
470 OcrReader *ocr_init(int h) {
471   OcrReader *rd;
472
473   if (o_flags & ff_dict_fetch) {
474     char *fetchfile= masprintf("char%d",h);
475     progress("Updating %s...",fetchfile);
476     fetch_with_rsync(fetchfile);
477     free(fetchfile);
478   }
479
480   rd= mmalloc(sizeof(*rd));
481   memset(rd,0,sizeof(*rd));
482   rd->h= h;
483   readdb(rd);
484   return rd;
485 }