3 ###############################################################################
5 # This script assumes the presence of the COVID-19 repo.
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.
10 ###############################################################################
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()
41 outputPath = args.output_folder
42 articleFile = args.article_file
46 queryDate = args.query_date
48 yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
49 queryDate = yesterday.strftime("%Y%m%d")
51 queryDate = queryDate + "00" #requires specifying hours
54 logHome = f"{args.logging_destination}dailylogrun{datetime.datetime.today().strftime('%Y%m%d')}"
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)
69 print("Choose a valid log level: debug, info, warning, error, or critical")
74 logging.debug(f"Starting run at {datetime.datetime.now()}")
76 #1 Load up the list of article names
78 j_Out = f"{outputPath}dailyviews{queryDate}.json"
79 t_Out = f"{outputPath}dailyviews{queryDate}.tsv"
81 with open(articleFile, 'r') as infile:
82 next(infile) #skip header
83 articleList = list(infile)
86 success = 0 #for logging how many work/fail
89 #2 Repeatedly call the API with that list of names
92 a = a.strip("\"\n") #destringify
93 url= f"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/{a}/daily/{queryDate}/{queryDate}"
95 response = requests.get(url)
97 jd = json.loads(response.content)
98 j.append(jd["items"][0])
100 success = success + 1
102 failure = failure + 1
103 logging.warning(f"Failure: {response.status_code} from {url}")
105 #3 Save results as a JSON and TSV
107 #all data in j now, make json file
108 logging.info(f"Processed {success} successful URLs and {failure} failures.")
110 with open(j_Out, 'w') as j_outfile:
111 json.dump(j, j_outfile, indent=2)
113 with open(t_Out, 'w') as t_outfile:
114 dw = csv.DictWriter(t_outfile, sorted(j[0].keys()), delimiter='\t')
118 logging.debug(f"Run complete at {datetime.datetime.now()}")
120 # f_Out = outputPath + "dailyviews" + queryDate + ".feather"
121 # read the json back in and make a feather file?
124 if __name__ == "__main__":