SCAND / download_data.py
franciszzj's picture
Add files using upload-large-folder tool
d6e767b verified
import os
import time
from pyDataverse.api import NativeApi, DataAccessApi
from pyDataverse.models import Dataverse
import requests
base_url = 'https://dataverse.tdl.org/'
api_token = "70fcc8fa-3717-4c1b-863d-2da0fb5d9d35"
api = NativeApi(base_url, api_token)
data_api = DataAccessApi(base_url)
DOI = "doi:10.18738/T8/0PRYRH"
dataset = api.get_dataset(DOI)
if not os.path.exists("random_mdps"):
os.makedirs("random_mdps")
if not os.path.exists("delivery_mdp"):
os.makedirs("delivery_mdp")
files_list = dataset.json()['data']['latestVersion']['files']
# Function to download a file with retry mechanism and exponential backoff
def download_file(download_url, headers, dir, filename):
max_retries = 5
backoff_factor = 1
for attempt in range(max_retries):
try:
with requests.get(download_url, headers=headers, stream=True) as response:
response.raise_for_status()
with open(os.path.join(dir, filename), "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Successfully downloaded: {filename}")
return
except requests.RequestException as e:
wait_time = backoff_factor * (2 ** attempt)
print(f"Error downloading {filename}: {str(e)}. Retrying in {wait_time} seconds...")
time.sleep(wait_time)
print(f"Failed to download {filename} after {max_retries} attempts.")
for file in files_list:
filename = file["dataFile"]["filename"]
file_id = file["dataFile"]["id"]
print(f"Downloading: File name {filename}, id {file_id}")
# Construct the download URL
download_url = f"{base_url}api/access/datafile/{file_id}"
# Set up the request headers with the API token
headers = {'X-Dataverse-key': api_token}
# Determine the directory
dir = "delivery_mdp/" if "DELIVERY" in filename else "random_mdps/"
# Download the file
download_file(download_url, headers, dir, filename)
print("Download process completed.")