chiark / gitweb /
much fixes for new arrangements
[ypp-sc-tools.web-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 4
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              DEBUGP(callout) ? "--debug" : "--noop-arg",
189              "--automatic-1",
190              (char*)0);
191       eassert(!"execlp failed");
192     }
193     r= close(jobpipe[0]); eassert(!r);
194     r= close(donepipe[1]); eassert(!r);
195     resolver= fdopen(jobpipe[1],"w"); eassert(resolver);
196     resolver_done= donepipe[0];
197   }
198   fprintf(resolver,"%d %d ",unk_l,unk_r);
199   cu_pr_ctxmap(unk_ctxmap);
200   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
201     if (!strcmp(s->s," ")) continue;
202     fprintf(resolver," %d %d ",s->l,s->r);
203     cu_pr_ctxmap(s->ctxmap);
204     fprintf(resolver," ");
205     for (p=s->s; (c= *p); p++) {
206       if (c=='\\') fprintf(resolver,"\\%c",c);
207       else if (c>=33 && c<=126) fputc(c,resolver);
208       else fprintf(resolver,"\\x%02x",(unsigned char)c);
209     }
210   }
211   fputc('\n',resolver);
212
213   fprintf(resolver,
214           "/* XPM */\n"
215           "static char *t[] = {\n"
216           "/* columns rows colors chars-per-pixel */\n"
217           "\"%d %d 2 1\",\n"
218           "\"  c black\",\n"
219           "\"o c white\",\n",
220           w,rd->h);
221   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
222     fputc('"',resolver);
223     for (x=0; x<w; x++)
224       fputc(cols[x] & pv ? 'o' : ' ', resolver);
225     fputs("\",\n",resolver);
226   }
227   fputs("};\n",resolver);
228   eassert(!ferror(resolver));
229   eassert(!fflush(resolver));
230
231   eassert(resolver);
232
233   for (;;) {
234     r= read(resolver_done,&cb,1);
235     if (r==-1) { eassert(errno==EINTR); continue; }
236     break;
237   }
238
239   if (r==0) {
240     pid_t pid;
241     for (;;) {
242       pid= waitpid(resolver_pid, &r, 0);
243       if (pid==-1) { eassert(errno==EINTR); continue; }
244       break;
245     }
246     eassert(pid==resolver_pid);
247     if (WIFEXITED(r)) {
248       eassert(!WEXITSTATUS(r));
249       fclose(resolver);
250       close(resolver_done);
251       resolver= 0;
252     } else if (WIFSIGNALED(r)) {
253       eassert(!"resolver child died due to signal");
254     } else {
255       eassert(!"weird wait status");
256     }
257   } else {
258     eassert(r==1);
259     eassert(cb==0);
260   }
261
262   readdb(rd);
263 }
264
265 static void add_result(OcrReader *rd, const char *s, int l, int r,
266                        unsigned ctxmap) {
267   if (rd->nresults >= rd->aresults) {
268     rd->aresults++; rd->aresults<<=1;
269     rd->results= realloc(rd->results,sizeof(*rd->results)*rd->aresults);
270     eassert(rd->results);
271   }
272   rd->results[rd->nresults].s= s;
273   rd->results[rd->nresults].l= l;
274   rd->results[rd->nresults].r= r;
275   rd->results[rd->nresults].ctxmap= ctxmap;
276   rd->nresults++;
277 }
278
279 struct OcrCellTypeInfo {
280   unsigned initial, nextword, midword;
281 };
282 const struct OcrCellTypeInfo ocr_celltype_number= {
283   4,4,4
284 };
285 const struct OcrCellTypeInfo ocr_celltype_text= {
286   .initial=2 /* Uppercase */,
287   .nextword=3 /* Either */,
288   .midword=1 /* Lower only */
289 };
290
291 static void vdebugf(const char *fmt, va_list al) {
292   if (DEBUGP(ocr))
293     vfprintf(debug,fmt,al);
294 }
295 static void debugf(const char *fmt, ...) {
296   va_list al;  va_start(al,fmt);  vdebugf(fmt,al);  va_end(al);
297 }
298
299 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
300   int nspaces;
301   unsigned ctxmap;
302   int ctxi, i, x;
303
304  restart:
305
306   nspaces=- w;
307   ctxmap= ct->initial;
308   rd->nresults=0;
309   debugf("OCR h=%d w=%d",rd->h,w);
310   for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
311   debugf("\n");
312   debug_flush();
313
314   x=0;
315   for (;;) {
316     debug_flush();
317     /* skip spaces */
318     if (x>=w)
319       break;
320
321     if (!cols[x]) {
322       nspaces++;
323       x++;
324       if (nspaces==SPACE_SPACES) {
325         debugf("OCR  x=%x nspaces=%d space\n",x,nspaces);
326         ctxmap= ct->nextword;
327       }
328       continue;
329     }
330
331     /* something here, so we need to add the spaces */
332     if (nspaces>=SPACE_SPACES)
333       add_result(rd," ",x-nspaces,x+1,0);
334     nspaces=0;
335
336     /* find character */
337     int lx=x;
338
339     DatabaseNode *uniquematch= 0;
340     int uniquematch_rx=-1;
341     
342     debugf("OCR  lx=%d ctxmap=%x  ",lx,ctxmap);
343
344     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
345       DatabaseNode *current= &rd->contexts[ctxi];;
346       DatabaseNode *bestmatch= 0;
347       int bestmatch_rx=-1;
348
349       x= lx;
350       if (!(ctxmap & (1u << ctxi))) continue;
351       debugf(" || %s",context_names[ctxi]);
352
353       for (;;) {
354         debug_flush();
355         debugf(" | x=%d",x);
356         if (x>w) break;
357         Pixcol cv= cols[x];
358         debugf(" cv=%"PSPIXCOL(PRIx),cv);
359         for (i=0; i<current->nlinks; i++)
360           if (current->links[i].col == cv)
361             goto found;
362         /* not found */
363         debugf(" ?");
364         break;
365
366       found:
367         current= current->links[i].then;
368         if (current->s[0]) {
369           debugf(" \"%s\"",current->s);
370           bestmatch= current;
371           bestmatch_rx= x;
372         } else {
373           debugf(" ...");
374         }
375
376         x++;
377       }
378       
379       if (bestmatch) {
380         if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
381           debugf( " ambiguous");
382           uniquematch= 0;
383           break;
384         }
385         uniquematch= bestmatch;
386         uniquematch_rx= bestmatch_rx;
387       }
388     }
389
390     if (uniquematch) {
391       debugf(" || YES\n");
392       add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
393       x= uniquematch_rx+1;
394       ctxmap= ct->midword;
395     } else {
396       int rx;
397       debugf(" || UNKNOWN");
398       for (rx=lx; rx<w && cols[rx]; rx++);
399       debugf(" x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
400       debug_flush();
401       callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
402       goto restart;
403     }
404   }
405   add_result(rd, 0,-1,-1,0);
406   debugf("OCR  finished %d glyphs\n",rd->nresults);
407   debug_flush();
408   return rd->results;
409 }
410
411 OcrReader *ocr_init(int h) {
412   OcrReader *rd;
413
414   rd= malloc(sizeof(*rd));  eassert(rd);
415   memset(rd,0,sizeof(*rd));
416   rd->h= h;
417   readdb(rd);
418   return rd;
419 }