chiark / gitweb /
show extent of character updates
[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, local:1;
40   DatabaseLink *links;
41 } DatabaseNode;
42
43 typedef struct {
44   OcrReader *rd;
45   OcrCellType ct;
46   int w;
47   const 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(Lower)                                   \
59   EACH(Upper)                                   \
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, int local);
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", 0);
111   readdb1(rd, "local",  1);
112 }
113
114 static void readdb1(OcrReader *rd, const char *which, int local) {
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 v2"));
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       dbassert( strlen(lbuf) == rd->h );
165       FILLZERO(cv);
166       int y;
167       for (y=0; y<h; y++) {
168         char pb[2];
169         pb[0]= lbuf[y];
170         pb[1]= 0;
171         char *ep;
172         unsigned pv= strtoul(pb,&ep,16);  dbassert(!*ep);
173         pixcol_p_add(&cv, y, pv);
174       }
175       
176       for (j=0; j<current->nlinks; j++)
177         if (!pixcol_cmp(&cv, &current->links[j].col)) {
178           current= current->links[j].then;
179           goto found_link;
180         }
181
182       additional= mmalloc(sizeof(*additional));
183       additional->str= 0;
184       additional->defined= 0;
185       additional->match= 0;
186       additional->endsword= 0;
187       additional->nlinks= additional->alinks= 0;
188       additional->links= 0;
189       if (current->nlinks==current->alinks) {
190         current->alinks++;
191         current->alinks<<=1;
192         current->links= mrealloc(current->links,
193                                  sizeof(*current->links) * current->alinks);
194       }
195       current->links[current->nlinks].col= cv;
196       current->links[current->nlinks].then= additional;
197       current->nlinks++;
198       current= additional;
199
200     found_link:;
201     }
202
203     if (!current->defined) {
204       free(current->str);
205       current->str= 0;
206       current->defined= 1;
207       current->match= 0;
208       current->local= local;
209
210       if (nchrs) {
211         current->str= mmalloc(nchrs+1);
212         memcpy(current->str, chrs, nchrs);
213         current->str[nchrs]= 0;
214         current->match= 1;
215         current->endsword= endsword;
216       }
217     }
218   }
219  x:
220   dbfile_close();
221   free(dbfname);
222 }
223
224 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
225   fprintf(resolver,"{");
226   const char *spc="";
227   int ctxi;
228   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
229     if (!(ctxmap & (1u << ctxi))) continue;
230     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
231     spc=" ";
232   }
233   fprintf(resolver,"}");
234 }
235
236 static void callout_unknown(OcrReader *rd, int w, const Pixcol cols[],
237                             int unk_l, int unk_r, unsigned unk_ctxmap) {
238   int c,i, x,y;
239   const OcrResultGlyph *s;
240   const char *p;
241
242   FILE *resolver= resolve_start();
243   if (!resolver || !(o_flags & ff_editcharset))
244     fatal("OCR failed - unrecognised characters or ligatures.\n"
245           "Character set database needs to be updated or augmented.\n"
246           "See README.charset.\n");
247   
248   fprintf(resolver,
249           "char\n"
250           "%d %d ",unk_l,unk_r);
251   cu_pr_ctxmap(resolver,unk_ctxmap);
252   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
253     if (!strcmp(s->s," ")) continue;
254     fprintf(resolver," %d %d ",s->l,s->r);
255     cu_pr_ctxmap(resolver, 1u << s->match);
256     fprintf(resolver," ");
257     cu_pr_ctxmap(resolver, s->ctxmap);
258     fprintf(resolver," ");
259     for (p=s->s; (c= *p); p++) {
260       if (c=='\\') fprintf(resolver,"\\%c",c);
261       else if (c>=33 && c<=126) fputc(c,resolver);
262       else fprintf(resolver,"\\x%02x",(unsigned char)c);
263     }
264   }
265   fputc('\n',resolver);
266
267   fprintf(resolver,
268           "P2\n%d %d %d\n", w, rd->h, AAMAXVAL);
269   for (y=0; y<rd->h; y++) {
270     for (x=0; x<w; x++)
271       fprintf(resolver, " %d", pixcol_p_get(&cols[x], y));
272     fputc('\n',resolver);
273   }
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="PIXCOL_PRFMT, PIXCOL_PRVAL(cv));
307     for (i=0; i<current->nlinks; i++)
308       if (!pixcol_cmp(&cv, &current->links[i].col))
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   
366   dbassert(! results[ct_Digit].match ); /* digits are supposedly unambiguous */
367
368   switch (fca->ctxmap) {
369
370 #define RETURN_IF_LONGER(this,that) do{                 \
371     if (results[ct_##this].rx > results[ct_##that].rx)  \
372        return ct_##this;                                \
373   }while(0)
374
375   case ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word:
376     /* Start of word.  Prefer Word match; failing that, take the longest */
377     if (results[ct_Word].match) return ct_Word;
378     RETURN_IF_LONGER(Lower,Upper);
379     RETURN_IF_LONGER(Upper,Lower);
380     break;
381
382   case ctf_Digit | ctf_Upper | ctf_Lower:
383     /* Mid-word.  Prefer longer match; failing that, match lower. */
384     RETURN_IF_LONGER(Upper,Lower);
385     return ct_Lower;
386   }
387
388   /* oh well */
389   return -1;
390 }
391
392 const struct OcrCellTypeInfo ocr_celltype_number= {
393   ctf_Digit, ctf_Digit, ctf_Digit,
394   .space_spaces= 5,
395   .name= "number",
396   .findchar_select= 0
397 };
398 const struct OcrCellTypeInfo ocr_celltype_text= {
399   .initial=  ctf_Digit | ctf_Upper,
400   .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
401   .midword=  ctf_Digit | ctf_Upper | ctf_Lower,
402   .space_spaces= 4,
403   .name= "text",
404   .findchar_select= findchar_select_text
405 };
406
407
408 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
409
410 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w,
411                     const Pixcol cols[]) {
412   int nspaces;
413   int x;
414
415   FindCharArgs fca;
416   fca.rd= rd;
417   fca.ct= ct;
418   fca.w= w;
419   fca.cols= cols;
420   fca.x= -1;
421
422  restart:
423
424   nspaces=- w;
425   fca.ctxmap= ct->initial;
426   rd->nresults=0;
427   debugf("OCR h=%d w=%d",rd->h,w);
428   for (x=0; x<w; x++) debugf(" "PIXCOL_PRFMT, PIXCOL_PRVAL(cols[x]));
429   debugf("\n");
430   debug_flush();
431
432   x=0;
433   for (;;) {
434     debug_flush();
435     /* skip spaces */
436     if (x>=w)
437       break;
438
439     if (!pixcol_nonzero(&cols[x])) {
440       nspaces++;
441       x++;
442       if (nspaces == ct->space_spaces) {
443         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
444         fca.ctxmap= ct->nextword;
445       }
446       continue;
447     }
448
449     /* something here, so we need to add the spaces */
450     if (nspaces >= ct->space_spaces)
451       add_result(rd," ",x-nspaces,x+1,-1,0);
452     nspaces=0;
453
454     fca.x= x;
455
456     int match_rx=-1;
457     int match_ctxi=-1;
458     DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
459     
460     if (match) {
461       debugf(" || YES");
462       add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
463       x= match_rx+1;
464       if (match->match) fca.ctxmap= ct->midword;
465       else debugf(" (empty)");
466       if (match->endsword) {
467         nspaces= ct->space_spaces;
468         debugf("_");
469         fca.ctxmap= ct->nextword;
470       }
471       debugf("\n");
472     } else {
473       int rx;
474       debugf(" || UNKNOWN");
475       for (rx=x; rx<w && pixcol_nonzero(&cols[rx]); rx++);
476       debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
477       debug_flush();
478       callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
479       goto restart;
480     }
481
482   }
483   add_result(rd, 0,-1,-1,-1,0);
484   debugf("OCR  finished %d glyphs\n",rd->nresults);
485   debug_flush();
486   return rd->results;
487 }
488
489 OcrReader *ocr_init(int h) {
490   OcrReader *rd;
491
492   assert(h <= OCR_MAX_H);
493
494   if (o_flags & ff_dict_fetch) {
495     char *fetchfile= masprintf("char%d",h);
496     progress("Updating %s...",fetchfile);
497     fetch_with_rsync(fetchfile);
498     free(fetchfile);
499   }
500
501   rd= mmalloc(sizeof(*rd));
502   memset(rd,0,sizeof(*rd));
503   rd->h= h;
504   readdb(rd);
505   return rd;
506 }
507
508 /*---------- character set dump ----------*/
509
510 static void show_recurse(const DatabaseNode *t, int *count,
511                          const DatabaseNode **store_ary) {
512   if (t->defined) {
513     if (store_ary) store_ary[*count]= t;
514     (*count)++;
515   }
516   int l;
517   for (l=0; l<t->nlinks; l++)
518     show_recurse(t->links[l].then, count,store_ary);
519 }
520
521 static int show_char_compar(const void *av, const void *bv) {
522   const DatabaseNode *const *ap= av;  const DatabaseNode *a= *ap;
523   const DatabaseNode *const *bp= bv;  const DatabaseNode *b= *bp;
524   return strcmp(a->str, b->str) ?:
525     ((int)a->match -    (int)b->match) ?:
526     ((int)a->endsword - (int)b->endsword) ?:
527     ((int)a->local -    (int)b->local) ?:
528     0;
529 }
530
531 void ocr_showcharsets(void) {
532   DIR *d;
533   struct dirent *de;
534   char found[OCR_MAX_H];
535   pcre *fnpat;
536   int matchvec[10];
537   char hbuf[10];
538   const char *pcre_err;
539   int pcre_erroffset;
540
541   memset(found,0,sizeof(found));
542   
543   fnpat= pcre_compile("\\#(?:master|local)\\-char([1-9]\\d{0,2})\\#\\.txt$",
544                       PCRE_ANCHORED|PCRE_DOLLAR_ENDONLY,
545                       &pcre_err,&pcre_erroffset, 0);
546   debugf("pcre_compile %p %s\n",fnpat,pcre_err);
547   assert(fnpat);
548
549   sysassert( d= opendir(get_vardir()) );
550   for (;;) {
551     errno=0; de= readdir(d);  if (!de) break;
552
553     int rer= pcre_exec(fnpat,0, de->d_name,strlen(de->d_name), 0,0,
554                        matchvec,ARRAYSIZE(matchvec));
555     debugf("pcre_exec `%s' => %d\n", de->d_name,rer);
556
557     if (rer==PCRE_ERROR_NOMATCH || rer==PCRE_ERROR_BADUTF8) continue;
558     assert(rer==2);
559
560     rer= pcre_copy_substring(de->d_name,matchvec,rer, 1, hbuf,sizeof(hbuf));
561     debugf("pcre_copy_substring => %d\n", rer);
562     assert(rer>0);
563
564     int h= atoi(hbuf);
565     if (h >= ARRAYSIZE(found)) continue;
566     
567     found[h]= 1;
568   }
569
570   int h;
571   for (h=0; h<ARRAYSIZE(found); h++) {
572     if (!found[h]) continue;
573
574     OcrReader *rd= ocr_init(h); /* we leak this but never mind */
575     progress("");
576
577     int ctxi;
578     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
579       int nchars= 0;
580       show_recurse(&rd->contexts[ctxi], &nchars, 0);
581       const DatabaseNode **chars= mmalloc(sizeof(*chars) * nchars);
582       int chari= 0;
583       show_recurse(&rd->contexts[ctxi], &chari, chars);
584       assert(chari==nchars);
585       qsort(chars, nchars, sizeof(*chars), show_char_compar);
586
587       int local;
588       for (local=0; local<2; local++) {
589         printf("%2d %-6s %-6s ", h, context_names[ctxi],
590                local?"local":"master");
591         for (chari=0; chari<nchars; chari++) {
592           const DatabaseNode *t= chars[chari];
593           static const char accept[]=
594             "abcdefghijklmnopqrstuvwxyz"
595             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
596             "0123456789" "'!&-+.,>";
597
598           if (t->local != local) continue;
599
600           if (!t->match)
601             printf(" [nomatch]");
602           else if (!t->endsword && strspn(t->str, accept) == strlen(t->str))
603             printf(" %s",t->str);
604           else {
605             printf(" \"");
606             char *p= t->str;
607             int c;
608             while ((c=*p++)) {
609               if (c=='"' || c=='\\') printf("\\%c",c);
610               else if (c>=' ' && c<=126) putchar(c);
611               else printf("\\x%02x", (unsigned char)c);
612             }
613             if (t->endsword) putchar(' ');
614             putchar('"');
615           }
616         }
617         putchar('\n');
618       }
619       free(chars);
620     }
621   }
622 }