Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Read_SDMX method #159

Closed
wants to merge 28 commits into from
Closed
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
3664415
Draft code for read_sdmx.
javihern98 Dec 18, 2024
bdf8145
Merge branch 'develop' into 156-add-read_sdmx-convenience-method
javihern98 Dec 18, 2024
2d87af7
Refactored code on Message class to move submission and ActionType to…
javihern98 Dec 19, 2024
617aa4c
Linting and mypy changes
javihern98 Dec 19, 2024
2c2cab3
Refactored code to ensure we use the Short URN as keys of the message…
javihern98 Dec 19, 2024
ffb2a8e
Added tests for read_sdmx with csv files.
javihern98 Dec 19, 2024
01f5489
Linting and mypy changes.
javihern98 Dec 19, 2024
ab63f01
Adapted structures tests to reach max code coverage
javihern98 Dec 19, 2024
8b960d2
Removed unique_id method and adapted code to use Reference.
javihern98 Dec 19, 2024
41e7a8d
Added utils methods and classes to all.
javihern98 Dec 19, 2024
b140de0
Adapted tests for input processor to max code coverage.
javihern98 Dec 19, 2024
0c03933
Adapted tests for read_sdmx to max code coverage.
javihern98 Dec 19, 2024
f567c50
Added tag to concept and itemReference to avoid serialization issues.
javihern98 Dec 19, 2024
85076af
Merge remote-tracking branch 'refs/remotes/origin/develop' into 156-a…
javihern98 Dec 19, 2024
fe1fbb4
Fixed message imports to prevent circular imports. Ruff automatic fix…
javihern98 Dec 19, 2024
6b6886f
Adapted ReadSDMX to infer the format automatically.
javihern98 Jan 9, 2025
b6e6200
Linting changes.
javihern98 Jan 9, 2025
03dd8ad
Renamed ReadFormat to SDMXFormat. Added Submission and Error formats …
javihern98 Jan 9, 2025
bd27711
Ignored mypy error.
javihern98 Jan 10, 2025
5818c40
Added to_schema method to DataStructureDefinition. Draft code for get…
javihern98 Jan 10, 2025
6a4bac7
Replaced whole URN to Short URN in Dataset. Added tests to match cove…
javihern98 Jan 10, 2025
d38ed7f
Added get_datasets to io
javihern98 Jan 10, 2025
e2b2946
Added URL parsing support on read_sdmx. Made httpx a mandatory depend…
javihern98 Jan 10, 2025
4eca815
Merge branch 'develop' into 156-add-read_sdmx-convenience-method
javihern98 Jan 10, 2025
183fe4d
Updated poetry lock.
javihern98 Jan 10, 2025
d8fa929
Merge remote-tracking branch 'origin/156-add-read_sdmx-convenience-me…
javihern98 Jan 10, 2025
3b48f9e
Updated poetry lock and used correct version of httpx. Updated tests …
javihern98 Jan 10, 2025
ed6303a
Added validate flag to get_datasets.
javihern98 Jan 10, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/pysdmx/io/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
"""IO module for SDMX data."""

from pysdmx.io.reader import read_sdmx

__all__ = ["read_sdmx"]
2 changes: 1 addition & 1 deletion src/pysdmx/io/csv/sdmx20/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""SDMX 2.0 CSV reader and writer."""

from pysdmx.model.message import ActionType
from pysdmx.model.dataset import ActionType

SDMX_CSV_ACTION_MAPPER = {
ActionType.Append: "A",
Expand Down
2 changes: 1 addition & 1 deletion src/pysdmx/io/csv/sdmx20/reader/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from pysdmx.errors import Invalid
from pysdmx.io.pd import PandasDataset
from pysdmx.model.message import ActionType
from pysdmx.model.dataset import ActionType

ACTION_SDMX_CSV_MAPPER_READING = {
"A": ActionType.Append,
Expand Down
37 changes: 32 additions & 5 deletions src/pysdmx/io/input_processor.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
"""Processes the input that comes into read_sdmx function."""

from io import BytesIO, TextIOWrapper
import os.path
from io import BytesIO, StringIO, TextIOWrapper
from json import JSONDecodeError, loads
from os import PathLike
from pathlib import Path
from typing import Tuple, Union

import pandas as pd

from pysdmx.errors import Invalid


Expand All @@ -17,6 +20,27 @@ def __check_xml(infile: str) -> bool:
return infile[:5] == "<?xml"


def __check_csv(infile: str) -> bool:
try:
pd.read_csv(StringIO(infile), nrows=2)
if (
len(infile.splitlines()) > 1
or infile.splitlines()[0].count(",") > 1
):
return True
except Exception:
return False
return False


def __check_json(infile: str) -> bool:
try:
loads(infile)
return True
except JSONDecodeError:
return False


def process_string_to_read(
infile: Union[str, Path, BytesIO],
) -> Tuple[str, str]:
Expand All @@ -31,6 +55,8 @@ def process_string_to_read(
Raises:
Invalid: If the input cannot be parsed as SDMX.
"""
if isinstance(infile, str) and os.path.exists(infile):
infile = Path(infile)
# Read file as string
if isinstance(infile, (Path, PathLike)):
with open(infile, "r", encoding="utf-8-sig", errors="replace") as f:
Expand All @@ -51,16 +77,17 @@ def process_string_to_read(
out_str = __remove_bom(out_str)

# Check if string is a valid JSON
try:
loads(out_str)
if __check_json(out_str):
return out_str, "json"
except JSONDecodeError:
pass

# Check if string is a valid XML
if __check_xml(out_str):
return out_str, "xml"

# Check if string is a valid CSV
if __check_csv(out_str):
return out_str, "csv"

raise Invalid(
"Validation Error", f"Cannot parse input as SDMX. Found {infile}"
)
112 changes: 112 additions & 0 deletions src/pysdmx/io/reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""SDMX All formats reader module."""

from enum import Enum
from io import BytesIO
from pathlib import Path
from typing import Union

from pysdmx.errors import Invalid
from pysdmx.io.input_processor import process_string_to_read
from pysdmx.model.dataset import Dataset
from pysdmx.model.message import Message


class ReadFormat(Enum):
"""Enumeration of supported SDMX read formats."""

SDMX_ML_2_1 = "SDMX-ML 2.1"
# SDMX_JSON_2 = "SDMX-JSON 2.0.0"
Copy link
Contributor Author

@javihern98 javihern98 Dec 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sosna This is a placeholder to include as well methods to read the JSON formats, still I have not found the way to implement them. Any ideas?

# FUSION_JSON = "FusionJSON"
SDMX_CSV_1_0 = "SDMX-CSV 1.0"
SDMX_CSV_2_0 = "SDMX-CSV 2.0"

def check_extension(self, extension: str) -> bool:
"""Check if the extension is valid for the format.

Args:
extension: The file extension.

Returns:
bool: True if the extension is valid, False otherwise
"""
if self == ReadFormat.SDMX_ML_2_1 and extension == "xml":
return True
# if self == ReadFormat.SDMX_JSON_2 and extension == "json":
# return True
# if self == ReadFormat.FUSION_JSON and extension == "json":
# return True
if self == ReadFormat.SDMX_CSV_1_0 and extension == "csv":
return True
return bool(self == ReadFormat.SDMX_CSV_2_0 and extension == "csv")

def __str__(self) -> str:
"""Return the string representation of the format."""
return self.value


def read_sdmx(
infile: Union[str, Path, BytesIO],
format: ReadFormat,
validate: bool = True,
use_dataset_id: bool = False,
) -> Message:
"""Reads any sdmx file or buffer and returns a dictionary.

Supported metadata formats are:
- SDMX-ML 2.1
- SDMX JSON 2.0.0
- FusionJSON

Supported data formats are:
- SDMX-ML 2.1
- SDMX-CSV 1.0
- SDMX-CSV 2.0

Args:
infile: Path to file (pathlib.Path), URL, or string.
format: Enumerated format of the SDMX file.
use_dataset_id: Whether to use the dataset ID as
the key in the resulting dictionary (only for SDMX-ML).
validate: Validate the input file (only for SDMX-ML).

Returns:
A dictionary containing the parsed SDMX data or metadata.

Raises:
Invalid: If the file is empty or the format is not supported.
"""
input_str, ext = process_string_to_read(infile)
if not format.check_extension(ext):
raise Invalid(f"Invalid format {format} for extension {ext}.")

elif format == ReadFormat.SDMX_ML_2_1:
# SDMX-ML 2.1
from pysdmx.io.xml.sdmx21.reader import read_xml

result = read_xml(
input_str, validate=validate, use_dataset_id=use_dataset_id
)
elif format == ReadFormat.SDMX_CSV_1_0:
# SDMX-CSV 1.0
from pysdmx.io.csv.sdmx10.reader import read

result = read(input_str)
else:
# SDMX-CSV 2.0
from pysdmx.io.csv.sdmx20.reader import read

result = read(input_str)

if len(result) == 0:
raise Invalid("Empty SDMX Message")

# TODO: Add here the Schema download for Datasets, based on structure

# Returning a Message class
if format in (ReadFormat.SDMX_CSV_1_0, ReadFormat.SDMX_CSV_2_0):
return Message(data=result)

first_value = next(iter(result.values()))
if isinstance(first_value, Dataset):
return Message(data=result)
return Message(structures=result)
16 changes: 1 addition & 15 deletions src/pysdmx/io/xml/sdmx21/reader/__utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
AGENCIES = "AgencyScheme"
ORGS = "OrganisationSchemes"
CLS = "Codelists"
CONCEPTS = "ConceptSchemes"
CONCEPTS = "Concepts"
CS = "ConceptScheme"
CODE = "Code"
DFW = "Dataflow"
Expand All @@ -124,17 +124,3 @@
"endTime": "end_time",
"isSequence": "is_sequence",
}


def unique_id(agencyID: str, id_: str, version: str) -> str:
"""Create a unique ID for an object.

Args:
agencyID: The agency ID
id_: The ID of the object
version: The version of the object

Returns:
A string with the unique ID
"""
return f"{agencyID}:{id_}({version})"
Loading
Loading