chiark / gitweb /
Seems to be able to do the whole thing
[ypp-sc-tools.db-test.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 cu_pr_ctxmap(unsigned ctxmap) {
150   fprintf(resolver,"{");
151   const char *spc="";
152   int ctxi;
153   for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
154     if (!(ctxmap & (1u << ctxi))) continue;
155     fprintf(resolver,"%s%s",spc,context_names[ctxi]);
156     spc=" ";
157   }
158   fprintf(resolver,"}");
159 }
160
161 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
162                             int unk_l, int unk_r, unsigned unk_ctxmap) {
163   int jobpipe[2],donepipe[2], c, r,i, x,y;
164   const OcrResultGlyph *s;
165   const char *p;
166   char cb;
167   Pixcol pv;
168   
169   if (!resolver) {
170     r= pipe(jobpipe);  eassert(!r);
171     r= pipe(donepipe);  eassert(!r);
172     resolver_pid= fork();
173     eassert(resolver_pid!=-1);
174     if (!resolver_pid) {
175       r= dup2(jobpipe[0],0); eassert(r==0);
176       r= close(jobpipe[1]); eassert(!r);
177       r= close(donepipe[0]); eassert(!r);
178       /* we know donepipe[1] is >= 4 and we have dealt with all the others
179        * so we aren't in any danger of overwriting some other fd 4: */
180       r= dup2(donepipe[1],4); eassert(r==4);
181       execlp("./show-thing.tcl", "./show-thing.tcl",
182              "--automatic","1",(char*)0);
183       eassert(!"execlp failed");
184     }
185     r= close(jobpipe[0]); eassert(!r);
186     r= close(donepipe[1]); eassert(!r);
187     resolver= fdopen(jobpipe[1],"w"); eassert(resolver);
188     resolver_done= donepipe[0];
189   }
190   fprintf(resolver,"%d %d ",unk_l,unk_r);
191   cu_pr_ctxmap(unk_ctxmap);
192   for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
193     if (!strcmp(s->s," ")) continue;
194     fprintf(resolver," %d %d ",s->l,s->r);
195     cu_pr_ctxmap(s->ctxmap);
196     fprintf(resolver," ");
197     for (p=s->s; (c= *p); p++) {
198       if (c=='\\') fprintf(resolver,"\\%c",c);
199       else if (c>=33 && c<=126) fputc(c,resolver);
200       else fprintf(resolver,"\\x%02x",(unsigned char)c);
201     }
202   }
203   fputc('\n',resolver);
204
205   fprintf(resolver,
206           "/* XPM */\n"
207           "static char *t[] = {\n"
208           "/* columns rows colors chars-per-pixel */\n"
209           "\"%d %d 2 1\",\n"
210           "\"  c black\",\n"
211           "\"o c white\",\n",
212           w,rd->h);
213   for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
214     fputc('"',resolver);
215     for (x=0; x<w; x++)
216       fputc(cols[x] & pv ? 'o' : ' ', resolver);
217     fputs("\",\n",resolver);
218   }
219   fputs("};\n",resolver);
220   eassert(!ferror(resolver));
221   eassert(!fflush(resolver));
222
223   eassert(resolver);
224
225   for (;;) {
226     r= read(resolver_done,&cb,1);
227     if (r==-1) { eassert(errno==EINTR); continue; }
228     break;
229   }
230
231   if (r==0) {
232     pid_t pid;
233     for (;;) {
234       pid= waitpid(resolver_pid, &r, 0);
235       if (pid==-1) { eassert(errno==EINTR); continue; }
236       break;
237     }
238     eassert(pid==resolver_pid);
239     if (WIFEXITED(r)) {
240       eassert(!WEXITSTATUS(r));
241       fclose(resolver);
242       close(resolver_done);
243       resolver= 0;
244     } else if (WIFSIGNALED(r)) {
245       eassert(!"resolver child died due to signal");
246     } else {
247       eassert(!"weird wait status");
248     }
249   } else {
250     eassert(r==1);
251     eassert(cb==0);
252   }
253
254   readdb(rd);
255 }
256
257 static void add_result(OcrReader *rd, const char *s, int l, int r,
258                        unsigned ctxmap) {
259   if (rd->nresults >= rd->aresults) {
260     rd->aresults++; rd->aresults<<=1;
261     rd->results= realloc(rd->results,sizeof(*rd->results)*rd->aresults);
262     eassert(rd->results);
263   }
264   rd->results[rd->nresults].s= s;
265   rd->results[rd->nresults].l= l;
266   rd->results[rd->nresults].r= r;
267   rd->results[rd->nresults].ctxmap= ctxmap;
268   rd->nresults++;
269 }
270
271 struct OcrCellTypeInfo {
272   unsigned initial, nextword, midword;
273 };
274 const struct OcrCellTypeInfo ocr_celltype_number= {
275   4,4,4
276 };
277 const struct OcrCellTypeInfo ocr_celltype_text= {
278   .initial=2 /* Uppercase */,
279   .nextword=3 /* Either */,
280   .midword=1 /* Lower only */
281 };
282
283 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
284   int nspaces;
285   unsigned ctxmap;
286   int ctxi, i, x;
287
288  restart:
289
290   nspaces=- w;
291   ctxmap= ct->initial;
292   rd->nresults=0;
293   fprintf(debug,"OCR h=%d w=%d",rd->h,w);
294   for (x=0; x<w; x++) fprintf(debug," %"PSPIXCOL(PRIx),cols[x]);
295   fprintf(debug,"\n");
296   debug_flush();
297
298   x=0;
299   for (;;) {
300     debug_flush();
301     /* skip spaces */
302     if (x>=w)
303       break;
304
305     if (!cols[x]) {
306       nspaces++;
307       x++;
308       if (nspaces==3) {
309         fprintf(debug,"OCR  x=%x nspaces=%d space\n",x,nspaces);
310         add_result(rd," ",x-nspaces,x+1,0);
311         ctxmap= ct->nextword;
312       }
313       continue;
314     }
315     nspaces=0;
316
317     /* find character */
318     int lx=x;
319
320     DatabaseNode *uniquematch= 0;
321     int uniquematch_rx=-1;
322     
323     fprintf(debug,"OCR  lx=%d ctxmap=%x  ",lx,ctxmap);
324
325     for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
326       DatabaseNode *current= &rd->contexts[ctxi];;
327       DatabaseNode *bestmatch= 0;
328       int bestmatch_rx=-1;
329
330       x= lx;
331       if (!(ctxmap & (1u << ctxi))) continue;
332       fprintf(debug," || %s",context_names[ctxi]);
333
334       for (;;) {
335         debug_flush();
336         fprintf(debug," | x=%d",x);
337         if (x>w) break;
338         Pixcol cv= cols[x];
339         fprintf(debug," cv=%"PSPIXCOL(PRIx),cv);
340         for (i=0; i<current->nlinks; i++)
341           if (current->links[i].col == cv)
342             goto found;
343         /* not found */
344         fprintf(debug," ?");
345         break;
346
347       found:
348         current= current->links[i].then;
349         if (current->s[0]) {
350           fprintf(debug," \"%s\"",current->s);
351           bestmatch= current;
352           bestmatch_rx= x;
353         } else {
354           fprintf(debug," ...");
355         }
356
357         x++;
358       }
359       
360       if (bestmatch) {
361         if (uniquematch && strcmp(bestmatch->s, uniquematch->s)) {
362           fprintf(debug, " ambiguous");
363           uniquematch= 0;
364           break;
365         }
366         uniquematch= bestmatch;
367         uniquematch_rx= bestmatch_rx;
368       }
369     }
370
371     if (uniquematch) {
372       fprintf(debug," || YES\n");
373       add_result(rd, uniquematch->s, lx, uniquematch_rx, ctxmap);
374       x= uniquematch_rx+1;
375       ctxmap= ct->midword;
376     } else {
377       int rx;
378       fprintf(debug," || UNKNOWN");
379       for (rx=lx; rx<w && cols[rx]; rx++);
380       fprintf(debug," x=%d ctxmap=%x %d..%d\n",x, ctxmap, lx,rx);
381       debug_flush();
382       callout_unknown(rd, w,cols, lx,rx-1, ctxmap);
383       goto restart;
384     }
385   }
386   add_result(rd, 0,-1,-1,0);
387   fprintf(debug,"OCR  finished %d glyphs\n",rd->nresults);
388   debug_flush();
389   return rd->results;
390 }
391
392 OcrReader *ocr_init(int h) {
393   OcrReader *rd;
394
395   rd= malloc(sizeof(*rd));  eassert(rd);
396   memset(rd,0,sizeof(*rd));
397   rd->h= h;
398   readdb(rd);
399   return rd;
400 }