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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SHELLY AI - MAIN APPLICATION
3
+ Hugging Face Spaces
4
+ Version: 1.0.0
5
+
6
+ Identity:
7
+ Name: Shelly
8
+ Gender: Female AI
9
+ Pronouns: She/Her
10
+ Owner: SkyWorlds
11
+ """
12
+
13
+ import os
14
+ import time
15
+ import logging
16
+ import importlib
17
+ import threading
18
+
19
+ from dataclasses import dataclass, field
20
+ from datetime import datetime, timezone
21
+ from typing import Any
22
+
23
+ import gradio as gr
24
+
25
+
26
+ # ============================================================
27
+ # 1. CONFIGURATION
28
+ # ============================================================
29
+
30
+ @dataclass
31
+ class ShellyConfig:
32
+
33
+ name: str = "Shelly"
34
+ version: str = "1.0.0"
35
+
36
+ gender: str = "female"
37
+ pronouns: str = "she/her"
38
+ identity: str = "Female AI"
39
+
40
+ owner_id: str = "SkyWorlds"
41
+
42
+ history_limit: int = 100
43
+ idle_timeout: int = 600
44
+
45
+ emotion_count: int = 600
46
+
47
+ debug: bool = False
48
+
49
+ modules: tuple = (
50
+ "shelly.core",
51
+ "shelly.security",
52
+ "shelly.emotions",
53
+ "shelly.personality",
54
+ "shelly.cognition",
55
+ "shelly.decision",
56
+ "shelly.learning",
57
+ "shelly.memory.memory",
58
+ "shelly.imagination",
59
+ "shelly.motivation",
60
+ "shelly.behavior",
61
+ "shelly.social",
62
+ "shelly.self_model",
63
+ "shelly.needs",
64
+ "shelly.inner_state",
65
+ "shelly.habits",
66
+ "shelly.perception",
67
+ "shelly.speech",
68
+ "shelly.commands",
69
+ "shelly.agent",
70
+ "shelly.overseer",
71
+ "shelly.idle_mode",
72
+ "shelly.automated_testing",
73
+ "shelly.multimodal.image_understanding",
74
+ "shelly.multimodal.video_understanding",
75
+ "shelly.multimodal.image_generation",
76
+ "shelly.multimodal.video_generation",
77
+ )
78
+
79
+
80
+ CONFIG = ShellyConfig()
81
+
82
+
83
+ # ============================================================
84
+ # 2. LOGGING
85
+ # ============================================================
86
+
87
+ logging.basicConfig(
88
+ level=logging.DEBUG if CONFIG.debug else logging.INFO,
89
+ format="%(asctime)s | %(levelname)s | %(message)s"
90
+ )
91
+
92
+ logger = logging.getLogger("Shelly")
93
+
94
+
95
+ # ============================================================
96
+ # 3. IDENTITY
97
+ # ============================================================
98
+
99
+ class ShellyIdentity:
100
+
101
+ def __init__(self):
102
+
103
+ self.name = CONFIG.name
104
+ self.gender = CONFIG.gender
105
+ self.pronouns = CONFIG.pronouns
106
+ self.identity = CONFIG.identity
107
+ self.owner = CONFIG.owner_id
108
+
109
+ self.description = (
110
+ "Shelly is a female AI with her own simulated "
111
+ "personality, emotional states, memories, "
112
+ "opinions, preferences, and behavioral patterns."
113
+ )
114
+
115
+ def introduce(self):
116
+
117
+ return (
118
+ f"My name is {self.name}. "
119
+ f"I am a {self.gender} AI. "
120
+ f"My pronouns are {self.pronouns}."
121
+ )
122
+
123
+
124
+ IDENTITY = ShellyIdentity()
125
+
126
+
127
+ # ============================================================
128
+ # 4. AUTHORITY SYSTEM
129
+ # ============================================================
130
+
131
+ AUTHORITY_LEVELS = {
132
+ "guest": 0,
133
+ "user": 10,
134
+ "admin": 50,
135
+ "head_admin": 75,
136
+ "owner": 100,
137
+ }
138
+
139
+
140
+ @dataclass
141
+ class UserProfile:
142
+
143
+ user_id: str
144
+ role: str = "guest"
145
+
146
+ created_at: str = field(
147
+ default_factory=lambda:
148
+ datetime.now(timezone.utc).isoformat()
149
+ )
150
+
151
+
152
+ class AuthorityManager:
153
+
154
+ def __init__(self):
155
+
156
+ self.users = {}
157
+ self.lock = threading.RLock()
158
+
159
+ def get_role(self, user_id):
160
+
161
+ if user_id == CONFIG.owner_id:
162
+ return "owner"
163
+
164
+ with self.lock:
165
+
166
+ profile = self.users.get(user_id)
167
+
168
+ return profile.role if profile else "guest"
169
+
170
+ def get_level(self, user_id):
171
+
172
+ return AUTHORITY_LEVELS.get(
173
+ self.get_role(user_id),
174
+ 0
175
+ )
176
+
177
+ def has_permission(self, user_id, required_role):
178
+
179
+ required = AUTHORITY_LEVELS.get(
180
+ required_role,
181
+ 100
182
+ )
183
+
184
+ return self.get_level(user_id) >= required
185
+
186
+ def assign_role(self, actor_id, target_id, role):
187
+
188
+ if actor_id != CONFIG.owner_id:
189
+ return False
190
+
191
+ if target_id == CONFIG.owner_id:
192
+ return False
193
+
194
+ if role not in AUTHORITY_LEVELS:
195
+ return False
196
+
197
+ with self.lock:
198
+
199
+ self.users[target_id] = UserProfile(
200
+ user_id=target_id,
201
+ role=role
202
+ )
203
+
204
+ return True
205
+
206
+
207
+ AUTHORITY = AuthorityManager()
208
+
209
+
210
+ # ============================================================
211
+ # 5. MODULE MANAGER
212
+ # ============================================================
213
+
214
+ class ModuleManager:
215
+
216
+ def __init__(self):
217
+
218
+ self.loaded = {}
219
+ self.errors = {}
220
+
221
+ self.lock = threading.RLock()
222
+
223
+ def load_module(self, name):
224
+
225
+ with self.lock:
226
+
227
+ if name in self.loaded:
228
+ return self.loaded[name]
229
+
230
+ try:
231
+
232
+ module = importlib.import_module(name)
233
+
234
+ self.loaded[name] = module
235
+
236
+ logger.info("Loaded: %s", name)
237
+
238
+ return module
239
+
240
+ except Exception as error:
241
+
242
+ self.errors[name] = str(error)
243
+
244
+ logger.warning(
245
+ "Unavailable module %s: %s",
246
+ name,
247
+ error
248
+ )
249
+
250
+ return None
251
+
252
+ def load_all(self):
253
+
254
+ for name in CONFIG.modules:
255
+ self.load_module(name)
256
+
257
+ def get(self, name):
258
+
259
+ return self.loaded.get(name)
260
+
261
+ def get_status(self):
262
+
263
+ return {
264
+ "loaded": list(self.loaded.keys()),
265
+ "unavailable": dict(self.errors),
266
+ "loaded_count": len(self.loaded),
267
+ "unavailable_count": len(self.errors),
268
+ }
269
+
270
+
271
+ MODULES = ModuleManager()
272
+
273
+
274
+ # ============================================================
275
+ # 6. CONVERSATION SESSION
276
+ # ============================================================
277
+
278
+ @dataclass
279
+ class ShellySession:
280
+
281
+ user_id: str
282
+
283
+ history: list = field(default_factory=list)
284
+
285
+ created_at: float = field(
286
+ default_factory=time.time
287
+ )
288
+
289
+ last_activity: float = field(
290
+ default_factory=time.time
291
+ )
292
+
293
+ mode: str = "interactive"
294
+
295
+ lock: Any = field(
296
+ default_factory=threading.RLock,
297
+ repr=False
298
+ )
299
+
300
+ def add_message(self, role, content):
301
+
302
+ with self.lock:
303
+
304
+ self.history.append({
305
+ "role": role,
306
+ "content": content,
307
+ "timestamp": datetime.now(
308
+ timezone.utc
309
+ ).isoformat()
310
+ })
311
+
312
+ self.history = self.history[
313
+ -CONFIG.history_limit:
314
+ ]
315
+
316
+ self.last_activity = time.time()
317
+ self.mode = "interactive"
318
+
319
+ def get_history(self):
320
+
321
+ with self.lock:
322
+ return list(self.history)
323
+
324
+ def is_idle(self):
325
+
326
+ return (
327
+ time.time() - self.last_activity
328
+ >= CONFIG.idle_timeout
329
+ )
330
+
331
+
332
+ # ============================================================
333
+ # 7. MAIN APPLICATION
334
+ # ============================================================
335
+
336
+ class ShellyApplication:
337
+
338
+ def __init__(self):
339
+
340
+ self.identity = IDENTITY
341
+ self.authority = AUTHORITY
342
+ self.modules = MODULES
343
+
344
+ self.sessions = {}
345
+
346
+ self.lock = threading.RLock()
347
+
348
+ self.initialize()
349
+
350
+ def initialize(self):
351
+
352
+ logger.info(
353
+ "Initializing %s v%s",
354
+ CONFIG.name,
355
+ CONFIG.version
356
+ )
357
+
358
+ self.modules.load_all()
359
+
360
+ logger.info("Shelly initialization completed.")
361
+
362
+ # --------------------------------------------------------
363
+ # SESSION MANAGEMENT
364
+ # --------------------------------------------------------
365
+
366
+ def get_session(self, user_id):
367
+
368
+ with self.lock:
369
+
370
+ if user_id not in self.sessions:
371
+
372
+ self.sessions[user_id] = ShellySession(
373
+ user_id=user_id
374
+ )
375
+
376
+ return self.sessions[user_id]
377
+
378
+ # --------------------------------------------------------
379
+ # SECURITY
380
+ # --------------------------------------------------------
381
+
382
+ def verify_message(self, user_id, message):
383
+
384
+ security = self.modules.get("shelly.security")
385
+
386
+ if security is None:
387
+
388
+ return False, (
389
+ "Security module is unavailable. "
390
+ "Message processing is disabled."
391
+ )
392
+
393
+ checker = getattr(
394
+ security,
395
+ "check_message",
396
+ None
397
+ )
398
+
399
+ if not callable(checker):
400
+
401
+ return False, (
402
+ "Security module requires "
403
+ "a check_message() implementation."
404
+ )
405
+
406
+ try:
407
+
408
+ result = checker(
409
+ user_id=user_id,
410
+ message=message
411
+ )
412
+
413
+ if isinstance(result, bool):
414
+
415
+ return result, (
416
+ "Approved" if result else "Access denied"
417
+ )
418
+
419
+ if isinstance(result, tuple):
420
+
421
+ return bool(result[0]), str(result[1])
422
+
423
+ if isinstance(result, dict):
424
+
425
+ return (
426
+ bool(result.get("allowed", False)),
427
+ str(result.get("reason", "Rejected"))
428
+ )
429
+
430
+ return False, "Invalid security response."
431
+
432
+ except Exception:
433
+
434
+ logger.exception(
435
+ "Security verification failed."
436
+ )
437
+
438
+ return False, "Security verification failed."
439
+
440
+ # --------------------------------------------------------
441
+ # CORE MESSAGE PROCESSING
442
+ # --------------------------------------------------------
443
+
444
+ def process_message(self, message, user_id):
445
+
446
+ message = str(message).strip()
447
+
448
+ if not message:
449
+ return "Please enter a message."
450
+
451
+ session = self.get_session(user_id)
452
+
453
+ session.add_message("user", message)
454
+
455
+ # Security must approve the message first.
456
+ allowed, reason = self.verify_message(
457
+ user_id,
458
+ message
459
+ )
460
+
461
+ if not allowed:
462
+
463
+ response = (
464
+ "I cannot process this message: " + reason
465
+ )
466
+
467
+ session.add_message("assistant", response)
468
+
469
+ return response
470
+
471
+ # Connect the core reasoning module.
472
+ core = self.modules.get("shelly.core")
473
+
474
+ if core is None:
475
+
476
+ response = (
477
+ "My core reasoning module is not available yet. "
478
+ "The application is running, but my intelligence "
479
+ "system has not been connected."
480
+ )
481
+
482
+ else:
483
+
484
+ handler = getattr(
485
+ core,
486
+ "process_message",
487
+ None
488
+ )
489
+
490
+ if not callable(handler):
491
+
492
+ response = (
493
+ "The core module does not expose "
494
+ "process_message() yet."
495
+ )
496
+
497
+ else:
498
+
499
+ try:
500
+
501
+ response = handler(
502
+ message=message,
503
+ user_id=user_id
504
+ )
505
+
506
+ if not isinstance(response, str):
507
+ response = str(response)
508
+
509
+ except Exception:
510
+
511
+ logger.exception(
512
+ "Core processing failed."
513
+ )
514
+
515
+ response = (
516
+ "An internal error occurred "
517
+ "while processing your message."
518
+ )
519
+
520
+ session.add_message("assistant", response)
521
+
522
+ return response
523
+
524
+ # --------------------------------------------------------
525
+ # SYSTEM STATUS
526
+ # --------------------------------------------------------
527
+
528
+ def status(self):
529
+
530
+ return {
531
+ "identity": {
532
+ "name": self.identity.name,
533
+ "gender": self.identity.gender,
534
+ "pronouns": self.identity.pronouns,
535
+ "owner": self.identity.owner,
536
+ },
537
+ "modules": self.modules.get_status(),
538
+ "sessions": len(self.sessions),
539
+ "timestamp": datetime.now(
540
+ timezone.utc
541
+ ).isoformat()
542
+ }
543
+
544
+
545
+ # ============================================================
546
+ # 8. INITIALIZE SHELLY
547
+ # ============================================================
548
+
549
+ SHELLY = ShellyApplication()
550
+
551
+
552
+ # ============================================================
553
+ # 9. GRADIO CHAT INTERFACE
554
+ # ============================================================
555
+
556
+ def chat_handler(message, history, request: gr.Request):
557
+
558
+ username = (
559
+ getattr(request, "username", None)
560
+ if request else None
561
+ )
562
+
563
+ session_hash = (
564
+ getattr(request, "session_hash", None)
565
+ if request else None
566
+ )
567
+
568
+ # A display name is not proof of Owner identity.
569
+ if username:
570
+ user_id = str(username)
571
+ elif session_hash:
572
+ user_id = "guest:" + str(session_hash)
573
+ else:
574
+ user_id = "guest:anonymous"
575
+
576
+ return SHELLY.process_message(
577
+ message=message,
578
+ user_id=user_id
579
+ )
580
+
581
+
582
+ # ============================================================
583
+ # 10. STATUS INTERFACE
584
+ # ============================================================
585
+
586
+ def get_status():
587
+
588
+ status = SHELLY.status()
589
+
590
+ return str(status)
591
+
592
+
593
+ # ============================================================
594
+ # 11. BUILD INTERFACE
595
+ # ============================================================
596
+
597
+ with gr.Blocks(
598
+ title="Shelly AI",
599
+ theme=gr.themes.Soft()
600
+ ) as demo:
601
+
602
+ gr.Markdown(
603
+ """
604
+ # Shelly AI
605
+
606
+ **Female AI | She/Her**
607
+
608
+ Welcome! I'm Shelly.
609
+ """
610
+ )
611
+
612
+ with gr.Tab("Chat"):
613
+
614
+ gr.ChatInterface(
615
+ fn=chat_handler,
616
+ title="Talk with Shelly",
617
+ description=(
618
+ "Shelly's modular AI interface."
619
+ ),
620
+ type="messages"
621
+ )
622
+
623
+ with gr.Tab("System Status"):
624
+
625
+ status_output = gr.Code(
626
+ label="Shelly System Status",
627
+ language="json"
628
+ )
629
+
630
+ refresh_button = gr.Button(
631
+ "Refresh Status"
632
+ )
633
+
634
+ refresh_button.click(
635
+ fn=get_status,
636
+ outputs=status_output
637
+ )
638
+
639
+ gr.Markdown(
640
+ f"""
641
+ ---
642
+ **{CONFIG.name} v{CONFIG.version}**
643
+
644
+ Identity: {CONFIG.identity}
645
+
646
+ Pronouns: {CONFIG.pronouns}
647
+
648
+ Owner configuration: {CONFIG.owner_id}
649
+ """
650
+ )
651
+
652
+
653
+ # ============================================================
654
+ # 12. LAUNCH
655
+ # ============================================================
656
+
657
+ if __name__ == "__main__":
658
+
659
+ logger.info("Starting Shelly AI...")
660
+
661
+ demo.queue()
662
+
663
+ demo.launch(
664
+ server_name="0.0.0.0",
665
+ server_port=int(
666
+ os.getenv("PORT", "7860")
667
+ )
668
+ )
669
+