2 * Core OCR algorithm (first exact bitmap match)
5 * This is part of ypp-sc-tools, a set of third-party tools for assisting
6 * players of Yohoho Puzzle Pirates.
8 * Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 * Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24 * are used without permission. This program is not endorsed or
25 * sponsored by Three Rings.
33 struct DatabaseNode *then;
36 typedef struct DatabaseNode {
39 unsigned match:1, defined:1, endsword:1;
55 static const char *context_names[]= {
60 struct OcrCellTypeInfo {
61 /* bitmaps of indices into context_names: */
62 unsigned initial, nextword, midword;
66 const struct OcrCellTypeInfo ocr_celltype_number= {
71 const struct OcrCellTypeInfo ocr_celltype_text= {
72 .initial=2, /* Uppercase */
73 .nextword=3, /* Either */
74 .midword=1, /* Lower only */
80 #define NCONTEXTS (sizeof(context_names)/sizeof(context_names[0]))
84 DatabaseNode contexts[NCONTEXTS];
85 OcrResultGlyph *results;
86 int aresults, nresults;
89 DEBUG_DEFINE_DEBUGF(ocr)
91 #define FGETSLINE (dbfile_getsline(lbuf,sizeof(lbuf),__FILE__,__LINE__))
93 static void cleardb_node(DatabaseNode *n) {
95 free(n->str); n->str=0;
96 n->defined=n->match=n->endsword= 0;
97 for (i=0; i<n->nlinks; i++)
98 cleardb_node(n->links[i].then);
101 static void readdb1(OcrReader *rd, const char *which);
103 static void readdb(OcrReader *rd) {
106 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
107 cleardb_node(&rd->contexts[ctxi]);
109 readdb1(rd, "master");
110 readdb1(rd, "local");
113 static void readdb1(OcrReader *rd, const char *which) {
115 DatabaseNode *current, *additional;
122 char *dbfname= masprintf("%s/#%s-char%d#.txt",
123 get_vardir(), which, rd->h);
125 if (!dbfile_open(dbfname))
129 dbassert(!strcmp(lbuf,"# ypp-sc-tools pctb font v1"));
131 dbassert( dbfile_scanf("%d", &h) == 1);
136 if (!lbuf[0] || lbuf[0]=='#') continue;
137 if (!strcmp(lbuf,".")) break;
139 for (ctxi=0; ctxi<NCONTEXTS; ctxi++)
140 if (!strcmp(lbuf,context_names[ctxi]))
142 /* not found, just skip */
143 for (;;) { FGETSLINE; if (!lbuf[0]) break; }
148 int c= fgetc(dbfile); sysassert(!ferror(dbfile)); dbassert(c!=EOF);
149 if (c=='\n') break; /* forces no match */
150 dbassert(nchrs<sizeof(chrs));
154 if (nchrs>0 && chrs[nchrs-1]==' ') {
159 current= &rd->contexts[ctxi];
162 if (!lbuf[0]) { dbassert(current != &rd->contexts[ctxi]); break; }
164 cv= strtoul(lbuf,&ep,16); dbassert(!*ep);
165 dbassert(!(cv & ~((1UL << rd->h)-1)));
167 for (j=0; j<current->nlinks; j++)
168 if (current->links[j].col == cv) {
169 current= current->links[j].then;
173 additional= mmalloc(sizeof(*additional));
175 additional->defined= 0;
176 additional->match= 0;
177 additional->endsword= 0;
178 additional->nlinks= additional->alinks= 0;
179 additional->links= 0;
180 if (current->nlinks==current->alinks) {
183 current->links= mrealloc(current->links,
184 sizeof(*current->links) * current->alinks);
186 current->links[current->nlinks].col= cv;
187 current->links[current->nlinks].then= additional;
194 if (!current->defined) {
201 current->str= mmalloc(nchrs+1);
202 memcpy(current->str, chrs, nchrs);
203 current->str[nchrs]= 0;
205 current->endsword= endsword;
214 static void cu_pr_ctxmap(FILE *resolver, unsigned ctxmap) {
215 fprintf(resolver,"{");
218 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
219 if (!(ctxmap & (1u << ctxi))) continue;
220 fprintf(resolver,"%s%s",spc,context_names[ctxi]);
223 fprintf(resolver,"}");
226 static void callout_unknown(OcrReader *rd, int w, Pixcol cols[],
227 int unk_l, int unk_r, unsigned unk_ctxmap) {
229 const OcrResultGlyph *s;
233 FILE *resolver= resolve_start();
235 fatal("OCR failed - unrecognised characters or ligatures.\n"
236 "Character set database needs to be updated or augmented.\n"
237 "See README.charset.\n");
241 "%d %d ",unk_l,unk_r);
242 cu_pr_ctxmap(resolver,unk_ctxmap);
243 for (i=0, s=rd->results; i<rd->nresults; i++, s++) {
244 if (!strcmp(s->s," ")) continue;
245 fprintf(resolver," %d %d ",s->l,s->r);
246 cu_pr_ctxmap(resolver,s->ctxmap);
247 fprintf(resolver," ");
248 for (p=s->s; (c= *p); p++) {
249 if (c=='\\') fprintf(resolver,"\\%c",c);
250 else if (c>=33 && c<=126) fputc(c,resolver);
251 else fprintf(resolver,"\\x%02x",(unsigned char)c);
254 fputc('\n',resolver);
258 "static char *t[] = {\n"
259 "/* columns rows colors chars-per-pixel */\n"
264 for (y=0, pv=1; y<rd->h; y++, pv<<=1) {
267 fputc(cols[x] & pv ? 'o' : ' ', resolver);
268 fputs("\",\n",resolver);
270 fputs("};\n",resolver);
276 static void add_result(OcrReader *rd, const char *s, int l, int r,
278 if (rd->nresults >= rd->aresults) {
279 rd->aresults++; rd->aresults<<=1;
280 rd->results= mrealloc(rd->results, sizeof(*rd->results)*rd->aresults);
282 rd->results[rd->nresults].s= s;
283 rd->results[rd->nresults].l= l;
284 rd->results[rd->nresults].r= r;
285 rd->results[rd->nresults].ctxmap= ctxmap;
290 static DatabaseNode *findchar_1ctx(const FindCharArgs *fca,
291 DatabaseNode *start, int *matchx_r) {
292 DatabaseNode *current= start;
293 DatabaseNode *bestmatch= 0;
300 if (x > fca->w) break;
301 Pixcol cv= fca->cols[x];
302 debugf(" cv=%"PSPIXCOL(PRIx),cv);
303 for (i=0; i<current->nlinks; i++)
304 if (current->links[i].col == cv)
311 current= current->links[i].then;
312 if (current->match) {
313 debugf(" \"%s\"%s",current->str,current->endsword?"_":"");
325 static DatabaseNode *findchar(const FindCharArgs *fca, int *match_rx) {
326 FindCharResults results[NCONTEXTS];
327 int ctxi, match=-1, nmatches=0;
329 debugf("OCR lx=%d ct_state=%x ", fca->x, fca->ctxmap);
330 for (ctxi=0; ctxi<NCONTEXTS; ctxi++) {
331 results[ctxi].match= 0;
332 if (!(fca->ctxmap & (1u << ctxi))) continue;
333 debugf(" || %s",context_names[ctxi]);
335 results[ctxi].match= findchar_1ctx(fca, &fca->rd->contexts[ctxi],
337 if (!results[ctxi].match) continue;
343 debugf( " unambiguous");
350 *match_rx= results[ctxi].rx;
351 return results[ctxi].match;
354 const char *ocr_celltype_name(OcrCellType ct) { return ct->name; }
356 OcrResultGlyph *ocr(OcrReader *rd, OcrCellType ct, int w, Pixcol cols[]) {
369 fca.ctxmap= ct->initial;
371 debugf("OCR h=%d w=%d",rd->h,w);
372 for (x=0; x<w; x++) debugf(" %"PSPIXCOL(PRIx),cols[x]);
386 if (nspaces == ct->space_spaces) {
387 debugf("OCR x=%x nspaces=%d space\n",x,nspaces);
388 fca.ctxmap= ct->nextword;
393 /* something here, so we need to add the spaces */
394 if (nspaces >= ct->space_spaces)
395 add_result(rd," ",x-nspaces,x+1,0);
401 DatabaseNode *match= findchar(&fca, &match_rx);
405 add_result(rd, match->str, x, match_rx, fca.ctxmap);
407 if (match->match) fca.ctxmap= ct->midword;
408 else debugf(" (empty)");
409 if (match->endsword) {
410 nspaces= ct->space_spaces;
412 fca.ctxmap= ct->nextword;
417 debugf(" || UNKNOWN");
418 for (rx=x; rx<w && cols[rx]; rx++);
419 debugf(" x=%d ctxmap=%x %d..%d\n",x, fca.ctxmap, x,rx);
421 callout_unknown(rd, w,cols, x,rx-1, fca.ctxmap);
426 add_result(rd, 0,-1,-1,0);
427 debugf("OCR finished %d glyphs\n",rd->nresults);
432 OcrReader *ocr_init(int h) {
435 if (o_flags & ff_dict_fetch) {
436 char *fetchfile= masprintf("char%d",h);
437 progress("Updating %s...",fetchfile);
438 fetch_with_rsync(fetchfile);
442 rd= mmalloc(sizeof(*rd));
443 memset(rd,0,sizeof(*rd));