chiark / gitweb /
bb9576769e10a1d633ed6ebb7786d75e3bfcf585
[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 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 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
290   int nspaces;
291   unsigned ctxmap;
292   int ctxi, i, x;
293
294  restart:
295
296   nspaces=- w;
297   ctxmap= ct->initial;
298   rd->nresults=0;
299   fprintf(debug,"OCR h=%d w=%d",rd->h,w);
300   for (x=0; x<w; x++) fprintf(debug," %"PSPIXCOL(PRIx),cols[x]);
301   fprintf(debug,"\n");
302   debug_flush();
303
304   x=0;
305   for (;;) {
306     debug_flush();
307     /* skip spaces */
308     if (x>=w)
309       break;
310
311     if (!cols[x]) {
312       nspaces++;
313       x++;
314       if (nspaces==SPACE_SPACES) {
315         fprintf(debug,"OCR  x=%x nspaces=%d space\n",x,nspaces);
316         ctxmap= ct->nextword;
317       }
318       continue;
319     }
320
321     /* something here, so we need to add the spaces */
322     if (nspaces>=SPACE_SPACES)
323       add_result(rd," ",x-nspaces,x+1,0);
324     nspaces=0;
325
326     /* find character */
327     int lx=x;
328
329     DatabaseNode *uniquematch= 0;
330     int uniquematch_rx=-1;
331     
332     fprintf(debug,"OCR  lx=%d ctxmap=%x  ",lx,ctxmap);
333
334     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
335       DatabaseNode *current= &rd->contexts[ctxi];;
336       DatabaseNode *bestmatch= 0;
337       int bestmatch_rx=-1;
338
339       x= lx;
340       if (!(ctxmap & (1u << ctxi))) continue;
341       fprintf(debug," || %s",context_names[ctxi]);
342
343       for (;;) {
344         debug_flush();
345         fprintf(debug," | x=%d",x);
346         if (x>w) break;
347         Pixcol cv= cols[x];
348         fprintf(debug," cv=%"PSPIXCOL(PRIx),cv);
349         for (i=0; i<current->nlinks; i++)
350           if (current->links[i].col == cv)
351             goto found;
352         /* not found */
353         fprintf(debug," ?");
354         break;
355
356       found:
357         current= current->links[i].then;
358         if (current->s[0]) {
359           fprintf(debug," \"%s\"",current->s);
360           bestmatch= current;
361           bestmatch_rx= x;
362         } else {
363           fprintf(debug," ...");
364         }
365
366         x++;
367       }
368       
369       if (bestmatch) {
370         if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
371           fprintf(debug, " ambiguous");
372           uniquematch= 0;
373           break;
374         }
375         uniquematch= bestmatch;
376         uniquematch_rx= bestmatch_rx;
377       }
378     }
379
380     if (uniquematch) {
381       fprintf(debug," || YES\n");
382       add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
383       x= uniquematch_rx+1;
384       ctxmap= ct->midword;
385     } else {
386       int rx;
387       fprintf(debug," || UNKNOWN");
388       for (rx=lx; rx<w && cols[rx]; rx++);
389       fprintf(debug," x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
390       debug_flush();
391       callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
392       goto restart;
393     }
394   }
395   add_result(rd, 0,-1,-1,0);
396   fprintf(debug,"OCR  finished %d glyphs\n",rd->nresults);
397   debug_flush();
398   return rd->results;
399 }
400
401 OcrReader *ocr_init(int h) {
402   OcrReader *rd;
403
404   rd= malloc(sizeof(*rd));  eassert(rd);
405   memset(rd,0,sizeof(*rd));
406   rd->h= h;
407   readdb(rd);
408   return rd;
409 }