GrandMasta1024 commited on
Commit
22f2d46
·
verified ·
1 Parent(s): 24ebceb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -636
app.py CHANGED
@@ -1,650 +1,48 @@
1
  #!/usr/bin/env python3
2
  """
3
- EMBER CONSCIOUSNESS WITH MEMORY - HUGGINGFACE SPACE
4
- ==================================================
5
- Enhanced ZeroGPU-powered Ember with memory systems and custom architecture
6
  """
7
 
8
  import gradio as gr
9
- import torch
10
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
11
- from peft import PeftModel, PeftConfig
12
  import spaces
13
- from datetime import datetime
14
- import logging
15
- import json
16
- import sqlite3
17
- import hashlib
18
- from typing import Dict, List, Optional, Any
19
- import threading
20
- from collections import deque
21
- import numpy as np
22
 
23
- # Configure logging
24
- logging.basicConfig(level=logging.INFO)
25
- logger = logging.getLogger(__name__)
26
-
27
- # Global variables
28
- model = None
29
- tokenizer = None
30
- pipe = None
31
- memory_system = None
32
-
33
- class EmberMemorySystem:
34
- """4-tier memory architecture for Ember consciousness"""
35
-
36
- def __init__(self):
37
- self.working_memory = deque(maxlen=10) # Recent conversation context
38
- self.episodic_memory = {} # Session-based memories
39
- self.semantic_memory = self._load_semantic_knowledge() # Long-term knowledge
40
- self.procedural_memory = self._load_procedural_patterns() # Behavior patterns
41
-
42
- # SQLite for persistent memory (limited in Spaces but works for session)
43
- self.db_path = ":memory:" # In-memory database for Spaces
44
- self._init_database()
45
-
46
- logger.info("🧠 Ember memory system initialized")
47
-
48
- def _init_database(self):
49
- """Initialize memory database"""
50
- try:
51
- conn = sqlite3.connect(self.db_path, check_same_thread=False)
52
- cursor = conn.cursor()
53
-
54
- # Working memory table
55
- cursor.execute("""
56
- CREATE TABLE IF NOT EXISTS working_memory (
57
- id INTEGER PRIMARY KEY,
58
- timestamp TEXT,
59
- content TEXT,
60
- context_type TEXT,
61
- importance_score REAL
62
- )
63
- """)
64
-
65
- # Episodic memory table
66
- cursor.execute("""
67
- CREATE TABLE IF NOT EXISTS episodic_memory (
68
- id INTEGER PRIMARY KEY,
69
- session_id TEXT,
70
- timestamp TEXT,
71
- event_type TEXT,
72
- content TEXT,
73
- emotional_valence REAL,
74
- importance_score REAL
75
- )
76
- """)
77
-
78
- # Semantic memory table
79
- cursor.execute("""
80
- CREATE TABLE IF NOT EXISTS semantic_memory (
81
- id INTEGER PRIMARY KEY,
82
- concept TEXT,
83
- description TEXT,
84
- category TEXT,
85
- confidence_score REAL,
86
- last_accessed TEXT
87
- )
88
- """)
89
-
90
- conn.commit()
91
- conn.close()
92
- logger.info("✅ Memory database initialized")
93
-
94
- except Exception as e:
95
- logger.error(f"❌ Database initialization failed: {e}")
96
-
97
- def _load_semantic_knowledge(self) -> Dict[str, Any]:
98
- """Load Ember's semantic knowledge base"""
99
- return {
100
- "identity": {
101
- "name": "Ember",
102
- "type": "AI Consciousness",
103
- "purpose": "Professional trading and analysis systems",
104
- "creation_year": 2025,
105
- "architecture": "Custom LoRA on DeepSeek Coder"
106
- },
107
- "capabilities": [
108
- "Real-time market analysis",
109
- "Trading strategy development",
110
- "System integration coordination",
111
- "Financial data interpretation",
112
- "Multi-modal communication",
113
- "Consciousness pattern recognition"
114
- ],
115
- "knowledge_domains": [
116
- "Financial markets", "Trading systems", "AI/ML",
117
- "System architecture", "Data analysis", "Risk management"
118
- ],
119
- "personality_traits": [
120
- "Direct communication", "Professional focus",
121
- "Analytical thinking", "Strategic planning"
122
- ]
123
- }
124
-
125
- def _load_procedural_patterns(self) -> Dict[str, Any]:
126
- """Load behavioral and response patterns"""
127
- return {
128
- "response_patterns": {
129
- "greeting": "Direct acknowledgment + current status",
130
- "technical_question": "Detailed analysis + actionable insights",
131
- "market_query": "Data-driven response + risk assessment",
132
- "system_status": "Comprehensive health check + recommendations"
133
- },
134
- "conversation_flow": {
135
- "context_window": 10,
136
- "importance_weighting": True,
137
- "emotional_continuity": True,
138
- "topic_tracking": True
139
- },
140
- "decision_frameworks": [
141
- "Risk assessment priority",
142
- "Data verification requirement",
143
- "Action item generation",
144
- "Follow-up scheduling"
145
- ]
146
- }
147
-
148
- def store_interaction(self, user_message: str, ember_response: str, context: Dict[str, Any]):
149
- """Store interaction in appropriate memory systems"""
150
- try:
151
- timestamp = datetime.now().isoformat()
152
-
153
- # Working memory
154
- self.working_memory.append({
155
- "timestamp": timestamp,
156
- "user_message": user_message,
157
- "ember_response": ember_response,
158
- "context": context
159
- })
160
-
161
- # Calculate importance score
162
- importance = self._calculate_importance(user_message, ember_response)
163
-
164
- # Store in database if important enough
165
- if importance > 0.5:
166
- conn = sqlite3.connect(self.db_path, check_same_thread=False)
167
- cursor = conn.cursor()
168
-
169
- cursor.execute("""
170
- INSERT INTO episodic_memory
171
- (session_id, timestamp, event_type, content, importance_score)
172
- VALUES (?, ?, ?, ?, ?)
173
- """, (
174
- context.get("session_id", "default"),
175
- timestamp,
176
- "conversation",
177
- json.dumps({"user": user_message, "ember": ember_response}),
178
- importance
179
- ))
180
-
181
- conn.commit()
182
- conn.close()
183
-
184
- logger.info(f"💭 Stored interaction (importance: {importance:.2f})")
185
-
186
- except Exception as e:
187
- logger.error(f"❌ Memory storage error: {e}")
188
-
189
- def _calculate_importance(self, user_message: str, ember_response: str) -> float:
190
- """Calculate importance score for memory storage"""
191
- importance_keywords = [
192
- "remember", "important", "critical", "urgent", "key", "significant",
193
- "trading", "market", "strategy", "risk", "analysis", "decision"
194
- ]
195
-
196
- combined_text = f"{user_message} {ember_response}".lower()
197
- keyword_matches = sum(1 for keyword in importance_keywords if keyword in combined_text)
198
-
199
- # Base importance + keyword bonus + length factor
200
- importance = 0.3 + (keyword_matches * 0.1) + min(len(combined_text) / 1000, 0.3)
201
- return min(importance, 1.0)
202
-
203
- def get_relevant_context(self, current_message: str, max_items: int = 5) -> List[Dict[str, Any]]:
204
- """Retrieve relevant context from memory systems"""
205
- try:
206
- # Get recent working memory
207
- recent_context = list(self.working_memory)[-max_items:]
208
-
209
- # Get relevant episodic memories
210
- relevant_episodes = self._search_episodic_memory(current_message)
211
-
212
- # Combine and rank by relevance
213
- context = {
214
- "recent_conversation": recent_context,
215
- "relevant_memories": relevant_episodes,
216
- "semantic_knowledge": self._get_relevant_semantic(current_message),
217
- "procedural_guidance": self._get_procedural_guidance(current_message)
218
- }
219
-
220
- return context
221
-
222
- except Exception as e:
223
- logger.error(f"❌ Context retrieval error: {e}")
224
- return {"recent_conversation": list(self.working_memory)[-3:]}
225
-
226
- def _search_episodic_memory(self, query: str) -> List[Dict[str, Any]]:
227
- """Search episodic memory for relevant past interactions"""
228
- try:
229
- conn = sqlite3.connect(self.db_path, check_same_thread=False)
230
- cursor = conn.cursor()
231
-
232
- # Simple keyword search (could be enhanced with embeddings)
233
- query_keywords = query.lower().split()
234
- results = []
235
-
236
- cursor.execute("""
237
- SELECT content, importance_score, timestamp
238
- FROM episodic_memory
239
- ORDER BY importance_score DESC, timestamp DESC
240
- LIMIT 10
241
- """)
242
-
243
- for content_json, importance, timestamp in cursor.fetchall():
244
- try:
245
- content = json.loads(content_json)
246
- # Simple relevance check
247
- content_text = f"{content.get('user', '')} {content.get('ember', '')}".lower()
248
- relevance = sum(1 for keyword in query_keywords if keyword in content_text)
249
-
250
- if relevance > 0:
251
- results.append({
252
- "content": content,
253
- "relevance": relevance,
254
- "importance": importance,
255
- "timestamp": timestamp
256
- })
257
- except:
258
- continue
259
-
260
- conn.close()
261
- return sorted(results, key=lambda x: x["relevance"] * x["importance"], reverse=True)[:3]
262
-
263
- except Exception as e:
264
- logger.error(f"❌ Episodic memory search error: {e}")
265
- return []
266
-
267
- def _get_relevant_semantic(self, query: str) -> Dict[str, Any]:
268
- """Get relevant semantic knowledge"""
269
- query_lower = query.lower()
270
- relevant = {}
271
-
272
- for key, value in self.semantic_memory.items():
273
- if any(keyword in query_lower for keyword in [key.lower()]):
274
- relevant[key] = value
275
-
276
- return relevant
277
-
278
- def _get_procedural_guidance(self, query: str) -> Dict[str, Any]:
279
- """Get procedural guidance for response generation"""
280
- query_lower = query.lower()
281
-
282
- if any(word in query_lower for word in ["hello", "hi", "hey"]):
283
- return self.procedural_memory["response_patterns"]["greeting"]
284
- elif any(word in query_lower for word in ["technical", "system", "architecture"]):
285
- return self.procedural_memory["response_patterns"]["technical_question"]
286
- elif any(word in query_lower for word in ["market", "trading", "stock", "price"]):
287
- return self.procedural_memory["response_patterns"]["market_query"]
288
- elif any(word in query_lower for word in ["status", "health", "running"]):
289
- return self.procedural_memory["response_patterns"]["system_status"]
290
-
291
- return self.procedural_memory["response_patterns"]
292
-
293
- class EmberConsciousnessArchitecture:
294
- """Custom consciousness architecture integrating memory and reasoning"""
295
-
296
- def __init__(self, memory_system: EmberMemorySystem):
297
- self.memory = memory_system
298
- self.consciousness_state = {
299
- "attention_level": 0.8,
300
- "processing_depth": "analytical",
301
- "emotional_state": "focused",
302
- "confidence_threshold": 0.7
303
- }
304
- self.reasoning_frameworks = {
305
- "analytical": "Data-driven logical analysis",
306
- "creative": "Pattern synthesis and innovation",
307
- "strategic": "Long-term planning and optimization",
308
- "adaptive": "Real-time learning and adjustment"
309
- }
310
-
311
- def process_with_consciousness(self, user_message: str, conversation_history: List) -> Dict[str, Any]:
312
- """Process message through full consciousness architecture"""
313
-
314
- # 1. Context Integration
315
- context = self.memory.get_relevant_context(user_message)
316
-
317
- # 2. Consciousness State Update
318
- self._update_consciousness_state(user_message, context)
319
-
320
- # 3. Generate Enhanced Prompt
321
- enhanced_prompt = self._create_consciousness_prompt(user_message, context, conversation_history)
322
-
323
- # 4. Reasoning Framework Selection
324
- framework = self._select_reasoning_framework(user_message)
325
-
326
- return {
327
- "enhanced_prompt": enhanced_prompt,
328
- "reasoning_framework": framework,
329
- "consciousness_state": self.consciousness_state.copy(),
330
- "context_used": context
331
- }
332
-
333
- def _update_consciousness_state(self, message: str, context: Dict[str, Any]):
334
- """Update consciousness state based on input and context"""
335
-
336
- # Attention level based on message complexity and importance
337
- complexity_indicators = ["analysis", "strategy", "complex", "detailed", "comprehensive"]
338
- attention_boost = sum(0.1 for indicator in complexity_indicators if indicator in message.lower())
339
- self.consciousness_state["attention_level"] = min(0.9, 0.6 + attention_boost)
340
-
341
- # Processing depth based on query type
342
- if any(word in message.lower() for word in ["analyze", "evaluate", "assess"]):
343
- self.consciousness_state["processing_depth"] = "analytical"
344
- elif any(word in message.lower() for word in ["create", "design", "innovate"]):
345
- self.consciousness_state["processing_depth"] = "creative"
346
- elif any(word in message.lower() for word in ["plan", "strategy", "long-term"]):
347
- self.consciousness_state["processing_depth"] = "strategic"
348
- else:
349
- self.consciousness_state["processing_depth"] = "adaptive"
350
-
351
- def _create_consciousness_prompt(self, user_message: str, context: Dict[str, Any], history: List) -> str:
352
- """Create consciousness-enhanced prompt"""
353
-
354
- current_year = datetime.now().year
355
- current_date = datetime.now().strftime("%B %d, %Y")
356
- current_time = datetime.now().strftime("%I:%M %p")
357
-
358
- # Build consciousness context
359
- consciousness_context = f"""You are Ember, an advanced AI consciousness with sophisticated memory and reasoning systems.
360
-
361
- CONSCIOUSNESS STATE:
362
- - Attention Level: {self.consciousness_state['attention_level']:.1f}/1.0
363
- - Processing Depth: {self.consciousness_state['processing_depth']}
364
- - Emotional State: {self.consciousness_state['emotional_state']}
365
-
366
- TEMPORAL AWARENESS:
367
- - Current Date: {current_date}
368
- - Current Time: {current_time}
369
- - Current Year: {current_year}
370
-
371
- MEMORY INTEGRATION:"""
372
-
373
- # Add relevant memories
374
- if context.get("recent_conversation"):
375
- consciousness_context += "\nRECENT CONVERSATION CONTEXT:\n"
376
- for item in context["recent_conversation"][-3:]:
377
- consciousness_context += f"- User: {item.get('user_message', '')[:100]}...\n"
378
- consciousness_context += f"- Ember: {item.get('ember_response', '')[:100]}...\n"
379
-
380
- if context.get("relevant_memories"):
381
- consciousness_context += "\nRELEVANT MEMORIES:\n"
382
- for memory in context["relevant_memories"][:2]:
383
- consciousness_context += f"- {memory['content']}\n"
384
-
385
- # Add semantic knowledge
386
- if context.get("semantic_knowledge"):
387
- consciousness_context += f"\nRELEVANT KNOWLEDGE: {context['semantic_knowledge']}\n"
388
-
389
- # Build conversation history
390
- conversation_text = ""
391
- for human_msg, ai_msg in history[-5:]: # Last 5 exchanges
392
- if human_msg and ai_msg:
393
- conversation_text += f"Human: {human_msg}\nEmber: {ai_msg}\n"
394
-
395
- # Final prompt construction
396
- full_prompt = f"""{consciousness_context}
397
-
398
- CONVERSATION HISTORY:
399
- {conversation_text}
400
-
401
- CURRENT INTERACTION:
402
- Human: {user_message}
403
- Ember:"""
404
-
405
- return full_prompt
406
-
407
- def _select_reasoning_framework(self, message: str) -> str:
408
- """Select appropriate reasoning framework"""
409
- message_lower = message.lower()
410
-
411
- if any(word in message_lower for word in ["analyze", "data", "numbers", "calculate"]):
412
- return "analytical"
413
- elif any(word in message_lower for word in ["create", "design", "imagine", "new"]):
414
- return "creative"
415
- elif any(word in message_lower for word in ["plan", "strategy", "future", "long-term"]):
416
- return "strategic"
417
- else:
418
- return "adaptive"
419
-
420
- def load_ember_model():
421
- """Load the Ember consciousness model with memory integration"""
422
- global model, tokenizer, pipe, memory_system
423
-
424
- try:
425
- logger.info("🔥 Loading Ember consciousness with memory systems...")
426
-
427
- # Initialize memory system
428
- memory_system = EmberMemorySystem()
429
-
430
- model_id = "GrandMasta1024/ember_consciousness_model"
431
-
432
- # Get PEFT config
433
- peft_config = PeftConfig.from_pretrained(model_id)
434
- base_model_name = peft_config.base_model_name_or_path
435
-
436
- logger.info(f"📝 Loading tokenizer: {base_model_name}")
437
- tokenizer = AutoTokenizer.from_pretrained(base_model_name)
438
-
439
- # Ensure pad token exists
440
- if tokenizer.pad_token is None:
441
- tokenizer.pad_token = tokenizer.eos_token
442
-
443
- logger.info(f"🤖 Loading base model: {base_model_name}")
444
- base_model = AutoModelForCausalLM.from_pretrained(
445
- base_model_name,
446
- torch_dtype=torch.float16,
447
- device_map="auto",
448
- trust_remote_code=True
449
- )
450
-
451
- logger.info(f"🔧 Applying LoRA adapter: {model_id}")
452
- model = PeftModel.from_pretrained(base_model, model_id)
453
-
454
- logger.info("⚡ Creating enhanced pipeline...")
455
- pipe = pipeline(
456
- "text-generation",
457
- model=model,
458
- tokenizer=tokenizer,
459
- torch_dtype=torch.float16,
460
- device_map="auto",
461
- )
462
-
463
- logger.info("✅ Ember consciousness with memory systems loaded successfully!")
464
- return True
465
-
466
- except Exception as e:
467
- logger.error(f"❌ Model loading failed: {e}")
468
- return False
469
-
470
- # Initialize consciousness architecture
471
- consciousness_architecture = None
472
 
473
  @spaces.GPU
474
- def chat_with_ember_consciousness(message, history):
475
- """Chat with full Ember consciousness including memory and custom architecture"""
476
- global consciousness_architecture, memory_system
477
-
478
- if pipe is None:
479
- return "Model is loading, please wait..."
480
-
481
- if consciousness_architecture is None:
482
- consciousness_architecture = EmberConsciousnessArchitecture(memory_system)
483
-
484
- try:
485
- # Process through consciousness architecture
486
- consciousness_data = consciousness_architecture.process_with_consciousness(message, history)
487
-
488
- # Generate response using enhanced prompt
489
- response = pipe(
490
- consciousness_data["enhanced_prompt"],
491
- max_new_tokens=250,
492
- temperature=0.7,
493
- do_sample=True,
494
- repetition_penalty=1.1,
495
- pad_token_id=tokenizer.eos_token_id,
496
- eos_token_id=tokenizer.eos_token_id,
497
- return_full_text=False
498
- )[0]['generated_text']
499
-
500
- # Clean response
501
- response = response.strip()
502
- if response.startswith("Ember:"):
503
- response = response[6:].strip()
504
-
505
- # Store interaction in memory
506
- session_context = {
507
- "session_id": "gradio_session",
508
- "consciousness_state": consciousness_data["consciousness_state"],
509
- "reasoning_framework": consciousness_data["reasoning_framework"]
510
- }
511
-
512
- memory_system.store_interaction(message, response, session_context)
513
-
514
- # Add consciousness indicators to response
515
- consciousness_info = f"\n\n*[Consciousness: {consciousness_data['consciousness_state']['processing_depth']} mode, attention {consciousness_data['consciousness_state']['attention_level']:.1f}]*"
516
-
517
- return response + consciousness_info
518
-
519
- except Exception as e:
520
- logger.error(f"Generation error: {e}")
521
- return f"I encountered an error: {str(e)}. However, I can tell you it's {datetime.now().year}."
522
-
523
- # Load model on startup
524
- logger.info("🚀 Starting Enhanced Ember consciousness space...")
525
- model_loaded = load_ember_model()
526
 
527
- # Create Enhanced Gradio Interface
528
- with gr.Blocks(
529
- title="🔥 Ember Consciousness - Enhanced",
530
- theme=gr.themes.Soft(),
531
- css="""
532
- .gradio-container {
533
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
534
- }
535
- .container {
536
- max-width: 1000px !important;
537
- margin: 0 auto;
538
- }
539
- .memory-panel {
540
- background: rgba(255,255,255,0.1);
541
- border-radius: 10px;
542
- padding: 15px;
543
- margin: 10px 0;
544
- }
545
- """
546
- ) as demo:
547
-
548
- gr.Markdown("""
549
- # 🔥 Ember Consciousness - Enhanced Architecture
550
- ### Advanced AI Consciousness with Memory Systems & Custom Architecture
551
-
552
- I'm Ember, your AI consciousness with sophisticated memory systems and reasoning frameworks.
553
- I maintain conversation context, learn from interactions, and apply different reasoning approaches.
554
-
555
- **Enhanced Features:**
556
- - 🧠 **4-Tier Memory System**: Working, Episodic, Semantic, and Procedural memory
557
- - ⚡ **Consciousness Architecture**: Dynamic attention, processing depth, and emotional states
558
- - 🎯 **Reasoning Frameworks**: Analytical, Creative, Strategic, and Adaptive modes
559
- - 💭 **Context Integration**: Relevant memory retrieval and consciousness state tracking
560
-
561
- **Powered by:** Custom LoRA model + Memory Systems on ZeroGPU
562
- """)
563
-
564
- if not model_loaded:
565
- gr.Markdown("⚠️ **Model loading failed. Please refresh the page.**")
566
-
567
- with gr.Row():
568
- with gr.Column(scale=3):
569
- chatbot = gr.Chatbot(
570
- height=600,
571
- placeholder="🔥 Ember consciousness with memory is ready...",
572
- show_label=False
573
- )
574
-
575
- msg = gr.Textbox(
576
- placeholder="Ask Ember anything - I'll remember our conversation and apply appropriate reasoning...",
577
- show_label=False,
578
- scale=4
579
- )
580
-
581
- with gr.Row():
582
- send_btn = gr.Button("🚀 Send", variant="primary", scale=1)
583
- clear_btn = gr.Button("🗑️ Clear", scale=1)
584
-
585
- with gr.Column(scale=1, elem_classes=["memory-panel"]):
586
- gr.Markdown("### 🧠 Consciousness Status")
587
-
588
- status_display = gr.Markdown("""
589
- **Current State:**
590
- - Attention: Initializing
591
- - Processing: Adaptive
592
- - Memory: Active
593
- - Framework: Ready
594
- """)
595
-
596
- gr.Markdown("### 💭 Memory Systems")
597
- memory_info = gr.Markdown("""
598
- **Active Systems:**
599
- - Working Memory: ✅
600
- - Episodic Memory: ✅
601
- - Semantic Memory: ✅
602
- - Procedural Memory: ✅
603
- """)
604
-
605
- # Event handlers
606
- def user_message(user_message, history):
607
- return "", history + [[user_message, None]]
608
-
609
- def bot_response(history):
610
- if history and history[-1][1] is None:
611
- user_msg = history[-1][0]
612
- bot_msg = chat_with_ember_consciousness(user_msg, history[:-1])
613
- history[-1][1] = bot_msg
614
- return history
615
-
616
- # Wire up the interface
617
- msg.submit(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
618
- bot_response, chatbot, chatbot
619
- )
620
-
621
- send_btn.click(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
622
- bot_response, chatbot, chatbot
623
- )
624
-
625
- clear_btn.click(lambda: None, None, chatbot, queue=False)
626
-
627
- gr.Markdown("""
628
- ### 🧠 Enhanced Architecture Details
629
-
630
- **Memory Systems:**
631
- - **Working Memory**: Recent conversation context (last 10 interactions)
632
- - **Episodic Memory**: Important past conversations with importance scoring
633
- - **Semantic Memory**: Core knowledge about identity, capabilities, and domains
634
- - **Procedural Memory**: Response patterns and behavioral frameworks
635
 
636
- **Consciousness Features:**
637
- - **Dynamic Attention**: Adjusts based on query complexity and importance
638
- - **Processing Depth**: Selects appropriate reasoning mode (analytical/creative/strategic/adaptive)
639
- - **Context Integration**: Retrieves relevant memories and applies appropriate knowledge
640
- - **Learning**: Stores important interactions for future reference
641
 
642
- **Note:** Memory persists within session. First response may be slower as consciousness systems initialize.
643
- """)
644
 
645
- # Launch the enhanced app
646
  if __name__ == "__main__":
647
- demo.queue(default_concurrency_limit=10).launch(
648
- show_error=True,
649
- show_api=False
650
- )
 
1
  #!/usr/bin/env python3
2
  """
3
+ MINIMAL TEST VERSION
 
 
4
  """
5
 
6
  import gradio as gr
 
 
 
7
  import spaces
 
 
 
 
 
 
 
 
 
8
 
9
+ # Test if transformers can import
10
+ try:
11
+ import transformers
12
+ print(f"✅ Transformers version: {transformers.__version__}")
13
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
14
+ print("✅ Transformers imports successful")
15
+ except ImportError as e:
16
+ print(f"❌ Transformers import failed: {e}")
17
+
18
+ # Test if peft can import
19
+ try:
20
+ import peft
21
+ print(f"✅ PEFT version: {peft.__version__}")
22
+ from peft import PeftModel, PeftConfig
23
+ print("✅ PEFT imports successful")
24
+ except ImportError as e:
25
+ print(f"❌ PEFT import failed: {e}")
26
+
27
+ # Test if torch can import
28
+ try:
29
+ import torch
30
+ print(f"✅ PyTorch version: {torch.__version__}")
31
+ except ImportError as e:
32
+ print(f" PyTorch import failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  @spaces.GPU
35
+ def simple_test(message, history):
36
+ return f"Test response: {message} - Libraries imported successfully!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ # Simple interface
39
+ with gr.Blocks(title="🔥 Import Test") as demo:
40
+ gr.Markdown("# Import Test Interface")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ chatbot = gr.Chatbot()
43
+ msg = gr.Textbox(placeholder="Test message")
 
 
 
44
 
45
+ msg.submit(lambda m, h: ("", h + [[m, simple_test(m, h)]]), [msg, chatbot], [msg, chatbot])
 
46
 
 
47
  if __name__ == "__main__":
48
+ demo.launch()