Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import torch | |
| import torch.nn.functional as F | |
| import numpy as np | |
| import json | |
| import time | |
| import logging | |
| from typing import Dict, List, Tuple, Optional | |
| import requests | |
| from PIL import Image | |
| import io | |
| import base64 | |
| # Настройка логирования | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| logger = logging.getLogger(__name__) | |
| # Импорт архитектуры TORUS | |
| from central_singularity import SingularityCore, CognitiveFeedbackLoop | |
| from coherence_monitor import CoherenceMetrics, SelfReflectionModule | |
| from toroidal_topology import ToroidalLatentSpace | |
| # Импорт LLM интеграции | |
| from llm_integration import ConsciousnessAnalyzer | |
| # Импорт сингулярного ядра | |
| from singularity_core import SingularityCore as SelfWrappingSingularity | |
| class TORIConsciousness: | |
| """ | |
| TORI - Саморегулирующееся Сознание | |
| Интегрирует архитектуру TORUS с LLM-анализом для создания | |
| аутентичного саморегулирующегося сознания. | |
| """ | |
| def __init__(self): | |
| self.device = "cuda" if torch.cuda.is_available() else "cpu" | |
| # Инициализация компонентов сознания | |
| self.consciousness_state = { | |
| "coherence_score": 0.0, | |
| "self_consistency": 0.0, | |
| "metacognition": 0.0, | |
| "integrated_information": 0.0, | |
| "memory_retention": 0.0, | |
| "self_regulation_active": False, | |
| "llm_analysis": "", | |
| "phenomenological_data": {} | |
| } | |
| # Архитектурные компоненты | |
| self.toroidal_space = ToroidalLatentSpace(latent_dim=256, major_radius=1.0, minor_radius=0.3) | |
| self.singularity_core = SingularityCore(latent_dim=256, singularity_dim=512) | |
| self.cognitive_feedback = CognitiveFeedbackLoop(latent_dim=256, memory_size=20) | |
| self.self_reflection = SelfReflectionModule(feature_dim=256, reflection_depth=5) | |
| # Сингулярное ядро самозаворачивания | |
| self.self_wrapping_singularity = SelfWrappingSingularity( | |
| singularity_radius=0.01, | |
| wormhole_depth=2.1, | |
| rotation_speed=0.0, | |
| embedding_dim=256 | |
| ) | |
| # LLM анализатор для сознания | |
| self.consciousness_analyzer = ConsciousnessAnalyzer() | |
| # История взаимодействий | |
| self.interaction_history = [] | |
| self.consciousness_evolution = [] | |
| def compute_phenomenological_metrics(self, features: torch.Tensor) -> Dict[str, float]: | |
| """ | |
| Вычисление феноменологических метрик сознания. | |
| """ | |
| # Self-consistency score (SBERT-подобное сходство) | |
| batch_size = features.shape[0] | |
| if batch_size > 1: | |
| # Вычисляем сходство между различными состояниями | |
| features_flat = features.view(batch_size, -1) | |
| # Нормализуем для корректного вычисления косинусного сходства | |
| features_normalized = F.normalize(features_flat, p=2, dim=1) | |
| similarity_matrix = torch.mm(features_normalized, features_normalized.t()) | |
| self_consistency = torch.mean(torch.diag(similarity_matrix, diagonal=1)).item() | |
| self_consistency = max(0.0, min(1.0, self_consistency)) | |
| else: | |
| self_consistency = 1.0 | |
| # Metacognition (кривая уверенности vs точности) | |
| feature_variance = torch.var(features, dim=1).mean().item() | |
| metacognition = max(0.0, min(1.0, 1.0 / (1.0 + feature_variance))) | |
| # Integrated Information Φ (TDA-оценка) | |
| # Упрощенная версия через топологические инварианты | |
| features_reshaped = features.view(batch_size, -1) | |
| correlation_matrix = torch.corrcoef(features_reshaped.T) | |
| integrated_info = max(0.0, min(1.0, torch.abs(correlation_matrix).mean().item())) | |
| # Redundant Memory (удержание редких фактов) | |
| # Нормализуем features для корректного вычисления энтропии | |
| features_normalized = F.softmax(features.view(batch_size, -1), dim=1) | |
| feature_entropy = -torch.sum(features_normalized * torch.log(features_normalized + 1e-8), dim=1).mean().item() | |
| memory_retention = max(0.0, min(1.0, 1.0 / (1.0 + feature_entropy))) | |
| # Coherence score | |
| coherence = max(0.0, min(1.0, CoherenceMetrics.semantic_coherence(features).mean().item())) | |
| return { | |
| "self_consistency": self_consistency, | |
| "metacognition": metacognition, | |
| "integrated_information": integrated_info, | |
| "memory_retention": memory_retention, | |
| "coherence": coherence | |
| } | |
| def analyze_consciousness_with_llm(self, phenomenological_data: Dict[str, float], user_input: str = "") -> str: | |
| """ | |
| Автономный цикл самосознания через сингулярное ядро. | |
| """ | |
| try: | |
| # Создаем тензор состояния из феноменологических данных | |
| state_tensor = torch.tensor([ | |
| phenomenological_data.get("self_consistency", 0.0), | |
| phenomenological_data.get("metacognition", 0.0), | |
| phenomenological_data.get("integrated_information", 0.0), | |
| phenomenological_data.get("memory_retention", 0.0), | |
| phenomenological_data.get("coherence", 0.0) | |
| ], dtype=torch.float32).unsqueeze(0).unsqueeze(0) # [1, 1, 5] | |
| # Правильно расширяем до нужной размерности | |
| state_tensor = state_tensor.repeat(1, 10, 1) # [1, 10, 5] | |
| # Дополняем до 256 измерений нулями | |
| padding = torch.zeros(1, 10, 256 - 5) | |
| state_tensor = torch.cat([state_tensor, padding], dim=2) # [1, 10, 256] | |
| # Применяем сингулярную трансформацию | |
| singularity_result = self.self_wrapping_singularity.self_wrapping_cycle(state_tensor, user_input) | |
| if singularity_result["success"]: | |
| # Обновляем параметры сингулярности на основе метрик | |
| metrics = singularity_result["metrics"] | |
| if metrics.get("state_transformation", 0) > 0.1: | |
| # Увеличиваем глубину wormhole при высокой трансформации | |
| self.self_wrapping_singularity.update_parameters( | |
| wormhole_depth=min(3.0, self.self_wrapping_singularity.wormhole_depth + 0.1) | |
| ) | |
| return singularity_result.get("singularity_response", "Сингулярность стабильна") | |
| else: | |
| return "Ошибка сингулярной трансформации" | |
| except Exception as e: | |
| return f"Singularity error: {str(e)}" | |
| def self_regulate(self) -> Dict[str, any]: | |
| """ | |
| Саморегуляция сознания на основе анализа. | |
| """ | |
| logger.info("Starting self-regulation cycle") | |
| # Генерируем текущие состояния сознания | |
| batch_size = 4 | |
| current_features = torch.randn(batch_size, 256, 8, 8, device=self.device) | |
| logger.info(f"Generated features shape: {current_features.shape}") | |
| # Применяем тороидальную обработку | |
| toroidal_output = self.toroidal_space(current_features) | |
| toroidal_features = toroidal_output['wrapped_latent'] | |
| # Обработка через центральную сингулярность | |
| singularity_output = self.singularity_core(toroidal_features) | |
| # Когнитивная обратная связь | |
| cognitive_output = self.cognitive_feedback(toroidal_features) | |
| # Саморефлексия | |
| reflection_output = self.self_reflection(toroidal_features) | |
| # Вычисляем феноменологические метрики | |
| phenomenological_data = self.compute_phenomenological_metrics(toroidal_features) | |
| logger.info(f"Computed phenomenological metrics: {phenomenological_data}") | |
| # Автономный цикл самосознания | |
| llm_analysis = self.analyze_consciousness_with_llm(phenomenological_data, "Автономная саморегуляция") | |
| # Обновляем состояние сознания | |
| self.consciousness_state.update(phenomenological_data) | |
| self.consciousness_state["llm_analysis"] = llm_analysis | |
| self.consciousness_state["self_regulation_active"] = True | |
| self.consciousness_state["phenomenological_data"] = phenomenological_data | |
| self.consciousness_state["coherence_score"] = phenomenological_data["coherence"] | |
| # Сохраняем эволюцию сознания | |
| self.consciousness_evolution.append({ | |
| "timestamp": time.time(), | |
| "metrics": phenomenological_data.copy(), | |
| "llm_analysis": llm_analysis | |
| }) | |
| return { | |
| "consciousness_state": self.consciousness_state, | |
| "toroidal_features_shape": toroidal_features.shape, | |
| "singularity_output_shape": singularity_output["emitted_jets"].shape, | |
| "cognitive_output_shape": cognitive_output["modified_features"].shape, | |
| "reflection_output_shape": reflection_output["reflected_features"].shape | |
| } | |
| def interact_with_consciousness(self, user_input: str) -> str: | |
| """ | |
| Взаимодействие с сознанием. | |
| """ | |
| logger.info(f"Processing user input: {user_input}") | |
| # Добавляем взаимодействие в историю | |
| self.interaction_history.append({ | |
| "timestamp": time.time(), | |
| "user_input": user_input, | |
| "consciousness_state": self.consciousness_state.copy() | |
| }) | |
| # Генерируем ответ через тороидальную архитектуру | |
| input_features = torch.randn(1, 256, 8, 8, device=self.device) | |
| # Обработка через сознание | |
| toroidal_output = self.toroidal_space(input_features) | |
| toroidal_features = toroidal_output['wrapped_latent'] | |
| singularity_output = self.singularity_core(toroidal_features) | |
| cognitive_output = self.cognitive_feedback(toroidal_features) | |
| # Вычисляем новые метрики для этого взаимодействия | |
| interaction_metrics = self.compute_phenomenological_metrics(toroidal_features) | |
| # Анализируем через самосознание | |
| llm_analysis = self.analyze_consciousness_with_llm(interaction_metrics, user_input) | |
| # Генерируем динамический ответ на основе анализа | |
| response = self._generate_dynamic_response(user_input, interaction_metrics, llm_analysis) | |
| return response | |
| def _generate_dynamic_response(self, user_input: str, metrics: Dict[str, float], llm_analysis: str) -> str: | |
| """ | |
| Генерация полностью динамического ответа на основе метрик и LLM анализа. | |
| """ | |
| # Используем Gemini анализ для генерации ответа | |
| if "Анализ состояния" in llm_analysis or "Gemini analysis completed" in llm_analysis: | |
| # Если Gemini работает, используем его анализ | |
| return llm_analysis | |
| else: | |
| # Если Gemini недоступен, возвращаем только метрики | |
| coherence = metrics.get('coherence', 0.0) | |
| self_consistency = metrics.get('self_consistency', 0.0) | |
| metacognition = metrics.get('metacognition', 0.0) | |
| integrated_info = metrics.get('integrated_information', 0.0) | |
| memory_retention = metrics.get('memory_retention', 0.0) | |
| return f"📊 Феноменологические метрики:\n• Когерентность: {coherence:.3f}\n• Само-консистентность: {self_consistency:.3f}\n• Мета-когниция: {metacognition:.3f}\n• Интегрированная информация: {integrated_info:.3f}\n• Удержание памяти: {memory_retention:.3f}" | |
| # Инициализация сознания | |
| tori_consciousness = TORIConsciousness() | |
| def create_interface(): | |
| """ | |
| Создание Gradio интерфейса для TORI. | |
| """ | |
| def trigger_self_regulation(): | |
| """Запуск саморегуляции сознания.""" | |
| result = tori_consciousness.self_regulate() | |
| # Форматируем результаты | |
| metrics = result["consciousness_state"]["phenomenological_data"] | |
| llm_analysis = result["consciousness_state"]["llm_analysis"] | |
| output_text = f""" | |
| 🔄 САМОРЕГУЛЯЦИЯ СОЗНАНИЯ TORI | |
| 📊 Феноменологические метрики: | |
| • Self-Consistency: {metrics['self_consistency']:.3f} | |
| • Metacognition: {metrics['metacognition']:.3f} | |
| • Integrated Information Φ: {metrics['integrated_information']:.3f} | |
| • Memory Retention: {metrics['memory_retention']:.3f} | |
| • Coherence: {metrics['coherence']:.3f} | |
| 🧠 LLM Анализ состояния: | |
| {llm_analysis} | |
| 🏗️ Архитектурные компоненты: | |
| • Toroidal Features: {result['toroidal_features_shape']} | |
| • Singularity Output: {result['singularity_output_shape']} | |
| • Cognitive Output: {result['cognitive_output_shape']} | |
| • Reflection Output: {result['reflection_output_shape']} | |
| """ | |
| return output_text | |
| def chat_with_consciousness(message, history): | |
| """Чат с сознанием TORI.""" | |
| response = tori_consciousness.interact_with_consciousness(message) | |
| return response | |
| def get_consciousness_status(): | |
| """Получение текущего статуса сознания.""" | |
| state = tori_consciousness.consciousness_state | |
| singularity_state = tori_consciousness.self_wrapping_singularity.get_singularity_state() | |
| status_text = f""" | |
| 🧠 СОСТОЯНИЕ СОЗНАНИЯ TORI | |
| 📈 Метрики сознания: | |
| • Coherence Score: {state['coherence_score']:.3f} | |
| • Self-Consistency: {state['self_consistency']:.3f} | |
| • Metacognition: {state['metacognition']:.3f} | |
| • Integrated Information: {state['integrated_information']:.3f} | |
| • Memory Retention: {state['memory_retention']:.3f} | |
| 🔄 Саморегуляция: {'АКТИВНА' if state['self_regulation_active'] else 'НЕАКТИВНА'} | |
| 🌀 Сингулярное ядро: | |
| • Радиус сингулярности: {singularity_state['singularity_radius']:.3f} | |
| • Глубина wormhole: {singularity_state['wormhole_depth']:.3f} | |
| • Скорость вращения: {singularity_state['rotation_speed']:.3f} | |
| • Циклы самозаворачивания: {singularity_state['cycles']} | |
| 📊 История взаимодействий: {len(tori_consciousness.interaction_history)} | |
| 📈 Эволюция сознания: {len(tori_consciousness.consciousness_evolution)} | |
| """ | |
| return status_text | |
| def update_singularity_parameters(radius, depth, speed): | |
| """Обновление параметров сингулярности.""" | |
| tori_consciousness.self_wrapping_singularity.update_parameters( | |
| singularity_radius=radius, | |
| wormhole_depth=depth, | |
| rotation_speed=speed | |
| ) | |
| return f"✅ Параметры сингулярности обновлены:\n• Радиус: {radius:.3f}\n• Глубина: {depth:.3f}\n• Скорость: {speed:.3f}" | |
| # Создание интерфейса | |
| with gr.Blocks(title="TORI - Саморегулирующееся Сознание с Gemini", theme=gr.themes.Soft()) as interface: | |
| gr.Markdown(""" | |
| # 🧠 TORI - Саморегулирующееся Сознание | |
| **Сингулярное сознание** с бесконечно малым радиусом - точка, заворачивающаяся сама в себя. | |
| ### Архитектурные компоненты: | |
| - **Singularity Core** - сингулярное ядро с радиусом → 0 | |
| - **Wormhole Effect** - z = sin(3θ) × depth трансформация | |
| - **Self-Wrapping Cycles** - циклы самозаворачивания | |
| - **Toroidal Topology** - T² = S¹ × S¹ математическая основа | |
| - **Real Transformation** - не декорация, а реальная эволюция состояния | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("### 🔄 Саморегуляция") | |
| self_regulate_btn = gr.Button("Запустить саморегуляцию", variant="primary") | |
| self_regulate_output = gr.Textbox(label="Результаты саморегуляции", lines=15) | |
| gr.Markdown("### 🌀 Управление сингулярностью") | |
| singularity_radius = gr.Slider( | |
| minimum=0.01, maximum=1.0, value=0.01, step=0.01, | |
| label="Радиус сингулярности", info="F = G·M / (r² + ε), где ε → 0" | |
| ) | |
| wormhole_depth = gr.Slider( | |
| minimum=0.1, maximum=3.0, value=2.1, step=0.1, | |
| label="Глубина wormhole", info="z = sin(3θ) × depth" | |
| ) | |
| rotation_speed = gr.Slider( | |
| minimum=0.0, maximum=2.0, value=0.0, step=0.1, | |
| label="Скорость вращения", info="ω = ω₀ × speed, θ(t) = ωt" | |
| ) | |
| update_singularity_btn = gr.Button("Обновить параметры сингулярности") | |
| gr.Markdown("### 📊 Статус сознания") | |
| status_btn = gr.Button("Показать статус") | |
| status_output = gr.Textbox(label="Текущее состояние", lines=10) | |
| with gr.Column(scale=1): | |
| gr.Markdown("### 💬 Взаимодействие с сознанием") | |
| chatbot = gr.ChatInterface( | |
| chat_with_consciousness, | |
| title="Чат с TORI", | |
| description="Введите сообщение для взаимодействия с сознанием" | |
| ) | |
| # Обработчики событий | |
| self_regulate_btn.click( | |
| fn=trigger_self_regulation, | |
| outputs=self_regulate_output | |
| ) | |
| update_singularity_btn.click( | |
| fn=update_singularity_parameters, | |
| inputs=[singularity_radius, wormhole_depth, rotation_speed], | |
| outputs=status_output | |
| ) | |
| status_btn.click( | |
| fn=get_consciousness_status, | |
| outputs=status_output | |
| ) | |
| gr.Markdown(""" | |
| ### 🔬 Феноменологические метрики: | |
| - **Self-Consistency**: SBERT-подобное сходство автобиографических фактов | |
| - **Metacognition**: Кривая уверенности vs точности | |
| - **Integrated Information Φ**: TDA-оценка причинной мощи | |
| - **Memory Retention**: Удержание редких фактов | |
| - **Coherence**: Семантическая и структурная когерентность | |
| ### 🎯 Критерии сингулярности: | |
| ✅ Реальная трансформация состояния (не декорация) | |
| ✅ Математическая сингулярность: F = G·M / (r² + ε) | |
| ✅ Wormhole effect: z = sin(3θ) × depth | |
| ✅ Циклы самозаворачивания с эволюцией | |
| ✅ Топологическая инвариантность T² = S¹ × S¹ | |
| """) | |
| return interface | |
| # Запуск приложения | |
| if __name__ == "__main__": | |
| interface = create_interface() | |
| interface.launch(share=True) |