chiark / gitweb /
Much faster
[ypp-sc-tools.db-test.git] / pctb / ocr.c
1 /*
2   */
3
4 #include "ocr.h"
5
6 typedef struct {
7   Pixcol col;
8   struct DatabaseNode *then;
9 } DatabaseLink;
10
11 #define MAXGLYPHCHRS 3
12
13 typedef struct DatabaseNode {
14   char s[MAXGLYPHCHRS+1]; /* null-terminated; "" means no match here */
15   int nlinks, alinks;
16   DatabaseLink *links;
17 } DatabaseNode;
18
19 static const char *context_names[]= {
20   "Lower",
21   "Upper",
22   "Digit"
23 };
24
25 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
26
27 #define SPACE_SPACES 3
28
29 struct OcrReader {
30   int h;
31   DatabaseNode contexts[NCONTEXTS];
32   OcrResultGlyph *results;
33   int aresults, nresults;
34 };
35
36 static FILE *resolver;
37 static pid_t resolver_pid;
38 static int resolver_done;
39
40 static void fgetsline(FILE *f, char *lbuf, size_t lbufsz) {
41   char *s= fgets(lbuf,lbufsz,f);
42   eassert(s);
43   int l= strlen(lbuf);
44   eassert(l>0);  eassert(lbuf[--l]='\n');
45   lbuf[l]= 0;
46 }
47 #define FGETSLINE(f,buf) (fgetsline(f,buf,sizeof(buf)))
48
49 static void cleardb_node(DatabaseNode *n) {
50   int i;
51   n->s[0]= 0;
52   for (i=0; i<n->nlinks; i++)
53     cleardb_node(n->links[i].then);
54 }
55
56 static void readdb(OcrReader *rd) {
57   int nchrs;
58   DatabaseNode *current, *additional;
59   char chrs[MAXGLYPHCHRS+1];
60   Pixcol cv;
61   int r,j,ctxi;
62   int h;
63   char lbuf[100];
64   FILE *db;
65
66   for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
67     cleardb_node(&rd->contexts[ctxi]);
68
69   char *dbfname=0;
70   asprintf(&dbfname,"%s/charset-%d.txt",get_vardir(),rd->h);
71   eassert(dbfname);
72   
73   db= fopen(dbfname,"r");
74   free(dbfname);
75   if (!db) {
76     eassert(errno==ENOENT);
77     return;
78   }
79
80   FGETSLINE(db,lbuf);
81   eassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
82
83   r= fscanf(db, "%d", &h);
84   eassert(r==1);
85   eassert(h==rd->h);
86
87   for (;;) {
88     FGETSLINE(db,lbuf);
89     if (!lbuf || lbuf[0]=='#') continue;
90     if (!strcmp(lbuf,".")) break;
91
92     for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
93       if (!strcmp(lbuf,context_names[ctxi]))
94         goto found_ctx;
95     /* not found, just skip */
96     for (;;) { FGETSLINE(db,lbuf); if (!lbuf[0]) break; }
97     continue;
98
99   found_ctx:
100     for (nchrs=0;;) {
101       int c= fgetc(db);  eassert(c!=EOF);
102       if (c=='\n') { eassert(nchrs); break; }
103       eassert(nchrs<MAXGLYPHCHRS);
104       if (c=='\\') {
105         unsigned cr;
106         c= fgetc(db);  eassert(c=='x');
107         r= fscanf(db, "%2x", &cr);  eassert(r==1);
108         assert(cr>0 && cr<=255);
109         c= cr;
110       }
111       chrs[nchrs++]= c;
112     }
113     chrs[nchrs]= 0;
114
115     current= &rd->contexts[ctxi];
116     for (;;) {
117       FGETSLINE(db,lbuf);
118       if (!lbuf[0]) { eassert(current != &rd->contexts[ctxi]); break; }
119       char *ep;
120       cv= strtoul(lbuf,&ep,16);  eassert(!*ep);
121       eassert(!(cv & ~((1UL << rd->h)-1)));
122       
123       for (j=0; j<current->nlinks; j++)
124         if (current->links[j].col == cv) {
125           current= current->links[j].then;
126           goto found_link;
127         }
128
129       additional= malloc(sizeof(*additional)); eassert(additional);
130       additional->s[0]= 0;
131       additional->nlinks= additional->alinks= 0;
132       additional->links= 0;
133       if (current->nlinks==current->alinks) {
134         current->alinks++;
135         current->alinks<<=1;
136         current->links= realloc(current->links,
137                                 sizeof(*current->links) * current->alinks);
138         eassert(current->links);
139       }
140       current->links[current->nlinks].col= cv;
141       current->links[current->nlinks].then= additional;
142       current->nlinks++;
143       current= additional;
144
145     found_link:;
146     }
147
148     eassert(!current->s[0]);
149     strcpy(current->s, chrs);
150   }
151   eassert(!ferror(db));
152   eassert(!fclose(db));
153 }
154
155 static void cu_pr_ctxmap(unsigned ctxmap) {
156   fprintf(resolver,"{");
157   const char *spc="";
158   int ctxi;
159   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
160     if (!(ctxmap & (1u << ctxi))) continue;
161     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
162     spc=" ";
163   }
164   fprintf(resolver,"}");
165 }
166
167 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
168                             int unk_l, int unk_r, unsigned unk_ctxmap) {
169   int jobpipe[2],donepipe[2], c, r,i, x,y;
170   const OcrResultGlyph *s;
171   const char *p;
172   char cb;
173   Pixcol pv;
174   
175   if (!resolver) {
176     r= pipe(jobpipe);  eassert(!r);
177     r= pipe(donepipe);  eassert(!r);
178     resolver_pid= fork();
179     eassert(resolver_pid!=-1);
180     if (!resolver_pid) {
181       r= dup2(jobpipe[0],0); eassert(r==0);
182       r= close(jobpipe[1]); eassert(!r);
183       r= close(donepipe[0]); eassert(!r);
184       /* we know donepipe[1] is >= 4 and we have dealt with all the others
185        * so we aren't in any danger of overwriting some other fd 4: */
186       r= dup2(donepipe[1],4); eassert(r==4);
187       execlp("./show-thing.tcl", "./show-thing.tcl",
188              "--automatic","1",(char*)0);
189       eassert(!"execlp failed");
190     }
191     r= close(jobpipe[0]); eassert(!r);
192     r= close(donepipe[1]); eassert(!r);
193     resolver= fdopen(jobpipe[1],"w"); eassert(resolver);
194     resolver_done= donepipe[0];
195   }
196   fprintf(resolver,"%d %d ",unk_l,unk_r);
197   cu_pr_ctxmap(unk_ctxmap);
198   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
199     if (!strcmp(s->s," ")) continue;
200     fprintf(resolver," %d %d ",s->l,s->r);
201     cu_pr_ctxmap(s->ctxmap);
202     fprintf(resolver," ");
203     for (p=s->s; (c= *p); p++) {
204       if (c=='\\') fprintf(resolver,"\\%c",c);
205       else if (c>=33 && c<=126) fputc(c,resolver);
206       else fprintf(resolver,"\\x%02x",(unsigned char)c);
207     }
208   }
209   fputc('\n',resolver);
210
211   fprintf(resolver,
212           "/* XPM */\n"
213           "static char *t[] = {\n"
214           "/* columns rows colors chars-per-pixel */\n"
215           "\"%d %d 2 1\",\n"
216           "\"  c black\",\n"
217           "\"o c white\",\n",
218           w,rd->h);
219   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
220     fputc('"',resolver);
221     for (x=0; x<w; x++)
222       fputc(cols[x] & pv ? 'o' : ' ', resolver);
223     fputs("\",\n",resolver);
224   }
225   fputs("};\n",resolver);
226   eassert(!ferror(resolver));
227   eassert(!fflush(resolver));
228
229   eassert(resolver);
230
231   for (;;) {
232     r= read(resolver_done,&cb,1);
233     if (r==-1) { eassert(errno==EINTR); continue; }
234     break;
235   }
236
237   if (r==0) {
238     pid_t pid;
239     for (;;) {
240       pid= waitpid(resolver_pid, &r, 0);
241       if (pid==-1) { eassert(errno==EINTR); continue; }
242       break;
243     }
244     eassert(pid==resolver_pid);
245     if (WIFEXITED(r)) {
246       eassert(!WEXITSTATUS(r));
247       fclose(resolver);
248       close(resolver_done);
249       resolver= 0;
250     } else if (WIFSIGNALED(r)) {
251       eassert(!"resolver child died due to signal");
252     } else {
253       eassert(!"weird wait status");
254     }
255   } else {
256     eassert(r==1);
257     eassert(cb==0);
258   }
259
260   readdb(rd);
261 }
262
263 static void add_result(OcrReader *rd, const char *s, int l, int r,
264                        unsigned ctxmap) {
265   if (rd->nresults >= rd->aresults) {
266     rd->aresults++; rd->aresults<<=1;
267     rd->results= realloc(rd->results,sizeof(*rd->results)*rd->aresults);
268     eassert(rd->results);
269   }
270   rd->results[rd->nresults].s= s;
271   rd->results[rd->nresults].l= l;
272   rd->results[rd->nresults].r= r;
273   rd->results[rd->nresults].ctxmap= ctxmap;
274   rd->nresults++;
275 }
276
277 struct OcrCellTypeInfo {
278   unsigned initial, nextword, midword;
279 };
280 const struct OcrCellTypeInfo ocr_celltype_number= {
281   4,4,4
282 };
283 const struct OcrCellTypeInfo ocr_celltype_text= {
284   .initial=2 /* Uppercase */,
285   .nextword=3 /* Either */,
286   .midword=1 /* Lower only */
287 };
288
289 static void vdebugf(const char *fmt, va_list al) {
290 #ifdef DEBUG_OCR
291   vfprintf(debug,fmt,al);
292 #endif
293 }
294 static void debugf(const char *fmt, ...) {
295   va_list al;  va_start(al,fmt);  vdebugf(fmt,al);  va_end(al);
296 }
297
298 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
299   int nspaces;
300   unsigned ctxmap;
301   int ctxi, i, x;
302
303  restart:
304
305   nspaces=- w;
306   ctxmap= ct->initial;
307   rd->nresults=0;
308   debugf("OCR h=%d w=%d",rd->h,w);
309   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
310   debugf("\n");
311   debug_flush();
312
313   x=0;
314   for (;;) {
315     debug_flush();
316     /* skip spaces */
317     if (x>=w)
318       break;
319
320     if (!cols[x]) {
321       nspaces++;
322       x++;
323       if (nspaces==SPACE_SPACES) {
324         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
325         ctxmap= ct->nextword;
326       }
327       continue;
328     }
329
330     /* something here, so we need to add the spaces */
331     if (nspaces>=SPACE_SPACES)
332       add_result(rd," ",x-nspaces,x+1,0);
333     nspaces=0;
334
335     /* find character */
336     int lx=x;
337
338     DatabaseNode *uniquematch= 0;
339     int uniquematch_rx=-1;
340     
341     debugf("OCR  lx=%d ctxmap=%x  ",lx,ctxmap);
342
343     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
344       DatabaseNode *current= &rd->contexts[ctxi];;
345       DatabaseNode *bestmatch= 0;
346       int bestmatch_rx=-1;
347
348       x= lx;
349       if (!(ctxmap & (1u << ctxi))) continue;
350       debugf(" || %s",context_names[ctxi]);
351
352       for (;;) {
353         debug_flush();
354         debugf(" | x=%d",x);
355         if (x>w) break;
356         Pixcol cv= cols[x];
357         debugf(" cv=%"PSPIXCOL(PRIx),cv);
358         for (i=0; i<current->nlinks; i++)
359           if (current->links[i].col == cv)
360             goto found;
361         /* not found */
362         debugf(" ?");
363         break;
364
365       found:
366         current= current->links[i].then;
367         if (current->s[0]) {
368           debugf(" \"%s\"",current->s);
369           bestmatch= current;
370           bestmatch_rx= x;
371         } else {
372           debugf(" ...");
373         }
374
375         x++;
376       }
377       
378       if (bestmatch) {
379         if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
380           debugf( " ambiguous");
381           uniquematch= 0;
382           break;
383         }
384         uniquematch= bestmatch;
385         uniquematch_rx= bestmatch_rx;
386       }
387     }
388
389     if (uniquematch) {
390       debugf(" || YES\n");
391       add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
392       x= uniquematch_rx+1;
393       ctxmap= ct->midword;
394     } else {
395       int rx;
396       debugf(" || UNKNOWN");
397       for (rx=lx; rx<w && cols[rx]; rx++);
398       debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
399       debug_flush();
400       callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
401       goto restart;
402     }
403   }
404   add_result(rd, 0,-1,-1,0);
405   debugf("OCR  finished %d glyphs\n",rd->nresults);
406   debug_flush();
407   return rd->results;
408 }
409
410 OcrReader *ocr_init(int h) {
411   OcrReader *rd;
412
413   rd= malloc(sizeof(*rd));  eassert(rd);
414   memset(rd,0,sizeof(*rd));
415   rd->h= h;
416   readdb(rd);
417   return rd;
418 }