__init__.py 8.22 KB
Newer Older
Louis's avatar
Louis committed
1
2
#!/usr/bin/env python3

3
from pkgtools import pypi
Louis's avatar
Louis committed
4
import collections
5
import urllib
Louis's avatar
Louis committed
6
import datetime
7
8
9
10
import itertools
import logging
import jinja2
import pkg_resources
Louis's avatar
Louis committed
11
12
13
14
15
16
17
18
import pprint
import sys

try:
    import xmlrpclib
except ImportError:
    import xmlrpc.client as xmlrpclib

19
20
_client = xmlrpclib.ServerProxy("http://pypi.python.org/pypi")
LOGGER = logging.getLogger(__name__)
Louis's avatar
Louis committed
21
LOGGER.setLevel(logging.INFO)
22
23
24

class PackageList:
    def __init__(self, user=None, pkg=None):
Louis's avatar
Louis committed
25
        self.packages = {name: Package(name) for name in sorted(self._get_packages(user, pkg))}
26

Louis's avatar
Louis committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    @staticmethod
    def _get_packages(users, packages):
        if users is not None:
            for user in users:
                for _, package in _client.user_packages(user):
                    try:
                        yield package
                    except urllib.error.HTTPError as error:
                        LOGGER.warning("Ignoring user '{}': {}.".format(
                            user,
                            str(error),
                            ))
        if packages is not None:
            yield from packages
            #for pkg in packages:
            #    try:
            #        yield pypi.real_name(pkg)
            #    except urllib.error.HTTPError as error:
            #        LOGGER.warning("Ignoring package '{}': {}.".format(
            #            pkg,
            #            str(error),
            #            ))
49
50
51
52

    def __iter__(self):
        yield from self.packages

Louis's avatar
Louis committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
    def values(self):
        yield from self.packages.values()

    def __getitem__(self, key):
        return self.packages[key]

    def iter_dated_downloads(self, name=None):
        if name is None:
            packages = list(self.values())
        else:
            packages = [self[name]]
        for date in set(itertools.chain(*(package.iter_dates() for package in packages))):
            downloads = []
            for package in packages:
                try:
                    downloads.append((package.name, package.releases[date]['previous']))
                except KeyError:
                    pass
            yield (date, downloads)
        yield (
            datetime.datetime.now(),
            [(package.name, package.total_downloads) for package in packages],
            )

    def iter_ykeys(self, name=None):
        if name is None:
            yield from self
        else:
            yield name

def DateTime2datetime(date):
    timetuple = date.timetuple()
    return datetime.datetime(
            timetuple.tm_year,
            timetuple.tm_mon,
            timetuple.tm_mday,
            timetuple.tm_hour,
            timetuple.tm_min,
            timetuple.tm_sec,
            )

94
95
96
class Package:

    def __init__(self, name):
Louis's avatar
Louis committed
97
        sys.stderr.write("Retrieving information about pypi package '{}'...\n".format(name))
98
        self.name = name
Louis's avatar
Louis committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
        self.releases = {}
        for release in _client.package_releases(name, True):
            release_urls = _client.release_urls(name, release)
            if not release_urls:
                continue
            date = DateTime2datetime(min((url['upload_time'] for url in release_urls)))
            self.releases[date] = {}
            self.releases[date]['downloads'] = sum((url['downloads'] for url in release_urls))
            self.releases[date]['version'] = release

        downloads = 0
        for release in sorted(self.releases):
            self.releases[release]['previous'] = downloads
            downloads += self.releases[release]['downloads']

        self.data = _client.release_data(name, self.releases[max(sorted(self.releases))]['version'])

    def iter_dates(self):
        yield from self.releases.keys()

    @property
    def total_downloads(self):
        last = sorted(self.releases.keys())[-1]
        return self.releases[last]['downloads'] + self.releases[last]['previous']
123
124
125
126

################################################################################
# OLD
################################################################################
Louis's avatar
Louis committed
127

128
USER = "spalax"
Louis's avatar
Louis committed
129
130
131
132

def process_package(package):
    data = {}
    sys.stderr.write("Processing {}...\n".format(package))
133
    for release in _client.package_releases(package, True):
Louis's avatar
Louis committed
134
135
        sys.stderr.write("Processing version {}...".format(release))
        data[release] = {'downloads': 0}
136
        for urls in _client.release_urls(package, release):
Louis's avatar
Louis committed
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
            data[release]['downloads'] += urls['downloads']
            data[release]['upload_time'] = urls['upload_time']
        sys.stderr.write(" Done\n")
    return data

def get_release_date(data):
    try:
        return data[1]['upload_time']
    except KeyError:
        # Will be ignored later
        return datetime.datetime.fromtimestamp(0)

def shift(data):
    date = [{'downloads': 0}]
    for release, _ in sorted(data.items(), key=get_release_date):
        try:
            datetuple = data[release]['upload_time'].timetuple()
        except KeyError:
            continue
        date[-1].update({
            'date': datetime.date(datetuple.tm_year, datetuple.tm_mon, datetuple.tm_mday),
             'release': release,
        })
        date.append({
            'downloads': data[release]['downloads'] + date[-1]['downloads'],
        })
    date[-1].update({
        'date': datetime.date.today(),
        'release': "",
    })
    return date

def bydate(package, data):
    dateddata = collections.defaultdict(list)
    for release in data:
        dateddata[release['date']].append({
            'downloads': release['downloads'],
            'release': release['release'],
            'package': package,
            })
    return dateddata

def compile_dates(package_data):
    data = collections.defaultdict(list)
    for package in package_data:
        for date, release in package.items():
            data[date].extend(release)
    return data

HTML_BEGIN = """
<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="utf-8">
      <title>Pypi statistics</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
                    </head>
                      <body>
                      """

HTML_GRAPHDIV = """
<div id="pystats{counter}" style="height: 250px;"></div>
"""

HTML_SCRIPT = """
<script>
new Morris.Line({{
  element: 'pystats{counter}',
  data: [
    {yvalues}
  ],
  xkey: 'date',
  ykeys: [{ykeys}],
  labels: [{ykeys}]
}});
</script>
"""

HTML_END = """
</body>
</html>
"""

def make_id(string):
    new = ""
    for char in string:
        if char.isidentifier():
            new += char
    return new

def print_y(data):
    for date, releaselist in data.items():
        values = ", ".join((
            "{}: {}".format(make_id(release['package']), release['downloads'])
            for release in releaselist
            ))
        yield "{{ date: '{}', {}}}".format(str(date), values)

def print_ykeys(data):
    packages = set()
    for releaselist in data.values():
        for release in releaselist:
            packages.add(make_id(release['package']))
    for package in packages:
        yield "'{}'".format(package)

class Counter:
    def __init__(self):
        self.total = 0
    def count(self):
        self.total += 1
        return self.total
counter = Counter()

def get_compiled(packages):
    compiled = compile_dates((
        bydate(package, shift(process_package(package)))
        for package in packages
       ))

    count = counter.count()
    return (
            HTML_SCRIPT.format(
                ykeys=", ".join(print_ykeys(compiled)),
                yvalues=",\n".join(print_y(compiled)),
                counter= count,
                ),
            HTML_GRAPHDIV.format(counter=count),
            )

270
271
if __name__ == "__main__":
    packages = [package for role, package in _client.user_packages(USER)] + ["patacrep"]
Louis's avatar
Louis committed
272

273
274
275
276
277
278
279
280
281
282
283
    graphs = []
    graphs.append(get_compiled(packages))
    for package in packages:
        graphs.append(get_compiled([package]))

    print(HTML_BEGIN)
    for _, div in graphs:
        print(div)
    for script, _ in graphs:
        print(script)
    print(HTML_END)