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