-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_cli.py
More file actions
279 lines (219 loc) · 9.64 KB
/
app_cli.py
File metadata and controls
279 lines (219 loc) · 9.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/env python3
"""
Autumn AI Assistant - Command Line Interface
A sophisticated AI personal assistant with local processing and personality.
Author: Shrey
Date: June 20, 2025
"""
import asyncio
import logging
import sys
from pathlib import Path
# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
from core.brain import AutumnBrain
from core.voice import AutumnVoice
from core.memory import AutumnMemory
from config.personality import AutumnPersonality, AutumnMode
from config.settings import Settings
from core.logging_utils import setup_logging, get_logger
# Configure Unicode-safe logging
setup_logging(log_file='autumn.log')
logger = get_logger('cli')
class AutumnCLI:
"""Command Line Interface for Autumn AI Assistant."""
def __init__(self):
"""Initialize Autumn with all her core components."""
logger.info("🍂 Initializing Autumn AI Assistant (CLI Mode)...")
# Load configuration
self.settings = Settings()
self.personality = AutumnPersonality()
# Initialize core components
self.memory = AutumnMemory()
self.brain = AutumnBrain(self.memory, self.personality)
self.voice = AutumnVoice()
# Set voice callback
self.voice.set_voice_callback(self.handle_voice_input)
self.running = False
logger.info("[INIT] Autumn components initialized successfully")
async def start(self):
"""Start Autumn AI Assistant in CLI mode."""
try:
logger.info("🚀 Starting Autumn AI Assistant (CLI Mode)...")
# Initialize memory system
await self.memory.initialize()
# Initialize AI brain (Ollama connection)
await self.brain.initialize()
# Initialize voice system
await self.voice.initialize()
print("\n" + "="*60)
print("🍂 AUTUMN AI ASSISTANT - COMMAND LINE MODE")
print("="*60)
print("[READY] All systems initialized and ready!")
print("\n📖 Available commands:")
print(" - Type 'voice' to start voice mode")
print(" - Type 'test voice' to test voice input/output")
print(" - Type 'quit' or 'exit' to shutdown")
print(" - Type anything else to chat with Autumn")
print("="*60)
self.running = True
await self.run_cli()
except Exception as e:
logger.error(f"❌ Failed to start Autumn: {e}")
raise
async def run_cli(self):
"""Run the main CLI loop."""
while self.running:
try:
# Get user input
user_input = input("\n👤 You: ").strip()
if not user_input:
continue
# Handle special commands
if user_input.lower() in ['quit', 'exit', 'bye', 'goodbye']:
print("👋 Goodbye! Have a wonderful day!")
break
elif user_input.lower() == 'voice':
await self.start_voice_mode()
continue
elif user_input.lower() == 'test voice':
await self.test_voice()
continue
elif user_input.lower() == 'help':
self.show_help()
continue
# Process normal input
await self.handle_text_input(user_input)
except KeyboardInterrupt:
print("\n🛑 Interrupted. Type 'quit' to exit gracefully.")
except EOFError:
print("\n👋 Goodbye!")
break
except Exception as e:
logger.error(f"❌ Error in CLI loop: {e}")
print(f"❌ An error occurred: {e}")
async def handle_text_input(self, user_input: str):
"""Handle text input from the user."""
try:
print("🤖 Autumn is thinking...")
# Store interaction in memory
await self.memory.store_interaction(user_input, "user")
# Process with Autumn's brain
response = await self.brain.process(user_input, "text")
# Store Autumn's response
await self.memory.store_interaction(response, "autumn")
# Display and speak the response
print(f"🍂 Autumn: {response}")
# Speak the response (non-blocking)
await self.voice.speak(response, mode=AutumnMode.FREE)
except Exception as e:
logger.error(f"❌ Error processing text input: {e}")
print("❌ I encountered an error processing your request. Please try again.")
async def handle_voice_input(self, voice_text: str):
"""Handle voice input from the voice system."""
print(f"🎤 You said: {voice_text}")
await self.handle_text_input(voice_text)
async def start_voice_mode(self):
"""Start voice interaction mode."""
print("\n🎤 Starting voice mode...")
print("💡 Say 'Autumn' or 'Hey Autumn' to activate voice commands")
print("💡 Press Ctrl+C to return to text mode")
try:
# Start continuous voice listening
while True:
# Listen for wake word
if await self.voice.listen_for_wake_word():
# Acknowledge
await self.voice.speak("Yes sir? How can I help?", mode=AutumnMode.FREE)
# Listen for command
command = await self.voice.listen_for_command()
if command:
await self.handle_voice_input(command)
else:
await self.voice.speak("I didn't catch that. Could you repeat?", mode=AutumnMode.FREE)
# Small pause
await asyncio.sleep(0.5)
except KeyboardInterrupt:
print("\n📝 Returning to text mode...")
except Exception as e:
logger.error(f"❌ Voice mode error: {e}")
print("❌ Voice mode encountered an error. Returning to text mode.")
def show_help(self):
"""Show help information."""
print("\n" + "="*60)
print("📖 AUTUMN AI ASSISTANT - HELP")
print("="*60)
print("Available commands:")
print(" voice - Start voice interaction mode")
print(" test voice - Test voice input/output")
print(" help - Show this help message")
print(" quit/exit - Shutdown Autumn")
print("\nIn voice mode:")
print(" Say 'Autumn' or 'Hey Autumn' to wake up")
print(" Press Ctrl+C to return to text mode")
print("\nGeneral usage:")
print(" - Ask questions: 'What's 5 plus 3?'")
print(" - Request jokes: 'Tell me a joke'")
print(" - Have conversations: 'How are you today?'")
print("="*60)
async def shutdown(self):
"""Gracefully shutdown Autumn."""
logger.info("🛑 Shutting down Autumn AI Assistant...")
self.running = False
if self.voice:
await self.voice.shutdown()
if self.brain:
await self.brain.shutdown()
if self.memory:
await self.memory.close()
logger.info("👋 Autumn has been shut down gracefully")
async def test_voice(self):
"""Test voice input and output."""
print("\n🎙️ Testing voice system...")
# Test TTS
print("🔊 Testing Text-to-Speech...")
await self.voice.speak("Hello! This is a voice test. Can you hear me clearly?", mode=AutumnMode.FREE)
# Test microphone
print("🎤 Testing microphone...")
print("🎤 Say something now (5 seconds)...")
text = await self.voice.listen_and_transcribe(duration=5)
if text:
print(f"[HEARD] I heard: '{text}'")
await self.voice.speak(f"I heard you say: {text}", mode=AutumnMode.FREE)
else:
print("❌ No speech detected")
# Test wake word
print("🎯 Testing wake word detection...")
print("🎤 Say 'Autumn' or 'Hey Autumn' now...")
detected = await self.voice.listen_for_wake_word()
if detected:
print("[WAKE] Wake word detected!")
await self.voice.speak("Wake word detected successfully!", mode=AutumnMode.FREE)
else:
print("❌ Wake word not detected")
print("🎙️ Voice test complete!")
async def main():
"""Main entry point for Autumn AI Assistant CLI."""
autumn = None
try:
# Create and start Autumn
autumn = AutumnCLI()
await autumn.start()
except KeyboardInterrupt:
logger.info("🛑 Received shutdown signal")
except Exception as e:
logger.error(f"❌ Critical error: {e}")
finally:
if autumn:
await autumn.shutdown()
if __name__ == "__main__":
print("🍂 Welcome to Autumn AI Assistant (CLI Mode)")
print("⚡ Starting up...")
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n👋 Goodbye!")
except Exception as e:
print(f"❌ Failed to start: {e}")
sys.exit(1)