chiark / gitweb /
WIP island determination; pixmap handling in progress
[ypp-sc-tools.db-test.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 read_xpm {f} {
130     global glyphsdone mul inter rhsmost_max unk_l unk_r mulcols mulrows
131     global cols rows wordmap
132     
133     set o {}
134     set y -3
135     while 1 {
136         if {[gets $f l] < 0} { error "huh? "}
137         if {![regexp {^"(.*)",$} $l dummy l]} {
138             append o "$l\n"
139             if {[regexp {^\}\;$} $l]} break
140             continue
141         }
142         if {$y==-3} {
143             manyset $l cols rows colours cpp
144             if {$colours!=2 || $cpp!=1} { error "$l ?" }
145
146             set chop_l [expr {$unk_l - 80}]
147             set chop_r [expr {$cols - $unk_l - 100}]
148             if {$chop_l<0} { set chop_l 0 }
149
150             set unk_l [expr {$unk_l - $chop_l}]
151             set unk_r [expr {$unk_r - $chop_l}]
152             set ngd {}
153             foreach {min max contexts got} $glyphsdone {
154                 lappend ngd \
155                     [expr {$min-$chop_l}] \
156                     [expr {$max-$chop_l}] \
157                     $contexts $got
158             }
159             set glyphsdone $ngd
160
161             set realcols $cols
162             set cols [expr {$cols - $chop_l - $chop_r}]
163             debug "NOW cols=$cols chop_l,r=$chop_l,$chop_r rows=$rows\
164                 $unk_l $unk_r $ngd"
165             
166             set mulcols [expr {$cols*$mul+$inter}]
167             set mulrows [expr {$rows*$mul+$inter}]
168             append o "\"$mulcols $mulrows 9 1\",\n"
169             for {set x 0} {$x<$cols} {incr x} { set wordmap($x) 0 }
170         } elseif {$y==-2} { # first pixel
171             append o \
172 "\"+ c #111\",
173 \"a c #800\",
174 \"A c #fcc\",
175 \"b c #00c\",
176 \"B c #fff\",
177 \"u c #000\",
178 \"U c #ff0\",
179 \"q c #000\",
180 \"Q c #ff0\",\n"
181         } elseif {$y==-1} { # 2nd pixel but we've already printed ours
182         } else {
183             set ybit [expr {1<<$y}]
184             set x 0
185             set ol "\"+"
186             set olh $ol
187             if {$chop_r>=0} {
188                 set l [string range $l $chop_l end-$chop_r]
189             } else {
190                 set l [string range $l $chop_l end]
191                 append l [string repeat " " [expr -$chop_r]]
192             }
193             foreach c [split $l ""] {
194                 set how "u"
195                 if {$x >= $unk_l && $x <= $unk_r} {
196                     set how q
197                 } else {
198                     set ab 0
199                     foreach {min max contexts got} $glyphsdone {
200                         set rhsmost_max $max
201                         if {$x >= $min && $x <= $max} {
202                             set how [lindex {a b} $ab]
203                             break
204                         }
205                         set ab [expr {!$ab}]
206                     }
207                 }
208                 switch -exact $c {
209                     " " { set p $how }
210                     "o" {
211                         set p [string toupper $how]
212                         incr wordmap($x) $ybit
213                     }
214                     default { error "$c ?" }
215                 }
216                 append ol "[string repeat $p [expr {$mul-$inter}]][
217                          string repeat + $inter]"
218                 append olh [string repeat + $mul]
219                 incr x
220             }
221             set ole "\",\n"
222             append ol $ole
223             append olh $ole
224             set olhn [string repeat $olh $inter]
225             if {!$y} { append o $olhn }
226             append o [string repeat $ol [expr {$mul-1}]]
227             append o $olhn
228         }
229         incr y
230     }
231     set data [exec xpmtoppm << $o]
232     image create photo image/main -data $data
233 }
234
235
236 #---------- per-invocation display ----------
237
238 proc draw_glyphsdone {} {
239     global glyphsdone mul inter
240     eval destroy [winfo children .d.got]
241     foreach {min max contexts got} $glyphsdone {
242         frame .d.got.m$min -bd 0 -background \#888
243         label .d.got.m$min.l -text "$got" -fg white -bg black -bd 0
244         pack .d.got.m$min.l -padx 1 -pady 1
245         place .d.got.m$min -x [expr {$min*$mul+$inter}] -y 0
246     }
247 }
248
249 proc startup_cursor {} {
250     global cur_already cur_mode cur_0 cur_1 last_ht
251     global glyphsdone unk_l unk_r
252     
253     set cur_already [expr {[llength $glyphsdone]/4-1}]
254     set cur_mode 1 ;# one of:   0 1 already text
255
256     set cur_0 $unk_l
257     set cur_1 [expr {$unk_r+1}]
258     set last_ht {}
259
260     recursor
261 }
262
263
264 #---------- runtime display and keystroke handling ----------
265
266 proc helptext {t} {
267     global last_ht
268     if {![string compare $t $last_ht]} return
269     eval destroy [grid slaves .help]
270     set y 0; foreach l $t {
271         set x 0; foreach c $l {
272             set w .help.at${x}x${y}
273             label $w -text $c
274             grid $w -row $y -column $x -padx 5
275             incr x
276         }
277         incr y
278     }
279     set last_ht $t
280 }
281
282 proc recursor/0 {} { recursor//01 0 }
283 proc recursor/1 {} { recursor//01 1 }
284 proc recursor//01 {z1} {
285     global mul rhsmost_max cols glyphsdone
286     upvar #0 cur_$z1 cur
287     .d.csr.csr.l configure -text {adjust}
288     place .d.csr.csr -x [expr {$cur*$mul - 7}]
289     bind_key space { othercursor }
290     bind_leftright_q cur_$z1 0 [expr {$cols-1}]
291     if {[llength $glyphsdone]} {
292         bind_key Tab { set cur_mode already; recursor }
293     } else {
294         bind_key Tab {}
295     }
296     bind_key Return {
297         if {$cur_0 != $cur_1} {
298             .d.csr.csr.e delete 0 end
299             set cur_mode text
300             recursor
301         }
302     }
303     helptext {
304         {{<- ->}   {move cursor, adjusting area to define}}
305         {Space     {switch to moving other cursor}}
306         {Return    {confirm location, enter letter(s)}}
307         {Tab       {switch to correcting earlier ocr}}
308         {Q         {quit and abandon OCR run}}
309     }
310 }
311 proc othercursor {} {
312     global cur_mode
313     set cur_mode [expr {!$cur_mode}]
314     recursor
315 }
316
317 proc recursor/text {} {
318     helptext {
319         {Return   {confirm entry of new glyph}}
320         {Escape   {abandon entry}}
321     }
322     unbind_all_keys
323     .d.csr.csr.l configure -text {define:}
324     pack .d.csr.csr.e -side left
325     focus .d.csr.csr.e
326     bind_key Return {
327         set strq [.d.csr.csr.e get]
328         if {[regexp {^(?:[!-[]|[]-~]|\\\\|\\x[0-9a-f]{2})+} $strq]} {
329             RETURN_RESULT DEFINE "$cur_0 $cur_1 $strq"
330         }
331     }
332     bind_key Escape {
333         bind_key Escape {}
334         pack forget .d.csr.csr.e
335         set cur_mode 1
336         recursor
337     }
338 }
339
340 proc recursor/already {} {
341     global mul
342     global glyphsdone
343     global cur_already mul
344     global glyphsdone cur_already mul
345     .d.csr.csr.l configure -text {correct}
346     set rmax [lindex $glyphsdone [expr {$cur_already*4}]]
347     place .d.csr.csr -x [expr {$rmax*$mul-3}]
348     bind_key Return {}
349     bind_key space {}
350     bind_leftright_q cur_already 0 [expr {[llength $glyphsdone]/4-1}]
351     bind_key Tab { bind_key Delete {}; set cur_mode 1; recursor }
352     bind_key Delete {
353         RETURN_RESULT DELETE [lrange $glyphsdone \
354                                   [expr $cur_already*4] \
355                                   [expr $cur_already*4+2]]
356     }
357     helptext {
358         {{<- ->}   {move cursor, selecting glyph to correct}}
359         {Del       {clear this glyph from the recognition database}}
360         {Tab       {switch to selecting area to define as new glyph}}
361         {Q         {quit and abandon OCR run}}
362     }
363 }
364
365 proc bind_key {k proc} {
366     global keybindings
367     bind . <Key-$k> $proc
368     set keybindings($k) [expr {!![string length $proc]}]
369 }
370 proc unbind_all_keys {} {
371     global keybindings
372     foreach k [array names keybindings] { bind_key $k {} }
373 }
374
375 proc bind_leftright_q {var min max} {
376     bind_key Left  [list leftright $var $min $max -1]
377     bind_key Right [list leftright $var $min $max +1]
378     bind_key q     {
379         puts stderr "\nCharacter resolver quitting as you requested."
380         exit 1
381     }
382 }
383 proc leftright {var min max inc} {
384     upvar #0 $var v
385     set vnew $v
386     incr vnew $inc
387     if {$vnew < $min || $vnew > $max} return
388     set v $vnew
389     recursor
390 }
391
392 proc recursor {} {
393     global csrh cur_mode cur_0 cur_1 mul
394     foreach z1 {0 1} {
395         place .d.mi.csr_$z1 -y 0 -x [expr {[set cur_$z1] * $mul}]
396     }
397     recursor/$cur_mode
398 }
399
400
401 #---------- database read and write ----------
402
403 # OUT OF DATE
404 # database format:
405 # series of glyphs:
406 #   <context> <ncharacters> <hex>...
407 #   width
408 #   <hex-bitmap>
409
410 # $database($context 0x<bits> 0x<bits>...) = $hex
411
412 set database_header {# ypp-sc-tools pctb font v1}
413
414 proc db_getsl {f} {
415     if {[gets $f l] < 0} { error "unexpected db eof" }
416     return $l
417 }
418     
419 proc read_database {} {
420     global database database_header rows database_fn
421     catch { unset database }
422     set database_fn ./charset-$rows.txt
423     if {![file exists $database_fn]} return
424     set f [open $database_fn r]
425     if {[string compare [db_getsl $f] $database_header]} { error "$l ?" }
426     if {([db_getsl $f])+0 != $rows} { error "wrong h ?" }
427     while 1 {
428         set context [db_getsl $f]
429         if {![string length $context]} continue
430         if {[regexp {^\#} $context]} continue
431         if {![string compare . $context]} break
432
433         set bm $context
434         set strq [db_getsl $f]
435         while 1 {
436             set l [db_getsl $f]
437             if {![string length $l]} break
438             lappend bm [format %x 0x$l]
439         }
440         set database($bm) $strq
441     }
442     close $f
443 }
444
445 proc write_database {} {
446     global database rows database_fn database_header
447     set ol {}
448     foreach bm [array names database] {
449         set strq $database($bm)
450         set o "[lindex $bm 0]\n$strq\n"
451         foreach x [lrange $bm 1 end] { append o "$x\n" }
452         
453         lappend ol $o
454     }
455     set f [open $database_fn.new w]
456     puts $f "$database_header\n$rows\n"
457     foreach o [lsort $ol] {
458         puts $f $o
459     }
460     puts $f "."
461     close $f
462     file rename -force $database_fn.new $database_fn
463 }
464
465 proc dbkey {ctx l r} {
466     global wordmap
467     set bm $ctx
468     for {set x $l} {$x <= $r} {incr x} {
469         lappend bm [format %x $wordmap($x)]
470     }
471     return $bm
472 }
473
474 proc update_database/DEFINE {c0 c1 strq} {
475     global glyphsdone unk_l unk_contexts wordmap database
476     if {$c0 > $c1} { manyset [list $c0 $c1] c1 c0 }
477     if {$c0 == $unk_l} {
478         set ncontexts $unk_contexts
479     } else {
480         foreach {l r contexts got} $glyphsdone {
481             if {$l==$c0} { set ncontexts $contexts; break }
482         }
483         if {![info exists ncontexts]} {
484             puts stderr "must start at letter LHS!"
485             return
486         }
487     }
488     incr c1 -1
489     foreach c $ncontexts {
490         set bm [dbkey $c $c0 $c1]
491         set database($bm) $strq
492     }
493     write_database
494 }
495
496 proc update_database/DELETE {l r ctxs} {
497     global database
498     foreach ctx $ctxs {
499         set bm [dbkey $ctx $l $r]
500         catch { unset database($bm) }
501     }
502     write_database
503 }
504     
505
506 proc RETURN_RESULT {how what} {
507     global mainkind
508     place forget .d.csr.csr
509     pack forget .d.csr.csr.e
510     helptext {{{ Processing }}}
511     unbind_all_keys
512     update idletasks
513     debug "$how $what"
514     eval update_database/$how $what
515     done/$mainkind
516 }
517
518 #---------- main progrm ----------
519
520 proc main/default {} {
521     puts stderr "Do not run this program directly."
522     exit 12
523     
524     global glyphsdone unk_l unk_r unk_contexts
525
526     set glyphsdone {
527         7 11 1 M
528         13 17 0 a
529         19 23 0 n
530     }
531     set unk_l 25
532     set unk_r 29
533     set unk_contexts Test
534
535     set f [open text.xpm]
536     read_xpm $f
537     close $f
538
539     read_database
540     resize_widgets
541     draw_glyphsdone
542     startup_cursor
543 }
544 proc done/default {} {
545 }
546
547 proc required {} {
548     global glyphsdone unk_l unk_r unk_contexts
549     
550     if {[gets stdin l]<0} {
551         if {[eof stdin]} { fconfigure stdin -blocking yes; exit 0 }
552         return
553     }
554     init_widgets
555     manyset [lrange $l 0 3] unk_l unk_r unk_contexts
556     set glyphsdone [lrange $l 3 end]
557     debug "GOT $l"
558
559     fileevent stdin readable {}
560     fconfigure stdin -blocking yes
561
562     read_xpm stdin
563     resize_widgets
564     read_database
565     draw_glyphsdone
566     startup_cursor
567 }
568
569 proc main/automatic {} {
570     fconfigure stdin -blocking no
571     fileevent stdin readable required
572 }
573 proc done/automatic {} {
574     exec sh -c {printf \\0 >&4}
575     main/automatic
576 }
577
578 proc debug {m} { }
579
580 set mainkind default
581 foreach arg $argv {
582     switch -exact -- $arg {
583         {--debug}        { proc debug {m} { puts stderr "SHOW-THING $m" } }
584         {--noop-arg}     { }
585         {--automatic-1}  { set mainkind automatic }
586         {--automatic*}   { error "incompatible versions - install problem" }
587         default          { error "huh $argv ?" }
588     }
589 }
590
591 main/$mainkind