Spaces:
Sleeping
Sleeping
Commit
·
607becf
1
Parent(s):
349493b
ok
Browse files
app.py
CHANGED
|
@@ -1,9 +1,16 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import spaces
|
| 3 |
import torch
|
| 4 |
import numpy as np
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
| 6 |
import random
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# Try importing Stable Diffusion dependencies
|
| 9 |
try:
|
|
@@ -13,6 +20,14 @@ except ImportError:
|
|
| 13 |
print("Warning: diffusers package not available. Artistic visualization will be disabled.")
|
| 14 |
STABLE_DIFFUSION_AVAILABLE = False
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# Initialize Stable Diffusion only if available
|
| 17 |
pipe = None
|
| 18 |
if STABLE_DIFFUSION_AVAILABLE:
|
|
@@ -24,32 +39,269 @@ if STABLE_DIFFUSION_AVAILABLE:
|
|
| 24 |
pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
|
| 25 |
pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(model_repo_id, subfolder="scheduler", shift=5)
|
| 26 |
pipe = pipe.to(device)
|
|
|
|
| 27 |
except Exception as e:
|
| 28 |
-
print(f"
|
| 29 |
STABLE_DIFFUSION_AVAILABLE = False
|
| 30 |
|
|
|
|
| 31 |
MAX_SEED = np.iinfo(np.int32).max
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
class EmotionalContext:
|
| 34 |
"""Implements Mem|8's emotional context structure"""
|
| 35 |
-
def __init__(self):
|
| 36 |
-
self.
|
| 37 |
-
self.
|
| 38 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
"""
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
def generate_memory_prompt(operation: str, emotion_valence: float) -> str:
|
| 48 |
"""Generate artistic prompts based on memory operation and emotional state"""
|
| 49 |
base_prompts = {
|
| 50 |
"wave_memory": "memories flowing like waves in an infinite ocean, ",
|
| 51 |
"interference": "two waves of memory intersecting and creating patterns, ",
|
| 52 |
-
"resonance": "resonating waves of consciousness forming harmonious patterns, "
|
|
|
|
|
|
|
|
|
|
| 53 |
}
|
| 54 |
|
| 55 |
emotion_desc = "serene and peaceful" if -20 <= emotion_valence <= 20 else \
|
|
@@ -57,73 +309,125 @@ def generate_memory_prompt(operation: str, emotion_valence: float) -> str:
|
|
| 57 |
"dark and introspective"
|
| 58 |
|
| 59 |
style = "digital art, abstract, flowing, wave patterns, "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
prompt = f"{base_prompts[operation]}{emotion_desc}, {style} ethereal, dreamlike quality"
|
| 61 |
return prompt
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
emotion_valence: float,
|
| 68 |
-
generate_art: bool = True,
|
| 69 |
-
seed: int = 42
|
| 70 |
-
) -> Tuple[str, np.ndarray, np.ndarray]:
|
| 71 |
-
"""Perform quantum-inspired memory operations using Mem|8 concepts."""
|
| 72 |
-
# Initialize emotional context
|
| 73 |
-
emotion = EmotionalContext()
|
| 74 |
-
emotion.valence = torch.tensor([emotion_valence]).cuda()
|
| 75 |
-
emotion.arousal = torch.abs(torch.tensor([emotion_valence * 2])).cuda()
|
| 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 |
-
if generate_art and STABLE_DIFFUSION_AVAILABLE and pipe is not None:
|
| 124 |
-
prompt = generate_memory_prompt(operation, emotion_valence)
|
| 125 |
generator = torch.Generator().manual_seed(seed)
|
| 126 |
-
|
| 127 |
prompt=prompt,
|
| 128 |
negative_prompt="text, watermark, signature, blurry, distorted",
|
| 129 |
guidance_scale=1.5,
|
|
@@ -133,91 +437,95 @@ def quantum_memory_ops(
|
|
| 133 |
generator=generator,
|
| 134 |
).images[0]
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
results.append(f"\nArtistic Visualization:")
|
| 141 |
-
results.append(f"Not available - Stable Diffusion could not be initialized")
|
| 142 |
-
|
| 143 |
-
return "\n".join(results), wave_viz, art_viz
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
with gr.Column():
|
| 159 |
-
size_input = gr.Slider(
|
| 160 |
-
minimum=16,
|
| 161 |
-
maximum=128,
|
| 162 |
-
value=32,
|
| 163 |
-
step=16,
|
| 164 |
-
label="Memory Grid Size"
|
| 165 |
-
)
|
| 166 |
-
operation_input = gr.Radio(
|
| 167 |
-
["wave_memory", "interference", "resonance"],
|
| 168 |
-
label="Memory Wave Operation",
|
| 169 |
-
value="wave_memory",
|
| 170 |
-
info="Select the type of wave-based memory operation to visualize"
|
| 171 |
-
)
|
| 172 |
-
emotion_input = gr.Slider(
|
| 173 |
-
minimum=-128,
|
| 174 |
-
maximum=127,
|
| 175 |
-
value=0,
|
| 176 |
-
step=1,
|
| 177 |
-
label="Emotional Valence",
|
| 178 |
-
info="Emotional context from negative to positive (-128 to 127)"
|
| 179 |
-
)
|
| 180 |
-
|
| 181 |
-
with gr.Accordion("Advanced Settings", open=False):
|
| 182 |
-
generate_art = gr.Checkbox(
|
| 183 |
-
label="Generate Artistic Visualization",
|
| 184 |
-
value=True,
|
| 185 |
-
info="Use Stable Diffusion to create artistic representations"
|
| 186 |
-
)
|
| 187 |
-
seed = gr.Slider(
|
| 188 |
-
label="Art Generation Seed",
|
| 189 |
-
minimum=0,
|
| 190 |
-
maximum=MAX_SEED,
|
| 191 |
-
step=1,
|
| 192 |
-
value=42
|
| 193 |
-
)
|
| 194 |
-
|
| 195 |
-
run_btn = gr.Button("Generate Memory Wave", variant="primary")
|
| 196 |
-
|
| 197 |
-
with gr.Column():
|
| 198 |
-
output_text = gr.Textbox(label="Wave Analysis", lines=8)
|
| 199 |
-
with gr.Row():
|
| 200 |
-
wave_plot = gr.Plot(label="Wave Pattern")
|
| 201 |
-
art_output = gr.Image(label="Artistic Visualization")
|
| 202 |
-
|
| 203 |
-
run_btn.click(
|
| 204 |
-
quantum_memory_ops,
|
| 205 |
-
inputs=[size_input, operation_input, emotion_input, generate_art, seed],
|
| 206 |
-
outputs=[output_text, wave_plot, art_output]
|
| 207 |
-
)
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
|
|
|
| 211 |
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
|
| 218 |
-
|
| 219 |
|
| 220 |
-
|
| 221 |
-
""")
|
| 222 |
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import torch
|
| 3 |
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from matplotlib import cm
|
| 6 |
+
import plotly.graph_objects as go
|
| 7 |
+
from plotly.subplots import make_subplots
|
| 8 |
import random
|
| 9 |
+
from typing import Tuple, List, Dict, Any, Optional
|
| 10 |
+
import time
|
| 11 |
+
import colorsys
|
| 12 |
+
import math
|
| 13 |
+
from PIL import Image, ImageDraw, ImageFilter
|
| 14 |
|
| 15 |
# Try importing Stable Diffusion dependencies
|
| 16 |
try:
|
|
|
|
| 20 |
print("Warning: diffusers package not available. Artistic visualization will be disabled.")
|
| 21 |
STABLE_DIFFUSION_AVAILABLE = False
|
| 22 |
|
| 23 |
+
# Try importing 3D visualization dependencies
|
| 24 |
+
try:
|
| 25 |
+
import plotly.express as px
|
| 26 |
+
PLOTLY_3D_AVAILABLE = True
|
| 27 |
+
except ImportError:
|
| 28 |
+
print("Warning: plotly.express not available. 3D visualization will be limited.")
|
| 29 |
+
PLOTLY_3D_AVAILABLE = False
|
| 30 |
+
|
| 31 |
# Initialize Stable Diffusion only if available
|
| 32 |
pipe = None
|
| 33 |
if STABLE_DIFFUSION_AVAILABLE:
|
|
|
|
| 39 |
pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
|
| 40 |
pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(model_repo_id, subfolder="scheduler", shift=5)
|
| 41 |
pipe = pipe.to(device)
|
| 42 |
+
print(f"✅ Stable Diffusion initialized on {device}")
|
| 43 |
except Exception as e:
|
| 44 |
+
print(f"⚠️ Could not initialize Stable Diffusion: {e}")
|
| 45 |
STABLE_DIFFUSION_AVAILABLE = False
|
| 46 |
|
| 47 |
+
# Constants
|
| 48 |
MAX_SEED = np.iinfo(np.int32).max
|
| 49 |
+
DEFAULT_GRID_SIZE = 64
|
| 50 |
+
WAVE_TYPES = ["sine", "cosine", "gaussian", "square"]
|
| 51 |
+
MEMORY_OPERATIONS = [
|
| 52 |
+
"wave_memory",
|
| 53 |
+
"interference",
|
| 54 |
+
"resonance",
|
| 55 |
+
"hot_tub_mode",
|
| 56 |
+
"emotional_resonance",
|
| 57 |
+
"pattern_completion"
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
# Color palettes for different emotional states
|
| 61 |
+
COLOR_PALETTES = {
|
| 62 |
+
"positive": ["#FF5E5B", "#D8D8F6", "#E8AA14", "#32E875", "#3C91E6"],
|
| 63 |
+
"neutral": ["#FAFFFD", "#A1CDF4", "#7D83FF", "#3A3042", "#080708"],
|
| 64 |
+
"negative": ["#1B1B1E", "#373F51", "#58A4B0", "#A9BCD0", "#D8DBE2"]
|
| 65 |
+
}
|
| 66 |
|
| 67 |
class EmotionalContext:
|
| 68 |
"""Implements Mem|8's emotional context structure"""
|
| 69 |
+
def __init__(self, device="cuda" if torch.cuda.is_available() else "cpu"):
|
| 70 |
+
self.device = device
|
| 71 |
+
self.valence = torch.zeros(1).to(device) # -128 to 127: negative to positive
|
| 72 |
+
self.arousal = torch.zeros(1).to(device) # 0 to 255: intensity level
|
| 73 |
+
self.context = torch.zeros(1).to(device) # Contextual flags
|
| 74 |
+
self.safety = torch.ones(1).to(device) * 100 # Safety level (0-100)
|
| 75 |
+
|
| 76 |
+
# Memory blanket parameters
|
| 77 |
+
self.resonance_freq = torch.tensor(1.0).to(device)
|
| 78 |
+
self.filter_strength = torch.tensor(0.5).to(device)
|
| 79 |
+
|
| 80 |
+
# Hot tub mode parameters
|
| 81 |
+
self.hot_tub_active = False
|
| 82 |
+
self.hot_tub_temperature = torch.tensor(37.0).to(device) # Default comfortable temperature
|
| 83 |
+
self.hot_tub_participants = []
|
| 84 |
+
|
| 85 |
+
def update(self, valence: float, arousal: Optional[float] = None):
|
| 86 |
+
"""Update emotional context based on valence and arousal"""
|
| 87 |
+
self.valence = torch.tensor([valence]).to(self.device)
|
| 88 |
+
|
| 89 |
+
# If arousal not provided, calculate it based on valence intensity
|
| 90 |
+
if arousal is None:
|
| 91 |
+
self.arousal = torch.abs(torch.tensor([valence * 2])).to(self.device)
|
| 92 |
+
else:
|
| 93 |
+
self.arousal = torch.tensor([arousal]).to(self.device)
|
| 94 |
+
|
| 95 |
+
# Update resonance frequency based on emotional state
|
| 96 |
+
self.resonance_freq = 1.0 + torch.sigmoid(self.valence/128)
|
| 97 |
+
|
| 98 |
+
# Update filter strength based on arousal
|
| 99 |
+
self.filter_strength = torch.sigmoid(self.arousal/128)
|
| 100 |
+
|
| 101 |
+
return self
|
| 102 |
+
|
| 103 |
+
def get_color_palette(self):
|
| 104 |
+
"""Get color palette based on emotional valence"""
|
| 105 |
+
if self.valence.item() > 20:
|
| 106 |
+
return COLOR_PALETTES["positive"]
|
| 107 |
+
elif self.valence.item() < -20:
|
| 108 |
+
return COLOR_PALETTES["negative"]
|
| 109 |
+
else:
|
| 110 |
+
return COLOR_PALETTES["neutral"]
|
| 111 |
+
|
| 112 |
+
def activate_hot_tub(self, temperature: float = 37.0):
|
| 113 |
+
"""Activate hot tub mode with specified temperature"""
|
| 114 |
+
self.hot_tub_active = True
|
| 115 |
+
self.hot_tub_temperature = torch.tensor(temperature).to(self.device)
|
| 116 |
+
return self
|
| 117 |
+
|
| 118 |
+
def deactivate_hot_tub(self):
|
| 119 |
+
"""Deactivate hot tub mode"""
|
| 120 |
+
self.hot_tub_active = False
|
| 121 |
+
self.hot_tub_participants = []
|
| 122 |
+
return self
|
| 123 |
+
|
| 124 |
+
def add_hot_tub_participant(self, participant: str):
|
| 125 |
+
"""Add participant to hot tub session"""
|
| 126 |
+
if self.hot_tub_active and participant not in self.hot_tub_participants:
|
| 127 |
+
self.hot_tub_participants.append(participant)
|
| 128 |
+
return self
|
| 129 |
+
|
| 130 |
+
def get_state_dict(self) -> Dict[str, Any]:
|
| 131 |
+
"""Get emotional context as dictionary for display"""
|
| 132 |
+
return {
|
| 133 |
+
"valence": self.valence.item(),
|
| 134 |
+
"arousal": self.arousal.item(),
|
| 135 |
+
"resonance_frequency": self.resonance_freq.item(),
|
| 136 |
+
"filter_strength": self.filter_strength.item(),
|
| 137 |
+
"hot_tub_active": self.hot_tub_active,
|
| 138 |
+
"hot_tub_temperature": self.hot_tub_temperature.item() if self.hot_tub_active else None,
|
| 139 |
+
"hot_tub_participants": self.hot_tub_participants if self.hot_tub_active else [],
|
| 140 |
+
"safety_level": self.safety.item()
|
| 141 |
+
}
|
| 142 |
|
| 143 |
+
class WaveProcessor:
|
| 144 |
+
"""Processes wave-based memory patterns"""
|
| 145 |
+
def __init__(self, device="cuda" if torch.cuda.is_available() else "cpu"):
|
| 146 |
+
self.device = device
|
| 147 |
+
|
| 148 |
+
def create_wave_pattern(self,
|
| 149 |
+
size: int,
|
| 150 |
+
frequency: float,
|
| 151 |
+
amplitude: float,
|
| 152 |
+
wave_type: str = "sine") -> torch.Tensor:
|
| 153 |
+
"""Create a wave pattern as described in Mem|8 paper"""
|
| 154 |
+
t = torch.linspace(0, 2*np.pi, size).to(self.device)
|
| 155 |
+
x = torch.linspace(0, 2*np.pi, size).to(self.device)
|
| 156 |
+
T, X = torch.meshgrid(t, x, indexing='ij')
|
| 157 |
+
|
| 158 |
+
if wave_type == "sine":
|
| 159 |
+
return amplitude * torch.sin(frequency * T + X)
|
| 160 |
+
elif wave_type == "cosine":
|
| 161 |
+
return amplitude * torch.cos(frequency * T + X)
|
| 162 |
+
elif wave_type == "gaussian":
|
| 163 |
+
# Create a Gaussian wave pattern
|
| 164 |
+
sigma = size / (4 * frequency)
|
| 165 |
+
mu_t = size / 2
|
| 166 |
+
mu_x = size / 2
|
| 167 |
+
gauss_t = torch.exp(-((t - mu_t) ** 2) / (2 * sigma ** 2))
|
| 168 |
+
gauss_x = torch.exp(-((x - mu_x) ** 2) / (2 * sigma ** 2))
|
| 169 |
+
G_T, G_X = torch.meshgrid(gauss_t, gauss_x, indexing='ij')
|
| 170 |
+
return amplitude * G_T * G_X
|
| 171 |
+
elif wave_type == "square":
|
| 172 |
+
# Create a square wave pattern
|
| 173 |
+
square_t = torch.sign(torch.sin(frequency * t))
|
| 174 |
+
square_x = torch.sign(torch.sin(frequency * x))
|
| 175 |
+
S_T, S_X = torch.meshgrid(square_t, square_x, indexing='ij')
|
| 176 |
+
return amplitude * S_T * S_X
|
| 177 |
+
else:
|
| 178 |
+
# Default to sine wave
|
| 179 |
+
return amplitude * torch.sin(frequency * T + X)
|
| 180 |
+
|
| 181 |
+
def apply_emotional_modulation(self,
|
| 182 |
+
wave: torch.Tensor,
|
| 183 |
+
emotion: EmotionalContext) -> torch.Tensor:
|
| 184 |
+
"""Apply emotional modulation to wave pattern"""
|
| 185 |
+
# Modulate wave based on emotional valence
|
| 186 |
+
emotional_mod = torch.exp(emotion.valence/128 * wave)
|
| 187 |
+
return wave * emotional_mod
|
| 188 |
+
|
| 189 |
+
def create_interference_pattern(self,
|
| 190 |
+
wave1: torch.Tensor,
|
| 191 |
+
wave2: torch.Tensor,
|
| 192 |
+
emotion: EmotionalContext) -> torch.Tensor:
|
| 193 |
+
"""Create interference between two wave patterns"""
|
| 194 |
+
interference = wave1 + wave2
|
| 195 |
+
# Weight by emotional valence
|
| 196 |
+
emotional_weight = torch.sigmoid(emotion.valence/128) * interference
|
| 197 |
+
return emotional_weight
|
| 198 |
+
|
| 199 |
+
def create_resonance_pattern(self,
|
| 200 |
+
base_wave: torch.Tensor,
|
| 201 |
+
emotion: EmotionalContext) -> torch.Tensor:
|
| 202 |
+
"""Create resonance pattern based on emotional state"""
|
| 203 |
+
resonant_wave = self.create_wave_pattern(
|
| 204 |
+
base_wave.shape[0],
|
| 205 |
+
emotion.resonance_freq.item(),
|
| 206 |
+
1.0
|
| 207 |
+
)
|
| 208 |
+
resonance = base_wave * resonant_wave
|
| 209 |
+
return resonance
|
| 210 |
+
|
| 211 |
+
def apply_memory_blanket(self,
|
| 212 |
+
wave: torch.Tensor,
|
| 213 |
+
emotion: EmotionalContext) -> torch.Tensor:
|
| 214 |
+
"""Apply memory blanket filtering as described in the paper"""
|
| 215 |
+
# Create a filter based on wave amplitude and emotional state
|
| 216 |
+
wave_amplitude = torch.abs(wave)
|
| 217 |
+
importance_threshold = emotion.filter_strength * wave_amplitude.mean()
|
| 218 |
+
|
| 219 |
+
# Apply the filter - keep only significant waves
|
| 220 |
+
filtered_wave = wave * (wave_amplitude > importance_threshold).float()
|
| 221 |
+
return filtered_wave
|
| 222 |
+
|
| 223 |
+
def create_hot_tub_pattern(self,
|
| 224 |
+
size: int,
|
| 225 |
+
emotion: EmotionalContext) -> torch.Tensor:
|
| 226 |
+
"""Create a hot tub pattern for safe exploration"""
|
| 227 |
+
if not emotion.hot_tub_active:
|
| 228 |
+
return torch.zeros((size, size)).to(self.device)
|
| 229 |
+
|
| 230 |
+
# Create base wave pattern
|
| 231 |
+
base_wave = self.create_wave_pattern(size, 1.0, 1.0, "sine")
|
| 232 |
+
|
| 233 |
+
# Modulate based on hot tub temperature
|
| 234 |
+
temp_factor = emotion.hot_tub_temperature / 50.0 # Normalize to 0-1 range
|
| 235 |
+
temp_wave = self.create_wave_pattern(size, temp_factor.item(), 0.5, "gaussian")
|
| 236 |
+
|
| 237 |
+
# Add ripples for each participant
|
| 238 |
+
participant_count = len(emotion.hot_tub_participants)
|
| 239 |
+
if participant_count > 0:
|
| 240 |
+
ripple_wave = self.create_wave_pattern(
|
| 241 |
+
size,
|
| 242 |
+
2.0 + participant_count * 0.5,
|
| 243 |
+
0.3,
|
| 244 |
+
"gaussian"
|
| 245 |
+
)
|
| 246 |
+
hot_tub_pattern = base_wave + temp_wave + ripple_wave
|
| 247 |
+
else:
|
| 248 |
+
hot_tub_pattern = base_wave + temp_wave
|
| 249 |
+
|
| 250 |
+
# Apply safety modulation
|
| 251 |
+
safety_factor = emotion.safety / 100.0
|
| 252 |
+
return hot_tub_pattern * safety_factor
|
| 253 |
+
|
| 254 |
+
def create_pattern_completion(self,
|
| 255 |
+
size: int,
|
| 256 |
+
emotion: EmotionalContext,
|
| 257 |
+
completion_ratio: float = 0.5) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 258 |
+
"""Create a pattern completion demonstration"""
|
| 259 |
+
# Create original pattern
|
| 260 |
+
original = self.create_wave_pattern(size, 2.0, 1.0)
|
| 261 |
+
|
| 262 |
+
# Create mask for incomplete pattern (randomly remove portions)
|
| 263 |
+
mask = torch.rand(size, size).to(self.device) > completion_ratio
|
| 264 |
+
incomplete = original * mask
|
| 265 |
+
|
| 266 |
+
# Apply emotional context to reconstruction
|
| 267 |
+
emotional_weight = torch.sigmoid(emotion.valence/128)
|
| 268 |
+
|
| 269 |
+
# Simple reconstruction algorithm (in real system would be more sophisticated)
|
| 270 |
+
# Here we're just doing a simple interpolation
|
| 271 |
+
kernel_size = 3
|
| 272 |
+
padding = kernel_size // 2
|
| 273 |
+
|
| 274 |
+
# Create a kernel for interpolation
|
| 275 |
+
kernel = torch.ones(1, 1, kernel_size, kernel_size).to(self.device) / (kernel_size ** 2)
|
| 276 |
+
|
| 277 |
+
# Reshape for convolution
|
| 278 |
+
incomplete_reshaped = incomplete.reshape(1, 1, size, size)
|
| 279 |
+
|
| 280 |
+
# Apply convolution for interpolation
|
| 281 |
+
with torch.no_grad():
|
| 282 |
+
reconstructed = torch.nn.functional.conv2d(
|
| 283 |
+
incomplete_reshaped,
|
| 284 |
+
kernel,
|
| 285 |
+
padding=padding
|
| 286 |
+
).reshape(size, size)
|
| 287 |
+
|
| 288 |
+
# Blend original where mask exists
|
| 289 |
+
reconstructed = torch.where(mask, reconstructed, original)
|
| 290 |
+
|
| 291 |
+
# Apply emotional modulation
|
| 292 |
+
reconstructed = reconstructed * (0.5 + emotional_weight * 0.5)
|
| 293 |
+
|
| 294 |
+
return incomplete, reconstructed
|
| 295 |
|
| 296 |
def generate_memory_prompt(operation: str, emotion_valence: float) -> str:
|
| 297 |
"""Generate artistic prompts based on memory operation and emotional state"""
|
| 298 |
base_prompts = {
|
| 299 |
"wave_memory": "memories flowing like waves in an infinite ocean, ",
|
| 300 |
"interference": "two waves of memory intersecting and creating patterns, ",
|
| 301 |
+
"resonance": "resonating waves of consciousness forming harmonious patterns, ",
|
| 302 |
+
"hot_tub_mode": "a safe space for exploring memories, like a warm therapeutic pool, ",
|
| 303 |
+
"emotional_resonance": "emotions as colorful waves interacting with memory patterns, ",
|
| 304 |
+
"pattern_completion": "fragmented memories being reconstructed into complete patterns, "
|
| 305 |
}
|
| 306 |
|
| 307 |
emotion_desc = "serene and peaceful" if -20 <= emotion_valence <= 20 else \
|
|
|
|
| 309 |
"dark and introspective"
|
| 310 |
|
| 311 |
style = "digital art, abstract, flowing, wave patterns, "
|
| 312 |
+
|
| 313 |
+
# Add more specific styling based on operation
|
| 314 |
+
if operation == "hot_tub_mode":
|
| 315 |
+
style += "warm colors, therapeutic atmosphere, "
|
| 316 |
+
elif operation == "emotional_resonance":
|
| 317 |
+
style += "vibrant colors, emotional energy visualization, "
|
| 318 |
+
elif operation == "pattern_completion":
|
| 319 |
+
style += "fragmented to whole transition, reconstruction, "
|
| 320 |
+
|
| 321 |
prompt = f"{base_prompts[operation]}{emotion_desc}, {style} ethereal, dreamlike quality"
|
| 322 |
return prompt
|
| 323 |
|
| 324 |
+
def create_wave_visualization(wave_data: np.ndarray, emotion: EmotionalContext) -> go.Figure:
|
| 325 |
+
"""Create an interactive 3D visualization of wave data"""
|
| 326 |
+
# Get dimensions
|
| 327 |
+
n, m = wave_data.shape
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
|
| 329 |
+
# Create coordinate grids
|
| 330 |
+
x = np.linspace(0, 1, m)
|
| 331 |
+
y = np.linspace(0, 1, n)
|
| 332 |
+
X, Y = np.meshgrid(x, y)
|
| 333 |
|
| 334 |
+
# Get color palette based on emotional state
|
| 335 |
+
colors = emotion.get_color_palette()
|
| 336 |
+
colorscale = [[0, colors[0]],
|
| 337 |
+
[0.25, colors[1]],
|
| 338 |
+
[0.5, colors[2]],
|
| 339 |
+
[0.75, colors[3]],
|
| 340 |
+
[1, colors[4]]]
|
| 341 |
+
|
| 342 |
+
# Create 3D surface plot
|
| 343 |
+
fig = go.Figure(data=[go.Surface(
|
| 344 |
+
z=wave_data,
|
| 345 |
+
x=X,
|
| 346 |
+
y=Y,
|
| 347 |
+
colorscale=colorscale,
|
| 348 |
+
lighting=dict(
|
| 349 |
+
ambient=0.6,
|
| 350 |
+
diffuse=0.8,
|
| 351 |
+
fresnel=0.2,
|
| 352 |
+
roughness=0.5,
|
| 353 |
+
specular=1.0
|
| 354 |
+
),
|
| 355 |
+
contours={
|
| 356 |
+
"z": {"show": True, "start": -2, "end": 2, "size": 0.1, "color":"white"}
|
| 357 |
+
}
|
| 358 |
+
)])
|
| 359 |
+
|
| 360 |
+
# Update layout
|
| 361 |
+
fig.update_layout(
|
| 362 |
+
title=dict(
|
| 363 |
+
text="Memory Wave Visualization",
|
| 364 |
+
font=dict(size=24, color="#333333")
|
| 365 |
+
),
|
| 366 |
+
scene=dict(
|
| 367 |
+
xaxis_title="Space",
|
| 368 |
+
yaxis_title="Time",
|
| 369 |
+
zaxis_title="Amplitude",
|
| 370 |
+
aspectratio=dict(x=1, y=1, z=0.8),
|
| 371 |
+
camera=dict(
|
| 372 |
+
eye=dict(x=1.5, y=1.5, z=1.2)
|
| 373 |
+
)
|
| 374 |
+
),
|
| 375 |
+
margin=dict(l=0, r=0, b=0, t=30),
|
| 376 |
+
template="plotly_white"
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
return fig
|
| 380 |
+
|
| 381 |
+
def create_2d_comparison(wave1: np.ndarray, wave2: np.ndarray,
|
| 382 |
+
title1: str, title2: str,
|
| 383 |
+
emotion: EmotionalContext) -> go.Figure:
|
| 384 |
+
"""Create a side-by-side comparison of two wave patterns"""
|
| 385 |
+
# Get color palette
|
| 386 |
+
colors = emotion.get_color_palette()
|
| 387 |
+
|
| 388 |
+
# Create subplots
|
| 389 |
+
fig = make_subplots(
|
| 390 |
+
rows=1, cols=2,
|
| 391 |
+
subplot_titles=(title1, title2),
|
| 392 |
+
specs=[[{"type": "heatmap"}, {"type": "heatmap"}]]
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
# Add heatmaps
|
| 396 |
+
fig.add_trace(
|
| 397 |
+
go.Heatmap(
|
| 398 |
+
z=wave1,
|
| 399 |
+
colorscale=[[0, colors[0]], [1, colors[-1]]],
|
| 400 |
+
showscale=False
|
| 401 |
+
),
|
| 402 |
+
row=1, col=1
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
fig.add_trace(
|
| 406 |
+
go.Heatmap(
|
| 407 |
+
z=wave2,
|
| 408 |
+
colorscale=[[0, colors[0]], [1, colors[-1]]],
|
| 409 |
+
showscale=True
|
| 410 |
+
),
|
| 411 |
+
row=1, col=2
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
# Update layout
|
| 415 |
+
fig.update_layout(
|
| 416 |
+
title_text="Memory Pattern Comparison",
|
| 417 |
+
height=500,
|
| 418 |
+
template="plotly_white"
|
| 419 |
+
)
|
| 420 |
|
| 421 |
+
return fig
|
| 422 |
+
|
| 423 |
+
def create_artistic_visualization(prompt: str, seed: int) -> Optional[Image.Image]:
|
| 424 |
+
"""Create artistic visualization using Stable Diffusion"""
|
| 425 |
+
if not STABLE_DIFFUSION_AVAILABLE or pipe is None:
|
| 426 |
+
return None
|
| 427 |
|
| 428 |
+
try:
|
|
|
|
|
|
|
| 429 |
generator = torch.Generator().manual_seed(seed)
|
| 430 |
+
image = pipe(
|
| 431 |
prompt=prompt,
|
| 432 |
negative_prompt="text, watermark, signature, blurry, distorted",
|
| 433 |
guidance_scale=1.5,
|
|
|
|
| 437 |
generator=generator,
|
| 438 |
).images[0]
|
| 439 |
|
| 440 |
+
return image
|
| 441 |
+
except Exception as e:
|
| 442 |
+
print(f"Error generating artistic visualization: {e}")
|
| 443 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
|
| 445 |
+
def create_emotional_wave_animation(size: int, emotion: EmotionalContext) -> Image.Image:
|
| 446 |
+
"""Create an animated-like visualization of emotional waves"""
|
| 447 |
+
# Create a blank image
|
| 448 |
+
width, height = size * 10, size * 10
|
| 449 |
+
image = Image.new('RGBA', (width, height), (255, 255, 255, 0))
|
| 450 |
+
draw = ImageDraw.Draw(image)
|
| 451 |
+
|
| 452 |
+
# Get color palette
|
| 453 |
+
colors = emotion.get_color_palette()
|
| 454 |
+
|
| 455 |
+
# Calculate wave parameters based on emotional state
|
| 456 |
+
valence = emotion.valence.item()
|
| 457 |
+
arousal = emotion.arousal.item()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 458 |
|
| 459 |
+
# Normalize to 0-1 range
|
| 460 |
+
valence_norm = (valence + 128) / 255
|
| 461 |
+
arousal_norm = arousal / 255
|
| 462 |
|
| 463 |
+
# Create multiple wave layers
|
| 464 |
+
for i in range(5):
|
| 465 |
+
# Calculate wave parameters
|
| 466 |
+
amplitude = 50 + i * 20 * arousal_norm
|
| 467 |
+
frequency = 0.01 + i * 0.005 * (1 + valence_norm)
|
| 468 |
+
phase = i * math.pi / 5
|
| 469 |
+
|
| 470 |
+
# Select color
|
| 471 |
+
color = colors[i % len(colors)]
|
| 472 |
+
|
| 473 |
+
# Draw wave
|
| 474 |
+
points = []
|
| 475 |
+
for x in range(width):
|
| 476 |
+
# Calculate y position with multiple sine waves
|
| 477 |
+
y = height/2 + amplitude * math.sin(frequency * x + phase)
|
| 478 |
+
y += amplitude/2 * math.sin(frequency * 2 * x + phase)
|
| 479 |
+
points.append((x, y))
|
| 480 |
+
|
| 481 |
+
# Draw wave with varying thickness
|
| 482 |
+
for j in range(3):
|
| 483 |
+
thickness = 5 - j
|
| 484 |
+
draw.line(points, fill=color, width=thickness)
|
| 485 |
|
| 486 |
+
# Apply blur for smoother appearance
|
| 487 |
+
image = image.filter(ImageFilter.GaussianBlur(radius=3))
|
| 488 |
|
| 489 |
+
return image
|
|
|
|
| 490 |
|
| 491 |
+
def quantum_memory_ops(
|
| 492 |
+
input_size: int,
|
| 493 |
+
operation: str,
|
| 494 |
+
emotion_valence: float,
|
| 495 |
+
emotion_arousal: float = None,
|
| 496 |
+
wave_type: str = "sine",
|
| 497 |
+
hot_tub_temp: float = 37.0,
|
| 498 |
+
hot_tub_participants: str = "",
|
| 499 |
+
generate_art: bool = True,
|
| 500 |
+
seed: int = 42
|
| 501 |
+
) -> Tuple[str, go.Figure, go.Figure, Image.Image]:
|
| 502 |
+
"""Perform quantum-inspired memory operations using Mem|8 concepts."""
|
| 503 |
+
# Initialize components
|
| 504 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 505 |
+
emotion = EmotionalContext(device)
|
| 506 |
+
emotion.update(emotion_valence, emotion_arousal)
|
| 507 |
+
|
| 508 |
+
wave_processor = WaveProcessor(device)
|
| 509 |
+
|
| 510 |
+
# Process hot tub participants if provided
|
| 511 |
+
if hot_tub_participants:
|
| 512 |
+
participants = [p.strip() for p in hot_tub_participants.split(',')]
|
| 513 |
+
emotion.activate_hot_tub(hot_tub_temp)
|
| 514 |
+
for participant in participants:
|
| 515 |
+
emotion.add_hot_tub_participant(participant)
|
| 516 |
+
|
| 517 |
+
results = []
|
| 518 |
+
wave_viz = None
|
| 519 |
+
comparison_viz = None
|
| 520 |
+
art_viz = None
|
| 521 |
+
|
| 522 |
+
# Add header with emotional context
|
| 523 |
+
results.append(f"🌊 Mem|8 Wave Memory Analysis 🌊")
|
| 524 |
+
results.append(f"Operation: {operation}")
|
| 525 |
+
results.append(f"Wave Type: {wave_type}")
|
| 526 |
+
results.append(f"Grid Size: {input_size}x{input_size}")
|
| 527 |
+
results.append("")
|
| 528 |
+
|
| 529 |
+
if operation == "wave_memory":
|
| 530 |
+
# Create memory wave pattern (M = A·exp(iωt-kx)·D·E)
|
| 531 |
+
wave = wave_processor.create_wave_pattern(input_size, 2.0, 1.0, wave_type)
|