~jstys-z/helioviewer.org/client5

« back to all changes in this revision

Viewing changes to api/scripts/youtube_stats.py

  • Committer: Keith Hughitt
  • Date: 2012-06-12 20:18:46 UTC
  • Revision ID: keith.hughitt@gmail.com-20120612201846-k3nm2g2sznpfumhc
Added latest movies page

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
#-*- coding:utf-8 -*-
 
3
"""
 
4
YouTube View Count Statistics
 
5
 
 
6
Queries YouTube and determines the total number of views of Helioviewer.org
 
7
videos.
 
8
 
 
9
To generate list of 
 
10
mysql -uUSERNAME -p DBNAME -e "SELECT youtubeId FROM youtube WHERE youtubeId IS NOT NULL" | sed 1d > youtube_ids
 
11
 
 
12
"""
 
13
import os
 
14
import sys
 
15
import argparse
 
16
import gdata.youtube
 
17
import gdata.youtube.service
 
18
import numpy as np
 
19
 
 
20
def main():
 
21
    """Main"""
 
22
    args = get_args()
 
23
    
 
24
    # Connect to YouTube
 
25
    yt_service = gdata.youtube.service.YouTubeService()
 
26
    yt_service.ssl = True
 
27
    
 
28
    # Read list of ids
 
29
    ids = open(args.file).read().splitlines()
 
30
    
 
31
    counts = []
 
32
    retries = {i:0 for i in ids} # Limit number of retries due to network failures
 
33
 
 
34
    for video_id in ids:
 
35
        try:
 
36
            entry = yt_service.GetYouTubeVideoEntry(video_id=video_id)
 
37
            counts.append(int(entry.statistics.view_count))
 
38
        except gdata.service.RequestError:
 
39
            retries[video_id] += 1
 
40
            
 
41
            if retries[video_id] > 1:
 
42
                print("Retrying %s (try #%d)" % (video_id, retries[video_id]))
 
43
            
 
44
            #For request errors, append back to end of the queue
 
45
            if retries[video_id] <= 20:
 
46
                ids.append(video_id)
 
47
 
 
48
        except AttributeError:
 
49
            # If entry.statistics is None, stats are unavailable (hidden by user?)
 
50
            print("Skipping %s (Statistics Unavailable)" % video_id)
 
51
            
 
52
    counts = np.array(counts)
 
53
    
 
54
    print("===========")
 
55
    print(" Summary")
 
56
    print("===========")
 
57
    print("Total views: %d" % counts.sum())
 
58
    print("Min: %d" % counts.min())
 
59
    print("Max: %d" % counts.max())
 
60
 
 
61
def get_args():
 
62
    """Get command-line arguments"""
 
63
    parser = argparse.ArgumentParser(description='Collects statistics on videos uploaded to YouTube from Helioviewer.org.')
 
64
    parser.add_argument('file', metavar='FILE', 
 
65
                        help='File containing a newline-delimited list of YouTube movie ids.')
 
66
    args = parser.parse_args()
 
67
    
 
68
    if not os.path.isfile(args.file):
 
69
        sys.exit("Invalid file specified: %s" % args.file)
 
70
    
 
71
    return args
 
72
 
 
73
if __name__ == '__main__':
 
74
    sys.exit(main())