]> code.communitydata.science - covid19.git/blob - bin/fetch_daily_views.py
initial files
[covid19.git] / bin / fetch_daily_views.py
1 #!/usr/bin/env python3
2
3 ###############################################################################
4 #
5 # This script assumes the presence of the COVID-19 repo.
6
7 # It (1) reads in the article list and then (2) calls the Wikimedia API to 
8 # fetch view information for each article. Output is to (3) JSON and TSV.
9 #
10 ###############################################################################
11
12
13 #1 Load up the list of article names
14
15 #2 Repeatedly call the API with that list of names
16
17 #3 Save results as a TSV
18
19 import requests
20 import argparse
21 import json
22 import csv
23 import time
24 import os.path
25 import datetime
26 #import feather
27
28
29
30 def parse_args():
31
32     parser = argparse.ArgumentParser(description='Call the views API repeatedly.')
33     parser.add_argument('-o', '--output_folder', help='Where to save output', default="../data/", type=str)
34     parser.add_argument('-i', '--article_file', help='File listing article names', default="../resources/articles.txt", type=str)
35     parser.add_argument('-d', '--query_date', help='Date if not yesterday, in YYYYMMDD format please.', type=str)
36     args = parser.parse_args()
37
38     return(args)
39
40
41 def main():
42
43     args = parse_args()
44
45     outputPath = args.output_folder
46     articleFile = args.article_file
47
48     if (args.query_date):
49         queryDate = args.query_date
50     else:
51         yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
52         queryDate = yesterday.strftime("%Y%m%d")
53
54     queryDate = queryDate + "00" #requires specifying hours
55
56
57     articleList = []
58     with open(articleFile, 'r') as infileHandle:
59         #theInfile = csv.reader(infileHandle, quotechar='"')
60         theInfile = csv.reader(infileHandle)
61         next(theInfile) #skip header
62         for currentLine in theInfile:
63             articleList.append(currentLine)
64
65     j_Out = outputPath + "dailyviews" + queryDate + ".json"
66     t_Out = outputPath + "dailyviews" + queryDate + ".tsv"
67
68     j = []
69
70     i = 0 #iterator to deal with end of file
71
72     for a in articleList:
73         a = a[0] #destringify
74         i = i+1
75         url= "https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/"
76         url= url + a + "/daily/" + queryDate + "/" + queryDate #for now, single date at a time
77         response = requests.get(url)
78         if response.ok:
79             jd = json.loads(response.content)
80             j.append(jd["items"][0])
81             time.sleep(.1)
82
83
84     #all data in j now, make json file
85     with open(j_Out, 'w') as j_outfile: 
86         json.dump(j, j_outfile, indent=2)
87
88     with open(t_Out, 'w') as t_outfile:
89         dw = csv.DictWriter(t_outfile, sorted(j[0].keys()), delimiter='\t')
90         dw.writeheader()
91         dw.writerows(j)
92
93
94     f_Out = outputPath + "dailyviews" + queryDate + ".feather"
95     #read the json back in and make a feather file? 
96
97
98 if __name__ == "__main__":
99
100     main()

Community Data Science Collective || Want to submit a patch?