You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Utiliser importlib.metadata pour la gestion des chemins d'accès des fichiers de la librairie (exemple rapide) :
importosfrompathlibimportPathimportimportlib.metadataasmetadatafromdotenvimportload_dotenvload_dotenv()
# Change config env in productionIS_PROD=False# Pathstry:
package_name="vcub_keeper"package_location=metadata.distribution(package_name).locate_file("")
ROOT_DIR=Path(package_location).resolve()
print("ROOT_DIR: ", ROOT_DIR)
exceptExceptionase: # noqa: E722# Case of heroku env varprint("Try to find environment variable")
# Ne plus utiliser ce hack et la lecture dans le .env ??ROOT_DIR=Path(os.environ.get("ROOT_DIR", ""))
IS_PROD=True# If package is installed with pipif"site-packages"instr(ROOT_DIR): # install via pipload_dotenv()
ROOT_DIR=Path(os.environ.get("ROOT_DIR", ROOT_DIR)) # with .env file in preprodprint("Package installed with pip: ", ROOT_DIR)
IS_PROD=True# In case where ROOT_DIR is None (pre-prod) but we don't need these variablestry:
ROOT_DATA_RAW=ROOT_DIR/"data/raw/"ROOT_DATA_CLEAN=ROOT_DIR/"data/clean/"ROOT_DATA_REF=ROOT_DIR/"data/ref/"ROOT_MODEL=ROOT_DIR/"model/"ROOT_TESTS_DATA=ROOT_DIR/"tests/data_for_tests/"exceptExceptionase: # noqa: E722print("Can't have repository variables")
ROOT_DATA_REF=""# https://github.com/armgilles/vcub_keeper/issues/56#issuecomment-1007593715# Only in devifIS_PRODisFalse:
# ROOT_DATA_RAWifnotROOT_DATA_RAW.exists():
ROOT_DATA_RAW.mkdir(parents=True, exist_ok=True)
print("Create "+str(ROOT_DATA_RAW))
# ROOT_DATA_CLEANifnotROOT_DATA_CLEAN.exists():
ROOT_DATA_CLEAN.mkdir(parents=True, exist_ok=True)
print("Create "+str(ROOT_DATA_CLEAN))
# ROOT_DATA_REFifnotROOT_DATA_REF.exists():
ROOT_DATA_REF.mkdir(parents=True, exist_ok=True)
print("Create "+str(ROOT_DATA_REF))
# ROOT_MODELifnotROOT_MODEL.exists():
ROOT_MODEL.mkdir(parents=True, exist_ok=True)
print("Create "+str(ROOT_MODEL))
# ROOT_TESTS_DATAifnotROOT_TESTS_DATA.exists():
ROOT_TESTS_DATA.mkdir(parents=True, exist_ok=True)
print("Create "+str(ROOT_TESTS_DATA))
Autre solution plus ou moins identique mais sans doute plus élégant et pythonique mais nécessite que le répertoire data et model soit dans le package...
# Dans le fichier pyproject.toml
[tool.setuptools.package-data]
"vcub_keeper"= ["data/ref/station_attribute.csv", "model*.joblib"] # tous les fichier dont on a besoin
# Exemple de refacto pour la focntion de lecture du fichier read_stations_attributes()fromimportlib.resourcesimportfilesimportioimportpolarsasplimportpandasaspddefread_stations_attributes(
data: None|io.StringIO=None,
file_name: str="station_attribute.csv",
output_type: str="",
) ->pl.DataFrame|pd.DataFrame:
""" Lecture du fichier sur les attributs des Vcub à Bordeaux. Ce fichier provient de create.creator.py - create_station_attribute() Parameters ---------- data : io.StringIO | None Données en mémoire (utilisées si présentes). file_name : str Nom du fichier CSV à lire (par défaut "station_attribute.csv"). output_type : str Format de sortie, "pandas" pour un DataFrame Pandas. Par défaut, retourne un DataFrame Polars. Returns ------- stations : pl.DataFrame | pd.DataFrame DataFrame contenant les attributs des stations. Examples -------- stations = read_stations_attributes() stations_pandas = read_stations_attributes(output_type="pandas") """column_dtypes= {"station_id": pl.UInt16}
# Si un objet `io.StringIO` est fourni, on l'utilise directementifisinstance(data, io.StringIO):
file_path=dataelse:
# Récupère le chemin du fichier dans le packagefile_path=files('vcub_keeper.data').joinpath(file_name)
# Lecture du fichier CSV avec Polarsstations=pl.read_csv(file_path, separator=";", schema_overrides=column_dtypes)
# Conversion en DataFrame Pandas si demandéifoutput_type=="pandas":
stations=stations.to_pandas()
returnstations
The text was updated successfully, but these errors were encountered:
Il peut y avoir des problèmes avec la gestion des path actuelles pour la lecture de fichiers et model dans le package lorsque celui-ci est installé (
pip install
) notamment dans le front surheroku
:https://github.com/armgilles/vcub_keeper/blob/efa5a147b0ee8724a8ad379e27cca830b1a01be1/src/vcub_keeper/config.py#L11C1-L30C48
Utiliser
importlib.metadata
pour la gestion des chemins d'accès des fichiers de la librairie (exemple rapide) :Autre solution plus ou moins identique mais sans doute plus élégant et pythonique mais nécessite que le répertoire
data
etmodel
soit dans le package...The text was updated successfully, but these errors were encountered: