replaced libart with new polygon code
[swftools.git] / lib / gocr / database.c
1 /*
2 This is a Optical-Character-Recognition program
3 Copyright (C) 2000-2006 Joerg Schulenburg
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19  see README for EMAIL address
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include "gocr.h"
25 #include "pnm.h"
26 #include "pgm2asc.h"
27 #include <string.h>
28 #include <time.h>
29
30 #define Blen  256
31
32 // load boxes from database into boxlist (for faster access)
33 //   used as alternate engine, comparing chars with database
34 int load_db(void) {
35   FILE *f1;
36   char s1[Blen+1],
37        s2[Blen+1] = "./db/", /* ToDo: replace by constant! by configure */
38        *s3;
39   int i, j, ii, i2, line;
40   struct box *box1;
41   pix *pp;
42
43   if( JOB->cfg.db_path ) strncpy(s2,JOB->cfg.db_path,Blen-1);
44   i2=strlen(s2);
45   if (JOB->cfg.verbose)
46     fprintf(stderr, "# load database %s %s ... ",s2,JOB->cfg.db_path);
47
48   strncpy(s2+i2,"db.lst",Blen-i2);s2[Blen]=0;
49   f1 = fopen(s2, "r");
50   if (!f1) {
51     fprintf(stderr, " DB %s not found\n",s2);
52     return 1;
53   }
54
55   line = 0; /* line counter for better error report */
56   for (ii = 0; !feof(f1); ii++) {
57 /* bbg: should write a better input routine */
58     if (!fgets(s1, Blen, f1)) break; line++;
59     j = strlen(s1);
60     /* remove carriage return sequences from line */
61     while (j > 0 && (s1[j - 1] == '\r' || s1[j - 1] == '\n'))
62       s1[--j] = 0;
63     if (!j)         continue;   /* skip empty line */
64     if (s1[0]=='#') continue;   /* skip comments (v0.44) */
65     /* copy file name */
66     for (i = 0; i < j && i+i2 < Blen && strchr(" \t,;",s1[i]) == 0; i++)
67       s2[i2 + i] = s1[i];
68     s2[i2+i]=0;
69     /* skip spaces */
70     for (; i < j && strchr(" \t",s1[i]) != 0; i++);
71     /* by now: read pix, fill box, goto next ??? */
72     pp = (pix *)malloc(sizeof(pix));
73     if( !pp ) fprintf(stderr,"malloc error in load_db pix\n");
74
75     //readpgm(s2, pp, 0 * JOB->cfg.verbose);
76     fprintf(stderr, "Can't call readpgm()\n");
77
78     box1 = (struct box *)malloc_box(NULL);
79     if(!box1) fprintf(stderr,"malloc error in load_db box1\n");
80     box1->x0 = 0;
81     box1->x1 = pp->x-1;       // white border 1 pixel width
82     box1->y0 = 0;
83     box1->y1 = pp->y-1;
84     box1->x = 1;
85     box1->y = 1;
86     box1->dots = 0;
87     box1->c = 0;
88     box1->modifier = 0; /* ToDo: obsolete */
89     box1->tas[0]=NULL;
90     box1->tac[0]=0;
91     box1->wac[0]=100; /* really 100% sure? */
92     box1->num_ac=1;
93     if (s1[i]=='"'){  /* parse a string */
94       j=strrchr(s1+i+1,'"')-(s1+i+1); /* we only look for first and last "" */
95       if (j>=1) {
96         s3=(char *)malloc(j+1);
97         if (!s3) fprintf (stderr, "malloc error in load_db s3\n");
98         if (s3) {
99           memcpy(s3,s1+i+1,j);
100           s3[j]=0;
101           box1->tas[0]=s3;
102           // fprintf(stderr,"\nstring=%s",s3);
103         }
104       } else { fprintf(stderr,"load_db: string parse error L%d\n",line); }
105     } else {
106       box1->tac[0] = box1->c = s1[i];      /* try to interpret as ASCII */
107       /* we can live without hexcode in future if we use UTF8-strings */
108       s3=s1+i;
109       j=strtol( s1+i, &s3, 16); /* try to read 4 to 8 digit hex unicode */
110       /* if its an hexcode, ASCII interpretation is overwritten */
111       if( j && i+3<=Blen && s3-s1-i>3 ) box1->tac[0] = box1->c = j;
112       // fprintf(stderr,"\nhexcode=%04x=%04x %d",(int)j,(int)box1->c,s3-s1-i);
113     }
114     box1->num = 0;
115     box1->line = -1;
116     box1->m1 = 0;  /* ToDo: should be given too in the database! */
117     box1->m2 = 0;
118     box1->m3 = 0;
119     box1->m4 = 0;
120     box1->p = pp;
121     list_app(&JOB->tmp.dblist, box1);   // append to list
122 #if 0
123      out_x(box1);
124 #endif
125   }
126   fclose(f1);
127   if (JOB->cfg.verbose)
128     fprintf(stderr, " %d chars loaded\n", ii);
129   return 0;
130 }
131
132 // expand database from box/boxlist name=db_$utime.pbm
133 // this is added in version v0.3.3
134 int store_db(struct box *box1) {
135   FILE *f1;
136   char s2[Blen+1] = "./db/", s3[Blen+1];
137   int i2, dx, dy;
138   pix b;        /* temporary mini page */
139
140   if( JOB->cfg.db_path ) strncpy(s2,JOB->cfg.db_path,Blen-1);
141   i2=strlen(s2);
142  
143   /* name generation can cause problems, if called twice within a second */
144   if (box1->num_ac && box1->tas[0])
145     sprintf(s3,"db_%04x_%lu.pbm", (unsigned int)box1->tas[0][0],
146                                   (unsigned long)time(NULL));
147   else
148     sprintf(s3,"db_%04x_%lu.pbm", (unsigned int)box1->c,
149                                   (unsigned long)time(NULL));
150   /* ToDo: the file name may be not unique */
151   strncpy(s2+i2,"db.lst",Blen-i2);s2[Blen]=0;
152   f1 = fopen(s2, "a");
153   if (!f1) {
154     fprintf(stderr, " could not access %s\n",s2);
155     return 1;
156   }
157   strncpy(s2+i2,s3,strlen(s3)); s2[i2+strlen(s3)]=0;
158   /* store image and infos about the char */
159   /* ToDo: store the vector list instead of the pixelarray */
160   
161   if (JOB->cfg.verbose)
162     fprintf(stderr, "store_db: add file %s to database\n#",s3);
163   dx=box1->x1-box1->x0+1;
164   dy=box1->y1-box1->y0+1;
165   b.p = (unsigned char *) malloc( dx * dy );
166   if( !b.p ){
167     fprintf( stderr, "\nFATAL: malloc failed, skip store_db" );
168     return 2;
169   }
170   if (copybox(box1->p, box1->x0, box1->y0, dx, dy, &b, dx * dy))
171     return -1;
172                           
173   //writepbm(s2,&b); /* What is to do on error? */
174
175   free(b.p);
176
177   /* store the database line */
178   /* some infos about box1->m1,..,m4 should added (base line, high etc.) */
179   if (box1->num_ac && box1->tas[0]) {
180     fprintf(f1, "%s \"%s\"\n",s3,box1->tas[0]);
181     /* ToDo: what if tas contains '"'? */
182   } else {
183     if( (box1->c >= '0' && box1->c <= '9')
184      || (box1->c >= 'A' && box1->c <= 'Z')
185      || (box1->c >= 'a' && box1->c <= 'z') )
186       fprintf(f1, "%s %c\n",s3,(char)box1->c);
187     else {
188       if (((box1->c)>>16)>>16)
189         fprintf(f1, "%s %08x\n",s3,(unsigned int)box1->c);
190       else
191         fprintf(f1, "%s %04x\n",s3,(unsigned int)box1->c);
192     }
193   }
194   fclose(f1);
195   return 0;
196 }
197
198 /* function is only for user prompt on console to identify chars
199    it prints out a part of pixmap b at point x0,y0 to stderr
200    using dots .,; if no pixel, and @xoO for pixels
201  */
202 void out_env(struct box *px ){
203   int x0,y0,x1,y1,dx,dy,x,y,x2,y2,yy0,tx,ty,i,cs;
204   char c1, c2; pix *b;
205   cs=JOB->cfg.cs;
206   yy0=px->y0;
207   { /* overwrite rest of arguments */
208     b=px->p;
209     x0=px->x0; x1=px->x1; dx=x1-x0+1;
210     y0=px->y0; y1=px->y1; dy=y1-y0+1;
211     y0-=2; y1+=2; 
212     if (px->m4 && y0>px->m1) y0=px->m1;
213     if (px->m4 && y1<px->m4) y1=px->m4;
214     if (x1-x0+1<52) { x0-=10; x1+=10; } /* fragment? expand frame */
215     if (x1-x0+1<52) { x0-=10; x1+=10; } /* fragment? expand frame */
216     if (x1-x0+1<62) { x0-=5;  x1+=5; }
217     if (y1-y0+1<10) { y0-= 4; y1+= 4; } /* fragment? */
218     if (x0<0) x0=0;  if (x1>=b->x) x1=b->x-1; 
219     if (y0<0) y0=0;  if (y1>=b->y) y1=b->y-1; 
220     dx=x1-x0+1;
221     dy=y1-y0+1; yy0=y0;
222     fprintf(stderr,"\n# show box + environment");
223     fprintf(stderr,"\n# show box     x= %4d %4d d= %3d %3d r= %d %d",
224           px->x0, px->y0, px->x1 - px->x0 + 1, px->y1 - px->y0 + 1,
225           px->x - px->x0, px->y - px->y0);
226     if (px->num_ac){ /* output table of chars and its probabilities */
227       fprintf(stderr,"\n# list box char: ");
228       for(i=0;i<px->num_ac && i<NumAlt;i++)
229       /* output the (xml-)string (picture position, barcodes, glyphs, ...) */
230         if (px->tas[i])
231          fprintf(stderr," %s(%d)",       px->tas[i]       ,px->wac[i]);
232         else
233          fprintf(stderr," %s(%d)",decode(px->tac[i],ASCII),px->wac[i]);
234     }
235     fprintf(stderr,"\n");
236     if (px->dots && px->m2 && px->m1<y0) { yy0=px->m1; dy=px->y1-yy0+1; }
237   }
238   tx=dx/80+1;
239   ty=dy/40+1; // step, usually 1, but greater on large maps 
240   fprintf(stderr,"# show pattern x= %4d %4d d= %3d %3d t= %d %d\n",
241                  x0,y0,dx,dy,tx,ty);
242   if (dx>0)
243   for(y=yy0;y<yy0+dy;y+=ty) { /* reduce the output to max 78x40 */
244
245     /* image is the boxframe + environment in the original bitmap */
246     for(x=x0;x<x0+dx;x+=tx){  /* by merging sub-pixels */
247       c1='.';
248       for(y2=y;y2<y+ty && y2<y0+dy;y2++) /* sub-pixels */
249       for(x2=x;x2<x+tx && x2<x0+dx;x2++)
250         { if((getpixel(b,x2,y2)<cs)) c1='#'; }
251       // show pixels outside the box thinner/weaker
252       if (x+tx-1 < px->x0 || x > px->x1
253        || y+ty-1 < px->y0 || y > px->y1) c1=((c1=='#')?'O':',');
254       fprintf(stderr,"%c", c1 );
255     }
256
257     c1=c2=' ';
258     /* mark lines with < */
259     if (px) if (y==px->m1 || y==px->m2 || y==px->m3 || y==px->m4)  c1='<';
260     if (y==px->y0 || y==px->y1)  c2='-';  /* boxmarks */
261     fprintf(stderr,"%c%c\n",c1,c2);
262   }
263 }
264
265
266 /*
267 // second variant, for database (with slightly other behaviour)
268 // new variant
269 //  look at the environment of the pixel too (contrast etc.)
270 //   detailed analysis only of diff pixels!
271 //
272 // 100% * distance, 0 is best fit
273 // = similarity of 2 chars for recognition of noisy chars
274 //   weigth of pixels with only one same neighbour set to 0
275 //   look at contours too!
276    ToDo: especially on small boxes distance should only be 0 if
277        characters are 100% identical! 
278 */
279 // #define DEBUG 2
280 int distance2( pix *p1, struct box *box1,
281                pix *p2, struct box *box2, int cs){
282    int rc=0,x,y,v1,v2,i1,i2,rgood=0,rbad=0,
283        x1,y1,x2,y2,dx,dy,dx1,dy1,dx2,dy2,tx,ty;
284 #if DEBUG == 2
285   if(JOB->cfg.verbose)
286     fprintf(stderr," DEBUG: distance2\n");
287 #endif
288    x1=box1->x0;y1=box1->y0;x2=box2->x0;y2=box2->y0;
289    dx1=box1->x1-box1->x0+1; dx2=box2->x1-box2->x0+1; dx=((dx1>dx2)?dx1:dx2);dx=dx1;
290    dy1=box1->y1-box1->y0+1; dy2=box2->y1-box2->y0+1; dy=((dy1>dy2)?dy1:dy2);dy=dy1;
291    if(abs(dx1-dx2)>1+dx/16 || abs(dy1-dy2)>1+dy/16) rbad++; // how to weight?
292    // compare relations to baseline and upper line
293    if(box1->m4>0 && box2->m4>0){  // used ???
294      if(2*box1->y1>box1->m3+box1->m4 && 2*box2->y1<box2->m3+box2->m4) rbad+=128;
295      if(2*box1->y0>box1->m1+box1->m2 && 2*box2->y0<box2->m1+box2->m2) rbad+=128;
296    }
297    tx=dx/16; if(dx<17)tx=1; // raster
298    ty=dy/32; if(dy<33)ty=1;
299    // compare pixels
300    for( y=0;y<dy;y+=ty )
301    for( x=0;x<dx;x+=tx ) {      // try global shift too ???
302      v1=((getpixel(p1,x1+x*dx1/dx,y1+y*dy1/dy)<cs)?1:0); i1=8;  // better gray?
303      v2=((getpixel(p2,x2+x*dx2/dx,y2+y*dy2/dy)<cs)?1:0); i2=8;  // better gray?
304      if(v1==v2) { rgood+=16; continue; } // all things are right!
305      // what about different pixel???
306      // test overlapp of surounding pixels ???
307      v1=1; rbad+=4;
308      v1=-1;
309      for(i1=-1;i1<2;i1++)
310      for(i2=-1;i2<2;i2++)if(i1!=0 || i2!=0){
311        if( ((getpixel(p1,x1+x*dx1/dx+i1*(1+dx1/32),y1+y*dy1/dy+i2*(1+dy1/32))<cs)?1:0)
312          !=((getpixel(p2,x2+x*dx2/dx+i1*(1+dx2/32),y2+y*dy2/dy+i2*(1+dy2/32))<cs)?1:0) ) v1++;
313      }
314      if(v1>0)
315      rbad+=16*v1;
316    }
317    if(rgood+rbad) rc= 100*rbad/(rgood+rbad); else rc=99;
318    /* if width/high is not correct add badness */
319    rc += ( abs(dx1*dy2-dx2*dy1) * 10 ) / (dy1*dy2);
320    if (rc>100) rc=100;
321    if(/* rc<10 && */ JOB->cfg.verbose /* &1024 */){
322 #if DEBUG == 2
323      fprintf(stderr," distance2 rc=%d rgood=%d rbad=%d\n",rc,rgood,rbad);
324 //     out_b(NULL,p1,box1->x0,box1->y0,box1->x1-box1->x0+1,
325 //                                box1->y1-box1->y0+1,cs);
326 //     out_b(NULL,p2,box2->x0,box2->y0,box2->x1-box2->x0+1,
327 //                                box2->y1-box2->y0+1,cs);
328      out_x(box1);
329      out_x(box2);
330 #endif
331    }
332    return rc;
333 }
334
335 wchar_t ocr_db(struct box *box1) {
336   int dd = 1000, dist = 1000;
337   wchar_t c = UNKNOWN;
338   char buf[200];
339   Box *box2, *box3;
340   
341   if (!list_empty(&JOB->tmp.dblist)){ 
342     box3 = (Box *)list_get_header(&JOB->tmp.dblist);
343     if(JOB->cfg.verbose)
344       fprintf(stderr,"\n#DEBUG: ocr_db (%d,%d) ",box1->x0, box1->y0);
345
346     for_each_data(&JOB->tmp.dblist) {
347       box2 = (Box *)list_get_current(&JOB->tmp.dblist);
348       /* do preselect!!! distance() slowly */
349       dd = distance2( box2->p, box2, box1->p, box1, JOB->cfg.cs);
350       if (dd <= dist) {  /* new best fit */ 
351         dist = dd;
352         box3 = box2; /* box3 is a pointer and not copied box2 */
353
354         if (dist<100 && 100-dist > JOB->cfg.certainty) {
355           /* some deviation of the pattern is tolerated */
356           int i, wa;
357           for (i=0;i<box3->num_ac;i++) {
358            wa = (100-dist)*box3->wac[i]/100; /* weight *= (100-dist) */
359            if (box3->tas[i]) setas(box1,box3->tas[i],wa);
360            else              setac(box1,box3->tac[i],wa);
361           }
362           if (box3->num_ac) c=box3->tac[0]; /* 0 for strings (!UNKNOWN) */
363           if (JOB->cfg.verbose)
364             fprintf(stderr, " dist=%4d c= %c 0x%02x %s  wc= %3d", dist,
365                ((box3->c>32 && box3->c<127) ? (char) box3->c : '.'),
366                (int)box3->c, ((box3->tas[0])?box3->tas[0]:""), box3->wac[0]);
367         }
368         if (dd<=0 && ((box3->num_ac && box3->tas[0]) || box3->c >= 128
369                        || !strchr ("l1|I0O", box3->c)))
370           break; /* speedup if found */
371       }
372     } end_for_each(&JOB->tmp.dblist);
373     
374   }
375
376   if( (JOB->cfg.mode&128) != 0 && c == UNKNOWN ) { /* prompt the user */
377     /* should the output go to stderr or special pipe??? */
378     int utf8_ok=0;  /* trigger this flag if input is ok */
379     int i, endchar; /* index */
380     out_env(box1);  /* old: out_x(box1); */
381     fprintf(stderr,"The above pattern was not recognized.\n"
382       "Enter UTF8 char or string for above pattern. Leave empty if unsure.\n"
383       "Press RET at the end (ALT+RET to store into RAM only) : "
384     );  /* ToDo: empty + alt-return (0x1b 0x0a) for help? ^a for skip all */
385     /* UTF-8 (man 7 utf-8):
386      *   7bit = 0xxxxxxx                            (0000-007F)
387      *  11bit = 110xxxxx 10xxxxxx                   (0080-07FF)
388      *  16bit = 1110xxxx 10xxxxxx 10xxxxxx          (0800-FFFF)
389      *  21bit = 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
390      *  26bit = 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
391      *  31bit = 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
392      */
393     buf[0]=0;
394     /* shift/ctrl/altgr-enter acts like enter or ^j or ^m,
395      * alt-enter returns 0x1b 0x0a and returns from fgets()
396      * ^d (EOF) returns (nil) from fgets()
397      * x+(2*)ctrl-d returns from fgets() without returning a 0x0a
398      * if not UTF-input-mode, we are in trouble?
399      * ^a=0x01, ^b=0x02, ^e=05, ..., ToDo: meaning of no-input or <=space
400      */
401     fgets(buf,200,stdin); /* including \n=0x0a */
402     dd=strlen(buf);
403     /* output hexcode if verbose set */
404     if (JOB->cfg.verbose) {
405       fprintf(stderr, "\n# fgets [%d]:", dd);
406       for(i=0; i<dd; i++)
407         fprintf(stderr, " %02x", (unsigned)((unsigned char)buf[i]));
408       fprintf(stderr, "\n#");
409     }
410     /* we dont accept chars which could destroy database file */
411     for (i=0; i<dd; i++) if (buf[i]<32) break;
412     endchar=buf[i]; /* last char is 0x0a (ret) 0x00 (EOF) or 0x1b (alt+ret) */
413     if (endchar==0x01) { i=0;JOB->cfg.mode&=~128; } /* skip all */
414     buf[dd=i]=0; /* replace final 0x0a or other special codes */
415     if (dd==1 && !(buf[0]&128)) { c=buf[0]; utf8_ok=1; } /* single char */
416     if (dd>1 && dd<7) {        /* try to decode single wide char (utf8) */ 
417       int u0, u1;  /* define UTF8-start sequences, u0=0bits u1=1bits */
418       u0=       1<<(7-dd);       /* compute start byte from UTF8-length */
419       u1=255&~((1<<(8-dd))-1);
420       for (i=1;i<dd;i++) if ((buf[i]&0xc0)!=0x80) break; /* 10xxxxxx */
421       if (i==dd && (buf[0]&(u0|u1))==u1) { utf8_ok=1;
422         c=buf[0]&(u0-1);                                 /* 11..0x.. */
423         for (i=1;i<dd;i++) { c<<=6; c|=buf[i]&0x3F; }    /* 10xxxxxx */
424       }
425     }
426     if (dd>0){ /* ToDo: skip space and tab too? */
427       if (utf8_ok==1) { setac(box1, c, 100); } /* store single wchar */
428       if (utf8_ok==0) {     /* store a string of chars (UTF8-string) */
429         c='_'; /* what should we do with c? probably a bad idea? */
430         setas(box1, buf, 100);
431       }
432       /* decide between
433        *  0) just help gocr to find the results and (dont remember, 0x01)
434        *  1) help and remember in the same run (store to memory, 0x1b)
435        *  2) expand the database (dont store ugly chars to the database!)
436        */
437       if (endchar!=0x01){ /* ^a before hit return */
438       /* is there a reason to dont store to memory? */
439         list_app(&JOB->tmp.dblist, box1); /* append to list for 1+2 */
440       }
441       if (endchar!=0x01 && endchar!=0x1b){
442         store_db(box1);  /* store to disk for 2 */
443       }
444       if (JOB->cfg.verbose)
445         fprintf(stderr, " got  char= %c  16bit= 0x%04x  string= \"%s\"\n",
446            ((c>32 && c<127)?(char)c:'.'), (int)c, buf);
447     }
448   }
449   
450   return c;
451 }