/
youtube-stat.py
executable file
·141 lines (118 loc) · 4.07 KB
/
youtube-stat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#!/usr/bin/python -tt
# -*- coding: UTF-8 -*-
# vim: ts=4 sw=4 et ai si
"""
Gather statistics of uploaded video by given user.
"""
__author__ = "Andy Shevchenko <andy.shevchenko@gmail.com>"
__license__ = "GPLv2"
import os
import sys
import dateutil.parser
import datetime
import Gnuplot
import operator
from optparse import OptionParser
import gdata.youtube.service
def parse_video_entry(entry):
"""Parse video entry - retrive necessary fields."""
return {
'title' : entry.media.title.text,
'date' : dateutil.parser.parse(entry.published.text),
'desc' : entry.media.description.text,
'view count': int(entry.statistics.view_count),
}
def parse_video_feed(feed):
"""Parse video feed."""
data = {}
for entry in feed.entry:
data[entry.id.text] = parse_video_entry(entry)
return data
def get_user_uploads(username, version=2):
"""Get user's uploads and gather necessary data."""
service = gdata.youtube.service.YouTubeService()
base_uri = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?v=%d' % (username, version)
data = {}
start_index = 1
max_results = 50
while True:
uri = '%s&start-index=%d&max-results=%d' % (base_uri, start_index, max_results)
feed = service.GetYouTubeVideoFeed(uri)
entry_data = parse_video_feed(feed)
if entry_data:
data.update(entry_data)
if len(entry_data) == max_results:
start_index += max_results
continue
break
return data
def print_video_feed(username, data, outfile="-"):
"""Print short description of each entry."""
if outfile == '-':
fd = sys.stdout
else:
fd = open(outfile, 'w')
fd.write('List of videos published by %s\n\n' % username)
for id in data:
fd.write('Video title: %(title)s\n' % data[id])
fd.write('Video published on: %(date)s\n' % data[id])
fd.write('Video description: %(desc)s\n' % data[id])
fd.write('Video view count: %(view count)d\n' % data[id])
fd.write('---\n\n')
fd.close()
def plot_video_stat(username, data, outfile="-"):
"""Plot video statistics using Gnuplot."""
gp = Gnuplot.Gnuplot()
# Should be first command!
gp('set terminal png')
if outfile == '-':
gp('set output')
else:
gp('set output "%s"' % outfile)
gp.title('View count versus date of publishing for %s' % username)
gp.xlabel('Date')
gp.ylabel('View count')
gp('set autoscale')
gp('set xdata time')
gp('set xtics rotate')
timefmt = "%s"
gp('set timefmt "%s"' % timefmt)
xy = []
for id in data:
xy.append([
id,
int(data[id]['date'].strftime(timefmt)),
data[id]['view count'],
])
xy.sort(key=operator.itemgetter(1))
gpdata = Gnuplot.Data([x[1] for x in xy], [y[2] for y in xy],
using='1:2', with_='linespoints')
gp.plot(gpdata)
def main(argv):
"""MAIN"""
parser = OptionParser(usage='%prog [options] <youtube_username>')
parser.add_option("--show", dest="show", action="store_true", default=False,
help="show the feed entries")
parser.add_option("--output", dest="output", default="-",
help="save output to the FILE")
parser.add_option("--plot", dest="plot", action="store_true", default=False,
help="plot chart with statistics")
parser.add_option("--plot-file", dest="plot_file",
help="plot chart to the FILE")
(opts, args) = parser.parse_args(argv)
if len(args) == 1:
parser.error("incorrect number of arguments")
if not opts.show and not opts.plot:
parser.error("no action asked (--show or --plot)")
username = args[1]
data = get_user_uploads(username)
if opts.show:
print_video_feed(username, data, opts.output)
if opts.plot:
if opts.plot_file:
outfile = opts.plot_file
else:
outfile = "%s.png" % username
plot_video_stat(username, data, outfile)
if __name__ == "__main__":
sys.exit(main(sys.argv))