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