celiolr commited on
Commit
beb04eb
·
1 Parent(s): 130f1a7

Deploy: 51 arquivos - 2025-12-19 14:32:02

Browse files
app/core/config.py CHANGED
@@ -1,64 +1,69 @@
1
- import os
2
- import logging
3
- import warnings
4
- from typing import List, Optional
5
- from dotenv import load_dotenv
6
-
7
- # Carrega variáveis do arquivo .env
8
- load_dotenv()
9
-
10
- # Silencia warnings específicos de bibliotecas de terceiros
11
- try:
12
- from cryptography.utils import CryptographyDeprecationWarning
13
- warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning)
14
- except ImportError:
15
- pass
16
-
17
- class Settings:
18
- def __init__(self):
19
- self.api_prefix: str = "/api/v1"
20
- self.project_name: str = "Local RAG API"
21
- self.version: str = "1.0.0"
22
- self.description: str = "RAG system with local Chroma vector store"
23
- self.port: int = 8000
24
-
25
- # Security (NOVO)
26
- self.secret_key: str = os.getenv("SECRET_KEY", "uma_chave_padrao_insegura_para_dev")
27
-
28
- # Embeddings
29
- self.embeddings_model: str = os.getenv("EMBEDDINGS_MODEL", "paraphrase-multilingual-mpnet-base-v2")
30
-
31
- # LLM API Keys
32
- self.openai_api_key: Optional[str] = os.getenv("OPENAI_API_KEY")
33
- self.google_api_key: Optional[str] = os.getenv("GOOGLE_API_KEY")
34
- self.groq_api_key: Optional[str] = os.getenv("GROQ_API_KEY")
35
-
36
- # TFS Configuration
37
- self.tfs_url: Optional[str] = os.getenv("TFS_URL")
38
- self.tfs_pat: Optional[str] = os.getenv("TFS_PAT")
39
- self.tfs_project: Optional[str] = os.getenv("TFS_PROJECT")
40
-
41
- # Vector Store
42
- self.chroma_persist_directory: str = os.getenv("CHROMA_PERSIST_DIRECTORY", "./data/chroma_db")
43
- self.collection_name: str = os.getenv("COLLECTION_NAME", "document_chunks")
44
-
45
- # Document Processing
46
- self.documents_directory_raw: str = os.getenv("DOCUMENTS_DIRECTORY_RAW", "./data/raw_documents")
47
- self.documents_directory_processed: str = os.getenv("DOCUMENTS_DIRECTORY_PROCESSED", "./data/processed")
48
-
49
- self.chunk_size: int = int(os.getenv("CHUNK_SIZE", "1000"))
50
- self.chunk_overlap: int = int(os.getenv("CHUNK_OVERLAP", "200"))
51
-
52
- self.supported_extensions: List[str] = [
53
- '.txt', '.md', '.pdf', '.docx', '.ini',
54
- '.xlsx', '.xls', '.pptx', '.ppt', '.html',
55
- ]
56
-
57
- # Logging
58
- self.log_level: str = os.getenv("LOG_LEVEL", "INFO")
59
-
60
- # Instância global de configurações
61
- settings = Settings()
62
-
63
- # O logger é apenas instanciado aqui, mas não configurado.
64
- logger = logging.getLogger(__name__)
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import warnings
4
+ from pathlib import Path
5
+ from typing import List, Optional
6
+ from dotenv import load_dotenv
7
+
8
+ # Carrega variáveis do arquivo .env
9
+ load_dotenv()
10
+
11
+ # Silencia warnings específicos de bibliotecas de terceiros
12
+ try:
13
+ from cryptography.utils import CryptographyDeprecationWarning
14
+ warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning)
15
+ except ImportError:
16
+ pass
17
+
18
+ class Settings:
19
+ def __init__(self):
20
+ # Define a raiz do projeto dinamicamente (2 níveis acima de app/core/config.py)
21
+ # Isso garante que os caminhos funcionem no Windows, Linux e Docker sem depender do CWD
22
+ self.root_dir: Path = Path(__file__).resolve().parent.parent.parent
23
+
24
+ self.api_prefix: str = "/api/v1"
25
+ self.project_name: str = "Local RAG API"
26
+ self.version: str = "1.0.0"
27
+ self.description: str = "RAG system with local Chroma vector store"
28
+ self.port: int = int(os.getenv("PORT", 8000))
29
+
30
+ # Security (NOVO)
31
+ self.secret_key: str = os.getenv("SECRET_KEY", "uma_chave_padrao_insegura_para_dev")
32
+
33
+ # Embeddings
34
+ self.embeddings_model: str = os.getenv("EMBEDDINGS_MODEL", "paraphrase-multilingual-mpnet-base-v2")
35
+
36
+ # LLM API Keys
37
+ self.openai_api_key: Optional[str] = os.getenv("OPENAI_API_KEY")
38
+ self.google_api_key: Optional[str] = os.getenv("GOOGLE_API_KEY")
39
+ self.groq_api_key: Optional[str] = os.getenv("GROQ_API_KEY")
40
+
41
+ # TFS Configuration
42
+ self.tfs_url: Optional[str] = os.getenv("TFS_URL")
43
+ self.tfs_pat: Optional[str] = os.getenv("TFS_PAT")
44
+ self.tfs_project: Optional[str] = os.getenv("TFS_PROJECT")
45
+
46
+ # Vector Store
47
+ self.chroma_persist_directory: str = os.getenv("CHROMA_PERSIST_DIRECTORY", str(self.root_dir / "data" / "chroma_db"))
48
+ self.collection_name: str = os.getenv("COLLECTION_NAME", "document_chunks")
49
+
50
+ # Document Processing
51
+ self.documents_directory_raw: str = os.getenv("DOCUMENTS_DIRECTORY_RAW", str(self.root_dir / "data" / "raw_documents"))
52
+ self.documents_directory_processed: str = os.getenv("DOCUMENTS_DIRECTORY_PROCESSED", str(self.root_dir / "data" / "processed"))
53
+
54
+ self.chunk_size: int = int(os.getenv("CHUNK_SIZE", "1000"))
55
+ self.chunk_overlap: int = int(os.getenv("CHUNK_OVERLAP", "200"))
56
+
57
+ self.supported_extensions: List[str] = [
58
+ '.txt', '.md', '.pdf', '.docx', '.ini',
59
+ '.xlsx', '.xls', '.pptx', '.ppt', '.html',
60
+ ]
61
+
62
+ # Logging
63
+ self.log_level: str = os.getenv("LOG_LEVEL", "INFO")
64
+
65
+ # Instância global de configurações
66
+ settings = Settings()
67
+
68
+ # O logger é apenas instanciado aqui, mas não configurado.
69
+ logger = logging.getLogger(__name__)
app//core//config.py CHANGED
@@ -1,64 +1,69 @@
1
- import os
2
- import logging
3
- import warnings
4
- from typing import List, Optional
5
- from dotenv import load_dotenv
6
-
7
- # Carrega variáveis do arquivo .env
8
- load_dotenv()
9
-
10
- # Silencia warnings específicos de bibliotecas de terceiros
11
- try:
12
- from cryptography.utils import CryptographyDeprecationWarning
13
- warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning)
14
- except ImportError:
15
- pass
16
-
17
- class Settings:
18
- def __init__(self):
19
- self.api_prefix: str = "/api/v1"
20
- self.project_name: str = "Local RAG API"
21
- self.version: str = "1.0.0"
22
- self.description: str = "RAG system with local Chroma vector store"
23
- self.port: int = 8000
24
-
25
- # Security (NOVO)
26
- self.secret_key: str = os.getenv("SECRET_KEY", "uma_chave_padrao_insegura_para_dev")
27
-
28
- # Embeddings
29
- self.embeddings_model: str = os.getenv("EMBEDDINGS_MODEL", "paraphrase-multilingual-mpnet-base-v2")
30
-
31
- # LLM API Keys
32
- self.openai_api_key: Optional[str] = os.getenv("OPENAI_API_KEY")
33
- self.google_api_key: Optional[str] = os.getenv("GOOGLE_API_KEY")
34
- self.groq_api_key: Optional[str] = os.getenv("GROQ_API_KEY")
35
-
36
- # TFS Configuration
37
- self.tfs_url: Optional[str] = os.getenv("TFS_URL")
38
- self.tfs_pat: Optional[str] = os.getenv("TFS_PAT")
39
- self.tfs_project: Optional[str] = os.getenv("TFS_PROJECT")
40
-
41
- # Vector Store
42
- self.chroma_persist_directory: str = os.getenv("CHROMA_PERSIST_DIRECTORY", "./data/chroma_db")
43
- self.collection_name: str = os.getenv("COLLECTION_NAME", "document_chunks")
44
-
45
- # Document Processing
46
- self.documents_directory_raw: str = os.getenv("DOCUMENTS_DIRECTORY_RAW", "./data/raw_documents")
47
- self.documents_directory_processed: str = os.getenv("DOCUMENTS_DIRECTORY_PROCESSED", "./data/processed")
48
-
49
- self.chunk_size: int = int(os.getenv("CHUNK_SIZE", "1000"))
50
- self.chunk_overlap: int = int(os.getenv("CHUNK_OVERLAP", "200"))
51
-
52
- self.supported_extensions: List[str] = [
53
- '.txt', '.md', '.pdf', '.docx', '.ini',
54
- '.xlsx', '.xls', '.pptx', '.ppt', '.html',
55
- ]
56
-
57
- # Logging
58
- self.log_level: str = os.getenv("LOG_LEVEL", "INFO")
59
-
60
- # Instância global de configurações
61
- settings = Settings()
62
-
63
- # O logger é apenas instanciado aqui, mas não configurado.
64
- logger = logging.getLogger(__name__)
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import warnings
4
+ from pathlib import Path
5
+ from typing import List, Optional
6
+ from dotenv import load_dotenv
7
+
8
+ # Carrega variáveis do arquivo .env
9
+ load_dotenv()
10
+
11
+ # Silencia warnings específicos de bibliotecas de terceiros
12
+ try:
13
+ from cryptography.utils import CryptographyDeprecationWarning
14
+ warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning)
15
+ except ImportError:
16
+ pass
17
+
18
+ class Settings:
19
+ def __init__(self):
20
+ # Define a raiz do projeto dinamicamente (2 níveis acima de app/core/config.py)
21
+ # Isso garante que os caminhos funcionem no Windows, Linux e Docker sem depender do CWD
22
+ self.root_dir: Path = Path(__file__).resolve().parent.parent.parent
23
+
24
+ self.api_prefix: str = "/api/v1"
25
+ self.project_name: str = "Local RAG API"
26
+ self.version: str = "1.0.0"
27
+ self.description: str = "RAG system with local Chroma vector store"
28
+ self.port: int = int(os.getenv("PORT", 8000))
29
+
30
+ # Security (NOVO)
31
+ self.secret_key: str = os.getenv("SECRET_KEY", "uma_chave_padrao_insegura_para_dev")
32
+
33
+ # Embeddings
34
+ self.embeddings_model: str = os.getenv("EMBEDDINGS_MODEL", "paraphrase-multilingual-mpnet-base-v2")
35
+
36
+ # LLM API Keys
37
+ self.openai_api_key: Optional[str] = os.getenv("OPENAI_API_KEY")
38
+ self.google_api_key: Optional[str] = os.getenv("GOOGLE_API_KEY")
39
+ self.groq_api_key: Optional[str] = os.getenv("GROQ_API_KEY")
40
+
41
+ # TFS Configuration
42
+ self.tfs_url: Optional[str] = os.getenv("TFS_URL")
43
+ self.tfs_pat: Optional[str] = os.getenv("TFS_PAT")
44
+ self.tfs_project: Optional[str] = os.getenv("TFS_PROJECT")
45
+
46
+ # Vector Store
47
+ self.chroma_persist_directory: str = os.getenv("CHROMA_PERSIST_DIRECTORY", str(self.root_dir / "data" / "chroma_db"))
48
+ self.collection_name: str = os.getenv("COLLECTION_NAME", "document_chunks")
49
+
50
+ # Document Processing
51
+ self.documents_directory_raw: str = os.getenv("DOCUMENTS_DIRECTORY_RAW", str(self.root_dir / "data" / "raw_documents"))
52
+ self.documents_directory_processed: str = os.getenv("DOCUMENTS_DIRECTORY_PROCESSED", str(self.root_dir / "data" / "processed"))
53
+
54
+ self.chunk_size: int = int(os.getenv("CHUNK_SIZE", "1000"))
55
+ self.chunk_overlap: int = int(os.getenv("CHUNK_OVERLAP", "200"))
56
+
57
+ self.supported_extensions: List[str] = [
58
+ '.txt', '.md', '.pdf', '.docx', '.ini',
59
+ '.xlsx', '.xls', '.pptx', '.ppt', '.html',
60
+ ]
61
+
62
+ # Logging
63
+ self.log_level: str = os.getenv("LOG_LEVEL", "INFO")
64
+
65
+ # Instância global de configurações
66
+ settings = Settings()
67
+
68
+ # O logger é apenas instanciado aqui, mas não configurado.
69
+ logger = logging.getLogger(__name__)
scripts/hugging_face_deploy.py CHANGED
@@ -1,642 +1,649 @@
1
- #!/usr/bin/env python3
2
- """
3
- huggingface_force_deploy.py - Deploy FORÇADO para Hugging Face Spaces
4
- Versão FINAL com suporte a arquivos grandes
5
- """
6
-
7
- import os
8
- import sys
9
- import shutil
10
- import tempfile
11
- import subprocess
12
- from pathlib import Path
13
- from dotenv import load_dotenv
14
- import argparse
15
- import time
16
- import fnmatch
17
- import atexit
18
-
19
-
20
- class SimpleHFDeploy:
21
- def __init__(self):
22
- self.config = self.load_config()
23
- self.temp_dirs = []
24
-
25
- # Registrar limpeza automática
26
- atexit.register(self.cleanup_temp_dirs)
27
-
28
- def cleanup_temp_dirs(self):
29
- """Limpa todos os diretórios temporários"""
30
- for temp_dir in self.temp_dirs[:]:
31
- if os.path.exists(temp_dir):
32
- try:
33
- self.force_remove_windows(temp_dir)
34
- self.temp_dirs.remove(temp_dir)
35
- except:
36
- pass
37
-
38
- def force_remove_windows(self, path):
39
- """Remove arquivos/diretórios no Windows"""
40
- if not os.path.exists(path):
41
- return
42
-
43
- try:
44
- # Tentar remover normalmente primeiro
45
- if os.path.isfile(path):
46
- os.unlink(path)
47
- else:
48
- shutil.rmtree(path, ignore_errors=True)
49
- except:
50
- # Se falhar, tentar como administrador
51
- try:
52
- if sys.platform == 'win32':
53
- subprocess.run(f'rmdir /S /Q "{path}"', shell=True,
54
- capture_output=True, timeout=5)
55
- else:
56
- subprocess.run(['rm', '-rf', path],
57
- capture_output=True, timeout=5)
58
- except:
59
- pass # Ignorar erros finais
60
-
61
- def load_config(self):
62
- """Carrega configurações do .env"""
63
- config = {
64
- 'token': None,
65
- 'repo_id': None,
66
- 'project_path': None,
67
- 'use_git_lfs': False # Nova opção para Git LFS
68
- }
69
-
70
- # Carregar .env
71
- env_path = Path.cwd() / ".env"
72
- if env_path.exists():
73
- load_dotenv(env_path)
74
- print(f"🔧 Configurações de: {env_path}")
75
-
76
- config['token'] = os.getenv("HUGGINGFACE_HUB_TOKEN")
77
- config['repo_id'] = os.getenv("HF_SPACE_NAME")
78
-
79
- # Nova configuração para Git LFS
80
- config['use_git_lfs'] = os.getenv("HF_USE_GIT_LFS", "false").lower() == "true"
81
-
82
- # Determinar caminho do projeto
83
- project_path = os.getenv("HF_PROJECT_PATH")
84
- if project_path:
85
- config['project_path'] = Path(project_path)
86
- if not config['project_path'].is_absolute():
87
- config['project_path'] = Path.cwd() / config['project_path']
88
- else:
89
- config['project_path'] = Path.cwd()
90
-
91
- return config
92
-
93
- def fix_git_safe_directory(self, repo_dir):
94
- """Corrige problema de safe.directory do Git no Windows"""
95
- try:
96
- # Configurar diretório como seguro
97
- git_path = str(repo_dir).replace('\\', '/')
98
- cmd = f'git config --global --add safe.directory "{git_path}"'
99
-
100
- result = subprocess.run(cmd, shell=True,
101
- capture_output=True, text=True)
102
-
103
- if result.returncode == 0:
104
- print(f"✅ Diretório seguro configurado: {git_path}")
105
- return True
106
- else:
107
- print(f"⚠️ Não foi possível configurar diretório seguro: {result.stderr[:100]}")
108
- return False
109
-
110
- except Exception as e:
111
- print(f"⚠️ Erro ao configurar diretório seguro: {e}")
112
- return False
113
-
114
- def should_ignore_file(self, file_path, rel_path):
115
- """Determina se um arquivo deve ser ignorado baseado em padrões"""
116
-
117
- # Converter caminho para string Unix-style
118
- rel_str = str(rel_path).replace('\\', '/')
119
- file_name = file_path.name
120
-
121
- # Lista de padrões para IGNORAR
122
- ignore_patterns = [
123
- # Sistema e IDE
124
- '.git', '.gitignore', '.env', '.env.example',
125
- '.vscode', '.idea', '.DS_Store',
126
-
127
- # Python
128
- '__pycache__/', '*.pyc', '*.pyo', '*.pyd',
129
- 'venv/', '.venv/', 'env/',
130
-
131
- # Testes e cache
132
- '.pytest_cache/', '.coverage', 'htmlcov/',
133
- '*.log', '*.tmp', '*.temp',
134
-
135
- # Dados temporários/processados
136
- 'data/processed/', 'data/raw_documents/',
137
- 'data/temp/', 'data/cache/', 'data/backup/',
138
-
139
- # Build e distribuição
140
- 'dist/', 'build/', '*.egg-info/',
141
-
142
- # Outros
143
- '*.db-wal', '*.db-shm', '*.sqlite3-journal'
144
- ]
145
-
146
- # Verificar arquivos grandes (>10MB) - NÃO enviar pelo Git normal
147
- try:
148
- file_size = file_path.stat().st_size
149
- if file_size > 10 * 1024 * 1024: # 10MB
150
- # Apenas ignorar se NÃO estivermos usando Git LFS
151
- if not self.config['use_git_lfs']:
152
- return True
153
- except:
154
- pass
155
-
156
- # Verificar cada padrão
157
- for pattern in ignore_patterns:
158
- # Padrão de diretório (termina com /)
159
- if pattern.endswith('/'):
160
- dir_pattern = pattern.rstrip('/')
161
- if rel_str.startswith(dir_pattern + '/') or rel_str == dir_pattern:
162
- return True
163
-
164
- # Padrão com wildcard
165
- elif '*' in pattern:
166
- if fnmatch.fnmatch(rel_str, pattern) or fnmatch.fnmatch(file_name, pattern):
167
- return True
168
-
169
- # Padrão exato
170
- elif pattern == rel_str or pattern == file_name:
171
- return True
172
-
173
- return False
174
-
175
- def setup_git_lfs(self, repo_dir):
176
- """Configura Git LFS para arquivos grandes"""
177
- try:
178
- original_dir = os.getcwd()
179
- os.chdir(repo_dir)
180
-
181
- print("🔧 Configurando Git LFS...")
182
-
183
- # Verificar se Git LFS está instalado
184
- result = subprocess.run(['git', 'lfs', '--version'],
185
- capture_output=True, text=True)
186
-
187
- if result.returncode != 0:
188
- print("⚠️ Git LFS não está instalado. Ignorando arquivos grandes.")
189
- os.chdir(original_dir)
190
- return False
191
-
192
- # Instalar Git LFS no repositório
193
- subprocess.run(['git', 'lfs', 'install'], capture_output=True)
194
-
195
- # Rastrear tipos de arquivo grandes
196
- lfs_patterns = ['*.sqlite3', '*.bin', '*.pickle', '*.pkl',
197
- '*.h5', '*.pt', '*.pth']
198
-
199
- for pattern in lfs_patterns:
200
- subprocess.run(['git', 'lfs', 'track', pattern], capture_output=True)
201
-
202
- # Adicionar .gitattributes
203
- subprocess.run(['git', 'add', '.gitattributes'], capture_output=True)
204
-
205
- print("✅ Git LFS configurado para arquivos grandes")
206
- os.chdir(original_dir)
207
- return True
208
-
209
- except Exception as e:
210
- print(f"⚠️ Erro ao configurar Git LFS: {e}")
211
- os.chdir(original_dir)
212
- return False
213
-
214
- def clone_repo(self, repo_url, target_dir):
215
- """Clona repositório com todas as correções necessárias"""
216
-
217
- try:
218
- os.makedirs(target_dir, exist_ok=True)
219
-
220
- # Primeiro corrigir safe.directory
221
- self.fix_git_safe_directory(target_dir)
222
-
223
- # Comando de clone com todas as correções para Windows
224
- clone_cmd = [
225
- 'git', 'clone',
226
- '--depth', '1',
227
- '--config', 'core.protectNTFS=false',
228
- '--config', 'core.protectHFS=false',
229
- '--config', 'core.autocrlf=false',
230
- repo_url,
231
- target_dir
232
- ]
233
-
234
- print(f" Clonando: {repo_url.split('@')[-1]}")
235
-
236
- result = subprocess.run(clone_cmd, capture_output=True,
237
- text=True, timeout=120)
238
-
239
- if result.returncode == 0:
240
- print("✅ Repositório clonado")
241
-
242
- # Configurar Git LFS se necessário
243
- if self.config['use_git_lfs']:
244
- self.setup_git_lfs(target_dir)
245
-
246
- return True
247
- else:
248
- print(f"⚠️ Clone falhou: {result.stderr[:200]}")
249
-
250
- # Tentar método alternativo
251
- return self.clone_repo_alternative(repo_url, target_dir)
252
-
253
- except subprocess.TimeoutExpired:
254
- print("⚠️ Timeout ao clonar")
255
- return self.clone_repo_alternative(repo_url, target_dir)
256
- except Exception as e:
257
- print(f"⚠️ Erro ao clonar: {e}")
258
- return self.clone_repo_alternative(repo_url, target_dir)
259
-
260
- def clone_repo_alternative(self, repo_url, target_dir):
261
- """Método alternativo para clonar"""
262
- try:
263
- os.makedirs(target_dir, exist_ok=True)
264
-
265
- # Inicializar repositório vazio
266
- subprocess.run(['git', 'init'], cwd=target_dir, capture_output=True)
267
-
268
- # Configurar para Windows
269
- subprocess.run(['git', 'config', 'core.protectNTFS', 'false'],
270
- cwd=target_dir, capture_output=True)
271
- subprocess.run(['git', 'config', 'core.protectHFS', 'false'],
272
- cwd=target_dir, capture_output=True)
273
- subprocess.run(['git', 'config', 'core.autocrlf', 'false'],
274
- cwd=target_dir, capture_output=True)
275
-
276
- # Adicionar remote
277
- subprocess.run(['git', 'remote', 'add', 'origin', repo_url],
278
- cwd=target_dir, capture_output=True)
279
-
280
- # Fazer fetch
281
- result = subprocess.run(['git', 'fetch', 'origin'],
282
- cwd=target_dir, capture_output=True, text=True)
283
-
284
- if result.returncode != 0:
285
- return False
286
-
287
- # Reset para HEAD
288
- subprocess.run(['git', 'reset', '--hard', 'FETCH_HEAD'],
289
- cwd=target_dir, capture_output=True)
290
-
291
- print("✅ Repositório preparado (método alternativo)")
292
- return True
293
-
294
- except Exception as e:
295
- print(f"❌ Método alternativo falhou: {e}")
296
- return False
297
-
298
- def clean_repo(self, repo_dir):
299
- """Limpa repositório completamente"""
300
- original_dir = os.getcwd()
301
-
302
- try:
303
- os.chdir(repo_dir)
304
-
305
- # Remover todos os arquivos trackeados
306
- result = subprocess.run(['git', 'ls-files'],
307
- capture_output=True, text=True)
308
-
309
- if result.returncode == 0 and result.stdout.strip():
310
- files = result.stdout.strip().split('\n')
311
-
312
- for file in files:
313
- if file and not file.startswith('.git/'):
314
- file_path = Path(file)
315
- if file_path.exists():
316
- try:
317
- if file_path.is_file():
318
- file_path.unlink()
319
- elif file_path.is_dir():
320
- shutil.rmtree(file_path, ignore_errors=True)
321
- except:
322
- pass
323
-
324
- print(f"✅ {len(files)} arquivos removidos")
325
-
326
- # Remover arquivos não trackeados
327
- subprocess.run(['git', 'clean', '-fd'], capture_output=True)
328
-
329
- # Remover tudo exceto .git
330
- for item in os.listdir('.'):
331
- if item != '.git':
332
- item_path = Path(item)
333
- try:
334
- if item_path.is_file():
335
- item_path.unlink()
336
- elif item_path.is_dir():
337
- shutil.rmtree(item_path, ignore_errors=True)
338
- except:
339
- pass
340
-
341
- return True
342
-
343
- finally:
344
- os.chdir(original_dir)
345
-
346
- def copy_project_files(self, target_dir):
347
- """Copia arquivos do projeto respeitando regras de ignore"""
348
-
349
- files_copied = 0
350
- total_size = 0
351
- ignored_count = 0
352
- large_files_ignored = 0
353
-
354
- print("\n📋 Analisando arquivos do projeto...")
355
-
356
- for root, dirs, files in os.walk(self.config['project_path']):
357
- # Filtrar diretórios
358
- dirs[:] = [d for d in dirs if not self.should_ignore_file(
359
- Path(root) / d,
360
- Path(d)
361
- )]
362
-
363
- for file in files:
364
- src_path = Path(root) / file
365
- rel_path = src_path.relative_to(self.config['project_path'])
366
-
367
- # Verificar se deve ignorar
368
- if self.should_ignore_file(src_path, rel_path):
369
- ignored_count += 1
370
-
371
- # Verificar se é arquivo grande
372
- try:
373
- if src_path.stat().st_size > 10 * 1024 * 1024:
374
- large_files_ignored += 1
375
- if large_files_ignored <= 5:
376
- size_mb = src_path.stat().st_size / 1024 / 1024
377
- print(f" 🚫 GRANDE ({size_mb:.1f} MB): {rel_path}")
378
- except:
379
- pass
380
-
381
- continue
382
-
383
- dst_path = Path(target_dir) / rel_path
384
- dst_path.parent.mkdir(parents=True, exist_ok=True)
385
-
386
- try:
387
- shutil.copy2(src_path, dst_path)
388
- files_copied += 1
389
- total_size += src_path.stat().st_size
390
- except Exception as e:
391
- print(f"⚠️ Não pôde copiar {rel_path}: {e}")
392
-
393
- print(f"\n📊 Estatísticas:")
394
- print(f" • Arquivos copiados: {files_copied}")
395
- print(f" • Tamanho total: {total_size / 1024 / 1024:.1f} MB")
396
- print(f" • Arquivos ignorados: {ignored_count}")
397
-
398
- if large_files_ignored > 0:
399
- print(f" • Arquivos grandes ignorados (>10MB): {large_files_ignored}")
400
-
401
- if not self.config['use_git_lfs'] and large_files_ignored > 0:
402
- print(f"\n⚠️ ATENÇÃO: {large_files_ignored} arquivos grandes foram ignorados.")
403
- print(" Para incluir arquivos grandes, use Git LFS:")
404
- print(" 1. Adicione HF_USE_GIT_LFS=true ao .env")
405
- print(" 2. Instale Git LFS: https://git-lfs.com/")
406
- print(" 3. Execute novamente")
407
-
408
- return files_copied, total_size
409
-
410
- def force_deploy(self, dry_run=False, skip_confirmation=False):
411
- """Executa o deploy forçado"""
412
-
413
- print("=" * 60)
414
- print("🚀 DEPLOY FORÇADO PARA HUGGING FACE")
415
- print("=" * 60)
416
-
417
- # Configuração
418
- if not self.config['repo_id']:
419
- self.config['repo_id'] = input(
420
- "Digite o nome do Space (usuário/nome-space): "
421
- ).strip()
422
-
423
- if not self.config['token']:
424
- print("🔑 Token não encontrado no .env")
425
- self.config['token'] = input("Digite seu token do Hugging Face: ").strip()
426
-
427
- if not self.config['token'] or not self.config['repo_id']:
428
- print("❌ Token e nome do Space são obrigatórios")
429
- return False
430
-
431
- print(f"\n🎯 Space: {self.config['repo_id']}")
432
- print(f"📁 Projeto: {self.config['project_path']}")
433
-
434
- if self.config['use_git_lfs']:
435
- print("🔧 Modo: Git LFS ativado para arquivos grandes")
436
- else:
437
- print("⚠️ Modo: Arquivos >10MB serão ignorados")
438
-
439
- if not skip_confirmation and not dry_run:
440
- print("\n⚠️ ATENÇÃO: Isso apagará TUDO no Space")
441
- confirm = input("🔴 Continuar? (s/n): ").lower()
442
- if confirm not in ['s', 'sim', 'y', 'yes']:
443
- print("❌ Cancelado")
444
- return False
445
-
446
- # Criar diretório temporário
447
- temp_dir = tempfile.mkdtemp(prefix="hf_deploy_")
448
- self.temp_dirs.append(temp_dir)
449
-
450
- try:
451
- # Clonar repositório
452
- print(f"\n📦 Preparando em: {temp_dir}")
453
- print("\n⬇️ Clonando repositório...")
454
-
455
- repo_url = f"https://user:{self.config['token']}@huggingface.co/spaces/{self.config['repo_id']}"
456
-
457
- if not self.clone_repo(repo_url, temp_dir):
458
- print("❌ Não foi possível clonar")
459
- return False
460
-
461
- # Limpar repositório
462
- print("\n🗑️ Limpando repositório...")
463
- self.clean_repo(temp_dir)
464
-
465
- if dry_run:
466
- print("\n🚀 MODO SIMULAÇÃO")
467
- print("Arquivos que seriam enviados:")
468
- self.list_files_dryrun()
469
- return True
470
-
471
- # Copiar arquivos
472
- print("\n📋 Copiando arquivos...")
473
- files_copied, total_size = self.copy_project_files(temp_dir)
474
-
475
- if files_copied == 0:
476
- print("❌ Nenhum arquivo para copiar")
477
- return False
478
-
479
- # Commit e push
480
- print("\n💾 Commit e push...")
481
- original_dir = os.getcwd()
482
- os.chdir(temp_dir)
483
-
484
- try:
485
- # Adicionar tudo
486
- subprocess.run(['git', 'add', '.'], capture_output=True)
487
-
488
- # Verificar se há mudanças
489
- result = subprocess.run(['git', 'status', '--porcelain'],
490
- capture_output=True, text=True)
491
-
492
- if not result.stdout.strip():
493
- print("⚠️ Nenhuma mudança detectada")
494
- with open('.deploy_marker', 'w') as f:
495
- f.write(f"Deploy: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
496
- subprocess.run(['git', 'add', '.deploy_marker'], capture_output=True)
497
-
498
- # Commit
499
- commit_msg = f'Deploy: {files_copied} arquivos - {time.strftime("%Y-%m-%d %H:%M:%S")}'
500
- subprocess.run(['git', 'commit', '-m', commit_msg],
501
- capture_output=True, text=True)
502
-
503
- print("✅ Commit criado")
504
-
505
- # Push
506
- print("\n⬆️ Enviando...")
507
- push_result = subprocess.run(['git', 'push', 'origin', 'HEAD'],
508
- capture_output=True, text=True, timeout=180)
509
-
510
- if push_result.returncode != 0:
511
- print(f"⚠️ Push falhou: {push_result.stderr[:200]}")
512
-
513
- # Tentar push forçado
514
- print(" Tentando push forçado...")
515
- push_result = subprocess.run(['git', 'push', '--force', 'origin', 'HEAD'],
516
- capture_output=True, text=True, timeout=180)
517
-
518
- if push_result.returncode != 0:
519
- print(f"❌ Push forçado falhou: {push_result.stderr[:200]}")
520
- return False
521
-
522
- print("✅ Push realizado!")
523
-
524
- # Resultado
525
- print("\n" + "=" * 60)
526
- print("✨ DEPLOY CONCLUÍDO!")
527
- print("=" * 60)
528
- print(f"📊 Estatísticas:")
529
- print(f" • Arquivos: {files_copied}")
530
- print(f" • Tamanho: {total_size / 1024 / 1024:.1f} MB")
531
- print(f" • Space: {self.config['repo_id']}")
532
- print(f"🌐 URL: https://huggingface.co/spaces/{self.config['repo_id']}")
533
- print("=" * 60)
534
-
535
- return True
536
-
537
- finally:
538
- os.chdir(original_dir)
539
-
540
- except Exception as e:
541
- print(f"❌ Erro: {e}")
542
- import traceback
543
- traceback.print_exc()
544
- return False
545
-
546
- def list_files_dryrun(self):
547
- """Lista arquivos no modo dry-run"""
548
- files_listed = 0
549
- total_size = 0
550
- ignored_count = 0
551
-
552
- for root, dirs, files in os.walk(self.config['project_path']):
553
- # Filtrar diretórios
554
- dirs[:] = [d for d in dirs if not self.should_ignore_file(
555
- Path(root) / d,
556
- Path(d)
557
- )]
558
-
559
- for file in files:
560
- src_path = Path(root) / file
561
- rel_path = src_path.relative_to(self.config['project_path'])
562
-
563
- if self.should_ignore_file(src_path, rel_path):
564
- ignored_count += 1
565
- continue
566
-
567
- size_kb = src_path.stat().st_size / 1024
568
- total_size += src_path.stat().st_size
569
- files_listed += 1
570
-
571
- if files_listed <= 50:
572
- print(f" 📄 {rel_path} ({size_kb:.1f} KB)")
573
- elif files_listed == 51:
574
- print(f" ... e mais arquivos")
575
-
576
- print(f"\n Total: {files_listed} arquivos ({total_size / 1024 / 1024:.1f} MB)")
577
- print(f" Ignorados: {ignored_count} arquivos")
578
-
579
- def check_dockerfile(self):
580
- """Verifica Dockerfile"""
581
- dockerfile_path = self.config['project_path'] / "Dockerfile"
582
-
583
- if not dockerfile_path.exists():
584
- print(f"❌ Dockerfile não encontrado")
585
- return False
586
-
587
- print(f"✅ Dockerfile: {dockerfile_path}")
588
- return True
589
-
590
-
591
- def main():
592
- parser = argparse.ArgumentParser(
593
- description="Deploy FORÇADO para Hugging Face Spaces"
594
- )
595
- parser.add_argument("--repo", "-r", help="Nome do Space")
596
- parser.add_argument("--project", "-p", help="Caminho do projeto")
597
- parser.add_argument("--token", "-t", help="Token")
598
- parser.add_argument("--dry-run", "-d", action="store_true", help="Modo simulação")
599
- parser.add_argument("--check", "-c", action="store_true", help="Verificar Dockerfile")
600
- parser.add_argument("--yes", "-y", action="store_true", help="Pular confirmações")
601
- parser.add_argument("--lfs", action="store_true", help="Usar Git LFS para arquivos grandes")
602
-
603
- args = parser.parse_args()
604
-
605
- deployer = SimpleHFDeploy()
606
-
607
- # Sobrescrever configurações
608
- if args.repo:
609
- deployer.config['repo_id'] = args.repo
610
- if args.project:
611
- deployer.config['project_path'] = Path(args.project)
612
- if args.token:
613
- deployer.config['token'] = args.token
614
- if args.lfs:
615
- deployer.config['use_git_lfs'] = True
616
-
617
- # Verificar Dockerfile
618
- if args.check or not deployer.check_dockerfile():
619
- if args.check:
620
- sys.exit(0)
621
- else:
622
- print("\n❌ Dockerfile necessário")
623
- sys.exit(1)
624
-
625
- # Executar deploy
626
- success = deployer.force_deploy(
627
- dry_run=args.dry_run,
628
- skip_confirmation=args.yes
629
- )
630
-
631
- sys.exit(0 if success else 1)
632
-
633
-
634
- if __name__ == "__main__":
635
- # Verificar Git
636
- try:
637
- subprocess.run(['git', '--version'], capture_output=True, check=True)
638
- except:
639
- print("❌ Git não está instalado")
640
- sys.exit(1)
641
-
642
- main()
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ huggingface_force_deploy.py - Deploy FORÇADO para Hugging Face Spaces
4
+ Versão FINAL com suporte a arquivos grandes
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import shutil
10
+ import tempfile
11
+ import subprocess
12
+ from pathlib import Path
13
+ from dotenv import load_dotenv
14
+ import argparse
15
+ import time
16
+ import fnmatch
17
+ import atexit
18
+
19
+
20
+ class SimpleHFDeploy:
21
+ def __init__(self):
22
+ self.config = self.load_config()
23
+ self.temp_dirs = []
24
+
25
+ # Registrar limpeza automática
26
+ atexit.register(self.cleanup_temp_dirs)
27
+
28
+ def cleanup_temp_dirs(self):
29
+ """Limpa todos os diretórios temporários"""
30
+ for temp_dir in self.temp_dirs[:]:
31
+ if os.path.exists(temp_dir):
32
+ try:
33
+ self.force_remove_windows(temp_dir)
34
+ self.temp_dirs.remove(temp_dir)
35
+ except:
36
+ pass
37
+
38
+ def force_remove_windows(self, path):
39
+ """Remove arquivos/diretórios no Windows"""
40
+ if not os.path.exists(path):
41
+ return
42
+
43
+ try:
44
+ # Tentar remover normalmente primeiro
45
+ if os.path.isfile(path):
46
+ os.unlink(path)
47
+ else:
48
+ shutil.rmtree(path, ignore_errors=True)
49
+ except:
50
+ # Se falhar, tentar como administrador
51
+ try:
52
+ if sys.platform == 'win32':
53
+ subprocess.run(f'rmdir /S /Q "{path}"', shell=True,
54
+ capture_output=True, timeout=5)
55
+ else:
56
+ subprocess.run(['rm', '-rf', path],
57
+ capture_output=True, timeout=5)
58
+ except:
59
+ pass # Ignorar erros finais
60
+
61
+ def load_config(self):
62
+ """Carrega configurações do .env"""
63
+ config = {
64
+ 'token': None,
65
+ 'repo_id': None,
66
+ 'project_path': None,
67
+ 'use_git_lfs': False # Nova opção para Git LFS
68
+ }
69
+
70
+ # Carregar .env
71
+ env_path = Path.cwd() / ".env"
72
+ if env_path.exists():
73
+ load_dotenv(env_path)
74
+ print(f"🔧 Configurações de: {env_path}")
75
+
76
+ config['token'] = os.getenv("HUGGINGFACE_HUB_TOKEN")
77
+ config['repo_id'] = os.getenv("HF_SPACE_NAME")
78
+
79
+ # Nova configuração para Git LFS
80
+ config['use_git_lfs'] = os.getenv("HF_USE_GIT_LFS", "false").lower() == "true"
81
+
82
+ # Determinar caminho do projeto
83
+ project_path = os.getenv("HF_PROJECT_PATH")
84
+ if project_path:
85
+ config['project_path'] = Path(project_path)
86
+ if not config['project_path'].is_absolute():
87
+ config['project_path'] = Path.cwd() / config['project_path']
88
+ else:
89
+ config['project_path'] = Path.cwd()
90
+
91
+ return config
92
+
93
+ def fix_git_safe_directory(self, repo_dir):
94
+ """Corrige problema de safe.directory do Git no Windows"""
95
+ try:
96
+ # Configurar diretório como seguro
97
+ git_path = str(repo_dir).replace('\\', '/')
98
+ cmd = f'git config --global --add safe.directory "{git_path}"'
99
+
100
+ result = subprocess.run(cmd, shell=True,
101
+ capture_output=True, text=True)
102
+
103
+ if result.returncode == 0:
104
+ print(f"✅ Diretório seguro configurado: {git_path}")
105
+ return True
106
+ else:
107
+ print(f"⚠️ Não foi possível configurar diretório seguro: {result.stderr[:100]}")
108
+ return False
109
+
110
+ except Exception as e:
111
+ print(f"⚠️ Erro ao configurar diretório seguro: {e}")
112
+ return False
113
+
114
+ def should_ignore_file(self, file_path, rel_path):
115
+ """Determina se um arquivo deve ser ignorado baseado em padrões"""
116
+
117
+ # Converter caminho para string Unix-style
118
+ rel_str = str(rel_path).replace('\\', '/')
119
+ file_name = file_path.name
120
+
121
+ # Lista de padrões para IGNORAR
122
+ ignore_patterns = [
123
+ # Sistema e IDE
124
+ '.git', '.gitignore', '.env', '.env.example',
125
+ '.vscode', '.idea', '.DS_Store',
126
+
127
+ # Python
128
+ '__pycache__/', '*.pyc', '*.pyo', '*.pyd',
129
+ 'venv/', '.venv/', 'env/',
130
+
131
+ # Testes e cache
132
+ '.pytest_cache/', '.coverage', 'htmlcov/',
133
+ '*.log', '*.tmp', '*.temp',
134
+
135
+ # Dados temporários/processados
136
+ 'data/processed/', 'data/raw_documents/',
137
+ 'data/temp/', 'data/cache/', 'data/backup/',
138
+
139
+ # Build e distribuição
140
+ 'dist/', 'build/', '*.egg-info/',
141
+
142
+ # Outros
143
+ '*.db-wal', '*.db-shm', '*.sqlite3-journal'
144
+ ]
145
+
146
+ # Verificar arquivos grandes (>10MB) - NÃO enviar pelo Git normal
147
+ try:
148
+ file_size = file_path.stat().st_size
149
+ if file_size > 10 * 1024 * 1024: # 10MB
150
+ # Apenas ignorar se NÃO estivermos usando Git LFS
151
+ if not self.config['use_git_lfs']:
152
+ return True
153
+ except:
154
+ pass
155
+
156
+ # Verificar cada padrão
157
+ for pattern in ignore_patterns:
158
+ # Padrão de diretório (termina com /)
159
+ if pattern.endswith('/'):
160
+ dir_pattern = pattern.rstrip('/')
161
+ if rel_str.startswith(dir_pattern + '/') or rel_str == dir_pattern:
162
+ return True
163
+
164
+ # Padrão com wildcard
165
+ elif '*' in pattern:
166
+ if fnmatch.fnmatch(rel_str, pattern) or fnmatch.fnmatch(file_name, pattern):
167
+ return True
168
+
169
+ # Padrão exato
170
+ elif pattern == rel_str or pattern == file_name:
171
+ return True
172
+
173
+ return False
174
+
175
+ def setup_git_lfs(self, repo_dir):
176
+ """Configura Git LFS para arquivos grandes"""
177
+ try:
178
+ original_dir = os.getcwd()
179
+ os.chdir(repo_dir)
180
+
181
+ print("🔧 Configurando Git LFS...")
182
+
183
+ # Verificar se Git LFS está instalado
184
+ result = subprocess.run(['git', 'lfs', '--version'],
185
+ capture_output=True, text=True)
186
+
187
+ if result.returncode != 0:
188
+ print("⚠️ Git LFS não está instalado. Ignorando arquivos grandes.")
189
+ os.chdir(original_dir)
190
+ return False
191
+
192
+ # Instalar Git LFS no repositório
193
+ subprocess.run(['git', 'lfs', 'install'], capture_output=True)
194
+
195
+ # Rastrear tipos de arquivo grandes
196
+ lfs_patterns = ['*.sqlite3', '*.bin', '*.pickle', '*.pkl',
197
+ '*.h5', '*.pt', '*.pth']
198
+
199
+ for pattern in lfs_patterns:
200
+ subprocess.run(['git', 'lfs', 'track', pattern], capture_output=True)
201
+
202
+ # Adicionar .gitattributes
203
+ subprocess.run(['git', 'add', '.gitattributes'], capture_output=True)
204
+
205
+ print("✅ Git LFS configurado para arquivos grandes")
206
+ os.chdir(original_dir)
207
+ return True
208
+
209
+ except Exception as e:
210
+ print(f"⚠️ Erro ao configurar Git LFS: {e}")
211
+ os.chdir(original_dir)
212
+ return False
213
+
214
+ def clone_repo(self, repo_url, target_dir):
215
+ """Clona repositório com todas as correções necessárias"""
216
+
217
+ try:
218
+ os.makedirs(target_dir, exist_ok=True)
219
+
220
+ # Primeiro corrigir safe.directory
221
+ self.fix_git_safe_directory(target_dir)
222
+
223
+ # Comando de clone com todas as correções para Windows
224
+ clone_cmd = [
225
+ 'git', 'clone',
226
+ '--depth', '1',
227
+ '--config', 'core.protectNTFS=false',
228
+ '--config', 'core.protectHFS=false',
229
+ '--config', 'core.autocrlf=false',
230
+ repo_url,
231
+ target_dir
232
+ ]
233
+
234
+ print(f" Clonando: {repo_url.split('@')[-1]}")
235
+
236
+ result = subprocess.run(clone_cmd, capture_output=True,
237
+ text=True, timeout=120)
238
+
239
+ if result.returncode == 0:
240
+ print("✅ Repositório clonado")
241
+
242
+ # Configurar Git LFS se necessário
243
+ if self.config['use_git_lfs']:
244
+ self.setup_git_lfs(target_dir)
245
+
246
+ return True
247
+ else:
248
+ print(f"⚠️ Clone falhou: {result.stderr[:200]}")
249
+
250
+ # Tentar método alternativo
251
+ return self.clone_repo_alternative(repo_url, target_dir)
252
+
253
+ except subprocess.TimeoutExpired:
254
+ print("⚠️ Timeout ao clonar")
255
+ return self.clone_repo_alternative(repo_url, target_dir)
256
+ except Exception as e:
257
+ print(f"⚠️ Erro ao clonar: {e}")
258
+ return self.clone_repo_alternative(repo_url, target_dir)
259
+
260
+ def clone_repo_alternative(self, repo_url, target_dir):
261
+ """Método alternativo para clonar"""
262
+ try:
263
+ os.makedirs(target_dir, exist_ok=True)
264
+
265
+ # Inicializar repositório vazio
266
+ subprocess.run(['git', 'init'], cwd=target_dir, capture_output=True)
267
+
268
+ # Configurar para Windows
269
+ subprocess.run(['git', 'config', 'core.protectNTFS', 'false'],
270
+ cwd=target_dir, capture_output=True)
271
+ subprocess.run(['git', 'config', 'core.protectHFS', 'false'],
272
+ cwd=target_dir, capture_output=True)
273
+ subprocess.run(['git', 'config', 'core.autocrlf', 'false'],
274
+ cwd=target_dir, capture_output=True)
275
+
276
+ # Adicionar remote
277
+ subprocess.run(['git', 'remote', 'add', 'origin', repo_url],
278
+ cwd=target_dir, capture_output=True)
279
+
280
+ # Fazer fetch
281
+ result = subprocess.run(['git', 'fetch', 'origin'],
282
+ cwd=target_dir, capture_output=True, text=True)
283
+
284
+ if result.returncode != 0:
285
+ return False
286
+
287
+ # Reset para HEAD
288
+ subprocess.run(['git', 'reset', '--hard', 'FETCH_HEAD'],
289
+ cwd=target_dir, capture_output=True)
290
+
291
+ print("✅ Repositório preparado (método alternativo)")
292
+ return True
293
+
294
+ except Exception as e:
295
+ print(f"❌ Método alternativo falhou: {e}")
296
+ return False
297
+
298
+ def clean_repo(self, repo_dir):
299
+ """Limpa repositório completamente"""
300
+ original_dir = os.getcwd()
301
+
302
+ try:
303
+ os.chdir(repo_dir)
304
+
305
+ # Remover todos os arquivos trackeados
306
+ result = subprocess.run(['git', 'ls-files'],
307
+ capture_output=True, text=True)
308
+
309
+ if result.returncode == 0 and result.stdout.strip():
310
+ files = result.stdout.strip().split('\n')
311
+
312
+ for file in files:
313
+ if file and not file.startswith('.git/'):
314
+ file_path = Path(file)
315
+ if file_path.exists():
316
+ try:
317
+ if file_path.is_file():
318
+ file_path.unlink()
319
+ elif file_path.is_dir():
320
+ shutil.rmtree(file_path, ignore_errors=True)
321
+ except:
322
+ pass
323
+
324
+ print(f"✅ {len(files)} arquivos removidos")
325
+
326
+ # Remover arquivos não trackeados
327
+ subprocess.run(['git', 'clean', '-fd'], capture_output=True)
328
+
329
+ # Remover tudo exceto .git
330
+ for item in os.listdir('.'):
331
+ if item != '.git':
332
+ item_path = Path(item)
333
+ try:
334
+ if item_path.is_file():
335
+ item_path.unlink()
336
+ elif item_path.is_dir():
337
+ shutil.rmtree(item_path, ignore_errors=True)
338
+ except:
339
+ pass
340
+
341
+ return True
342
+
343
+ finally:
344
+ os.chdir(original_dir)
345
+
346
+ def copy_project_files(self, target_dir):
347
+ """Copia arquivos do projeto respeitando regras de ignore"""
348
+
349
+ files_copied = 0
350
+ total_size = 0
351
+ ignored_count = 0
352
+ large_files_ignored = 0
353
+
354
+ print("\n📋 Analisando arquivos do projeto...")
355
+
356
+ for root, dirs, files in os.walk(self.config['project_path']):
357
+ # Filtrar diretórios
358
+ dirs[:] = [d for d in dirs if not self.should_ignore_file(
359
+ Path(root) / d,
360
+ Path(d)
361
+ )]
362
+
363
+ for file in files:
364
+ src_path = Path(root) / file
365
+ rel_path = src_path.relative_to(self.config['project_path'])
366
+
367
+ # Verificar se deve ignorar
368
+ if self.should_ignore_file(src_path, rel_path):
369
+ ignored_count += 1
370
+
371
+ # Verificar se é arquivo grande
372
+ try:
373
+ if src_path.stat().st_size > 10 * 1024 * 1024:
374
+ large_files_ignored += 1
375
+ if large_files_ignored <= 5:
376
+ size_mb = src_path.stat().st_size / 1024 / 1024
377
+ print(f" 🚫 GRANDE ({size_mb:.1f} MB): {rel_path}")
378
+ except:
379
+ pass
380
+
381
+ continue
382
+
383
+ dst_path = Path(target_dir) / rel_path
384
+ dst_path.parent.mkdir(parents=True, exist_ok=True)
385
+
386
+ try:
387
+ shutil.copy2(src_path, dst_path)
388
+ files_copied += 1
389
+ total_size += src_path.stat().st_size
390
+ except Exception as e:
391
+ print(f"⚠️ Não pôde copiar {rel_path}: {e}")
392
+
393
+ print(f"\n📊 Estatísticas:")
394
+ print(f" • Arquivos copiados: {files_copied}")
395
+ print(f" • Tamanho total: {total_size / 1024 / 1024:.1f} MB")
396
+ print(f" • Arquivos ignorados: {ignored_count}")
397
+
398
+ if large_files_ignored > 0:
399
+ print(f" • Arquivos grandes ignorados (>10MB): {large_files_ignored}")
400
+
401
+ if not self.config['use_git_lfs'] and large_files_ignored > 0:
402
+ print(f"\n⚠️ ATENÇÃO: {large_files_ignored} arquivos grandes foram ignorados.")
403
+ print(" Para incluir arquivos grandes, use Git LFS:")
404
+ print(" 1. Adicione HF_USE_GIT_LFS=true ao .env")
405
+ print(" 2. Instale Git LFS: https://git-lfs.com/")
406
+ print(" 3. Execute novamente")
407
+
408
+ return files_copied, total_size
409
+
410
+ def force_deploy(self, dry_run=False, skip_confirmation=False):
411
+ """Executa o deploy forçado"""
412
+
413
+ print("=" * 60)
414
+ print("🚀 DEPLOY FORÇADO PARA HUGGING FACE")
415
+ print("=" * 60)
416
+
417
+ # Configuração
418
+ if not self.config['repo_id']:
419
+ self.config['repo_id'] = input(
420
+ "Digite o nome do Space (usuário/nome-space): "
421
+ ).strip()
422
+
423
+ if not self.config['token']:
424
+ print("🔑 Token não encontrado no .env")
425
+ self.config['token'] = input("Digite seu token do Hugging Face: ").strip()
426
+
427
+ if not self.config['token'] or not self.config['repo_id']:
428
+ print("❌ Token e nome do Space são obrigatórios")
429
+ return False
430
+
431
+ print(f"\n🎯 Space: {self.config['repo_id']}")
432
+ print(f"📁 Projeto: {self.config['project_path']}")
433
+
434
+ if self.config['use_git_lfs']:
435
+ print("🔧 Modo: Git LFS ativado para arquivos grandes")
436
+ else:
437
+ print("⚠️ Modo: Arquivos >10MB serão ignorados")
438
+
439
+ if not skip_confirmation and not dry_run:
440
+ print("\n⚠️ ATENÇÃO: Isso apagará TUDO no Space")
441
+ confirm = input("🔴 Continuar? (s/n): ").lower()
442
+ if confirm not in ['s', 'sim', 'y', 'yes']:
443
+ print("❌ Cancelado")
444
+ return False
445
+
446
+ # Criar diretório temporário
447
+ temp_dir = tempfile.mkdtemp(prefix="hf_deploy_")
448
+ self.temp_dirs.append(temp_dir)
449
+
450
+ try:
451
+ # Clonar repositório
452
+ print(f"\n📦 Preparando em: {temp_dir}")
453
+ print("\n⬇️ Clonando repositório...")
454
+
455
+ repo_url = f"https://user:{self.config['token']}@huggingface.co/spaces/{self.config['repo_id']}"
456
+
457
+ if not self.clone_repo(repo_url, temp_dir):
458
+ print("❌ Não foi possível clonar")
459
+ return False
460
+
461
+ # Limpar repositório
462
+ print("\n🗑️ Limpando repositório...")
463
+ self.clean_repo(temp_dir)
464
+
465
+ if dry_run:
466
+ print("\n🚀 MODO SIMULAÇÃO")
467
+ print("Arquivos que seriam enviados:")
468
+ self.list_files_dryrun()
469
+ return True
470
+
471
+ # Copiar arquivos
472
+ print("\n📋 Copiando arquivos...")
473
+ files_copied, total_size = self.copy_project_files(temp_dir)
474
+
475
+ if files_copied == 0:
476
+ print("❌ Nenhum arquivo para copiar")
477
+ return False
478
+
479
+ # Commit e push
480
+ print("\n💾 Commit e push...")
481
+ original_dir = os.getcwd()
482
+ os.chdir(temp_dir)
483
+
484
+ try:
485
+ # Adicionar tudo
486
+ subprocess.run(['git', 'add', '.'], capture_output=True)
487
+
488
+ # Verificar se há mudanças
489
+ result = subprocess.run(['git', 'status', '--porcelain'],
490
+ capture_output=True, text=True)
491
+
492
+ if not result.stdout.strip():
493
+ print("⚠️ Nenhuma mudança detectada")
494
+ with open('.deploy_marker', 'w') as f:
495
+ f.write(f"Deploy: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
496
+ subprocess.run(['git', 'add', '.deploy_marker'], capture_output=True)
497
+
498
+ # Commit
499
+ commit_msg = f'Deploy: {files_copied} arquivos - {time.strftime("%Y-%m-%d %H:%M:%S")}'
500
+ subprocess.run(['git', 'commit', '-m', commit_msg],
501
+ capture_output=True, text=True)
502
+
503
+ print("✅ Commit criado")
504
+
505
+ # Push
506
+ print("\n⬆️ Enviando...")
507
+ push_result = subprocess.run(['git', 'push', 'origin', 'HEAD'],
508
+ capture_output=True, text=True, timeout=180)
509
+
510
+ if push_result.returncode != 0:
511
+ print(f"⚠️ Push falhou: {push_result.stderr[:200]}")
512
+
513
+ # Tentar push forçado
514
+ print(" Tentando push forçado...")
515
+ push_result = subprocess.run(['git', 'push', '--force', 'origin', 'HEAD'],
516
+ capture_output=True, text=True, timeout=180)
517
+
518
+ if push_result.returncode != 0:
519
+ print(f"❌ Push forçado falhou: {push_result.stderr[:200]}")
520
+ return False
521
+
522
+ print("✅ Push realizado!")
523
+
524
+ # Resultado
525
+ print("\n" + "=" * 60)
526
+ print("✨ DEPLOY CONCLUÍDO!")
527
+ print("=" * 60)
528
+ print(f"📊 Estatísticas:")
529
+ print(f" • Arquivos: {files_copied}")
530
+ print(f" • Tamanho: {total_size / 1024 / 1024:.1f} MB")
531
+ print(f" • Space: {self.config['repo_id']}")
532
+ print(f"🌐 URL: https://huggingface.co/spaces/{self.config['repo_id']}")
533
+ print("=" * 60)
534
+
535
+ return True
536
+
537
+ finally:
538
+ os.chdir(original_dir)
539
+
540
+ except Exception as e:
541
+ print(f"❌ Erro: {e}")
542
+ import traceback
543
+ traceback.print_exc()
544
+ return False
545
+
546
+ def list_files_dryrun(self):
547
+ """Lista arquivos no modo dry-run"""
548
+ files_listed = 0
549
+ total_size = 0
550
+ ignored_count = 0
551
+
552
+ for root, dirs, files in os.walk(self.config['project_path']):
553
+ # Filtrar diretórios
554
+ dirs[:] = [d for d in dirs if not self.should_ignore_file(
555
+ Path(root) / d,
556
+ Path(d)
557
+ )]
558
+
559
+ for file in files:
560
+ src_path = Path(root) / file
561
+ rel_path = src_path.relative_to(self.config['project_path'])
562
+
563
+ if self.should_ignore_file(src_path, rel_path):
564
+ ignored_count += 1
565
+ continue
566
+
567
+ size_kb = src_path.stat().st_size / 1024
568
+ total_size += src_path.stat().st_size
569
+ files_listed += 1
570
+
571
+ if files_listed <= 50:
572
+ print(f" 📄 {rel_path} ({size_kb:.1f} KB)")
573
+ elif files_listed == 51:
574
+ print(f" ... e mais arquivos")
575
+
576
+ print(f"\n Total: {files_listed} arquivos ({total_size / 1024 / 1024:.1f} MB)")
577
+ print(f" Ignorados: {ignored_count} arquivos")
578
+
579
+ def check_prerequisites(self):
580
+ """Verifica arquivos obrigatórios (Dockerfile e requirements.txt)"""
581
+ dockerfile_path = self.config['project_path'] / "Dockerfile"
582
+ req_path = self.config['project_path'] / "requirements.txt"
583
+
584
+ missing = []
585
+ if not dockerfile_path.exists():
586
+ missing.append("Dockerfile")
587
+ if not req_path.exists():
588
+ missing.append("requirements.txt")
589
+
590
+ if missing:
591
+ print(f"❌ Arquivos obrigatórios faltando: {', '.join(missing)}")
592
+ return False
593
+
594
+ print(f"✅ Pré-requisitos encontrados: Dockerfile e requirements.txt")
595
+ return True
596
+
597
+
598
+ def main():
599
+ parser = argparse.ArgumentParser(
600
+ description="Deploy FORÇADO para Hugging Face Spaces"
601
+ )
602
+ parser.add_argument("--repo", "-r", help="Nome do Space")
603
+ parser.add_argument("--project", "-p", help="Caminho do projeto")
604
+ parser.add_argument("--token", "-t", help="Token")
605
+ parser.add_argument("--dry-run", "-d", action="store_true", help="Modo simulação")
606
+ parser.add_argument("--check", "-c", action="store_true", help="Verificar Dockerfile")
607
+ parser.add_argument("--yes", "-y", action="store_true", help="Pular confirmações")
608
+ parser.add_argument("--lfs", action="store_true", help="Usar Git LFS para arquivos grandes")
609
+
610
+ args = parser.parse_args()
611
+
612
+ deployer = SimpleHFDeploy()
613
+
614
+ # Sobrescrever configurações
615
+ if args.repo:
616
+ deployer.config['repo_id'] = args.repo
617
+ if args.project:
618
+ deployer.config['project_path'] = Path(args.project)
619
+ if args.token:
620
+ deployer.config['token'] = args.token
621
+ if args.lfs:
622
+ deployer.config['use_git_lfs'] = True
623
+
624
+ # Verificar Pré-requisitos
625
+ if args.check or not deployer.check_prerequisites():
626
+ if args.check:
627
+ sys.exit(0)
628
+ else:
629
+ print("\n❌ Arquivos de configuração necessários")
630
+ sys.exit(1)
631
+
632
+ # Executar deploy
633
+ success = deployer.force_deploy(
634
+ dry_run=args.dry_run,
635
+ skip_confirmation=args.yes
636
+ )
637
+
638
+ sys.exit(0 if success else 1)
639
+
640
+
641
+ if __name__ == "__main__":
642
+ # Verificar Git
643
+ try:
644
+ subprocess.run(['git', '--version'], capture_output=True, check=True)
645
+ except:
646
+ print("❌ Git não está instalado")
647
+ sys.exit(1)
648
+
649
+ main()
scripts//hugging_face_deploy.py CHANGED
@@ -1,642 +1,649 @@
1
- #!/usr/bin/env python3
2
- """
3
- huggingface_force_deploy.py - Deploy FORÇADO para Hugging Face Spaces
4
- Versão FINAL com suporte a arquivos grandes
5
- """
6
-
7
- import os
8
- import sys
9
- import shutil
10
- import tempfile
11
- import subprocess
12
- from pathlib import Path
13
- from dotenv import load_dotenv
14
- import argparse
15
- import time
16
- import fnmatch
17
- import atexit
18
-
19
-
20
- class SimpleHFDeploy:
21
- def __init__(self):
22
- self.config = self.load_config()
23
- self.temp_dirs = []
24
-
25
- # Registrar limpeza automática
26
- atexit.register(self.cleanup_temp_dirs)
27
-
28
- def cleanup_temp_dirs(self):
29
- """Limpa todos os diretórios temporários"""
30
- for temp_dir in self.temp_dirs[:]:
31
- if os.path.exists(temp_dir):
32
- try:
33
- self.force_remove_windows(temp_dir)
34
- self.temp_dirs.remove(temp_dir)
35
- except:
36
- pass
37
-
38
- def force_remove_windows(self, path):
39
- """Remove arquivos/diretórios no Windows"""
40
- if not os.path.exists(path):
41
- return
42
-
43
- try:
44
- # Tentar remover normalmente primeiro
45
- if os.path.isfile(path):
46
- os.unlink(path)
47
- else:
48
- shutil.rmtree(path, ignore_errors=True)
49
- except:
50
- # Se falhar, tentar como administrador
51
- try:
52
- if sys.platform == 'win32':
53
- subprocess.run(f'rmdir /S /Q "{path}"', shell=True,
54
- capture_output=True, timeout=5)
55
- else:
56
- subprocess.run(['rm', '-rf', path],
57
- capture_output=True, timeout=5)
58
- except:
59
- pass # Ignorar erros finais
60
-
61
- def load_config(self):
62
- """Carrega configurações do .env"""
63
- config = {
64
- 'token': None,
65
- 'repo_id': None,
66
- 'project_path': None,
67
- 'use_git_lfs': False # Nova opção para Git LFS
68
- }
69
-
70
- # Carregar .env
71
- env_path = Path.cwd() / ".env"
72
- if env_path.exists():
73
- load_dotenv(env_path)
74
- print(f"🔧 Configurações de: {env_path}")
75
-
76
- config['token'] = os.getenv("HUGGINGFACE_HUB_TOKEN")
77
- config['repo_id'] = os.getenv("HF_SPACE_NAME")
78
-
79
- # Nova configuração para Git LFS
80
- config['use_git_lfs'] = os.getenv("HF_USE_GIT_LFS", "false").lower() == "true"
81
-
82
- # Determinar caminho do projeto
83
- project_path = os.getenv("HF_PROJECT_PATH")
84
- if project_path:
85
- config['project_path'] = Path(project_path)
86
- if not config['project_path'].is_absolute():
87
- config['project_path'] = Path.cwd() / config['project_path']
88
- else:
89
- config['project_path'] = Path.cwd()
90
-
91
- return config
92
-
93
- def fix_git_safe_directory(self, repo_dir):
94
- """Corrige problema de safe.directory do Git no Windows"""
95
- try:
96
- # Configurar diretório como seguro
97
- git_path = str(repo_dir).replace('\\', '/')
98
- cmd = f'git config --global --add safe.directory "{git_path}"'
99
-
100
- result = subprocess.run(cmd, shell=True,
101
- capture_output=True, text=True)
102
-
103
- if result.returncode == 0:
104
- print(f"✅ Diretório seguro configurado: {git_path}")
105
- return True
106
- else:
107
- print(f"⚠️ Não foi possível configurar diretório seguro: {result.stderr[:100]}")
108
- return False
109
-
110
- except Exception as e:
111
- print(f"⚠️ Erro ao configurar diretório seguro: {e}")
112
- return False
113
-
114
- def should_ignore_file(self, file_path, rel_path):
115
- """Determina se um arquivo deve ser ignorado baseado em padrões"""
116
-
117
- # Converter caminho para string Unix-style
118
- rel_str = str(rel_path).replace('\\', '/')
119
- file_name = file_path.name
120
-
121
- # Lista de padrões para IGNORAR
122
- ignore_patterns = [
123
- # Sistema e IDE
124
- '.git', '.gitignore', '.env', '.env.example',
125
- '.vscode', '.idea', '.DS_Store',
126
-
127
- # Python
128
- '__pycache__/', '*.pyc', '*.pyo', '*.pyd',
129
- 'venv/', '.venv/', 'env/',
130
-
131
- # Testes e cache
132
- '.pytest_cache/', '.coverage', 'htmlcov/',
133
- '*.log', '*.tmp', '*.temp',
134
-
135
- # Dados temporários/processados
136
- 'data/processed/', 'data/raw_documents/',
137
- 'data/temp/', 'data/cache/', 'data/backup/',
138
-
139
- # Build e distribuição
140
- 'dist/', 'build/', '*.egg-info/',
141
-
142
- # Outros
143
- '*.db-wal', '*.db-shm', '*.sqlite3-journal'
144
- ]
145
-
146
- # Verificar arquivos grandes (>10MB) - NÃO enviar pelo Git normal
147
- try:
148
- file_size = file_path.stat().st_size
149
- if file_size > 10 * 1024 * 1024: # 10MB
150
- # Apenas ignorar se NÃO estivermos usando Git LFS
151
- if not self.config['use_git_lfs']:
152
- return True
153
- except:
154
- pass
155
-
156
- # Verificar cada padrão
157
- for pattern in ignore_patterns:
158
- # Padrão de diretório (termina com /)
159
- if pattern.endswith('/'):
160
- dir_pattern = pattern.rstrip('/')
161
- if rel_str.startswith(dir_pattern + '/') or rel_str == dir_pattern:
162
- return True
163
-
164
- # Padrão com wildcard
165
- elif '*' in pattern:
166
- if fnmatch.fnmatch(rel_str, pattern) or fnmatch.fnmatch(file_name, pattern):
167
- return True
168
-
169
- # Padrão exato
170
- elif pattern == rel_str or pattern == file_name:
171
- return True
172
-
173
- return False
174
-
175
- def setup_git_lfs(self, repo_dir):
176
- """Configura Git LFS para arquivos grandes"""
177
- try:
178
- original_dir = os.getcwd()
179
- os.chdir(repo_dir)
180
-
181
- print("🔧 Configurando Git LFS...")
182
-
183
- # Verificar se Git LFS está instalado
184
- result = subprocess.run(['git', 'lfs', '--version'],
185
- capture_output=True, text=True)
186
-
187
- if result.returncode != 0:
188
- print("⚠️ Git LFS não está instalado. Ignorando arquivos grandes.")
189
- os.chdir(original_dir)
190
- return False
191
-
192
- # Instalar Git LFS no repositório
193
- subprocess.run(['git', 'lfs', 'install'], capture_output=True)
194
-
195
- # Rastrear tipos de arquivo grandes
196
- lfs_patterns = ['*.sqlite3', '*.bin', '*.pickle', '*.pkl',
197
- '*.h5', '*.pt', '*.pth']
198
-
199
- for pattern in lfs_patterns:
200
- subprocess.run(['git', 'lfs', 'track', pattern], capture_output=True)
201
-
202
- # Adicionar .gitattributes
203
- subprocess.run(['git', 'add', '.gitattributes'], capture_output=True)
204
-
205
- print("✅ Git LFS configurado para arquivos grandes")
206
- os.chdir(original_dir)
207
- return True
208
-
209
- except Exception as e:
210
- print(f"⚠️ Erro ao configurar Git LFS: {e}")
211
- os.chdir(original_dir)
212
- return False
213
-
214
- def clone_repo(self, repo_url, target_dir):
215
- """Clona repositório com todas as correções necessárias"""
216
-
217
- try:
218
- os.makedirs(target_dir, exist_ok=True)
219
-
220
- # Primeiro corrigir safe.directory
221
- self.fix_git_safe_directory(target_dir)
222
-
223
- # Comando de clone com todas as correções para Windows
224
- clone_cmd = [
225
- 'git', 'clone',
226
- '--depth', '1',
227
- '--config', 'core.protectNTFS=false',
228
- '--config', 'core.protectHFS=false',
229
- '--config', 'core.autocrlf=false',
230
- repo_url,
231
- target_dir
232
- ]
233
-
234
- print(f" Clonando: {repo_url.split('@')[-1]}")
235
-
236
- result = subprocess.run(clone_cmd, capture_output=True,
237
- text=True, timeout=120)
238
-
239
- if result.returncode == 0:
240
- print("✅ Repositório clonado")
241
-
242
- # Configurar Git LFS se necessário
243
- if self.config['use_git_lfs']:
244
- self.setup_git_lfs(target_dir)
245
-
246
- return True
247
- else:
248
- print(f"⚠️ Clone falhou: {result.stderr[:200]}")
249
-
250
- # Tentar método alternativo
251
- return self.clone_repo_alternative(repo_url, target_dir)
252
-
253
- except subprocess.TimeoutExpired:
254
- print("⚠️ Timeout ao clonar")
255
- return self.clone_repo_alternative(repo_url, target_dir)
256
- except Exception as e:
257
- print(f"⚠️ Erro ao clonar: {e}")
258
- return self.clone_repo_alternative(repo_url, target_dir)
259
-
260
- def clone_repo_alternative(self, repo_url, target_dir):
261
- """Método alternativo para clonar"""
262
- try:
263
- os.makedirs(target_dir, exist_ok=True)
264
-
265
- # Inicializar repositório vazio
266
- subprocess.run(['git', 'init'], cwd=target_dir, capture_output=True)
267
-
268
- # Configurar para Windows
269
- subprocess.run(['git', 'config', 'core.protectNTFS', 'false'],
270
- cwd=target_dir, capture_output=True)
271
- subprocess.run(['git', 'config', 'core.protectHFS', 'false'],
272
- cwd=target_dir, capture_output=True)
273
- subprocess.run(['git', 'config', 'core.autocrlf', 'false'],
274
- cwd=target_dir, capture_output=True)
275
-
276
- # Adicionar remote
277
- subprocess.run(['git', 'remote', 'add', 'origin', repo_url],
278
- cwd=target_dir, capture_output=True)
279
-
280
- # Fazer fetch
281
- result = subprocess.run(['git', 'fetch', 'origin'],
282
- cwd=target_dir, capture_output=True, text=True)
283
-
284
- if result.returncode != 0:
285
- return False
286
-
287
- # Reset para HEAD
288
- subprocess.run(['git', 'reset', '--hard', 'FETCH_HEAD'],
289
- cwd=target_dir, capture_output=True)
290
-
291
- print("✅ Repositório preparado (método alternativo)")
292
- return True
293
-
294
- except Exception as e:
295
- print(f"❌ Método alternativo falhou: {e}")
296
- return False
297
-
298
- def clean_repo(self, repo_dir):
299
- """Limpa repositório completamente"""
300
- original_dir = os.getcwd()
301
-
302
- try:
303
- os.chdir(repo_dir)
304
-
305
- # Remover todos os arquivos trackeados
306
- result = subprocess.run(['git', 'ls-files'],
307
- capture_output=True, text=True)
308
-
309
- if result.returncode == 0 and result.stdout.strip():
310
- files = result.stdout.strip().split('\n')
311
-
312
- for file in files:
313
- if file and not file.startswith('.git/'):
314
- file_path = Path(file)
315
- if file_path.exists():
316
- try:
317
- if file_path.is_file():
318
- file_path.unlink()
319
- elif file_path.is_dir():
320
- shutil.rmtree(file_path, ignore_errors=True)
321
- except:
322
- pass
323
-
324
- print(f"✅ {len(files)} arquivos removidos")
325
-
326
- # Remover arquivos não trackeados
327
- subprocess.run(['git', 'clean', '-fd'], capture_output=True)
328
-
329
- # Remover tudo exceto .git
330
- for item in os.listdir('.'):
331
- if item != '.git':
332
- item_path = Path(item)
333
- try:
334
- if item_path.is_file():
335
- item_path.unlink()
336
- elif item_path.is_dir():
337
- shutil.rmtree(item_path, ignore_errors=True)
338
- except:
339
- pass
340
-
341
- return True
342
-
343
- finally:
344
- os.chdir(original_dir)
345
-
346
- def copy_project_files(self, target_dir):
347
- """Copia arquivos do projeto respeitando regras de ignore"""
348
-
349
- files_copied = 0
350
- total_size = 0
351
- ignored_count = 0
352
- large_files_ignored = 0
353
-
354
- print("\n📋 Analisando arquivos do projeto...")
355
-
356
- for root, dirs, files in os.walk(self.config['project_path']):
357
- # Filtrar diretórios
358
- dirs[:] = [d for d in dirs if not self.should_ignore_file(
359
- Path(root) / d,
360
- Path(d)
361
- )]
362
-
363
- for file in files:
364
- src_path = Path(root) / file
365
- rel_path = src_path.relative_to(self.config['project_path'])
366
-
367
- # Verificar se deve ignorar
368
- if self.should_ignore_file(src_path, rel_path):
369
- ignored_count += 1
370
-
371
- # Verificar se é arquivo grande
372
- try:
373
- if src_path.stat().st_size > 10 * 1024 * 1024:
374
- large_files_ignored += 1
375
- if large_files_ignored <= 5:
376
- size_mb = src_path.stat().st_size / 1024 / 1024
377
- print(f" 🚫 GRANDE ({size_mb:.1f} MB): {rel_path}")
378
- except:
379
- pass
380
-
381
- continue
382
-
383
- dst_path = Path(target_dir) / rel_path
384
- dst_path.parent.mkdir(parents=True, exist_ok=True)
385
-
386
- try:
387
- shutil.copy2(src_path, dst_path)
388
- files_copied += 1
389
- total_size += src_path.stat().st_size
390
- except Exception as e:
391
- print(f"⚠️ Não pôde copiar {rel_path}: {e}")
392
-
393
- print(f"\n📊 Estatísticas:")
394
- print(f" • Arquivos copiados: {files_copied}")
395
- print(f" • Tamanho total: {total_size / 1024 / 1024:.1f} MB")
396
- print(f" • Arquivos ignorados: {ignored_count}")
397
-
398
- if large_files_ignored > 0:
399
- print(f" • Arquivos grandes ignorados (>10MB): {large_files_ignored}")
400
-
401
- if not self.config['use_git_lfs'] and large_files_ignored > 0:
402
- print(f"\n⚠️ ATENÇÃO: {large_files_ignored} arquivos grandes foram ignorados.")
403
- print(" Para incluir arquivos grandes, use Git LFS:")
404
- print(" 1. Adicione HF_USE_GIT_LFS=true ao .env")
405
- print(" 2. Instale Git LFS: https://git-lfs.com/")
406
- print(" 3. Execute novamente")
407
-
408
- return files_copied, total_size
409
-
410
- def force_deploy(self, dry_run=False, skip_confirmation=False):
411
- """Executa o deploy forçado"""
412
-
413
- print("=" * 60)
414
- print("🚀 DEPLOY FORÇADO PARA HUGGING FACE")
415
- print("=" * 60)
416
-
417
- # Configuração
418
- if not self.config['repo_id']:
419
- self.config['repo_id'] = input(
420
- "Digite o nome do Space (usuário/nome-space): "
421
- ).strip()
422
-
423
- if not self.config['token']:
424
- print("🔑 Token não encontrado no .env")
425
- self.config['token'] = input("Digite seu token do Hugging Face: ").strip()
426
-
427
- if not self.config['token'] or not self.config['repo_id']:
428
- print("❌ Token e nome do Space são obrigatórios")
429
- return False
430
-
431
- print(f"\n🎯 Space: {self.config['repo_id']}")
432
- print(f"📁 Projeto: {self.config['project_path']}")
433
-
434
- if self.config['use_git_lfs']:
435
- print("🔧 Modo: Git LFS ativado para arquivos grandes")
436
- else:
437
- print("⚠️ Modo: Arquivos >10MB serão ignorados")
438
-
439
- if not skip_confirmation and not dry_run:
440
- print("\n⚠️ ATENÇÃO: Isso apagará TUDO no Space")
441
- confirm = input("🔴 Continuar? (s/n): ").lower()
442
- if confirm not in ['s', 'sim', 'y', 'yes']:
443
- print("❌ Cancelado")
444
- return False
445
-
446
- # Criar diretório temporário
447
- temp_dir = tempfile.mkdtemp(prefix="hf_deploy_")
448
- self.temp_dirs.append(temp_dir)
449
-
450
- try:
451
- # Clonar repositório
452
- print(f"\n📦 Preparando em: {temp_dir}")
453
- print("\n⬇️ Clonando repositório...")
454
-
455
- repo_url = f"https://user:{self.config['token']}@huggingface.co/spaces/{self.config['repo_id']}"
456
-
457
- if not self.clone_repo(repo_url, temp_dir):
458
- print("❌ Não foi possível clonar")
459
- return False
460
-
461
- # Limpar repositório
462
- print("\n🗑️ Limpando repositório...")
463
- self.clean_repo(temp_dir)
464
-
465
- if dry_run:
466
- print("\n🚀 MODO SIMULAÇÃO")
467
- print("Arquivos que seriam enviados:")
468
- self.list_files_dryrun()
469
- return True
470
-
471
- # Copiar arquivos
472
- print("\n📋 Copiando arquivos...")
473
- files_copied, total_size = self.copy_project_files(temp_dir)
474
-
475
- if files_copied == 0:
476
- print("❌ Nenhum arquivo para copiar")
477
- return False
478
-
479
- # Commit e push
480
- print("\n💾 Commit e push...")
481
- original_dir = os.getcwd()
482
- os.chdir(temp_dir)
483
-
484
- try:
485
- # Adicionar tudo
486
- subprocess.run(['git', 'add', '.'], capture_output=True)
487
-
488
- # Verificar se há mudanças
489
- result = subprocess.run(['git', 'status', '--porcelain'],
490
- capture_output=True, text=True)
491
-
492
- if not result.stdout.strip():
493
- print("⚠️ Nenhuma mudança detectada")
494
- with open('.deploy_marker', 'w') as f:
495
- f.write(f"Deploy: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
496
- subprocess.run(['git', 'add', '.deploy_marker'], capture_output=True)
497
-
498
- # Commit
499
- commit_msg = f'Deploy: {files_copied} arquivos - {time.strftime("%Y-%m-%d %H:%M:%S")}'
500
- subprocess.run(['git', 'commit', '-m', commit_msg],
501
- capture_output=True, text=True)
502
-
503
- print("✅ Commit criado")
504
-
505
- # Push
506
- print("\n⬆️ Enviando...")
507
- push_result = subprocess.run(['git', 'push', 'origin', 'HEAD'],
508
- capture_output=True, text=True, timeout=180)
509
-
510
- if push_result.returncode != 0:
511
- print(f"⚠️ Push falhou: {push_result.stderr[:200]}")
512
-
513
- # Tentar push forçado
514
- print(" Tentando push forçado...")
515
- push_result = subprocess.run(['git', 'push', '--force', 'origin', 'HEAD'],
516
- capture_output=True, text=True, timeout=180)
517
-
518
- if push_result.returncode != 0:
519
- print(f"❌ Push forçado falhou: {push_result.stderr[:200]}")
520
- return False
521
-
522
- print("✅ Push realizado!")
523
-
524
- # Resultado
525
- print("\n" + "=" * 60)
526
- print("✨ DEPLOY CONCLUÍDO!")
527
- print("=" * 60)
528
- print(f"📊 Estatísticas:")
529
- print(f" • Arquivos: {files_copied}")
530
- print(f" • Tamanho: {total_size / 1024 / 1024:.1f} MB")
531
- print(f" • Space: {self.config['repo_id']}")
532
- print(f"🌐 URL: https://huggingface.co/spaces/{self.config['repo_id']}")
533
- print("=" * 60)
534
-
535
- return True
536
-
537
- finally:
538
- os.chdir(original_dir)
539
-
540
- except Exception as e:
541
- print(f"❌ Erro: {e}")
542
- import traceback
543
- traceback.print_exc()
544
- return False
545
-
546
- def list_files_dryrun(self):
547
- """Lista arquivos no modo dry-run"""
548
- files_listed = 0
549
- total_size = 0
550
- ignored_count = 0
551
-
552
- for root, dirs, files in os.walk(self.config['project_path']):
553
- # Filtrar diretórios
554
- dirs[:] = [d for d in dirs if not self.should_ignore_file(
555
- Path(root) / d,
556
- Path(d)
557
- )]
558
-
559
- for file in files:
560
- src_path = Path(root) / file
561
- rel_path = src_path.relative_to(self.config['project_path'])
562
-
563
- if self.should_ignore_file(src_path, rel_path):
564
- ignored_count += 1
565
- continue
566
-
567
- size_kb = src_path.stat().st_size / 1024
568
- total_size += src_path.stat().st_size
569
- files_listed += 1
570
-
571
- if files_listed <= 50:
572
- print(f" 📄 {rel_path} ({size_kb:.1f} KB)")
573
- elif files_listed == 51:
574
- print(f" ... e mais arquivos")
575
-
576
- print(f"\n Total: {files_listed} arquivos ({total_size / 1024 / 1024:.1f} MB)")
577
- print(f" Ignorados: {ignored_count} arquivos")
578
-
579
- def check_dockerfile(self):
580
- """Verifica Dockerfile"""
581
- dockerfile_path = self.config['project_path'] / "Dockerfile"
582
-
583
- if not dockerfile_path.exists():
584
- print(f"❌ Dockerfile não encontrado")
585
- return False
586
-
587
- print(f"✅ Dockerfile: {dockerfile_path}")
588
- return True
589
-
590
-
591
- def main():
592
- parser = argparse.ArgumentParser(
593
- description="Deploy FORÇADO para Hugging Face Spaces"
594
- )
595
- parser.add_argument("--repo", "-r", help="Nome do Space")
596
- parser.add_argument("--project", "-p", help="Caminho do projeto")
597
- parser.add_argument("--token", "-t", help="Token")
598
- parser.add_argument("--dry-run", "-d", action="store_true", help="Modo simulação")
599
- parser.add_argument("--check", "-c", action="store_true", help="Verificar Dockerfile")
600
- parser.add_argument("--yes", "-y", action="store_true", help="Pular confirmações")
601
- parser.add_argument("--lfs", action="store_true", help="Usar Git LFS para arquivos grandes")
602
-
603
- args = parser.parse_args()
604
-
605
- deployer = SimpleHFDeploy()
606
-
607
- # Sobrescrever configurações
608
- if args.repo:
609
- deployer.config['repo_id'] = args.repo
610
- if args.project:
611
- deployer.config['project_path'] = Path(args.project)
612
- if args.token:
613
- deployer.config['token'] = args.token
614
- if args.lfs:
615
- deployer.config['use_git_lfs'] = True
616
-
617
- # Verificar Dockerfile
618
- if args.check or not deployer.check_dockerfile():
619
- if args.check:
620
- sys.exit(0)
621
- else:
622
- print("\n❌ Dockerfile necessário")
623
- sys.exit(1)
624
-
625
- # Executar deploy
626
- success = deployer.force_deploy(
627
- dry_run=args.dry_run,
628
- skip_confirmation=args.yes
629
- )
630
-
631
- sys.exit(0 if success else 1)
632
-
633
-
634
- if __name__ == "__main__":
635
- # Verificar Git
636
- try:
637
- subprocess.run(['git', '--version'], capture_output=True, check=True)
638
- except:
639
- print("❌ Git não está instalado")
640
- sys.exit(1)
641
-
642
- main()
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ huggingface_force_deploy.py - Deploy FORÇADO para Hugging Face Spaces
4
+ Versão FINAL com suporte a arquivos grandes
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import shutil
10
+ import tempfile
11
+ import subprocess
12
+ from pathlib import Path
13
+ from dotenv import load_dotenv
14
+ import argparse
15
+ import time
16
+ import fnmatch
17
+ import atexit
18
+
19
+
20
+ class SimpleHFDeploy:
21
+ def __init__(self):
22
+ self.config = self.load_config()
23
+ self.temp_dirs = []
24
+
25
+ # Registrar limpeza automática
26
+ atexit.register(self.cleanup_temp_dirs)
27
+
28
+ def cleanup_temp_dirs(self):
29
+ """Limpa todos os diretórios temporários"""
30
+ for temp_dir in self.temp_dirs[:]:
31
+ if os.path.exists(temp_dir):
32
+ try:
33
+ self.force_remove_windows(temp_dir)
34
+ self.temp_dirs.remove(temp_dir)
35
+ except:
36
+ pass
37
+
38
+ def force_remove_windows(self, path):
39
+ """Remove arquivos/diretórios no Windows"""
40
+ if not os.path.exists(path):
41
+ return
42
+
43
+ try:
44
+ # Tentar remover normalmente primeiro
45
+ if os.path.isfile(path):
46
+ os.unlink(path)
47
+ else:
48
+ shutil.rmtree(path, ignore_errors=True)
49
+ except:
50
+ # Se falhar, tentar como administrador
51
+ try:
52
+ if sys.platform == 'win32':
53
+ subprocess.run(f'rmdir /S /Q "{path}"', shell=True,
54
+ capture_output=True, timeout=5)
55
+ else:
56
+ subprocess.run(['rm', '-rf', path],
57
+ capture_output=True, timeout=5)
58
+ except:
59
+ pass # Ignorar erros finais
60
+
61
+ def load_config(self):
62
+ """Carrega configurações do .env"""
63
+ config = {
64
+ 'token': None,
65
+ 'repo_id': None,
66
+ 'project_path': None,
67
+ 'use_git_lfs': False # Nova opção para Git LFS
68
+ }
69
+
70
+ # Carregar .env
71
+ env_path = Path.cwd() / ".env"
72
+ if env_path.exists():
73
+ load_dotenv(env_path)
74
+ print(f"🔧 Configurações de: {env_path}")
75
+
76
+ config['token'] = os.getenv("HUGGINGFACE_HUB_TOKEN")
77
+ config['repo_id'] = os.getenv("HF_SPACE_NAME")
78
+
79
+ # Nova configuração para Git LFS
80
+ config['use_git_lfs'] = os.getenv("HF_USE_GIT_LFS", "false").lower() == "true"
81
+
82
+ # Determinar caminho do projeto
83
+ project_path = os.getenv("HF_PROJECT_PATH")
84
+ if project_path:
85
+ config['project_path'] = Path(project_path)
86
+ if not config['project_path'].is_absolute():
87
+ config['project_path'] = Path.cwd() / config['project_path']
88
+ else:
89
+ config['project_path'] = Path.cwd()
90
+
91
+ return config
92
+
93
+ def fix_git_safe_directory(self, repo_dir):
94
+ """Corrige problema de safe.directory do Git no Windows"""
95
+ try:
96
+ # Configurar diretório como seguro
97
+ git_path = str(repo_dir).replace('\\', '/')
98
+ cmd = f'git config --global --add safe.directory "{git_path}"'
99
+
100
+ result = subprocess.run(cmd, shell=True,
101
+ capture_output=True, text=True)
102
+
103
+ if result.returncode == 0:
104
+ print(f"✅ Diretório seguro configurado: {git_path}")
105
+ return True
106
+ else:
107
+ print(f"⚠️ Não foi possível configurar diretório seguro: {result.stderr[:100]}")
108
+ return False
109
+
110
+ except Exception as e:
111
+ print(f"⚠️ Erro ao configurar diretório seguro: {e}")
112
+ return False
113
+
114
+ def should_ignore_file(self, file_path, rel_path):
115
+ """Determina se um arquivo deve ser ignorado baseado em padrões"""
116
+
117
+ # Converter caminho para string Unix-style
118
+ rel_str = str(rel_path).replace('\\', '/')
119
+ file_name = file_path.name
120
+
121
+ # Lista de padrões para IGNORAR
122
+ ignore_patterns = [
123
+ # Sistema e IDE
124
+ '.git', '.gitignore', '.env', '.env.example',
125
+ '.vscode', '.idea', '.DS_Store',
126
+
127
+ # Python
128
+ '__pycache__/', '*.pyc', '*.pyo', '*.pyd',
129
+ 'venv/', '.venv/', 'env/',
130
+
131
+ # Testes e cache
132
+ '.pytest_cache/', '.coverage', 'htmlcov/',
133
+ '*.log', '*.tmp', '*.temp',
134
+
135
+ # Dados temporários/processados
136
+ 'data/processed/', 'data/raw_documents/',
137
+ 'data/temp/', 'data/cache/', 'data/backup/',
138
+
139
+ # Build e distribuição
140
+ 'dist/', 'build/', '*.egg-info/',
141
+
142
+ # Outros
143
+ '*.db-wal', '*.db-shm', '*.sqlite3-journal'
144
+ ]
145
+
146
+ # Verificar arquivos grandes (>10MB) - NÃO enviar pelo Git normal
147
+ try:
148
+ file_size = file_path.stat().st_size
149
+ if file_size > 10 * 1024 * 1024: # 10MB
150
+ # Apenas ignorar se NÃO estivermos usando Git LFS
151
+ if not self.config['use_git_lfs']:
152
+ return True
153
+ except:
154
+ pass
155
+
156
+ # Verificar cada padrão
157
+ for pattern in ignore_patterns:
158
+ # Padrão de diretório (termina com /)
159
+ if pattern.endswith('/'):
160
+ dir_pattern = pattern.rstrip('/')
161
+ if rel_str.startswith(dir_pattern + '/') or rel_str == dir_pattern:
162
+ return True
163
+
164
+ # Padrão com wildcard
165
+ elif '*' in pattern:
166
+ if fnmatch.fnmatch(rel_str, pattern) or fnmatch.fnmatch(file_name, pattern):
167
+ return True
168
+
169
+ # Padrão exato
170
+ elif pattern == rel_str or pattern == file_name:
171
+ return True
172
+
173
+ return False
174
+
175
+ def setup_git_lfs(self, repo_dir):
176
+ """Configura Git LFS para arquivos grandes"""
177
+ try:
178
+ original_dir = os.getcwd()
179
+ os.chdir(repo_dir)
180
+
181
+ print("🔧 Configurando Git LFS...")
182
+
183
+ # Verificar se Git LFS está instalado
184
+ result = subprocess.run(['git', 'lfs', '--version'],
185
+ capture_output=True, text=True)
186
+
187
+ if result.returncode != 0:
188
+ print("⚠️ Git LFS não está instalado. Ignorando arquivos grandes.")
189
+ os.chdir(original_dir)
190
+ return False
191
+
192
+ # Instalar Git LFS no repositório
193
+ subprocess.run(['git', 'lfs', 'install'], capture_output=True)
194
+
195
+ # Rastrear tipos de arquivo grandes
196
+ lfs_patterns = ['*.sqlite3', '*.bin', '*.pickle', '*.pkl',
197
+ '*.h5', '*.pt', '*.pth']
198
+
199
+ for pattern in lfs_patterns:
200
+ subprocess.run(['git', 'lfs', 'track', pattern], capture_output=True)
201
+
202
+ # Adicionar .gitattributes
203
+ subprocess.run(['git', 'add', '.gitattributes'], capture_output=True)
204
+
205
+ print("✅ Git LFS configurado para arquivos grandes")
206
+ os.chdir(original_dir)
207
+ return True
208
+
209
+ except Exception as e:
210
+ print(f"⚠️ Erro ao configurar Git LFS: {e}")
211
+ os.chdir(original_dir)
212
+ return False
213
+
214
+ def clone_repo(self, repo_url, target_dir):
215
+ """Clona repositório com todas as correções necessárias"""
216
+
217
+ try:
218
+ os.makedirs(target_dir, exist_ok=True)
219
+
220
+ # Primeiro corrigir safe.directory
221
+ self.fix_git_safe_directory(target_dir)
222
+
223
+ # Comando de clone com todas as correções para Windows
224
+ clone_cmd = [
225
+ 'git', 'clone',
226
+ '--depth', '1',
227
+ '--config', 'core.protectNTFS=false',
228
+ '--config', 'core.protectHFS=false',
229
+ '--config', 'core.autocrlf=false',
230
+ repo_url,
231
+ target_dir
232
+ ]
233
+
234
+ print(f" Clonando: {repo_url.split('@')[-1]}")
235
+
236
+ result = subprocess.run(clone_cmd, capture_output=True,
237
+ text=True, timeout=120)
238
+
239
+ if result.returncode == 0:
240
+ print("✅ Repositório clonado")
241
+
242
+ # Configurar Git LFS se necessário
243
+ if self.config['use_git_lfs']:
244
+ self.setup_git_lfs(target_dir)
245
+
246
+ return True
247
+ else:
248
+ print(f"⚠️ Clone falhou: {result.stderr[:200]}")
249
+
250
+ # Tentar método alternativo
251
+ return self.clone_repo_alternative(repo_url, target_dir)
252
+
253
+ except subprocess.TimeoutExpired:
254
+ print("⚠️ Timeout ao clonar")
255
+ return self.clone_repo_alternative(repo_url, target_dir)
256
+ except Exception as e:
257
+ print(f"⚠️ Erro ao clonar: {e}")
258
+ return self.clone_repo_alternative(repo_url, target_dir)
259
+
260
+ def clone_repo_alternative(self, repo_url, target_dir):
261
+ """Método alternativo para clonar"""
262
+ try:
263
+ os.makedirs(target_dir, exist_ok=True)
264
+
265
+ # Inicializar repositório vazio
266
+ subprocess.run(['git', 'init'], cwd=target_dir, capture_output=True)
267
+
268
+ # Configurar para Windows
269
+ subprocess.run(['git', 'config', 'core.protectNTFS', 'false'],
270
+ cwd=target_dir, capture_output=True)
271
+ subprocess.run(['git', 'config', 'core.protectHFS', 'false'],
272
+ cwd=target_dir, capture_output=True)
273
+ subprocess.run(['git', 'config', 'core.autocrlf', 'false'],
274
+ cwd=target_dir, capture_output=True)
275
+
276
+ # Adicionar remote
277
+ subprocess.run(['git', 'remote', 'add', 'origin', repo_url],
278
+ cwd=target_dir, capture_output=True)
279
+
280
+ # Fazer fetch
281
+ result = subprocess.run(['git', 'fetch', 'origin'],
282
+ cwd=target_dir, capture_output=True, text=True)
283
+
284
+ if result.returncode != 0:
285
+ return False
286
+
287
+ # Reset para HEAD
288
+ subprocess.run(['git', 'reset', '--hard', 'FETCH_HEAD'],
289
+ cwd=target_dir, capture_output=True)
290
+
291
+ print("✅ Repositório preparado (método alternativo)")
292
+ return True
293
+
294
+ except Exception as e:
295
+ print(f"❌ Método alternativo falhou: {e}")
296
+ return False
297
+
298
+ def clean_repo(self, repo_dir):
299
+ """Limpa repositório completamente"""
300
+ original_dir = os.getcwd()
301
+
302
+ try:
303
+ os.chdir(repo_dir)
304
+
305
+ # Remover todos os arquivos trackeados
306
+ result = subprocess.run(['git', 'ls-files'],
307
+ capture_output=True, text=True)
308
+
309
+ if result.returncode == 0 and result.stdout.strip():
310
+ files = result.stdout.strip().split('\n')
311
+
312
+ for file in files:
313
+ if file and not file.startswith('.git/'):
314
+ file_path = Path(file)
315
+ if file_path.exists():
316
+ try:
317
+ if file_path.is_file():
318
+ file_path.unlink()
319
+ elif file_path.is_dir():
320
+ shutil.rmtree(file_path, ignore_errors=True)
321
+ except:
322
+ pass
323
+
324
+ print(f"✅ {len(files)} arquivos removidos")
325
+
326
+ # Remover arquivos não trackeados
327
+ subprocess.run(['git', 'clean', '-fd'], capture_output=True)
328
+
329
+ # Remover tudo exceto .git
330
+ for item in os.listdir('.'):
331
+ if item != '.git':
332
+ item_path = Path(item)
333
+ try:
334
+ if item_path.is_file():
335
+ item_path.unlink()
336
+ elif item_path.is_dir():
337
+ shutil.rmtree(item_path, ignore_errors=True)
338
+ except:
339
+ pass
340
+
341
+ return True
342
+
343
+ finally:
344
+ os.chdir(original_dir)
345
+
346
+ def copy_project_files(self, target_dir):
347
+ """Copia arquivos do projeto respeitando regras de ignore"""
348
+
349
+ files_copied = 0
350
+ total_size = 0
351
+ ignored_count = 0
352
+ large_files_ignored = 0
353
+
354
+ print("\n📋 Analisando arquivos do projeto...")
355
+
356
+ for root, dirs, files in os.walk(self.config['project_path']):
357
+ # Filtrar diretórios
358
+ dirs[:] = [d for d in dirs if not self.should_ignore_file(
359
+ Path(root) / d,
360
+ Path(d)
361
+ )]
362
+
363
+ for file in files:
364
+ src_path = Path(root) / file
365
+ rel_path = src_path.relative_to(self.config['project_path'])
366
+
367
+ # Verificar se deve ignorar
368
+ if self.should_ignore_file(src_path, rel_path):
369
+ ignored_count += 1
370
+
371
+ # Verificar se é arquivo grande
372
+ try:
373
+ if src_path.stat().st_size > 10 * 1024 * 1024:
374
+ large_files_ignored += 1
375
+ if large_files_ignored <= 5:
376
+ size_mb = src_path.stat().st_size / 1024 / 1024
377
+ print(f" 🚫 GRANDE ({size_mb:.1f} MB): {rel_path}")
378
+ except:
379
+ pass
380
+
381
+ continue
382
+
383
+ dst_path = Path(target_dir) / rel_path
384
+ dst_path.parent.mkdir(parents=True, exist_ok=True)
385
+
386
+ try:
387
+ shutil.copy2(src_path, dst_path)
388
+ files_copied += 1
389
+ total_size += src_path.stat().st_size
390
+ except Exception as e:
391
+ print(f"⚠️ Não pôde copiar {rel_path}: {e}")
392
+
393
+ print(f"\n📊 Estatísticas:")
394
+ print(f" • Arquivos copiados: {files_copied}")
395
+ print(f" • Tamanho total: {total_size / 1024 / 1024:.1f} MB")
396
+ print(f" • Arquivos ignorados: {ignored_count}")
397
+
398
+ if large_files_ignored > 0:
399
+ print(f" • Arquivos grandes ignorados (>10MB): {large_files_ignored}")
400
+
401
+ if not self.config['use_git_lfs'] and large_files_ignored > 0:
402
+ print(f"\n⚠️ ATENÇÃO: {large_files_ignored} arquivos grandes foram ignorados.")
403
+ print(" Para incluir arquivos grandes, use Git LFS:")
404
+ print(" 1. Adicione HF_USE_GIT_LFS=true ao .env")
405
+ print(" 2. Instale Git LFS: https://git-lfs.com/")
406
+ print(" 3. Execute novamente")
407
+
408
+ return files_copied, total_size
409
+
410
+ def force_deploy(self, dry_run=False, skip_confirmation=False):
411
+ """Executa o deploy forçado"""
412
+
413
+ print("=" * 60)
414
+ print("🚀 DEPLOY FORÇADO PARA HUGGING FACE")
415
+ print("=" * 60)
416
+
417
+ # Configuração
418
+ if not self.config['repo_id']:
419
+ self.config['repo_id'] = input(
420
+ "Digite o nome do Space (usuário/nome-space): "
421
+ ).strip()
422
+
423
+ if not self.config['token']:
424
+ print("🔑 Token não encontrado no .env")
425
+ self.config['token'] = input("Digite seu token do Hugging Face: ").strip()
426
+
427
+ if not self.config['token'] or not self.config['repo_id']:
428
+ print("❌ Token e nome do Space são obrigatórios")
429
+ return False
430
+
431
+ print(f"\n🎯 Space: {self.config['repo_id']}")
432
+ print(f"📁 Projeto: {self.config['project_path']}")
433
+
434
+ if self.config['use_git_lfs']:
435
+ print("🔧 Modo: Git LFS ativado para arquivos grandes")
436
+ else:
437
+ print("⚠️ Modo: Arquivos >10MB serão ignorados")
438
+
439
+ if not skip_confirmation and not dry_run:
440
+ print("\n⚠️ ATENÇÃO: Isso apagará TUDO no Space")
441
+ confirm = input("🔴 Continuar? (s/n): ").lower()
442
+ if confirm not in ['s', 'sim', 'y', 'yes']:
443
+ print("❌ Cancelado")
444
+ return False
445
+
446
+ # Criar diretório temporário
447
+ temp_dir = tempfile.mkdtemp(prefix="hf_deploy_")
448
+ self.temp_dirs.append(temp_dir)
449
+
450
+ try:
451
+ # Clonar repositório
452
+ print(f"\n📦 Preparando em: {temp_dir}")
453
+ print("\n⬇️ Clonando repositório...")
454
+
455
+ repo_url = f"https://user:{self.config['token']}@huggingface.co/spaces/{self.config['repo_id']}"
456
+
457
+ if not self.clone_repo(repo_url, temp_dir):
458
+ print("❌ Não foi possível clonar")
459
+ return False
460
+
461
+ # Limpar repositório
462
+ print("\n🗑️ Limpando repositório...")
463
+ self.clean_repo(temp_dir)
464
+
465
+ if dry_run:
466
+ print("\n🚀 MODO SIMULAÇÃO")
467
+ print("Arquivos que seriam enviados:")
468
+ self.list_files_dryrun()
469
+ return True
470
+
471
+ # Copiar arquivos
472
+ print("\n📋 Copiando arquivos...")
473
+ files_copied, total_size = self.copy_project_files(temp_dir)
474
+
475
+ if files_copied == 0:
476
+ print("❌ Nenhum arquivo para copiar")
477
+ return False
478
+
479
+ # Commit e push
480
+ print("\n💾 Commit e push...")
481
+ original_dir = os.getcwd()
482
+ os.chdir(temp_dir)
483
+
484
+ try:
485
+ # Adicionar tudo
486
+ subprocess.run(['git', 'add', '.'], capture_output=True)
487
+
488
+ # Verificar se há mudanças
489
+ result = subprocess.run(['git', 'status', '--porcelain'],
490
+ capture_output=True, text=True)
491
+
492
+ if not result.stdout.strip():
493
+ print("⚠️ Nenhuma mudança detectada")
494
+ with open('.deploy_marker', 'w') as f:
495
+ f.write(f"Deploy: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
496
+ subprocess.run(['git', 'add', '.deploy_marker'], capture_output=True)
497
+
498
+ # Commit
499
+ commit_msg = f'Deploy: {files_copied} arquivos - {time.strftime("%Y-%m-%d %H:%M:%S")}'
500
+ subprocess.run(['git', 'commit', '-m', commit_msg],
501
+ capture_output=True, text=True)
502
+
503
+ print("✅ Commit criado")
504
+
505
+ # Push
506
+ print("\n⬆️ Enviando...")
507
+ push_result = subprocess.run(['git', 'push', 'origin', 'HEAD'],
508
+ capture_output=True, text=True, timeout=180)
509
+
510
+ if push_result.returncode != 0:
511
+ print(f"⚠️ Push falhou: {push_result.stderr[:200]}")
512
+
513
+ # Tentar push forçado
514
+ print(" Tentando push forçado...")
515
+ push_result = subprocess.run(['git', 'push', '--force', 'origin', 'HEAD'],
516
+ capture_output=True, text=True, timeout=180)
517
+
518
+ if push_result.returncode != 0:
519
+ print(f"❌ Push forçado falhou: {push_result.stderr[:200]}")
520
+ return False
521
+
522
+ print("✅ Push realizado!")
523
+
524
+ # Resultado
525
+ print("\n" + "=" * 60)
526
+ print("✨ DEPLOY CONCLUÍDO!")
527
+ print("=" * 60)
528
+ print(f"📊 Estatísticas:")
529
+ print(f" • Arquivos: {files_copied}")
530
+ print(f" • Tamanho: {total_size / 1024 / 1024:.1f} MB")
531
+ print(f" • Space: {self.config['repo_id']}")
532
+ print(f"🌐 URL: https://huggingface.co/spaces/{self.config['repo_id']}")
533
+ print("=" * 60)
534
+
535
+ return True
536
+
537
+ finally:
538
+ os.chdir(original_dir)
539
+
540
+ except Exception as e:
541
+ print(f"❌ Erro: {e}")
542
+ import traceback
543
+ traceback.print_exc()
544
+ return False
545
+
546
+ def list_files_dryrun(self):
547
+ """Lista arquivos no modo dry-run"""
548
+ files_listed = 0
549
+ total_size = 0
550
+ ignored_count = 0
551
+
552
+ for root, dirs, files in os.walk(self.config['project_path']):
553
+ # Filtrar diretórios
554
+ dirs[:] = [d for d in dirs if not self.should_ignore_file(
555
+ Path(root) / d,
556
+ Path(d)
557
+ )]
558
+
559
+ for file in files:
560
+ src_path = Path(root) / file
561
+ rel_path = src_path.relative_to(self.config['project_path'])
562
+
563
+ if self.should_ignore_file(src_path, rel_path):
564
+ ignored_count += 1
565
+ continue
566
+
567
+ size_kb = src_path.stat().st_size / 1024
568
+ total_size += src_path.stat().st_size
569
+ files_listed += 1
570
+
571
+ if files_listed <= 50:
572
+ print(f" 📄 {rel_path} ({size_kb:.1f} KB)")
573
+ elif files_listed == 51:
574
+ print(f" ... e mais arquivos")
575
+
576
+ print(f"\n Total: {files_listed} arquivos ({total_size / 1024 / 1024:.1f} MB)")
577
+ print(f" Ignorados: {ignored_count} arquivos")
578
+
579
+ def check_prerequisites(self):
580
+ """Verifica arquivos obrigatórios (Dockerfile e requirements.txt)"""
581
+ dockerfile_path = self.config['project_path'] / "Dockerfile"
582
+ req_path = self.config['project_path'] / "requirements.txt"
583
+
584
+ missing = []
585
+ if not dockerfile_path.exists():
586
+ missing.append("Dockerfile")
587
+ if not req_path.exists():
588
+ missing.append("requirements.txt")
589
+
590
+ if missing:
591
+ print(f"❌ Arquivos obrigatórios faltando: {', '.join(missing)}")
592
+ return False
593
+
594
+ print(f"✅ Pré-requisitos encontrados: Dockerfile e requirements.txt")
595
+ return True
596
+
597
+
598
+ def main():
599
+ parser = argparse.ArgumentParser(
600
+ description="Deploy FORÇADO para Hugging Face Spaces"
601
+ )
602
+ parser.add_argument("--repo", "-r", help="Nome do Space")
603
+ parser.add_argument("--project", "-p", help="Caminho do projeto")
604
+ parser.add_argument("--token", "-t", help="Token")
605
+ parser.add_argument("--dry-run", "-d", action="store_true", help="Modo simulação")
606
+ parser.add_argument("--check", "-c", action="store_true", help="Verificar Dockerfile")
607
+ parser.add_argument("--yes", "-y", action="store_true", help="Pular confirmações")
608
+ parser.add_argument("--lfs", action="store_true", help="Usar Git LFS para arquivos grandes")
609
+
610
+ args = parser.parse_args()
611
+
612
+ deployer = SimpleHFDeploy()
613
+
614
+ # Sobrescrever configurações
615
+ if args.repo:
616
+ deployer.config['repo_id'] = args.repo
617
+ if args.project:
618
+ deployer.config['project_path'] = Path(args.project)
619
+ if args.token:
620
+ deployer.config['token'] = args.token
621
+ if args.lfs:
622
+ deployer.config['use_git_lfs'] = True
623
+
624
+ # Verificar Pré-requisitos
625
+ if args.check or not deployer.check_prerequisites():
626
+ if args.check:
627
+ sys.exit(0)
628
+ else:
629
+ print("\n❌ Arquivos de configuração necessários")
630
+ sys.exit(1)
631
+
632
+ # Executar deploy
633
+ success = deployer.force_deploy(
634
+ dry_run=args.dry_run,
635
+ skip_confirmation=args.yes
636
+ )
637
+
638
+ sys.exit(0 if success else 1)
639
+
640
+
641
+ if __name__ == "__main__":
642
+ # Verificar Git
643
+ try:
644
+ subprocess.run(['git', '--version'], capture_output=True, check=True)
645
+ except:
646
+ print("❌ Git não está instalado")
647
+ sys.exit(1)
648
+
649
+ main()