Skip to content

Commit

Permalink
Introduce InProcAssetMetadataProvider (facebookresearch#168)
Browse files Browse the repository at this point in the history
  • Loading branch information
cbalioglu authored Nov 20, 2023
1 parent ebf637d commit c620f09
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/fairseq2/assets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
from fairseq2.assets.metadata_provider import (
FileAssetMetadataProvider as FileAssetMetadataProvider,
)
from fairseq2.assets.metadata_provider import (
InProcAssetMetadataProvider as InProcAssetMetadataProvider,
)
from fairseq2.assets.store import AssetStore as AssetStore
from fairseq2.assets.store import ProviderBackedAssetStore as ProviderBackedAssetStore
from fairseq2.assets.store import asset_store as asset_store
43 changes: 42 additions & 1 deletion src/fairseq2/assets/metadata_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from abc import ABC, abstractmethod
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Optional, final
from typing import Any, Dict, Optional, Sequence, final

import yaml
from typing_extensions import NoReturn
Expand Down Expand Up @@ -132,6 +132,47 @@ def clear_cache(self) -> None:
self._cache = None


@final
class InProcAssetMetadataProvider(AssetMetadataProvider):
"""Provides asset metadata stored in-memory."""

_metadata: Dict[str, Dict[str, Any]]

def __init__(self, metadata: Sequence[Dict[str, Any]]) -> None:
self._metadata = {}

for idx, m in enumerate(metadata):
try:
name = m["name"]
except KeyError:
raise AssetMetadataError(
f"The asset metadata at index {idx} in `metadata` does not have a name."
)

if not isinstance(name, str):
raise AssetMetadataError(
f"The asset metadata at index {idx} in `metadata` has an invalid name."
)

if name in self._metadata:
raise AssetMetadataError(f"Two assets have the same name '{name}'.")

self._metadata[name] = m

@finaloverride
def get_metadata(self, name: str) -> Dict[str, Any]:
try:
return deepcopy(self._metadata[name])
except KeyError:
raise AssetNotFoundError(
f"An asset with the name '{name}' cannot be found."
)

@finaloverride
def clear_cache(self) -> None:
pass


class AssetNotFoundError(AssetError):
"""Raised when an asset cannot be found."""

Expand Down

0 comments on commit c620f09

Please sign in to comment.