saranka85's picture
Upload folder using huggingface_hub
9a7106b verified
Raw
History Blame Contribute Delete
1.82 kB
import os
from pathlib import Path
from dotenv import load_dotenv
from huggingface_hub import HfApi
def str_to_bool(value: str, default: bool = False) -> bool:
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "y"}
def push_deployment_files_to_hf_space(env_path: str = ".env") -> str:
load_dotenv(env_path)
hf_username = os.getenv("HF_USERNAME")
hf_token = os.getenv("HF_TOKEN")
if not hf_username or not hf_token:
raise EnvironmentError(f"HF_USERNAME and HF_TOKEN must be set in {env_path}.")
space_repo = os.getenv("HF_SPACE_REPO", f"{hf_username}/predictive-maintenance-engine-space")
space_private = str_to_bool(os.getenv("HF_SPACE_PRIVATE"), default=False)
deployment_dir = Path(__file__).resolve().parent
required_files = ["Dockerfile", "README.md", "app.py", "requirements.txt", "deployment_config.json", ".dockerignore"]
missing_files = [file_name for file_name in required_files if not (deployment_dir / file_name).exists()]
if missing_files:
raise FileNotFoundError(f"Missing deployment files: {missing_files}")
api = HfApi(token=hf_token)
api.create_repo(
repo_id=space_repo,
repo_type="space",
space_sdk="docker",
private=space_private,
exist_ok=True,
)
api.upload_folder(
repo_id=space_repo,
repo_type="space",
folder_path=str(deployment_dir),
path_in_repo=".",
ignore_patterns=["__pycache__/*", "*.pyc", ".env", "prediction_logs/*", "sample_prediction_inputs.csv"],
)
space_url = f"https://huggingface.co/spaces/{space_repo}"
print("Deployment files pushed to Hugging Face Space:", space_url)
return space_url
if __name__ == "__main__":
push_deployment_files_to_hf_space()