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