chiark / gitweb /
47597828c5f0091f1b5dce2e1592bb2e82aa4da6
[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, 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   if (local)
130     o_flags |= ff_charset_havelocal;
131
132   FGETSLINE;
133   dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v2"));
134
135   dbassert( dbfile_scanf("%d", &h) == 1);
136   dbassert(h==rd->h);
137
138   for (;;) {
139     FGETSLINE;
140     if (!lbuf[0] || lbuf[0]=='#') continue;
141     if (!strcmp(lbuf,".")) break;
142
143     for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
144       if (!strcmp(lbuf,context_names[ctxi]))
145         goto found_ctx;
146     /* not found, just skip */
147     for (;;) { FGETSLINE; if (!lbuf[0]) break; }
148     continue;
149
150   found_ctx:
151     for (nchrs=0;;) {
152       int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
153       if (c=='\n') break; /* forces no match */
154       dbassert(nchrs<sizeof(chrs));
155       chrs[nchrs++]= c;
156     }
157     endsword= 0;
158     if (nchrs>0 && chrs[nchrs-1]==' ') {
159       endsword= 1;
160       nchrs--;
161     }
162
163     current= &rd->contexts[ctxi];
164     for (;;) {
165       FGETSLINE;
166       if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
167       dbassert( strlen(lbuf) == rd->h );
168       FILLZERO(cv);
169       int y;
170       for (y=0; y<h; y++) {
171         char pb[2];
172         pb[0]= lbuf[y];
173         pb[1]= 0;
174         char *ep;
175         unsigned pv= strtoul(pb,&ep,16);  dbassert(!*ep);
176         pixcol_p_add(&cv, y, pv);
177       }
178       
179       for (j=0; j<current->nlinks; j++)
180         if (!pixcol_cmp(&cv, &current->links[j].col)) {
181           current= current->links[j].then;
182           goto found_link;
183         }
184
185       additional= mmalloc(sizeof(*additional));
186       additional->str= 0;
187       additional->defined= 0;
188       additional->match= 0;
189       additional->endsword= 0;
190       additional->nlinks= additional->alinks= 0;
191       additional->links= 0;
192       if (current->nlinks==current->alinks) {
193         current->alinks++;
194         current->alinks<<=1;
195         current->links= mrealloc(current->links,
196                                  sizeof(*current->links) * current->alinks);
197       }
198       current->links[current->nlinks].col= cv;
199       current->links[current->nlinks].then= additional;
200       current->nlinks++;
201       current= additional;
202
203     found_link:;
204     }
205
206     if (!current->defined) {
207       free(current->str);
208       current->str= 0;
209       current->defined= 1;
210       current->match= 0;
211       current->local= local;
212
213       if (nchrs) {
214         current->str= mmalloc(nchrs+1);
215         memcpy(current->str, chrs, nchrs);
216         current->str[nchrs]= 0;
217         current->match= 1;
218         current->endsword= endsword;
219       }
220     }
221   }
222  x:
223   dbfile_close();
224   free(dbfname);
225 }
226
227 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
228   fprintf(resolver,"{");
229   const char *spc="";
230   int ctxi;
231   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
232     if (!(ctxmap & (1u << ctxi))) continue;
233     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
234     spc=" ";
235   }
236   fprintf(resolver,"}");
237 }
238
239 static void callout_unknown(OcrReader *rd, int w, const Pixcol cols[],
240                             int unk_l, int unk_r, unsigned unk_ctxmap) {
241   int c,i, x,y;
242   const OcrResultGlyph *s;
243   const char *p;
244
245   FILE *resolver= resolve_start();
246   if (!resolver || !(o_flags & ff_editcharset))
247     fatal("OCR failed - unrecognised characters or ligatures.\n"
248           "Character set database needs to be updated or augmented.\n"
249           "See README.charset.\n");
250   
251   fprintf(resolver,
252           "char\n"
253           "%d %d ",unk_l,unk_r);
254   cu_pr_ctxmap(resolver,unk_ctxmap);
255   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
256     if (!strcmp(s->s," ")) continue;
257     fprintf(resolver," %d %d ",s->l,s->r);
258     cu_pr_ctxmap(resolver, 1u << s->match);
259     fprintf(resolver," ");
260     cu_pr_ctxmap(resolver, s->ctxmap);
261     fprintf(resolver," ");
262     for (p=s->s; (c= *p); p++) {
263       if (c=='\\') fprintf(resolver,"\\%c",c);
264       else if (c>=33 && c<=126) fputc(c,resolver);
265       else fprintf(resolver,"\\x%02x",(unsigned char)c);
266     }
267   }
268   fputc('\n',resolver);
269
270   fprintf(resolver,
271           "P2\n%d %d %d\n", w, rd->h, AAMAXVAL);
272   for (y=0; y<rd->h; y++) {
273     for (x=0; x<w; x++)
274       fprintf(resolver, " %d", pixcol_p_get(&cols[x], y));
275     fputc('\n',resolver);
276   }
277
278   resolve_finish();
279   readdb(rd);
280 }
281
282 static void add_result(OcrReader *rd, const char *s, int l, int r,
283                        int match, unsigned ctxmap) {
284   if (rd->nresults >= rd->aresults) {
285     rd->aresults++; rd->aresults<<=1;
286     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
287   }
288   rd->results[rd->nresults].s= s;
289   rd->results[rd->nresults].l= l;
290   rd->results[rd->nresults].r= r;
291   rd->results[rd->nresults].match= match;
292   rd->results[rd->nresults].ctxmap= ctxmap;
293   rd->nresults++;
294 }
295
296
297 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
298                                    DatabaseNode *start, int *matchx_r) {
299   DatabaseNode *current= start;
300   DatabaseNode *bestmatch= 0;
301   int i;
302   int x= fca->x;
303
304   for (;;) {
305     debug_flush();
306     debugf(" | x=%d",x);
307     if (x > fca->w) break;
308     Pixcol cv= fca->cols[x];
309     debugf(" cv="PIXCOL_PRFMT, PIXCOL_PRVAL(cv));
310     for (i=0; i<current->nlinks; i++)
311       if (!pixcol_cmp(&cv, &current->links[i].col))
312         goto found;
313     /* not found */
314     debugf(" ?");
315     break;
316
317   found:
318     current= current->links[i].then;
319     if (current->match) {
320       debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
321       bestmatch= current;
322       *matchx_r= x;
323     } else {
324       debugf(" ...");
325     }
326
327     x++;
328   }
329   return bestmatch;
330 }  
331
332 static DatabaseNode *findchar(const FindCharArgs *fca,
333                               int *match_rx, int *match_rctxi) {
334   FindCharResults results[NCONTEXTS];
335   int ctxi, match=-1, nmatches=0;
336
337   debugf("OCR  lx=%d ct_state=%x  ", fca->x, fca->ctxmap);
338   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
339     results[ctxi].match= 0;
340     if (!(fca->ctxmap & (1u << ctxi))) continue;
341     debugf(" || %s",context_names[ctxi]);
342
343     results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
344                                        &results[ctxi].rx);
345     if (!results[ctxi].match) continue;
346
347     match= ctxi;
348     nmatches++;
349   }
350   if (nmatches==1) {
351     debugf(" unique");
352   } else {
353     debugf(" ambiguous");
354     match= !fca->ct->findchar_select ? -1 :
355       fca->ct->findchar_select(fca,results);
356     debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
357   }
358   if (match<0)
359     return 0;
360   
361   *match_rx= results[match].rx;
362   if (match_rctxi) *match_rctxi= match;
363   return results[match].match;
364 }
365
366 static int findchar_select_text(const FindCharArgs *fca,
367                                 const FindCharResults results[]) {
368   
369   dbassert(! results[ct_Digit].match ); /* digits are supposedly unambiguous */
370
371   switch (fca->ctxmap) {
372
373 #define RETURN_IF_LONGER(this,that) do{                 \
374     if (results[ct_##this].rx > results[ct_##that].rx)  \
375        return ct_##this;                                \
376   }while(0)
377
378   case ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word:
379     /* Start of word.  Prefer Word match; failing that, take the longest */
380     if (results[ct_Word].match) return ct_Word;
381     RETURN_IF_LONGER(Lower,Upper);
382     RETURN_IF_LONGER(Upper,Lower);
383     break;
384
385   case ctf_Digit | ctf_Upper | ctf_Lower:
386     /* Mid-word.  Prefer longer match; failing that, match lower. */
387     RETURN_IF_LONGER(Upper,Lower);
388     return ct_Lower;
389   }
390
391   /* oh well */
392   return -1;
393 }
394
395 const struct OcrCellTypeInfo ocr_celltype_number= {
396   ctf_Digit, ctf_Digit, ctf_Digit,
397   .space_spaces= 5,
398   .name= "number",
399   .findchar_select= 0
400 };
401 const struct OcrCellTypeInfo ocr_celltype_text= {
402   .initial=  ctf_Digit | ctf_Upper,
403   .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
404   .midword=  ctf_Digit | ctf_Upper | ctf_Lower,
405   .space_spaces= 4,
406   .name= "text",
407   .findchar_select= findchar_select_text
408 };
409
410
411 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
412
413 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w,
414                     const Pixcol cols[]) {
415   int nspaces;
416   int x;
417
418   FindCharArgs fca;
419   fca.rd= rd;
420   fca.ct= ct;
421   fca.w= w;
422   fca.cols= cols;
423   fca.x= -1;
424
425  restart:
426
427   nspaces=- w;
428   fca.ctxmap= ct->initial;
429   rd->nresults=0;
430   debugf("OCR h=%d w=%d",rd->h,w);
431   for (x=0; x<w; x++) debugf(" "PIXCOL_PRFMT, PIXCOL_PRVAL(cols[x]));
432   debugf("\n");
433   debug_flush();
434
435   x=0;
436   for (;;) {
437     debug_flush();
438     /* skip spaces */
439     if (x>=w)
440       break;
441
442     if (!pixcol_nonzero(&cols[x])) {
443       nspaces++;
444       x++;
445       if (nspaces == ct->space_spaces) {
446         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
447         fca.ctxmap= ct->nextword;
448       }
449       continue;
450     }
451
452     /* something here, so we need to add the spaces */
453     if (nspaces >= ct->space_spaces)
454       add_result(rd," ",x-nspaces,x+1,-1,0);
455     nspaces=0;
456
457     fca.x= x;
458
459     int match_rx=-1;
460     int match_ctxi=-1;
461     DatabaseNode *match= findchar(&fca, &match_rx, &match_ctxi);
462     
463     if (match) {
464       debugf(" || YES");
465       add_result(rd, match->str, x, match_rx, match_ctxi, fca.ctxmap);
466       x= match_rx+1;
467       if (match->match) fca.ctxmap= ct->midword;
468       else debugf(" (empty)");
469       if (match->endsword) {
470         nspaces= ct->space_spaces;
471         debugf("_");
472         fca.ctxmap= ct->nextword;
473       }
474       debugf("\n");
475     } else {
476       int rx;
477       debugf(" || UNKNOWN");
478       for (rx=x; rx<w && pixcol_nonzero(&cols[rx]); rx++);
479       debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
480       debug_flush();
481       callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
482       goto restart;
483     }
484
485   }
486   add_result(rd, 0,-1,-1,-1,0);
487   debugf("OCR  finished %d glyphs\n",rd->nresults);
488   debug_flush();
489   return rd->results;
490 }
491
492 OcrReader *ocr_init(int h) {
493   OcrReader *rd;
494
495   assert(h <= OCR_MAX_H);
496
497   if (o_flags & ff_dict_fetch) {
498     char *fetchfile= masprintf("char%d",h);
499     progress("Updating %s...",fetchfile);
500     fetch_with_rsync(fetchfile);
501     free(fetchfile);
502   }
503
504   rd= mmalloc(sizeof(*rd));
505   memset(rd,0,sizeof(*rd));
506   rd->h= h;
507   readdb(rd);
508   return rd;
509 }
510
511 /*---------- character set dump ----------*/
512
513 static void show_recurse(const DatabaseNode *t, int *count,
514                          const DatabaseNode **store_ary) {
515   if (t->defined) {
516     if (store_ary) store_ary[*count]= t;
517     (*count)++;
518   }
519   int l;
520   for (l=0; l<t->nlinks; l++)
521     show_recurse(t->links[l].then, count,store_ary);
522 }
523
524 static int show_char_compar(const void *av, const void *bv) {
525   const DatabaseNode *const *ap= av;  const DatabaseNode *a= *ap;
526   const DatabaseNode *const *bp= bv;  const DatabaseNode *b= *bp;
527   return strcmp(a->str, b->str) ?:
528     ((int)a->match -    (int)b->match) ?:
529     ((int)a->endsword - (int)b->endsword) ?:
530     ((int)a->local -    (int)b->local) ?:
531     0;
532 }
533
534 void ocr_showcharsets(void) {
535   DIR *d;
536   struct dirent *de;
537   char found[OCR_MAX_H];
538   pcre *fnpat;
539   int matchvec[10];
540   char hbuf[10];
541   const char *pcre_err;
542   int pcre_erroffset;
543
544   memset(found,0,sizeof(found));
545   
546   fnpat= pcre_compile("\\#(?:master|local)\\-char([1-9]\\d{0,2})\\#\\.txt$",
547                       PCRE_ANCHORED|PCRE_DOLLAR_ENDONLY,
548                       &pcre_err,&pcre_erroffset, 0);
549   debugf("pcre_compile %p %s\n",fnpat,pcre_err);
550   assert(fnpat);
551
552   sysassert( d= opendir(get_vardir()) );
553   for (;;) {
554     errno=0; de= readdir(d);  if (!de) break;
555
556     int rer= pcre_exec(fnpat,0, de->d_name,strlen(de->d_name), 0,0,
557                        matchvec,ARRAYSIZE(matchvec));
558     debugf("pcre_exec `%s' => %d\n", de->d_name,rer);
559
560     if (rer==PCRE_ERROR_NOMATCH || rer==PCRE_ERROR_BADUTF8) continue;
561     assert(rer==2);
562
563     rer= pcre_copy_substring(de->d_name,matchvec,rer, 1, hbuf,sizeof(hbuf));
564     debugf("pcre_copy_substring => %d\n", rer);
565     assert(rer>0);
566
567     int h= atoi(hbuf);
568     if (h >= ARRAYSIZE(found)) continue;
569     
570     found[h]= 1;
571   }
572
573   int h;
574   for (h=0; h<ARRAYSIZE(found); h++) {
575     if (!found[h]) continue;
576
577     OcrReader *rd= ocr_init(h); /* we leak this but never mind */
578     progress("");
579
580     int ctxi;
581     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
582       int nchars= 0;
583       show_recurse(&rd->contexts[ctxi], &nchars, 0);
584       const DatabaseNode **chars= mmalloc(sizeof(*chars) * nchars);
585       int chari= 0;
586       show_recurse(&rd->contexts[ctxi], &chari, chars);
587       assert(chari==nchars);
588       qsort(chars, nchars, sizeof(*chars), show_char_compar);
589
590       int local;
591       for (local=0; local<2; local++) {
592         printf("%2d %-6s %-6s ", h, context_names[ctxi],
593                local?"local":"master");
594         for (chari=0; chari<nchars; chari++) {
595           const DatabaseNode *t= chars[chari];
596           static const char accept[]=
597             "abcdefghijklmnopqrstuvwxyz"
598             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
599             "0123456789" "'!&-+.,>";
600
601           if (t->local != local) continue;
602
603           if (!t->match)
604             printf(" [nomatch]");
605           else if (!t->endsword && strspn(t->str, accept) == strlen(t->str))
606             printf(" %s",t->str);
607           else {
608             printf(" \"");
609             char *p= t->str;
610             int c;
611             while ((c=*p++)) {
612               if (c=='"' || c=='\\') printf("\\%c",c);
613               else if (c>=' ' && c<=126) putchar(c);
614               else printf("\\x%02x", (unsigned char)c);
615             }
616             if (t->endsword) putchar(' ');
617             putchar('"');
618           }
619         }
620         putchar('\n');
621       }
622       free(chars);
623     }
624   }
625 }