Spaces:
Sleeping
Sleeping
Download deploy.py from kishankrish19/Vision: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/spaces/kishankrish19/Vision/resolve/main/deploy.py
- Command line
-
hf download hf://spaces/kishankrish19/Vision/deploy.py
-
curl -L -o deploy.py https://huggingface.co/spaces/kishankrish19/Vision/resolve/main/deploy.py
20.4 kB
import os
import sys
import subprocess
import shutil
import time
from pathlib import Path
# ============================================================
# CONFIGURATION
# ============================================================
PROJECT_DIR = Path(__file__).resolve().parent
HF_REMOTE = "https://huggingface.co/spaces/kishankrish19/Vision"
BRANCH = "main"
COMMIT_MESSAGE = "Deploy MoM application"
MAX_RETRIES = 3
# ============================================================
# COLORS
# ============================================================
class C:
RESET = "\033[0m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
CYAN = "\033[96m"
BOLD = "\033[1m"
def info(message):
print(f"{C.BLUE}[INFO]{C.RESET} {message}")
def success(message):
print(f"{C.GREEN}[OK]{C.RESET} {message}")
def warning(message):
print(f"{C.YELLOW}[WARNING]{C.RESET} {message}")
def error(message):
print(f"{C.RED}[ERROR]{C.RESET} {message}")
def title(message):
print()
print("=" * 70)
print(f"{C.BOLD}{C.CYAN}{message}{C.RESET}")
print("=" * 70)
# ============================================================
# COMMAND RUNNER
# ============================================================
def run(
command,
check=True,
capture=False,
retries=1,
retry_delay=3,
):
"""
Run a command with retries.
"""
if isinstance(command, str):
shell = True
display_command = command
else:
shell = False
display_command = " ".join(command)
for attempt in range(1, retries + 1):
print()
print(f"{C.CYAN}> {display_command}{C.RESET}")
try:
result = subprocess.run(
command,
cwd=PROJECT_DIR,
shell=shell,
text=True,
capture_output=capture,
)
if result.returncode == 0:
return result
if attempt < retries:
warning(
f"Command failed (attempt {attempt}/{retries}). "
f"Retrying in {retry_delay}s..."
)
time.sleep(retry_delay)
else:
if check:
error(f"Command failed with exit code {result.returncode}")
if capture:
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr)
raise RuntimeError(display_command)
return result
except FileNotFoundError:
error(f"Command not found: {display_command}")
if check:
raise
return None
# ============================================================
# BASIC CHECKS
# ============================================================
def check_project():
title("Checking project")
if not PROJECT_DIR.exists():
error("Project directory does not exist.")
sys.exit(1)
required = [
"app.py",
"requirements.txt",
"Dockerfile",
]
missing = []
for file in required:
if not (PROJECT_DIR / file).exists():
missing.append(file)
if missing:
error("Missing required files:")
for file in missing:
print(f" - {file}")
error(
"Make sure this script is inside your "
"MOM automation project."
)
sys.exit(1)
success(f"Project detected: {PROJECT_DIR}")
# ============================================================
# GIT CHECK
# ============================================================
def check_git():
title("Checking Git")
result = run(
["git", "--version"],
capture=True,
)
print(result.stdout.strip())
success("Git is available.")
# ============================================================
# INSTALL GIT LFS
# ============================================================
def install_git_lfs():
title("Checking Git LFS")
result = subprocess.run(
["git", "lfs", "version"],
cwd=PROJECT_DIR,
text=True,
capture_output=True,
)
if result.returncode == 0:
success("Git LFS is already installed.")
print(result.stdout.strip())
return
warning("Git LFS is not installed.")
winget = shutil.which("winget")
if not winget:
error("winget was not found.")
error(
"Install Git LFS manually from:"
)
print(
"https://git-lfs.com/"
)
sys.exit(1)
info("Installing Git LFS using winget...")
run(
[
"winget",
"install",
"--id",
"Git.GitLFS",
"-e",
"--accept-source-agreements",
"--accept-package-agreements",
],
retries=2,
)
# Check again
result = subprocess.run(
["git", "lfs", "version"],
cwd=PROJECT_DIR,
text=True,
capture_output=True,
)
if result.returncode != 0:
error(
"Git LFS was installed but is not available "
"in this terminal."
)
error(
"Close this CMD window, open a new one, "
"and run this script again."
)
sys.exit(1)
success("Git LFS installed.")
# ============================================================
# INSTALL GIT XET
# ============================================================
def install_git_xet():
title("Checking Git Xet")
result = subprocess.run(
["git", "xet", "--version"],
cwd=PROJECT_DIR,
text=True,
capture_output=True,
)
if result.returncode == 0:
success("Git Xet is already installed.")
print(
result.stdout.strip()
or result.stderr.strip()
)
return
warning("Git Xet is not installed.")
winget = shutil.which("winget")
if not winget:
error("winget is not available.")
print()
print(
"Install Git Xet manually from:"
)
print(
"https://huggingface.co/docs/hub/xet/using-xet-storage"
)
sys.exit(1)
info("Installing Git Xet using winget...")
run(
[
"winget",
"install",
"git-xet",
"--accept-source-agreements",
"--accept-package-agreements",
],
retries=2,
)
# Check again
result = subprocess.run(
["git", "xet", "--version"],
cwd=PROJECT_DIR,
text=True,
capture_output=True,
)
if result.returncode != 0:
error(
"Git Xet was installed but this terminal "
"cannot see it yet."
)
print()
warning(
"Close this CMD/PowerShell window and open "
"a NEW terminal."
)
warning(
"Then run this script again."
)
sys.exit(1)
success("Git Xet installed.")
# ============================================================
# INITIALIZE XET
# ============================================================
def initialize_xet():
title("Initializing Git Xet")
run(
["git", "xet", "install"],
retries=2,
)
success("Git Xet initialized.")
# ============================================================
# TRACK BINARY FILES
# ============================================================
def configure_xet():
title("Configuring Xet for Excel files")
source_dir = PROJECT_DIR / "sources"
if not source_dir.exists():
warning("sources/ directory does not exist.")
return
xlsx_files = list(source_dir.glob("*.xlsx"))
if not xlsx_files:
warning("No .xlsx files found in sources/.")
return
info("Excel files found:")
for file in xlsx_files:
print(f" - {file.name}")
info("Configuring Git Xet for *.xlsx")
run(
[
"git",
"xet",
"track",
"*.xlsx",
],
retries=2,
)
success("Xet tracking configured for *.xlsx")
# ============================================================
# CHECK GITIGNORE
# ============================================================
def check_gitignore():
title("Checking .gitignore")
gitignore = PROJECT_DIR / ".gitignore"
if not gitignore.exists():
warning(".gitignore does not exist.")
return
content = gitignore.read_text(
encoding="utf-8",
errors="ignore",
)
if "*.xlsx" in content:
warning(
".gitignore contains *.xlsx."
)
warning(
"Your project requires the source Excel files."
)
print()
print(
"The script will NOT automatically modify "
"your .gitignore."
)
print()
print(
"If sources/*.xlsx are ignored, they will be "
"force-added later."
)
# ============================================================
# INITIALIZE GIT IF NEEDED
# ============================================================
def initialize_git():
title("Checking Git repository")
git_dir = PROJECT_DIR / ".git"
if not git_dir.exists():
info("No Git repository found.")
info("Initializing Git...")
run(
["git", "init"],
retries=2,
)
run(
["git", "branch", "-M", BRANCH],
retries=2,
)
success("Git repository initialized.")
else:
success("Git repository already exists.")
# ============================================================
# CONFIGURE REMOTE
# ============================================================
def configure_remote():
title("Checking Hugging Face remote")
result = run(
["git", "remote", "get-url", "origin"],
check=False,
capture=True,
)
if result.returncode != 0:
info("No origin remote found.")
run(
[
"git",
"remote",
"add",
"origin",
HF_REMOTE,
],
retries=2,
)
success("Hugging Face remote added.")
else:
current = result.stdout.strip()
if current != HF_REMOTE:
warning(
f"Current origin:\n{current}"
)
warning(
f"Expected origin:\n{HF_REMOTE}"
)
answer = input(
"Replace origin with the Hugging Face Space? [y/N]: "
).strip().lower()
if answer == "y":
run(
[
"git",
"remote",
"set-url",
"origin",
HF_REMOTE,
],
retries=2,
)
success("Remote updated.")
else:
error(
"Remote was not changed."
)
sys.exit(1)
else:
success("Remote is correct.")
# ============================================================
# CHECK REMOTE ACCESS
# ============================================================
def check_remote():
title("Checking Hugging Face repository access")
result = run(
[
"git",
"ls-remote",
"origin",
"HEAD",
],
check=False,
capture=True,
retries=2,
)
if result.returncode == 0:
success("Hugging Face authentication/access works.")
return True
error("Cannot access the Hugging Face repository.")
if result.stderr:
print(result.stderr)
print()
warning(
"Make sure your Hugging Face token is configured "
"in Git Credential Manager."
)
print()
print(
"You can authenticate with:"
)
print(
" hf auth login"
)
print()
print(
"Then retry this script."
)
return False
# ============================================================
# CHECK REMOTE DIVERGENCE
# ============================================================
def check_remote_sync():
title("Checking remote history")
# Fetch remote metadata.
result = run(
[
"git",
"fetch",
"origin",
BRANCH,
],
check=False,
capture=True,
retries=3,
)
if result.returncode != 0:
warning(
"Unable to fetch remote branch."
)
if result.stderr:
print(result.stderr)
return False
# Determine whether remote branch exists.
result = run(
[
"git",
"rev-parse",
f"origin/{BRANCH}",
],
check=False,
capture=True,
)
if result.returncode != 0:
info(
"Remote main branch does not appear to have "
"a commit yet."
)
return True
remote_commit = result.stdout.strip()
local_result = run(
[
"git",
"rev-parse",
"HEAD",
],
check=False,
capture=True,
)
if local_result.returncode != 0:
info("Local repository has no commits yet.")
return True
local_commit = local_result.stdout.strip()
if local_commit == remote_commit:
success("Local and remote are synchronized.")
return True
# Check ancestry.
ancestor = subprocess.run(
[
"git",
"merge-base",
"--is-ancestor",
f"origin/{BRANCH}",
"HEAD",
],
cwd=PROJECT_DIR,
)
if ancestor.returncode == 0:
success(
"Remote history is already contained in local history."
)
return True
warning(
"Local and remote histories have diverged."
)
print()
print(
"This can happen because README.md/Dockerfile were "
"edited directly on Hugging Face."
)
print()
error(
"The script will NOT force-push and overwrite those changes."
)
print()
print(
"Synchronize the remote changes first, then run this "
"deployment script again."
)
print()
print(
"Recommended command:"
)
print(
" git pull --rebase origin main"
)
print()
print(
"If Git reports unrelated histories, STOP and send "
"the output to me rather than using git push -f."
)
return False
# ============================================================
# STAGE FILES
# ============================================================
def stage_files():
title("Staging project files")
run(
["git", "add", "."],
retries=2,
)
# Force-add required source workbooks in case
# .gitignore contains *.xlsx.
source_dir = PROJECT_DIR / "sources"
if source_dir.exists():
xlsx_files = list(source_dir.glob("*.xlsx"))
if xlsx_files:
info("Force-adding required source workbooks...")
for file in xlsx_files:
run(
[
"git",
"add",
"-f",
str(file.relative_to(PROJECT_DIR)),
],
retries=2,
)
success("Files staged.")
# ============================================================
# SHOW STATUS
# ============================================================
def show_status():
title("Reviewing changes")
result = run(
["git", "status", "--short"],
check=False,
capture=True,
)
if result.stdout:
print(result.stdout)
if result.returncode != 0:
error("Could not read Git status.")
sys.exit(1)
if not result.stdout.strip():
success("No changes to commit.")
return False
return True
# ============================================================
# COMMIT
# ============================================================
def commit():
title("Creating commit")
run(
[
"git",
"commit",
"-m",
COMMIT_MESSAGE,
],
retries=2,
)
success("Commit created.")
# ============================================================
# PUSH
# ============================================================
def push():
title("Pushing to Hugging Face")
for attempt in range(1, MAX_RETRIES + 1):
print()
info(
f"Push attempt {attempt}/{MAX_RETRIES}"
)
result = subprocess.run(
[
"git",
"push",
"origin",
BRANCH,
],
cwd=PROJECT_DIR,
text=True,
)
if result.returncode == 0:
success(
"Push completed successfully!"
)
return True
print()
warning(
f"Push failed on attempt {attempt}."
)
if attempt < MAX_RETRIES:
warning(
"Waiting before retry..."
)
time.sleep(5)
# Refresh remote information before retry.
run(
[
"git",
"fetch",
"origin",
BRANCH,
],
check=False,
capture=True,
retries=1,
)
error("All push attempts failed.")
print()
print(
"IMPORTANT: Do NOT use git push -f automatically."
)
print(
"Paste the complete Git error into the chat."
)
return False
# ============================================================
# MAIN
# ============================================================
def main():
print()
print(
f"{C.BOLD}{C.CYAN}"
"Hugging Face MoM Deployment"
f"{C.RESET}"
)
print(
f"Project: {PROJECT_DIR}"
)
print(
f"Space: {HF_REMOTE}"
)
print()
try:
check_project()
check_git()
install_git_lfs()
install_git_xet()
initialize_xet()
configure_xet()
check_gitignore()
initialize_git()
configure_remote()
if not check_remote():
sys.exit(1)
if not check_remote_sync():
sys.exit(1)
stage_files()
has_changes = show_status()
if not has_changes:
print()
success(
"Everything is already committed."
)
return
print()
answer = input(
"Continue with this commit and push? [Y/n]: "
).strip().lower()
if answer not in ("", "y", "yes"):
warning("Deployment cancelled.")
return
commit()
if not push():
sys.exit(1)
print()
title("DEPLOYMENT COMPLETE")
success(
"Your project was pushed to:"
)
print(HF_REMOTE)
print()
info(
"Hugging Face should now rebuild the Docker Space."
)
print()
info(
"After the build completes, check:"
)
print(
"https://kishankrish19-vision.hf.space/health"
)
except KeyboardInterrupt:
print()
warning("Deployment cancelled by user.")
sys.exit(1)
except Exception as exc:
print()
error("Deployment stopped.")
error(str(exc))
print()
warning(
"No force push was performed."
)
sys.exit(1)
if __name__ == "__main__":
main()
import os
import sys
import subprocess
import shutil
import time
from pathlib import Path
# ============================================================
# CONFIGURATION
# ============================================================
PROJECT_DIR = Path(__file__).resolve().parent
HF_REMOTE = "https://huggingface.co/spaces/kishankrish19/Vision"
BRANCH = "main"
COMMIT_MESSAGE = "Deploy MoM application"
MAX_RETRIES = 3
# ============================================================
# COLORS
# ============================================================
class C:
RESET = "\033[0m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
CYAN = "\033[96m"
BOLD = "\033[1m"
def info(message):
print(f"{C.BLUE}[INFO]{C.RESET} {message}")
def success(message):
print(f"{C.GREEN}[OK]{C.RESET} {message}")
def warning(message):
print(f"{C.YELLOW}[WARNING]{C.RESET} {message}")
def error(message):
print(f"{C.RED}[ERROR]{C.RESET} {message}")
def title(message):
print()
print("=" * 70)
print(f"{C.BOLD}{C.CYAN}{message}{C.RESET}")
print("=" * 70)
# ============================================================
# COMMAND RUNNER
# ============================================================
def run(
command,
check=True,
capture=False,
retries=1,
retry_delay=3,
):
"""
Run a command with retries.
"""
if isinstance(command, str):
shell = True
display_command = command
else:
shell = False
display_command = " ".join(command)
for attempt in range(1, retries + 1):
print()
print(f"{C.CYAN}> {display_command}{C.RESET}")
try:
result = subprocess.run(
command,
cwd=PROJECT_DIR,
shell=shell,
text=True,
capture_output=capture,
)
if result.returncode == 0:
return result
if attempt < retries:
warning(