Simplify the player create/update function.
[xonotic/xonstat.git] / xonstat / batch / badges / gen_badges.py
1 #-*- coding: utf-8 -*-
2
3 import sys
4 from datetime import datetime, timedelta
5
6 from playerdata import PlayerData
7 from pyramid.paster import bootstrap
8 from skin import Skin
9 from sqlalchemy import distinct
10 from xonstat.models import DBSession, PlayerGameStat, Player, PlayerElo
11 from xonstat.util import datetime_seconds
12
13 # maximal number of query results (for testing, set to None to get all)
14 NUM_PLAYERS = None
15
16 # filter by player id (for testing, set to None to disable)
17 PLAYER_ID = None
18
19 # we look for players who have activity within the past DELTA hours
20 DELTA = 50000
21
22 VERBOSE = False
23
24 INIFILE = None  # keep this set to "None"
25
26 # classic skin WITHOUT NAME - writes PNGs into "output//###.png"
27 skin_classic = Skin( "",
28         bg              = "broken_noise",
29         overlay         = "overlay_classic",
30     )
31
32 # more fancy skin [** WIP **]- writes PNGs into "output/archer/###.png"
33 skin_archer = Skin( "archer",
34         #bg              = "background_archer-v2_full",
35         bg              = "background_archer-v3",
36         overlay         = "",
37         nick_maxwidth   = 260,
38         gametype_pos    = (95,33),
39         nostats_pos     = (95,59),
40         elo_pos         = (95,47),
41         rank_pos        = (95,58),
42         winp_pos        = (509,19),
43         wins_pos        = (508,34),
44         loss_pos        = (508,45),
45         kdr_pos         = (392,19),
46         kills_pos       = (392,34),
47         deaths_pos      = (392,45),
48         ptime_color     = (0.05, 0.05, 0.1),
49     )
50
51 # minimal skin - writes PNGs into "output/minimal/###.png"
52 skin_minimal = Skin( "minimal",
53         bg              = None,
54         bgcolor         = (0.04, 0.04, 0.04, 1.0),
55         overlay         = "overlay_minimal",
56         width           = 560,
57         height          = 40,
58         nick_fontsize   = 16,
59         nick_pos        = (36,17),
60         num_gametypes   = 3,
61         nick_maxwidth   = 280,
62         gametype_pos    = (70,30),
63         gametype_color  = (0.0, 0.0, 0.0),
64         gametype_text   = "%s:",
65         gametype_width  = 100,
66         gametype_fontsize = 10,
67         gametype_align  = -1,
68         gametype_upper  = False,
69         elo_pos         = (75,30),
70         elo_text        = "Elo %.0f",
71         elo_color       = (0.7, 0.7, 0.7),
72         elo_align       = 1,
73         rank_pos        = None,
74         nostats_pos     = None,
75         #nostats_pos     = (75,30),
76         #nostats_fontsize = 10,
77         #nostats_angle   = 0,
78         #nostats_text    = "no stats yet!",
79         #nostats_color   = (0.7, 0.4, 0.4),
80         kdr_pos         = (392,15),
81         kdr_fontsize    = 11,
82         kdr_colortop    = (0.6, 0.8, 0.6),
83         kdr_colormid    = (0.6, 0.6, 0.6),
84         kdr_colorbot    = (0.8, 0.6, 0.6),
85         kills_pos       = None,
86         deaths_pos      = None,
87         winp_pos        = (509,15),
88         winp_fontsize   = 11,
89         winp_colortop   = (0.6, 0.8, 0.8),
90         winp_colormid   = (0.6, 0.6, 0.6),
91         winp_colorbot   = (0.8, 0.8, 0.6),
92         wins_pos        = None,
93         loss_pos        = None,
94         ptime_pos       = (451,30),
95         ptime_color     = (0.7, 0.7, 0.7),
96     )
97
98
99 # parse cmdline parameters (for testing)
100
101 skins = []
102 for arg in sys.argv[1:]:
103     if arg.startswith("-"):
104         try:
105             key,value = arg[1:].split("=")
106         except:
107             key,value = arg[1:], ""
108         if key == "force":
109             DELTA = 2**24   # large enough to enforce update, and doesn't result in errors
110         elif key == "delta":
111             DELTA = float(value)
112         elif key == "test":
113             NUM_PLAYERS = 100
114         elif key == "player":
115             PLAYER_ID = int(value)
116         elif key == "verbose":
117             VERBOSE = True
118         else:
119             print """Usage:  gen_badges.py [options] <ini-file> [skin list]
120     Options:
121         -force      Force updating all badges (delta = 2^24)
122         -delta n    Manually set an update interval (delta)
123         -test       Limit number of players to 100 (for testing)
124         -player #   Filter by given player id
125         -verbose    Show more verbose output
126         -help       Show this help text
127     Ini-File:
128         Name of a Pyramid ini-file to use (e.g. prodution.ini or development.ini).
129     Skin list:
130         Space-separated list of skins to use when creating badges.
131         Available skins:  classic, minimal, archer
132         If no skins are given, classic and minmal will be used by default.
133         NOTE: Output directories must exists before running the program!
134 """
135             sys.exit(-1)
136     else:
137         if INIFILE == None:
138             INIFILE = arg
139         else:
140             if arg == "classic":
141                 skins.append(skin_classic)
142             elif arg == "minimal":
143                 skins.append(skin_minimal)
144             elif arg == "archer":
145                         skins.append(skin_archer)
146
147 if len(skins) == 0:
148     skins = [ skin_classic, skin_minimal, skin_archer ]
149
150 if not INIFILE:
151     print "You must provide the name of an ini-file to use! Type 'gen_badges.py -h' for help."
152     sys.exit(-1)
153
154 # environment setup
155 env = bootstrap(INIFILE)
156 req = env['request']
157 req.matchdict = {'id':3}
158
159 print "Requesting player data from db ..."
160 cutoff_dt = datetime.utcnow() - timedelta(hours=DELTA)
161 start = datetime.now()
162 players = []
163 if NUM_PLAYERS:
164     players = DBSession.query(distinct(Player.player_id)).\
165             filter(Player.player_id == PlayerElo.player_id).\
166             filter(Player.player_id == PlayerGameStat.player_id).\
167             filter(PlayerGameStat.create_dt > cutoff_dt).\
168             filter(Player.nick != None).\
169             filter(Player.player_id > 2).\
170             filter(Player.active_ind == True).\
171             limit(NUM_PLAYERS).all()
172 elif PLAYER_ID:
173     players = DBSession.query(distinct(Player.player_id)).\
174             filter(Player.player_id == PlayerElo.player_id).\
175             filter(Player.player_id == PlayerGameStat.player_id).\
176             filter(PlayerGameStat.create_dt > cutoff_dt).\
177             filter(Player.nick != None).\
178             filter(Player.player_id == PLAYER_ID).\
179             filter(Player.active_ind == True).\
180             limit(NUM_PLAYERS).all()
181 else:
182     players = DBSession.query(distinct(Player.player_id)).\
183             filter(Player.player_id == PlayerElo.player_id).\
184             filter(Player.player_id == PlayerGameStat.player_id).\
185             filter(PlayerGameStat.create_dt > cutoff_dt).\
186             filter(Player.nick != None).\
187             filter(Player.player_id > 2).\
188             filter(Player.active_ind == True).\
189             all()
190
191 playerdata = PlayerData
192
193 if len(players) > 0:
194     stop = datetime.now()
195     td = stop-start
196     print "Query took %.2f seconds" % (datetime_seconds(td))
197
198     print "Creating badges for %d players ..." % len(players)
199     start = datetime.now()
200     data_time, render_time = 0,0
201     for player_id in players:
202         req.matchdict['id'] = player_id
203
204         sstart = datetime.now()
205         playerdata.get_data(player_id)
206         sstop = datetime.now()
207         td = sstop-sstart
208         data_time += datetime_seconds(td)
209
210         sstart = datetime.now()
211         for sk in skins:
212             sk.render_image(playerdata.data, "output/%s/%d.png" % (str(sk), player_id[0]))
213         sstop = datetime.now()
214         td = sstop-sstart
215         render_time += datetime_seconds(td)
216
217         if VERBOSE == True:
218             print player_id, unicode(playerdata.data['player'].nick)
219
220     stop = datetime.now()
221     td = stop-start
222     total_seconds = datetime_seconds(td)
223     print "Creating the badges took %.1f seconds (%.3f s per player)" % (total_seconds, total_seconds/float(len(players)))
224     print "Total time for rendering images: %.3f s" % render_time
225     print "Total time for getting data: %.3f s" % data_time
226
227 else:
228     print "No active players found!"
229