Skip to content

Commit bc5ef5f

Browse files
authored
Add JSON file output option (#5)
1 parent 772ef2e commit bc5ef5f

3 files changed

Lines changed: 43 additions & 10 deletions

File tree

src/nomad_actions/actions/entries/activities.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ async def create_artifact_subdirectory(data: CreateArtifactSubdirectoryInput) ->
3737
async def search(data: SearchInput) -> list[str]:
3838
"""
3939
Activity to perform NOMAD search based on the provided input data. The search
40-
results are written to a file in the specified format (Parquet or CSV) in the
40+
results are written to a file in the specified format (Parquet, CSV, or JSON) in the
4141
artifacts directory.
4242
4343
Args:
@@ -46,24 +46,30 @@ async def search(data: SearchInput) -> list[str]:
4646
Returns:
4747
list[str]: List of the generated output file paths.
4848
"""
49-
from nomad.search import search
49+
from nomad.search import search as nomad_search
5050

51-
from nomad_actions.actions.entries.utils import write_csv_file, write_parquet_file
51+
from nomad_actions.actions.entries.utils import (
52+
write_csv_file,
53+
write_json_file,
54+
write_parquet_file,
55+
)
5256

5357
logger = activity.logger
5458

5559
if data.output_file_type == 'parquet':
5660
write_dataset_file = write_parquet_file
5761
elif data.output_file_type == 'csv':
5862
write_dataset_file = write_csv_file
63+
elif data.output_file_type == 'json':
64+
write_dataset_file = write_json_file
5965
else:
60-
raise ValueError('Unsupported file format. Please use parquet or csv.')
66+
raise ValueError('Unsupported file format. Please use parquet, csv, or json.')
6167

6268
generated_file_paths = []
6369

6470
# first query
6571
search_counter = 1
66-
response = search(
72+
response = nomad_search(
6773
user_id=data.user_id,
6874
owner=data.owner,
6975
query=data.query,
@@ -86,7 +92,7 @@ async def search(data: SearchInput) -> list[str]:
8692
# create a copy to preserve the original pagination settings
8793
pagination = data.pagination.model_copy()
8894
pagination.page_after_value = response.pagination.next_page_after_value
89-
response = search(
95+
response = nomad_search(
9096
user_id=data.user_id,
9197
owner=data.owner,
9298
query=data.query,
@@ -111,7 +117,7 @@ async def search(data: SearchInput) -> list[str]:
111117
@activity.defn
112118
async def consolidate_output_files(data: ConsolidateOutputFilesInput) -> str:
113119
"""
114-
Activity to consolidate multiple Parquet or CSV files into a single file.
120+
Activity to consolidate multiple Parquet, CSV, or JSON files into a single file.
115121
116122
Args:
117123
data (ConsolidateOutputFilesInput): Input data for consolidating files.

src/nomad_actions/actions/entries/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from pydantic import BaseModel, Field
66

77
OwnerLiteral = Literal['public', 'visible', 'shared', 'user', 'staging']
8-
OutputFileTypeLiteral = Literal['parquet', 'csv']
8+
OutputFileTypeLiteral = Literal['parquet', 'csv', 'json']
99
IndexLiteral = Literal['entries', 'datasets', 'models', 'spaces']
1010

1111

src/nomad_actions/actions/entries/utils.py

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,24 @@ def write_csv_file(path: str, data: list[dict]):
4444
df.to_csv(path, index=False, mode='w', header=True)
4545

4646

47+
def write_json_file(path: str, data: list[dict]):
48+
"""Writes a list of NOMAD entry dicts to a JSON file.
49+
50+
Args:
51+
path (str): The path where the file will be saved.
52+
data (list[dict]): The list of NOMAD entry dicts to be written to the file.
53+
"""
54+
if not path.endswith('json'):
55+
raise ValueError('Unsupported file type. Please use JSON.')
56+
57+
import json
58+
59+
with open(path, 'w') as f:
60+
json.dump(data, f, indent=4)
61+
62+
4763
def consolidate_files(input_file_paths: list[str], output_file_path: str):
48-
"""Consolidates multiple Parquet or CSV files into a single file.
64+
"""Consolidates multiple Parquet, CSV, or JSON files into a single file.
4965
5066
Args:
5167
input_file_paths (list[str]): List of file paths to be consolidated.
@@ -78,5 +94,16 @@ def consolidate_files(input_file_paths: list[str], output_file_path: str):
7894
dataframes.append(df)
7995
combined_df = pd.concat(dataframes, ignore_index=True)
8096
combined_df.to_csv(output_file_path, index=False)
97+
elif output_file_path.endswith('json'):
98+
import json
99+
100+
combined_data = []
101+
for file_path in input_file_paths:
102+
with open(file_path, encoding='utf-8') as f:
103+
data = json.load(f)
104+
# extend the combined entry list with entry list from each file
105+
combined_data.extend(data)
106+
with open(output_file_path, 'w', encoding='utf-8') as f:
107+
json.dump(combined_data, f, indent=4)
81108
else:
82-
raise ValueError('Unsupported file type. Please use parquet or CSV.')
109+
raise ValueError('Unsupported file type. Please use parquet, CSV, or JSON.')

0 commit comments

Comments
 (0)