-
Notifications
You must be signed in to change notification settings - Fork 0
/
BotDetails.py
429 lines (365 loc) · 18 KB
/
BotDetails.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
#!/usr/bin/env python
#import cgi
import datetime
import wsgiref.handlers
import time
#try:
# import json
#except:
# import simplejson as json
import string
import zlib
import cPickle as pickle
import marshal
#from google.appengine.ext import db
#from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import memcache
from operator import attrgetter
import structures
from structures import global_dict
from PIL import Image
import base64
import cStringIO
import numpy
class BotDetails(webapp.RequestHandler):
def get(self):
# global_dict = {}
global global_dict
starttime = time.time()
query = self.request.query_string
query = query.replace("%20"," ")
parts = query.split("&")
requests = {}
if parts[0] != "":
for pair in parts:
ab = pair.split('=')
requests[ab[0]] = ab[1]
game = requests.get("game",)
if game is None:
self.response.out.write("ERROR: RUMBLE NOT SPECIFIED IN FORMAT game=____")
return
name = requests.get("name",None)
if name is None:
self.response.out.write("ERROR: BOT NOT SPECIFIED IN FORMAT name=____")
return
lim = int(requests.get("limit","10000000"))
order = requests.get("order",None)
timing = bool(requests.get("timing",False))
api = bool(requests.get("api",False))
extraArgs = ""
if timing:
extraArgs += "&timing=1"
reverseSort = True
if order is None or order.replace(" ","") == "":
order = "Name"
reverseSort = False
elif order[0] == "-":
order = order[1:]
reverseSort = False
if order == "Latest Battle":
order = "LastUpload"
parsetime = time.time() - starttime
cached = True
keyhash = name + "|" + game
#bot = global_dict.get(keyhash,None)
#if bot is None:
bot = memcache.get(keyhash)
# global_dict[keyhash] = bot
if bot is None or bot.PairingsList is None:
bot = structures.BotEntry.get_by_key_name(keyhash)
if bot is not None:
memcache.set(keyhash,bot)
# global_dict[keyhash] = bot
cached = False
rumble = None
if not api:
rumble = global_dict.get(game,None)
if rumble is None:
rumble = memcache.get(game)
if rumble is None:
rumble = structures.Rumble.get_by_key_name(game)
if rumble is None:
self.response.out.write("RUMBLE NOT FOUND")
return
else:
global_dict[game]=rumble
memcache.set(game,rumble)
else:
global_dict[game] = rumble
if bot is None:
self.response.out.write( "ERROR. name/game combination does not exist: " + name + "/" + game)
else:
flagmap = global_dict.get(structures.default_flag_map)
if flagmap is None:
flagmap = memcache.get(structures.default_flag_map)
if flagmap is None:
flagmapholder = structures.FlagMap.get_by_key_name(structures.default_flag_map)
if flagmapholder is None:
flagmap = zlib.compress(pickle.dumps({}))
else:
flagmap = flagmapholder.InternalMap
memcache.set(structures.default_flag_map,flagmap)
global_dict[structures.default_flag_map] = flagmap
else:
global_dict[structures.default_flag_map] = flagmap
try:
flagmap = pickle.loads(zlib.decompress(flagmap))
except:
flagmap = marshal.loads(zlib.decompress(flagmap))
bots = None
if lim > 0 or not api:
try:
bots = pickle.loads(zlib.decompress(bot.PairingsList))
except:
botsDicts = marshal.loads(zlib.decompress(bot.PairingsList))
bots = [structures.ScoreSet() for _ in botsDicts]
for s,d in zip(bots,botsDicts):
s.__dict__.update(d)
removes = []
for b in bots:
lastUpload = None
try:
lastUpload = b.LastUpload
except:
b.LastUpload = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
package = string.split(b.Name,".")[0]
if package in flagmap:
b.Flag = flagmap[package]
else:
b.Flag = "NONE"
try:
b.APS = float(b.APS)
b.KNNPBI = float(b.KNNPBI)
b.NPP = float(b.NPP)
b.Battles = int(b.Battles)
except:
removes.append(b)
for b in removes:
bots.pop(bots.index(b))
package = string.split(bot.Name,".")[0]
if package in flagmap:
bot.Flag = flagmap[package]
else:
bot.Flag = "NONE"
retrievetime = time.time() - parsetime - starttime
if lim > 0:
bots = filter(lambda b: getattr(b,'Alive',True), bots)
if order not in bots[0].__dict__:
order = "Name"
bots = sorted(bots, key=attrgetter(order), reverse=reverseSort)
if api:
outs = ["{"]
outs.append("\n\"name\":\"")
outs.append(name)
outs.append("\",\n\"flag\":\"")
outs.append(bot.Flag)
outs.append("\",\n\"APS\":")
outs.append(str(bot.APS))
outs.append(",\n\"PWIN\":")
outs.append(str(50.0*float(bot.PL)/bot.Pairings + 50.0))
outs.append(",\n\"ANPP\":")
outs.append(str(bot.ANPP))
outs.append(",\n\"vote\":")
outs.append(str(bot.VoteScore))
outs.append(",\n\"survival\":")
outs.append(str(bot.Survival))
outs.append(",\n\"pairings\":")
outs.append(str(bot.Pairings))
outs.append(",\n\"battles\":")
outs.append(str(bot.Battles))
outs.append(",\n\"latest\":\"")
outs.append(str(bot.LastUpload))
outs.append("\"")
if lim > 0:
outs.append(",\n\"pairingsList\":[\n")
headings = [
"\"name\"",
"\"flag\"",
"\"rank\"",
"\"APS\"",
"\"NPP\"",
"\"survival\"",
"\"KNNPBI\"",
"\"battles\"",
"\"latest\""]
escapes = ["\"","\"","","","","","","","\""]
count = 0
for b in bots:
count += 1
if count > lim:
break
cells = [b.Name,
b.Flag,
count,
round(100.0*b.APS)*0.01,
round(100.0*b.NPP)*0.01,
round(100.0*b.Survival)*0.01,
round(100.0*b.KNNPBI)*0.01,
b.Battles,b.LastUpload]
outs.append(" {")
for i in range(len(cells)):
outs.append(headings[i])
outs.append(":")
outs.append(escapes[i])
outs.append(str(cells[i]))
outs.append(escapes[i])
outs.append(",")
outs[-1] = "},\n"
outs[-1] = "}\n]"
outs.append("\n}")
self.response.out.write(''.join(outs))
else:
sorttime = time.time() - retrievetime - parsetime - starttime
if order == "LastUpload":
order = "Latest Battle"
out = []
gameHref = "<a href=\"Rankings?game=" + game + extraArgs + "\">" + game + "</a>"
gameTitle = "Bot details of <b>" + name + "</b> in "+ gameHref + " vs. " + str(len(bots)) + " bots."
flagtag = "<img id='flag' src=\"/flags/" + bot.Flag + ".gif\"> " + structures.country_lookup[bot.Flag]
endName = name.split(" ")[0].split(".")[-1]
out.append(structures.html_header % (endName + " in " + game,gameTitle))
out.append("<table>\n")
out.append("<tr>\n<th>Name</th>\n<td>\n" + name + "</td>\n<th>Score Distribution</th></tr>")
out.append("<tr>\n<th>Flag</th>\n<td>\n" + flagtag + "</td><td rowspan=\"9\">")
enemyScores = pickle.loads(zlib.decompress(rumble.ParticipantsScores))
# RGB color model
# Default colors
# colorSurvival = (0,255,0)
# colorAPS = (255,0,0)
# colorAPSvsKNPBI = (0,0,255)
# Colors suggested at
# http://ksrowell.com/blog-visualizing-data/2012/02/02/optimal-colors-for-graphs/
colorSurvival = (62,150,81)
colorAPS = (204,37,41)
colorKNPBI = (57,106,177)
size = 230
a = numpy.zeros((size+1,size+1,3), dtype=numpy.uint32)
counts = numpy.zeros((size+1, size+1), dtype=numpy.uint32)
for b in bots:
eScore = enemyScores.get(b.Name,None)
if eScore:
x = int(round(eScore.APS*0.01*size))
yAPS = max(0,min(size,size-int(round(b.APS*0.01*size))))
a[yAPS, x, :] += colorAPS
counts[yAPS,x] += 1
ySurvival = max(0,min(size,size-int(round(b.Survival*0.01*size))))
a[ySurvival, x, :] += colorSurvival
counts[ySurvival,x] += 1
yKNNPBI = max(0,min(size,size-int(round((b.KNNPBI+50)*0.01*size))))
a[yKNNPBI, x, :] += colorKNPBI
counts[yKNNPBI,x] += 1
a[counts==0,:] = 255
setVals = counts>1
for i in range(3):
a[setVals,i] = a[setVals,i]/counts[setVals]
midHeight = size - int(round(.5*size))
a[midHeight,counts[midHeight,:] == 0,:] = 127
b = Image.fromarray(a.astype("uint8"),"RGB")
c = cStringIO.StringIO()
b.save(c,format="png")
d = c.getvalue()
c.close()
e = base64.b64encode(d).decode("ascii")
out.append('<img title=\"Red = APS, Green = Survival, Blue = APS vs (KNNPBI+50)\" style=\"border: black 1px solid;\" alt="score distibution" src="data:image/png;base64,')
out.append(e)
out.append("\">")
out.append("</td></tr>")
out.append("<tr>\n<th>APS</th>\n<td>\n" + str(bot.APS) + "</td></tr>")
out.append("<tr>\n<th>PWIN</th>\n<td>\n" + str(50.0*float(bot.PL)/bot.Pairings + 50.0) + "</td></tr>")
out.append("<tr>\n<th>ANPP</th>\n<td>\n" + str(bot.ANPP) + "</td></tr>")
out.append("<tr>\n<th>Vote</th>\n<td>\n" + str(bot.VoteScore) + "</td></tr>")
out.append("<tr>\n<th>Survival</th>\n<td>\n" + str(bot.Survival) + "</td></tr>")
out.append("<tr>\n<th>Pairings</th>\n<td>\n" + str(bot.Pairings) + "</td></tr>")
out.append("<tr>\n<th>Battles</th>\n<td>\n" + str(bot.Battles) + "</td></tr>")
out.append("<tr>\n<th>Latest Battle</th>\n<td>\n" + str(bot.LastUpload) + " UTC</td></tr>")
out.append("<tr>\n<td colspan=\"2\">")
out.append("<form name=\"input\" action=\"BotCompare\" method=\"get\">")
out.append("<input type=\"hidden\" name=\"game\" value=\"" + game+ "\" />")
out.append("<input type=\"hidden\" name=\"bota\" value=\"" + name + "\" />")
out.append("<input type=\"text\" name=\"botb\" value=\"" + name + "\" />")
out.append("<input type=\"submit\" value=\"Compare\" /></form>")
out.append("</td><td>Opponent APS (X) vs. Pairing (Y) </td></tr></table>")
if lim > 0:
out.append("\n<table>\n<tr>\n")
headings = [" ",
"Flag",
"Name",
"",
"APS",
"NPP",
"Survival",
"KNNPBI",
"Battles",
"Latest Battle"]
for heading in headings:
sortedBy = (order == heading)
headinglink = heading
if sortedBy and reverseSort:
heading = "-" + heading
headinglink = heading
elif not sortedBy:
headinglink = "-" + headinglink
orderHref = "<a href=\"BotDetails?game="+game+"&name="+name.replace(" ","%20")+"&order="+ headinglink.replace(" ","%20") + extraArgs + "\">"+heading+"</a>"
if sortedBy:
out.append( "\n<th class=\"sortedby\">" + orderHref + "</th>")
else:
out.append( "\n<th>" + orderHref + "</th>")
out.append( "\n</tr>")
rank = 0
highlightKey = [False,False,False,False,True,True,True,True,False,False]
mins = [0,0,0,0,40,40,40,-0.1,0,0]
maxs = [0,0,0,0,60,70,60, 0.1,0,0]
for bot in bots:
rank += 1
if rank > lim:
break
botName=bot.Name
botNameHref = "<a href=\"BotDetails?game="+game+"&name=" + botName.replace(" ","%20")+extraArgs+"\">"+botName+" </a>"
compareHref = "<a href=\"BotCompare?game="+game+"&bota=" + name.replace(" ","%20") + "&botb=" + botName.replace(" ","%20") + extraArgs + "\">compare</a>"
ft = []
ft.append("<img id='flag' src=\"/flags/")
ft.append(bot.Flag)
ft.append(".gif\">")
flagtag = ''.join(ft)
cells = [str(rank),
flagtag,
botNameHref,
compareHref,
round(100.0*bot.APS)*0.01,
round(100.0*bot.NPP)*0.01,
round(100.0*bot.Survival)*0.01,
round(100.0*bot.KNNPBI)*0.01,
bot.Battles,
bot.LastUpload]
out.append("\n<tr>")
for i,cell in enumerate(cells):
if highlightKey[i]:
if cell < mins[i]:
out.append( "\n<td class=\"red\">" + str(cell) + "</td>")
elif cell > maxs[i]:
out.append( "\n<td class=\"green\">" + str(cell) + "</td>")
else:
out.append( "\n<td>" + str(cell) + "</td>")
else:
out.append( "\n<td>" + str(cell) + "</td>")
out.append( "\n</tr>")
out.append( "</table>")
htmltime = time.time() - sorttime - retrievetime - parsetime - starttime
elapsed = time.time() - starttime
if timing:
out.append( "<br />\n Page served in " + str(int(round(elapsed*1000))) + "ms. Bot cached: " + str(cached))
out.append("\n<br /> parsing: " + str(int(round(parsetime*1000))) )
out.append("\n<br /> retrieve: " + str(int(round(retrievetime*1000))) )
out.append("\n<br /> sort: " + str(int(round(sorttime*1000))) )
out.append("\n<br /> html generation: " + str(int(round(htmltime*1000))) )
out.append( "</body></html>")
outstr = string.join(out,"")
self.response.out.write(outstr)
application = webapp.WSGIApplication([
('/BotDetails', BotDetails)
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()