]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/gen_badges.py
Fixed bug in "wins" query
[xonotic/xonstat.git] / xonstat / batch / badges / gen_badges.py
1 #-*- coding: utf-8 -*-
2
3 import sys
4 import re
5 import cairo as C
6 import sqlalchemy as sa
7 import sqlalchemy.sql.functions as func
8 from datetime import datetime
9 from mako.template import Template
10 from os import system
11 from pyramid.paster import bootstrap
12 from xonstat.models import *
13 from xonstat.views.player import player_info_data
14 from xonstat.util import qfont_decode, _all_colors
15 from colorsys import rgb_to_hls, hls_to_rgb
16
17
18 # similar to html_colors() from util.py
19 _contrast_threshold = 0.5
20
21 _dec_colors = [ (0.5,0.5,0.5),
22                 (1.0,0.0,0.0),
23                 (0.2,1.0,0.0),
24                 (1.0,1.0,0.0),
25                 (0.2,0.4,1.0),
26                 (0.2,1.0,1.0),
27                 (1.0,0.2,102),
28                 (1.0,1.0,1.0),
29                 (0.6,0.6,0.6),
30                 (0.5,0.5,0.5)
31             ]
32
33
34 # maximal number of query results (for testing, set to 0 to get all)
35 NUM_PLAYERS = 50
36
37 # image dimensions (likely breaks layout if changed)
38 WIDTH   = 560
39 HEIGHT  = 70
40
41 # output filename, parameter is player id
42 OUTPUT = "output/%d.png"
43
44
45 NICK_POS        = (5,18)
46 NICK_MAXWIDTH   = 330
47
48 GAMES_POS       = (60,35)
49 GAMES_WIDTH     = 110
50
51 WINLOSS_POS     = (508,6)
52 WINLOSS_WIDTH   = 104
53
54 KILLDEATH_POS   = (390,6)
55 KILLDEATH_WIDTH = 104
56
57 PLAYTIME_POS    = (452,64)
58 PLAYTIME_WIDTH  = 218
59
60
61 # parameters to affect the output, could be changed via URL
62 params = {
63     'bg':           1,                      # 0 - black, 1 - dark_wall, ...
64     'overlay':      0,                      # 0 - none, 1 - default overlay, ...
65     'font':         0,                      # 0 - xolonium, 1 - dejavu sans
66 }
67
68
69 # parse cmdline parameters (for testing)
70 for arg in sys.argv[1:]:
71     try:
72         k,v = arg.split("=")
73         if params.has_key(k.lower()):
74             params[k] = int(v)
75     except:
76         continue
77
78
79 def get_data(player):
80     """Return player data as dict.
81     
82     This function is similar to the function in player.py but more optimized
83     for this purpose.
84     """
85
86     # total games
87     # wins/losses
88     # kills/deaths
89     # duel/dm/tdm/ctf elo + rank
90     
91     player_id = player.player_id
92     
93     total_stats = {}
94     
95     games_played = DBSession.query(
96             Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
97             filter(Game.game_id == PlayerGameStat.game_id).\
98             filter(PlayerGameStat.player_id == player_id).\
99             group_by(Game.game_type_cd).\
100             order_by(func.count().desc()).\
101             limit(3).all()  # limit to 3 gametypes!
102     
103     total_stats['games'] = 0
104     total_stats['games_breakdown'] = {}  # this is a dictionary inside a dictionary .. dictception?
105     total_stats['games_alivetime'] = {}
106     total_stats['gametypes'] = []
107     for (game_type_cd, games, alivetime) in games_played:
108         total_stats['games'] += games
109         total_stats['gametypes'].append(game_type_cd)
110         total_stats['games_breakdown'][game_type_cd] = games
111         total_stats['games_alivetime'][game_type_cd] = alivetime
112     
113     (total_stats['kills'], total_stats['deaths'], total_stats['alivetime'],) = DBSession.query(
114             func.sum(PlayerGameStat.kills),
115             func.sum(PlayerGameStat.deaths),
116             func.sum(PlayerGameStat.alivetime)).\
117             filter(PlayerGameStat.player_id == player_id).\
118             one()
119     
120 #    (total_stats['wins'],) = DBSession.query(
121 #            func.count("*")).\
122 #            filter(Game.game_id == PlayerGameStat.game_id).\
123 #            filter(PlayerGameStat.player_id == player_id).\
124 #            filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
125 #            one()
126
127     (total_stats['wins'],) = DBSession.\
128             query("total_wins").\
129             from_statement(
130                 "select count(*) total_wins "
131                 "from games g, player_game_stats pgs "
132                 "where g.game_id = pgs.game_id "
133                 "and player_id=:player_id "
134                 "and (g.winner = pgs.team or pgs.rank = 1)"
135             ).params(player_id=player_id).one()
136     
137     ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
138             from_statement(
139                 "select pr.game_type_cd, pr.rank, overall.max_rank "
140                 "from player_ranks pr,  "
141                    "(select game_type_cd, max(rank) max_rank "
142                     "from player_ranks  "
143                     "group by game_type_cd) overall "
144                 "where pr.game_type_cd = overall.game_type_cd  "
145                 "and player_id = :player_id "
146                 "order by rank").\
147             params(player_id=player_id).all()
148     
149     ranks_dict = {}
150     for gtc,rank,max_rank in ranks:
151         ranks_dict[gtc] = (rank, max_rank)
152
153     elos = DBSession.query(PlayerElo).\
154             filter_by(player_id=player_id).\
155             order_by(PlayerElo.elo.desc()).\
156             all()
157     
158     elos_dict = {}
159     for elo in elos:
160         if elo.games > 32:
161             elos_dict[elo.game_type_cd] = elo.elo
162     
163     data = {
164             'player':player,
165             'total_stats':total_stats,
166             'ranks':ranks_dict,
167             'elos':elos_dict,
168         }
169         
170     #print data
171     return data
172
173
174 def render_image(data):
175     """Render an image from the given data fields."""
176     
177     font = "Xolonium"
178     if params['font'] == 1:
179         font = "DejaVu Sans"
180
181     total_stats = data['total_stats']
182     total_games = total_stats['games']
183     elos = data["elos"]
184     ranks = data["ranks"]
185
186
187     ## create background
188
189     surf = C.ImageSurface(C.FORMAT_RGB24, WIDTH, HEIGHT)
190     ctx = C.Context(surf)
191     ctx.set_antialias(C.ANTIALIAS_GRAY)
192
193     # draw background (just plain fillcolor)
194     if params['bg'] == 0:
195         ctx.rectangle(0, 0, WIDTH, HEIGHT)
196         ctx.set_source_rgb(0.04, 0.04, 0.04)  # bgcolor of Xonotic forum
197         ctx.fill()
198     
199     # draw background image (try to get correct tiling, too)
200     if params['bg'] > 0:
201         bg = None
202         if params['bg'] == 1:
203             bg = C.ImageSurface.create_from_png("img/dark_wall.png")
204         elif params['bg'] == 2:
205             bg = C.ImageSurface.create_from_png("img/asfalt.png")
206         elif params['bg'] == 3:
207             bg = C.ImageSurface.create_from_png("img/broken_noise.png")
208         elif params['bg'] == 4:
209             bg = C.ImageSurface.create_from_png("img/burried.png")
210         elif params['bg'] == 5:
211             bg = C.ImageSurface.create_from_png("img/dark_leather.png")
212         elif params['bg'] == 6:
213             bg = C.ImageSurface.create_from_png("img/txture.png")
214         elif params['bg'] == 7:
215             bg = C.ImageSurface.create_from_png("img/black_linen_v2.png")
216         elif params['bg'] == 8:
217             bg = C.ImageSurface.create_from_png("img/background_archer-v1.png")
218         
219         # tile image
220         if bg:
221             bg_w, bg_h = bg.get_width(), bg.get_height()
222             bg_xoff = 0
223             while bg_xoff < WIDTH:
224                 bg_yoff = 0
225                 while bg_yoff < HEIGHT:
226                     ctx.set_source_surface(bg, bg_xoff, bg_yoff)
227                     ctx.paint()
228                     bg_yoff += bg_h
229                 bg_xoff += bg_w
230     
231     # draw overlay graphic
232     if params['overlay'] > 0:
233         overlay = None
234         if params['overlay'] == 1:
235             overlay = C.ImageSurface.create_from_png("img/overlay.png")
236         if overlay:
237             ctx.set_source_surface(overlay, 0, 0)
238             ctx.mask_surface(overlay)
239             ctx.paint()
240
241
242     ## draw player's nickname with fancy colors
243     
244     # deocde nick, strip all weird-looking characters
245     qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '').replace(u' ', '    ')
246     chars = []
247     for c in qstr:
248         if ord(c) < 128:
249             chars.append(c)
250     qstr = ''.join(chars)
251     stripped_nick = strip_colors(qstr)
252     
253     # fontsize is reduced if width gets too large
254     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
255     ctx.set_font_size(20)
256     xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
257     if tw > NICK_MAXWIDTH:
258         ctx.set_font_size(18)
259         xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
260         if tw > NICK_MAXWIDTH:
261             ctx.set_font_size(16)
262             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
263             if tw > NICK_MAXWIDTH:
264                 ctx.set_font_size(14)
265                 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
266                 if tw > NICK_MAXWIDTH:
267                     ctx.set_font_size(12)
268     
269     
270     # split up nick into colored segments and draw each of them
271     
272     # split nick into colored segments
273     xoffset = 0
274     _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
275     #print qstr, _all_colors.findall(qstr), _all_colors.split(qstr)
276     
277     parts = _all_colors.split(qstr)
278     while len(parts) > 0:
279         tag = None
280         txt = parts[0]
281         if _all_colors.match(txt):
282             tag = txt[1:]  # strip leading '^'
283             if len(parts) < 2:
284                 break
285             txt = parts[1]
286             del parts[1]
287         del parts[0]
288             
289         if not txt or len(txt) == 0:
290             # only colorcode and no real text, skip this
291             continue
292             
293         r,g,b = _dec_colors[7]
294         try:
295             if tag.startswith('x'):
296                 r = int(tag[1] * 2, 16) / 255.0
297                 g = int(tag[2] * 2, 16) / 255.0
298                 b = int(tag[3] * 2, 16) / 255.0
299                 hue, light, satur = rgb_to_hls(r, g, b)
300                 if light < _contrast_threshold:
301                     light = _contrast_threshold
302                     r, g, b = hls_to_rgb(hue, light, satur)
303             else:
304                 r,g,b = _dec_colors[int(tag[0])]
305         except:
306             r,g,b = _dec_colors[7]
307         
308         ctx.set_source_rgb(r, g, b)
309         ctx.move_to(NICK_POS[0] + xoffset, NICK_POS[1])
310         ctx.show_text(txt)
311
312         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
313         tw += (len(txt)-len(txt.strip()))*3  # account for lost whitespaces
314         xoffset += tw + 2
315
316
317     ## print elos and ranks
318     
319     # show up to three gametypes the player has participated in
320     xoffset = 0
321     for gt in total_stats['gametypes'][:3]:
322         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
323         ctx.set_font_size(10)
324         ctx.set_source_rgb(1.0, 1.0, 1.0)
325         txt = "[ %s ]" % gt.upper()
326         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
327         ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]-yoff-4)
328         ctx.show_text(txt)
329         
330         old_aa = ctx.get_antialias()
331         ctx.set_antialias(C.ANTIALIAS_NONE)
332         ctx.set_source_rgb(0.8, 0.8, 0.8)
333         ctx.set_line_width(1)
334         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+8)
335         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+8)
336         ctx.stroke()
337         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+32)
338         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+32)
339         ctx.stroke()
340         ctx.set_antialias(old_aa)
341         
342         if not elos.has_key(gt) or not ranks.has_key(gt):
343             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
344             ctx.set_font_size(12)
345             ctx.set_source_rgb(0.8, 0.2, 0.2)
346             txt = "no stats yet!"
347             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
348             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+28-yoff-4)
349             ctx.save()
350             ctx.rotate(math.radians(-10))
351             ctx.show_text(txt)
352             ctx.restore()
353         else:
354             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
355             ctx.set_font_size(10)
356             ctx.set_source_rgb(1.0, 1.0, 0.5)
357             txt = "Elo: %.0f" % round(elos[gt], 0)
358             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
359             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+15-yoff-4)
360             ctx.show_text(txt)
361             
362             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
363             ctx.set_font_size(8)
364             ctx.set_source_rgb(0.8, 0.8, 1.0)
365             txt = "Rank %d of %d" % ranks[gt]
366             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
367             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+25-yoff-3)
368             ctx.show_text(txt)
369         
370         xoffset += GAMES_WIDTH
371
372
373     # print win percentage
374     
375     if params['overlay'] == 0:
376         ctx.rectangle(WINLOSS_POS[0]-WINLOSS_WIDTH/2, WINLOSS_POS[1]-7, WINLOSS_WIDTH, 15)
377         ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
378         ctx.fill();
379     
380     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
381     ctx.set_font_size(10)
382     ctx.set_source_rgb(0.8, 0.8, 0.8)
383     txt = "Win Percentage"
384     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
385     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]-yoff-3)
386     ctx.show_text(txt)
387     
388     wins, losses = total_stats["wins"], total_games-total_stats["wins"]
389     txt = "???"
390     try:
391         ratio = float(wins)/total_games
392         txt = "%.2f%%" % round(ratio * 100, 2)
393     except:
394         ratio = 0
395     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
396     ctx.set_font_size(12)
397     if ratio >= 0.90:
398         ctx.set_source_rgb(0.2, 1.0, 1.0)
399     elif ratio >= 0.75:
400         ctx.set_source_rgb(0.5, 1.0, 1.0)
401     elif ratio >= 0.5:
402         ctx.set_source_rgb(0.5, 1.0, 0.8)
403     elif ratio >= 0.25:
404         ctx.set_source_rgb(0.8, 1.0, 0.5)
405     else:
406         ctx.set_source_rgb(1.0, 1.0, 0.5)
407     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
408     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+18-yoff-4)
409     ctx.show_text(txt)
410     
411     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
412     ctx.set_font_size(8)
413     ctx.set_source_rgb(0.6, 0.8, 0.8)
414     txt = "%d win" % wins
415     if wins != 1:
416         txt += "s"
417     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
418     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+30-yoff-3)
419     ctx.show_text(txt)
420     ctx.set_source_rgb(0.8, 0.8, 0.6)
421     txt = "%d loss" % losses
422     if losses != 1:
423         txt += "es"
424     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
425     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+40-yoff-3)
426     ctx.show_text(txt)
427
428
429     # print kill/death ratio
430     
431     if params['overlay'] == 0:
432         ctx.rectangle(KILLDEATH_POS[0]-KILLDEATH_WIDTH/2, KILLDEATH_POS[1]-7, KILLDEATH_WIDTH, 15)
433         ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
434         ctx.fill()
435     
436     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
437     ctx.set_font_size(10)
438     ctx.set_source_rgb(0.8, 0.8, 0.8)
439     txt = "Kill Ratio"
440     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
441     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]-yoff-3)
442     ctx.show_text(txt)
443     
444     kills, deaths = total_stats['kills'] , total_stats['deaths'] 
445     txt = "???"
446     try:
447         ratio = float(kills)/deaths
448         txt = "%.3f" % round(ratio, 3)
449     except:
450         ratio = 0
451     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
452     ctx.set_font_size(12)
453     if ratio >= 3:
454         ctx.set_source_rgb(0.0, 1.0, 0.0)
455     elif ratio >= 2:
456         ctx.set_source_rgb(0.2, 1.0, 0.2)
457     elif ratio >= 1:
458         ctx.set_source_rgb(0.5, 1.0, 0.5)
459     elif ratio >= 0.5:
460         ctx.set_source_rgb(1.0, 0.5, 0.5)
461     else:
462         ctx.set_source_rgb(1.0, 0.2, 0.2)
463     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
464     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+18-yoff-4)
465     ctx.show_text(txt)
466
467     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
468     ctx.set_font_size(8)
469     ctx.set_source_rgb(0.6, 0.8, 0.6)
470     txt = "%d kill" % kills
471     if kills != 1:
472         txt += "s"
473     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
474     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+30-yoff-3)
475     ctx.show_text(txt)
476     ctx.set_source_rgb(0.8, 0.6, 0.6)
477     txt = "%d death" % deaths
478     if deaths != 1:
479         txt += "s"
480     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
481     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+40-yoff-3)
482     ctx.show_text(txt)
483
484
485     # print playing time
486     
487     if params['overlay'] == 0:
488         ctx.rectangle( PLAYTIME_POS[0]-PLAYTIME_WIDTH/2, PLAYTIME_POS[1]-7, PLAYTIME_WIDTH, 14)
489         ctx.set_source_rgba(0.8, 0.8, 0.8, 0.6)
490         ctx.fill();
491     
492     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
493     ctx.set_font_size(10)
494     ctx.set_source_rgb(0.1, 0.1, 0.1)
495     txt = "Playing time: %s" % str(total_stats['alivetime'])
496     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
497     ctx.move_to(PLAYTIME_POS[0]-xoff-tw/2, PLAYTIME_POS[1]-yoff-4)
498     ctx.show_text(txt)
499
500
501     # save to PNG
502     surf.write_to_png(OUTPUT % data['player'].player_id)
503
504
505 # environment setup
506 env = bootstrap('../../../development.ini')
507 req = env['request']
508 req.matchdict = {'id':3}
509
510 print "Requesting player data from db ..."
511 start = datetime.now()
512 players = DBSession.query(Player).\
513         filter(Player.player_id == PlayerElo.player_id).\
514         filter(Player.nick != None).\
515         filter(Player.player_id > 2).\
516         filter(Player.active_ind == True).\
517         limit(NUM_PLAYERS).all()
518 stop = datetime.now()
519 print "Query took %.2f seconds" % (stop-start).total_seconds()
520
521 print "Creating badges for %d active players ..." % len(players)
522 start = datetime.now()
523 data_time, render_time = 0,0
524 for player in players:
525     req.matchdict['id'] = player.player_id
526     
527     sstart = datetime.now()
528     #data = player_info_data(req)
529     data = get_data(player)
530     sstop = datetime.now()
531     data_time += (sstop-sstart).total_seconds()
532     
533     print "\r  #%-5d" % player.player_id,
534     sys.stdout.flush()
535
536     sstart = datetime.now()
537     render_image(data)
538     sstop = datetime.now()
539     render_time += (sstop-sstart).total_seconds()
540 print
541
542 stop = datetime.now()
543 print "Creating the badges took %.2f seconds (%.2f s per player)" % ((stop-start).total_seconds(), (stop-start).total_seconds()/float(len(players)))
544 print " Total time for getting data: %.2f s" % data_time
545 print " Total time for renering images: %.2f s" % render_time
546