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