chiark / gitweb /
016a95e58bfc90557e370ca7c36728dca32a0531
[ypp-sc-tools.db-test.git] / pctb / yppsc-ocr-resolver
1 #!/usr/bin/wish
2
3 # usage:
4 #  run show-thing without args
5 #  then on stdin write
6 #     one line which is a Tcl list for unk_{l,r} unk_contexts glyphsdone
7 #     the xpm in the format expected
8 #  then expect child to raise SIGSTOP or exit 0 or exit nonzero
9 #  if child raised SIGSTOP, check database was updated
10
11
12 proc manyset {list args} {
13     foreach val $list var $args {
14         upvar 1 $var my
15         set my $val
16     }
17 }
18
19
20 #---------- display core ----------
21
22 set mul 6
23 set inter 1
24
25 set gotsh 20
26 set csrh 20
27 set ctxh 20
28
29 proc init_widgets {} {
30     # idempotent
31     global csrh gotsh ctxh
32
33     if {[winfo exists .d]} return
34     
35     frame .d
36
37     image create bitmap image/main
38     label .d.mi -image image/main -borderwidth 0
39
40     frame .d.csr -bg black -height $csrh
41     frame .d.got -bg black -height $gotsh
42     frame .d.ctx -bg black
43
44     image create bitmap image/cursor -data \
45 {#define csr_width 11
46 #define csr_height 11
47 static unsigned char csr_bits[] = {
48    0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x21, 0x04, 0x22, 0x02, 0x25, 0x05,
49    0xaa, 0x02, 0x74, 0x01, 0xa8, 0x00, 0x70, 0x00, 0x20, 0x00};
50 }
51
52     frame .d.csr.csr
53     label .d.csr.csr.l -image image/cursor -compound left
54     entry .d.csr.csr.e -bd 0
55     pack .d.csr.csr.l -side left
56
57     frame .d.mi.csr_0 -bg white -width 1
58     frame .d.mi.csr_1 -bg white -width 1
59
60     pack .d.csr .d.mi .d.got .d.ctx -side top
61     pack .d
62
63     frame .help
64     pack .help
65 }
66
67 proc show_context {maxhv x ctxs} {
68     global mul
69     upvar 1 $maxhv maxh
70     set w .d.ctx.at$x
71     if {[llength $ctxs]==1} { set fg blue } { set fg yellow }
72     label $w -bg black -fg $fg -text [join $ctxs "/\n"] -justify left
73     place $w -x [expr {($x-1)*$mul}] -y 0
74     set wh [winfo reqheight $w]
75     if {$wh > $maxh} { set maxh $wh }
76 }
77
78 proc resize_widgets {} {
79     global mulcols mulrows csrh gotsh ctxh glyphsdone
80     global unk_l unk_contexts
81     
82     foreach w {.d.csr .d.got .d.ctx} {
83         $w configure -width $mulcols
84     }
85     #.d configure -height [expr {$csrh+$mulrows+$gotsh+$ctxh}]
86     foreach w {0 1} {
87         .d.mi.csr_$w configure -height $mulrows
88     }
89
90     eval destroy [winfo children .d.ctx]
91
92     set maxh 0
93     foreach {min max contexts got} $glyphsdone {
94         show_context maxh $min $contexts
95     }
96     show_context maxh $unk_l $unk_contexts
97     .d.ctx configure -height $maxh
98 }
99
100
101 #---------- xpm input processor ----------
102
103 proc read_xpm {f} {
104     global glyphsdone mul inter rhsmost_max unk_l unk_r mulcols mulrows
105     global cols rows wordmap
106     
107     set o {}
108     set y -3
109     while 1 {
110         if {[gets $f l] < 0} { error "huh? "}
111         if {![regexp {^"(.*)",$} $l dummy l]} {
112             append o "$l\n"
113             if {[regexp {^\}\;$} $l]} break
114             continue
115         }
116         if {$y==-3} {
117             manyset $l cols rows colours cpp
118             if {$colours!=2 || $cpp!=1} { error "$l ?" }
119
120             set chop_l [expr {$unk_l - 80}]
121             set chop_r [expr {$cols - $unk_l - 100}]
122             if {$chop_l<0} { set chop_l 0 }
123
124             set unk_l [expr {$unk_l - $chop_l}]
125             set unk_r [expr {$unk_r - $chop_l}]
126             set ngd {}
127             foreach {min max contexts got} $glyphsdone {
128                 lappend ngd \
129                     [expr {$min-$chop_l}] \
130                     [expr {$max-$chop_l}] \
131                     $contexts $got
132             }
133             set glyphsdone $ngd
134
135             set realcols $cols
136             set cols [expr {$cols - $chop_l - $chop_r}]
137             debug "NOW cols=$cols chop_l,r=$chop_l,$chop_r rows=$rows\
138                 $unk_l $unk_r $ngd"
139             
140             set mulcols [expr {$cols*$mul+$inter}]
141             set mulrows [expr {$rows*$mul+$inter}]
142             append o "\"$mulcols $mulrows 9 1\",\n"
143             for {set x 0} {$x<$cols} {incr x} { set wordmap($x) 0 }
144         } elseif {$y==-2} { # first pixel
145             append o \
146 "\"+ c #111\",
147 \"a c #800\",
148 \"A c #fcc\",
149 \"b c #00c\",
150 \"B c #fff\",
151 \"u c #000\",
152 \"U c #ff0\",
153 \"q c #000\",
154 \"Q c #ff0\",\n"
155         } elseif {$y==-1} { # 2nd pixel but we've already printed ours
156         } else {
157             set ybit [expr {1<<$y}]
158             set x 0
159             set ol "\"+"
160             set olh $ol
161             if {$chop_r>=0} {
162                 set l [string range $l $chop_l end-$chop_r]
163             } else {
164                 set l [string range $l $chop_l end]
165                 append l [string repeat " " [expr -$chop_r]]
166             }
167             foreach c [split $l ""] {
168                 set how "u"
169                 if {$x >= $unk_l && $x <= $unk_r} {
170                     set how q
171                 } else {
172                     set ab 0
173                     foreach {min max contexts got} $glyphsdone {
174                         set rhsmost_max $max
175                         if {$x >= $min && $x <= $max} {
176                             set how [lindex {a b} $ab]
177                             break
178                         }
179                         set ab [expr {!$ab}]
180                     }
181                 }
182                 switch -exact $c {
183                     " " { set p $how }
184                     "o" {
185                         set p [string toupper $how]
186                         incr wordmap($x) $ybit
187                     }
188                     default { error "$c ?" }
189                 }
190                 append ol "[string repeat $p [expr {$mul-$inter}]][
191                          string repeat + $inter]"
192                 append olh [string repeat + $mul]
193                 incr x
194             }
195             set ole "\",\n"
196             append ol $ole
197             append olh $ole
198             set olhn [string repeat $olh $inter]
199             if {!$y} { append o $olhn }
200             append o [string repeat $ol [expr {$mul-1}]]
201             append o $olhn
202         }
203         incr y
204     }
205     set data [exec xpmtoppm << $o]
206     image create photo image/main -data $data
207 }
208
209
210 #---------- per-invocation display ----------
211
212 proc draw_glyphsdone {} {
213     global glyphsdone mul inter
214     eval destroy [winfo children .d.got]
215     foreach {min max contexts got} $glyphsdone {
216         frame .d.got.m$min -bd 0 -background \#888
217         label .d.got.m$min.l -text "$got" -fg white -bg black -bd 0
218         pack .d.got.m$min.l -padx 1 -pady 1
219         place .d.got.m$min -x [expr {$min*$mul+$inter}] -y 0
220     }
221 }
222
223 proc startup_cursor {} {
224     global cur_already cur_mode cur_0 cur_1 last_ht
225     global glyphsdone unk_l unk_r
226     
227     set cur_already [expr {[llength $glyphsdone]/4-1}]
228     set cur_mode 1 ;# one of:   0 1 already text
229
230     set cur_0 $unk_l
231     set cur_1 [expr {$unk_r+1}]
232     set last_ht {}
233
234     recursor
235 }
236
237
238 #---------- runtime display and keystroke handling ----------
239
240 proc helptext {t} {
241     global last_ht
242     if {![string compare $t $last_ht]} return
243     eval destroy [grid slaves .help]
244     set y 0; foreach l $t {
245         set x 0; foreach c $l {
246             set w .help.at${x}x${y}
247             label $w -text $c
248             grid $w -row $y -column $x -padx 5
249             incr x
250         }
251         incr y
252     }
253     set last_ht $t
254 }
255
256 proc recursor/0 {} { recursor//01 0 }
257 proc recursor/1 {} { recursor//01 1 }
258 proc recursor//01 {z1} {
259     global mul rhsmost_max cols glyphsdone
260     upvar #0 cur_$z1 cur
261     .d.csr.csr.l configure -text {adjust}
262     place .d.csr.csr -x [expr {$cur*$mul - 7}]
263     bind_key space { othercursor }
264     bind_leftright_q cur_$z1 0 [expr {$cols-1}]
265     if {[llength $glyphsdone]} {
266         bind_key Tab { set cur_mode already; recursor }
267     } else {
268         bind_key Tab {}
269     }
270     bind_key Return {
271         if {$cur_0 != $cur_1} {
272             .d.csr.csr.e delete 0 end
273             set cur_mode text
274             recursor
275         }
276     }
277     helptext {
278         {{<- ->}   {move cursor, adjusting area to define}}
279         {Space     {switch to moving other cursor}}
280         {Return    {confirm location, enter letter(s)}}
281         {Tab       {switch to correcting earlier ocr}}
282         {Q         {quit and abandon OCR run}}
283     }
284 }
285 proc othercursor {} {
286     global cur_mode
287     set cur_mode [expr {!$cur_mode}]
288     recursor
289 }
290
291 proc recursor/text {} {
292     helptext {
293         {Return   {confirm entry of new glyph}}
294         {Escape   {abandon entry}}
295     }
296     unbind_all_keys
297     .d.csr.csr.l configure -text {define:}
298     pack .d.csr.csr.e -side left
299     focus .d.csr.csr.e
300     bind_key Return {
301         set strq [.d.csr.csr.e get]
302         if {[regexp {^(?:[!-[]|[]-~]|\\\\|\\x[0-9a-f]{2})+} $strq]} {
303             RETURN_RESULT DEFINE "$cur_0 $cur_1 $strq"
304         }
305     }
306     bind_key Escape {
307         bind_key Escape {}
308         pack forget .d.csr.csr.e
309         set cur_mode 1
310         recursor
311     }
312 }
313
314 proc recursor/already {} {
315     global mul
316     global glyphsdone
317     global cur_already mul
318     global glyphsdone cur_already mul
319     .d.csr.csr.l configure -text {correct}
320     set rmax [lindex $glyphsdone [expr {$cur_already*4}]]
321     place .d.csr.csr -x [expr {$rmax*$mul-3}]
322     bind_key Return {}
323     bind_key space {}
324     bind_leftright_q cur_already 0 [expr {[llength $glyphsdone]/4-1}]
325     bind_key Tab { bind_key Delete {}; set cur_mode 1; recursor }
326     bind_key Delete {
327         RETURN_RESULT DELETE [lrange $glyphsdone \
328                                   [expr $cur_already*4] \
329                                   [expr $cur_already*4+2]]
330     }
331     helptext {
332         {{<- ->}   {move cursor, selecting glyph to correct}}
333         {Del       {clear this glyph from the recognition database}}
334         {Tab       {switch to selecting area to define as new glyph}}
335         {Q         {quit and abandon OCR run}}
336     }
337 }
338
339 proc bind_key {k proc} {
340     global keybindings
341     bind . <Key-$k> $proc
342     set keybindings($k) [expr {!![string length $proc]}]
343 }
344 proc unbind_all_keys {} {
345     global keybindings
346     foreach k [array names keybindings] { bind_key $k {} }
347 }
348
349 proc bind_leftright_q {var min max} {
350     bind_key Left  [list leftright $var $min $max -1]
351     bind_key Right [list leftright $var $min $max +1]
352     bind_key q     {
353         puts stderr "\nCharacter resolver quitting as you requested."
354         exit 1
355     }
356 }
357 proc leftright {var min max inc} {
358     upvar #0 $var v
359     set vnew $v
360     incr vnew $inc
361     if {$vnew < $min || $vnew > $max} return
362     set v $vnew
363     recursor
364 }
365
366 proc recursor {} {
367     global csrh cur_mode cur_0 cur_1 mul
368     foreach z1 {0 1} {
369         place .d.mi.csr_$z1 -y 0 -x [expr {[set cur_$z1] * $mul}]
370     }
371     recursor/$cur_mode
372 }
373
374
375 #---------- database read and write ----------
376
377 # database format:
378 # series of glyphs:
379 #   <context> <ncharacters> <hex>...
380 #   width
381 #   <hex-bitmap>
382
383 # $database($context 0x<bits> 0x<bits>...) = $hex
384
385 set database_header {# ypp-sc-tools pctb font v1}
386
387 proc db_getsl {f} {
388     if {[gets $f l] < 0} { error "unexpected db eof" }
389     return $l
390 }
391     
392 proc read_database {} {
393     global database database_header rows database_fn
394     catch { unset database }
395     set database_fn ./charset-$rows.txt
396     if {![file exists $database_fn]} return
397     set f [open $database_fn r]
398     if {[string compare [db_getsl $f] $database_header]} { error "$l ?" }
399     if {([db_getsl $f])+0 != $rows} { error "wrong h ?" }
400     while 1 {
401         set context [db_getsl $f]
402         if {![string length $context]} continue
403         if {[regexp {^\#} $context]} continue
404         if {![string compare . $context]} break
405
406         set bm $context
407         set strq [db_getsl $f]
408         while 1 {
409             set l [db_getsl $f]
410             if {![string length $l]} break
411             lappend bm [format %x 0x$l]
412         }
413         set database($bm) $strq
414     }
415     close $f
416 }
417
418 proc write_database {} {
419     global database rows database_fn database_header
420     set ol {}
421     foreach bm [array names database] {
422         set strq $database($bm)
423         set o "[lindex $bm 0]\n$strq\n"
424         foreach x [lrange $bm 1 end] { append o "$x\n" }
425         
426         lappend ol $o
427     }
428     set f [open $database_fn.new w]
429     puts $f "$database_header\n$rows\n"
430     foreach o [lsort $ol] {
431         puts $f $o
432     }
433     puts $f "."
434     close $f
435     file rename -force $database_fn.new $database_fn
436 }
437
438 proc dbkey {ctx l r} {
439     global wordmap
440     set bm $ctx
441     for {set x $l} {$x <= $r} {incr x} {
442         lappend bm [format %x $wordmap($x)]
443     }
444     return $bm
445 }
446
447 proc update_database/DEFINE {c0 c1 strq} {
448     global glyphsdone unk_l unk_contexts wordmap database
449     if {$c0 > $c1} { manyset [list $c0 $c1] c1 c0 }
450     if {$c0 == $unk_l} {
451         set ncontexts $unk_contexts
452     } else {
453         foreach {l r contexts got} $glyphsdone {
454             if {$l==$c0} { set ncontexts $contexts; break }
455         }
456         if {![info exists ncontexts]} {
457             puts stderr "must start at letter LHS!"
458             return
459         }
460     }
461     incr c1 -1
462     foreach c $ncontexts {
463         set bm [dbkey $c $c0 $c1]
464         set database($bm) $strq
465     }
466     write_database
467 }
468
469 proc update_database/DELETE {l r ctxs} {
470     global database
471     foreach ctx $ctxs {
472         set bm [dbkey $ctx $l $r]
473         catch { unset database($bm) }
474     }
475     write_database
476 }
477     
478
479 proc RETURN_RESULT {how what} {
480     global mainkind
481     place forget .d.csr.csr
482     pack forget .d.csr.csr.e
483     helptext {{{ Processing }}}
484     unbind_all_keys
485     update idletasks
486     debug "$how $what"
487     eval update_database/$how $what
488     done/$mainkind
489 }
490
491 #---------- main progrm ----------
492
493 proc main/test {} {
494     global glyphsdone unk_l unk_r unk_contexts
495
496     set glyphsdone {
497         7 11 1 M
498         13 17 0 a
499         19 23 0 n
500     }
501     set unk_l 25
502     set unk_r 29
503     set unk_contexts Test
504
505     set f [open text.xpm]
506     read_xpm $f
507     close $f
508
509     read_database
510     resize_widgets
511     draw_glyphsdone
512     startup_cursor
513 }
514 proc done/test {} {
515 }
516
517 proc required {} {
518     global glyphsdone unk_l unk_r unk_contexts
519     
520     if {[gets stdin l]<0} {
521         if {[eof stdin]} { fconfigure stdin -blocking yes; exit 0 }
522         return
523     }
524     init_widgets
525     manyset [lrange $l 0 3] unk_l unk_r unk_contexts
526     set glyphsdone [lrange $l 3 end]
527     debug "GOT $l"
528
529     fileevent stdin readable {}
530     fconfigure stdin -blocking yes
531
532     read_xpm stdin
533     resize_widgets
534     read_database
535     draw_glyphsdone
536     startup_cursor
537 }
538
539 proc main/automatic {} {
540     fconfigure stdin -blocking no
541     fileevent stdin readable required
542 }
543 proc done/automatic {} {
544     exec sh -c {printf \\0 >&4}
545     main/automatic
546 }
547
548 proc debug {m} { }
549
550 set mainkind test
551 foreach arg $argv {
552     switch -exact -- $arg {
553         {--debug}        { proc debug {m} { puts stderr "SHOW-THING $m" } }
554         {--noop-arg}     { }
555         {--automatic-1}  { set mainkind automatic }
556         {--automatic*}   { error "incompatible versions - install problem" }
557         default          { error "huh $argv ?" }
558     }
559 }
560
561 main/$mainkind