Upload catalog.py with huggingface_hub
Browse files123456789101112131415161718191 unmodified line21222324252627282930313233343536373839404142434445464748495051525354555657585960616238 unmodified lines1011021031041051061071081091101115 unmodified lines1171181191201211221238 unmodified lines1321331341351361371382 unmodified lines14114214314414514622 unmodified lines169170171172173174175import osimport refrom collections import Counterfrom pathlib import Pathfrom typing import Optionalimport requestsfrom .artifact import Artifact, Artifactories, Artifactory, reset_artifacts_cachefrom .logging_utils import get_loggerfrom .text_utils import print_dictfrom .version import versionlogger = get_logger()COLLECTION_SEPARATOR = "."PATHS_SEP = ":"class Catalog(Artifactory):1 unmodified linelocation: str = Nonetry:import unitxtif unitxt.__file__:lib_dir = os.path.dirname(unitxt.__file__)else:lib_dir = os.path.dirname(__file__)except ImportError:lib_dir = os.path.dirname(__file__)default_catalog_path = os.path.join(lib_dir, "catalog")class LocalCatalog(Catalog):name: str = "local"location: str = default_catalog_pathis_local: bool = Truedef path(self, artifact_identifier: str):assert (artifact_identifier.strip()), "artifact_identifier should not be an empty string."parts = artifact_identifier.split(COLLECTION_SEPARATOR)parts[-1] = parts[-1] + ".json"return os.path.join(self.location, *parts)def load(self, artifact_identifier: str):assert (artifact_identifier in self), f"Artifact with name {artifact_identifier} does not exist"path = self.path(artifact_identifier)return Artifact.load(path, artifact_identifier)def __getitem__(self, name) -> Artifact:return self.load(name)def __contains__(self, artifact_identifier: str):if not os.path.exists(self.location):return False38 unmodified linestag = versionself.location = f"https://raw.githubusercontent.com/{self.user}/{self.repo}/{tag}/{self.repo_dir}"def load(self, artifact_identifier: str):url = self.path(artifact_identifier)response = requests.get(url)data = response.json()new_artifact = Artifact.from_dict(data)new_artifact.artifact_identifier = artifact_identifierreturn new_artifact5 unmodified linesdef verify_legal_catalog_name(name):assert re.match(r"^[\w" + COLLECTION_SEPARATOR + "]+$", name), f'Artifict name ("{name}") should be alphanumeric. Use "." for nesting (e.g. myfolder.my_artifact)'8 unmodified linesreset_artifacts_cache()if catalog is None:if catalog_path is None:catalog_path = default_catalog_pathcatalog = LocalCatalog(location=catalog_path)verify_legal_catalog_name(name)catalog.save_artifact(2 unmodified lines# verify namedef get_local_catalogs_paths():result = []for artifactory in Artifactories():22 unmodified linesdef summary():result = Counter()for local_catalog_path in get_local_catalogs_paths():result += Counter(local_catalog_summary(local_catalog_path))print_dict(result)return result12345678910111213141516171819202122232425261 unmodified line2829303132333435363738394041424344454647484950515253545556575859606138 unmodified lines1001011021031041051061071081091105 unmodified lines1161171181191201211228 unmodified lines1311321331341351361372 unmodified lines14014114214314414514614714814915015115215315415515615715815916016116216316416516616716816922 unmodified lines192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225import osimport refrom collections import Counterfrom functools import lru_cachefrom pathlib import Pathfrom typing import Optionalimport requestsfrom .artifact import (Artifact,Artifactories,Artifactory,get_artifactory_name_and_args,reset_artifacts_cache,)from .logging_utils import get_loggerfrom .settings_utils import get_constantsfrom .text_utils import print_dictfrom .version import versionlogger = get_logger()constants = get_constants()class Catalog(Artifactory):1 unmodified linelocation: str = Noneclass LocalCatalog(Catalog):name: str = "local"location: str = constants.default_catalog_pathis_local: bool = Truedef path(self, artifact_identifier: str):assert (artifact_identifier.strip()), "artifact_identifier should not be an empty string."parts = artifact_identifier.split(constants.catalog_hirarchy_sep)parts[-1] = parts[-1] + ".json"return os.path.join(self.location, *parts)def load(self, artifact_identifier: str, overwrite_args=None):assert (artifact_identifier in self), f"Artifact with name {artifact_identifier} does not exist"path = self.path(artifact_identifier)return Artifact.load(path, artifact_identifier=artifact_identifier, overwrite_args=overwrite_args)def __getitem__(self, name) -> Artifact:return self.load(name)def get_with_overwrite(self, name, overwrite_args):return self.load(name, overwrite_args=overwrite_args)def __contains__(self, artifact_identifier: str):if not os.path.exists(self.location):return False38 unmodified linestag = versionself.location = f"https://raw.githubusercontent.com/{self.user}/{self.repo}/{tag}/{self.repo_dir}"def load(self, artifact_identifier: str, overwrite_args=None):url = self.path(artifact_identifier)response = requests.get(url)data = response.json()new_artifact = Artifact.from_dict(data, overwrite_args=overwrite_args)new_artifact.artifact_identifier = artifact_identifierreturn new_artifact5 unmodified linesdef verify_legal_catalog_name(name):assert re.match(r"^[\w" + constants.catalog_hirarchy_sep + "]+$", name), f'Artifict name ("{name}") should be alphanumeric. Use "." for nesting (e.g. myfolder.my_artifact)'8 unmodified linesreset_artifacts_cache()if catalog is None:if catalog_path is None:catalog_path = constants.default_catalog_pathcatalog = LocalCatalog(location=catalog_path)verify_legal_catalog_name(name)catalog.save_artifact(2 unmodified lines# verify name@lru_cache(maxsize=None)def get_from_catalog(name: str,catalog: Catalog = None,catalog_path: Optional[str] = None,):if catalog_path is not None:catalog = LocalCatalog(location=catalog_path)if catalog is None:artifactories = Noneelse:artifactories = [catalog]catalog, name, args = get_artifactory_name_and_args(name, artifactories=artifactories)return catalog.get_with_overwrite(name=name,overwrite_args=args,)def get_local_catalogs_paths():result = []for artifactory in Artifactories():22 unmodified linesdef summary():result = Counter()done = set()for local_catalog_path in get_local_catalogs_paths():if local_catalog_path not in done:result += Counter(local_catalog_summary(local_catalog_path))done.add(local_catalog_path)print_dict(result)return resultdef ls(to_file=None):done = set()result = []for local_catalog_path in get_local_catalogs_paths():if local_catalog_path not in done:for root, _, files in os.walk(local_catalog_path):for file in files:if ".json" not in file:continuefile_path = os.path.relpath(os.path.join(root, file), local_catalog_path)file_id = ".".join(file_path.replace(".json", "").split(os.path.sep))result.append(file_id)if to_file:with open(to_file, "w+") as f:f.write("\n".join(result))else:logger.info("\n".join(result))return result
catalog.py+75-25