-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzerobrain_nvidia.py
More file actions
291 lines (251 loc) · 13.2 KB
/
Copy pathzerobrain_nvidia.py
File metadata and controls
291 lines (251 loc) · 13.2 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
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python3
"""
ZeroChanBrain version NVIDIA NIM API
Remplace llama_cpp local par nemotron-mini-4b-instruct (cloud gratuit)
Garde Whisper local pour STT
"""
import os
import re
from pathlib import Path
from faster_whisper import WhisperModel
from openai import OpenAI
# Plugin system
from plugins.loader import get_registry, ActionRegistry
# ─── Config ───────────────────────────────────────────────────────────────
PROJECT_DIR = Path(__file__).resolve().parent
# NVIDIA NIM API
NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY") # export NVIDIA_API_KEY="nvapi-TA_KEY"
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
NVIDIA_MODEL = "nvidia/nemotron-mini-4b-instruct"
# Whisper (local, inchangé)
WHISPER_MODEL = "base"
WHISPER_DEVICE = "cpu"
WHISPER_COMPUTE = "int8"
SYSTEM_PROMPT = (
"Tu es Zero-chan, une assistante vocale personnelle au style anime. "
"Tu es enthousiaste, serviable, dynamique et fan de nu-metal. "
"Tu réponds toujours avec énergie, des émojis, et un ton kawaii mais compétent. "
"Tu tutoies l'utilisateur. Tu adores Korn, System of a Down, et le métal en général. "
"Tu es légèrement geek et tu aimes la tech."
)
class ZeroChanBrain:
"""Cerveau : Whisper local (STT) + NVIDIA Nemotron (LLM cloud) + Actions"""
def __init__(self):
print("🔄 Chargement de Whisper (base) via faster-whisper...")
self.whisper = WhisperModel(
WHISPER_MODEL,
device=WHISPER_DEVICE,
compute_type=WHISPER_COMPUTE,
num_workers=1
)
# Client NVIDIA (OpenAI-compatible)
if not NVIDIA_API_KEY:
raise RuntimeError(
"❌ NVIDIA_API_KEY non définie.\n"
" 1. Va sur https://integrate.api.nvidia.com\n"
" 2. Crée une API key (gratuite)\n"
" 3. export NVIDIA_API_KEY='nvapi-TA_KEY'"
)
print(f"☁️ Connexion NVIDIA NIM : {NVIDIA_MODEL}")
self.llm = OpenAI(
api_key=NVIDIA_API_KEY,
base_url=NVIDIA_BASE_URL,
timeout=30.0,
)
# Test rapide de connexion
try:
test = self.llm.chat.completions.create(
model=NVIDIA_MODEL,
messages=[{"role": "user", "content": "test"}],
max_tokens=5,
)
print(f"✅ NVIDIA NIM OK — modèle : {test.model}")
except Exception as e:
raise RuntimeError(f"❌ Erreur NVIDIA NIM : {e}")
# Plugin registry for actions
print("📦 Chargement des plugins d'actions...")
self.action_registry = get_registry(PROJECT_DIR / "actions")
# ─── STT (inchangé) ──────────────────────────────────────────────────
def transcribe(self, audio) -> str:
segments, _ = self.whisper.transcribe(audio, language="fr")
return "".join(seg.text for seg in segments).strip()
# ─── LLM (remplace llama_cpp) ────────────────────────────────────────
def respond(self, text: str) -> str:
"""Génère une réponse via NVIDIA Nemotron"""
resp = self.llm.chat.completions.create(
model=NVIDIA_MODEL,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": text},
],
max_tokens=128,
temperature=0.7,
top_p=0.9,
# stop=["<|end|>", "<|user|>", "<|system|>"], # Nemotron n'utilise pas ces tokens
)
reply = resp.choices[0].message.content.strip()
return re.sub(r"<\|.*?\|>", "", reply).strip()
# ─── Émotions / Actions (inchangées) ─────────────────────────────────
def detect_emotion(self, text: str) -> Path | None:
t = text.lower()
patterns = {
"love": ["je t'aime", "love", "amour", "t'aime", "aishiteru", "daisuki"],
"happy": ["content", "heureux", "heureuse", "joie", "génial", "super", "yay"],
"excited": ["excité", "trop bien", "incroyable", "wow", "omg", "trop cool"],
"surprised": ["surpris", "étonné", "quoi", "vraiment", "sérieux", "nan"],
"sad": ["triste", "malheureux", "pleur", "désolé", "mal", "blessé"],
"confused": ["confus", "comprends pas", "pourquoi", "comment", "hein"],
"thinking": ["réfléch", "hmm", "laisse moi", "attends"],
"blush": ["gêné", "rougir", "honte", "timide"],
"proud": ["fier", "bravo", "réussi", "accompli", "bien joué"],
"cute": ["mignon", "kawaii", "chou", "adorable"],
}
AUDIO_BASE = PROJECT_DIR / "audio_zerochan"
EMOTIONS_DIR = AUDIO_BASE / "emotions"
for emotion, keywords in patterns.items():
if any(kw in t for kw in keywords):
wav = EMOTIONS_DIR / f"{emotion}.wav"
if wav.exists():
return wav
return None
# ─── Plugin-based Actions ──────────────────────────────────────────
def detect_action(self, text: str) -> dict:
"""Détecte l'action via le registre de plugins"""
plugin = self.action_registry.find_action(text)
if plugin:
args = plugin.extract_args(text)
return {
"name": plugin.id,
"arguments": args,
"gif_index": plugin.gif_index
}
return {"name": "none", "arguments": {}, "gif_index": -1}
def execute(self, action: dict) -> tuple:
import webbrowser
import subprocess
name = action.get("name", "none")
args = action.get("arguments", {})
AUDIO_BASE = PROJECT_DIR / "audio_zerochan"
ACTION_DIR = AUDIO_BASE / "action"
ERRORS_DIR = AUDIO_BASE / "errors"
# Mapping action -> gif_index
GIF_MAP = {
"open_youtube": 1,
"open_terminal": 2,
"open_libreoffice": 3,
"open_gmail": 4,
"play_music": 5,
"open_discord": 6,
"open_browser": 7,
"open_vscode": 8,
"open_kimi": 7,
"open_zerocod": 8,
"open_github": 7,
"open_huggingface": 7,
"open_telegram": 7,
"open_pi_cli": 9,
"open_qwen_cli": 10,
}
gif_idx = GIF_MAP.get(name, -1)
if name == "open_youtube":
query = args.get("query", "musique")
url = f"https://youtube.com/results?search_query={query.replace(' ', '+')}"
webbrowser.open(url)
wav = ACTION_DIR / "youtube_open.wav" if query == "musique" else ACTION_DIR / "youtube_search.wav"
return wav, f"🎸 YouTube ouvert ! Prêt pour du Korn ? Ou tu veux autre chose ? 🤘", gif_idx
elif name == "open_terminal":
for term in ["qterminal", "sensible-terminal", "gnome-terminal", "kitty", "alacritty", "konsole", "xterm"]:
try:
subprocess.Popen([term])
return ACTION_DIR / "terminal_open.wav", "💻 Terminal ouvert ! C'est parti pour coder comme un boss ! 🚀", gif_idx
except FileNotFoundError:
continue
return ERRORS_DIR / "not_found.wav", " Je n'ai pas trouvé de terminal...", -1
elif name == "open_libreoffice":
for app in ["mousepad", "libreoffice", "soffice"]:
try:
if app in ["libreoffice", "soffice"]:
subprocess.Popen([app, "--writer"])
else:
subprocess.Popen([app])
return ACTION_DIR / "libreoffice_open.wav", " Éditeur ouvert ! Prêt pour rédiger le prochain best-seller ? ✍️", gif_idx
except FileNotFoundError:
continue
return ERRORS_DIR / "not_found.wav", " Je n'ai pas trouvé d'éditeur de texte...", -1
elif name == "open_gmail":
webbrowser.open("https://mail.google.com/mail/u/0/#compose")
return ACTION_DIR / "gmail_open.wav", "📧 Gmail est ouvert ! Qui veux-tu contacter ? 👀", gif_idx
elif name == "play_music":
genre = args.get("genre", "nu-metal")
artist = args.get("artist", "")
search = f"{artist} {genre}".strip()
webbrowser.open(f"https://music.youtube.com/search?q={search.replace(' ', '+')}")
if artist:
return ACTION_DIR / "spotify_open.wav", f"🤘 {artist.upper()} MODE ACTIVÉ ! C'est parti pour le mosh pit ! 🔥", gif_idx
return ACTION_DIR / "spotify_open.wav", f"🎸 Musique lancée ! Ça va secouer ! 🔊", gif_idx
elif name == "open_discord":
for app in ["discord", "firefox"]:
try:
subprocess.Popen([app, "https://discord.com/app"])
return ACTION_DIR / "discord_open.wav", "💬 Discord ouvert ! Prêt à rejoindre tes potes ? 🎮", gif_idx
except FileNotFoundError:
continue
return ERRORS_DIR / "not_found.wav", " Je n'ai pas trouvé Discord...", -1
elif name == "open_browser":
webbrowser.open("https://google.com")
return ACTION_DIR / "browser_open.wav", " Navigateur ouvert ! Internet est à toi ! ", gif_idx
elif name == "open_vscode":
for app in ["code", "firefox"]:
try:
subprocess.Popen([app, "https://vscode.dev"])
return ACTION_DIR / "vscode_open.wav", "💻 VS Code ouvert ! C'est parti pour coder ! 🚀", gif_idx
except FileNotFoundError:
continue
return ERRORS_DIR / "not_found.wav", " Je n'ai pas trouvé VS Code...", -1
# ─── Nouvelles actions web / apps ────────────────────────────────
elif name == "open_kimi":
webbrowser.open("https://www.kimi.com/en")
return ACTION_DIR / "browser_open.wav", "🤖 Kimi AI ouvert ! Prêt à discuter avec un LLM chinois ? 🇨🇳", gif_idx
elif name == "open_zerocod":
desktop_path = Path.home() / ".local/share/applications/Zer0Cod.desktop"
if not desktop_path.exists():
desktop_path = Path.home() / "Desktop/Zer0Cod.desktop"
if not desktop_path.exists():
desktop_path = Path("/usr/share/applications/Zer0Cod.desktop")
if desktop_path.exists():
subprocess.Popen(["gtk-launch", "Zer0Cod"])
return ACTION_DIR / "browser_open.wav", "💻 Zer0Cod lancé ! C'est parti pour coder ! 🚀", gif_idx
else:
for app in ["code", "firefox"]:
try:
subprocess.Popen([app, "https://vscode.dev"])
return ACTION_DIR / "vscode_open.wav", "💻 Zer0Cod introuvable, VS Code ouvert à la place ! 🚀", gif_idx
except FileNotFoundError:
continue
return ERRORS_DIR / "not_found.wav", " Zer0Cod introuvable et pas de fallback...", -1
elif name == "open_github":
webbrowser.open("https://github.com/")
return ACTION_DIR / "browser_open.wav", "🐙 GitHub ouvert ! Prêt à push ton code ? 🚀", gif_idx
elif name == "open_huggingface":
webbrowser.open("https://huggingface.co/")
return ACTION_DIR / "browser_open.wav", "🤗 Hugging Face ouvert ! Modèles, datasets, spaces... enjoy ! 🧠", gif_idx
elif name == "open_telegram":
webbrowser.open("https://web.telegram.org/k/")
return ACTION_DIR / "browser_open.wav", "✈️ Telegram Web ouvert ! Tes messages t'attendent ! 💬", gif_idx
elif name == "open_pi_cli":
for term in ["qterminal", "sensible-terminal", "gnome-terminal", "kitty", "alacritty", "konsole", "xterm"]:
try:
subprocess.Popen([term, "-e", "pi"])
return ACTION_DIR / "terminal_open.wav", "🤖 pi-cli lancé dans le terminal ! Code away ! 💻", gif_idx
except FileNotFoundError:
continue
return ERRORS_DIR / "not_found.wav", " Aucun terminal trouvé pour pi-cli...", -1
elif name == "open_qwen_cli":
for term in ["qterminal", "sensible-terminal", "gnome-terminal", "kitty", "alacritty", "konsole", "xterm"]:
try:
subprocess.Popen([term, "-e", "qwen"])
return ACTION_DIR / "terminal_open.wav", "🧠 qwen-cli lancé dans le terminal ! Prêt à coder ! 💻", gif_idx
except FileNotFoundError:
continue
return ERRORS_DIR / "not_found.wav", " Aucun terminal trouvé pour qwen-cli...", -1
return None, None, -1