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