Skip to content

Commit e4b09be

Browse files
committed
Refactor redundant code, add error handling, optimize performance, improve readability.
1 parent 37b6ff9 commit e4b09be

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

braininventory/get.py

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,40 @@
1010
import squarify
1111
import matplotlib.pyplot as plt
1212

13-
def get_jsonFile(df):
13+
14+
def get_random_sample(df):
1415
"""
16+
Returns a random sample from the dataframe from a dataset with non-zero score.
17+
1518
Input: dataframe
16-
Output:open the jsonFile that was located in datasets Brain Image Library dataframe
19+
Output:open the json file that was located in datasets Brain Image Library dataframe
1720
"""
18-
isNotZero = df[df["score"] != 0.0] #only have files with the correct data
19-
randomRow = isNotZero.iloc[random.randint(0, len(isNotZero))] #select a random row of random index
20-
jsonFileLink = randomRow.json_file.replace("/bil/data", "https://download.brainimagelibrary.org", 1) #create the link
21+
22+
isNotZero = df[df["score"] != 0.0] # only have files with the correct data
23+
randomRow = isNotZero.iloc[
24+
random.randint(0, len(isNotZero))
25+
] # select a random row of random index
26+
jsonFileLink = randomRow.json_file.replace(
27+
"/bil/data", "https://download.brainimagelibrary.org", 1
28+
) # create the link
2129
result = requests.get(jsonFileLink)
2230

2331
return result.json()
24-
32+
33+
2534
def today():
2635
"""
2736
Get today's snapshot of Brain Image Library.
2837
"""
2938

39+
# if file can be found locally, then load from disk
40+
directory = "/bil/data/inventory/daily/reports/"
41+
if Path(directory).exists():
42+
data = json.loads(f"{directory}/today.json")
43+
data = pd.DataFrame(data)
44+
return data
45+
46+
# else get file from the web
3047
server = "https://download.brainimagelibrary.org/inventory/daily/reports/"
3148
filename = "today.json"
3249

@@ -38,7 +55,6 @@ def today():
3855
data = json.loads(response.text)
3956
data = pd.DataFrame(data)
4057
return data
41-
4258
else:
4359
print("Error: Failed to fetch JSON data")
4460
return pd.DataFrame()

0 commit comments

Comments
 (0)