-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_utils.py
245 lines (206 loc) · 8.84 KB
/
file_utils.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
Provides utility functions for file and metadata handling.
"""
import json
import tempfile
import os
from io import BytesIO
from tempfile import gettempdir
import pandas as pd
import requests
import croissant
import dcat
import de
import migration
def extract_metadata(json_data):
"""
Extracts metadata from a given JSON object.
Args:
json_data (dict): JSON data containing metadata information.
Returns:
dict: A dictionary containing extracted metadata.
"""
metadata = {
'title': json_data.get('title', 'Untitled'),
'description': json_data.get('description', 'No description provided.'),
'author': json_data.get('author', 'Unknown author'),
'keywords': json_data.get('keyword', []),
'publisher': json_data.get('publisher', {}).get('name', 'Unknown publisher'),
'date_published': json_data.get('datePublished', 'Unknown date'),
'license_url': json_data.get('license', 'No license specified')
}
return metadata
def generate_croissant_json(username, password, de_link, title, description, author):
"""
Generates a Croissant JSON-LD file for a dataset.
Args:
username (str): The username for authentication.
password (str): The password for authentication.
de_link (str): The Discovery Environment link to the dataset.
title (str): The title of the dataset.
description (str): The description of the dataset.
author (str): The author of the dataset.
Returns:
str: The path to the generated Croissant JSON-LD file or an error message.
"""
# Obtain DE API token
token = de.get_de_api_key(username, password)
if token is None:
return "Error obtaining DE API key. Please check username and password."
# Set up headers for authorization
headers = {'Authorization': f'Bearer {token}'}
path_parts = de_link.split('/')
directory_path = '/'.join(path_parts[:-1]) # Get directory path
# Get datasets from the directory
datasets = de.get_datasets(directory_path, headers)
for dataset in datasets:
if dataset['path'] == de_link:
dataset_metadata = de.get_all_metadata_dataset(dataset)
break
if not title:
title = migration.get_title(dataset_metadata)
if not description:
description = migration.get_description(dataset_metadata)
if not author:
author = migration.get_author(dataset_metadata)
# Extract keywords from dataset metadata
keywords = []
if 'subject' in dataset_metadata:
subjects = dataset_metadata['subject']
if isinstance(subjects, str):
subjects = (subjects.replace("(", "")
.replace(")", "")
.replace("&", "-")
.split(','))
keywords = list(subjects)
else:
keywords = [subject
.replace("(", "")
.replace(")", "")
.replace("&", "-")
.replace("#", "-")
for subject in subjects]
for tag in keywords:
if ', ' in tag:
keywords.remove(tag)
keywords += [{'name': t.strip()} for t in tag.split(',')]
# Get dataset version
version = dataset_metadata.get('version', dataset_metadata.get('Version', ''))
# Get list of files in the dataset
files = de.get_files(dataset_metadata['de_path'])
num_files = files['total']
distributions = []
if num_files is not None:
files = de.get_files(dataset_metadata['de_path'], limit=num_files)
for file in files['files']:
file_metadata = de.get_all_metadata_file(file)
distribution = croissant.create_distribution(file_metadata['file_name'],
file_metadata['file_type'],
file_metadata['web_dav_location'])
distributions.append(distribution)
# Create Croissant JSON-LD
croissant_json = croissant.create_croissant_jsonld(title, description, author,
keywords=keywords, version=version,
distributions=distributions)
temp_dir = tempfile.gettempdir() # Get temporary directory
output_filename = os.path.join(temp_dir, "croissant.json")
with open(output_filename, "w", encoding="utf-8") as f:
json.dump(croissant_json, f, indent=4)
return output_filename
def generate_dcat_json(username, password, de_link, title, description, author):
"""
Generates a DCAT JSON-LD file for a dataset.
Args:
username (str): The username for authentication.
password (str): The password for authentication.
de_link (str): The Discovery Environment link to the dataset.
title (str): The title of the dataset.
description (str): The description of the dataset.
author (str): The author of the dataset.
Returns:
str: The path to the generated DCAT JSON-LD file or an error message.
"""
# Obtain DE API token
token = de.get_de_api_key(username, password)
if token is None:
return "Error obtaining DE API key. Please check username and password."
# Set up headers for authorization
headers = {'Authorization': f'Bearer {token}'}
path_parts = de_link.split('/')
directory_path = '/'.join(path_parts[:-1]) # Get directory path
# Get datasets from the directory
datasets = de.get_datasets(directory_path, headers)
for dataset in datasets:
if dataset['path'] == de_link:
dataset_metadata = de.get_all_metadata_dataset(dataset)
break
if not title:
title = migration.get_title(dataset_metadata)
if not description:
description = migration.get_description(dataset_metadata)
if not author:
author = migration.get_author(dataset_metadata)
# Extract keywords from dataset metadata
keywords = []
if 'subject' in dataset_metadata:
subjects = dataset_metadata['subject']
if isinstance(subjects, str):
subjects = (subjects.replace("(", "")
.replace(")", "")
.replace("&", "-")
.split(','))
keywords = list(subjects)
else:
keywords = [subject.replace("(", "")
.replace(")", "").replace("&", "-")
.replace("#", "-")
for subject in subjects]
for tag in keywords:
if ', ' in tag:
keywords.remove(tag)
keywords += [{'name': t.strip()} for t in tag.split(',')]
# Get dataset version
version = dataset_metadata.get('version', dataset_metadata.get('Version', ''))
# Get list of files in the dataset
files = de.get_files(dataset_metadata['de_path'])
num_files = files['total']
distributions = []
if num_files is not None:
files = de.get_files(dataset_metadata['de_path'], limit=num_files)
for file in files['files']:
file_metadata = de.get_all_metadata_file(file)
distribution = dcat.create_distribution(file_metadata['file_name'],
file_metadata['file_type'],
file_metadata['web_dav_location'])
distributions.append(distribution)
# Create DCAT JSON-LD
dcat_json = dcat.create_dcat_jsonld(title, description, author,
keywords=keywords, version=version,
distributions=distributions)
temp_dir = tempfile.gettempdir() # Get temporary directory
output_filename = os.path.join(temp_dir, "dcat.json")
with open(output_filename, "w", encoding="utf-8") as f:
json.dump(dcat_json, f, indent=4)
return output_filename
# Function to convert CSV to Parquet
def convert_csv_to_parquet(files):
"""
Convert CSV files to Parquet format.
Args:
files: The list of files to be converted.
Returns:
list: The list of files with CSV files converted to Parquet.
"""
parquet_files = []
for file in files['files']:
if file['file_type'] == 'csv':
csv_url = file['web_dav_location']
response = requests.get(csv_url, timeout=10)
csv_data = pd.read_csv(BytesIO(response.content))
parquet_filename = file['file_name'].replace('.csv', '.parquet')
parquet_filepath = os.path.join(gettempdir(), parquet_filename)
csv_data.to_parquet(parquet_filepath)
file['web_dav_location'] = parquet_filepath
file['file_type'] = 'parquet'
parquet_files.append(file)
return parquet_files