-
Notifications
You must be signed in to change notification settings - Fork 66
/
toolbox.py
2537 lines (2114 loc) · 72.2 KB
/
toolbox.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from traceback import format_exc
class GRPException(Exception):
def __init__(self,msg):
if type(msg)==type(u"abc"):
self.utf_msg=msg
self.str_msg=msg.encode("utf-8",errors='replace')
else:
self.str_msg=msg
self.utf_msg=msg.decode("utf-8",errors='replace')
log("===")
log(format_exc())
log("===")
Exception.__init__(self,self.str_msg)
def __unicode__(self):
return self.utf_msg
import threading
import codecs
loglock=threading.Lock()
def log(*args):
global loglock
loglock.acquire()
encoding=sys.stdout.encoding
for arg in args:
try:
if type(arg)==type(str('abc')):
arg=arg.decode('utf-8',errors='replace')
elif type(arg)!=type(u'abc'):
try:
arg=str(arg)
except:
arg=unicode(arg,errors='replace')
arg=arg.decode('utf-8',errors='replace')
arg=arg.encode(encoding, errors='replace')
print arg,
except:
print "?"*len(arg),
print
loglock.release()
def linelog(*args):
global loglock
loglock.acquire()
encoding=sys.stdout.encoding
for arg in args:
try:
if type(arg)==type(str('abc')):
arg=arg.decode('utf-8',errors='replace')
elif type(arg)!=type(u'abc'):
try:
arg=str(arg)
except:
arg=unicode(arg,errors='replace')
arg=arg.decode('utf-8',errors='replace')
arg=arg.encode(encoding, errors='replace')
print arg,
except:
print "?"*len(arg),
loglock.release()
import tkMessageBox
def show_error(txt,parent=None):
if type(txt)==type(str('abc')):
txt=txt.decode('utf-8',errors='replace')
try:
tkMessageBox.showerror(_("Error"),txt,parent=parent)
log("ERROR: "+txt)
except:
log("ERROR: "+txt)
def show_info(txt,parent=None):
if type(txt)==type(str('abc')):
txt=txt.decode('utf-8',errors='replace')
try:
tkMessageBox.showinfo(_("Information"),txt,parent=parent)
log("INFO: "+txt)
except:
log("INFO: "+txt)
def get_moves_number(move_zero):
k=0
move=move_zero
while move:
move=move[0]
k+=1
return k
def go_to_move(move_zero,move_number=0):
if move_number==0:
return move_zero
move=move_zero
k=0
while k!=move_number:
if not move:
log("The end of the sgf tree was reached before getting to move_number",move_number)
log("Could only reach move_number",k)
return False
move=move[0]
k+=1
return move
def gtp2ij(move):
try:
letters="ABCDEFGHJKLMNOPQRSTUVWXYZ"
return int(move[1:])-1,letters.index(move[0])
except:
raise GRPException("Cannot convert GTP coordinates "+str(move)+" to grid coordinates!")
def ij2gtp(m):
# (17,0) => a18
try:
if m==None:
return "pass"
i,j=m
letters="ABCDEFGHJKLMNOPQRSTUVWXYZ"
return letters[j]+str(i+1)
except:
raise GRPException("Cannot convert grid coordinates "+str(m)+" to GTP coordinates!")
def sgf2ij(m):
# cj => 8,2
a, b=m
letters="abcdefghjklmnopqrstuvwxyz"
i=letters.index(b)
j=letters.index(a)
return i, j
def ij2sgf(m):
# (17,0) => ???
try:
if m==None:
return "pass"
i,j=m
letters=['a','b','c','d','e','f','g','h','j','k','l','m','n','o','p','q','r','s','t']
return letters[j]+letters[i]
except:
raise GRPException("Cannot convert grid coordinates "+str(m)+" to SGF coordinates!")
from gomill import sgf, sgf_moves
from Tkinter import *
#from Tix import Tk, NoteBook
from Tkconstants import *
import sys
import os
import urllib2
class DownloadFromURL(Toplevel):
def __init__(self,parent,bots=None):
Toplevel.__init__(self,parent)
self.bots=bots
self.parent=parent
self.title('GoReviewPartner')
self.config(padx=10,pady=10)
Label(self,text=_("Paste the URL to the SGF file (http or https):")).grid(row=1,column=1,sticky=W)
self.url_entry=Entry(self)
self.url_entry.grid(row=2,column=1,sticky=W)
self.url_entry.focus()
Button(self,text=_("Get"),command=self.get).grid(row=3,column=1,sticky=E)
self.protocol("WM_DELETE_WINDOW", self.close)
def get(self):
user_agent = 'GoReviewPartner (https://github.com/pnprog/goreviewpartner/)'
headers = { 'User-Agent' : user_agent }
url=self.url_entry.get()
if not url:
return
if url[:4]!="http":
url="http://"+url
log("Downloading",url)
r=urllib2.Request(url,headers=headers)
try:
h=urllib2.urlopen(r)
except:
show_error(_("Could not open the URL"),parent=self)
return
filename=""
sgf=h.read()
if sgf[:7]!="(;FF[4]":
log("not a sgf file")
show_error(_("Not a valid SGF file!"),parent=self)
log(sgf[:7])
return
try:
filename=h.info()['Content-Disposition']
if 'filename="' in filename:
filename=filename.split('filename="')[0][:-1]
if "''" in filename:
filename=filename.split("''")[1]
except:
log("no Content-Disposition in header")
black='black'
white='white'
date=""
if 'PB[' in sgf:
black=sgf.split('PB[')[1].split(']')[0]
if 'PW[' in sgf:
white=sgf.split('PW[')[1].split(']')[0]
if 'DT[' in sgf:
date=sgf.split('DT[')[1].split(']')[0]
filename=""
if date:
filename=date+'_'
filename+=black+'_VS_'+white+'.sgf'
log(filename)
game = convert_sgf_to_utf(sgf)
write_rsgf(filename,game)
popup=RangeSelector(self.parent,filename,self.bots)
self.parent.add_popup(popup)
self.close()
def close(self):
log("Closing DownloadFromURL()")
self.parent.remove_popup(self)
self.destroy()
filelock=threading.Lock()
c=0
def write_rsgf(filename,sgf_content):
filelock.acquire()
global c
try:
#log("Saving RSGF file",filename)
if type(sgf_content)==type("abc"):
content=sgf_content
else:
content=sgf_content.serialise()
filename2=filename
if type(filename2)==type(u"abc"):
if sys.getfilesystemencoding()!="mbcs":
filename2=filename2.encode(sys.getfilesystemencoding())
try:
new_file=open(filename2,'w')
new_file.write(content)
except:
new_file=codecs.open(filename2,"w","utf-8")
new_file.write(content)
new_file.close()
filelock.release()
except IOError, e:
filelock.release()
log("Could not save the RSGF file",filename)
log("=>", e.errno,e.strerror)
raise GRPException(_("Could not save the RSGF file: ")+filename+"\n"+e.strerror)
except Exception,e:
filelock.release()
log("Could not save the RSGF file",filename)
log("=>",e)
raise GRPException(_("Could not save the RSGF file: ")+filename+"\n"+unicode(e))
def write_sgf(filename,sgf_content):
filelock.acquire()
try:
log("Saving SGF file",filename)
if type(sgf_content)==type("abc"):
content=sgf_content
else:
content=sgf_content.serialise()
filename2=filename
if type(filename2)==type(u"abc"):
if sys.getfilesystemencoding()!="mbcs":
filename2=filename2.encode(sys.getfilesystemencoding())
try:
new_file=open(filename2,'w')
new_file.write(content)
except:
new_file=codecs.open(filename2,"w","utf-8")
new_file.write(content)
new_file.close()
filelock.release()
except IOError, e:
filelock.release()
log("Could not save the SGF file",filename)
log("=>", e.errno,e.strerror)
raise GRPException(_("Could not save the RSGF file: ")+filename+"\n"+e.strerror)
except Exception,e:
filelock.release()
log("Could not save the RSGF file",filename)
log("=>",e)
raise GRPException(_("Could not save the SGF file: ")+filename+"\n"+unicode(e))
def convert_sgf_to_utf(content):
game = sgf.Sgf_game.from_string(content)
gameroot=game.get_root()
sgf_moves.indicate_first_player(game) #adding the PL property on the root
if node_has(gameroot,"CA"):
ca=node_get(gameroot,"CA")
if ca=="UTF-8":
#the sgf is already in UTF, so we accept it directly
return game
else:
log("Encoding is",ca)
log("Converting from",ca,"to UTF-8")
encoding=(codecs.lookup(ca).name.replace("_", "-").upper().replace("ISO8859", "ISO-8859")) #from gomill code
content=game.serialise()
content=content.decode(encoding,errors='ignore') #transforming content into a unicode object
content=content.replace("CA["+ca+"]","CA[UTF-8]")
game = sgf.Sgf_game.from_string(content.encode("utf-8")) #sgf.Sgf_game.from_string requires str object, not unicode
return game
else:
log("the sgf has no declared encoding, we will enforce UTF-8 encoding")
content=game.serialise()
content=content.decode("utf",errors="replace").encode("utf")
game = sgf.Sgf_game.from_string(content,override_encoding="UTF-8")
return game
def open_sgf(filename):
filelock.acquire()
try:
#log("Opening SGF file",filename)
filename2=filename
if type(filename2)==type(u"abc"):
if sys.getfilesystemencoding()!="mbcs":
filename2=filename2.encode(sys.getfilesystemencoding())
txt = open(filename2,'r')
content=clean_sgf(txt.read())
txt.close()
filelock.release()
game = convert_sgf_to_utf(content)
return game
except IOError, e:
filelock.release()
log("Could not open the SGF file",filename)
log("=>", e.errno,e.strerror)
raise GRPException(_("Could not open the RSGF file: ")+filename+"\n"+e.strerror)
except Exception,e:
log("Could not open the SGF file",filename)
log("=>",e)
try:
filelock.release()
except:
pass
raise GRPException(_("Could not open the SGF file: ")+filename+"\n"+unicode(e))
def clean_sgf(txt):
#txt is still of type str here....
#https://github.com/pnprog/goreviewpartner/issues/56
txt=txt.replace(str(";B[ ])"),str(";B[])")).replace(str(";W[ ])"),str(";W[])"))
#https://github.com/pnprog/goreviewpartner/issues/71
txt=txt.replace(str("KM[]"),str(""))
txt=txt.replace(str("B[**];"),str("B[];")).replace(str("W[**];"),str("W[];"))
return txt
def get_all_sgf_leaves(root,deep=0):
if len(root)==0:
#this is a leave
return [(root,deep)]
leaves=[]
deep+=1
for leaf in root:
leaves.extend(get_all_sgf_leaves(leaf,deep))
return leaves
def keep_only_one_leaf(leaf):
while 1:
try:
parent=leaf.parent
for other_leaf in parent:
if other_leaf!=leaf:
log("deleting...")
other_leaf.delete()
leaf=parent
except:
#reached root
return
def check_selection(selection,nb_moves):
move_selection=[]
selection=selection.replace(" ","")
for sub_selection in selection.split(","):
if sub_selection:
try:
if "-" in sub_selection:
a,b=sub_selection.split('-')
a=int(a)
b=int(b)
else:
a=int(sub_selection)
b=a
if a<=b and a>0 and b<=nb_moves:
move_selection.extend(range(a,b+1))
except Exception, e:
print e
return False
move_selection=list(set(move_selection))
move_selection=sorted(move_selection)
return move_selection
def check_selection_for_color(move_zero,move_selection,color):
if color=="black":
new_move_selection=[]
for m in move_selection:
player_color=guess_color_to_play(move_zero,m)
if player_color.lower()=='b':
new_move_selection.append(m)
return new_move_selection
elif color=="white":
new_move_selection=[]
for m in move_selection:
player_color=guess_color_to_play(move_zero,m)
if player_color.lower()=='w':
new_move_selection.append(m)
return new_move_selection
else:
return move_selection
class RangeSelector(Toplevel):
def __init__(self,parent,filename,bots=None):
Toplevel.__init__(self,parent)
self.parent=parent
self.filename=filename
self.config(padx=10,pady=10)
root = self
root.parent.title('GoReviewPartner')
self.protocol("WM_DELETE_WINDOW", self.close)
self.bots=bots
self.g=open_sgf(self.filename)
self.move_zero=self.g.get_root()
nb_moves=get_moves_number(self.move_zero)
self.nb_moves=nb_moves
row=0
Label(self,text="").grid(row=row,column=1)
row+=1
Label(self,text=_("Bot to use for analysis:")).grid(row=row,column=1,sticky=N+W)
#value={"slow":" (%s)"%_("Slow profile"),"fast":" (%s)"%_("Fast profile")}
bot_names=[bot['name']+" - "+bot['profile'] for bot in bots]
self.bot_selection=StringVar()
if not bot_names:
Label(self,text=_("There is no bot configured in Settings")).grid(row=row,column=2,sticky=W)
else:
botOptionMenu = apply(OptionMenu,(self, self.bot_selection)+tuple(bot_names))
botOptionMenu.config(width=20)
botOptionMenu.grid(row=row,column=2,sticky=W)
self.bot_selection.set(bot_names[0])
analyser=grp_config.get("Analysis","analyser")
if analyser in bot_names:
self.bot_selection.set(analyser)
row+=1
Label(self,text="").grid(row=row,column=1)
row+=1
variation_label_widget=Label(self,text=_("Select variation to be analysed"))
self.leaves=get_all_sgf_leaves(self.move_zero)
self.variation_selection=StringVar()
self.variation_selection.trace("w", self.variation_changed)
options=[]
v=1
for unused,deep in self.leaves:
options.append(_("Variation %i (%i moves)")%(v,deep))
v+=1
self.variation_selection.set(options[0])
variation_menu_widget=apply(OptionMenu,(self,self.variation_selection)+tuple(options))
existing_variations = StringVar()
existing_variations.set("remove_everything")
if node_has(self.move_zero,"RSGF"):
existing_variations.set("keep")
row+=10
Label(self,text=_("This analysis will be performed on an already analysed SGF file.")).grid(row=row,column=1,columnspan=2,sticky=W)
row+=1
Label(self,text=_("What to do with the existing variations?")).grid(row=row,column=1,columnspan=2,sticky=W)
row+=1
d1=Radiobutton(self,text=_("Keep existing variations"),variable=existing_variations, value="keep")
d1.grid(row=row,column=1,sticky=W)
row+=1
d2=Radiobutton(self,text=_("Replace existing variations"),variable=existing_variations, value="replace")
d2.grid(row=row,column=1,sticky=W)
else:
variation_label_widget.grid(row=row,column=1,sticky=W)
variation_menu_widget.grid(row=row,column=2,sticky=W)
self.rsgf_filename=".".join(self.filename.split(".")[:-1])+".rsgf"
row+=1
Label(self,text="").grid(row=row,column=1)
row+=1
Label(self,text=_("Select moves to be analysed")).grid(row=row,column=1,sticky=W)
row+=1
s = StringVar()
s.set("all")
self.r1=Radiobutton(self,text=_("Analyse all %i moves")%nb_moves,variable=s, value="all")
self.r1.grid(row=row,column=1,sticky=W)
self.after(0,self.r1.select)
row+=1
r2=Radiobutton(self,text=_("Analyse only those moves:"),variable=s, value="only")
r2.grid(row=row,column=1,sticky=W)
only_entry=Entry(self)
only_entry.bind("<Button-1>", lambda e: r2.select())
only_entry.grid(row=row,column=2,sticky=W)
only_entry.delete(0, END)
if nb_moves>0:
only_entry.insert(0, "1-"+str(nb_moves))
row+=3
Label(self,text="").grid(row=row,column=1)
row+=1
Label(self,text=_("Select colors to be analysed")).grid(row=row,column=1,sticky=W)
c = StringVar()
c.set("both")
row+=1
c0=Radiobutton(self,text=_("Black & white"),variable=c, value="both")
c0.grid(row=row,column=1,sticky=W)
self.after(0,c0.select)
if node_has(self.move_zero,'PB'):
black_player=node_get(self.move_zero,'PB')
if black_player.lower().strip() in ['black','']:
black_player=''
else:
black_player=' ('+black_player+')'
else:
black_player=''
if node_has(self.move_zero,'PW'):
white_player=node_get(self.move_zero,'PW')
if white_player.lower().strip() in ['white','']:
white_player=''
else:
white_player=' ('+white_player+')'
else:
white_player=''
row+=1
c1=Radiobutton(self,text=_("Black only")+black_player,variable=c, value="black")
c1.grid(row=row,column=1,sticky=W)
row+=1
c2=Radiobutton(self,text=_("White only")+white_player,variable=c, value="white")
c2.grid(row=row,column=1,sticky=W)
row+=10
Label(self,text="").grid(row=row,column=1)
row+=1
Label(self,text=_("Confirm the value of komi")).grid(row=row,column=1,sticky=W)
komi_entry=Entry(self)
komi_entry.grid(row=row,column=2,sticky=W)
komi_entry.delete(0, END)
try:
komi=self.g.get_komi()
komi_entry.insert(0, str(komi))
except Exception, e:
log("Error while reading komi value, please check:\n"+unicode(e))
show_error(_("Error while reading komi value, please check:")+"\n"+unicode(e),parent=self)
komi_entry.insert(0, "0")
row+=10
Label(self,text="").grid(row=row,column=1)
row+=1
Label(self,text=_("Stop the analysis if the bot resigns")).grid(row=row,column=1,sticky=W)
StopAtFirstResign = BooleanVar(value=grp_config.getboolean('Analysis', 'StopAtFirstResign'))
StopAtFirstResignCheckbutton=Checkbutton(self, text="", variable=StopAtFirstResign,onvalue=True,offvalue=False)
StopAtFirstResignCheckbutton.grid(row=row,column=2,sticky=W)
StopAtFirstResignCheckbutton.var=StopAtFirstResign
self.StopAtFirstResign=StopAtFirstResign
row+=10
Label(self,text="").grid(row=row,column=1)
row+=1
start_button=Button(self,text=_("Start"),command=self.start)
start_button.grid(row=row,column=2,sticky=E)
if not bot_names:
start_button.config(state="disabled")
self.mode=s
self.color=c
self.existing_variations=existing_variations
self.nb_moves=nb_moves
self.only_entry=only_entry
self.komi_entry=komi_entry
self.focus()
self.parent.focus()
def variation_changed(self,*unused):
log("variation changed!",self.variation_selection.get())
try:
self.after(0,self.r1.select)
variation=int(self.variation_selection.get().split(" ")[1])-1
deep=self.leaves[variation][1]
self.only_entry.delete(0, END)
if deep>0:
self.only_entry.insert(0, "1-"+str(deep))
self.r1.config(text=_("Analyse all %i moves")%deep)
self.nb_moves=deep
except:
pass
def close(self):
self.destroy()
self.parent.remove_popup(self)
def start(self):
#if self.nb_moves==0:
# show_error(_("This variation is empty (0 move), the analysis cannot be performed!"),parent=self)
# return
try:
komi=float(self.komi_entry.get())
except:
show_error(_("Incorrect value for komi (%s), please double check.")%self.komi_entry.get(),parent=self)
return
if self.bots!=None:
bot=self.bot_selection.get()
log("bot selection:",bot)
bot={bot['name']+" - "+bot['profile']:bot for bot in self.bots}[bot]
RunAnalysis=bot['runanalysis']
if self.mode.get()=="all":
intervals="all moves"
move_selection=range(1,self.nb_moves+1)
else:
selection = self.only_entry.get()
intervals="moves "+selection
move_selection=check_selection(selection,self.nb_moves)
if move_selection==False:
show_error(_("Could not make sense of the moves range.")+"\n"+_("Please indicate one or more move intervals (e.g. \"10-20, 40,50-51,63,67\")"),parent=self)
return
if self.color.get()=="black":
intervals+=" (black only)"
log("black only")
elif self.color.get()=="white":
intervals+=" (white only)"
log("white only")
else:
intervals+=" (both colors)"
move_selection=check_selection_for_color(self.move_zero,move_selection,self.color.get())
log("========= move selection")
log(move_selection)
log("========= variation")
variation=int(self.variation_selection.get().split(" ")[1])-1
log(variation)
grp_config.set("Analysis","analyser",self.bot_selection.get())
grp_config.set("Analysis","StopAtFirstResign",self.StopAtFirstResign.get())
popup=RunAnalysis(self.parent,(self.filename,self.rsgf_filename),move_selection,intervals,variation,komi,bot,self.existing_variations.get())
self.parent.add_popup(popup)
self.close()
import Queue
import time
import ttk
def guess_color_to_play(move_zero,move_number):
one_move=go_to_move(move_zero,move_number)
if one_move==False:
previous_move_color=guess_color_to_play(move_zero,move_number-1)
if previous_move_color.lower()=='b':
return "w"
else:
return "b"
player_color,unused=one_move.get_move()
if player_color != None:
return player_color
if one_move is move_zero:
if node_has(move_zero,"PL"):
if node_get(move_zero,"PL").lower()=="b":
return "w"
if node_get(move_zero,"PL").lower()=="w":
return "b"
else:
return "w"
previous_move_color=guess_color_to_play(move_zero,move_number-1)
if previous_move_color.lower()=='b':
return "w"
else:
return "b"
class LiveAnalysisBase():
def __init__(self,g,rsgf_filename,profile):
self.g=g
self.rsgf_filename=rsgf_filename
self.profile=profile
self.bot=self.initialize_bot()
self.update_queue=Queue.PriorityQueue()
self.label_queue=Queue.Queue()
self.best_moves_queue=Queue.Queue()
self.move_zero=self.g.get_root()
self.no_variation_if_same_move=True
size=self.g.get_size()
log("size of the tree:", size)
self.size=size
self.no_variation_if_same_move=grp_config.getboolean('Analysis', 'NoVariationIfSameMove')
self.maxvariations=grp_config.getint("Analysis", "maxvariations")
self.stop_at_first_resign=False
self.cpu_lock=threading.Lock()
def start(self):
threading.Thread(target=self.run_live_analysis).start()
def play(self,gtp_color,gtp_move):
if gtp_color=='w':
self.bot.place_white(gtp_move)
else:
self.bot.place_black(gtp_move)
def undo(self):
self.bot.undo()
def run_live_analysis(self):
self.current_move=1
wait=0
while 1:
while wait>0:
time.sleep(0.1)
wait-=0.1
try:
priority,msg=self.update_queue.get(False)
if priority<1:
log("Analyser received a high priority message")
wait=0
self.update_queue.put((priority,msg))
except:
continue
if not self.cpu_lock.acquire(False):
time.sleep(2) #let's wait just enough time in case human player already has a move to play
continue
try:
priority,msg=self.update_queue.get(False)
except:
self.cpu_lock.release()
time.sleep(.5)
continue
if msg==None:
log("Leaving the analysis")
self.cpu_lock.release()
return
if msg=="wait":
log("Analyser iddle for five seconds")
self.cpu_lock.release()
wait=5
continue
if type(msg)==type("undo xxx"):
move_to_undo=int(msg.split()[1])
log("received undo msg for move",move_to_undo,"and beyong")
log("GTP bot is currently at move",len(self.bot.history))
while len(self.bot.history)>=move_to_undo:
log("Undoing move",len(self.bot.history),"through GTP")
self.undo()
self.current_move-=1
log("Deleting the SGF branch")
parent=go_to_move(self.move_zero,move_to_undo-1)
new_branch=parent[0]
old_branch=parent[1]
for p in ["ES","CBM","BWWR","VNWR", "MCWR","UBS","LBS","C"]:
if node_has(old_branch,p):
node_set(new_branch,p,node_get(old_branch,p))
old_branch.delete()
write_rsgf(self.rsgf_filename,self.g)
self.cpu_lock.release()
self.update_queue.put((0,"wait"))
self.best_moves_queue.put((priority,msg))#sending echo
continue
log("Analyser received msg to analyse move",msg)
while msg>self.current_move:
log("Analyser currently at move",self.current_move)
log("So asking "+self.bot.bot_name+" to play the game move",self.current_move)
one_move=go_to_move(self.move_zero,self.current_move)
player_color,player_move=one_move.get_move()
log("game move",self.current_move,"is",player_color,"at",player_move)
if player_color in ('w',"W"):
log("white at",ij2gtp(player_move))
self.play("w",ij2gtp(player_move))
else:
log("black at",ij2gtp(player_move))
self.play("b",ij2gtp(player_move))
self.current_move+=1
log("Analyser is currently at move",self.current_move)
self.label_queue.put(self.current_move)
log("starting analysis of move",self.current_move)
answer=self.run_analysis(self.current_move)
log("Analyser best move: move %i at %s"%(self.current_move,answer))
self.best_moves_queue.put([self.current_move,answer])
try:
game_move=go_to_move(self.move_zero,self.current_move).get_move()[1]
log("Game move:",game_move)
if game_move:
if self.no_variation_if_same_move:
if ij2gtp(game_move)==answer:
log("Bot move and game move are the same ("+answer+"), removing variations for this move")
parent=go_to_move(self.move_zero,self.current_move-1)
for child in parent[1:]:
child.delete()
except:
#what could possibly go wrong with this?
pass
if self.update_queue.empty():
self.label_queue.put("")
write_rsgf(self.rsgf_filename,self.g)
self.cpu_lock.release()
#self.current_move+=1
time.sleep(.1) #enought time for Live analysis to grap the lock
class RunAnalysisBase(Toplevel):
def __init__(self,parent,filenames,move_range,intervals,variation,komi,profile,existing_variations="remove_everything"):
if parent!="no-gui":
Toplevel.__init__(self,parent)
self.parent=parent
self.filename=filenames[0]
self.rsgf_filename=filenames[1]
self.move_range=move_range
self.update_queue=Queue.Queue(1)
self.intervals=intervals
self.variation=variation
self.komi=komi
self.profile=profile
self.g=None
self.move_zero=None
self.current_move=None
self.time_per_move=None
self.existing_variations=existing_variations
self.no_variation_if_same_move=grp_config.getboolean('Analysis', 'NoVariationIfSameMove')
self.error=None
try:
self.g=open_sgf(self.filename)
self.move_zero=self.g.get_root()
self.max_move=get_moves_number(self.move_zero)
if existing_variations=="remove_everything":
leaves=get_all_sgf_leaves(self.g.get_root())
log("keeping only variation",self.variation)
keep_only_one_leaf(leaves[self.variation][0])
else:
log("analysis will be performed on first variation")
if existing_variations=="keep":
move=1
log("checking for moves already analysed")
already_analysed=[]
while move<=self.max_move:
if move in self.move_range:
node=go_to_move(self.move_zero,move)
if len(node.parent)>1:
already_analysed.append(move)
move+=1
log("The following moves are already analysed and will be skipped")
log(already_analysed)
for move in already_analysed:
self.move_range.remove(move)
if not self.move_range:
self.move_range=["empty"]
size=self.g.get_size()
log("size of the tree:", size)
self.size=size
log("Setting new komi")
node_set(self.g.get_root(),"KM",self.komi)
except Exception,e:
self.error=unicode(e)
self.abort()
return
try:
self.bot=self.initialize_bot()
except Exception,e:
self.error=_("Error while initializing the GTP bot:")+"\n"+unicode(e)
self.abort()
return
if not self.bot:
return
self.total_done=0
if parent!="no-gui":
try:
self.initialize_UI()
except Exception,e:
self.error=_("Error while initializing the graphical interface:")+"\n"+unicode(e)
self.abort()
return
self.root.after(500,self.follow_analysis)
first_comment=_("Analysis by GoReviewPartner")
first_comment+="\n"+_("Bot")+(": %s/%s"%(self.bot.bot_name,self.bot.bot_version))
first_comment+="\n"+_("Komi")+(": %0.1f"%self.komi)
first_comment+="\n"+_("Intervals")+(": %s"%self.intervals)
if grp_config.getboolean('Analysis', 'SaveCommandLine'):
first_comment+="\n"+(_("Command line")+": %s"%self.bot.command_line)
first_comment+="\n"
node_set(self.move_zero,"RSGF",first_comment)
node_set(self.move_zero,"BOT",self.bot.bot_name)
node_set(self.move_zero,"BOTV",self.bot.bot_version)
self.maxvariations=grp_config.getint("Analysis", "maxvariations")
try: