exactor-accelerator 2.0.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.
Files changed (44) hide show
  1. exactor_accelerator/__init__.py +56 -0
  2. exactor_accelerator/adapter/__init__.py +10 -0
  3. exactor_accelerator/adapter/jev_schema.py +106 -0
  4. exactor_accelerator/adapter/translator.py +170 -0
  5. exactor_accelerator/api/__init__.py +3 -0
  6. exactor_accelerator/api/server.py +498 -0
  7. exactor_accelerator/config.py +175 -0
  8. exactor_accelerator/core/__init__.py +15 -0
  9. exactor_accelerator/core/exactor_bridge.py +213 -0
  10. exactor_accelerator/core/hypercube.py +375 -0
  11. exactor_accelerator/data/sample_clinical_triage.csv +501 -0
  12. exactor_accelerator/data/sample_customer_churn.csv +501 -0
  13. exactor_accelerator/data/sample_fraud_transactions.csv +501 -0
  14. exactor_accelerator/data/sample_soc_intrusion.json +6502 -0
  15. exactor_accelerator/data/sample_sre_incidents.json +7002 -0
  16. exactor_accelerator/data/sample_support_conversations.csv +501 -0
  17. exactor_accelerator/data/sample_support_conversations.json +6002 -0
  18. exactor_accelerator/engine/__init__.py +4 -0
  19. exactor_accelerator/engine/batch_processor.py +55 -0
  20. exactor_accelerator/engine/deepseek_client.py +165 -0
  21. exactor_accelerator/engine/jev_client.py +239 -0
  22. exactor_accelerator/engine/runtime.py +764 -0
  23. exactor_accelerator/ingestion/__init__.py +5 -0
  24. exactor_accelerator/ingestion/binarizer.py +456 -0
  25. exactor_accelerator/ingestion/loader.py +335 -0
  26. exactor_accelerator/ingestion/semantic_discovery.py +244 -0
  27. exactor_accelerator/ingestion/text_extractor.py +111 -0
  28. exactor_accelerator/ledger/__init__.py +3 -0
  29. exactor_accelerator/ledger/sqlite_wal.py +305 -0
  30. exactor_accelerator/model_persistence.py +123 -0
  31. exactor_accelerator/model_server.py +120 -0
  32. exactor_accelerator/py.typed +1 -0
  33. exactor_accelerator/regime_detector.py +376 -0
  34. exactor_accelerator/sdk.py +343 -0
  35. exactor_accelerator/sklearn_interface.py +360 -0
  36. exactor_accelerator/web/app.js +1345 -0
  37. exactor_accelerator/web/index.html +1196 -0
  38. exactor_accelerator/web/styles.css +295 -0
  39. exactor_accelerator-2.0.0.dist-info/METADATA +363 -0
  40. exactor_accelerator-2.0.0.dist-info/RECORD +44 -0
  41. exactor_accelerator-2.0.0.dist-info/WHEEL +5 -0
  42. exactor_accelerator-2.0.0.dist-info/entry_points.txt +2 -0
  43. exactor_accelerator-2.0.0.dist-info/licenses/LICENSE +21 -0
  44. exactor_accelerator-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,56 @@
1
+ """
2
+ Exactor Accelerator: High-Speed Boolean Logic Layer for TypeSafe AI
3
+
4
+ Combines EXACTOR boolean minimization (Rust) with Jev (TypeSafe AI)
5
+ to accelerate decisions by 4,770-24,000x with 95-100% accuracy.
6
+ """
7
+
8
+ __version__ = "2.0.0"
9
+ __author__ = "Exactor Contributors"
10
+ __license__ = "MIT"
11
+
12
+ from .config import configure, get_config
13
+ from .ingestion import AdaptiveBinarizer, DataLoader, Proposition, BinarizationResult, SemanticPropositionDiscovery
14
+ from .core import ExactorBridge, ExactorHypercubeReducer, ExactorSimplificationResult
15
+ from .adapter import ExactorToJevTranslator, JevPayload, NoulQuestion, ChoiceQuestion, ScoreQuestion
16
+ from .ledger import MemoryLedger
17
+ from .engine import JevClient, HybridRuntime, QueryResult
18
+ from .sklearn_interface import ExactorAcceleratorClassifier, ExactorAcceleratorMultiLabelClassifier
19
+ from .model_persistence import save_model, load_model, log_to_mlflow, log_to_wandb
20
+ from .sdk import ExactorAccelerator
21
+
22
+
23
+ __all__ = [
24
+ # Top-level API
25
+ "configure",
26
+ "get_config",
27
+ "ExactorAccelerator",
28
+ "ExactorAcceleratorClassifier",
29
+ "ExactorAcceleratorMultiLabelClassifier",
30
+ # Model persistence
31
+ "save_model",
32
+ "load_model",
33
+ "log_to_mlflow",
34
+ "log_to_wandb",
35
+ # Ingestion
36
+ "SemanticPropositionDiscovery",
37
+ "AdaptiveBinarizer",
38
+ "DataLoader",
39
+ "Proposition",
40
+ "BinarizationResult",
41
+ # Core
42
+ "ExactorBridge",
43
+ "ExactorHypercubeReducer",
44
+ "ExactorSimplificationResult",
45
+ # Adapter
46
+ "ExactorToJevTranslator",
47
+ "JevPayload",
48
+ "NoulQuestion",
49
+ "ChoiceQuestion",
50
+ "ScoreQuestion",
51
+ # Ledger & Engine
52
+ "MemoryLedger",
53
+ "JevClient",
54
+ "HybridRuntime",
55
+ "QueryResult",
56
+ ]
@@ -0,0 +1,10 @@
1
+ from .jev_schema import NoulQuestion, ChoiceQuestion, ScoreQuestion, JevPayload
2
+ from .translator import ExactorToJevTranslator
3
+
4
+ __all__ = [
5
+ "NoulQuestion",
6
+ "ChoiceQuestion",
7
+ "ScoreQuestion",
8
+ "JevPayload",
9
+ "ExactorToJevTranslator",
10
+ ]
@@ -0,0 +1,106 @@
1
+ """
2
+ TypeSafe AI Jev Schema Primitives & Payload Models.
3
+ Defines Noul, Choice, Score question types and the System One payload structure.
4
+ """
5
+
6
+ from typing import Dict, Any, Optional, Union, List
7
+ import json
8
+
9
+
10
+ class NoulQuestion:
11
+ """
12
+ Noul question primitive (Bernoulli binary decision).
13
+ Returns a calibrated probability (0 to 1) representing the likelihood of truth.
14
+ """
15
+
16
+ def __init__(self, instructions: str):
17
+ self.type = "noul"
18
+ self.instructions = instructions
19
+
20
+ def to_dict(self) -> Dict[str, Any]:
21
+ return {
22
+ "type": self.type,
23
+ "instructions": self.instructions,
24
+ }
25
+
26
+
27
+ class ChoiceQuestion:
28
+ """
29
+ Choice question primitive for categorical decision-making.
30
+ Returns probabilities across each predefined option and the chosen category.
31
+ """
32
+
33
+ def __init__(self, instructions: str, criteria: Dict[str, Optional[str]]):
34
+ self.type = "choice"
35
+ self.instructions = instructions
36
+ self.criteria = criteria
37
+
38
+ def to_dict(self) -> Dict[str, Any]:
39
+ return {
40
+ "type": self.type,
41
+ "instructions": self.instructions,
42
+ "criteria": self.criteria,
43
+ }
44
+
45
+
46
+ class ScoreQuestion:
47
+ """
48
+ Score question primitive for continuous calibrated assessment on a spectrum.
49
+ TypeSafe API requires criteria to be an ordered list of score levels.
50
+ """
51
+
52
+ def __init__(self, instructions: str, criteria: Optional[Union[List[str], Dict[str, Optional[str]]]] = None):
53
+ self.type = "score"
54
+ self.instructions = instructions
55
+ if isinstance(criteria, dict):
56
+ self.criteria = [f"{k}: {v}" if v else k for k, v in criteria.items()]
57
+ elif isinstance(criteria, list):
58
+ self.criteria = criteria
59
+ else:
60
+ self.criteria = [
61
+ "Bajo: Bajo o nulo impacto/riesgo",
62
+ "Medio: Impacto moderado que requiere precaución",
63
+ "Crítico: Severo o crítico, activación mandatoria",
64
+ ]
65
+
66
+ def to_dict(self) -> Dict[str, Any]:
67
+ return {
68
+ "type": self.type,
69
+ "instructions": self.instructions,
70
+ "criteria": self.criteria,
71
+ }
72
+
73
+
74
+ class JevPayload:
75
+ """
76
+ Official payload structure for TypeSafe AI Jev System One model.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ state: Dict[str, Any],
82
+ questions: Dict[str, Union[NoulQuestion, ChoiceQuestion, ScoreQuestion, Dict[str, Any]]],
83
+ model: str = "jev-latest",
84
+ ):
85
+ self.model = model
86
+ self.state = state
87
+ self.questions = questions
88
+
89
+ def to_dict(self) -> Dict[str, Any]:
90
+ serialized_questions = {}
91
+ for q_name, q_obj in self.questions.items():
92
+ if hasattr(q_obj, "to_dict"):
93
+ serialized_questions[q_name] = q_obj.to_dict()
94
+ elif isinstance(q_obj, dict):
95
+ serialized_questions[q_name] = q_obj
96
+ else:
97
+ serialized_questions[q_name] = {"type": "noul", "instructions": str(q_obj)}
98
+
99
+ return {
100
+ "model": self.model,
101
+ "state": self.state,
102
+ "questions": serialized_questions,
103
+ }
104
+
105
+ def to_json(self, indent: int = 2) -> str:
106
+ return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
@@ -0,0 +1,170 @@
1
+ """
2
+ Dynamic Adapter: EXACTOR -> Jev.
3
+ Translates Boolean formulas and hypercube terms from Exactor into typed questions
4
+ for TypeSafe AI Jev (Noul, Choice, Score).
5
+ """
6
+
7
+ from typing import Dict, Any, List, Optional
8
+ from ..core.hypercube import ExactorSimplificationResult
9
+ from ..ingestion.binarizer import Proposition
10
+ from .jev_schema import NoulQuestion, ChoiceQuestion, ScoreQuestion, JevPayload
11
+
12
+
13
+ class ExactorToJevTranslator:
14
+ """
15
+ Translates minimized Boolean logic formulas into calibrated question schemas for Jev.
16
+ """
17
+
18
+ def __init__(self, target_label: str = "evento_critico"):
19
+ self.target_label = target_label
20
+
21
+ def generate_human_explanation(
22
+ self,
23
+ result: ExactorSimplificationResult,
24
+ propositions_map: Optional[Dict[str, Proposition]] = None,
25
+ ) -> str:
26
+ """Converts mathematical Boolean terms into natural semantic explanation."""
27
+ if not result.terms:
28
+ return "Ninguna condición histórica de activación fue detectada."
29
+
30
+ clauses = []
31
+ for term in result.terms:
32
+ literals = []
33
+ for i, s in enumerate(term.states):
34
+ if s == 2:
35
+ continue
36
+ v_name = result.variables[i]
37
+ prop = propositions_map.get(v_name) if propositions_map else None
38
+ desc = prop.description if prop else v_name
39
+ if s == 1:
40
+ literals.append(f"[{desc}]")
41
+ elif s == 0:
42
+ literals.append(f"[NO {desc}]")
43
+
44
+ clause_str = " Y ".join(literals) if literals else "SIEMPRE_ACTIVO"
45
+ clauses.append(clause_str)
46
+
47
+ if len(clauses) == 1:
48
+ return f"Se cumple cuando: {clauses[0]}"
49
+ return "Se cumple cuando al menos una de las siguientes combinaciones es verdadera: " + " O BIEN ".join(
50
+ [f"({c})" for c in clauses]
51
+ )
52
+
53
+ def create_questions_schema(
54
+ self,
55
+ result: ExactorSimplificationResult,
56
+ propositions_map: Optional[Dict[str, Proposition]] = None,
57
+ custom_action_choices: Optional[Dict[str, Optional[str]]] = None,
58
+ ) -> Dict[str, Any]:
59
+ """
60
+ Builds the complete typed questions schema according to TypeSafe AI specifications.
61
+ """
62
+ explanation = self.generate_human_explanation(result, propositions_map)
63
+ formula_snippet = result.formula_expr[:180] + ("..." if len(result.formula_expr) > 180 else "")
64
+
65
+ # 1. Primary Noul question: Exact boolean condition derived from Exactor
66
+ noul_instructions = (
67
+ f"¿Se cumple la condición booleana derivada del análisis histórico? "
68
+ f"Fórmula lógica: {formula_snippet}. Criterio: {explanation}"
69
+ )
70
+ criterio_logico = NoulQuestion(instructions=noul_instructions)
71
+
72
+ # 2. Autonomous Business Action: Choice question
73
+ if not custom_action_choices:
74
+ tl = self.target_label.lower()
75
+ if "fraud" in tl:
76
+ custom_action_choices = {
77
+ "BLOQUEAR_TRANSACCION": "Si el riesgo de fraude o anomalía es alto y cumple las condiciones de riesgo",
78
+ "REVISION_MANUAL": "Si hay sospecha moderada o parámetros limítrofes que requieren revisión",
79
+ "APROBAR_TRANSACCION": "Si la transacción es legítima, habitual y de bajo riesgo",
80
+ }
81
+ elif "mitigation" in tl or "sre" in tl:
82
+ custom_action_choices = {
83
+ "ACTIVAR_MITIGACION": "Si los incidentes y métricas de error superan los límites de SLA",
84
+ "ESCALAR_A_GUARDIA": "Si hay degradación parcial del servicio",
85
+ "DESESTIMAR_ALERTA": "Si las métricas están en parámetros normales de operación",
86
+ }
87
+ elif "churn" in tl:
88
+ custom_action_choices = {
89
+ "OFERTA_RETENCION_INMEDIATA": "Si el cliente tiene alto riesgo de cancelación inminente",
90
+ "CONTACTO_EXECUTIVE_CSM": "Si hay riesgo moderado de insatisfacción",
91
+ "MANTENER_PLAN_ACTUAL": "Si el cliente está fidelizado y satisfecho",
92
+ }
93
+ elif "block" in tl or "soc" in tl or "ip" in tl:
94
+ custom_action_choices = {
95
+ "BLOQUEAR_IP_FIREWALL": "Si se detecta un patrón claro de ciberataque o fuerza bruta",
96
+ "AISLAR_HOST_EN_QUARANTINE": "Si hay anomalías de tráfico sospechosas",
97
+ "PERMITIR_TRAFICO": "Si es tráfico verificado y legítimo",
98
+ }
99
+ elif "icu" in tl or "triage" in tl:
100
+ custom_action_choices = {
101
+ "TRANSFERIR_A_UCI_URGENTE": "Si los signos vitales indican riesgo vital inminente",
102
+ "OBSERVACION_CONTINUA_BOX": "Si el paciente requiere monitoreo intermedio",
103
+ "ALTA_A_SALA_COMUN": "Si los parámetros del paciente están estables",
104
+ }
105
+ elif "escalate" in tl or "sup" in tl:
106
+ custom_action_choices = {
107
+ "ESCALAR_A_SUPERVISOR_HUMANO": "Si el usuario está insatisfecho o reporta problemas críticos",
108
+ "TRANSFERIR_A_AGENTE_SENIOR": "Si la consulta es compleja",
109
+ "RESOLVER_CON_BOT": "Si es una consulta informativa estándar",
110
+ }
111
+ else:
112
+ custom_action_choices = {
113
+ "APROBAR_OPERACION": "El evento cumple con todos los parámetros normales y no presenta riesgo",
114
+ "REVISION_MANUAL": "Existe incertidumbre o valores límite en los parámetros del evento",
115
+ "BLOQUEAR_RIESGO": "El evento cumple las condiciones lógicas de riesgo o anomalía",
116
+ }
117
+
118
+ business_action = ChoiceQuestion(
119
+ instructions=(
120
+ f"¿Qué acción de negocio debe ejecutarse sobre este evento considerando la regla lógica '{formula_snippet}'?"
121
+ ),
122
+ criteria=custom_action_choices,
123
+ )
124
+
125
+ # 3. Calibrated Risk/Severity Score question
126
+ score_question = ScoreQuestion(
127
+ instructions=f"Evalúa en una escala continua el nivel de impacto/criticidad del evento según la regla lógica.",
128
+ criteria={
129
+ "bajo": "Evento estándar sin activación de reglas críticas",
130
+ "medio": "Parámetros cercanos a los límites de activación lógica",
131
+ "critico": "Cumplimiento total de la regla booleana con alta severidad",
132
+ },
133
+ )
134
+
135
+ return {
136
+ "criterio_logico": criterio_logico,
137
+ "accion_recomendada": business_action,
138
+ "calibracion_criticidad": score_question,
139
+ }
140
+
141
+ def build_payload(
142
+ self,
143
+ raw_event_state: Dict[str, Any],
144
+ result: ExactorSimplificationResult,
145
+ propositions_map: Optional[Dict[str, Proposition]] = None,
146
+ custom_action_choices: Optional[Dict[str, Optional[str]]] = None,
147
+ include_all_questions: bool = True,
148
+ ) -> JevPayload:
149
+ """
150
+ Builds the exact JSON payload expected by the TypeSafe AI Jev API.
151
+ """
152
+ if include_all_questions:
153
+ questions = self.create_questions_schema(
154
+ result=result,
155
+ propositions_map=propositions_map,
156
+ custom_action_choices=custom_action_choices,
157
+ )
158
+ else:
159
+ explanation = self.generate_human_explanation(result, propositions_map)
160
+ questions = {
161
+ "criterio_logico": NoulQuestion(
162
+ instructions=f"¿Se cumple la condición booleana derivada del análisis histórico? {explanation}"
163
+ )
164
+ }
165
+
166
+ return JevPayload(
167
+ model="jev-latest",
168
+ state={"evento": raw_event_state},
169
+ questions=questions,
170
+ )
@@ -0,0 +1,3 @@
1
+ from .server import app
2
+
3
+ __all__ = ["app"]