File size: 2,071 Bytes
d6e767b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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.")