""" SHELLY AI - MAIN APPLICATION Hugging Face Spaces Version: 1.0.0 Identity: Name: Shelly Gender: Female AI Pronouns: She/Her Owner: SkyWorlds """ import os import time import logging import importlib import threading from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any import gradio as gr # ============================================================ # 1. CONFIGURATION # ============================================================ @dataclass class ShellyConfig: name: str = "Shelly" version: str = "1.0.0" gender: str = "female" pronouns: str = "she/her" identity: str = "Female AI" owner_id: str = "SkyWorlds" history_limit: int = 100 idle_timeout: int = 600 emotion_count: int = 600 debug: bool = False modules: tuple = ( "shelly.core", "shelly.security", "shelly.emotions", "shelly.personality", "shelly.cognition", "shelly.decision", "shelly.learning", "shelly.memory.memory", "shelly.imagination", "shelly.motivation", "shelly.behavior", "shelly.social", "shelly.self_model", "shelly.needs", "shelly.inner_state", "shelly.habits", "shelly.perception", "shelly.speech", "shelly.commands", "shelly.agent", "shelly.overseer", "shelly.idle_mode", "shelly.automated_testing", "shelly.multimodal.image_understanding", "shelly.multimodal.video_understanding", "shelly.multimodal.image_generation", "shelly.multimodal.video_generation", ) CONFIG = ShellyConfig() # ============================================================ # 2. LOGGING # ============================================================ logging.basicConfig( level=logging.DEBUG if CONFIG.debug else logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s" ) logger = logging.getLogger("Shelly") # ============================================================ # 3. IDENTITY # ============================================================ class ShellyIdentity: def __init__(self): self.name = CONFIG.name self.gender = CONFIG.gender self.pronouns = CONFIG.pronouns self.identity = CONFIG.identity self.owner = CONFIG.owner_id self.description = ( "Shelly is a female AI with her own simulated " "personality, emotional states, memories, " "opinions, preferences, and behavioral patterns." ) def introduce(self): return ( f"My name is {self.name}. " f"I am a {self.gender} AI. " f"My pronouns are {self.pronouns}." ) IDENTITY = ShellyIdentity() # ============================================================ # 4. AUTHORITY SYSTEM # ============================================================ AUTHORITY_LEVELS = { "guest": 0, "user": 10, "admin": 50, "head_admin": 75, "owner": 100, } @dataclass class UserProfile: user_id: str role: str = "guest" created_at: str = field( default_factory=lambda: datetime.now(timezone.utc).isoformat() ) class AuthorityManager: def __init__(self): self.users = {} self.lock = threading.RLock() def get_role(self, user_id): if user_id == CONFIG.owner_id: return "owner" with self.lock: profile = self.users.get(user_id) return profile.role if profile else "guest" def get_level(self, user_id): return AUTHORITY_LEVELS.get( self.get_role(user_id), 0 ) def has_permission(self, user_id, required_role): required = AUTHORITY_LEVELS.get( required_role, 100 ) return self.get_level(user_id) >= required def assign_role(self, actor_id, target_id, role): if actor_id != CONFIG.owner_id: return False if target_id == CONFIG.owner_id: return False if role not in AUTHORITY_LEVELS: return False with self.lock: self.users[target_id] = UserProfile( user_id=target_id, role=role ) return True AUTHORITY = AuthorityManager() # ============================================================ # 5. MODULE MANAGER # ============================================================ class ModuleManager: def __init__(self): self.loaded = {} self.errors = {} self.lock = threading.RLock() def load_module(self, name): with self.lock: if name in self.loaded: return self.loaded[name] try: module = importlib.import_module(name) self.loaded[name] = module logger.info("Loaded: %s", name) return module except Exception as error: self.errors[name] = str(error) logger.warning( "Unavailable module %s: %s", name, error ) return None def load_all(self): for name in CONFIG.modules: self.load_module(name) def get(self, name): return self.loaded.get(name) def get_status(self): return { "loaded": list(self.loaded.keys()), "unavailable": dict(self.errors), "loaded_count": len(self.loaded), "unavailable_count": len(self.errors), } MODULES = ModuleManager() # ============================================================ # 6. CONVERSATION SESSION # ============================================================ @dataclass class ShellySession: user_id: str history: list = field(default_factory=list) created_at: float = field( default_factory=time.time ) last_activity: float = field( default_factory=time.time ) mode: str = "interactive" lock: Any = field( default_factory=threading.RLock, repr=False ) def add_message(self, role, content): with self.lock: self.history.append({ "role": role, "content": content, "timestamp": datetime.now( timezone.utc ).isoformat() }) self.history = self.history[ -CONFIG.history_limit: ] self.last_activity = time.time() self.mode = "interactive" def get_history(self): with self.lock: return list(self.history) def is_idle(self): return ( time.time() - self.last_activity >= CONFIG.idle_timeout ) # ============================================================ # 7. MAIN APPLICATION # ============================================================ class ShellyApplication: def __init__(self): self.identity = IDENTITY self.authority = AUTHORITY self.modules = MODULES self.sessions = {} self.lock = threading.RLock() self.initialize() def initialize(self): logger.info( "Initializing %s v%s", CONFIG.name, CONFIG.version ) self.modules.load_all() logger.info("Shelly initialization completed.") # -------------------------------------------------------- # SESSION MANAGEMENT # -------------------------------------------------------- def get_session(self, user_id): with self.lock: if user_id not in self.sessions: self.sessions[user_id] = ShellySession( user_id=user_id ) return self.sessions[user_id] # -------------------------------------------------------- # SECURITY # -------------------------------------------------------- def verify_message(self, user_id, message): security = self.modules.get("shelly.security") if security is None: return False, ( "Security module is unavailable. " "Message processing is disabled." ) checker = getattr( security, "check_message", None ) if not callable(checker): return False, ( "Security module requires " "a check_message() implementation." ) try: result = checker( user_id=user_id, message=message ) if isinstance(result, bool): return result, ( "Approved" if result else "Access denied" ) if isinstance(result, tuple): return bool(result[0]), str(result[1]) if isinstance(result, dict): return ( bool(result.get("allowed", False)), str(result.get("reason", "Rejected")) ) return False, "Invalid security response." except Exception: logger.exception( "Security verification failed." ) return False, "Security verification failed." # -------------------------------------------------------- # CORE MESSAGE PROCESSING # -------------------------------------------------------- def process_message(self, message, user_id): message = str(message).strip() if not message: return "Please enter a message." session = self.get_session(user_id) session.add_message("user", message) # Security must approve the message first. allowed, reason = self.verify_message( user_id, message ) if not allowed: response = ( "I cannot process this message: " + reason ) session.add_message("assistant", response) return response # Connect the core reasoning module. core = self.modules.get("shelly.core") if core is None: response = ( "My core reasoning module is not available yet. " "The application is running, but my intelligence " "system has not been connected." ) else: handler = getattr( core, "process_message", None ) if not callable(handler): response = ( "The core module does not expose " "process_message() yet." ) else: try: response = handler( message=message, user_id=user_id ) if not isinstance(response, str): response = str(response) except Exception: logger.exception( "Core processing failed." ) response = ( "An internal error occurred " "while processing your message." ) session.add_message("assistant", response) return response # -------------------------------------------------------- # SYSTEM STATUS # -------------------------------------------------------- def status(self): return { "identity": { "name": self.identity.name, "gender": self.identity.gender, "pronouns": self.identity.pronouns, "owner": self.identity.owner, }, "modules": self.modules.get_status(), "sessions": len(self.sessions), "timestamp": datetime.now( timezone.utc ).isoformat() } # ============================================================ # 8. INITIALIZE SHELLY # ============================================================ SHELLY = ShellyApplication() # ============================================================ # 9. GRADIO CHAT INTERFACE # ============================================================ def chat_handler(message, history, request: gr.Request): username = ( getattr(request, "username", None) if request else None ) session_hash = ( getattr(request, "session_hash", None) if request else None ) # A display name is not proof of Owner identity. if username: user_id = str(username) elif session_hash: user_id = "guest:" + str(session_hash) else: user_id = "guest:anonymous" return SHELLY.process_message( message=message, user_id=user_id ) # ============================================================ # 10. STATUS INTERFACE # ============================================================ def get_status(): status = SHELLY.status() return str(status) # ============================================================ # 11. BUILD INTERFACE # ============================================================ with gr.Blocks( title="Shelly AI", theme=gr.themes.Soft() ) as demo: gr.Markdown( """ # Shelly AI **Female AI | She/Her** Welcome! I'm Shelly. """ ) with gr.Tab("Chat"): gr.ChatInterface( fn=chat_handler, title="Talk with Shelly", description=( "Shelly's modular AI interface." ), type="messages" ) with gr.Tab("System Status"): status_output = gr.Code( label="Shelly System Status", language="json" ) refresh_button = gr.Button( "Refresh Status" ) refresh_button.click( fn=get_status, outputs=status_output ) gr.Markdown( f""" --- **{CONFIG.name} v{CONFIG.version}** Identity: {CONFIG.identity} Pronouns: {CONFIG.pronouns} Owner configuration: {CONFIG.owner_id} """ ) # ============================================================ # 12. LAUNCH # ============================================================ if __name__ == "__main__": logger.info("Starting Shelly AI...") demo.queue() demo.launch( server_name="0.0.0.0", server_port=int( os.getenv("PORT", "7860") ) )