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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
hf_docker_deploy.py - Deploy para Docker Spaces do Hugging Face
|
| 4 |
+
Especializado para Spaces com Dockerfile personalizado
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import shutil
|
| 10 |
+
import subprocess
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from dotenv import load_dotenv, find_dotenv
|
| 13 |
+
from huggingface_hub import HfApi
|
| 14 |
+
from tqdm import tqdm
|
| 15 |
+
import argparse
|
| 16 |
+
import tempfile
|
| 17 |
+
import re
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DockerSpaceDeployer:
|
| 21 |
+
def __init__(self):
|
| 22 |
+
self.config = self.load_config()
|
| 23 |
+
self.api = HfApi()
|
| 24 |
+
|
| 25 |
+
def load_config(self):
|
| 26 |
+
"""Carrega configurações do .env"""
|
| 27 |
+
config = {
|
| 28 |
+
'token': None,
|
| 29 |
+
'repo_id': None,
|
| 30 |
+
'project_path': None,
|
| 31 |
+
'dockerfile_path': None,
|
| 32 |
+
'dockerignore_path': None
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
# Carregar .env
|
| 36 |
+
env_path = find_dotenv(usecwd=True)
|
| 37 |
+
if env_path and Path(env_path).exists():
|
| 38 |
+
load_dotenv(env_path, override=True)
|
| 39 |
+
print(f"🔧 Configurações carregadas de: {env_path}")
|
| 40 |
+
else:
|
| 41 |
+
# Procurar .env em locais comuns
|
| 42 |
+
possible_paths = [
|
| 43 |
+
Path.cwd() / ".env",
|
| 44 |
+
Path(__file__).parent.parent / ".env",
|
| 45 |
+
Path.home() / ".hf_docker_deploy",
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
for path in possible_paths:
|
| 49 |
+
if path.exists():
|
| 50 |
+
load_dotenv(path, override=True)
|
| 51 |
+
print(f"🔧 Configurações carregadas de: {path}")
|
| 52 |
+
break
|
| 53 |
+
|
| 54 |
+
# Carregar valores
|
| 55 |
+
config['token'] = os.getenv("HUGGINGFACE_HUB_TOKEN") or os.getenv("HF_TOKEN")
|
| 56 |
+
config['repo_id'] = os.getenv("HF_SPACE_NAME")
|
| 57 |
+
|
| 58 |
+
# Determinar caminhos
|
| 59 |
+
project_path = os.getenv("HF_PROJECT_PATH")
|
| 60 |
+
if project_path:
|
| 61 |
+
config['project_path'] = Path(project_path)
|
| 62 |
+
if not config['project_path'].is_absolute():
|
| 63 |
+
config['project_path'] = Path.cwd() / config['project_path']
|
| 64 |
+
else:
|
| 65 |
+
config['project_path'] = Path.cwd()
|
| 66 |
+
|
| 67 |
+
# Encontrar Dockerfile
|
| 68 |
+
config['dockerfile_path'] = self.find_dockerfile(config['project_path'])
|
| 69 |
+
config['dockerignore_path'] = config['project_path'] / ".dockerignore"
|
| 70 |
+
|
| 71 |
+
return config
|
| 72 |
+
|
| 73 |
+
def find_dockerfile(self, project_path):
|
| 74 |
+
"""Encontra Dockerfile no projeto"""
|
| 75 |
+
possible_locations = [
|
| 76 |
+
project_path / "Dockerfile",
|
| 77 |
+
project_path / "docker" / "Dockerfile",
|
| 78 |
+
project_path / ".docker" / "Dockerfile",
|
| 79 |
+
project_path / "Dockerfile.hf",
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
for location in possible_locations:
|
| 83 |
+
if location.exists():
|
| 84 |
+
return location
|
| 85 |
+
|
| 86 |
+
# Se não encontrar, verificar se é um requisito
|
| 87 |
+
print("❌ Dockerfile não encontrado!")
|
| 88 |
+
print("\n📋 Para Docker Spaces você DEVE ter um Dockerfile")
|
| 89 |
+
print("\n💡 Exemplo básico de Dockerfile para Python:")
|
| 90 |
+
print("""
|
| 91 |
+
FROM python:3.9-slim
|
| 92 |
+
|
| 93 |
+
WORKDIR /app
|
| 94 |
+
|
| 95 |
+
# Instalar dependências do sistema se necessário
|
| 96 |
+
# RUN apt-get update && apt-get install -y \
|
| 97 |
+
# gcc \
|
| 98 |
+
# g++ \
|
| 99 |
+
# && rm -rf /var/lib/apt/lists/*
|
| 100 |
+
|
| 101 |
+
# Copiar requirements primeiro para cache de layers
|
| 102 |
+
COPY requirements.txt .
|
| 103 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 104 |
+
|
| 105 |
+
# Copiar o resto do código
|
| 106 |
+
COPY . .
|
| 107 |
+
|
| 108 |
+
# Comando para rodar o aplicativo
|
| 109 |
+
CMD ["python", "app.py"]
|
| 110 |
+
""")
|
| 111 |
+
|
| 112 |
+
create = input("\nCriar Dockerfile básico? (s/n): ").lower()
|
| 113 |
+
if create == 's':
|
| 114 |
+
dockerfile_content = """FROM python:3.9-slim
|
| 115 |
+
|
| 116 |
+
WORKDIR /app
|
| 117 |
+
|
| 118 |
+
# Instalar dependências necessárias
|
| 119 |
+
RUN apt-get update && apt-get install -y \
|
| 120 |
+
build-essential \
|
| 121 |
+
curl \
|
| 122 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 123 |
+
|
| 124 |
+
# Copiar requirements primeiro
|
| 125 |
+
COPY requirements.txt .
|
| 126 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 127 |
+
|
| 128 |
+
# Copiar aplicação
|
| 129 |
+
COPY . .
|
| 130 |
+
|
| 131 |
+
# Expor porta (necessário para Hugging Face Spaces)
|
| 132 |
+
EXPOSE 7860
|
| 133 |
+
|
| 134 |
+
# Comando para iniciar
|
| 135 |
+
CMD ["python", "app.py"]
|
| 136 |
+
"""
|
| 137 |
+
dockerfile_path = project_path / "Dockerfile"
|
| 138 |
+
with open(dockerfile_path, 'w', encoding='utf-8') as f:
|
| 139 |
+
f.write(dockerfile_content)
|
| 140 |
+
print(f"✅ Dockerfile criado em: {dockerfile_path}")
|
| 141 |
+
return dockerfile_path
|
| 142 |
+
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
def validate_dockerfile(self, dockerfile_path):
|
| 146 |
+
"""Valida se o Dockerfile está correto para Hugging Face"""
|
| 147 |
+
try:
|
| 148 |
+
with open(dockerfile_path, 'r', encoding='utf-8') as f:
|
| 149 |
+
content = f.read()
|
| 150 |
+
|
| 151 |
+
issues = []
|
| 152 |
+
|
| 153 |
+
# Verificar se expõe a porta correta
|
| 154 |
+
if "EXPOSE" not in content:
|
| 155 |
+
issues.append("❌ Dockerfile deve conter 'EXPOSE 7860' (ou outra porta)")
|
| 156 |
+
elif "EXPOSE 7860" not in content and "EXPOSE 80" not in content:
|
| 157 |
+
issues.append("⚠️ Recomendado: EXPOSE 7860 (porta padrão do HF)")
|
| 158 |
+
|
| 159 |
+
# Verificar se tem CMD
|
| 160 |
+
if "CMD [" not in content and "CMD " not in content:
|
| 161 |
+
issues.append("❌ Dockerfile deve conter CMD para iniciar o app")
|
| 162 |
+
|
| 163 |
+
# Verificar se usa workdir
|
| 164 |
+
if "WORKDIR" not in content:
|
| 165 |
+
issues.append("⚠️ Recomendado: Adicionar WORKDIR /app")
|
| 166 |
+
|
| 167 |
+
if issues:
|
| 168 |
+
print("\n🔍 Problemas encontrados no Dockerfile:")
|
| 169 |
+
for issue in issues:
|
| 170 |
+
print(f" {issue}")
|
| 171 |
+
|
| 172 |
+
fix = input("\nCorrigir automaticamente? (s/n): ").lower()
|
| 173 |
+
if fix == 's':
|
| 174 |
+
return self.fix_dockerfile(dockerfile_path, content)
|
| 175 |
+
|
| 176 |
+
return True
|
| 177 |
+
|
| 178 |
+
except Exception as e:
|
| 179 |
+
print(f"❌ Erro ao validar Dockerfile: {e}")
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
def fix_dockerfile(self, dockerfile_path, original_content):
|
| 183 |
+
"""Corrige problemas comuns no Dockerfile"""
|
| 184 |
+
lines = original_content.split('\n')
|
| 185 |
+
fixed_lines = []
|
| 186 |
+
has_expose = False
|
| 187 |
+
has_workdir = False
|
| 188 |
+
has_cmd = False
|
| 189 |
+
|
| 190 |
+
for line in lines:
|
| 191 |
+
if line.strip().startswith('EXPOSE'):
|
| 192 |
+
has_expose = True
|
| 193 |
+
# Garantir que expõe 7860
|
| 194 |
+
if '7860' not in line:
|
| 195 |
+
line = 'EXPOSE 7860'
|
| 196 |
+
|
| 197 |
+
if line.strip().startswith('WORKDIR'):
|
| 198 |
+
has_workdir = True
|
| 199 |
+
|
| 200 |
+
if line.strip().startswith('CMD'):
|
| 201 |
+
has_cmd = True
|
| 202 |
+
|
| 203 |
+
fixed_lines.append(line)
|
| 204 |
+
|
| 205 |
+
# Adicionar o que falta
|
| 206 |
+
if not has_workdir:
|
| 207 |
+
fixed_lines.insert(1, 'WORKDIR /app')
|
| 208 |
+
|
| 209 |
+
if not has_expose:
|
| 210 |
+
# Inserir antes do CMD
|
| 211 |
+
for i, line in enumerate(fixed_lines):
|
| 212 |
+
if line.strip().startswith('CMD'):
|
| 213 |
+
fixed_lines.insert(i, 'EXPOSE 7860')
|
| 214 |
+
break
|
| 215 |
+
else:
|
| 216 |
+
fixed_lines.append('EXPOSE 7860')
|
| 217 |
+
|
| 218 |
+
if not has_cmd:
|
| 219 |
+
fixed_lines.append('CMD ["python", "app.py"]')
|
| 220 |
+
|
| 221 |
+
# Salvar
|
| 222 |
+
with open(dockerfile_path, 'w', encoding='utf-8') as f:
|
| 223 |
+
f.write('\n'.join(fixed_lines))
|
| 224 |
+
|
| 225 |
+
print(f"✅ Dockerfile corrigido: {dockerfile_path}")
|
| 226 |
+
return True
|
| 227 |
+
|
| 228 |
+
def process_dockerignore(self, project_path, dockerignore_path):
|
| 229 |
+
"""Processa .dockerignore para excluir arquivos corretamente"""
|
| 230 |
+
ignore_patterns = []
|
| 231 |
+
|
| 232 |
+
if dockerignore_path.exists():
|
| 233 |
+
with open(dockerignore_path, 'r', encoding='utf-8') as f:
|
| 234 |
+
ignore_patterns = [
|
| 235 |
+
line.strip()
|
| 236 |
+
for line in f.readlines()
|
| 237 |
+
if line.strip() and not line.startswith('#')
|
| 238 |
+
]
|
| 239 |
+
|
| 240 |
+
# Padrões padrão para Hugging Face
|
| 241 |
+
default_patterns = [
|
| 242 |
+
'.git', '.env', '__pycache__', '*.pyc', '*.pyo', '*.pyd',
|
| 243 |
+
'.Python', '.vscode', '.idea', '*.log', '*.sqlite3-journal',
|
| 244 |
+
'venv/', 'env/', '.venv', '*.db-wal', '*.db-shm'
|
| 245 |
+
]
|
| 246 |
+
|
| 247 |
+
ignore_patterns.extend(default_patterns)
|
| 248 |
+
return ignore_patterns
|
| 249 |
+
|
| 250 |
+
def should_ignore(self, file_path, ignore_patterns, project_path):
|
| 251 |
+
"""Verifica se um arquivo deve ser ignorado - versão melhorada"""
|
| 252 |
+
import fnmatch
|
| 253 |
+
|
| 254 |
+
relative_path = str(file_path.relative_to(project_path))
|
| 255 |
+
# Normalizar para Unix-style paths
|
| 256 |
+
relative_path = relative_path.replace('\\', '/')
|
| 257 |
+
|
| 258 |
+
# Também considerar o caminho absoluto do arquivo
|
| 259 |
+
abs_path = str(file_path).replace('\\', '/')
|
| 260 |
+
|
| 261 |
+
for raw_pattern in ignore_patterns:
|
| 262 |
+
pattern = raw_pattern.replace('\\', '/')
|
| 263 |
+
|
| 264 |
+
# Pular padrões vazios
|
| 265 |
+
if not pattern:
|
| 266 |
+
continue
|
| 267 |
+
|
| 268 |
+
# 1. Tratar comentários (deveriam ter sido removidos, mas por segurança)
|
| 269 |
+
if pattern.startswith('#'):
|
| 270 |
+
continue
|
| 271 |
+
|
| 272 |
+
# 2. Tratar padrões que começam com ! (negação) - para implementação futura
|
| 273 |
+
if pattern.startswith('!'):
|
| 274 |
+
# Por enquanto, ignoramos negações
|
| 275 |
+
pattern = pattern[1:]
|
| 276 |
+
if not pattern:
|
| 277 |
+
continue
|
| 278 |
+
|
| 279 |
+
# 3. Tratar padrões com ** (recursivo)
|
| 280 |
+
if '**' in pattern:
|
| 281 |
+
# Converter ** para * para fnmatch
|
| 282 |
+
fn_pattern = pattern.replace('**', '*')
|
| 283 |
+
if fnmatch.fnmatch(relative_path, fn_pattern) or fnmatch.fnmatch(abs_path, fn_pattern):
|
| 284 |
+
return True
|
| 285 |
+
|
| 286 |
+
# 4. Tratar padrões de diretório (terminam com /)
|
| 287 |
+
elif pattern.endswith('/'):
|
| 288 |
+
dir_pattern = pattern.rstrip('/')
|
| 289 |
+
if (relative_path.startswith(dir_pattern + '/') or
|
| 290 |
+
relative_path == dir_pattern or
|
| 291 |
+
abs_path.endswith('/' + dir_pattern) or
|
| 292 |
+
('/' + dir_pattern + '/') in abs_path):
|
| 293 |
+
return True
|
| 294 |
+
|
| 295 |
+
# 5. Padrões relativos à raiz (começam com /)
|
| 296 |
+
elif pattern.startswith('/'):
|
| 297 |
+
root_pattern = pattern[1:]
|
| 298 |
+
if (relative_path == root_pattern or
|
| 299 |
+
relative_path.startswith(root_pattern + '/')):
|
| 300 |
+
return True
|
| 301 |
+
|
| 302 |
+
# 6. Verificar padrão em qualquer parte do caminho
|
| 303 |
+
elif pattern in relative_path or pattern in abs_path:
|
| 304 |
+
return True
|
| 305 |
+
|
| 306 |
+
# 7. Padrões com wildcards normais
|
| 307 |
+
elif '*' in pattern or '?' in pattern or '[' in pattern:
|
| 308 |
+
if (fnmatch.fnmatch(relative_path, pattern) or
|
| 309 |
+
fnmatch.fnmatch(abs_path, pattern)):
|
| 310 |
+
return True
|
| 311 |
+
|
| 312 |
+
# 8. Padrão simples (nome exato de arquivo)
|
| 313 |
+
elif file_path.name == pattern:
|
| 314 |
+
return True
|
| 315 |
+
|
| 316 |
+
return False
|
| 317 |
+
|
| 318 |
+
def collect_files_for_deploy(self):
|
| 319 |
+
"""Coleta arquivos para deploy, respeitando .dockerignore"""
|
| 320 |
+
print("📦 Coletando arquivos para deploy Docker...")
|
| 321 |
+
|
| 322 |
+
# Carregar padrões de ignore
|
| 323 |
+
ignore_patterns = self.process_dockerignore(
|
| 324 |
+
self.config['project_path'],
|
| 325 |
+
self.config['dockerignore_path']
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
# DEBUG: Mostrar padrões carregados
|
| 329 |
+
print(f"\n🔍 Padrões .dockerignore carregados ({len(ignore_patterns)}):")
|
| 330 |
+
for i, pattern in enumerate(ignore_patterns[:20], 1):
|
| 331 |
+
print(f" {i:2}. {pattern}")
|
| 332 |
+
if len(ignore_patterns) > 20:
|
| 333 |
+
print(f" ... e mais {len(ignore_patterns) - 20} padrões")
|
| 334 |
+
|
| 335 |
+
files_to_deploy = []
|
| 336 |
+
ignored_files = []
|
| 337 |
+
total_size = 0
|
| 338 |
+
|
| 339 |
+
for root, dirs, files in os.walk(self.config['project_path']):
|
| 340 |
+
# Converter caminho para Path object
|
| 341 |
+
root_path = Path(root)
|
| 342 |
+
|
| 343 |
+
# Filtrar diretórios
|
| 344 |
+
dirs_to_remove = []
|
| 345 |
+
for d in dirs:
|
| 346 |
+
dir_path = root_path / d
|
| 347 |
+
if self.should_ignore(dir_path, ignore_patterns, self.config['project_path']):
|
| 348 |
+
dirs_to_remove.append(d)
|
| 349 |
+
print(f" 🚫 Ignorando diretório: {dir_path.relative_to(self.config['project_path'])}")
|
| 350 |
+
|
| 351 |
+
for d in dirs_to_remove:
|
| 352 |
+
dirs.remove(d)
|
| 353 |
+
|
| 354 |
+
for file in files:
|
| 355 |
+
file_path = root_path / file
|
| 356 |
+
rel_path = file_path.relative_to(self.config['project_path'])
|
| 357 |
+
|
| 358 |
+
# Verificar se deve ignorar
|
| 359 |
+
if self.should_ignore(file_path, ignore_patterns, self.config['project_path']):
|
| 360 |
+
ignored_files.append(str(rel_path))
|
| 361 |
+
continue
|
| 362 |
+
|
| 363 |
+
# Verificar tamanho (Hugging Face tem limites)
|
| 364 |
+
file_size = file_path.stat().st_size
|
| 365 |
+
if file_size > 100 * 1024 * 1024: # 100MB
|
| 366 |
+
print(f"⚠️ Arquivo grande: {rel_path} ({file_size / 1024 / 1024:.1f} MB)")
|
| 367 |
+
confirm = input("Continuar com upload? (s/n): ").lower()
|
| 368 |
+
if confirm != 's':
|
| 369 |
+
ignored_files.append(f"{rel_path} (grande)")
|
| 370 |
+
continue
|
| 371 |
+
|
| 372 |
+
files_to_deploy.append((file_path, rel_path))
|
| 373 |
+
total_size += file_size
|
| 374 |
+
|
| 375 |
+
# Estatísticas
|
| 376 |
+
print(f"\n📊 Estatísticas:")
|
| 377 |
+
print(f" • Total arquivos processados: {len(files_to_deploy) + len(ignored_files)}")
|
| 378 |
+
print(f" • Arquivos para deploy: {len(files_to_deploy)}")
|
| 379 |
+
print(f" • Arquivos ignorados: {len(ignored_files)}")
|
| 380 |
+
print(f" • Tamanho total: {total_size / 1024 / 1024:.2f} MB")
|
| 381 |
+
|
| 382 |
+
# Mostrar alguns arquivos ignorados (para debug)
|
| 383 |
+
if ignored_files:
|
| 384 |
+
print(f"\n📋 Exemplos de arquivos ignorados (primeiros 10):")
|
| 385 |
+
for ignored in ignored_files[:10]:
|
| 386 |
+
print(f" 🚫 {ignored}")
|
| 387 |
+
if len(ignored_files) > 10:
|
| 388 |
+
print(f" ... e mais {len(ignored_files) - 10} arquivos ignorados")
|
| 389 |
+
|
| 390 |
+
# Listar os 10 maiores arquivos
|
| 391 |
+
if files_to_deploy:
|
| 392 |
+
print(f"\n📁 Maiores arquivos a serem enviados:")
|
| 393 |
+
files_with_size = [(p, p.stat().st_size) for p, _ in files_to_deploy]
|
| 394 |
+
files_with_size.sort(key=lambda x: x[1], reverse=True)
|
| 395 |
+
|
| 396 |
+
for file_path, size in files_with_size[:10]:
|
| 397 |
+
rel_path = file_path.relative_to(self.config['project_path'])
|
| 398 |
+
size_mb = size / 1024 / 1024
|
| 399 |
+
print(f" • {rel_path}: {size_mb:.2f} MB")
|
| 400 |
+
|
| 401 |
+
return files_to_deploy
|
| 402 |
+
|
| 403 |
+
def deploy(self, dry_run=False):
|
| 404 |
+
"""Executa o deploy para Docker Space"""
|
| 405 |
+
|
| 406 |
+
# Verificar se temos Dockerfile
|
| 407 |
+
if not self.config['dockerfile_path'] or not self.config['dockerfile_path'].exists():
|
| 408 |
+
print("❌ Dockerfile é obrigatório para Docker Spaces")
|
| 409 |
+
return False
|
| 410 |
+
|
| 411 |
+
# Validar Dockerfile
|
| 412 |
+
if not self.validate_dockerfile(self.config['dockerfile_path']):
|
| 413 |
+
return False
|
| 414 |
+
|
| 415 |
+
# Solicitar repo_id se não configurado
|
| 416 |
+
if not self.config['repo_id']:
|
| 417 |
+
self.config['repo_id'] = input(
|
| 418 |
+
"Digite o nome do Docker Space (usuário/space-name): "
|
| 419 |
+
).strip()
|
| 420 |
+
|
| 421 |
+
if not self.config['repo_id']:
|
| 422 |
+
print("❌ Nome do Space é obrigatório")
|
| 423 |
+
return False
|
| 424 |
+
|
| 425 |
+
# Solicitar token se não configurado
|
| 426 |
+
if not self.config['token']:
|
| 427 |
+
print("🔑 Token não encontrado no .env")
|
| 428 |
+
self.config['token'] = input("Digite seu token do Hugging Face: ").strip()
|
| 429 |
+
|
| 430 |
+
if not self.config['token']:
|
| 431 |
+
print("❌ Token é obrigatório")
|
| 432 |
+
return False
|
| 433 |
+
|
| 434 |
+
# Verificar espaço
|
| 435 |
+
try:
|
| 436 |
+
print(f"🔍 Verificando Docker Space: {self.config['repo_id']}")
|
| 437 |
+
repo_info = self.api.repo_info(
|
| 438 |
+
repo_id=self.config['repo_id'],
|
| 439 |
+
repo_type="space",
|
| 440 |
+
token=self.config['token']
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
if repo_info.private:
|
| 444 |
+
print("🔒 Space privado detectado")
|
| 445 |
+
|
| 446 |
+
print(f"✅ Space encontrado: {repo_info.id}")
|
| 447 |
+
print(f" 👤 Autor: {repo_info.author}")
|
| 448 |
+
print(f" 🐳 Tipo: Docker Space")
|
| 449 |
+
|
| 450 |
+
except Exception as e:
|
| 451 |
+
print(f"❌ Erro ao acessar Space: {e}")
|
| 452 |
+
print("\n💡 Certifique-se de:")
|
| 453 |
+
print(" 1. O Space existe e é do tipo Docker")
|
| 454 |
+
print(" 2. Você tem permissão de escrita")
|
| 455 |
+
print(" 3. O token está correto")
|
| 456 |
+
return False
|
| 457 |
+
|
| 458 |
+
# Coletar arquivos
|
| 459 |
+
files_to_deploy = self.collect_files_for_deploy()
|
| 460 |
+
|
| 461 |
+
if dry_run:
|
| 462 |
+
print("\n🚀 MODO SIMULAÇÃO - Nenhum arquivo será enviado")
|
| 463 |
+
print("Arquivos que seriam enviados:")
|
| 464 |
+
# for _, rel_path in files_to_deploy[:20]:
|
| 465 |
+
# print(f" 📄 {rel_path}")
|
| 466 |
+
# if len(files_to_deploy) > 20:
|
| 467 |
+
# print(f" ... e mais {len(files_to_deploy) - 20} arquivos")
|
| 468 |
+
for _, rel_path in files_to_deploy:
|
| 469 |
+
print(f" 📄 {rel_path}")
|
| 470 |
+
return True
|
| 471 |
+
|
| 472 |
+
# Confirmação final
|
| 473 |
+
print(f"\n⚠️ ATENÇÃO: Isso irá fazer upload para:")
|
| 474 |
+
print(f" Space: {self.config['repo_id']}")
|
| 475 |
+
print(f" Arquivos: {len(files_to_deploy)}")
|
| 476 |
+
print(f" Tipo: Docker Space (build automático após upload)")
|
| 477 |
+
|
| 478 |
+
confirm = input("\n🔴 Confirmar deploy? (s/n): ").lower()
|
| 479 |
+
if confirm not in ['s', 'sim', 'y', 'yes']:
|
| 480 |
+
print("❌ Deploy cancelado")
|
| 481 |
+
return False
|
| 482 |
+
|
| 483 |
+
# Fazer upload
|
| 484 |
+
print("\n⬆️ Enviando arquivos para Docker Space...")
|
| 485 |
+
successful = 0
|
| 486 |
+
failed = 0
|
| 487 |
+
|
| 488 |
+
for file_path, rel_path in tqdm(files_to_deploy, desc="Enviando"):
|
| 489 |
+
try:
|
| 490 |
+
# Para Docker Spaces, é importante manter a estrutura exata
|
| 491 |
+
self.api.upload_file(
|
| 492 |
+
path_or_fileobj=str(file_path),
|
| 493 |
+
path_in_repo=str(rel_path),
|
| 494 |
+
repo_id=self.config['repo_id'],
|
| 495 |
+
repo_type="space",
|
| 496 |
+
token=self.config['token'],
|
| 497 |
+
commit_message=f"Deploy Docker: {rel_path}"
|
| 498 |
+
)
|
| 499 |
+
successful += 1
|
| 500 |
+
|
| 501 |
+
except Exception as e:
|
| 502 |
+
print(f"\n❌ Falha ao enviar {rel_path}: {str(e)[:100]}")
|
| 503 |
+
failed += 1
|
| 504 |
+
|
| 505 |
+
# Resumo
|
| 506 |
+
print("\n" + "=" * 60)
|
| 507 |
+
print("🐳 DEPLOY DOCKER SPACE CONCLUÍDO")
|
| 508 |
+
print("=" * 60)
|
| 509 |
+
print(f"✅ Sucesso: {successful} arquivos")
|
| 510 |
+
if failed > 0:
|
| 511 |
+
print(f"❌ Falhas: {failed} arquivos")
|
| 512 |
+
print(f"🌐 Space: https://huggingface.co/spaces/{self.config['repo_id']}")
|
| 513 |
+
print(f"🔨 Build: https://huggingface.co/spaces/{self.config['repo_id']}/builds")
|
| 514 |
+
print("\n💡 IMPORTANTE:")
|
| 515 |
+
print(" • O Hugging Face iniciará automaticamente o build Docker")
|
| 516 |
+
print(" • O build pode levar alguns minutos")
|
| 517 |
+
print(" • Monitore o progresso na aba 'Builds'")
|
| 518 |
+
print("=" * 60)
|
| 519 |
+
|
| 520 |
+
return failed == 0
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def main():
|
| 524 |
+
parser = argparse.ArgumentParser(
|
| 525 |
+
description="Deploy especializado para Docker Spaces do Hugging Face"
|
| 526 |
+
)
|
| 527 |
+
parser.add_argument("--repo", "-r", help="Nome do Docker Space")
|
| 528 |
+
parser.add_argument("--project", "-p", help="Caminho do projeto")
|
| 529 |
+
parser.add_argument("--token", "-t", help="Token do Hugging Face")
|
| 530 |
+
parser.add_argument("--dry-run", "-d", action="store_true", help="Modo simulação")
|
| 531 |
+
parser.add_argument("--validate", "-v", action="store_true", help="Apenas validar Dockerfile")
|
| 532 |
+
|
| 533 |
+
args = parser.parse_args()
|
| 534 |
+
|
| 535 |
+
deployer = DockerSpaceDeployer()
|
| 536 |
+
|
| 537 |
+
# Sobrescrever configurações se fornecidas
|
| 538 |
+
if args.repo:
|
| 539 |
+
deployer.config['repo_id'] = args.repo
|
| 540 |
+
if args.project:
|
| 541 |
+
deployer.config['project_path'] = Path(args.project)
|
| 542 |
+
deployer.config['dockerfile_path'] = deployer.find_dockerfile(
|
| 543 |
+
deployer.config['project_path']
|
| 544 |
+
)
|
| 545 |
+
if args.token:
|
| 546 |
+
deployer.config['token'] = args.token
|
| 547 |
+
|
| 548 |
+
if args.validate:
|
| 549 |
+
# Apenas validação
|
| 550 |
+
if deployer.config['dockerfile_path']:
|
| 551 |
+
print(f"🔍 Validando Dockerfile: {deployer.config['dockerfile_path']}")
|
| 552 |
+
deployer.validate_dockerfile(deployer.config['dockerfile_path'])
|
| 553 |
+
return
|
| 554 |
+
|
| 555 |
+
# Executar deploy
|
| 556 |
+
success = deployer.deploy(args.dry_run)
|
| 557 |
+
sys.exit(0 if success else 1)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
if __name__ == "__main__":
|
| 561 |
+
main()
|