Datasets:
Upload folder using huggingface_hub
Browse files- utils/nyt_archive_downloader.py +107 -0
utils/nyt_archive_downloader.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import random
|
| 5 |
+
from concurrent.futures import Future, ThreadPoolExecutor
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from typing import Dict, List, Tuple
|
| 8 |
+
|
| 9 |
+
import requests
|
| 10 |
+
from tenacity import retry, wait_exponential, stop_after_delay
|
| 11 |
+
|
| 12 |
+
logging.basicConfig(level=logging.INFO)
|
| 13 |
+
LOGGER = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
API_KEYS = [
|
| 16 |
+
"6ZQc4XoaQPnHYOzKPLZR6kCR3ibSiafMxiWGCPeTx2VYI8cv", # Bruno
|
| 17 |
+
"MTXkBDV8cEEs9GQk6MXrhg7DfXeqAA8Fyx28sCcn7axcXeTc", # User 1
|
| 18 |
+
"ATqaJHb8eWZraTHOn2IO9TRAlkSYPkbaTDtVNaUzPVtbUVXu", # User 2
|
| 19 |
+
"EEnruAuDHEhLyArTgPA3hbwthxl02jWxOBRxSMlIJG5bpgWz", # User 3
|
| 20 |
+
"LdgKBnXAUSwWlDk0E2sf2SItbBEUvB31r1LHTf2z1fJweg5O", # User 4
|
| 21 |
+
"rip8LQojkkYnvKeaFB5J3InNBgOuOE0QTVbmOBR8cwLLKbAM", # User 5
|
| 22 |
+
"lsUcGIR8B3LmFKqlcRB3rqEWOh7Hv7swm9162dAHiDvSqB0G", # User 6
|
| 23 |
+
"ngxrdtaLKqhaAL45dSMokE07XC76MmTLWcSc8P6Gq3QRlJLk", # User 7
|
| 24 |
+
"Vnd8jKCkt8YqjTJNtCdYqLXHHhf27QgRV7r52dE1CQObUpMi", # User 8
|
| 25 |
+
"MDSNT0GTV4yTjxLz6nUqjjRz0kyU1k679gfzUf8VlZvHK5eu", # User 9
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
YEAR_START = 1927
|
| 29 |
+
YEAR_END = 2026
|
| 30 |
+
|
| 31 |
+
JSON_RAW_DIR_DEST = "./data/nyt_news_dataset/bulk"
|
| 32 |
+
REQ_TIMEOUT = 60 * 10 # 10 minutes
|
| 33 |
+
THREAD_MULTIPLIER = 1
|
| 34 |
+
N_PROC = 8
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _initialize_folder(folder_path: str) -> None:
|
| 38 |
+
if not os.path.exists(folder_path):
|
| 39 |
+
os.makedirs(folder_path)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# 24 hours = 24 * 60 * 60 = 86,400 seconds
|
| 43 |
+
# Max wait capped at 5 minutes = 300 seconds
|
| 44 |
+
@retry(
|
| 45 |
+
stop=stop_after_delay(86400),
|
| 46 |
+
wait=wait_exponential(multiplier=2, min=1, max=300) # Backoff up to 5 minutes, than every 5 minutes
|
| 47 |
+
)
|
| 48 |
+
def _fetch_nyt_month(
|
| 49 |
+
year: int,
|
| 50 |
+
month: int,
|
| 51 |
+
api_key_list: List[str] = API_KEYS,
|
| 52 |
+
timeout: int = REQ_TIMEOUT,
|
| 53 |
+
json_out_dir: str = JSON_RAW_DIR_DEST,
|
| 54 |
+
) -> None:
|
| 55 |
+
|
| 56 |
+
_initialize_folder(json_out_dir)
|
| 57 |
+
file_name = f"nyt_{year}_{month}.json"
|
| 58 |
+
f_path = os.path.join(json_out_dir, file_name)
|
| 59 |
+
if os.path.exists(f_path):
|
| 60 |
+
LOGGER.warning(f"File {f_path} already exists!")
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
url = f"https://api.nytimes.com/svc/archive/v1/{year}/{month}.json"
|
| 64 |
+
params = {"api-key": random.choice(api_key_list)}
|
| 65 |
+
LOGGER.info(f"Fetching articles for {year}-{month} from {url}")
|
| 66 |
+
response = requests.get(url, params=params, timeout=timeout)
|
| 67 |
+
|
| 68 |
+
if response.status_code != 200:
|
| 69 |
+
LOGGER.error(f"HTTP response {response.status_code} for {url}!")
|
| 70 |
+
raise ValueError(f"HTTP response {response.status_code}!")
|
| 71 |
+
|
| 72 |
+
LOGGER.info(f"Fetched articles for {year}-{month} from {response.url}")
|
| 73 |
+
|
| 74 |
+
json_obj = response.json()
|
| 75 |
+
if not json_obj:
|
| 76 |
+
LOGGER.warning(f"No data found for {year}-{month} from {response.url}")
|
| 77 |
+
|
| 78 |
+
with open(f_path, "w", encoding="utf-8") as f:
|
| 79 |
+
json.dump(json_obj, f, ensure_ascii=False, indent=4)
|
| 80 |
+
LOGGER.info(f"Saved JSON file to {f_path}")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def fetch_nyt_archive(
|
| 84 |
+
start_year: int = YEAR_START,
|
| 85 |
+
end_year: int = YEAR_END,
|
| 86 |
+
thread_mul: int = THREAD_MULTIPLIER,
|
| 87 |
+
n_proc: int = N_PROC,
|
| 88 |
+
) -> None:
|
| 89 |
+
max_workers = n_proc * thread_mul
|
| 90 |
+
|
| 91 |
+
futures: List[Tuple[str, Future]] = []
|
| 92 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 93 |
+
for year in range(start_year, end_year + 1):
|
| 94 |
+
for month in range(1, 13):
|
| 95 |
+
future_exec = executor.submit(_fetch_nyt_month, year, month)
|
| 96 |
+
futures.append((f"{year}-{month}", future_exec))
|
| 97 |
+
|
| 98 |
+
for str_key, future in futures:
|
| 99 |
+
try:
|
| 100 |
+
future.result()
|
| 101 |
+
except Exception:
|
| 102 |
+
LOGGER.exception(f"Error processing {str_key}. Skipped!")
|
| 103 |
+
LOGGER.info("Done!")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
fetch_nyt_archive()
|