]> code.communitydata.science - covid19.git/blob - wikipedia_views/scripts/fetch_daily_views.py
stop writing writing header to one-column list
[covid19.git] / wikipedia_views / scripts / 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 import requests
14 import argparse
15 import json
16 import csv
17 import time
18 import os.path
19 import datetime
20 import logging
21 #import feather #TBD
22
23
24 def parse_args():
25
26     parser = argparse.ArgumentParser(description='Call the views API repeatedly.')
27     parser.add_argument('-o', '--output_folder', help='Where to save output', default="../data/", type=str)
28     parser.add_argument('-i', '--article_file', help='File listing article names', default="../resources/articles.txt", type=str)
29     parser.add_argument('-d', '--query_date', help='Date if not yesterday, in YYYYMMDD format please.', type=str)
30     parser.add_argument('-L', '--logging_level', help='Logging level. Options are debug, info, warning, error, critical. Default: info.', default='info'), 
31     parser.add_argument('-W', '--logging_destination', help='Logging destination.', default='../logs/'), 
32     args = parser.parse_args()
33
34     return(args)
35
36
37 def main():
38
39     args = parse_args()
40
41     outputPath = args.output_folder
42     articleFile = args.article_file
43
44     #handle -d
45     if (args.query_date):
46         queryDate = args.query_date
47     else:
48         yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
49         queryDate = yesterday.strftime("%Y%m%d")
50
51     queryDate = queryDate + "00" #requires specifying hours
52
53     #handle -W
54     logHome = f"{args.logging_destination}dailylogrun{datetime.datetime.today().strftime('%Y%m%d')}"
55
56     #handle -L
57     loglevel = args.logging_level
58     if loglevel == 'debug':
59         logging.basicConfig(filename=logHome, filemode='a', level=logging.DEBUG)
60     elif loglevel == 'info':
61         logging.basicConfig(filename=logHome, filemode='a', level=logging.INFO)
62     elif loglevel == 'warning':
63         logging.basicConfig(filename=logHome, filemode='a', level=logging.WARNING)
64     elif loglevel == 'error':
65         logging.basicConfig(filename=logHome, filemode='a', level=logging.ERROR)
66     elif loglevel == 'critical':
67         logging.basicConfig(filename=logHome, filemode='a', level=logging.CRITICAL)
68     else: 
69         print("Choose a valid log level: debug, info, warning, error, or critical") 
70         exit
71
72
73     articleList = []
74     logging.debug(f"Starting run at {datetime.datetime.now()}")
75
76     #1 Load up the list of article names
77
78     j_Out = f"{outputPath}dailyviews{queryDate}.json"
79     t_Out = f"{outputPath}dailyviews{queryDate}.tsv"
80
81     with open(articleFile, 'r') as infile:
82         articleList = list(infile)
83
84     j = []
85     success = 0 #for logging how many work/fail
86     failure = 0 
87
88     #2 Repeatedly call the API with that list of names
89
90     for a in articleList:
91         a = a.strip("\"\n") #destringify
92         url= f"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/{a}/daily/{queryDate}/{queryDate}"
93
94         response = requests.get(url)
95         if response.ok:
96             jd = json.loads(response.content)
97             j.append(jd["items"][0])
98             time.sleep(.1)
99             success = success + 1
100         else:
101             failure = failure + 1
102             logging.warning(f"Failure: {response.status_code} from {url}")
103
104     #3 Save results as a JSON and TSV
105
106     #all data in j now, make json file
107     logging.info(f"Processed {success} successful URLs and {failure} failures.")
108
109     with open(j_Out, 'w') as j_outfile: 
110         json.dump(j, j_outfile, indent=2)
111
112     with open(t_Out, 'w') as t_outfile:
113         dw = csv.DictWriter(t_outfile, sorted(j[0].keys()), delimiter='\t')
114         dw.writeheader()
115         dw.writerows(j)
116
117     logging.debug(f"Run complete at {datetime.datetime.now()}")
118
119     # f_Out = outputPath + "dailyviews" + queryDate + ".feather"
120     # read the json back in and make a feather file? 
121
122
123 if __name__ == "__main__":
124
125     main()

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