]> git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/render.py
Hotfix - last commit introduced a bug where only the last defined skin could be used
[xonotic/xonstat.git] / xonstat / batch / badges / render.py
1 import re
2 import zlib, struct
3 import cairo as C
4 from colorsys import rgb_to_hls, hls_to_rgb
5 import sqlalchemy as sa
6 import sqlalchemy.sql.functions as func
7 from xonstat.models import *
8 from xonstat.util import qfont_decode, _all_colors
9
10 # similar to html_colors() from util.py
11 _contrast_threshold = 0.5
12
13 _dec_colors = [ (0.5,0.5,0.5),
14                 (1.0,0.0,0.0),
15                 (0.2,1.0,0.0),
16                 (1.0,1.0,0.0),
17                 (0.2,0.4,1.0),
18                 (0.2,1.0,1.0),
19                 (1.0,0.2,102),
20                 (1.0,1.0,1.0),
21                 (0.6,0.6,0.6),
22                 (0.5,0.5,0.5)
23             ]
24
25
26 def writepng(filename, buf, width, height):
27     width_byte_4 = width * 4
28     # fix color ordering (BGR -> RGB)
29     for byte in xrange(width*height):
30         pos = byte * 4
31         buf[pos:pos+4] = buf[pos+2] + buf[pos+1] + buf[pos+0] + buf[pos+3]
32     # merge lines
33     #raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in xrange((height - 1) * width * 4, -1, - width_byte_4))
34     raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in range(0, (height-1) * width * 4 + 1, width_byte_4))
35     def png_pack(png_tag, data):
36         chunk_head = png_tag + data
37         return struct.pack("!I", len(data)) + chunk_head + struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head))
38     data = b"".join([
39         b'\x89PNG\r\n\x1a\n',
40         png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
41         png_pack(b'IDAT', zlib.compress(raw_data, 9)),
42         png_pack(b'IEND', b'')])
43     f = open(filename, "wb")
44     try:
45         f.write(data)
46     finally:
47         f.close()
48
49
50 class Skin:
51
52     # player data, will be filled by get_data()
53     data = {}
54
55     # skin parameters, can be overriden by init
56     params = {}
57
58     def __init__(self, **params):
59         # default parameters
60         self.params = {
61             'bg':               "dark_wall",    # None - plain; otherwise use given texture
62             'bgcolor':          None,           # transparent bg when bgcolor==None
63             'overlay':          None,           # add overlay graphic on top of bg
64             'font':             "Xolonium",
65             'width':            560,
66             'height':           70,
67             'nick_fontsize':    20,
68             'nick_pos':         (5,18),
69             'nick_maxwidth':    330,
70             'gametype_fontsize':12,
71             'gametype_pos':     (60,31),
72             'gametype_width':   110,
73             'gametype_height':  22,
74             'gametype_color':   (1.0, 1.0, 1.0),
75             'gametype_text':    "[ %s ]",
76             'num_gametypes':    3,
77             'nostats_fontsize': 12,
78             'nostats_pos':      (60,59),
79             'nostats_color':    (0.8, 0.2, 0.2),
80             'nostats_angle':    -10,
81             'nostats_text':     "no stats yet!",
82             'elo_pos':          (60,47),
83             'elo_fontsize':     10,
84             'elo_color':        (1.0, 1.0, 0.5),
85             'elo_text':         "Elo %.0f",
86             'rank_fontsize':    8,
87             'rank_pos':         (60,57),
88             'rank_color':       (0.8, 0.8, 1.0),
89             'rank_text':        "Rank %d of %d",
90             'wintext_fontsize': 10,
91             'wintext_pos':      (508,3),
92             'wintext_width':    102,
93             'wintext_color':    (0.8, 0.8, 0.8),
94             'wintext_bg':       (0.8, 0.8, 0.8, 0.1),
95             'wintext_text':     "Win Percentage",
96             'winp_fontsize':    12,
97             'winp_pos':         (508,19),
98             'winp_colortop':    (0.2, 1.0, 1.0),
99             'winp_colorbot':    (1.0, 1.0, 0.2),
100             'wins_fontsize':    8,
101             'wins_pos':         (508,33),
102             'wins_color':       (0.6, 0.8, 0.8),
103             'loss_fontsize':    8,
104             'loss_pos':         (508,43),
105             'loss_color':       (0.8, 0.8, 0.6),
106             'kdtext_fontsize':  10,
107             'kdtext_pos':       (390,3),
108             'kdtext_width':     102,
109             'kdtext_color':     (0.8, 0.8, 0.8),
110             'kdtext_bg':        (0.8, 0.8, 0.8, 0.1),
111             'kdtext_text':      "Kill Ratio",
112             'kdr_fontsize':     12,
113             'kdr_pos':          (392,19),
114             'kdr_colortop':     (0.2, 1.0, 0.2),
115             'kdr_colorbot':     (1.0, 0.2, 0.2),
116             'kills_fontsize':   8,
117             'kills_pos':        (392,46),
118             'kills_color':      (0.6, 0.8, 0.6),
119             'deaths_fontsize':  8,
120             'deaths_pos':       (392,56),
121             'deaths_color':     (0.8, 0.6, 0.6),
122             'ptime_fontsize':   10,
123             'ptime_pos':        (451,60),
124             'ptime_width':      222,
125             'ptime_bg':         (0.8, 0.8, 0.8, 0.5),
126             'ptime_color':      (0.1, 0.1, 0.1),
127             'ptime_text':       "Playing Time: %s",
128         }
129         
130         for k,v in params.items():
131             if self.params.has_key(k):
132                 self.params[k] = v
133
134     def __getattr__(self, key):
135         if self.params.has_key(key):
136             return self.params[key]
137         return None
138
139     def render_image(self, output_filename):
140         """Render an image for the given player id."""
141
142         # setup variables
143
144         player = self.data['player']
145         total_stats = self.data['total_stats']
146         total_games = total_stats['games']
147         elos  = self.data["elos"]
148         ranks = self.data["ranks"]
149
150         font = "Xolonium"
151         if self.font == 1:
152             font = "DejaVu Sans"
153
154
155         # build image
156
157         surf = C.ImageSurface(C.FORMAT_ARGB32, self.width, self.height)
158         ctx = C.Context(surf)
159         ctx.set_antialias(C.ANTIALIAS_GRAY)
160         
161         # draw background
162         if self.bg == None:
163             if self.bgcolor != None:
164                 # plain fillcolor, full transparency possible with (1,1,1,0)
165                 ctx.save()
166                 ctx.set_operator(C.OPERATOR_SOURCE)
167                 ctx.rectangle(0, 0, self.width, self.height)
168                 ctx.set_source_rgba(self.bgcolor[0], self.bgcolor[1], self.bgcolor[2], self.bgcolor[3])
169                 ctx.fill()
170                 ctx.restore()
171         else:
172             try:
173                 # background texture
174                 bg = C.ImageSurface.create_from_png("img/%s.png" % self.bg)
175                 
176                 # tile image
177                 if bg:
178                     bg_w, bg_h = bg.get_width(), bg.get_height()
179                     bg_xoff = 0
180                     while bg_xoff < self.width:
181                         bg_yoff = 0
182                         while bg_yoff < self.height:
183                             ctx.set_source_surface(bg, bg_xoff, bg_yoff)
184                             #ctx.mask_surface(bg)
185                             ctx.paint()
186                             bg_yoff += bg_h
187                         bg_xoff += bg_w
188             except:
189                 #print "Error: Can't load background texture: %s" % self.bg
190                 pass
191
192         # draw overlay graphic
193         if self.overlay != None:
194             try:
195                 overlay = C.ImageSurface.create_from_png("img/%s.png" % self.overlay)
196                 ctx.set_source_surface(overlay, 0, 0)
197                 #ctx.mask_surface(overlay)
198                 ctx.paint()
199             except:
200                 #print "Error: Can't load overlay texture: %s" % self.overlay
201                 pass
202
203
204         ## draw player's nickname with fancy colors
205         
206         # deocde nick, strip all weird-looking characters
207         qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
208         chars = []
209         for c in qstr:
210             # replace weird characters that make problems - TODO
211             if ord(c) < 128:
212                 chars.append(c)
213         qstr = ''.join(chars)
214         stripped_nick = strip_colors(qstr.replace(' ', '_'))
215         
216         # fontsize is reduced if width gets too large
217         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
218         shrinknick = 0
219         while shrinknick < 10:
220             ctx.set_font_size(self.nick_fontsize - shrinknick)
221             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
222             if tw > self.nick_maxwidth:
223                 shrinknick += 2
224                 continue
225             break
226
227         # determine width of single whitespace for later use
228         xoff, yoff, tw, th = ctx.text_extents("_")[:4]
229         space_w = tw
230
231         # split nick into colored segments
232         xoffset = 0
233         _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
234         parts = _all_colors.split(qstr)
235         while len(parts) > 0:
236             tag = None
237             txt = parts[0]
238             if _all_colors.match(txt):
239                 tag = txt[1:]  # strip leading '^'
240                 if len(parts) < 2:
241                     break
242                 txt = parts[1]
243                 del parts[1]
244             del parts[0]
245                 
246             if not txt or len(txt) == 0:
247                 # only colorcode and no real text, skip this
248                 continue
249             
250             if tag:
251                 if tag.startswith('x'):
252                     r = int(tag[1] * 2, 16) / 255.0
253                     g = int(tag[2] * 2, 16) / 255.0
254                     b = int(tag[3] * 2, 16) / 255.0
255                     hue, light, satur = rgb_to_hls(r, g, b)
256                     if light < _contrast_threshold:
257                         light = _contrast_threshold
258                         r, g, b = hls_to_rgb(hue, light, satur)
259                 else:
260                     r,g,b = _dec_colors[int(tag[0])]
261             else:
262                 r,g,b = _dec_colors[7]
263             
264             ctx.set_source_rgb(r, g, b)
265             ctx.move_to(self.nick_pos[0] + xoffset, self.nick_pos[1])
266             ctx.show_text(txt)
267
268             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
269             tw += (len(txt)-len(txt.strip())) * space_w  # account for lost whitespaces
270             xoffset += tw + 2
271
272         ## print elos and ranks
273         
274         # show up to three gametypes the player has participated in
275         xoffset = 0
276         for gt in total_stats['gametypes'][:self.num_gametypes]:
277             if self.gametype_pos:
278                 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
279                 ctx.set_font_size(self.gametype_fontsize)
280                 ctx.set_source_rgb(self.gametype_color[0],self.gametype_color[1],self.gametype_color[2])
281                 txt = self.gametype_text % gt.upper()
282                 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
283                 ctx.move_to(self.gametype_pos[0]+xoffset-xoff-tw/2, self.gametype_pos[1]-yoff)
284                 ctx.show_text(txt)
285
286                 # draw lines - TODO put this in overlay graphic
287                 if self.overlay == None:
288                     old_aa = ctx.get_antialias()
289                     ctx.set_antialias(C.ANTIALIAS_NONE)
290                     ctx.set_source_rgb(0.8, 0.8, 0.8)
291                     ctx.set_line_width(1)
292                     ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+14)
293                     ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+14)
294                     ctx.stroke()
295                     ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+self.gametype_height+14)
296                     ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+self.gametype_height+14)
297                     ctx.stroke()
298                     ctx.set_antialias(old_aa)
299
300             if not elos.has_key(gt) or not ranks.has_key(gt):
301                 if self.nostats_pos:
302                     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
303                     ctx.set_font_size(self.nostats_fontsize)
304                     ctx.set_source_rgb(self.nostats_color[0],self.nostats_color[1],self.nostats_color[2])
305                     txt = self.nostats_text
306                     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
307                     ctx.move_to(self.nostats_pos[0]+xoffset-xoff-tw/2, self.nostats_pos[1]-yoff)
308                     ctx.save()
309                     ctx.rotate(math.radians(self.nostats_angle))
310                     ctx.show_text(txt)
311                     ctx.restore()
312             else:
313                 if self.elo_pos:
314                     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
315                     ctx.set_font_size(self.elo_fontsize)
316                     ctx.set_source_rgb(self.elo_color[0], self.elo_color[1], self.elo_color[2])
317                     txt = self.elo_text % round(elos[gt], 0)
318                     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
319                     ctx.move_to(self.elo_pos[0]+xoffset-xoff-tw/2, self.elo_pos[1]-yoff)
320                     ctx.show_text(txt)
321                 if  self.rank_pos:
322                     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
323                     ctx.set_font_size(self.rank_fontsize)
324                     ctx.set_source_rgb(self.rank_color[0], self.rank_color[1], self.rank_color[2])
325                     txt = self.rank_text % ranks[gt]
326                     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
327                     ctx.move_to(self.rank_pos[0]+xoffset-xoff-tw/2, self.rank_pos[1]-yoff)
328                     ctx.show_text(txt)
329             
330             xoffset += self.gametype_width
331
332
333         # print win percentage
334
335         if self.wintext_pos:
336             if self.overlay == None:
337                 ctx.rectangle(self.wintext_pos[0]-self.wintext_width/2, self.wintext_pos[1]-self.wintext_fontsize/2+1,
338                         self.wintext_width, self.wintext_fontsize+4)
339                 ctx.set_source_rgba(self.wintext_bg[0], self.wintext_bg[1], self.wintext_bg[2], self.wintext_bg[3])
340                 ctx.fill()
341
342             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
343             ctx.set_font_size(self.wintext_fontsize)
344             ctx.set_source_rgb(self.wintext_color[0], self.wintext_color[1], self.wintext_color[2])
345             txt = self.wintext_text
346             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
347             ctx.move_to(self.wintext_pos[0]-xoff-tw/2, self.wintext_pos[1]-yoff)
348             ctx.show_text(txt)
349
350         wins, losses = total_stats["wins"], total_games-total_stats["wins"]
351         txt = "???"
352         try:
353             ratio = float(wins)/total_games
354             txt = "%.2f%%" % round(ratio * 100, 2)
355         except:
356             ratio = 0
357         
358         if self.winp_pos:
359             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
360             ctx.set_font_size(self.winp_fontsize)
361             r = ratio*self.winp_colortop[0] + (1-ratio)*self.winp_colorbot[0]
362             g = ratio*self.winp_colortop[1] + (1-ratio)*self.winp_colorbot[1]
363             b = ratio*self.winp_colortop[2] + (1-ratio)*self.winp_colorbot[2]
364             ctx.set_source_rgb(r, g, b)
365             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
366             ctx.move_to(self.winp_pos[0]-xoff-tw/2, self.winp_pos[1]-yoff)
367             ctx.show_text(txt)
368
369         if self.wins_pos:
370             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
371             ctx.set_font_size(self.wins_fontsize)
372             ctx.set_source_rgb(self.wins_color[0], self.wins_color[1], self.wins_color[2])
373             txt = "%d win" % wins
374             if wins != 1:
375                 txt += "s"
376             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
377             ctx.move_to(self.wins_pos[0]-xoff-tw/2, self.wins_pos[1]-yoff)
378             ctx.show_text(txt)
379
380         if self.loss_pos:
381             ctx.set_font_size(self.loss_fontsize)
382             ctx.set_source_rgb(self.loss_color[0], self.loss_color[1], self.loss_color[2])
383             txt = "%d loss" % losses
384             if losses != 1:
385                 txt += "es"
386             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
387             ctx.move_to(self.loss_pos[0]-xoff-tw/2, self.loss_pos[1]-yoff)
388             ctx.show_text(txt)
389
390
391         # print kill/death ratio
392
393         if self.kdtext_pos:
394             if self.overlay == None:
395                 ctx.rectangle(self.kdtext_pos[0]-self.kdtext_width/2, self.kdtext_pos[1]-self.kdtext_fontsize/2+1,
396                         self.kdtext_width, self.kdtext_fontsize+4)
397                 ctx.set_source_rgba(self.kdtext_bg[0], self.kdtext_bg[1], self.kdtext_bg[2], self.kdtext_bg[3])
398                 ctx.fill()
399
400             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
401             ctx.set_font_size(self.kdtext_fontsize)
402             ctx.set_source_rgb(self.kdtext_color[0], self.kdtext_color[1], self.kdtext_color[2])
403             txt = self.kdtext_text
404             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
405             ctx.move_to(self.kdtext_pos[0]-xoff-tw/2, self.kdtext_pos[1]-yoff)
406             ctx.show_text(txt)
407         
408         kills, deaths = total_stats['kills'] , total_stats['deaths'] 
409         txt = "???"
410         try:
411             ratio = float(kills)/deaths
412             txt = "%.3f" % round(ratio, 3)
413         except:
414             ratio = 0
415
416         if self.kdr_pos:
417             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
418             ctx.set_font_size(self.kdr_fontsize)
419             nr = ratio / 2.0
420             if nr > 1:
421                 nr = 1
422             r = nr*self.kdr_colortop[0] + (1-nr)*self.kdr_colorbot[0]
423             g = nr*self.kdr_colortop[1] + (1-nr)*self.kdr_colorbot[1]
424             b = nr*self.kdr_colortop[2] + (1-nr)*self.kdr_colorbot[2]
425             ctx.set_source_rgb(r, g, b)
426             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
427             ctx.move_to(self.kdr_pos[0]-xoff-tw/2, self.kdr_pos[1]-yoff)
428             ctx.show_text(txt)
429
430         if self.kills_pos:
431             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
432             ctx.set_font_size(self.kills_fontsize)
433             ctx.set_source_rgb(self.kills_color[0], self.kills_color[1], self.kills_color[2])
434             txt = "%d kill" % kills
435             if kills != 1:
436                 txt += "s"
437             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
438             ctx.move_to(self.kills_pos[0]-xoff-tw/2, self.kills_pos[1]+yoff)
439             ctx.show_text(txt)
440
441         if self.deaths_pos:
442             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
443             ctx.set_font_size(self.deaths_fontsize)
444             ctx.set_source_rgb(self.deaths_color[0], self.deaths_color[1], self.deaths_color[2])
445             txt = "%d death" % deaths
446             if deaths != 1:
447                 txt += "s"
448             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
449             ctx.move_to(self.deaths_pos[0]-xoff-tw/2, self.deaths_pos[1]+yoff)
450             ctx.show_text(txt)
451
452
453         # print playing time
454
455         if self.ptime_pos:
456             if self.overlay == None:
457                 ctx.rectangle( self.ptime_pos[0]-self.ptime_width/2, self.ptime_pos[1]-self.ptime_fontsize/2+1,
458                         self.ptime_width, self.ptime_fontsize+4)
459                 ctx.set_source_rgba(self.ptime_bg[0], self.ptime_bg[1], self.ptime_bg[2], self.ptime_bg[2])
460                 ctx.fill()
461
462             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
463             ctx.set_font_size(self.ptime_fontsize)
464             ctx.set_source_rgb(self.ptime_color[0], self.ptime_color[1], self.ptime_color[2])
465             txt = self.ptime_text % str(total_stats['alivetime'])
466             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
467             ctx.move_to(self.ptime_pos[0]-xoff-tw/2, self.ptime_pos[1]-yoff)
468             ctx.show_text(txt)
469
470
471         # save to PNG
472         #surf.write_to_png(output_filename)
473         surf.flush()
474         imgdata = surf.get_data()
475         writepng(output_filename, imgdata, self.width, self.height)
476
477
478     def get_data(self, player):
479         """Return player data as dict.
480
481         This function is similar to the function in player.py but more optimized
482         for this purpose.
483         """
484
485         # total games
486         # wins/losses
487         # kills/deaths
488         # duel/dm/tdm/ctf elo + rank
489
490         player_id = player.player_id
491
492         games_played = DBSession.query(
493                 Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
494                 filter(Game.game_id == PlayerGameStat.game_id).\
495                 filter(PlayerGameStat.player_id == player_id).\
496                 group_by(Game.game_type_cd).\
497                 order_by(func.count().desc()).\
498                 limit(3).all()  # limit to 3 gametypes!
499
500         total_stats = {}
501         total_stats['games'] = 0
502         total_stats['games_breakdown'] = {}  # this is a dictionary inside a dictionary .. dictception?
503         total_stats['games_alivetime'] = {}
504         total_stats['gametypes'] = []
505         for (game_type_cd, games, alivetime) in games_played:
506             total_stats['games'] += games
507             total_stats['gametypes'].append(game_type_cd)
508             total_stats['games_breakdown'][game_type_cd] = games
509             total_stats['games_alivetime'][game_type_cd] = alivetime
510
511         (total_stats['kills'], total_stats['deaths'], total_stats['alivetime'],) = DBSession.query(
512                 func.sum(PlayerGameStat.kills),
513                 func.sum(PlayerGameStat.deaths),
514                 func.sum(PlayerGameStat.alivetime)).\
515                 filter(PlayerGameStat.player_id == player_id).\
516                 one()
517
518     #    (total_stats['wins'],) = DBSession.query(
519     #            func.count("*")).\
520     #            filter(Game.game_id == PlayerGameStat.game_id).\
521     #            filter(PlayerGameStat.player_id == player_id).\
522     #            filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
523     #            one()
524
525         (total_stats['wins'],) = DBSession.\
526                 query("total_wins").\
527                 from_statement(
528                     "select count(*) total_wins "
529                     "from games g, player_game_stats pgs "
530                     "where g.game_id = pgs.game_id "
531                     "and player_id=:player_id "
532                     "and (g.winner = pgs.team or pgs.rank = 1)"
533                 ).params(player_id=player_id).one()
534
535         ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
536                 from_statement(
537                     "select pr.game_type_cd, pr.rank, overall.max_rank "
538                     "from player_ranks pr,  "
539                        "(select game_type_cd, max(rank) max_rank "
540                         "from player_ranks  "
541                         "group by game_type_cd) overall "
542                     "where pr.game_type_cd = overall.game_type_cd  "
543                     "and player_id = :player_id "
544                     "order by rank").\
545                 params(player_id=player_id).all()
546
547         ranks_dict = {}
548         for gtc,rank,max_rank in ranks:
549             ranks_dict[gtc] = (rank, max_rank)
550
551         elos = DBSession.query(PlayerElo).\
552                 filter_by(player_id=player_id).\
553                 order_by(PlayerElo.elo.desc()).\
554                 all()
555
556         elos_dict = {}
557         for elo in elos:
558             if elo.games > 32:
559                 elos_dict[elo.game_type_cd] = elo.elo
560
561         self.data = {
562                 'player':player,
563                 'total_stats':total_stats,
564                 'ranks':ranks_dict,
565                 'elos':elos_dict,
566             }
567