Daniel251 commited on
Commit
71d7133
·
verified ·
1 Parent(s): 6ac3439

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -148
app.py CHANGED
@@ -2,7 +2,6 @@ import os
2
  import gradio as gr
3
  from pathlib import Path
4
  import tempfile
5
- import shutil
6
 
7
  class WebProjectAnalyzer:
8
  def __init__(self):
@@ -85,39 +84,19 @@ class WebProjectAnalyzer:
85
 
86
  return icon_map.get(ext, '📄')
87
 
88
- def collect_relevant_files(self, root_path, max_depth=4):
89
- """Coleta apenas os arquivos relevantes para upload"""
90
- relevant_files = []
91
-
92
- def scan_directory(current_path, current_depth):
93
- if current_depth > max_depth:
94
- return
95
-
96
- try:
97
- items = sorted(os.listdir(current_path))
98
-
99
- for item in items:
100
- full_path = os.path.join(current_path, item)
101
- relative_path = os.path.relpath(full_path, root_path)
102
-
103
- if self.should_ignore(item, full_path):
104
- continue
105
-
106
- if os.path.isdir(full_path):
107
- scan_directory(full_path, current_depth + 1)
108
- else:
109
- if self.is_relevant_file(item):
110
- relevant_files.append(full_path)
111
-
112
- except (PermissionError, OSError):
113
- pass
114
-
115
- scan_directory(root_path, 0)
116
- return relevant_files
117
-
118
  def analyze_structure(self, root_path, max_depth=4):
119
  """Analisa a estrutura do projeto"""
 
 
 
 
 
 
 
 
 
120
  structure_output = []
 
121
  stats = {
122
  'total_files': 0,
123
  'relevant_files': 0,
@@ -150,6 +129,7 @@ class WebProjectAnalyzer:
150
  stats['total_files'] += 1
151
  if self.is_relevant_file(item):
152
  stats['relevant_files'] += 1
 
153
 
154
  try:
155
  stats['total_size'] += os.path.getsize(full_path)
@@ -168,11 +148,22 @@ class WebProjectAnalyzer:
168
  structure_output.append(f"{indent}📁 {dir_name}/")
169
  analyze_directory(full_path, level + 1)
170
 
171
- except (PermissionError, OSError):
172
- structure_output.append(f"{indent}🚫 [Permissão negada]")
 
 
173
 
174
- analyze_directory(root_path)
175
- return '\n'.join(structure_output), stats
 
 
 
 
 
 
 
 
 
176
 
177
  def create_structure_report(self, folder_path, structure, stats, relevant_files):
178
  """Cria relatório completo da estrutura"""
@@ -182,6 +173,10 @@ class WebProjectAnalyzer:
182
 
183
  folder_name = os.path.basename(folder_path)
184
 
 
 
 
 
185
  report = f"""
186
  📊 **ANÁLISE DO PROJETO**: `{folder_name}`
187
  📍 **Pasta**: {folder_path}
@@ -190,7 +185,7 @@ class WebProjectAnalyzer:
190
 
191
  • 📁 Total de arquivos escaneados: {total_files}
192
  • 📄 Arquivos relevantes encontrados: {relevant_files_count}
193
- • 📤 Arquivos preparados para upload: {len(relevant_files)}
194
  • 💾 Tamanho total: {total_size / 1024 / 1024:.2f} MB
195
  • 🎯 Taxa de relevância: {(relevant_files_count/total_files*100) if total_files > 0 else 0:.1f}%
196
 
@@ -199,37 +194,44 @@ class WebProjectAnalyzer:
199
  {structure}
200
 
201
  💡 **INFORMAÇÕES**:
202
- - Apenas arquivos essenciais serão enviados
203
- - Pastas como node_modules, .git são ignoradas
204
- - Arquivos de configuração importantes são incluídos
205
- - Código fonte e documentação são priorizados
206
  """
207
  return report
208
 
209
- def process_uploaded_folder(self, folder_path, max_depth=4):
210
  """Processa a pasta enviada e analisa sua estrutura"""
211
- if not folder_path:
212
- return "❌ Nenhuma pasta selecionada.", [], ""
213
 
214
  try:
215
- # Coleta arquivos relevantes
216
- relevant_files = self.collect_relevant_files(folder_path, max_depth)
 
 
 
 
 
 
 
 
 
 
 
217
 
218
  # Analisa estrutura
219
- structure, stats = self.analyze_structure(folder_path, max_depth)
220
 
221
  # Cria relatório
222
  report = self.create_structure_report(folder_path, structure, stats, relevant_files)
223
 
224
- # Prepara arquivos para download (apenas os relevantes)
225
- download_files = []
226
- for file_path in relevant_files:
227
- download_files.append(file_path)
228
-
229
- return report, download_files, structure
230
 
231
  except Exception as e:
232
- return f"❌ Erro ao processar a pasta: {str(e)}", [], ""
 
233
 
234
  def analyze_demo_projects(self, project_type):
235
  """Fornece exemplos de estruturas de projetos"""
@@ -334,6 +336,38 @@ meu-app-vue/
334
  📄 index.html
335
  📄 package.json
336
  📄 vue.config.js
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
  📄 README.md
338
  """
339
  }
@@ -344,10 +378,10 @@ meu-app-vue/
344
 
345
  {demos[project_type]}
346
 
347
- 💡 **Como funcionaria com upload real:**
348
  - 📁 Pasta selecionada: `meu-app-{project_type}/`
349
- - 📄 Arquivos relevantes detectados: ~15-25 arquivos
350
- - 🎯 Apenas código e configurações seriam enviados
351
  - 🚫 node_modules, .git, cache seriam ignorados
352
  """
353
  else:
@@ -399,13 +433,19 @@ def create_interface():
399
  border: 1px solid #dee2e6;
400
  margin: 10px 0;
401
  }
402
- .file-list {
403
- max-height: 200px;
404
- overflow-y: auto;
405
- background: #f8f9fa;
406
  padding: 15px;
407
  border-radius: 8px;
408
- border: 1px solid #dee2e6;
 
 
 
 
 
 
 
409
  }
410
  """
411
  ) as interface:
@@ -414,7 +454,7 @@ def create_interface():
414
  """
415
  <div class="header">
416
  <h1>🔍 Web Project Structure Analyzer</h1>
417
- <p>Selecione uma pasta e faça upload apenas dos arquivos essenciais do projeto</p>
418
  </div>
419
  """
420
  )
@@ -428,19 +468,18 @@ def create_interface():
428
 
429
  with gr.Group():
430
  gr.Markdown("""
431
- **📤 Como funciona:**
432
- 1. Clique no botão abaixo
433
- 2. Selecione a pasta do seu projeto
434
- 3. O sistema analisa a estrutura
435
- 4. **Apenas arquivos relevantes** são enviados
436
- 5. Veja a estrutura organizada
437
  """)
438
 
439
  folder_input = gr.File(
440
- label="Selecione a pasta do projeto",
441
  file_count="directory",
442
  type="filepath",
443
- height=100
444
  )
445
 
446
  with gr.Group():
@@ -461,20 +500,20 @@ def create_interface():
461
  size="lg"
462
  )
463
 
464
- with gr.Accordion("📋 O que será enviado", open=True):
465
  gr.Markdown("""
466
- **✅ INCLUÍDO (Arquivos Essenciais):**
467
- - Código fonte (.py, .js, .html, .css)
468
- - Arquivos de configuração
469
- - Documentação (.md, .txt)
470
- - Configurações de projeto
471
 
472
- **🚫 IGNORADO (Arquivos Pesados):**
473
- - node_modules, .git, venv
474
- - Arquivos de cache
475
- - Dependências
476
- - Logs e builds
477
- - Arquivos temporários
478
  """)
479
 
480
  with gr.Column(scale=2):
@@ -482,7 +521,7 @@ def create_interface():
482
 
483
  # Estatísticas
484
  stats_display = gr.Markdown(
485
- label="Estatísticas",
486
  elem_classes=["stats-card"]
487
  )
488
 
@@ -494,15 +533,6 @@ def create_interface():
494
  elem_classes=["structure-box"]
495
  )
496
 
497
- # Lista de arquivos para upload
498
- with gr.Group():
499
- gr.Markdown("### 📄 Arquivos para Upload")
500
- files_display = gr.File(
501
- label="Arquivos Relevantes Detectados",
502
- file_count="multiple",
503
- height=150
504
- )
505
-
506
  # Botões de ação
507
  with gr.Row():
508
  export_btn = gr.Button("💾 Exportar Relatório", variant="secondary")
@@ -517,7 +547,8 @@ def create_interface():
517
  choices=[
518
  ("React App", "react"),
519
  ("Django Project", "django"),
520
- ("Vue.js App", "vue")
 
521
  ],
522
  label="Selecione o tipo de projeto",
523
  value="react"
@@ -538,81 +569,69 @@ def create_interface():
538
  elem_classes=["structure-box"]
539
  )
540
 
541
- with gr.TabItem("ℹ️ Sobre", id=2):
542
  gr.Markdown("""
543
- ## 🎯 Sobre Esta Ferramenta
544
 
545
- ### 🔍 **Objetivo**
546
- Analisar a estrutura de projetos web enviando **apenas os arquivos essenciais**,
547
- ignorando dependências e arquivos desnecessários que tornam o upload pesado.
548
 
549
- ### ⚡ **Como Funciona**
550
- 1. **Seleção**: Você escolhe a pasta do projeto
551
- 2. **Análise**: Sistema escaneia a estrutura
552
- 3. **Filtragem**: Identifica arquivos relevantes
553
- 4. **Upload**: Envia apenas o essencial
554
- 5. **Visualização**: Mostra estrutura organizada
555
 
556
- ### 🚀 **Vantagens**
557
- - ✅ **Upload leve**: Apenas arquivos importantes
558
- - ✅ **Rápido**: Ignora pastas pesadas
559
- - ✅ **Inteligente**: Detecta automaticamente o que é relevante
560
- - ✅ **Organizado**: Estrutura clara com ícones
 
 
 
 
561
 
562
- ### 🛠️ **Tecnologias Reconhecidas**
563
- **Frontend**: HTML, CSS, JS, TS, Vue, React, Angular
564
- **Backend**: Python, PHP, Java, Node.js
565
- **Config**: JSON, YAML, TOML, XML
566
- **Docs**: Markdown, Texto
 
 
 
 
567
 
568
- ### 📊 **Estatísticas Incluídas**
569
- - Total de arquivos escaneados
570
- - Arquivos relevantes encontrados
571
- - Arquivos preparados para upload
572
- - Tamanho total do projeto
573
- - Taxa de relevância
574
  """)
575
 
576
  # Manipuladores de eventos
577
  def analyze_project_structure(folder_input, max_depth_value):
578
  """Analisa a estrutura do projeto"""
579
- if not folder_input:
580
- return (
581
- "**📁 Status**: Aguardando seleção de pasta...",
582
- "ℹ️ Selecione uma pasta do projeto para ver a estrutura aqui...",
583
- []
584
- )
585
-
586
- try:
587
- # No Gradio, folder_input é o caminho do arquivo quando file_count="directory"
588
- folder_path = folder_input[0] if isinstance(folder_input, list) else folder_input
589
-
590
- # Processa a pasta
591
- report, relevant_files, structure = analyzer.process_uploaded_folder(folder_path, max_depth_value)
592
-
593
- return report, structure, relevant_files
594
-
595
- except Exception as e:
596
- error_msg = f"❌ Erro ao analisar o projeto: {str(e)}"
597
- return error_msg, "", []
598
 
599
  # Quando uma pasta é selecionada OU configurações mudam
600
  folder_input.change(
601
  fn=analyze_project_structure,
602
  inputs=[folder_input, max_depth],
603
- outputs=[stats_display, output_structure, files_display]
604
  )
605
 
606
  max_depth.change(
607
  fn=analyze_project_structure,
608
  inputs=[folder_input, max_depth],
609
- outputs=[stats_display, output_structure, files_display]
610
  )
611
 
612
  analyze_btn.click(
613
  fn=analyze_project_structure,
614
  inputs=[folder_input, max_depth],
615
- outputs=[stats_display, output_structure, files_display]
616
  )
617
 
618
  # Manipuladores para Exemplos
@@ -629,7 +648,7 @@ def create_interface():
629
  # Exportação
630
  def export_report(structure):
631
  """Exporta estrutura como arquivo"""
632
- if not structure or structure.startswith("ℹ️"):
633
  return None
634
 
635
  try:
@@ -650,14 +669,14 @@ def create_interface():
650
  # Limpar
651
  def clear_analysis():
652
  return (
653
- "**📁 Status**: Aguardando seleção de pasta...",
654
- "ℹ️ Selecione uma pasta do projeto para ver a estrutura aqui...",
655
- []
656
  )
657
 
658
  clear_btn.click(
659
  fn=clear_analysis,
660
- outputs=[stats_display, output_structure, files_display]
661
  )
662
 
663
  # Carregar exemplo inicial
@@ -676,7 +695,7 @@ def create_interface():
676
  def main():
677
  """Função principal"""
678
  print("🚀 Iniciando Web Project Structure Analyzer...")
679
- print("📁 Modo: Upload Inteligente de Arquivos Essenciais")
680
 
681
  # Cria e inicia a interface
682
  interface = create_interface()
 
2
  import gradio as gr
3
  from pathlib import Path
4
  import tempfile
 
5
 
6
  class WebProjectAnalyzer:
7
  def __init__(self):
 
84
 
85
  return icon_map.get(ext, '📄')
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  def analyze_structure(self, root_path, max_depth=4):
88
  """Analisa a estrutura do projeto"""
89
+ if not root_path:
90
+ return "❌ Nenhuma pasta selecionada.", {"total_files": 0, "relevant_files": 0, "total_size": 0}, []
91
+
92
+ if not os.path.exists(root_path):
93
+ return "❌ Pasta não encontrada.", {"total_files": 0, "relevant_files": 0, "total_size": 0}, []
94
+
95
+ if not os.path.isdir(root_path):
96
+ return "❌ Por favor, selecione uma PASTA (não um arquivo).", {"total_files": 0, "relevant_files": 0, "total_size": 0}, []
97
+
98
  structure_output = []
99
+ relevant_files = []
100
  stats = {
101
  'total_files': 0,
102
  'relevant_files': 0,
 
129
  stats['total_files'] += 1
130
  if self.is_relevant_file(item):
131
  stats['relevant_files'] += 1
132
+ relevant_files.append(full_path)
133
 
134
  try:
135
  stats['total_size'] += os.path.getsize(full_path)
 
148
  structure_output.append(f"{indent}📁 {dir_name}/")
149
  analyze_directory(full_path, level + 1)
150
 
151
+ except PermissionError:
152
+ structure_output.append(f"{indent}🚫 [Permissão negada para acessar esta pasta]")
153
+ except Exception as e:
154
+ structure_output.append(f"{indent}⚠️ [Erro: {str(e)}]")
155
 
156
+ try:
157
+ analyze_directory(root_path)
158
+
159
+ if not structure_output:
160
+ return "ℹ️ Nenhum arquivo relevante encontrado na pasta selecionada.", stats, relevant_files
161
+
162
+ structure_text = '\n'.join(structure_output)
163
+ return structure_text, stats, relevant_files
164
+
165
+ except Exception as e:
166
+ return f"❌ Erro ao analisar a pasta: {str(e)}", stats, []
167
 
168
  def create_structure_report(self, folder_path, structure, stats, relevant_files):
169
  """Cria relatório completo da estrutura"""
 
173
 
174
  folder_name = os.path.basename(folder_path)
175
 
176
+ # Verifica se é um arquivo individual
177
+ if os.path.isfile(folder_path):
178
+ return "❌ ERRO: Você selecionou um ARQUIVO individual. Por favor, selecione uma PASTA completa do projeto."
179
+
180
  report = f"""
181
  📊 **ANÁLISE DO PROJETO**: `{folder_name}`
182
  📍 **Pasta**: {folder_path}
 
185
 
186
  • 📁 Total de arquivos escaneados: {total_files}
187
  • 📄 Arquivos relevantes encontrados: {relevant_files_count}
188
+ • 📤 Arquivos preparados para análise: {len(relevant_files)}
189
  • 💾 Tamanho total: {total_size / 1024 / 1024:.2f} MB
190
  • 🎯 Taxa de relevância: {(relevant_files_count/total_files*100) if total_files > 0 else 0:.1f}%
191
 
 
194
  {structure}
195
 
196
  💡 **INFORMAÇÕES**:
197
+ - ✅ Apenas arquivos essenciais são mostrados
198
+ - 🚫 Pastas como node_modules, .git são ignoradas
199
+ - 📄 Arquivos de configuração importantes são incluídos
200
+ - 🔒 Código fonte e documentação são priorizados
201
  """
202
  return report
203
 
204
+ def process_uploaded_folder(self, folder_input, max_depth=4):
205
  """Processa a pasta enviada e analisa sua estrutura"""
206
+ if not folder_input:
207
+ return "**📁 Status**: Aguardando seleção de pasta...", "ℹ️ Selecione uma PASTA do projeto para ver a estrutura aqui...", []
208
 
209
  try:
210
+ # No Gradio, folder_input é uma lista quando file_count="directory"
211
+ if isinstance(folder_input, list):
212
+ folder_path = folder_input[0]
213
+ else:
214
+ folder_path = folder_input
215
+
216
+ # Verifica se é um arquivo individual
217
+ if os.path.isfile(folder_path):
218
+ return (
219
+ "❌ **ERRO**: Você selecionou um ARQUIVO individual!\n\n**📌 Solução:**\n- Clique em '🗑️ Nova Análise'\n- Selecione uma PASTA completa do projeto\n- Não selecione arquivos individuais",
220
+ "❌ Por favor, selecione uma PASTA (não um arquivo individual)",
221
+ []
222
+ )
223
 
224
  # Analisa estrutura
225
+ structure, stats, relevant_files = self.analyze_structure(folder_path, max_depth)
226
 
227
  # Cria relatório
228
  report = self.create_structure_report(folder_path, structure, stats, relevant_files)
229
 
230
+ return report, structure, relevant_files
 
 
 
 
 
231
 
232
  except Exception as e:
233
+ error_msg = f"❌ Erro ao processar: {str(e)}"
234
+ return error_msg, "", []
235
 
236
  def analyze_demo_projects(self, project_type):
237
  """Fornece exemplos de estruturas de projetos"""
 
336
  📄 index.html
337
  📄 package.json
338
  📄 vue.config.js
339
+ 📄 README.md
340
+ """,
341
+
342
+ "nodejs": """
343
+ meu-app-nodejs/
344
+ 📁 src/
345
+ 📁 controllers/
346
+ 📄 userController.js
347
+ 📄 productController.js
348
+ 📁 models/
349
+ 📄 User.js
350
+ 📄 Product.js
351
+ 📁 routes/
352
+ 📄 auth.js
353
+ 📄 users.js
354
+ 📄 products.js
355
+ 📁 middleware/
356
+ 📄 auth.js
357
+ 📄 validation.js
358
+ 📁 utils/
359
+ 📄 database.js
360
+ 📄 logger.js
361
+ 📄 app.js
362
+ 📄 server.js
363
+ 📁 config/
364
+ 📄 database.js
365
+ 📄 environment.js
366
+ 📁 tests/
367
+ 📄 user.test.js
368
+ 📄 product.test.js
369
+ 📄 package.json
370
+ 📄 .env.example
371
  📄 README.md
372
  """
373
  }
 
378
 
379
  {demos[project_type]}
380
 
381
+ 💡 **Como funcionaria com uma pasta real:**
382
  - 📁 Pasta selecionada: `meu-app-{project_type}/`
383
+ - 📄 Arquivos relevantes detectados: ~15-30 arquivos
384
+ - 🎯 Apenas código e configurações seriam analisados
385
  - 🚫 node_modules, .git, cache seriam ignorados
386
  """
387
  else:
 
433
  border: 1px solid #dee2e6;
434
  margin: 10px 0;
435
  }
436
+ .error-box {
437
+ background: #ffe6e6;
438
+ border: 2px solid #ff4444;
 
439
  padding: 15px;
440
  border-radius: 8px;
441
+ margin: 10px 0;
442
+ }
443
+ .success-box {
444
+ background: #e6ffe6;
445
+ border: 2px solid #44ff44;
446
+ padding: 15px;
447
+ border-radius: 8px;
448
+ margin: 10px 0;
449
  }
450
  """
451
  ) as interface:
 
454
  """
455
  <div class="header">
456
  <h1>🔍 Web Project Structure Analyzer</h1>
457
+ <p>Selecione uma PASTA completa do projeto para analisar sua estrutura</p>
458
  </div>
459
  """
460
  )
 
468
 
469
  with gr.Group():
470
  gr.Markdown("""
471
+ **📤 IMPORTANTE:**
472
+ - ✅ Selecione uma **PASTA COMPLETA** do projeto
473
+ - ❌ Não selecione arquivos individuais
474
+ - 🔍 O sistema analisará a estrutura automaticamente
475
+ - 🚫 Pastas pesadas serão ignoradas
 
476
  """)
477
 
478
  folder_input = gr.File(
479
+ label="Clique aqui para selecionar uma PASTA do projeto",
480
  file_count="directory",
481
  type="filepath",
482
+ height=120
483
  )
484
 
485
  with gr.Group():
 
500
  size="lg"
501
  )
502
 
503
+ with gr.Accordion("📋 O que será analisado", open=True):
504
  gr.Markdown("""
505
+ **✅ ARQUIVOS INCLUÍDOS:**
506
+ - 🐍 Código fonte (.py, .js, .html, .css)
507
+ - ⚙️ Arquivos de configuração
508
+ - 📖 Documentação (.md, .txt)
509
+ - 🛠️ Configurações de projeto
510
 
511
+ **🚫 ARQUIVOS IGNORADOS:**
512
+ - 📦 node_modules, .git, venv
513
+ - 🗑️ Arquivos de cache
514
+ - 🔧 Dependências
515
+ - 📊 Logs e builds
516
+ - ⏰ Arquivos temporários
517
  """)
518
 
519
  with gr.Column(scale=2):
 
521
 
522
  # Estatísticas
523
  stats_display = gr.Markdown(
524
+ label="Estatísticas da Análise",
525
  elem_classes=["stats-card"]
526
  )
527
 
 
533
  elem_classes=["structure-box"]
534
  )
535
 
 
 
 
 
 
 
 
 
 
536
  # Botões de ação
537
  with gr.Row():
538
  export_btn = gr.Button("💾 Exportar Relatório", variant="secondary")
 
547
  choices=[
548
  ("React App", "react"),
549
  ("Django Project", "django"),
550
+ ("Vue.js App", "vue"),
551
+ ("Node.js API", "nodejs")
552
  ],
553
  label="Selecione o tipo de projeto",
554
  value="react"
 
569
  elem_classes=["structure-box"]
570
  )
571
 
572
+ with gr.TabItem("ℹ️ Ajuda", id=2):
573
  gr.Markdown("""
574
+ ## 🆘 Guia de Uso - Como Selecionar Pastas
575
 
576
+ ### ❌ **ERRO COMUM:**
577
+ **Problema**: "Permissão negada" ou "0 arquivos encontrados"
578
+ **Causa**: Selecionou um arquivo individual em vez de uma pasta
579
 
580
+ ### ✅ **SOLUÇÃO CORRETA:**
581
+ 1. **Clique em "Selecionar Pasta"**
582
+ 2. **Navegue até a pasta do seu projeto**
583
+ 3. **Selecione a PASTA (ex: "meu-projeto-react")**
584
+ 4. **Não selecione arquivos dentro da pasta**
 
585
 
586
+ ### 📁 **EXEMPLO CORRETO:**
587
+ ```
588
+ minha-pasta-projetos/
589
+ └── 📁 meu-app-react/ ← SELECIONE ESTA PASTA!
590
+ ├── 📁 src/
591
+ ├── 📁 public/
592
+ ├── 📄 package.json
593
+ └── 📄 README.md
594
+ ```
595
 
596
+ ### 🚫 **EXEMPLO INCORRETO:**
597
+ ```
598
+ minha-pasta-projetos/
599
+ └── 📁 meu-app-react/
600
+ ├── 📁 src/
601
+ ├── 📁 public/
602
+ ├── 📄 package.json ← NÃO SELECIONE ESTE ARQUIVO!
603
+ └── 📄 README.md
604
+ ```
605
 
606
+ ### 🔧 **SE TIVER DIFICULDADE:**
607
+ - Use a aba "📚 Exemplos" para ver estruturas
608
+ - Certifique-se de selecionar a pasta raiz do projeto
609
+ - Projetos React: selecione a pasta com package.json
610
+ - Projetos Python: selecione a pasta com manage.py ou app.py
 
611
  """)
612
 
613
  # Manipuladores de eventos
614
  def analyze_project_structure(folder_input, max_depth_value):
615
  """Analisa a estrutura do projeto"""
616
+ return analyzer.process_uploaded_folder(folder_input, max_depth_value)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617
 
618
  # Quando uma pasta é selecionada OU configurações mudam
619
  folder_input.change(
620
  fn=analyze_project_structure,
621
  inputs=[folder_input, max_depth],
622
+ outputs=[stats_display, output_structure, gr.File(visible=False)]
623
  )
624
 
625
  max_depth.change(
626
  fn=analyze_project_structure,
627
  inputs=[folder_input, max_depth],
628
+ outputs=[stats_display, output_structure, gr.File(visible=False)]
629
  )
630
 
631
  analyze_btn.click(
632
  fn=analyze_project_structure,
633
  inputs=[folder_input, max_depth],
634
+ outputs=[stats_display, output_structure, gr.File(visible=False)]
635
  )
636
 
637
  # Manipuladores para Exemplos
 
648
  # Exportação
649
  def export_report(structure):
650
  """Exporta estrutura como arquivo"""
651
+ if not structure or structure.startswith("ℹ️") or structure.startswith("❌"):
652
  return None
653
 
654
  try:
 
669
  # Limpar
670
  def clear_analysis():
671
  return (
672
+ "**📁 Status**: Aguardando seleção de pasta...\n\n**💡 Dica**: Selecione a pasta COMPLETA do projeto (não arquivos individuais)",
673
+ "ℹ️ A estrutura do projeto aparecerá aqui após a seleção...",
674
+ gr.File(visible=False)
675
  )
676
 
677
  clear_btn.click(
678
  fn=clear_analysis,
679
+ outputs=[stats_display, output_structure, gr.File(visible=False)]
680
  )
681
 
682
  # Carregar exemplo inicial
 
695
  def main():
696
  """Função principal"""
697
  print("🚀 Iniciando Web Project Structure Analyzer...")
698
+ print("📁 Modo: Análise de Pastas Completas")
699
 
700
  # Cria e inicia a interface
701
  interface = create_interface()