chiark / gitweb /
6482b81430292af3a7c4da942088ce0e0ce00ace
[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   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 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       current->local= local;
201
202       if (nchrs) {
203         current->str= mmalloc(nchrs+1);
204         memcpy(current->str, chrs, nchrs);
205         current->str[nchrs]= 0;
206         current->match= 1;
207         current->endsword= endsword;
208       }
209     }
210   }
211  x:
212   dbfile_close();
213   free(dbfname);
214 }
215
216 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
217   fprintf(resolver,"{");
218   const char *spc="";
219   int ctxi;
220   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
221     if (!(ctxmap & (1u << ctxi))) continue;
222     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
223     spc=" ";
224   }
225   fprintf(resolver,"}");
226 }
227
228 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
229                             int unk_l, int unk_r, unsigned unk_ctxmap) {
230   int c,i, x,y;
231   const OcrResultGlyph *s;
232   const char *p;
233   Pixcol pv;
234
235   FILE *resolver= resolve_start();
236   if (!resolver || !(o_flags & ff_editcharset))
237     fatal("OCR failed - unrecognised characters or ligatures.\n"
238           "Character set database needs to be updated or augmented.\n"
239           "See README.charset.\n");
240   
241   fprintf(resolver,
242           "char\n"
243           "%d %d ",unk_l,unk_r);
244   cu_pr_ctxmap(resolver,unk_ctxmap);
245   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
246     if (!strcmp(s->s," ")) continue;
247     fprintf(resolver," %d %d ",s->l,s->r);
248     cu_pr_ctxmap(resolver, 1u << s->match);
249     fprintf(resolver," ");
250     cu_pr_ctxmap(resolver, s->ctxmap);
251     fprintf(resolver," ");
252     for (p=s->s; (c= *p); p++) {
253       if (c=='\\') fprintf(resolver,"\\%c",c);
254       else if (c>=33 && c<=126) fputc(c,resolver);
255       else fprintf(resolver,"\\x%02x",(unsigned char)c);
256     }
257   }
258   fputc('\n',resolver);
259
260   fprintf(resolver,
261           "/* XPM */\n"
262           "static char *t[] = {\n"
263           "/* columns rows colors chars-per-pixel */\n"
264           "\"%d %d 2 1\",\n"
265           "\"  c black\",\n"
266           "\"o c white\",\n",
267           w,rd->h);
268   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
269     fputc('"',resolver);
270     for (x=0; x<w; x++)
271       fputc(cols[x] & pv ? 'o' : ' ', resolver);
272     fputs("\",\n",resolver);
273   }
274   fputs("};\n",resolver);
275
276   resolve_finish();
277   readdb(rd);
278 }
279
280 static void add_result(OcrReader *rd, const char *s, int l, int r,
281                        int match, unsigned ctxmap) {
282   if (rd->nresults >= rd->aresults) {
283     rd->aresults++; rd->aresults<<=1;
284     rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
285   }
286   rd->results[rd->nresults].s= s;
287   rd->results[rd->nresults].l= l;
288   rd->results[rd->nresults].r= r;
289   rd->results[rd->nresults].match= match;
290   rd->results[rd->nresults].ctxmap= ctxmap;
291   rd->nresults++;
292 }
293
294
295 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
296                                    DatabaseNode *start, int *matchx_r) {
297   DatabaseNode *current= start;
298   DatabaseNode *bestmatch= 0;
299   int i;
300   int x= fca->x;
301
302   for (;;) {
303     debug_flush();
304     debugf(" | x=%d",x);
305     if (x > fca->w) break;
306     Pixcol cv= fca->cols[x];
307     debugf(" cv=%"PSPIXCOL(PRIx),cv);
308     for (i=0; i<current->nlinks; i++)
309       if (current->links[i].col == cv)
310         goto found;
311     /* not found */
312     debugf(" ?");
313     break;
314
315   found:
316     current= current->links[i].then;
317     if (current->match) {
318       debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
319       bestmatch= current;
320       *matchx_r= x;
321     } else {
322       debugf(" ...");
323     }
324
325     x++;
326   }
327   return bestmatch;
328 }  
329
330 static DatabaseNode *findchar(const FindCharArgs *fca,
331                               int *match_rx, int *match_rctxi) {
332   FindCharResults results[NCONTEXTS];
333   int ctxi, match=-1, nmatches=0;
334
335   debugf("OCR  lx=%d ct_state=%x  ", fca->x, fca->ctxmap);
336   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
337     results[ctxi].match= 0;
338     if (!(fca->ctxmap & (1u << ctxi))) continue;
339     debugf(" || %s",context_names[ctxi]);
340
341     results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
342                                        &results[ctxi].rx);
343     if (!results[ctxi].match) continue;
344
345     match= ctxi;
346     nmatches++;
347   }
348   if (nmatches==1) {
349     debugf(" unique");
350   } else {
351     debugf(" ambiguous");
352     match= !fca->ct->findchar_select ? -1 :
353       fca->ct->findchar_select(fca,results);
354     debugf(" resolved %s", match<0 ? "<none>" : context_names[match]);
355   }
356   if (match<0)
357     return 0;
358   
359   *match_rx= results[match].rx;
360   if (match_rctxi) *match_rctxi= match;
361   return results[match].match;
362 }
363
364 static int findchar_select_text(const FindCharArgs *fca,
365                                 const FindCharResults results[]) {
366   
367   dbassert(! results[ct_Digit].match ); /* digits are supposedly unambiguous */
368
369   switch (fca->ctxmap) {
370
371 #define RETURN_IF_LONGER(this,that) do{                 \
372     if (results[ct_##this].rx > results[ct_##that].rx)  \
373        return ct_##this;                                \
374   }while(0)
375
376   case ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word:
377     /* Start of word.  Prefer Word match; failing that, take the longest */
378     if (results[ct_Word].match) return ct_Word;
379     RETURN_IF_LONGER(Lower,Upper);
380     RETURN_IF_LONGER(Upper,Lower);
381     break;
382
383   case ctf_Digit | ctf_Upper | ctf_Lower:
384     /* Mid-word.  Prefer longer match; failing that, match lower. */
385     RETURN_IF_LONGER(Upper,Lower);
386     return ct_Lower;
387   }
388
389   /* oh well */
390   return -1;
391 }
392
393 const struct OcrCellTypeInfo ocr_celltype_number= {
394   ctf_Digit, ctf_Digit, ctf_Digit,
395   .space_spaces= 5,
396   .name= "number",
397   .findchar_select= 0
398 };
399 const struct OcrCellTypeInfo ocr_celltype_text= {
400   .initial=  ctf_Digit | ctf_Upper,
401   .nextword= ctf_Digit | ctf_Upper | ctf_Lower | ctf_Word,
402   .midword=  ctf_Digit | ctf_Upper | ctf_Lower,
403   .space_spaces= 4,
404   .name= "text",
405   .findchar_select= findchar_select_text
406 };
407
408
409 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
410
411 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, 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(" %"PSPIXCOL(PRIx),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 (!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 && 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   if (o_flags & ff_dict_fetch) {
493     char *fetchfile= masprintf("char%d",h);
494     progress("Updating %s...",fetchfile);
495     fetch_with_rsync(fetchfile);
496     free(fetchfile);
497   }
498
499   rd= mmalloc(sizeof(*rd));
500   memset(rd,0,sizeof(*rd));
501   rd->h= h;
502   readdb(rd);
503   return rd;
504 }
505
506 /*---------- character set dump ----------*/
507
508 static void show_recurse(const DatabaseNode *t, int *count,
509                          const DatabaseNode **store_ary) {
510   if (t->defined) {
511     if (store_ary) store_ary[*count]= t;
512     (*count)++;
513   }
514   int l;
515   for (l=0; l<t->nlinks; l++)
516     show_recurse(t->links[l].then, count,store_ary);
517 }
518
519 static int show_char_compar(const void *av, const void *bv) {
520   const DatabaseNode *const *ap= av;  const DatabaseNode *a= *ap;
521   const DatabaseNode *const *bp= bv;  const DatabaseNode *b= *bp;
522   return strcmp(a->str, b->str) ?:
523     ((int)a->match -    (int)b->match) ?:
524     ((int)a->endsword - (int)b->endsword) ?:
525     ((int)a->local -    (int)b->local) ?:
526     0;
527 }
528
529 void ocr_showcharsets(void) {
530   DIR *d;
531   struct dirent *de;
532   char found[32];
533   pcre *fnpat;
534   int matchvec[10];
535   char hbuf[10];
536   const char *pcre_err;
537   int pcre_erroffset;
538
539   memset(found,0,sizeof(found));
540   
541   fnpat= pcre_compile("\\#(?:master|local)\\-char([1-9]\\d{0,2})\\#\\.txt$",
542                       PCRE_ANCHORED|PCRE_DOLLAR_ENDONLY,
543                       &pcre_err,&pcre_erroffset, 0);
544   debugf("pcre_compile %p %s\n",fnpat,pcre_err);
545   assert(fnpat);
546
547   sysassert( d= opendir(get_vardir()) );
548   for (;;) {
549     errno=0; de= readdir(d);  if (!de) break;
550
551     int rer= pcre_exec(fnpat,0, de->d_name,strlen(de->d_name), 0,0,
552                        matchvec,ARRAYSIZE(matchvec));
553     debugf("pcre_exec `%s' => %d\n", de->d_name,rer);
554
555     if (rer==PCRE_ERROR_NOMATCH || rer==PCRE_ERROR_BADUTF8) continue;
556     assert(rer==2);
557
558     rer= pcre_copy_substring(de->d_name,matchvec,rer, 1, hbuf,sizeof(hbuf));
559     debugf("pcre_copy_substring => %d\n", rer);
560     assert(rer>0);
561
562     int h= atoi(hbuf);
563     if (h >= ARRAYSIZE(found)) continue;
564     
565     found[h]= 1;
566   }
567
568   int h;
569   for (h=0; h<ARRAYSIZE(found); h++) {
570     if (!found[h]) continue;
571
572     OcrReader *rd= ocr_init(h); /* we leak this but never mind */
573     progress("");
574
575     int ctxi;
576     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
577       int nchars= 0;
578       show_recurse(&rd->contexts[ctxi], &nchars, 0);
579       const DatabaseNode **chars= mmalloc(sizeof(*chars) * nchars);
580       int chari= 0;
581       show_recurse(&rd->contexts[ctxi], &chari, chars);
582       assert(chari==nchars);
583       qsort(chars, nchars, sizeof(*chars), show_char_compar);
584
585       int local;
586       for (local=0; local<2; local++) {
587         printf("%2d %-6s %-6s ", h, context_names[ctxi],
588                local?"local":"master");
589         for (chari=0; chari<nchars; chari++) {
590           const DatabaseNode *t= chars[chari];
591           static const char accept[]=
592             "abcdefghijklmnopqrstuvwxyz"
593             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
594             "0123456789" "'!&-+.,>";
595
596           if (t->local != local) continue;
597
598           if (!t->match)
599             printf(" [nomatch]");
600           else if (!t->endsword && strspn(t->str, accept) == strlen(t->str))
601             printf(" %s",t->str);
602           else {
603             printf(" \"");
604             char *p= t->str;
605             int c;
606             while ((c=*p++)) {
607               if (c=='"' || c=='\\') printf("\\%c",c);
608               else if (c>=' ' && c<=126) putchar(c);
609               else printf("\\x%02x", (unsigned char)c);
610             }
611             if (t->endsword) putchar(' ');
612             putchar('"');
613           }
614         }
615         putchar('\n');
616       }
617       free(chars);
618     }
619   }
620 }