Skip to content

Data Loaders

See Data Loaders for how to write one.

ClassificationLoader

rac4os.dataloaders.BaseDataLoader.ClassificationLoader

Bases: ABC

Template: subclasses provide read_raw() + to_records(); base handles the rest.

Source code in rac4os/dataloaders/BaseDataLoader.py
class ClassificationLoader(ABC):
    """Template: subclasses provide read_raw() + to_records(); base handles the rest."""
    def __init__(self, path: str | Path) -> None:
        """
        Stores the source path and checks that it exists.

        Failing here rather than at `to_records` means a wrong path is reported before any
        parsing work or model call happens.

        Raises:
            FileNotFoundError: if the path does not exist.
        """
        self.path = Path(path)
        if not self.path.exists():
            raise FileNotFoundError(f"Classification source not found: {self.path}")

    @abstractmethod
    def to_records(self) -> list[dict]:
        """Return a list of Code-shaped dicts. This is the ONLY thing subclasses implement."""
        ...

    def load(self) -> list[Code]:
        """
        Parse the source and return it as `Code` records.

        Calls the subclass's `to_records` and converts each dict with `Code.from_dict`, which
        drops keys `Code` does not define and leaves missing ones at their defaults.

        Returns:
            list[Code]: one record per category in the source.
        """
        return [Code.from_dict(r) for r in self.to_records()]

__init__

__init__(path)

Stores the source path and checks that it exists.

Failing here rather than at to_records means a wrong path is reported before any parsing work or model call happens.

Raises:

Type Description
FileNotFoundError

if the path does not exist.

Source code in rac4os/dataloaders/BaseDataLoader.py
def __init__(self, path: str | Path) -> None:
    """
    Stores the source path and checks that it exists.

    Failing here rather than at `to_records` means a wrong path is reported before any
    parsing work or model call happens.

    Raises:
        FileNotFoundError: if the path does not exist.
    """
    self.path = Path(path)
    if not self.path.exists():
        raise FileNotFoundError(f"Classification source not found: {self.path}")

to_records abstractmethod

to_records()

Return a list of Code-shaped dicts. This is the ONLY thing subclasses implement.

Source code in rac4os/dataloaders/BaseDataLoader.py
@abstractmethod
def to_records(self) -> list[dict]:
    """Return a list of Code-shaped dicts. This is the ONLY thing subclasses implement."""
    ...

load

load()

Parse the source and return it as Code records.

Calls the subclass's to_records and converts each dict with Code.from_dict, which drops keys Code does not define and leaves missing ones at their defaults.

Returns:

Type Description
list[Code]

list[Code]: one record per category in the source.

Source code in rac4os/dataloaders/BaseDataLoader.py
def load(self) -> list[Code]:
    """
    Parse the source and return it as `Code` records.

    Calls the subclass's `to_records` and converts each dict with `Code.from_dict`, which
    drops keys `Code` does not define and leaves missing ones at their defaults.

    Returns:
        list[Code]: one record per category in the source.
    """
    return [Code.from_dict(r) for r in self.to_records()]

Registry

rac4os.dataloaders.registry

register

register(name)

Class decorator that registers a ClassificationLoader implementation under a name.

The name is what a dataset refers to in mapping through its loader_name key, and what get_loader resolves.

Parameters:

Name Type Description Default
name str

key to register the decorated class under.

required

Returns:

Name Type Description
Callable Callable

the decorator, which registers the class and returns it unchanged.

Source code in rac4os/dataloaders/registry.py
def register(name: str) -> Callable:

    """
    Class decorator that registers a `ClassificationLoader` implementation under a name.

    The name is what a dataset refers to in `mapping` through its `loader_name` key, and
    what `get_loader` resolves.

    Parameters:
        name (str): key to register the decorated class under.

    Returns:
        Callable: the decorator, which registers the class and returns it unchanged.
    """
    def deco(cls):
        """
        Registers the decorated class under the captured name.

        Parameters:
            cls (type[ClassificationLoader]): the class being decorated.

        Returns:
            type[ClassificationLoader]: the same class, unmodified.
        """
        _REGISTRY_DL[name] = cls
        return cls
    return deco

get_loader

get_loader(name, path)

Build a registered loader for a source path.

Parameters:

Name Type Description Default
name str

a registered loader name, e.g. "JSON", "COICOP" or one of your own.

required
path str | Path

the file the loader should read.

required

Returns:

Name Type Description
ClassificationLoader ClassificationLoader

the loader, constructed and ready for load.

Raises:

Type Description
ValueError

if no loader is registered under that name.

Source code in rac4os/dataloaders/registry.py
def get_loader(name: str, path) -> ClassificationLoader:
    """
    Build a registered loader for a source path.

    Parameters:
        name (str): a registered loader name, e.g. "JSON", "COICOP" or one of your own.
        path (str|Path): the file the loader should read.

    Returns:
        ClassificationLoader: the loader, constructed and ready for `load`.

    Raises:
        ValueError: if no loader is registered under that name.
    """
    try:
        cls = _REGISTRY_DL[name]
    except KeyError:
        raise ValueError(f"Unknown format {name!r}; known: {sorted(_REGISTRY_DL)}")
    return cls(path)

Bundled loaders

rac4os.dataloaders.loaders.PredefinedJsonLoader

PredefinedJsonLoader

Bases: ClassificationLoader

Loader for a classification that is already in Code shape, registered under "JSON".

This is the loader to use for your own taxonomy once you have converted it once, and the one that reads back what ClassificationsSystemAugmenter writes: both are a flat JSON list of Code-shaped objects, so there is no parsing left to do.

Source code in rac4os/dataloaders/loaders/PredefinedJsonLoader.py
@register("JSON")
class PredefinedJsonLoader(ClassificationLoader):

  """
  Loader for a classification that is already in `Code` shape, registered under "JSON".

  This is the loader to use for your own taxonomy once you have converted it once, and
  the one that reads back what `ClassificationsSystemAugmenter` writes: both are a flat
  JSON list of `Code`-shaped objects, so there is no parsing left to do.
  """
  def to_records(
        self
    )->list[dict]:

    """
    Read the JSON file and return its contents unchanged.

    The file must hold a list of `Code`-shaped objects. Nothing is validated here; keys
    that `Code` does not define are dropped later, by `Code.from_dict`.

    Returns:
        list[dict]: the records as they stand in the file.
    """
    with open(f"{self.path}", "r", encoding = "utf-8") as f:
        all_labels = json.loads(f.read())

    return all_labels
to_records
to_records()

Read the JSON file and return its contents unchanged.

The file must hold a list of Code-shaped objects. Nothing is validated here; keys that Code does not define are dropped later, by Code.from_dict.

Returns:

Type Description
list[dict]

list[dict]: the records as they stand in the file.

Source code in rac4os/dataloaders/loaders/PredefinedJsonLoader.py
def to_records(
      self
  )->list[dict]:

  """
  Read the JSON file and return its contents unchanged.

  The file must hold a list of `Code`-shaped objects. Nothing is validated here; keys
  that `Code` does not define are dropped later, by `Code.from_dict`.

  Returns:
      list[dict]: the records as they stand in the file.
  """
  with open(f"{self.path}", "r", encoding = "utf-8") as f:
      all_labels = json.loads(f.read())

  return all_labels

rac4os.dataloaders.loaders.KlassServerDataLoader

KlassServerDataloader

Bases: ClassificationLoader

Loader for the XML exports of the German Klassifikationsserver, registered under "KLASS_SERVER".

One loader covers every classification published there: the export format is the same and only the file differs, so pointing it at another Klassifikationsserver export is all it takes to load one. The explanatory notes are parsed out of the nested detail elements into details, and empty detail dicts are removed so that a category without notes does not carry an empty field into the prompt.

Source code in rac4os/dataloaders/loaders/KlassServerDataLoader.py
@register("KLASS_SERVER")
class KlassServerDataloader(ClassificationLoader):

  """
  Loader for the XML exports of the German Klassifikationsserver, registered under
  "KLASS_SERVER".

  One loader covers every classification published there: the export format is the same
  and only the file differs, so pointing it at another Klassifikationsserver export is
  all it takes to load one. The explanatory
  notes are parsed out of the nested detail elements into `details`, and empty detail
  dicts are removed so that a category without notes does not carry an empty field into
  the prompt.
  """
  def __get_detail_dict(self, item):

    """
    Constructs a dictionary for all the relevant sea categories with the given class names from the xml file.
    Parameters:
        item:xml.etree.ElementTree.Element
    Returns:
        dict
    """

    return {
        "code":item.get("id"),
        "description":item.find(".//Label[@qualifier='Usual']").find("LabelText").text,
        "level":int(item.get("idLevel")),
        "details":{
            "keywords":[
                i.find(".//PropertyText[@type='Content']").text  if i.find(".//PropertyText[@type='Content']") is not None else ""   for i in item.findall(".//Property[@name='Keyword']")],
            "ExplanatoryNote":{
                "exclusions":[ex.find(".//PropertyQualifier[@name='Exclusions']").find("PropertyText").text if ex.find(".//PropertyQualifier[@name='Exclusions']") is not None else "" for ex in item.findall(".//Property[@name='ExplanatoryNote']")],
                "explicit_inclusion":[ex.find(".//PropertyQualifier[@name='CentralContent']").find("PropertyText").text if ex.find(".//PropertyQualifier[@name='CentralContent']") is not None else "" for ex in item.findall(".//Property[@name='ExplanatoryNote']")]
            },
            "context":item.find(".//Label[@qualifier='Context']").find("LabelText").text if item.find(".//Label[@qualifier='Context']") is not None else "",
        }
    }

  def __parse_xml(self, path):
    """
    Parses the sea-documentation xml file and extracts all the relevant information.
    Parameters:
      path:str
    Returns:
      list
    """
    tree = ET.parse(path)
    root = tree.getroot()
    classification = root.find("Classification")

    if classification is None:
       raise ValueError("Could not find any classification codes inside the file!")

    labels = classification.findall("Item")
    all_labels = [self.__get_detail_dict(l_) for l_ in labels]
    return all_labels

  def __clean_dict(self, all_labels):

    """
    Cleans the dictionary of empty values.
    Parameters:
      all_labels:list
    Returns:
      list
    """

    for label in all_labels:
      for key in list(label["details"].keys()):
        if key == "ExplanatoryNote":
          for key2 in list(label["details"]["ExplanatoryNote"].keys()):
            if label["details"]["ExplanatoryNote"][key2] == []:
              del label["details"]["ExplanatoryNote"][key2]
        if label["details"][key] == [""] or label["details"][key] == "" or label["details"][key] == [] or label["details"][key] == {}:
          del label["details"][key]
      if label["details"] == {}:
        del label["details"]

    return all_labels

  def to_records(
        self
    )->list[dict]:

    """
    Parse the XML export and return `Code`-shaped dicts.

    Returns:
        list[dict]: one dict per category, with the classification's explanatory notes under `details`.
    """
    all_labels = self.__parse_xml(self.path)
    all_labels = self.__clean_dict(all_labels)
    return all_labels
__get_detail_dict
__get_detail_dict(item)

Constructs a dictionary for all the relevant sea categories with the given class names from the xml file. Parameters: item:xml.etree.ElementTree.Element Returns: dict

Source code in rac4os/dataloaders/loaders/KlassServerDataLoader.py
def __get_detail_dict(self, item):

  """
  Constructs a dictionary for all the relevant sea categories with the given class names from the xml file.
  Parameters:
      item:xml.etree.ElementTree.Element
  Returns:
      dict
  """

  return {
      "code":item.get("id"),
      "description":item.find(".//Label[@qualifier='Usual']").find("LabelText").text,
      "level":int(item.get("idLevel")),
      "details":{
          "keywords":[
              i.find(".//PropertyText[@type='Content']").text  if i.find(".//PropertyText[@type='Content']") is not None else ""   for i in item.findall(".//Property[@name='Keyword']")],
          "ExplanatoryNote":{
              "exclusions":[ex.find(".//PropertyQualifier[@name='Exclusions']").find("PropertyText").text if ex.find(".//PropertyQualifier[@name='Exclusions']") is not None else "" for ex in item.findall(".//Property[@name='ExplanatoryNote']")],
              "explicit_inclusion":[ex.find(".//PropertyQualifier[@name='CentralContent']").find("PropertyText").text if ex.find(".//PropertyQualifier[@name='CentralContent']") is not None else "" for ex in item.findall(".//Property[@name='ExplanatoryNote']")]
          },
          "context":item.find(".//Label[@qualifier='Context']").find("LabelText").text if item.find(".//Label[@qualifier='Context']") is not None else "",
      }
  }
__parse_xml
__parse_xml(path)

Parses the sea-documentation xml file and extracts all the relevant information. Parameters: path:str Returns: list

Source code in rac4os/dataloaders/loaders/KlassServerDataLoader.py
def __parse_xml(self, path):
  """
  Parses the sea-documentation xml file and extracts all the relevant information.
  Parameters:
    path:str
  Returns:
    list
  """
  tree = ET.parse(path)
  root = tree.getroot()
  classification = root.find("Classification")

  if classification is None:
     raise ValueError("Could not find any classification codes inside the file!")

  labels = classification.findall("Item")
  all_labels = [self.__get_detail_dict(l_) for l_ in labels]
  return all_labels
__clean_dict
__clean_dict(all_labels)

Cleans the dictionary of empty values. Parameters: all_labels:list Returns: list

Source code in rac4os/dataloaders/loaders/KlassServerDataLoader.py
def __clean_dict(self, all_labels):

  """
  Cleans the dictionary of empty values.
  Parameters:
    all_labels:list
  Returns:
    list
  """

  for label in all_labels:
    for key in list(label["details"].keys()):
      if key == "ExplanatoryNote":
        for key2 in list(label["details"]["ExplanatoryNote"].keys()):
          if label["details"]["ExplanatoryNote"][key2] == []:
            del label["details"]["ExplanatoryNote"][key2]
      if label["details"][key] == [""] or label["details"][key] == "" or label["details"][key] == [] or label["details"][key] == {}:
        del label["details"][key]
    if label["details"] == {}:
      del label["details"]

  return all_labels
to_records
to_records()

Parse the XML export and return Code-shaped dicts.

Returns:

Type Description
list[dict]

list[dict]: one dict per category, with the classification's explanatory notes under details.

Source code in rac4os/dataloaders/loaders/KlassServerDataLoader.py
def to_records(
      self
  )->list[dict]:

  """
  Parse the XML export and return `Code`-shaped dicts.

  Returns:
      list[dict]: one dict per category, with the classification's explanatory notes under `details`.
  """
  all_labels = self.__parse_xml(self.path)
  all_labels = self.__clean_dict(all_labels)
  return all_labels

rac4os.dataloaders.loaders.CoicopDataLoader

CoicopDataLoader

Bases: ClassificationLoader

Loader for the official COICOP 2018 structure as published in xlsx, registered under "COICOP".

The sheet's three note columns (includes, alsoIncludes, excludes) are folded into the details dict rather than dropped, because the exclusion notes are what settle most of the hard cases between neighbouring categories. The level is derived from the code itself, by counting its dot-separated groups.

Source code in rac4os/dataloaders/loaders/CoicopDataLoader.py
@register("COICOP")
class CoicopDataLoader(ClassificationLoader):

    """
    Loader for the official COICOP 2018 structure as published in xlsx, registered under
    "COICOP".

    The sheet's three note columns (`includes`, `alsoIncludes`, `excludes`) are folded into
    the `details` dict rather than dropped, because the exclusion notes are what settle most
    of the hard cases between neighbouring categories. The level is derived from the code
    itself, by counting its dot-separated groups.
    """
    def to_records(
        self
    )->list[dict]:

        """
        Read the xlsx and return `Code`-shaped dicts.

        Non-breaking spaces and the `_x000D_` carriage returns that the published file contains
        are replaced with ordinary spaces first; left in, they end up in the embedded text and
        in the prompt.

        Returns:
            list[dict]: one dict per COICOP category, with `includes`, `alsoIncludes` and `excludes` kept under `details`.
        """
        coicop_df = pd.read_excel(self.path, dtype=str).fillna("")
        for col in coicop_df.columns:
            coicop_df[col] = coicop_df[col].apply(lambda s: re.sub(r"(\xa00)|(_x000D_\n)|(\xa0)", " ",s))
        coicop_df["details"] = coicop_df.apply(
            lambda row: {
                "includes":row["includes"],
                "alsoIncludes": row["alsoIncludes"],
                "excludes":row["excludes"]
            },axis=1)

        coicop_df = coicop_df.drop(
            [
                "includes",
                "alsoIncludes",
                "excludes"
            ], axis=1)

        coicop_df.columns = ["code", "description", "detailled_description", "details"]
        coicop_df["level"] = coicop_df.code.apply(lambda s: len(s.split("."))) # int
        return coicop_df.to_dict(orient="records") 
to_records
to_records()

Read the xlsx and return Code-shaped dicts.

Non-breaking spaces and the _x000D_ carriage returns that the published file contains are replaced with ordinary spaces first; left in, they end up in the embedded text and in the prompt.

Returns:

Type Description
list[dict]

list[dict]: one dict per COICOP category, with includes, alsoIncludes and excludes kept under details.

Source code in rac4os/dataloaders/loaders/CoicopDataLoader.py
def to_records(
    self
)->list[dict]:

    """
    Read the xlsx and return `Code`-shaped dicts.

    Non-breaking spaces and the `_x000D_` carriage returns that the published file contains
    are replaced with ordinary spaces first; left in, they end up in the embedded text and
    in the prompt.

    Returns:
        list[dict]: one dict per COICOP category, with `includes`, `alsoIncludes` and `excludes` kept under `details`.
    """
    coicop_df = pd.read_excel(self.path, dtype=str).fillna("")
    for col in coicop_df.columns:
        coicop_df[col] = coicop_df[col].apply(lambda s: re.sub(r"(\xa00)|(_x000D_\n)|(\xa0)", " ",s))
    coicop_df["details"] = coicop_df.apply(
        lambda row: {
            "includes":row["includes"],
            "alsoIncludes": row["alsoIncludes"],
            "excludes":row["excludes"]
        },axis=1)

    coicop_df = coicop_df.drop(
        [
            "includes",
            "alsoIncludes",
            "excludes"
        ], axis=1)

    coicop_df.columns = ["code", "description", "detailled_description", "details"]
    coicop_df["level"] = coicop_df.code.apply(lambda s: len(s.split("."))) # int
    return coicop_df.to_dict(orient="records") 

rac4os.dataloaders.loaders.ICATUSLoader

ICATUSLaoder

Bases: ClassificationLoader

Loader for the UNSD ICATUS 2016 time-use statistics csv, registered under "ICATUS".

The source spreads the code over three columns, one per level, with the deeper ones empty for higher categories. The loader collapses them into a single code and derives the level from its length.

Source code in rac4os/dataloaders/loaders/ICATUSLoader.py
@register("ICATUS")
class ICATUSLaoder(ClassificationLoader):

    """
    Loader for the UNSD ICATUS 2016 time-use statistics csv, registered under "ICATUS".

    The source spreads the code over three columns, one per level, with the deeper ones
    empty for higher categories. The loader collapses them into a single code and derives
    the level from its length.
    """
    def to_records(self) -> list[dict]:


        """
        Read the csv and return `Code`-shaped dicts.

        Returns:
            list[dict]: one dict per ICATUS category, with `includes`, `excludes` and `keywords` kept under `details`.
        """
        def map_code(PID, ID, CID):
            """
            Pick the deepest of the three code columns that is populated.

            Parameters:
                PID: major-division code, set for every row.
                ID: second-level code, empty for major divisions.
                CID: third-level code, empty above it.

            Returns:
                the most specific code present on the row.
            """
            if pd.isna(ID) and pd.isna(CID):
                return PID
            elif pd.isna(CID):
                return ID
            else:
                return CID

        df = pd.read_csv(self.path)
        df.columns = ['PID', 'ID', 'CID', 'description', 'detailled_description', 'includes', 'excludes', 'keywords']



        df["code"] = df.apply(lambda row: str(int(map_code(row["PID"], row["ID"], row["CID"]))),axis=1)
        codes = df.to_dict(orient="records")
        records = [
            {
                "code":c["code"], 
                "description":c["description"],
                "detailled_description":c["detailled_description"],
                "level":len(c["code"]),
                "details":{
                    "includes":c["includes"],
                    "excludes":c["excludes"],
                    "keywords":c["keywords"]
                }    
             } for c in codes
        ]

        return records
to_records
to_records()

Read the csv and return Code-shaped dicts.

Returns:

Type Description
list[dict]

list[dict]: one dict per ICATUS category, with includes, excludes and keywords kept under details.

Source code in rac4os/dataloaders/loaders/ICATUSLoader.py
def to_records(self) -> list[dict]:


    """
    Read the csv and return `Code`-shaped dicts.

    Returns:
        list[dict]: one dict per ICATUS category, with `includes`, `excludes` and `keywords` kept under `details`.
    """
    def map_code(PID, ID, CID):
        """
        Pick the deepest of the three code columns that is populated.

        Parameters:
            PID: major-division code, set for every row.
            ID: second-level code, empty for major divisions.
            CID: third-level code, empty above it.

        Returns:
            the most specific code present on the row.
        """
        if pd.isna(ID) and pd.isna(CID):
            return PID
        elif pd.isna(CID):
            return ID
        else:
            return CID

    df = pd.read_csv(self.path)
    df.columns = ['PID', 'ID', 'CID', 'description', 'detailled_description', 'includes', 'excludes', 'keywords']



    df["code"] = df.apply(lambda row: str(int(map_code(row["PID"], row["ID"], row["CID"]))),axis=1)
    codes = df.to_dict(orient="records")
    records = [
        {
            "code":c["code"], 
            "description":c["description"],
            "detailled_description":c["detailled_description"],
            "level":len(c["code"]),
            "details":{
                "includes":c["includes"],
                "excludes":c["excludes"],
                "keywords":c["keywords"]
            }    
         } for c in codes
    ]

    return records