]> code.communitydata.science - covid19.git/blob - wikipedia/scripts/fetch_enwiki_daily_views.py
changes to allow historical view data collection
[covid19.git] / wikipedia / scripts / fetch_enwiki_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 import sys
13 import requests
14 import argparse
15 import json
16 import time
17 import os.path
18 import datetime
19 import logging
20 from csv import DictWriter
21 import digobs
22 #import feather #TBD
23
24 def parse_args():
25     parser = argparse.ArgumentParser(description='Call the views API to collect Wikipedia view data.')
26     parser.add_argument('-o', '--output_folder', help='Where to save output', default="wikipedia/data", type=str)
27     parser.add_argument('-i', '--article_file', help='File listing article names', default="wikipedia/resources/enwp_wikiproject_covid19_articles.txt", type=str)
28     parser.add_argument('-d', '--query_date', help='Date if not yesterday, in YYYYMMDD format.', type=str)
29     parser.add_argument('-L', '--logging_level', help='Logging level. Options are debug, info, warning, error, critical. Default: info.', default='info', type=digobs.get_loglevel), 
30     parser.add_argument('-W', '--logging_destination', help='Logging destination file. (default: standard error)', type=str), 
31     args = parser.parse_args()
32     return(args)
33
34 def main():
35
36     args = parse_args()
37
38     outputPath = args.output_folder
39     articleFile = args.article_file
40
41     #handle -d
42     if args.query_date:
43         query_date = args.query_date
44     else:
45         yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
46         query_date = yesterday.strftime("%Y%m%d")
47
48     #handle -W
49     if args.logging_destination:
50         logging.basicConfig(filename=args.logging_destination, filemode='a', level=args.logging_level)
51     else:
52         logging.basicConfig(level=args.logging_level)
53
54     export_time = str(datetime.datetime.now())
55     export_date = datetime.datetime.today().strftime("%Y%m%d")
56
57     logging.info(f"Starting run at {export_time}")
58     logging.info(f"Last commit: {digobs.git_hash()}")
59
60     #1 Load up the list of article names
61     j_outfilename = os.path.join(outputPath, f"digobs_covid19-wikipedia-enwiki_dailyviews-{query_date}.json")
62     t_outfilename = os.path.join(outputPath, f"digobs_covid19-wikipedia-enwiki_dailyviews-{query_date}.tsv")
63
64     with open(articleFile, 'r') as infile:
65         articleList = list(map(str.strip, infile))
66
67     success = 0 #for logging how many work/fail
68     failure = 0 
69
70     #3 Save results as a JSON and TSV
71     with open(j_outfilename, 'w') as j_outfile, \
72          open(t_outfilename, 'w') as t_outfile:
73
74         #2 Repeatedly call the API with that list of names
75         for a in articleList:
76             url= f"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/{a}/daily/{query_date}00/{query_date}00"
77
78             response = requests.get(url)
79             if response.ok:
80                 jd = response.json()["items"][0]
81                 success = success + 1
82             else:
83                 failure = failure + 1
84                 logging.warning(f"Failure: {response.status_code} from {url}")
85                 continue
86
87             # start writing the CSV File if it doesn't exist yet
88             try:
89                 dw
90             except NameError:
91                 dw = DictWriter(t_outfile, sorted(jd.keys()), delimiter='\t')
92                 dw.writeheader()
93
94             logging.debug(f"printing data: {jd}")
95
96             # write out the line of the json file
97             print(json.dumps(jd), file=j_outfile)
98
99             # write out of the csv file
100             dw.writerow(jd)
101
102     # f_Out = outputPath + "dailyviews" + query_date + ".feather"
103     # read the json back in and make a feather file? 
104     logging.debug(f"Run complete at {datetime.datetime.now()}")
105     logging.info(f"Processed {success} successful URLs and {failure} failures.")
106
107
108 if __name__ == "__main__":
109
110     main()

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