-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcogctl.py
More file actions
180 lines (142 loc) · 6.3 KB
/
Copy pathcogctl.py
File metadata and controls
180 lines (142 loc) · 6.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
cogctl.py
---------
CLI mínima para orquestar los distintos módulos de la suite cognitiva.
Implementa subcomandos mediante el módulo estándar ``argparse`` para
eliminar dependencias externas como ``typer``. Los comandos disponibles
son:
- ``init`` → Crear la estructura básica de carpetas.
- ``ingest`` → Ingerir un archivo específico mediante el módulo de ingesta.
- ``analyze`` → Ejecutar el pipeline de análisis sobre los textos ingeridos.
- ``deploy`` → Levantar los servicios definidos en ``docker-compose.yml``.
- ``status`` → Mostrar el estado de los contenedores Docker.
- ``verify`` → Validar el progreso de un Lab (evidencia y seguridad).
Uso:
```
python cogctl.py init
python cogctl.py ingest nombre_archivo.ext
python cogctl.py analyze
python cogctl.py deploy
python cogctl.py status
```
"""
import argparse
import subprocess
import sys
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
INPUT_DIR = BASE_DIR / 'data' / 'input'
RAW_DIR = BASE_DIR / 'outputs' / 'raw'
INSIGHTS_DIR = BASE_DIR / 'outputs' / 'insights'
def cmd_init(args: argparse.Namespace) -> None:
"""Inicializa la estructura de carpetas requerida."""
for p in [INPUT_DIR, RAW_DIR, INSIGHTS_DIR]:
p.mkdir(parents=True, exist_ok=True)
print('📁 Estructura creada: data/input, outputs/raw, outputs/insights')
def cmd_ingest(args: argparse.Namespace) -> None:
"""Ingesta un archivo individual mediante el módulo ``ingestor``."""
target = INPUT_DIR / args.file
if not target.exists():
print(f'❌ Archivo no encontrado: {args.file}')
raise SystemExit(1)
RAW_DIR.mkdir(parents=True, exist_ok=True)
print(f'📥 Ingestando: {args.file}...')
try:
subprocess.run([
sys.executable,
str(BASE_DIR / 'ingestor' / 'ingest.py'),
str(target),
'--output',
str(RAW_DIR)
], check=True) # Removed capture_output=True to show errors
# Output file will be .txt, not the original extension
output_file = RAW_DIR / Path(args.file).with_suffix('.txt').name
print(f'✅ Ingesta completada: {output_file}')
except subprocess.CalledProcessError as e:
print(f'❌ Error en la ingesta: {e}')
raise SystemExit(1)
def cmd_analyze(args: argparse.Namespace) -> None:
"""Ejecuta el análisis cognitivo sobre los textos ingeridos."""
INSIGHTS_DIR.mkdir(parents=True, exist_ok=True)
try:
subprocess.run([
sys.executable,
str(BASE_DIR / 'pipeline' / 'analyze.py'),
'--input', str(RAW_DIR),
'--output', str(INSIGHTS_DIR / 'analysis.json'),
'--schema', str(BASE_DIR / 'schemas' / 'insight.schema.json')
], check=True)
except subprocess.CalledProcessError as e:
print(f'❌ Error en el análisis: {e}')
raise SystemExit(1)
def cmd_deploy(args: argparse.Namespace) -> None:
"""Despliega los servicios definidos en docker-compose."""
print('🚀 Desplegando servicios...')
subprocess.run(['docker-compose', 'up', '-d'], check=True)
def cmd_status(args: argparse.Namespace) -> None:
"""Muestra el estado actual de los contenedores Docker."""
subprocess.run(['docker', 'ps'], check=True)
def cmd_verify(args: argparse.Namespace) -> None:
"""Valida la evidencia generada durante un Lab."""
print("🔍 Validando Lab 01 - Línea base de pipeline seguro...")
# Check analysis.json
analysis_file = INSIGHTS_DIR / 'analysis.json'
if not analysis_file.exists():
print("❌ ERROR: No se encontró 'analysis.json'. ¿Has ejecutado 'python cogctl.py analyze'?")
return
import json
try:
data = json.loads(analysis_file.read_text(encoding='utf-8'))
if not data:
print("⚠️ ADVERTENCIA: 'analysis.json' está vacío. No hay archivos procesados.")
else:
print(f"✅ 'analysis.json' encontrado con {len(data)} registros.")
# Check for redaction
redacted_count = sum(1 for r in data if r.get('redacted'))
if redacted_count > 0:
print(f"✅ Seguridad: {redacted_count} registros están correctamente REDACTADOS.")
else:
print("⚠️ Seguridad: Ningún registro está redactado. Prueba con $env:COGNITIVE_REDACT='1' para pasar el Lab en modo 'Secure'.")
# Check for entities (AI Power-ups)
if any(r.get('entities') for r in data):
print("✅ IA: Se han detectado entidades mediante spaCy.")
else:
print("⚠️ IA: No se han detectado entidades. ¿Has instalado spaCy y su modelo de español?")
except Exception as e:
print(f"❌ ERROR: Fallo al leer la evidencia: {e}")
return
print("\n🎉 Si ves checks verdes, ¡has completado los requisitos técnicos del Lab 01!")
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description='Cognitive GitOps Suite CLI')
subparsers = parser.add_subparsers(title='comandos', dest='command')
# init
parser_init = subparsers.add_parser('init', help='Inicializa la estructura de carpetas')
parser_init.set_defaults(func=cmd_init)
# ingest
parser_ingest = subparsers.add_parser('ingest', help='Ingesta un archivo desde data/input')
parser_ingest.add_argument('file', help='Nombre del archivo en data/input a ingerir')
parser_ingest.set_defaults(func=cmd_ingest)
# analyze
parser_analyze = subparsers.add_parser('analyze', help='Ejecuta el análisis cognitivo')
parser_analyze.set_defaults(func=cmd_analyze)
# deploy
parser_deploy = subparsers.add_parser('deploy', help='Despliega servicios con docker-compose')
parser_deploy.set_defaults(func=cmd_deploy)
# status
parser_status = subparsers.add_parser('status', help='Muestra el estado de los contenedores')
parser_status.set_defaults(func=cmd_status)
# verify
parser_verify = subparsers.add_parser('verify', help='Valida el progreso del Lab')
parser_verify.set_defaults(func=cmd_verify)
return parser
def main() -> None:
parser = build_parser()
args = parser.parse_args()
if not hasattr(args, 'func'):
parser.print_help()
return
args.func(args)
if __name__ == '__main__':
main()