chatdoc / scripts /hugging_face_deploy.py
celiolr's picture
Deploy: 51 arquivos - 2025-12-19 14:32:02
beb04eb
Raw History Blame Contribute Delete
23.5 kB
#!/usr/bin/env python3
"""
huggingface_force_deploy.py - Deploy FORÇADO para Hugging Face Spaces
Versão FINAL com suporte a arquivos grandes
"""
import os
import sys
import shutil
import tempfile
import subprocess
from pathlib import Path
from dotenv import load_dotenv
import argparse
import time
import fnmatch
import atexit
class SimpleHFDeploy:
def __init__(self):
self.config = self.load_config()
self.temp_dirs = []
# Registrar limpeza automática
atexit.register(self.cleanup_temp_dirs)
def cleanup_temp_dirs(self):
"""Limpa todos os diretórios temporários"""
for temp_dir in self.temp_dirs[:]:
if os.path.exists(temp_dir):
try:
self.force_remove_windows(temp_dir)
self.temp_dirs.remove(temp_dir)
except:
pass
def force_remove_windows(self, path):
"""Remove arquivos/diretórios no Windows"""
if not os.path.exists(path):
return
try:
# Tentar remover normalmente primeiro
if os.path.isfile(path):
os.unlink(path)
else:
shutil.rmtree(path, ignore_errors=True)
except:
# Se falhar, tentar como administrador
try:
if sys.platform == 'win32':
subprocess.run(f'rmdir /S /Q "{path}"', shell=True,
capture_output=True, timeout=5)
else:
subprocess.run(['rm', '-rf', path],
capture_output=True, timeout=5)
except:
pass # Ignorar erros finais
def load_config(self):
"""Carrega configurações do .env"""
config = {
'token': None,
'repo_id': None,
'project_path': None,
'use_git_lfs': False # Nova opção para Git LFS
}
# Carregar .env
env_path = Path.cwd() / ".env"
if env_path.exists():
load_dotenv(env_path)
print(f"🔧 Configurações de: {env_path}")
config['token'] = os.getenv("HUGGINGFACE_HUB_TOKEN")
config['repo_id'] = os.getenv("HF_SPACE_NAME")
# Nova configuração para Git LFS
config['use_git_lfs'] = os.getenv("HF_USE_GIT_LFS", "false").lower() == "true"
# Determinar caminho do projeto
project_path = os.getenv("HF_PROJECT_PATH")
if project_path:
config['project_path'] = Path(project_path)
if not config['project_path'].is_absolute():
config['project_path'] = Path.cwd() / config['project_path']
else:
config['project_path'] = Path.cwd()
return config
def fix_git_safe_directory(self, repo_dir):
"""Corrige problema de safe.directory do Git no Windows"""
try:
# Configurar diretório como seguro
git_path = str(repo_dir).replace('\\', '/')
cmd = f'git config --global --add safe.directory "{git_path}"'
result = subprocess.run(cmd, shell=True,
capture_output=True, text=True)
if result.returncode == 0:
print(f"✅ Diretório seguro configurado: {git_path}")
return True
else:
print(f"⚠️ Não foi possível configurar diretório seguro: {result.stderr[:100]}")
return False
except Exception as e:
print(f"⚠️ Erro ao configurar diretório seguro: {e}")
return False
def should_ignore_file(self, file_path, rel_path):
"""Determina se um arquivo deve ser ignorado baseado em padrões"""
# Converter caminho para string Unix-style
rel_str = str(rel_path).replace('\\', '/')
file_name = file_path.name
# Lista de padrões para IGNORAR
ignore_patterns = [
# Sistema e IDE
'.git', '.gitignore', '.env', '.env.example',
'.vscode', '.idea', '.DS_Store',
# Python
'__pycache__/', '*.pyc', '*.pyo', '*.pyd',
'venv/', '.venv/', 'env/',
# Testes e cache
'.pytest_cache/', '.coverage', 'htmlcov/',
'*.log', '*.tmp', '*.temp',
# Dados temporários/processados
'data/processed/', 'data/raw_documents/',
'data/temp/', 'data/cache/', 'data/backup/',
# Build e distribuição
'dist/', 'build/', '*.egg-info/',
# Outros
'*.db-wal', '*.db-shm', '*.sqlite3-journal'
]
# Verificar arquivos grandes (>10MB) - NÃO enviar pelo Git normal
try:
file_size = file_path.stat().st_size
if file_size > 10 * 1024 * 1024: # 10MB
# Apenas ignorar se NÃO estivermos usando Git LFS
if not self.config['use_git_lfs']:
return True
except:
pass
# Verificar cada padrão
for pattern in ignore_patterns:
# Padrão de diretório (termina com /)
if pattern.endswith('/'):
dir_pattern = pattern.rstrip('/')
if rel_str.startswith(dir_pattern + '/') or rel_str == dir_pattern:
return True
# Padrão com wildcard
elif '*' in pattern:
if fnmatch.fnmatch(rel_str, pattern) or fnmatch.fnmatch(file_name, pattern):
return True
# Padrão exato
elif pattern == rel_str or pattern == file_name:
return True
return False
def setup_git_lfs(self, repo_dir):
"""Configura Git LFS para arquivos grandes"""
try:
original_dir = os.getcwd()
os.chdir(repo_dir)
print("🔧 Configurando Git LFS...")
# Verificar se Git LFS está instalado
result = subprocess.run(['git', 'lfs', '--version'],
capture_output=True, text=True)
if result.returncode != 0:
print("⚠️ Git LFS não está instalado. Ignorando arquivos grandes.")
os.chdir(original_dir)
return False
# Instalar Git LFS no repositório
subprocess.run(['git', 'lfs', 'install'], capture_output=True)
# Rastrear tipos de arquivo grandes
lfs_patterns = ['*.sqlite3', '*.bin', '*.pickle', '*.pkl',
'*.h5', '*.pt', '*.pth']
for pattern in lfs_patterns:
subprocess.run(['git', 'lfs', 'track', pattern], capture_output=True)
# Adicionar .gitattributes
subprocess.run(['git', 'add', '.gitattributes'], capture_output=True)
print("✅ Git LFS configurado para arquivos grandes")
os.chdir(original_dir)
return True
except Exception as e:
print(f"⚠️ Erro ao configurar Git LFS: {e}")
os.chdir(original_dir)
return False
def clone_repo(self, repo_url, target_dir):
"""Clona repositório com todas as correções necessárias"""
try:
os.makedirs(target_dir, exist_ok=True)
# Primeiro corrigir safe.directory
self.fix_git_safe_directory(target_dir)
# Comando de clone com todas as correções para Windows
clone_cmd = [
'git', 'clone',
'--depth', '1',
'--config', 'core.protectNTFS=false',
'--config', 'core.protectHFS=false',
'--config', 'core.autocrlf=false',
repo_url,
target_dir
]
print(f" Clonando: {repo_url.split('@')[-1]}")
result = subprocess.run(clone_cmd, capture_output=True,
text=True, timeout=120)
if result.returncode == 0:
print("✅ Repositório clonado")
# Configurar Git LFS se necessário
if self.config['use_git_lfs']:
self.setup_git_lfs(target_dir)
return True
else:
print(f"⚠️ Clone falhou: {result.stderr[:200]}")
# Tentar método alternativo
return self.clone_repo_alternative(repo_url, target_dir)
except subprocess.TimeoutExpired:
print("⚠️ Timeout ao clonar")
return self.clone_repo_alternative(repo_url, target_dir)
except Exception as e:
print(f"⚠️ Erro ao clonar: {e}")
return self.clone_repo_alternative(repo_url, target_dir)
def clone_repo_alternative(self, repo_url, target_dir):
"""Método alternativo para clonar"""
try:
os.makedirs(target_dir, exist_ok=True)
# Inicializar repositório vazio
subprocess.run(['git', 'init'], cwd=target_dir, capture_output=True)
# Configurar para Windows
subprocess.run(['git', 'config', 'core.protectNTFS', 'false'],
cwd=target_dir, capture_output=True)
subprocess.run(['git', 'config', 'core.protectHFS', 'false'],
cwd=target_dir, capture_output=True)
subprocess.run(['git', 'config', 'core.autocrlf', 'false'],
cwd=target_dir, capture_output=True)
# Adicionar remote
subprocess.run(['git', 'remote', 'add', 'origin', repo_url],
cwd=target_dir, capture_output=True)
# Fazer fetch
result = subprocess.run(['git', 'fetch', 'origin'],
cwd=target_dir, capture_output=True, text=True)
if result.returncode != 0:
return False
# Reset para HEAD
subprocess.run(['git', 'reset', '--hard', 'FETCH_HEAD'],
cwd=target_dir, capture_output=True)
print("✅ Repositório preparado (método alternativo)")
return True
except Exception as e:
print(f"❌ Método alternativo falhou: {e}")
return False
def clean_repo(self, repo_dir):
"""Limpa repositório completamente"""
original_dir = os.getcwd()
try:
os.chdir(repo_dir)
# Remover todos os arquivos trackeados
result = subprocess.run(['git', 'ls-files'],
capture_output=True, text=True)
if result.returncode == 0 and result.stdout.strip():
files = result.stdout.strip().split('\n')
for file in files:
if file and not file.startswith('.git/'):
file_path = Path(file)
if file_path.exists():
try:
if file_path.is_file():
file_path.unlink()
elif file_path.is_dir():
shutil.rmtree(file_path, ignore_errors=True)
except:
pass
print(f"✅ {len(files)} arquivos removidos")
# Remover arquivos não trackeados
subprocess.run(['git', 'clean', '-fd'], capture_output=True)
# Remover tudo exceto .git
for item in os.listdir('.'):
if item != '.git':
item_path = Path(item)
try:
if item_path.is_file():
item_path.unlink()
elif item_path.is_dir():
shutil.rmtree(item_path, ignore_errors=True)
except:
pass
return True
finally:
os.chdir(original_dir)
def copy_project_files(self, target_dir):
"""Copia arquivos do projeto respeitando regras de ignore"""
files_copied = 0
total_size = 0
ignored_count = 0
large_files_ignored = 0
print("\n📋 Analisando arquivos do projeto...")
for root, dirs, files in os.walk(self.config['project_path']):
# Filtrar diretórios
dirs[:] = [d for d in dirs if not self.should_ignore_file(
Path(root) / d,
Path(d)
)]
for file in files:
src_path = Path(root) / file
rel_path = src_path.relative_to(self.config['project_path'])
# Verificar se deve ignorar
if self.should_ignore_file(src_path, rel_path):
ignored_count += 1
# Verificar se é arquivo grande
try:
if src_path.stat().st_size > 10 * 1024 * 1024:
large_files_ignored += 1
if large_files_ignored <= 5:
size_mb = src_path.stat().st_size / 1024 / 1024
print(f" 🚫 GRANDE ({size_mb:.1f} MB): {rel_path}")
except:
pass
continue
dst_path = Path(target_dir) / rel_path
dst_path.parent.mkdir(parents=True, exist_ok=True)
try:
shutil.copy2(src_path, dst_path)
files_copied += 1
total_size += src_path.stat().st_size
except Exception as e:
print(f"⚠️ Não pôde copiar {rel_path}: {e}")
print(f"\n📊 Estatísticas:")
print(f" • Arquivos copiados: {files_copied}")
print(f" • Tamanho total: {total_size / 1024 / 1024:.1f} MB")
print(f" • Arquivos ignorados: {ignored_count}")
if large_files_ignored > 0:
print(f" • Arquivos grandes ignorados (>10MB): {large_files_ignored}")
if not self.config['use_git_lfs'] and large_files_ignored > 0:
print(f"\n⚠️ ATENÇÃO: {large_files_ignored} arquivos grandes foram ignorados.")
print(" Para incluir arquivos grandes, use Git LFS:")
print(" 1. Adicione HF_USE_GIT_LFS=true ao .env")
print(" 2. Instale Git LFS: https://git-lfs.com/")
print(" 3. Execute novamente")
return files_copied, total_size
def force_deploy(self, dry_run=False, skip_confirmation=False):
"""Executa o deploy forçado"""
print("=" * 60)
print("🚀 DEPLOY FORÇADO PARA HUGGING FACE")
print("=" * 60)
# Configuração
if not self.config['repo_id']:
self.config['repo_id'] = input(
"Digite o nome do Space (usuário/nome-space): "
).strip()
if not self.config['token']:
print("🔑 Token não encontrado no .env")
self.config['token'] = input("Digite seu token do Hugging Face: ").strip()
if not self.config['token'] or not self.config['repo_id']:
print("❌ Token e nome do Space são obrigatórios")
return False
print(f"\n🎯 Space: {self.config['repo_id']}")
print(f"📁 Projeto: {self.config['project_path']}")
if self.config['use_git_lfs']:
print("🔧 Modo: Git LFS ativado para arquivos grandes")
else:
print("⚠️ Modo: Arquivos >10MB serão ignorados")
if not skip_confirmation and not dry_run:
print("\n⚠️ ATENÇÃO: Isso apagará TUDO no Space")
confirm = input("🔴 Continuar? (s/n): ").lower()
if confirm not in ['s', 'sim', 'y', 'yes']:
print("❌ Cancelado")
return False
# Criar diretório temporário
temp_dir = tempfile.mkdtemp(prefix="hf_deploy_")
self.temp_dirs.append(temp_dir)
try:
# Clonar repositório
print(f"\n📦 Preparando em: {temp_dir}")
print("\n⬇️ Clonando repositório...")
repo_url = f"https://user:{self.config['token']}@huggingface.co/spaces/{self.config['repo_id']}"
if not self.clone_repo(repo_url, temp_dir):
print("❌ Não foi possível clonar")
return False
# Limpar repositório
print("\n🗑️ Limpando repositório...")
self.clean_repo(temp_dir)
if dry_run:
print("\n🚀 MODO SIMULAÇÃO")
print("Arquivos que seriam enviados:")
self.list_files_dryrun()
return True
# Copiar arquivos
print("\n📋 Copiando arquivos...")
files_copied, total_size = self.copy_project_files(temp_dir)
if files_copied == 0:
print("❌ Nenhum arquivo para copiar")
return False
# Commit e push
print("\n💾 Commit e push...")
original_dir = os.getcwd()
os.chdir(temp_dir)
try:
# Adicionar tudo
subprocess.run(['git', 'add', '.'], capture_output=True)
# Verificar se há mudanças
result = subprocess.run(['git', 'status', '--porcelain'],
capture_output=True, text=True)
if not result.stdout.strip():
print("⚠️ Nenhuma mudança detectada")
with open('.deploy_marker', 'w') as f:
f.write(f"Deploy: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
subprocess.run(['git', 'add', '.deploy_marker'], capture_output=True)
# Commit
commit_msg = f'Deploy: {files_copied} arquivos - {time.strftime("%Y-%m-%d %H:%M:%S")}'
subprocess.run(['git', 'commit', '-m', commit_msg],
capture_output=True, text=True)
print("✅ Commit criado")
# Push
print("\n⬆️ Enviando...")
push_result = subprocess.run(['git', 'push', 'origin', 'HEAD'],
capture_output=True, text=True, timeout=180)
if push_result.returncode != 0:
print(f"⚠️ Push falhou: {push_result.stderr[:200]}")
# Tentar push forçado
print(" Tentando push forçado...")
push_result = subprocess.run(['git', 'push', '--force', 'origin', 'HEAD'],
capture_output=True, text=True, timeout=180)
if push_result.returncode != 0:
print(f"❌ Push forçado falhou: {push_result.stderr[:200]}")
return False
print("✅ Push realizado!")
# Resultado
print("\n" + "=" * 60)
print("✨ DEPLOY CONCLUÍDO!")
print("=" * 60)
print(f"📊 Estatísticas:")
print(f" • Arquivos: {files_copied}")
print(f" • Tamanho: {total_size / 1024 / 1024:.1f} MB")
print(f" • Space: {self.config['repo_id']}")
print(f"🌐 URL: https://huggingface.co/spaces/{self.config['repo_id']}")
print("=" * 60)
return True
finally:
os.chdir(original_dir)
except Exception as e:
print(f"❌ Erro: {e}")
import traceback
traceback.print_exc()
return False
def list_files_dryrun(self):
"""Lista arquivos no modo dry-run"""
files_listed = 0
total_size = 0
ignored_count = 0
for root, dirs, files in os.walk(self.config['project_path']):
# Filtrar diretórios
dirs[:] = [d for d in dirs if not self.should_ignore_file(
Path(root) / d,
Path(d)
)]
for file in files:
src_path = Path(root) / file
rel_path = src_path.relative_to(self.config['project_path'])
if self.should_ignore_file(src_path, rel_path):
ignored_count += 1
continue
size_kb = src_path.stat().st_size / 1024
total_size += src_path.stat().st_size
files_listed += 1
if files_listed <= 50:
print(f" 📄 {rel_path} ({size_kb:.1f} KB)")
elif files_listed == 51:
print(f" ... e mais arquivos")
print(f"\n Total: {files_listed} arquivos ({total_size / 1024 / 1024:.1f} MB)")
print(f" Ignorados: {ignored_count} arquivos")
def check_prerequisites(self):
"""Verifica arquivos obrigatórios (Dockerfile e requirements.txt)"""
dockerfile_path = self.config['project_path'] / "Dockerfile"
req_path = self.config['project_path'] / "requirements.txt"
missing = []
if not dockerfile_path.exists():
missing.append("Dockerfile")
if not req_path.exists():
missing.append("requirements.txt")
if missing:
print(f"❌ Arquivos obrigatórios faltando: {', '.join(missing)}")
return False
print(f"✅ Pré-requisitos encontrados: Dockerfile e requirements.txt")
return True
def main():
parser = argparse.ArgumentParser(
description="Deploy FORÇADO para Hugging Face Spaces"
)
parser.add_argument("--repo", "-r", help="Nome do Space")
parser.add_argument("--project", "-p", help="Caminho do projeto")
parser.add_argument("--token", "-t", help="Token")
parser.add_argument("--dry-run", "-d", action="store_true", help="Modo simulação")
parser.add_argument("--check", "-c", action="store_true", help="Verificar Dockerfile")
parser.add_argument("--yes", "-y", action="store_true", help="Pular confirmações")
parser.add_argument("--lfs", action="store_true", help="Usar Git LFS para arquivos grandes")
args = parser.parse_args()
deployer = SimpleHFDeploy()
# Sobrescrever configurações
if args.repo:
deployer.config['repo_id'] = args.repo
if args.project:
deployer.config['project_path'] = Path(args.project)
if args.token:
deployer.config['token'] = args.token
if args.lfs:
deployer.config['use_git_lfs'] = True
# Verificar Pré-requisitos
if args.check or not deployer.check_prerequisites():
if args.check:
sys.exit(0)
else:
print("\n❌ Arquivos de configuração necessários")
sys.exit(1)
# Executar deploy
success = deployer.force_deploy(
dry_run=args.dry_run,
skip_confirmation=args.yes
)
sys.exit(0 if success else 1)
if __name__ == "__main__":
# Verificar Git
try:
subprocess.run(['git', '--version'], capture_output=True, check=True)
except:
print("❌ Git não está instalado")
sys.exit(1)
main()