docs-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
limpa_csv.py ADDED
@@ -0,0 +1,170 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Script para limpeza do arquivo qadata.csv
5
+ Remove linhas com respostas inválidas especificadas
6
+
7
+ Autor: Paulo Duarte
8
+ Data: 2025-05-30
9
+ """
10
+
11
+ import pandas as pd
12
+ import os
13
+ from pathlib import Path
14
+
15
+ def clean_csv_data(input_file, output_file=None):
16
+ """
17
+ Remove linhas com padrões de respostas inválidas do CSV
18
+
19
+ Args:
20
+ input_file (str): Caminho para o arquivo CSV de entrada
21
+ output_file (str, optional): Caminho para o arquivo CSV de saída
22
+
23
+ Returns:
24
+ dict: Estatísticas do processamento
25
+ """
26
+
27
+ # Definir padrões de respostas inválidas
28
+ invalid_patterns = [
29
+ "Please select from dropdown",
30
+ "1 2 3 4 5 Enter filename Enter filename Enter filename Enter filename Enter filename",
31
+ "Enter filename Enter filename Enter filename Enter filename Enter filename",
32
+ "1 2 3 4 5 6 7 8 9 10",
33
+ "Use + or - signs on the left to Expand or collapse Static Entitlement Assignment Policies Dynamic Entitlement Assignment Policies SOD Policies Enter filename Enter filename Enter filename Enter filename Enter filename"
34
+ ]
35
+
36
+ try:
37
+ # Ler o arquivo CSV
38
+ print(f"📖 Lendo arquivo: {input_file}")
39
+ df = pd.read_csv(input_file, encoding='utf-8')
40
+
41
+ print(f"✅ Arquivo carregado com sucesso!")
42
+ print(f"📊 Linhas originais: {len(df)}")
43
+ print(f"📋 Colunas: {list(df.columns)}")
44
+
45
+ # Criar cópia para trabalhar
46
+ df_clean = df.copy()
47
+
48
+ # Contador de linhas removidas por padrão
49
+ removal_stats = {}
50
+ total_removed = 0
51
+
52
+ # Remover linhas que contêm os padrões inválidos
53
+ for pattern in invalid_patterns:
54
+ # Encontrar linhas que contêm o padrão
55
+ mask = df_clean['response'].astype(str).str.contains(pattern, na=False)
56
+ rows_with_pattern = mask.sum()
57
+
58
+ if rows_with_pattern > 0:
59
+ # Remover as linhas
60
+ df_clean = df_clean[~mask]
61
+ removal_stats[pattern[:50] + "..."] = rows_with_pattern
62
+ total_removed += rows_with_pattern
63
+ print(f"🗑️ Removidas {rows_with_pattern} linhas com padrão: '{pattern[:50]}...'")
64
+
65
+ # Gerar nome do arquivo de saída se não fornecido
66
+ if output_file is None:
67
+ input_path = Path(input_file)
68
+ output_file = input_path.parent / f"{input_path.stem}_clean{input_path.suffix}"
69
+
70
+ # Salvar arquivo limpo
71
+ df_clean.to_csv(output_file, index=False, encoding='utf-8')
72
+ print(f"💾 Arquivo limpo salvo: {output_file}")
73
+
74
+ # Preparar estatísticas
75
+ stats = {
76
+ 'original_rows': len(df),
77
+ 'removed_rows': total_removed,
78
+ 'final_rows': len(df_clean),
79
+ 'removal_rate': (total_removed / len(df)) * 100,
80
+ 'removal_details': removal_stats,
81
+ 'output_file': str(output_file)
82
+ }
83
+
84
+ return stats
85
+
86
+ except FileNotFoundError:
87
+ print(f"❌ Erro: Arquivo '{input_file}' não encontrado!")
88
+ return None
89
+ except Exception as e:
90
+ print(f"❌ Erro durante o processamento: {str(e)}")
91
+ return None
92
+
93
+ def print_summary(stats):
94
+ """
95
+ Imprime um resumo formatado das estatísticas
96
+
97
+ Args:
98
+ stats (dict): Estatísticas do processamento
99
+ """
100
+ if not stats:
101
+ return
102
+
103
+ print("\n" + "="*60)
104
+ print("📊 RESUMO DO PROCESSAMENTO")
105
+ print("="*60)
106
+ print(f"📈 Total de linhas originais: {stats['original_rows']:,}")
107
+ print(f"🗑️ Linhas removidas: {stats['removed_rows']:,}")
108
+ print(f"✅ Linhas no arquivo limpo: {stats['final_rows']:,}")
109
+ print(f"📉 Taxa de remoção: {stats['removal_rate']:.1f}%")
110
+ print(f"💾 Arquivo de saída: {stats['output_file']}")
111
+
112
+ if stats['removal_details']:
113
+ print("\n📋 DETALHES DAS REMOÇÕES:")
114
+ print("-" * 50)
115
+ for pattern, count in stats['removal_details'].items():
116
+ print(f" • {count:2d}x: {pattern}")
117
+
118
+ print("="*60)
119
+ print("✨ Processamento concluído com sucesso!")
120
+
121
+ def main():
122
+ """
123
+ Função principal do script
124
+ """
125
+ print("🧹 CSV Cleaner - Limpeza de Dados QA")
126
+ print("="*50)
127
+
128
+ # Configurar arquivos
129
+ input_file = "data.csv"
130
+
131
+ # Verificar se o arquivo existe
132
+ if not os.path.exists(input_file):
133
+ print(f"❌ Arquivo '{input_file}' não encontrado no diretório atual!")
134
+ print("💡 Certifique-se de que o arquivo está no mesmo diretório do script.")
135
+ return
136
+
137
+ # Processar o arquivo
138
+ stats = clean_csv_data(input_file)
139
+
140
+ # Mostrar resumo
141
+ if stats:
142
+ print_summary(stats)
143
+ else:
144
+ print("❌ Falha no processamento do arquivo!")
145
+
146
+ def cli_main(): # Nova main para CLI
147
+ import argparse
148
+ import os # Para os.path.exists
149
+ import sys # Para sys.exit
150
+ parser = argparse.ArgumentParser(description="Limpa um arquivo CSV de Q&A removendo padrões inválidos.")
151
+ parser.add_argument("input_file", help="Caminho para o arquivo CSV de entrada.")
152
+ parser.add_argument("output_file", help="Caminho para salvar o arquivo CSV limpo.")
153
+ args = parser.parse_args()
154
+
155
+ print("🧹 CSV Cleaner - Limpeza de Dados QA")
156
+ print("="*50)
157
+ if not os.path.exists(args.input_file):
158
+ print(f"❌ Arquivo '{args.input_file}' não encontrado no diretório atual!")
159
+ sys.exit(1)
160
+
161
+ stats = clean_csv_data(args.input_file, args.output_file) # Passa ambos os argumentos
162
+ if stats:
163
+ print_summary(stats)
164
+ else:
165
+ print("❌ Falha no processamento do arquivo!")
166
+ sys.exit(1)
167
+
168
+ if __name__ == "__main__":
169
+ # from pathlib import Path # Mantenha se Path for usado em clean_csv_data
170
+ cli_main()
merge_markdown.py ADDED
@@ -0,0 +1,91 @@
1
+ import os
2
+ import glob
3
+ from pathlib import Path
4
+
5
+ def consolidate_markdown_files(input_directory, output_file):
6
+ """
7
+ Consolida todos os arquivos .md de um diretório em um único arquivo.
8
+
9
+ Args:
10
+ input_directory (str): Caminho para o diretório com os arquivos .md
11
+ output_file (str): Nome do arquivo de saída consolidado
12
+ """
13
+
14
+ # Caminho completo do diretório
15
+ docs_path = Path(input_directory)
16
+
17
+ if not docs_path.exists():
18
+ print(f"Erro: O diretório '{input_directory}' não foi encontrado.")
19
+ return
20
+
21
+ # Busca todos os arquivos .md recursivamente
22
+ md_files = list(docs_path.rglob('*.md'))
23
+
24
+ if not md_files:
25
+ print("Nenhum arquivo .md encontrado no diretório especificado.")
26
+ return
27
+
28
+ print(f"Encontrados {len(md_files)} arquivos Markdown.")
29
+
30
+ # Ordena os arquivos por caminho para manter consistência
31
+ md_files.sort(key=lambda x: str(x))
32
+
33
+ with open(output_file, 'w', encoding='utf-8') as consolidated_file:
34
+ # Cabeçalho do documento consolidado
35
+ consolidated_file.write("# Corpus Consolidada\n\n")
36
+ consolidated_file.write("---\n\n")
37
+
38
+ for md_file in md_files:
39
+ try:
40
+ # Caminho relativo para melhor organização
41
+ relative_path = md_file.relative_to(docs_path)
42
+
43
+ # Adiciona separador e título da seção
44
+ consolidated_file.write(f"\n\n## Arquivo: {relative_path}\n\n")
45
+ consolidated_file.write("---\n\n")
46
+
47
+ # Lê e adiciona o conteúdo do arquivo
48
+ with open(md_file, 'r', encoding='utf-8') as current_file:
49
+ content = current_file.read()
50
+ consolidated_file.write(content)
51
+ consolidated_file.write("\n\n")
52
+
53
+ print(f"Processado: {relative_path}")
54
+
55
+ except Exception as e:
56
+ print(f"Erro ao processar {md_file}: {str(e)}")
57
+
58
+ print(f"\nConsolidação concluída! Arquivo salvo como: {output_file}")
59
+
60
+ # Estatísticas do arquivo gerado
61
+ with open(output_file, 'r', encoding='utf-8') as f:
62
+ lines = len(f.readlines())
63
+ f.seek(0)
64
+ chars = len(f.read())
65
+
66
+ print(f"Estatísticas do arquivo consolidado:")
67
+ print(f"- Linhas: {lines:,}")
68
+ print(f"- Caracteres: {chars:,}")
69
+
70
+ def main():
71
+ # Configuração dos caminhos
72
+ input_dir = r"docs" # Diretório onde estão os arquivos .md
73
+ output_file = "corpus_consolidated.md"
74
+
75
+ print("Iniciando consolidação do seu corpus...")
76
+ print(f"Diretório de origem: {input_dir}")
77
+ print(f"Arquivo de destino: {output_file}")
78
+ print("-" * 50)
79
+
80
+ consolidate_markdown_files(input_dir, output_file)
81
+
82
+ def cli_main():
83
+ import argparse
84
+ parser = argparse.ArgumentParser(description="Consolida arquivos .md de um diretório em um único arquivo.")
85
+ parser.add_argument("input_directory", help="Caminho para o diretório com os arquivos .md")
86
+ parser.add_argument("output_file", help="Nome do arquivo de saída consolidado (ex: corpus_consolidated.md)")
87
+ args = parser.parse_args()
88
+ consolidate_markdown_files(args.input_directory, args.output_file)
89
+
90
+ if __name__ == "__main__":
91
+ cli_main() # Chame a nova main