Skip to content

Commit 441b344

Browse files
committed
Updated method
1 parent b6b021e commit 441b344

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed

brainimagelibrary/inventory.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
import uuid
33
import requests
44
import pandas as pd
5+
import gzip
6+
import io
7+
import json
58

69

710
def summary(dataset_id=None):
@@ -62,40 +65,40 @@ def __generate_dataset_uuid(directory):
6265

6366
return str(uuid.uuid5(uuid.NAMESPACE_DNS, directory))
6467

65-
6668
def get(dataset_id=None):
6769
"""
68-
Retrieves metadata for a dataset by its ID.
70+
Retrieves metadata for a dataset by its ID from a compressed JSON (.json.gz).
6971
7072
Args:
7173
dataset_id (str, optional): The unique identifier for the dataset. Defaults to None.
7274
7375
Returns:
74-
dict: A dictionary containing the dataset metadata if the request is successful.
75-
None: If the request fails or encounters an exception.
76+
dict | None: Dataset metadata if successful, otherwise None.
7677
"""
7778
if dataset_id is None:
7879
print("Error: dataset_id must be provided.")
7980
return None
8081

81-
filename = f"{dataset_id}.json"
82+
filename = f"{dataset_id}.json.gz"
8283
url = f"https://download.brainimagelibrary.org/inventory/datasets/{filename}"
8384

8485
try:
85-
response = requests.get(url, timeout=30)
86-
87-
# Check if request was successful
88-
if response.status_code != 200:
89-
print(f"Error: received status code {response.status_code} for {url}")
86+
resp = requests.get(url, timeout=30)
87+
if resp.status_code != 200:
88+
print(f"Error: received status code {resp.status_code} for {url}")
9089
return None
9190

92-
# Ensure we got JSON
9391
try:
94-
return response.json()
95-
except ValueError:
96-
print("Error: Response is not valid JSON.")
92+
with gzip.GzipFile(fileobj=io.BytesIO(resp.content)) as gz:
93+
data = json.load(gz)
94+
return data
95+
except gzip.BadGzipFile:
96+
print("Error: Response is not a valid gzip file.")
97+
return None
98+
except json.JSONDecodeError as e:
99+
print(f"Error: Decompressed content is not valid JSON: {e}")
97100
return None
98101

99102
except requests.exceptions.RequestException as e:
100103
print(f"Error making API request: {e}")
101-
return None
104+
return None

0 commit comments

Comments
 (0)