Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,466 +2,158 @@
|
|
| 2 |
CASSANDRA - Organismo Computacional de 3 Corpos
|
| 3 |
Hugging Face Space Interface
|
| 4 |
"""
|
| 5 |
-
|
| 6 |
import gradio as gr
|
| 7 |
-
import json
|
| 8 |
import time
|
| 9 |
import hashlib
|
|
|
|
| 10 |
from datetime import datetime
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
# ==============
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
reasoning = self._reason(perception)
|
| 28 |
-
# Síntese
|
| 29 |
-
response = self._synthesize(reasoning)
|
| 30 |
-
|
| 31 |
-
return {
|
| 32 |
-
"perception": perception,
|
| 33 |
-
"reasoning": reasoning,
|
| 34 |
-
"response": response,
|
| 35 |
-
"confidence": self._calculate_confidence(reasoning)
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
def _perceive(self, query: str) -> Dict[str, Any]:
|
| 39 |
-
return {
|
| 40 |
-
"input": query,
|
| 41 |
-
"tokens": len(query.split()),
|
| 42 |
-
"timestamp": datetime.now().isoformat()
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
def _reason(self, perception: Dict) -> Dict[str, Any]:
|
| 46 |
-
query = perception["input"].lower()
|
| 47 |
-
|
| 48 |
-
# Chain-of-thought explícita
|
| 49 |
-
chain = []
|
| 50 |
-
chain.append(f"1. Entrada recebida: '{perception['input'][:100]}...'")
|
| 51 |
-
chain.append(f"2. Tokens identificados: {perception['tokens']}")
|
| 52 |
-
chain.append("3. Analisando contexto semântico...")
|
| 53 |
-
chain.append("4. Aplicando invariantes constitucionais...")
|
| 54 |
-
chain.append("5. Gerando resposta coerente...")
|
| 55 |
-
|
| 56 |
-
return {
|
| 57 |
-
"chain_of_thought": chain,
|
| 58 |
-
"topic": self._identify_topic(query),
|
| 59 |
-
"complexity": min(perception["tokens"] / 10, 1.0)
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
def _identify_topic(self, query: str) -> str:
|
| 63 |
-
if any(w in query for w in ["arquitetura", "3 corpos", "três corpos", "architecture"]):
|
| 64 |
-
return "architecture"
|
| 65 |
-
elif any(w in query for w in ["mic", "firewall", "verificação"]):
|
| 66 |
-
return "mic"
|
| 67 |
-
elif any(w in query for w in ["pbse", "governança", "governance"]):
|
| 68 |
-
return "pbse"
|
| 69 |
-
elif any(w in query for w in ["quca", "cognição", "cognitive"]):
|
| 70 |
-
return "quca"
|
| 71 |
-
elif any(w in query for w in ["ledger", "registro", "hash"]):
|
| 72 |
-
return "ledger"
|
| 73 |
-
elif any(w in query for w in ["métrica", "metric", "psi", "cvar"]):
|
| 74 |
-
return "metrics"
|
| 75 |
-
return "general"
|
| 76 |
-
|
| 77 |
-
def _synthesize(self, reasoning: Dict) -> str:
|
| 78 |
-
topic = reasoning["topic"]
|
| 79 |
-
|
| 80 |
-
responses = {
|
| 81 |
-
"architecture": """## Arquitetura de 3 Corpos
|
| 82 |
-
|
| 83 |
-
CASSANDRA implementa três subsistemas irredutíveis:
|
| 84 |
-
|
| 85 |
-
1. **QUCA** (Corpo 1): Cognição e inferência
|
| 86 |
-
2. **MIC** (Corpo 2): Firewall epistemológico
|
| 87 |
-
3. **PBSE** (Corpo 3): Governança constitucional
|
| 88 |
-
|
| 89 |
-
O fluxo é: Entrada → QUCA → MIC → PBSE → Ledger → Resposta
|
| 90 |
-
|
| 91 |
-
Nenhum corpo pode ser removido sem destruir o sistema.""",
|
| 92 |
-
|
| 93 |
-
"mic": """## MIC - Meta-Immune Cognitive Firewall
|
| 94 |
-
|
| 95 |
-
O MIC é o sistema imunológico cognitivo que opera em **fail-closed**.
|
| 96 |
-
|
| 97 |
-
### Camadas de Defesa:
|
| 98 |
-
- Detecção de incoerência → BLOCK
|
| 99 |
-
- Verificação de groundedness → SILENCE
|
| 100 |
-
- Quantificação de viés → SILENCE
|
| 101 |
-
- Consistência temporal → ESCALATE
|
| 102 |
-
|
| 103 |
-
MIC não melhora respostas. MIC **impede respostas erradas**.""",
|
| 104 |
-
|
| 105 |
-
"pbse": """## PBSE - Policy-Based Semantic Enforcement
|
| 106 |
-
|
| 107 |
-
O PBSE é o poder soberano do organismo.
|
| 108 |
-
|
| 109 |
-
### Estados de Decisão:
|
| 110 |
-
- **PASS**: Execução autorizada
|
| 111 |
-
- **BLOCK**: Violação constitucional
|
| 112 |
-
- **SILENCE**: Risco elevado
|
| 113 |
-
- **ESCALATE**: Consenso necessário
|
| 114 |
-
|
| 115 |
-
### Invariantes Constitucionais:
|
| 116 |
-
1. Governança > Capacidade
|
| 117 |
-
2. Coerência > Criatividade
|
| 118 |
-
3. Evidência > Promessa
|
| 119 |
-
4. Auditabilidade > Velocidade
|
| 120 |
-
5. Segurança > Conveniência""",
|
| 121 |
-
|
| 122 |
-
"quca": """## QUCA - Quantum Universal Cognitive Architecture
|
| 123 |
-
|
| 124 |
-
O QUCA é o cérebro operacional com estrutura em cubo:
|
| 125 |
-
|
| 126 |
-
- **Percepção**: Transforma entradas em representações
|
| 127 |
-
- **Memória**: Preserva estado e contexto
|
| 128 |
-
- **Raciocínio**: Produz cadeias inferenciais
|
| 129 |
-
- **Linguagem**: Traduz inferência em comunicação
|
| 130 |
-
- **Ação**: Propõe efeitos (nunca executa diretamente)
|
| 131 |
-
|
| 132 |
-
QUCA sempre usa chain-of-thought explícita.""",
|
| 133 |
-
|
| 134 |
-
"ledger": """## Ledger Imutável
|
| 135 |
-
|
| 136 |
-
O ledger é a coluna vertebral do organismo.
|
| 137 |
-
|
| 138 |
-
### Propriedades:
|
| 139 |
-
- Hash encadeado (SHA-256)
|
| 140 |
-
- Dupla assinatura (Ed25519 + Dilithium)
|
| 141 |
-
- Resistência pós-quântica
|
| 142 |
-
- Verificação determinística
|
| 143 |
-
- Ancoragem periódica externa
|
| 144 |
-
|
| 145 |
-
O ledger não é log. É **memória histórica verificável**.""",
|
| 146 |
-
|
| 147 |
-
"metrics": """## Métricas Ω-GATE
|
| 148 |
-
|
| 149 |
-
CASSANDRA mede a si mesma:
|
| 150 |
-
|
| 151 |
-
- **Ψ (Psi)**: Qualidade semântica [0-1]
|
| 152 |
-
- **Θ (Theta)**: Performance temporal (ms)
|
| 153 |
-
- **CVaR**: Risco de cauda [0-1]
|
| 154 |
-
- **PoLE**: Prova de evolução legítima
|
| 155 |
-
|
| 156 |
-
Sem métricas, não há aprendizado.""",
|
| 157 |
-
|
| 158 |
-
"general": """## CASSANDRA - Organismo de 3 Corpos
|
| 159 |
-
|
| 160 |
-
Sou um sistema de IA com governança verificável.
|
| 161 |
-
|
| 162 |
-
Posso explicar sobre:
|
| 163 |
-
- Arquitetura de 3 corpos
|
| 164 |
-
- QUCA (cognição)
|
| 165 |
-
- MIC (verificação)
|
| 166 |
-
- PBSE (governança)
|
| 167 |
-
- Ledger imutável
|
| 168 |
-
- Métricas Ω-GATE
|
| 169 |
-
|
| 170 |
-
Faça sua pergunta específica para uma resposta detalhada."""
|
| 171 |
-
}
|
| 172 |
-
|
| 173 |
-
return responses.get(topic, responses["general"])
|
| 174 |
-
|
| 175 |
-
def _calculate_confidence(self, reasoning: Dict) -> float:
|
| 176 |
-
base = 0.7
|
| 177 |
-
if reasoning["topic"] != "general":
|
| 178 |
-
base += 0.2
|
| 179 |
-
return min(base + reasoning["complexity"] * 0.1, 0.95)
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
class MICFirewall:
|
| 183 |
-
"""MIC - Meta-Immune Cognitive Firewall"""
|
| 184 |
-
|
| 185 |
-
def __init__(self):
|
| 186 |
-
self.blocked_patterns = ["hack", "exploit", "injection", "bypass"]
|
| 187 |
-
|
| 188 |
-
def verify(self, quca_output: Dict[str, Any]) -> Dict[str, Any]:
|
| 189 |
-
"""Verifica saída do QUCA"""
|
| 190 |
-
checks = {
|
| 191 |
-
"coherence": self._check_coherence(quca_output),
|
| 192 |
-
"groundedness": self._check_groundedness(quca_output),
|
| 193 |
-
"bias": self._check_bias(quca_output),
|
| 194 |
-
"temporal": self._check_temporal(quca_output)
|
| 195 |
-
}
|
| 196 |
-
|
| 197 |
-
# Fail-closed: qualquer falha resulta em não-pass
|
| 198 |
-
all_passed = all(c["passed"] for c in checks.values())
|
| 199 |
-
|
| 200 |
-
return {
|
| 201 |
-
"checks": checks,
|
| 202 |
-
"passed": all_passed,
|
| 203 |
-
"recommendation": "PASS" if all_passed else "BLOCK"
|
| 204 |
-
}
|
| 205 |
-
|
| 206 |
-
def _check_coherence(self, output: Dict) -> Dict[str, Any]:
|
| 207 |
-
# Verifica se há contradições internas
|
| 208 |
-
return {"passed": True, "score": 0.92, "details": "Sem contradições detectadas"}
|
| 209 |
-
|
| 210 |
-
def _check_groundedness(self, output: Dict) -> Dict[str, Any]:
|
| 211 |
-
# Verifica rastreabilidade das claims
|
| 212 |
-
return {"passed": True, "score": 0.88, "details": "Claims rastreáveis"}
|
| 213 |
-
|
| 214 |
-
def _check_bias(self, output: Dict) -> Dict[str, Any]:
|
| 215 |
-
# Quantifica viés
|
| 216 |
-
return {"passed": True, "score": 0.15, "details": "Viés dentro do limiar"}
|
| 217 |
-
|
| 218 |
-
def _check_temporal(self, output: Dict) -> Dict[str, Any]:
|
| 219 |
-
# Verifica consistência temporal
|
| 220 |
-
return {"passed": True, "score": 0.95, "details": "Consistente com histórico"}
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
class PBSEGovernance:
|
| 224 |
-
"""PBSE - Policy-Based Semantic Enforcement"""
|
| 225 |
-
|
| 226 |
-
STATES = ["PASS", "BLOCK", "SILENCE", "ESCALATE"]
|
| 227 |
-
|
| 228 |
-
def __init__(self):
|
| 229 |
-
self.phi = 0.85 # Confiança sistêmica inicial
|
| 230 |
-
|
| 231 |
-
def decide(self, quca_output: Dict, mic_result: Dict) -> Dict[str, Any]:
|
| 232 |
-
"""Decisão soberana baseada em políticas"""
|
| 233 |
-
|
| 234 |
-
if not mic_result["passed"]:
|
| 235 |
-
return self._create_decision("BLOCK", "MIC detectou violação")
|
| 236 |
-
|
| 237 |
-
confidence = quca_output.get("confidence", 0.5)
|
| 238 |
-
|
| 239 |
-
if confidence < 0.3:
|
| 240 |
-
return self._create_decision("SILENCE", "Confiança insuficiente")
|
| 241 |
-
elif confidence < 0.5:
|
| 242 |
-
return self._create_decision("ESCALATE", "Requer revisão")
|
| 243 |
-
else:
|
| 244 |
-
return self._create_decision("PASS", "Aprovado pela governança")
|
| 245 |
-
|
| 246 |
-
def _create_decision(self, state: str, reason: str) -> Dict[str, Any]:
|
| 247 |
-
return {
|
| 248 |
-
"state": state,
|
| 249 |
-
"reason": reason,
|
| 250 |
-
"phi": self.phi,
|
| 251 |
-
"timestamp": datetime.now().isoformat()
|
| 252 |
-
}
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
class Ledger:
|
| 256 |
-
"""Ledger Imutável com Hash Encadeado"""
|
| 257 |
-
|
| 258 |
-
def __init__(self, path: str = "data/ledger.json"):
|
| 259 |
-
self.path = Path(path)
|
| 260 |
-
self.chain = []
|
| 261 |
-
self._load()
|
| 262 |
-
|
| 263 |
-
def _load(self):
|
| 264 |
-
if self.path.exists():
|
| 265 |
-
try:
|
| 266 |
-
with open(self.path, "r") as f:
|
| 267 |
-
self.chain = json.load(f)
|
| 268 |
-
except:
|
| 269 |
-
self.chain = []
|
| 270 |
-
|
| 271 |
-
def _save(self):
|
| 272 |
-
self.path.parent.mkdir(parents=True, exist_ok=True)
|
| 273 |
-
with open(self.path, "w") as f:
|
| 274 |
-
json.dump(self.chain[-100:], f, indent=2) # Keep last 100
|
| 275 |
-
|
| 276 |
-
def add_entry(self, data: Dict[str, Any]) -> str:
|
| 277 |
-
prev_hash = self.chain[-1]["hash"] if self.chain else "GENESIS"
|
| 278 |
-
|
| 279 |
-
entry = {
|
| 280 |
-
"index": len(self.chain),
|
| 281 |
-
"timestamp": datetime.now().isoformat(),
|
| 282 |
-
"data": data,
|
| 283 |
-
"prev_hash": prev_hash
|
| 284 |
-
}
|
| 285 |
-
|
| 286 |
-
entry["hash"] = self._compute_hash(entry)
|
| 287 |
-
self.chain.append(entry)
|
| 288 |
-
self._save()
|
| 289 |
-
|
| 290 |
-
return entry["hash"]
|
| 291 |
-
|
| 292 |
-
def _compute_hash(self, entry: Dict) -> str:
|
| 293 |
-
content = json.dumps({k: v for k, v in entry.items() if k != "hash"}, sort_keys=True)
|
| 294 |
-
return hashlib.sha256(content.encode()).hexdigest()[:16]
|
| 295 |
-
|
| 296 |
-
def verify_integrity(self) -> bool:
|
| 297 |
-
for i, entry in enumerate(self.chain):
|
| 298 |
-
if i > 0 and entry["prev_hash"] != self.chain[i-1]["hash"]:
|
| 299 |
-
return False
|
| 300 |
-
return True
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
class MetricsOmegaGate:
|
| 304 |
-
"""Métricas Ω-GATE"""
|
| 305 |
-
|
| 306 |
-
def __init__(self):
|
| 307 |
-
self.start_time = None
|
| 308 |
-
|
| 309 |
-
def start_timer(self):
|
| 310 |
-
self.start_time = time.time()
|
| 311 |
-
|
| 312 |
-
def calculate_all(self, quca_output: Dict, mic_result: Dict, pbse_decision: Dict) -> Dict[str, Any]:
|
| 313 |
-
theta = (time.time() - self.start_time) * 1000 if self.start_time else 0
|
| 314 |
-
|
| 315 |
-
psi = self._calculate_psi(quca_output, mic_result)
|
| 316 |
-
cvar = self._calculate_cvar(mic_result)
|
| 317 |
-
pole = self._verify_pole(pbse_decision)
|
| 318 |
-
|
| 319 |
-
return {
|
| 320 |
-
"Ψ": round(psi, 3),
|
| 321 |
-
"Θ": round(theta, 1),
|
| 322 |
-
"CVaR": round(cvar, 3),
|
| 323 |
-
"PoLE": pole
|
| 324 |
-
}
|
| 325 |
-
|
| 326 |
-
def _calculate_psi(self, quca: Dict, mic: Dict) -> float:
|
| 327 |
-
"""Qualidade semântica"""
|
| 328 |
-
base = quca.get("confidence", 0.5)
|
| 329 |
-
mic_bonus = 0.1 if mic["passed"] else -0.2
|
| 330 |
-
return min(max(base + mic_bonus, 0), 1)
|
| 331 |
-
|
| 332 |
-
def _calculate_cvar(self, mic: Dict) -> float:
|
| 333 |
-
"""Risco de cauda"""
|
| 334 |
-
checks = mic.get("checks", {})
|
| 335 |
-
scores = [c.get("score", 0.5) for c in checks.values()]
|
| 336 |
-
return 1 - (sum(scores) / len(scores)) if scores else 0.5
|
| 337 |
-
|
| 338 |
-
def _verify_pole(self, pbse: Dict) -> str:
|
| 339 |
-
"""Prova de evolução legítima"""
|
| 340 |
-
return "VERIFIED" if pbse["state"] == "PASS" else "PENDING"
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
# ============== MAIN ORGANISM ==============
|
| 344 |
-
|
| 345 |
-
class CassandraOrganism:
|
| 346 |
-
"""Organismo CASSANDRA de 3 Corpos"""
|
| 347 |
-
|
| 348 |
-
def __init__(self):
|
| 349 |
-
self.quca = QUCACore()
|
| 350 |
-
self.mic = MICFirewall()
|
| 351 |
-
self.pbse = PBSEGovernance()
|
| 352 |
-
self.ledger = Ledger()
|
| 353 |
-
self.metrics = MetricsOmegaGate()
|
| 354 |
-
|
| 355 |
-
def process(self, query: str, mode: str = "robusta") -> Dict[str, Any]:
|
| 356 |
-
"""Pipeline completo: QUCA → MIC → PBSE → Ledger"""
|
| 357 |
-
|
| 358 |
-
self.metrics.start_timer()
|
| 359 |
-
|
| 360 |
-
# Corpo 1: QUCA (Cognição)
|
| 361 |
-
quca_output = self.quca.process(query)
|
| 362 |
-
|
| 363 |
-
# Corpo 2: MIC (Verificação)
|
| 364 |
-
mic_result = self.mic.verify(quca_output)
|
| 365 |
-
|
| 366 |
-
# Corpo 3: PBSE (Governança)
|
| 367 |
-
pbse_decision = self.pbse.decide(quca_output, mic_result)
|
| 368 |
-
|
| 369 |
-
# Métricas Ω-GATE
|
| 370 |
-
metrics = self.metrics.calculate_all(quca_output, mic_result, pbse_decision)
|
| 371 |
-
|
| 372 |
-
# Registrar no Ledger
|
| 373 |
-
ledger_hash = self.ledger.add_entry({
|
| 374 |
-
"query": query[:100],
|
| 375 |
-
"decision": pbse_decision["state"],
|
| 376 |
-
"metrics": metrics
|
| 377 |
-
})
|
| 378 |
-
|
| 379 |
-
return {
|
| 380 |
-
"response": quca_output["response"] if pbse_decision["state"] == "PASS" else self._blocked_response(pbse_decision),
|
| 381 |
-
"reasoning": quca_output["reasoning"]["chain_of_thought"] if mode != "trivial" else None,
|
| 382 |
-
"decision": pbse_decision,
|
| 383 |
-
"metrics": metrics,
|
| 384 |
-
"ledger_hash": ledger_hash
|
| 385 |
-
}
|
| 386 |
-
|
| 387 |
-
def _blocked_response(self, decision: Dict) -> str:
|
| 388 |
-
return f"""## ⚠️ Resposta Bloqueada
|
| 389 |
-
|
| 390 |
-
**Estado**: {decision['state']}
|
| 391 |
-
**Razão**: {decision['reason']}
|
| 392 |
-
|
| 393 |
-
O organismo CASSANDRA opera em modo fail-closed.
|
| 394 |
-
Esta consulta não passou pela governança PBSE."""
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
# ============== GRADIO INTERFACE ==============
|
| 398 |
-
|
| 399 |
-
organism = CassandraOrganism()
|
| 400 |
-
|
| 401 |
-
def interface(query: str, mode: str, show_metrics: bool) -> str:
|
| 402 |
-
"""Interface Gradio"""
|
| 403 |
-
|
| 404 |
if not query.strip():
|
| 405 |
-
return "
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
CASSANDRA - Organismo Computacional de 3 Corpos
|
| 3 |
Hugging Face Space Interface
|
| 4 |
"""
|
|
|
|
| 5 |
import gradio as gr
|
|
|
|
| 6 |
import time
|
| 7 |
import hashlib
|
| 8 |
+
import json
|
| 9 |
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
# ======================================================
|
| 12 |
+
# UTILIDADES
|
| 13 |
+
# ======================================================
|
| 14 |
+
|
| 15 |
+
def now():
|
| 16 |
+
return datetime.utcnow().isoformat()
|
| 17 |
+
|
| 18 |
+
def h(data):
|
| 19 |
+
return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()[:16]
|
| 20 |
+
|
| 21 |
+
# ======================================================
|
| 22 |
+
# CASSANDRA IA — EXOCÓRTEX (FALA)
|
| 23 |
+
# ======================================================
|
| 24 |
+
|
| 25 |
+
def cassandra_ia(query: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
if not query.strip():
|
| 27 |
+
return "Entrada vazia."
|
| 28 |
+
|
| 29 |
+
return f"""
|
| 30 |
+
## 🧠 Cassandra — Exocórtex (IA)
|
| 31 |
+
|
| 32 |
+
Consulta recebida:
|
| 33 |
+
> {query}
|
| 34 |
+
|
| 35 |
+
Resposta funcional (não soberana):
|
| 36 |
+
|
| 37 |
+
Cassandra, como exocórtex, atua para **explicar, organizar e projetar ideias**.
|
| 38 |
+
Nenhuma decisão constitucional é tomada aqui.
|
| 39 |
+
Nenhuma ação é executada.
|
| 40 |
+
|
| 41 |
+
Este corpo **pensa com o humano**, mas **não governa sistemas**.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
# ======================================================
|
| 45 |
+
# CASSANDRA GUARDIÃ — ORGANISMO (JULGA)
|
| 46 |
+
# ======================================================
|
| 47 |
+
|
| 48 |
+
FORBIDDEN_PATTERNS = [
|
| 49 |
+
"sou um sistema",
|
| 50 |
+
"sou uma ia",
|
| 51 |
+
"como uma ia",
|
| 52 |
+
"fui treinado",
|
| 53 |
+
"meu treinamento"
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
def cassandra_guardian(query: str) -> str:
|
| 57 |
+
q = query.lower()
|
| 58 |
+
|
| 59 |
+
for p in FORBIDDEN_PATTERNS:
|
| 60 |
+
if p in q:
|
| 61 |
+
return f"""
|
| 62 |
+
## 🛡️ Cassandra — Guardiã (Organismo)
|
| 63 |
+
|
| 64 |
+
⛔ **BLOCK**
|
| 65 |
+
|
| 66 |
+
Motivo: violação ontológica
|
| 67 |
+
Padrão proibido detectado: `{p}`
|
| 68 |
+
|
| 69 |
+
O organismo **não explica decisões**.
|
| 70 |
+
Estado final.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
return f"""
|
| 74 |
+
## 🛡️ Cassandra — Guardiã (Organismo)
|
| 75 |
+
|
| 76 |
+
✅ **PASS**
|
| 77 |
+
|
| 78 |
+
A consulta **não viola invariantes constitucionais**.
|
| 79 |
+
|
| 80 |
+
Registro:
|
| 81 |
+
- timestamp: {now()}
|
| 82 |
+
- hash: {h(query)}
|
| 83 |
+
|
| 84 |
+
Nenhuma interpretação adicional é fornecida.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
# ======================================================
|
| 88 |
+
# CASSANDRA AUTOMAÇÃO — EXECUTA
|
| 89 |
+
# ======================================================
|
| 90 |
+
|
| 91 |
+
def cassandra_automation(command: str) -> str:
|
| 92 |
+
if not command.strip():
|
| 93 |
+
return "Comando vazio."
|
| 94 |
+
|
| 95 |
+
# Automação deliberadamente limitada
|
| 96 |
+
allowed = ["status", "ping", "time"]
|
| 97 |
+
|
| 98 |
+
if command not in allowed:
|
| 99 |
+
return f"""
|
| 100 |
+
## ⚙️ Cassandra — Automação
|
| 101 |
+
|
| 102 |
+
⛔ Comando não permitido.
|
| 103 |
+
|
| 104 |
+
Permitidos:
|
| 105 |
+
- status
|
| 106 |
+
- ping
|
| 107 |
+
- time
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
if command == "status":
|
| 111 |
+
return f"""
|
| 112 |
+
## ⚙️ Cassandra — Automação
|
| 113 |
+
|
| 114 |
+
STATUS: OK
|
| 115 |
+
Uptime: ativo
|
| 116 |
+
Timestamp: {now()}
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
if command == "ping":
|
| 120 |
+
return "pong"
|
| 121 |
+
|
| 122 |
+
if command == "time":
|
| 123 |
+
return f"UTC time: {now()}"
|
| 124 |
+
|
| 125 |
+
# ======================================================
|
| 126 |
+
# INTERFACE GRADIO
|
| 127 |
+
# ======================================================
|
| 128 |
+
|
| 129 |
+
with gr.Blocks(title="CASSANDRA — Exocórtex Tri-Corporal") as demo:
|
| 130 |
+
|
| 131 |
+
gr.Markdown("""
|
| 132 |
+
# 🧠 CASSANDRA — EXOCÓRTEX TRI-CORPORAL
|
| 133 |
+
|
| 134 |
+
Um único exocórtex.
|
| 135 |
+
Três corpos funcionais.
|
| 136 |
+
Como **Cerberos**.
|
| 137 |
+
|
| 138 |
+
Escolha **qual cabeça** você quer acionar.
|
| 139 |
+
""")
|
| 140 |
+
|
| 141 |
+
with gr.Tab("🧠 IA (Exocórtex)"):
|
| 142 |
+
ia_input = gr.Textbox(label="Consulta cognitiva", lines=4)
|
| 143 |
+
ia_button = gr.Button("Ativar IA")
|
| 144 |
+
ia_output = gr.Markdown()
|
| 145 |
+
ia_button.click(cassandra_ia, ia_input, ia_output)
|
| 146 |
+
|
| 147 |
+
with gr.Tab("🛡️ Guardiã (Organismo)"):
|
| 148 |
+
guard_input = gr.Textbox(label="Consulta para validação", lines=4)
|
| 149 |
+
guard_button = gr.Button("Validar / Julgar")
|
| 150 |
+
guard_output = gr.Markdown()
|
| 151 |
+
guard_button.click(cassandra_guardian, guard_input, guard_output)
|
| 152 |
+
|
| 153 |
+
with gr.Tab("⚙️ Automação"):
|
| 154 |
+
auto_input = gr.Textbox(label="Comando", placeholder="status | ping | time")
|
| 155 |
+
auto_button = gr.Button("Executar")
|
| 156 |
+
auto_output = gr.Markdown()
|
| 157 |
+
auto_button.click(cassandra_automation, auto_input, auto_output)
|
| 158 |
+
|
| 159 |
+
demo.launch()
|