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 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from pathlib import Path
4
+ import tempfile
5
+ import zipfile
6
+ import shutil
7
+
8
+ class WebProjectAnalyzer:
9
+ def __init__(self):
10
+ # Diretórios que devem ser completamente ignorados
11
+ self.ignored_dirs = {
12
+ '__pycache__', '.git', '.vscode', '.idea', 'node_modules',
13
+ 'vendor', 'dist', 'build', 'cache', 'logs', 'tmp',
14
+ 'coverage', '.github', '.circleci', '.docker', 'venv',
15
+ 'env', '.venv', 'virtualenv', 'bin', 'include', 'lib',
16
+ 'lib64', 'site-packages', 'dist-packages', '.gitlab',
17
+ '.svn', '.hg', '.pytest_cache', '.mypy_cache', '__MACOSX'
18
+ }
19
+
20
+ # Arquivos que devem ser ignorados
21
+ self.ignored_files = {
22
+ '.DS_Store', 'Thumbs.db', '.env', '.env.local',
23
+ 'package-lock.json', 'yarn.lock', '.gitignore',
24
+ '*.log', '*.swp', '*.swo', '.htaccess', '*.pyc',
25
+ '*.pyo', '*.pyd', 'Pipfile.lock', '*.egg-info',
26
+ '*.dist-info', '.dockerignore', '.npmrc', '.yarnrc',
27
+ 'composer.lock', 'Gemfile.lock', 'go.sum', 'poetry.lock'
28
+ }
29
+
30
+ # Extensões relevantes para projetos web
31
+ self.relevant_extensions = {
32
+ '.html', '.htm', '.js', '.css', '.scss', '.less', '.sass',
33
+ '.php', '.py', '.rb', '.java', '.ts', '.jsx', '.tsx',
34
+ '.json', '.xml', '.svg', '.sql', '.md', '.txt', '.yml',
35
+ '.yaml', '.toml', '.ini', '.cfg', '.conf', '.env.example',
36
+ '.gitattributes', '.editorconfig', '.prettierrc', '.eslintrc',
37
+ '.babelrc', '.npmignore', 'Dockerfile', 'docker-compose.yml',
38
+ 'Makefile', 'Procfile', '.travis.yml', 'app.yaml',
39
+ 'webpack.config.js', 'vite.config.js', 'next.config.js',
40
+ 'nuxt.config.js', 'vue.config.js', 'angular.json',
41
+ 'tailwind.config.js', 'postcss.config.js'
42
+ }
43
+
44
+ # Arquivos de configuração importantes
45
+ self.important_config_files = {
46
+ 'package.json', 'requirements.txt', 'Pipfile', 'pyproject.toml',
47
+ 'composer.json', 'Gemfile', 'go.mod', 'Cargo.toml',
48
+ 'pom.xml', 'build.gradle', 'build.gradle.kts', 'settings.gradle',
49
+ 'CMakeLists.txt', 'Makefile', 'docker-compose.yml', 'Dockerfile',
50
+ '.env.example', '.env.sample', 'README.md', 'README.rst',
51
+ 'LICENSE', 'CONTRIBUTING.md', 'CHANGELOG.md', 'TODO.md'
52
+ }
53
+
54
+ def should_ignore(self, name, path):
55
+ """Determina se um arquivo/diretório deve ser ignorado"""
56
+ # Ignora diretórios específicos
57
+ if name in self.ignored_dirs:
58
+ return True
59
+
60
+ # Ignora arquivos ocultos (iniciados com .) exceto arquivos de configuração importantes
61
+ if name.startswith('.') and name not in self.important_config_files:
62
+ # Permite alguns arquivos de configuração ocultos importantes
63
+ if not any(name.endswith(ext) for ext in ['.env.example', '.gitattributes', '.editorconfig']):
64
+ return True
65
+
66
+ # Ignora arquivos temporários
67
+ if name.endswith('~') or name.startswith('~'):
68
+ return True
69
+
70
+ # Ignora pastas de ambiente Python
71
+ if any(env_dir in path.split(os.sep) for env_dir in ['venv', 'virtualenv', '.venv']):
72
+ return True
73
+
74
+ # Ignora pastas de pacotes Python
75
+ if any(pkg_dir in path.split(os.sep) for pkg_dir in ['site-packages', 'dist-packages']):
76
+ return True
77
+
78
+ return False
79
+
80
+ def is_relevant_file(self, name):
81
+ """Determina se um arquivo é relevante para mostrar"""
82
+ # Arquivos de configuração importantes sempre são relevantes
83
+ if name in self.important_config_files:
84
+ return True
85
+
86
+ # Verifica extensões relevantes
87
+ _, ext = os.path.splitext(name)
88
+ return ext.lower() in self.relevant_extensions
89
+
90
+ def get_file_icon(self, filename):
91
+ """Retorna ícone apropriado para o tipo de arquivo"""
92
+ _, ext = os.path.splitext(filename)
93
+
94
+ icon_map = {
95
+ '.py': '🐍', '.js': '📜', '.jsx': '⚛️', '.ts': '📘', '.tsx': '⚛️',
96
+ '.html': '🌐', '.htm': '🌐', '.css': '🎨', '.scss': '🎨', '.less': '🎨',
97
+ '.php': '🐘', '.java': '☕', '.rb': '💎', '.json': '📋', '.xml': '📄',
98
+ '.sql': '🗃️', '.md': '📖', '.txt': '📄', '.yml': '⚙️', '.yaml': '⚙️',
99
+ '.toml': '⚙️', '.ini': '⚙️', '.cfg': '⚙️', '.conf': '⚙️'
100
+ }
101
+
102
+ return icon_map.get(ext, '📄')
103
+
104
+ def get_folder_stats(self, root_dir):
105
+ """Calcula estatísticas da pasta"""
106
+ total_files = 0
107
+ relevant_files = 0
108
+ total_size = 0
109
+
110
+ for root, dirs, files in os.walk(root_dir):
111
+ # Remove diretórios ignorados
112
+ dirs[:] = [d for d in dirs if not self.should_ignore(d, os.path.join(root, d))]
113
+
114
+ for file in files:
115
+ if self.should_ignore(file, os.path.join(root, file)):
116
+ continue
117
+
118
+ total_files += 1
119
+ file_path = os.path.join(root, file)
120
+
121
+ if self.is_relevant_file(file):
122
+ relevant_files += 1
123
+
124
+ try:
125
+ total_size += os.path.getsize(file_path)
126
+ except:
127
+ pass
128
+
129
+ return total_files, relevant_files, total_size
130
+
131
+ def analyze_web_project(self, root_dir, level=0, max_depth=4):
132
+ """Analisa a estrutura do projeto web"""
133
+ if level > max_depth:
134
+ return ""
135
+
136
+ indent = ' ' * level
137
+ output = []
138
+
139
+ try:
140
+ items = sorted(os.listdir(root_dir))
141
+
142
+ # Separa diretórios e arquivos
143
+ dirs = []
144
+ files = []
145
+
146
+ for item in items:
147
+ full_path = os.path.join(root_dir, item)
148
+
149
+ if self.should_ignore(item, full_path):
150
+ continue
151
+
152
+ if os.path.isdir(full_path):
153
+ dirs.append(item)
154
+ else:
155
+ if self.is_relevant_file(item):
156
+ files.append(item)
157
+
158
+ # Processa arquivos primeiro
159
+ for file in files:
160
+ icon = self.get_file_icon(file)
161
+ output.append(f"{indent}{icon} {file}")
162
+
163
+ # Processa diretórios
164
+ for dir_name in dirs:
165
+ full_path = os.path.join(root_dir, dir_name)
166
+ output.append(f"{indent}📁 {dir_name}/")
167
+
168
+ # Recursivamente analisa subdiretório
169
+ sub_output = self.analyze_web_project(full_path, level + 1, max_depth)
170
+ if sub_output.strip():
171
+ output.append(sub_output)
172
+
173
+ except PermissionError:
174
+ output.append(f"{indent}🚫 [Permissão negada]")
175
+ except Exception as e:
176
+ output.append(f"{indent}❌ [Erro: {str(e)}]")
177
+
178
+ return '\n'.join(output)
179
+
180
+ def extract_zip(self, zip_path, extract_to):
181
+ """Extrai arquivo ZIP"""
182
+ try:
183
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
184
+ zip_ref.extractall(extract_to)
185
+ return True
186
+ except Exception as e:
187
+ print(f"Erro ao extrair ZIP: {e}")
188
+ return False
189
+
190
+ def process_uploaded_file(self, uploaded_file):
191
+ """Processa arquivo enviado (ZIP ou pasta)"""
192
+ if uploaded_file is None:
193
+ return "❌ Por favor, faça upload de um arquivo ZIP ou selecione uma pasta.", ""
194
+
195
+ try:
196
+ # Cria diretório temporário para processamento
197
+ with tempfile.TemporaryDirectory() as temp_dir:
198
+ project_path = os.path.join(temp_dir, "project")
199
+
200
+ # Verifica se é arquivo ZIP
201
+ if hasattr(uploaded_file, 'name') and uploaded_file.name.endswith('.zip'):
202
+ # É um arquivo ZIP
203
+ if not self.extract_zip(uploaded_file, project_path):
204
+ return "❌ Erro ao extrair arquivo ZIP. Verifique se o arquivo não está corrompido.", ""
205
+ else:
206
+ # É um arquivo único ou diretório (no Gradio, uploaded_file é o caminho do arquivo)
207
+ if os.path.isdir(uploaded_file):
208
+ project_path = uploaded_file
209
+ else:
210
+ return "❌ Por favor, faça upload de um arquivo ZIP contendo o projeto ou selecione uma pasta.", ""
211
+
212
+ # Verifica se o diretório existe
213
+ if not os.path.exists(project_path):
214
+ return "❌ Diretório do projeto não encontrado após extração.", ""
215
+
216
+ # Obtém estatísticas
217
+ total_files, relevant_files, total_size = self.get_folder_stats(project_path)
218
+
219
+ # Analisa estrutura
220
+ structure = self.analyze_web_project(project_path)
221
+
222
+ # Prepara relatório
223
+ stats_report = f"""
224
+ 📊 **ESTATÍSTICAS DO PROJETO**
225
+
226
+ • 📁 Total de arquivos: {total_files}
227
+ • 📄 Arquivos relevantes: {relevant_files}
228
+ • 💾 Tamanho aproximado: {total_size / 1024 / 1024:.2f} MB
229
+ • 📈 Taxa de relevância: {(relevant_files/total_files*100) if total_files > 0 else 0:.1f}%
230
+
231
+ 🔍 **ESTRUTURA DO PROJETO**
232
+ """
233
+ full_output = stats_report + "\n" + structure
234
+
235
+ return full_output, ""
236
+
237
+ except Exception as e:
238
+ error_msg = f"❌ Erro ao processar projeto: {str(e)}"
239
+ print(f"Erro detalhado: {traceback.format_exc()}")
240
+ return error_msg, ""
241
+
242
+ # ================== Gradio Interface ==================
243
+
244
+ def create_interface():
245
+ """Cria a interface Gradio"""
246
+
247
+ analyzer = WebProjectAnalyzer()
248
+
249
+ with gr.Blocks(
250
+ title="Web Project Structure Viewer",
251
+ theme=gr.themes.Soft(),
252
+ css="""
253
+ .gradio-container {
254
+ max-width: 1000px !important;
255
+ }
256
+ .header {
257
+ text-align: center;
258
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
259
+ padding: 20px;
260
+ border-radius: 10px;
261
+ color: white;
262
+ margin-bottom: 20px;
263
+ }
264
+ .stats-box {
265
+ background-color: #f8f9fa;
266
+ border-left: 4px solid #007bff;
267
+ padding: 15px;
268
+ margin: 10px 0;
269
+ border-radius: 5px;
270
+ }
271
+ .structure-box {
272
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
273
+ font-size: 12px;
274
+ line-height: 1.4;
275
+ }
276
+ .warning {
277
+ background-color: #fff3cd;
278
+ border: 1px solid #ffeaa7;
279
+ padding: 10px;
280
+ border-radius: 5px;
281
+ margin: 10px 0;
282
+ }
283
+ """
284
+ ) as interface:
285
+
286
+ gr.Markdown(
287
+ """
288
+ <div class="header">
289
+ <h1>🔍 Web Project Structure Viewer</h1>
290
+ <p>Analise a estrutura de projetos web extraindo apenas os arquivos e pastas relevantes</p>
291
+ </div>
292
+ """
293
+ )
294
+
295
+ with gr.Row():
296
+ with gr.Column(scale=1):
297
+ with gr.Group():
298
+ gr.Markdown("### 📤 Upload do Projeto")
299
+
300
+ file_upload = gr.File(
301
+ label="Faça upload do projeto (ZIP)",
302
+ file_types=[".zip"],
303
+ type="filepath",
304
+ file_count="single"
305
+ )
306
+
307
+ gr.Markdown("""
308
+ **💡 Dicas:**
309
+ - Faça upload de um arquivo ZIP contendo seu projeto
310
+ - O sistema ignora automaticamente arquivos desnecessários
311
+ - Mostra apenas arquivos relevantes para desenvolvimento web
312
+ """)
313
+
314
+ with gr.Group():
315
+ gr.Markdown("### ⚙️ Configurações")
316
+
317
+ max_depth = gr.Slider(
318
+ minimum=1,
319
+ maximum=6,
320
+ value=4,
321
+ step=1,
322
+ label="Profundidade máxima de análise",
323
+ info="Controla quantos níveis de subpastas serão mostrados"
324
+ )
325
+
326
+ analyze_btn = gr.Button(
327
+ "🔍 Analisar Estrutura",
328
+ variant="primary",
329
+ size="lg"
330
+ )
331
+
332
+ with gr.Accordion("ℹ️ Sobre", open=False):
333
+ gr.Markdown("""
334
+ **📁 O que é mostrado:**
335
+ - Arquivos de código (.py, .js, .html, .css, etc.)
336
+ - Arquivos de configuração importantes
337
+ - Documentação (.md, .txt)
338
+ - Estrutura de pastas principais
339
+
340
+ **🚫 O que é ignorado:**
341
+ - Pastas de dependências (node_modules, venv, etc.)
342
+ - Arquivos de cache e temporários
343
+ - Arquivos ocultos do sistema
344
+ - Logs e arquivos de build
345
+
346
+ **🎯 Objetivo:**
347
+ Mostrar apenas a estrutura relevante para entender e trabalhar com o projeto
348
+ """)
349
+
350
+ with gr.Column(scale=2):
351
+ with gr.Group():
352
+ gr.Markdown("### 📊 Resultado da Análise")
353
+
354
+ output_text = gr.Textbox(
355
+ label="Estrutura do Projeto",
356
+ lines=20,
357
+ max_lines=30,
358
+ show_copy_button=True,
359
+ elem_classes=["structure-box"]
360
+ )
361
+
362
+ with gr.Group():
363
+ gr.Markdown("### 💾 Exportar")
364
+
365
+ export_btn = gr.Button("📥 Exportar como Texto", variant="secondary")
366
+
367
+ # Exemplos
368
+ with gr.Accordion("📚 Exemplos de Projetos", open=False):
369
+ gr.Markdown("""
370
+ **Estruturas típicas analisadas:**
371
+
372
+ ```
373
+ projeto-web/
374
+ 📁 src/
375
+ 📁 components/
376
+ 📄 Header.js
377
+ 📄 Footer.js
378
+ �� pages/
379
+ 📄 index.js
380
+ 📄 about.js
381
+ 📄 App.js
382
+ 📄 index.css
383
+ 📁 public/
384
+ 📄 index.html
385
+ 📄 favicon.ico
386
+ 📄 package.json
387
+ 📄 README.md
388
+ 🐍 app.py
389
+ 📄 requirements.txt
390
+ ```
391
+
392
+ **Projetos suportados:**
393
+ - React, Vue, Angular
394
+ - Django, Flask, FastAPI
395
+ - Laravel, Express.js
396
+ - E qualquer outro projeto web
397
+ """)
398
+
399
+ # Manipuladores de eventos
400
+ def analyze_structure(file_upload, max_depth_value):
401
+ """Função para analisar a estrutura"""
402
+ if file_upload is None:
403
+ return "❌ Por favor, faça upload de um arquivo ZIP do projeto.", ""
404
+
405
+ # Atualiza profundidade máxima
406
+ analyzer.max_depth = max_depth_value
407
+
408
+ # Processa o arquivo
409
+ result, _ = analyzer.process_uploaded_file(file_upload)
410
+ return result, result
411
+
412
+ analyze_btn.click(
413
+ fn=analyze_structure,
414
+ inputs=[file_upload, max_depth],
415
+ outputs=[output_text]
416
+ )
417
+
418
+ def export_structure(structure):
419
+ """Exporta a estrutura como arquivo de texto"""
420
+ if not structure or structure.startswith("❌"):
421
+ return None
422
+
423
+ try:
424
+ # Cria arquivo temporário
425
+ temp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8')
426
+ temp_file.write(structure)
427
+ temp_file.close()
428
+ return temp_file.name
429
+ except Exception as e:
430
+ print(f"Erro ao exportar: {e}")
431
+ return None
432
+
433
+ export_btn.click(
434
+ fn=export_structure,
435
+ inputs=[output_text],
436
+ outputs=gr.File(label="Download da Estrutura")
437
+ )
438
+
439
+ # Limpar saída quando novo arquivo for carregado
440
+ def clear_on_new_upload():
441
+ return ""
442
+
443
+ file_upload.change(
444
+ fn=clear_on_new_upload,
445
+ outputs=[output_text]
446
+ )
447
+
448
+ return interface
449
+
450
+ # ================== Execução Principal ==================
451
+
452
+ def main():
453
+ """Função principal"""
454
+ print("🚀 Iniciando Web Project Structure Viewer...")
455
+
456
+ # Cria e inicia a interface
457
+ interface = create_interface()
458
+ interface.launch(
459
+ server_name="0.0.0.0",
460
+ server_port=7860,
461
+ share=False,
462
+ show_error=True
463
+ )
464
+
465
+ if __name__ == "__main__":
466
+ import traceback
467
+ main()