__init__.py 8.64 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
5
import collections
import datetime
6
7
8
import itertools
import jinja2
import pkg_resources
Louis's avatar
Louis committed
9
import slumber
Louis's avatar
Louis committed
10
import sys
Louis's avatar
Louis committed
11
import urllib
Louis's avatar
Louis committed
12
13
14
15
16
17

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

18
19
20
21
_client = xmlrpclib.ServerProxy("http://pypi.python.org/pypi")

class PackageList:
    def __init__(self, user=None, pkg=None):
Louis's avatar
Louis committed
22
23
24
25
26
27
28
        self.packages = {}
        for name in sorted(self._get_packages(user, pkg)):
            try:
                self.packages[name] = Package(name)
            except ValueError:
                sys.stderr.write("Ignoring package '{}' with no releases.\n".format(name))
                continue
29

Louis's avatar
Louis committed
30
31
32
33
34
35
36
37
    @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:
Louis's avatar
Louis committed
38
                        sys.stderr.write("Ignoring user '{}': {}.".format(
Louis's avatar
Louis committed
39
40
41
42
43
                            user,
                            str(error),
                            ))
        if packages is not None:
            yield from packages
44
45
46
47

    def __iter__(self):
        yield from self.packages

Louis's avatar
Louis committed
48
49
50
51
52
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
    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,
            )

89
90
class Package:

Louis's avatar
Louis committed
91
92
93
94
    docs_api = {
        'readthedocs': slumber.API(base_url="http://readthedocs.org/api/v1/"),
        }

95
    def __init__(self, name):
Louis's avatar
Louis committed
96
        sys.stderr.write("Retrieving information about pypi package '{}'...\n".format(name))
97
        self.name = name
Louis's avatar
Louis committed
98
99
100
101
102
103
104
105
106
        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
Louis's avatar
Louis committed
107
108
        if not self.releases:
            raise ValueError("Package '{}' does not exist or haven't any release.".format(name))
Louis's avatar
Louis committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

        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']
124

Louis's avatar
Louis committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    def get_documentation(self):
        # Readthedocs
        if self.docs_api['readthedocs'].project.get(slug=self.name.lower())['objects']:
            return (
                'readthedocs', 
                None,
                )

        # Pypi docs
        if self.data['docs_url'] is not None:
            return ("pypi", self.name)

        # No documentation
        return (None, {})

140
141
142
################################################################################
# OLD
################################################################################
Louis's avatar
Louis committed
143

144
USER = "spalax"
Louis's avatar
Louis committed
145
146
147
148

def process_package(package):
    data = {}
    sys.stderr.write("Processing {}...\n".format(package))
149
    for release in _client.package_releases(package, True):
Louis's avatar
Louis committed
150
151
        sys.stderr.write("Processing version {}...".format(release))
        data[release] = {'downloads': 0}
152
        for urls in _client.release_urls(package, release):
Louis's avatar
Louis committed
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
            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),
            )

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

289
290
291
292
293
294
295
296
297
298
299
    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)