File size: 23,486 Bytes
beb04eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 | #!/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()
|