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