]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/gen_badges.py
Fixed some problems with playernicks in gen_badges
[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     ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
128             from_statement(
129                 "select pr.game_type_cd, pr.rank, overall.max_rank "
130                 "from player_ranks pr,  "
131                    "(select game_type_cd, max(rank) max_rank "
132                     "from player_ranks  "
133                     "group by game_type_cd) overall "
134                 "where pr.game_type_cd = overall.game_type_cd  "
135                 "and player_id = :player_id "
136                 "order by rank").\
137             params(player_id=player_id).all()
138     
139     ranks_dict = {}
140     for gtc,rank,max_rank in ranks:
141         ranks_dict[gtc] = (rank, max_rank)
142
143     elos = DBSession.query(PlayerElo).\
144             filter_by(player_id=player_id).\
145             order_by(PlayerElo.elo.desc()).\
146             all()
147     
148     elos_dict = {}
149     for elo in elos:
150         if elo.games > 32:
151             elos_dict[elo.game_type_cd] = elo.elo
152     
153     data = {
154             'player':player,
155             'total_stats':total_stats,
156             'ranks':ranks_dict,
157             'elos':elos_dict,
158         }
159         
160     #print data
161     return data
162
163
164 def render_image(data):
165     """Render an image from the given data fields."""
166     
167     font = "Xolonium"
168     if params['font'] == 1:
169         font = "DejaVu Sans"
170
171     total_stats = data['total_stats']
172     total_games = total_stats['games']
173     elos = data["elos"]
174     ranks = data["ranks"]
175
176
177     ## create background
178
179     surf = C.ImageSurface(C.FORMAT_RGB24, WIDTH, HEIGHT)
180     ctx = C.Context(surf)
181     ctx.set_antialias(C.ANTIALIAS_GRAY)
182
183     # draw background (just plain fillcolor)
184     if params['bg'] == 0:
185         ctx.rectangle(0, 0, WIDTH, HEIGHT)
186         ctx.set_source_rgb(0.04, 0.04, 0.04)  # bgcolor of Xonotic forum
187         ctx.fill()
188     
189     # draw background image (try to get correct tiling, too)
190     if params['bg'] > 0:
191         bg = None
192         if params['bg'] == 1:
193             bg = C.ImageSurface.create_from_png("img/dark_wall.png")
194         elif params['bg'] == 2:
195             bg = C.ImageSurface.create_from_png("img/asfalt.png")
196         elif params['bg'] == 3:
197             bg = C.ImageSurface.create_from_png("img/broken_noise.png")
198         elif params['bg'] == 4:
199             bg = C.ImageSurface.create_from_png("img/burried.png")
200         elif params['bg'] == 5:
201             bg = C.ImageSurface.create_from_png("img/dark_leather.png")
202         elif params['bg'] == 6:
203             bg = C.ImageSurface.create_from_png("img/txture.png")
204         elif params['bg'] == 7:
205             bg = C.ImageSurface.create_from_png("img/black_linen_v2.png")
206         elif params['bg'] == 8:
207             bg = C.ImageSurface.create_from_png("img/background_archer-v1.png")
208         
209         # tile image
210         if bg:
211             bg_w, bg_h = bg.get_width(), bg.get_height()
212             bg_xoff = 0
213             while bg_xoff < WIDTH:
214                 bg_yoff = 0
215                 while bg_yoff < HEIGHT:
216                     ctx.set_source_surface(bg, bg_xoff, bg_yoff)
217                     ctx.paint()
218                     bg_yoff += bg_h
219                 bg_xoff += bg_w
220     
221     # draw overlay graphic
222     if params['overlay'] > 0:
223         overlay = None
224         if params['overlay'] == 1:
225             overlay = C.ImageSurface.create_from_png("img/overlay.png")
226         if overlay:
227             ctx.set_source_surface(overlay, 0, 0)
228             ctx.mask_surface(overlay)
229             ctx.paint()
230
231
232     ## draw player's nickname with fancy colors
233     
234     # deocde nick, strip all weird-looking characters
235     qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '').replace(u' ', '    ')
236     chars = []
237     for c in qstr:
238         if ord(c) < 128:
239             chars.append(c)
240     qstr = ''.join(chars)
241     stripped_nick = strip_colors(qstr)
242     
243     # fontsize is reduced if width gets too large
244     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
245     ctx.set_font_size(20)
246     xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
247     if tw > NICK_MAXWIDTH:
248         ctx.set_font_size(18)
249         xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
250         if tw > NICK_MAXWIDTH:
251             ctx.set_font_size(16)
252             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
253             if tw > NICK_MAXWIDTH:
254                 ctx.set_font_size(14)
255                 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
256                 if tw > NICK_MAXWIDTH:
257                     ctx.set_font_size(12)
258     
259     
260     # split up nick into colored segments and draw each of them
261     
262     # split nick into colored segments
263     xoffset = 0
264     _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
265     #print qstr, _all_colors.findall(qstr), _all_colors.split(qstr)
266     
267     parts = _all_colors.split(qstr)
268     while len(parts) > 0:
269         tag = None
270         txt = parts[0]
271         if _all_colors.match(txt):
272             tag = txt[1:]  # strip leading '^'
273             if len(parts) < 2:
274                 break
275             txt = parts[1]
276             del parts[1]
277         del parts[0]
278             
279         if not txt or len(txt) == 0:
280             # only colorcode and no real text, skip this
281             continue
282             
283         r,g,b = _dec_colors[7]
284         try:
285             if tag.startswith('x'):
286                 r = int(tag[1] * 2, 16) / 255.0
287                 g = int(tag[2] * 2, 16) / 255.0
288                 b = int(tag[3] * 2, 16) / 255.0
289                 hue, light, satur = rgb_to_hls(r, g, b)
290                 if light < _contrast_threshold:
291                     light = _contrast_threshold
292                     r, g, b = hls_to_rgb(hue, light, satur)
293             else:
294                 r,g,b = _dec_colors[int(tag[0])]
295         except:
296             r,g,b = _dec_colors[7]
297         
298         ctx.set_source_rgb(r, g, b)
299         ctx.move_to(NICK_POS[0] + xoffset, NICK_POS[1])
300         ctx.show_text(txt)
301
302         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
303         tw += (len(txt)-len(txt.strip()))*3  # account for lost whitespaces
304         xoffset += tw + 2
305
306
307     ## print elos and ranks
308     
309     # show up to three gametypes the player has participated in
310     xoffset = 0
311     for gt in total_stats['gametypes'][:3]:
312         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
313         ctx.set_font_size(10)
314         ctx.set_source_rgb(1.0, 1.0, 1.0)
315         txt = "[ %s ]" % gt.upper()
316         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
317         ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]-yoff-4)
318         ctx.show_text(txt)
319         
320         old_aa = ctx.get_antialias()
321         ctx.set_antialias(C.ANTIALIAS_NONE)
322         ctx.set_source_rgb(0.8, 0.8, 0.8)
323         ctx.set_line_width(1)
324         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+8)
325         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+8)
326         ctx.stroke()
327         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+32)
328         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+32)
329         ctx.stroke()
330         ctx.set_antialias(old_aa)
331         
332         if not elos.has_key(gt) or not ranks.has_key(gt):
333             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
334             ctx.set_font_size(12)
335             ctx.set_source_rgb(0.8, 0.2, 0.2)
336             txt = "no stats yet!"
337             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
338             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+28-yoff-4)
339             ctx.save()
340             ctx.rotate(math.radians(-10))
341             ctx.show_text(txt)
342             ctx.restore()
343         else:
344             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
345             ctx.set_font_size(10)
346             ctx.set_source_rgb(1.0, 1.0, 0.5)
347             txt = "Elo: %.0f" % round(elos[gt], 0)
348             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
349             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+15-yoff-4)
350             ctx.show_text(txt)
351             
352             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
353             ctx.set_font_size(8)
354             ctx.set_source_rgb(0.8, 0.8, 1.0)
355             txt = "Rank %d of %d" % ranks[gt]
356             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
357             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+25-yoff-3)
358             ctx.show_text(txt)
359         
360         xoffset += GAMES_WIDTH
361
362
363     # print win percentage
364     
365     if params['overlay'] == 0:
366         ctx.rectangle(WINLOSS_POS[0]-WINLOSS_WIDTH/2, WINLOSS_POS[1]-7, WINLOSS_WIDTH, 15)
367         ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
368         ctx.fill();
369     
370     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
371     ctx.set_font_size(10)
372     ctx.set_source_rgb(0.8, 0.8, 0.8)
373     txt = "Win Percentage"
374     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
375     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]-yoff-3)
376     ctx.show_text(txt)
377     
378     wins, losses = total_stats["wins"], total_games-total_stats["wins"]
379     txt = "???"
380     try:
381         ratio = float(wins)/total_games
382         txt = "%.2f%%" % round(ratio * 100, 2)
383     except:
384         ratio = 0
385     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
386     ctx.set_font_size(12)
387     if ratio >= 0.90:
388         ctx.set_source_rgb(0.2, 1.0, 1.0)
389     elif ratio >= 0.75:
390         ctx.set_source_rgb(0.5, 1.0, 1.0)
391     elif ratio >= 0.5:
392         ctx.set_source_rgb(0.5, 1.0, 0.8)
393     elif ratio >= 0.25:
394         ctx.set_source_rgb(0.8, 1.0, 0.5)
395     else:
396         ctx.set_source_rgb(1.0, 1.0, 0.5)
397     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
398     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+18-yoff-4)
399     ctx.show_text(txt)
400     
401     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
402     ctx.set_font_size(8)
403     ctx.set_source_rgb(0.6, 0.8, 0.8)
404     txt = "%d win" % wins
405     if wins != 1:
406         txt += "s"
407     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
408     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+30-yoff-3)
409     ctx.show_text(txt)
410     ctx.set_source_rgb(0.8, 0.8, 0.6)
411     txt = "%d loss" % losses
412     if losses != 1:
413         txt += "es"
414     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
415     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+40-yoff-3)
416     ctx.show_text(txt)
417
418
419     # print kill/death ratio
420     
421     if params['overlay'] == 0:
422         ctx.rectangle(KILLDEATH_POS[0]-KILLDEATH_WIDTH/2, KILLDEATH_POS[1]-7, KILLDEATH_WIDTH, 15)
423         ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
424         ctx.fill()
425     
426     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
427     ctx.set_font_size(10)
428     ctx.set_source_rgb(0.8, 0.8, 0.8)
429     txt = "Kill Ratio"
430     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
431     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]-yoff-3)
432     ctx.show_text(txt)
433     
434     kills, deaths = total_stats['kills'] , total_stats['deaths'] 
435     txt = "???"
436     try:
437         ratio = float(kills)/deaths
438         txt = "%.3f" % round(ratio, 3)
439     except:
440         ratio = 0
441     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
442     ctx.set_font_size(12)
443     if ratio >= 3:
444         ctx.set_source_rgb(0.0, 1.0, 0.0)
445     elif ratio >= 2:
446         ctx.set_source_rgb(0.2, 1.0, 0.2)
447     elif ratio >= 1:
448         ctx.set_source_rgb(0.5, 1.0, 0.5)
449     elif ratio >= 0.5:
450         ctx.set_source_rgb(1.0, 0.5, 0.5)
451     else:
452         ctx.set_source_rgb(1.0, 0.2, 0.2)
453     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
454     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+18-yoff-4)
455     ctx.show_text(txt)
456
457     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
458     ctx.set_font_size(8)
459     ctx.set_source_rgb(0.6, 0.8, 0.6)
460     txt = "%d kill" % kills
461     if kills != 1:
462         txt += "s"
463     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
464     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+30-yoff-3)
465     ctx.show_text(txt)
466     ctx.set_source_rgb(0.8, 0.6, 0.6)
467     txt = "%d death" % deaths
468     if deaths != 1:
469         txt += "s"
470     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
471     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+40-yoff-3)
472     ctx.show_text(txt)
473
474
475     # print playing time
476     
477     if params['overlay'] == 0:
478         ctx.rectangle( PLAYTIME_POS[0]-PLAYTIME_WIDTH/2, PLAYTIME_POS[1]-7, PLAYTIME_WIDTH, 14)
479         ctx.set_source_rgba(0.8, 0.8, 0.8, 0.6)
480         ctx.fill();
481     
482     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
483     ctx.set_font_size(10)
484     ctx.set_source_rgb(0.1, 0.1, 0.1)
485     txt = "Playing time: %s" % str(total_stats['alivetime'])
486     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
487     ctx.move_to(PLAYTIME_POS[0]-xoff-tw/2, PLAYTIME_POS[1]-yoff-4)
488     ctx.show_text(txt)
489
490
491     # save to PNG
492     surf.write_to_png(OUTPUT % data['player'].player_id)
493
494
495 # environment setup
496 env = bootstrap('../../../development.ini')
497 req = env['request']
498 req.matchdict = {'id':3}
499
500 print "Requesting player data from db ..."
501 start = datetime.now()
502 players = DBSession.query(Player).\
503         filter(Player.player_id == PlayerElo.player_id).\
504         filter(Player.nick != None).\
505         filter(Player.player_id > 2).\
506         filter(Player.active_ind == True).\
507         limit(NUM_PLAYERS).all()
508 stop = datetime.now()
509 print "Query took %.2f seconds" % (stop-start).total_seconds()
510
511 print "Creating badges for %d active players ..." % len(players)
512 start = datetime.now()
513 data_time, render_time = 0,0
514 for player in players:
515     req.matchdict['id'] = player.player_id
516     
517     sstart = datetime.now()
518     #data = player_info_data(req)
519     data = get_data(player)
520     sstop = datetime.now()
521     data_time += (sstop-sstart).total_seconds()
522     
523     print "\r  #%-5d" % player.player_id,
524     sys.stdout.flush()
525
526     sstart = datetime.now()
527     render_image(data)
528     sstop = datetime.now()
529     render_time += (sstop-sstart).total_seconds()
530 print
531
532 stop = datetime.now()
533 print "Creating the badges took %.2f seconds (%.2f s per player)" % ((stop-start).total_seconds(), (stop-start).total_seconds()/float(len(players)))
534 print " Total time for getting data: %.2f s" % data_time
535 print " Total time for renering images: %.2f s" % render_time
536