DEFRAG-ENGINE / app.py
cjo93's picture
Create app.py
f7c4865 verified
import gradio as gr
import numpy as np
from dataclasses import dataclass
from typing import Dict, List, Any
import re
# =========================
# PHYSICS ENGINE (DEFRAG v2)
# =========================
@dataclass
class VectorState:
"""
Represents the user's dynamic state in 3D space.
Ranges: -10.0 (Collapse) to +10.0 (Sovereign)
Axes:
- X (Resilience): Root/Solar Plexus/Sacral → Vitality/Stress capacity
- Y (Autonomy): Heart/G-Center → Identity/Will/Self-direction
- Z (Connectivity): Throat/Ajna → Expression/Social integration
"""
resilience: float
autonomy: float
connectivity: float
def to_array(self) -> np.ndarray:
return np.array([self.resilience, self.autonomy, self.connectivity])
@staticmethod
def from_array(arr: np.ndarray) -> "VectorState":
return VectorState(
resilience=float(arr[0]),
autonomy=float(arr[1]),
connectivity=float(arr[2]),
)
def magnitude(self) -> float:
return float(np.linalg.norm(self.to_array()))
def distance_from_baseline(self, baseline: "VectorState") -> float:
diff = self.to_array() - baseline.to_array()
return float(np.linalg.norm(diff))
@dataclass
class PhysicsConstants:
"""
Physics properties derived from Human Design blueprint.
These govern how a specific user reacts to stress.
"""
mass: float # Resistance to change (1-10)
permeability: float # Environmental sensitivity (0-1.5)
elasticity_vector: np.ndarray # Dimensional recovery rates [X, Y, Z]
coupling_matrix: np.ndarray # 3×3 interaction matrix
class BlueprintPhysics:
"""
Converts Human Design blueprint into physics constants.
Pure mathematical derivation. No randomness.
"""
PROFILE_MASS_TABLE: Dict[str, float] = {
"1": 9.0,
"2": 8.0,
"3": 7.0,
"4": 4.0,
"5": 3.0,
"6": 2.0,
}
AUTHORITY_ELASTICITY: Dict[str, float] = {
"Emotional": 0.3,
"Lunar": 0.2,
"Self-Projected": 0.5,
"Environmental": 0.5,
"Ego": 0.6,
"Sacral": 0.8,
"Splenic": 0.95,
}
@staticmethod
def derive(blueprint: Dict) -> PhysicsConstants:
mass = BlueprintPhysics._calculate_mass(blueprint.get("profile", "3/5"))
elasticity_vector = BlueprintPhysics._calculate_elasticity(
blueprint.get("authority", "Emotional"),
blueprint.get("open_centers", []),
blueprint.get("defined_centers", []),
)
coupling_matrix = BlueprintPhysics._build_coupling_matrix(
blueprint.get("open_centers", []),
blueprint.get("defined_centers", []),
)
permeability = len(blueprint.get("open_centers", [])) * 0.15
return PhysicsConstants(
mass=mass,
permeability=permeability,
elasticity_vector=elasticity_vector,
coupling_matrix=coupling_matrix,
)
@staticmethod
def _calculate_mass(profile: str) -> float:
try:
p_line, d_line = profile.split("/")
p_mass = BlueprintPhysics.PROFILE_MASS_TABLE.get(p_line, 5.0)
d_mass = BlueprintPhysics.PROFILE_MASS_TABLE.get(d_line, 5.0)
return (p_mass + d_mass) / 2.0
except Exception:
return 5.0
@staticmethod
def _calculate_elasticity(
authority: str,
open_centers: List[str],
defined_centers: List[str],
) -> np.ndarray:
base = BlueprintPhysics.AUTHORITY_ELASTICITY.get(authority, 0.5)
elasticity = np.array([base, base, base])
if "SACRAL" in open_centers:
elasticity[0] *= 0.5
if "ROOT" in open_centers:
elasticity[0] *= 0.7
if "SOLAR_PLEXUS" in open_centers:
elasticity[0] *= 0.75
if "SACRAL" in defined_centers:
elasticity[0] *= 1.3
if "ROOT" in defined_centers:
elasticity[0] *= 1.2
if "HEART" in open_centers:
elasticity[1] *= 0.6
if "G_CENTER" in open_centers:
elasticity[1] *= 0.7
if "HEART" in defined_centers:
elasticity[1] *= 1.4
if "G_CENTER" in defined_centers:
elasticity[1] *= 1.3
if "THROAT" in open_centers:
elasticity[2] *= 0.7
if "AJNA" in open_centers:
elasticity[2] *= 0.8
if "THROAT" in defined_centers:
elasticity[2] *= 1.2
if "AJNA" in defined_centers:
elasticity[2] *= 1.15
elasticity = np.clip(elasticity, 0.1, 2.0)
return elasticity
@staticmethod
def _build_coupling_matrix(
open_centers: List[str],
defined_centers: List[str],
) -> np.ndarray:
m = np.eye(3, dtype=float)
if "HEAD" in open_centers:
m[0, 2] += 0.25
if "AJNA" in open_centers:
m[1, 2] += 0.3
if "THROAT" in open_centers:
m[2, 1] += 0.4
if "G_CENTER" in open_centers:
m[1, 2] += 0.6
if "HEART" in open_centers:
m[1, 2] += 0.5
m[1, 0] += 0.3
m[0, 2] += 0.2
if "SOLAR_PLEXUS" in open_centers:
m[0, 2] += 0.4
if "SACRAL" in open_centers:
m[0, 1] += 0.3
if "SPLEEN" in open_centers:
m[0, 2] += 0.35
if "ROOT" in open_centers:
m[0, 2] += 0.3
m[1, 2] += 0.2
if "SOLAR_PLEXUS" in defined_centers:
m[0, 2] = max(1.0, m[0, 2] - 0.2)
if "HEART" in defined_centers:
m[1, 2] = max(1.0, m[1, 2] - 0.3)
if "G_CENTER" in defined_centers:
m[1, 2] = max(1.0, m[1, 2] - 0.25)
return m
class PhysicsSolver:
@staticmethod
def calculate_impact(
current_state: VectorState,
stress_vector: VectorState,
physics: PhysicsConstants,
) -> VectorState:
curr_vec = current_state.to_array()
stress_vec = stress_vector.to_array()
amplified_force = stress_vec * (1.0 + physics.permeability)
acceleration = amplified_force / physics.mass
coupled_acceleration = np.dot(physics.coupling_matrix, acceleration)
recovery_force = curr_vec * physics.elasticity_vector * 0.1
new_vec = curr_vec + coupled_acceleration + recovery_force
new_vec = np.clip(new_vec, -10.0, 10.0)
return VectorState.from_array(new_vec)
@staticmethod
def predict_recovery_time(
current_state: VectorState,
baseline_state: VectorState,
physics: PhysicsConstants,
tolerance: float = 0.5,
) -> int:
distance = current_state.distance_from_baseline(baseline_state)
avg_elasticity = float(np.mean(physics.elasticity_vector))
time_constant = physics.mass / max(avg_elasticity, 0.1)
if distance < tolerance:
return 0
recovery_time = -time_constant * np.log(tolerance / distance)
return int(max(recovery_time, 0))
# =========================
# STRESS MAPPER
# =========================
@dataclass(frozen=True)
class AxisWeights:
resilience: float
autonomy: float
connectivity: float
class StressMapper:
MIN_SEVERITY = 1
MAX_SEVERITY = 10
MIN_FORCE = 0.5
MAX_FORCE = 6.0
CATEGORY_WEIGHTS: Dict[str, AxisWeights] = {
"burnout": AxisWeights(-1.0, -0.4, -0.1),
"overwork": AxisWeights(-0.9, -0.3, -0.1),
"fatigue": AxisWeights(-0.8, -0.2, -0.1),
"exhaustion": AxisWeights(-1.0, -0.3, -0.2),
"rejection": AxisWeights(-0.3, -1.0, -0.6),
"abandon": AxisWeights(-0.2, -1.0, -0.6),
"shame": AxisWeights(-0.2, -0.9, -0.5),
"failure": AxisWeights(-0.3, -0.8, -0.4),
"criticized": AxisWeights(-0.2, -0.8, -0.5),
"conflict": AxisWeights(-0.2, -0.5, -0.9),
"argument": AxisWeights(-0.1, -0.4, -0.9),
"breakup": AxisWeights(-0.3, -0.7, -1.0),
"lonely": AxisWeights(-0.1, -0.3, -0.9),
"isolation": AxisWeights(-0.1, -0.4, -1.0),
"money": AxisWeights(-0.7, -0.8, -0.2),
"debt": AxisWeights(-0.8, -0.9, -0.2),
"bills": AxisWeights(-0.7, -0.7, -0.2),
"job": AxisWeights(-0.6, -0.6, -0.3),
"career": AxisWeights(-0.5, -0.7, -0.3),
"prove": AxisWeights(-0.5, -0.9, -0.3),
"pressure": AxisWeights(-0.6, -0.7, -0.4),
"deadline": AxisWeights(-0.6, -0.7, -0.3),
"sick": AxisWeights(-0.9, -0.3, -0.2),
"illness": AxisWeights(-1.0, -0.3, -0.2),
"injury": AxisWeights(-1.0, -0.2, -0.2),
"stuck": AxisWeights(-0.4, -0.9, -0.3),
"lost": AxisWeights(-0.3, -1.0, -0.4),
"purposeless": AxisWeights(-0.2, -1.0, -0.4),
"directionless": AxisWeights(-0.2, -0.9, -0.4),
"anxiety": AxisWeights(-0.8, -0.5, -0.7),
"panic": AxisWeights(-0.9, -0.4, -0.8),
"fear": AxisWeights(-0.7, -0.5, -0.7),
}
DEFAULT_WEIGHTS = AxisWeights(-0.6, -0.6, -0.5)
@classmethod
def map_event_to_stress(cls, context: str, severity_numeric: int) -> VectorState:
norm = cls._normalize_severity(severity_numeric)
tokens = cls._tokenize(context)
agg_x = agg_y = agg_z = 0.0
hits = 0
for t in tokens:
if t in cls.CATEGORY_WEIGHTS:
w = cls.CATEGORY_WEIGHTS[t]
agg_x += w.resilience
agg_y += w.autonomy
agg_z += w.connectivity
hits += 1
if hits == 0:
base = cls.DEFAULT_WEIGHTS
agg_x, agg_y, agg_z = base.resilience, base.autonomy, base.connectivity
hits = 1
avg_x, avg_y, avg_z = agg_x / hits, agg_y / hits, agg_z / hits
return VectorState(
resilience=avg_x * norm,
autonomy=avg_y * norm,
connectivity=avg_z * norm,
)
@classmethod
def _normalize_severity(cls, severity: int) -> float:
s = max(cls.MIN_SEVERITY, min(cls.MAX_SEVERITY, int(severity)))
t = (s - cls.MIN_SEVERITY) / (cls.MAX_SEVERITY - cls.MIN_SEVERITY)
return cls.MIN_FORCE + t * (cls.MAX_FORCE - cls.MIN_FORCE)
@staticmethod
def _tokenize(text: str) -> List[str]:
if not text:
return []
text = text.lower()
tokens = re.split(r"[^a-z]+", text)
return [t for t in tokens if t]
# =========================
# INVERSION ENGINE (v1)
# =========================
class InversionEngine:
@staticmethod
def process_event(
blueprint: Dict[str, Any],
event_context: str,
severity_numeric: int,
vector_state: VectorState,
) -> Dict[str, Any]:
diagnosis = InversionEngine._diagnose(vector_state)
script = InversionEngine._script(vector_state)
experiments = InversionEngine._experiments(vector_state)
seda_locked = severity_numeric >= 8
return {
"diagnosis": diagnosis,
"script": script,
"script_source": "heuristic_v1",
"experiments": experiments,
"seda_locked": seda_locked,
"seda_keywords": ["SEDA"] if seda_locked else [],
}
@staticmethod
def _diagnose(state: VectorState) -> str:
if state.resilience < 3.0 and state.autonomy < 3.0:
return "Acute burnout with identity depletion."
if state.resilience < 3.0:
return "Resilience system overloaded."
if state.autonomy < 3.0:
return "Autonomy and self-direction destabilized."
if state.connectivity < 3.5:
return "Social connectivity suppressed."
return "System under manageable stress."
@staticmethod
def _script(state: VectorState) -> str:
parts = []
if state.resilience < 3.0:
parts.append(
"Pause output for 24 hours and reduce external demands to the minimum you can safely hold."
)
if state.autonomy < 3.0:
parts.append(
"Do not make major decisions alone; speak them out loud with a trusted person before acting."
)
if state.connectivity < 3.5:
parts.app