Skip to content

Instantly share code, notes, and snippets.

@mols3131d
Last active May 20, 2024 18:01
Show Gist options
  • Save mols3131d/e8872e33dd8d8fc276a316a304495bef to your computer and use it in GitHub Desktop.
Save mols3131d/e8872e33dd8d8fc276a316a304495bef to your computer and use it in GitHub Desktop.
python3-ds
import os
from pathlib import Path
def set_kaggleAPI(
config_dir: str | Path = None,
username_and_key: dict | list[str, str] | tuple[str, str] = None,
) -> None:
"""Sets environment variables for Kaggle API usage.
Args:
config_dir (str | Path, optional): Directory path containing kaggle.json. Defaults to ~/.kaggle/.
username_and_key (dict | list | tuple, optional): Dictionary, list, or tuple containing Kaggle username and API key.
Raises:
ImportError: If the `kaggle` package is not installed.
TypeError: If `username_and_key` is not a dict, list, or tuple.
FileNotFoundError: If the specified `config_dir` does not exist.
KeyError: If `username_and_key` does not contain 'username' or 'key'.
"""
# Check if kaggle package is installed
try:
import kaggle
except ImportError:
raise ImportError(
"kaggle is not installed. Please install it with 'pip install kaggle'"
)
# Handle config_dir (do nothing if None)
if config_dir is not None:
if isinstance(config_dir, str):
config_dir = Path(config_dir)
# If input is the kaggle.json file itself, get its parent directory
if config_dir.name == "kaggle.json":
config_dir = config_dir.parent
if not config_dir.exists():
raise FileNotFoundError(f"Directory not found: {config_dir}")
os.environ["KAGGLE_CONFIG_DIR"] = str(config_dir)
# Handle username_and_key
if username_and_key is not None:
if isinstance(username_and_key, (list, tuple)):
# Convert to dictionary if a list or tuple is provided
username_and_key = {
k: v for k, v in zip(["username", "key"], username_and_key)
}
elif not isinstance(username_and_key, dict):
raise TypeError("username_and_key must be a dictionary, list, or tuple.")
try:
os.environ["KAGGLE_USERNAME"] = username_and_key["username"]
os.environ["KAGGLE_KEY"] = username_and_key["key"]
except KeyError as e:
raise KeyError(f"username_and_key is missing the '{e.args[0]}' key.")
numpy
pandas
scipy
statsmodels
matplotlib
seaborn
plotly
bokeh
scikit-learn
Joblib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment