jefffffff9 Claude Sonnet 4.6 commited on
Commit
096b19d
·
1 Parent(s): 96cdb10

Phase 1: Sahel-Voice-Lab — The Memory Loop

Browse files

New project pivot: self-learning voice assistant for Bambara/Fula
using 100% non-Meta tech stack.

New files:
- app_lab.py — Gradio UI: push-to-talk + last 5 words panel
- src/memory/memory_manager.py — persists vocabulary.jsonl to HF Hub
- src/llm/gemma_client.py — Gemma via HF Serverless Inference API
- data/vocabulary.jsonl — empty initial vocabulary store

Flow: audio → Whisper STT → Gemma (with vocabulary context) →
teaching intent → MemoryManager.add_word_pair() → Hub push
question intent → answer from vocabulary
conversation → natural reply

README.md updated: app_file changed to app_lab.py, stack documented.

Stack: openai/whisper-large-v3-turbo (STT), google/gemma-3-4b-it (LLM),
Waxal TTS (Phase 2), HF Dataset for memory.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

README.md CHANGED
@@ -1,39 +1,50 @@
1
  ---
2
- title: Sahel-Agri Voice AI
3
- emoji: 🌾
4
- colorFrom: green
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: "5.25.0"
8
- app_file: app.py
9
  hardware: cpu-basic
10
  pinned: false
11
  license: mit
12
  tags:
13
- - agriculture
14
  - bambara
15
  - fula
16
  - speech-recognition
17
- - text-to-speech
18
  - west-africa
19
  - low-resource-nlp
 
20
  ---
21
 
22
- # 🌾 Sahel-Agri Voice AI
23
 
24
- Two-way voice assistant for Malian and Guinean farmers. Speak in **Bambara** or **Fula** get agricultural insights spoken back in your language.
25
 
26
- ## Features
27
- - 🎙️ Voice input via microphone or file upload
28
- - 🌍 Bambara (bam) and Fula (ful) speech recognition via Whisper + LoRA adapters
29
- - 🔊 Native-language voice responses via Facebook MMS-TTS
30
- - 📊 Soil, weather, irrigation, and pest alerts from IoT sensors
31
- - 💾 Feedback saved to HuggingFace Dataset for continuous improvement
32
 
33
- ## Languages supported
34
- | Language | STT | TTS |
35
- |----------|-----|-----|
36
- | Bambara (bam) | ✅ Whisper + LoRA | ✅ facebook/mms-tts-bam |
37
- | Fula (ful) | Whisper + LoRA | facebook/mms-tts-ful |
38
- | French (fr) | Whisper | facebook/mms-tts-fra |
39
- | English (en) | Whisper | ✅ facebook/mms-tts-eng |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Sahel-Voice-Lab
3
+ emoji: 🌍
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: gradio
7
  sdk_version: "5.25.0"
8
+ app_file: app_lab.py
9
  hardware: cpu-basic
10
  pinned: false
11
  license: mit
12
  tags:
 
13
  - bambara
14
  - fula
15
  - speech-recognition
16
+ - language-learning
17
  - west-africa
18
  - low-resource-nlp
19
+ - memory
20
  ---
21
 
22
+ # 🌍 Sahel-Voice-Lab — Internal Edition
23
 
24
+ **Phase 1 · The Memory Loop**
25
 
26
+ A self-learning voice assistant for Bambara and Fula. Teach it words — it remembers them forever.
 
 
 
 
 
27
 
28
+ ## Stack (100% non-Meta)
29
+ | Component | Model |
30
+ |-----------|-------|
31
+ | STT | `openai/whisper-large-v3-turbo` |
32
+ | LLM | `google/gemma-3-4b-it` (set `LLM_MODEL_ID` env var for Gemma 4) |
33
+ | TTS | Waxal Phase 2 |
34
+ | Memory | HF Dataset `vocabulary.jsonl` |
35
+
36
+ ## How it works
37
+ 1. Press Push-to-Talk → speak in Bambara, Fula, French, or English
38
+ 2. Whisper transcribes your speech
39
+ 3. Gemma reads the vocabulary it has learned so far, then:
40
+ - **Teaching mode**: detects "X means Y" → saves the word pair to the Hub
41
+ - **Question mode**: answers using vocabulary as source of truth
42
+ - **Conversation mode**: replies naturally
43
+ 4. The last 5 learned words are always visible
44
+
45
+ ## Space secrets required
46
+ | Key | Value |
47
+ |-----|-------|
48
+ | `HF_TOKEN` | Your HF write-access token |
49
+ | `FEEDBACK_REPO_ID` | `ous-sow/sahel-agri-feedback` |
50
+ | `LLM_MODEL_ID` | `google/gemma-3-4b-it` (or Gemma 4 model ID) |
app_lab.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sahel-Voice-Lab — Internal Edition (Phase 1: The Memory Loop)
3
+
4
+ Stack (100% non-Meta):
5
+ STT : openai/whisper-large-v3-turbo
6
+ LLM : google/gemma-3-4b-it (or LLM_MODEL_ID env var — update to Gemma 4)
7
+ TTS : Phase 2 — Waxal TTS (not yet integrated)
8
+ Store: HF Dataset ous-sow/sahel-agri-feedback → vocabulary.jsonl
9
+
10
+ Flow:
11
+ 1. User presses Push-to-Talk → records audio
12
+ 2. Whisper transcribes to text
13
+ 3. MemoryManager injects current vocabulary into Gemma's system prompt
14
+ 4. Gemma returns structured JSON:
15
+ teaching → MemoryManager.add_word_pair() → push to Hub
16
+ question → answer using vocabulary
17
+ conversation → natural reply
18
+ 5. UI shows Gemma's reply + last 5 learned words
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import sys
24
+ import threading
25
+ from pathlib import Path
26
+
27
+ import gradio as gr
28
+
29
+ ROOT = Path(__file__).parent
30
+ sys.path.insert(0, str(ROOT))
31
+
32
+ # ── Env ───────────────────────────────────────────────────────────────────────
33
+ HF_TOKEN = os.environ.get("HF_TOKEN")
34
+ FEEDBACK_REPO_ID = os.environ.get("FEEDBACK_REPO_ID", "ous-sow/sahel-agri-feedback")
35
+ WHISPER_MODEL_ID = os.environ.get("WHISPER_MODEL_ID", "openai/whisper-large-v3-turbo")
36
+ LLM_MODEL_ID = os.environ.get("LLM_MODEL_ID", "google/gemma-3-4b-it")
37
+
38
+ LANGUAGE_NAMES = {
39
+ "bam": "Bambara",
40
+ "ful": "Fula / Pular",
41
+ "fr": "French",
42
+ "en": "English",
43
+ }
44
+
45
+ # ── Singletons ────────────────────────────────────────────────────────────────
46
+ from src.memory.memory_manager import MemoryManager
47
+ from src.llm.gemma_client import GemmaClient
48
+
49
+ _memory = MemoryManager(repo_id=FEEDBACK_REPO_ID, hf_token=HF_TOKEN)
50
+ _gemma = GemmaClient(model_id=LLM_MODEL_ID, hf_token=HF_TOKEN)
51
+
52
+ # Whisper — loaded lazily in background
53
+ _whisper_model = None
54
+ _whisper_processor = None
55
+ _whisper_lock = threading.Lock()
56
+ _whisper_status = "not loaded"
57
+
58
+
59
+ # ── Whisper loading ───────────────────────────────────────────────────────────
60
+
61
+ def _do_load_whisper() -> None:
62
+ global _whisper_model, _whisper_processor, _whisper_status
63
+ import torch
64
+ try:
65
+ from transformers.models.whisper import WhisperProcessor, WhisperForConditionalGeneration
66
+ except ImportError:
67
+ from transformers.models.whisper.processing_whisper import WhisperProcessor
68
+ from transformers.models.whisper.modeling_whisper import WhisperForConditionalGeneration
69
+
70
+ _whisper_status = "loading…"
71
+ try:
72
+ _whisper_processor = WhisperProcessor.from_pretrained(
73
+ WHISPER_MODEL_ID, token=HF_TOKEN
74
+ )
75
+ _whisper_model = WhisperForConditionalGeneration.from_pretrained(
76
+ WHISPER_MODEL_ID, token=HF_TOKEN
77
+ )
78
+ _whisper_model.eval()
79
+ _whisper_status = f"ready ({WHISPER_MODEL_ID})"
80
+ except Exception as exc:
81
+ _whisper_status = f"error: {exc}"
82
+
83
+
84
+ def _ensure_whisper() -> str:
85
+ global _whisper_status
86
+ with _whisper_lock:
87
+ if _whisper_model is None and "loading" not in _whisper_status:
88
+ _whisper_status = "loading…"
89
+ threading.Thread(target=_do_load_whisper, daemon=True).start()
90
+ return _whisper_status
91
+
92
+
93
+ def _whisper_status_label() -> str:
94
+ s = _ensure_whisper()
95
+ if "ready" in s: return f"🟢 STT {s}"
96
+ if "loading" in s: return f"🟡 STT {s}"
97
+ if "error" in s: return f"🔴 STT {s}"
98
+ return f"⚪ STT {s}"
99
+
100
+
101
+ def _transcribe(audio_path: str, language_hint: str) -> str:
102
+ """Run Whisper STT. Returns transcribed text."""
103
+ if _whisper_model is None:
104
+ return ""
105
+ import torch, librosa
106
+ audio_np, _ = librosa.load(audio_path, sr=16_000, mono=True)
107
+
108
+ with _whisper_lock:
109
+ inputs = _whisper_processor.feature_extractor(
110
+ audio_np, sampling_rate=16_000, return_tensors="pt"
111
+ )
112
+ input_features = inputs.input_features
113
+
114
+ # Whisper doesn't have Bambara / Fula tokens — let it auto-detect
115
+ if language_hint in ("bam", "ful"):
116
+ forced_ids = None
117
+ else:
118
+ try:
119
+ forced_ids = _whisper_processor.get_decoder_prompt_ids(
120
+ language=language_hint, task="transcribe"
121
+ )
122
+ except Exception:
123
+ forced_ids = None
124
+
125
+ with torch.no_grad():
126
+ predicted_ids = _whisper_model.generate(
127
+ input_features,
128
+ forced_decoder_ids=forced_ids,
129
+ max_new_tokens=256,
130
+ )
131
+
132
+ return _whisper_processor.batch_decode(predicted_ids, skip_special_tokens=True)[0].strip()
133
+
134
+
135
+ # ── Core pipeline ─────────────────────────────────────────────────────────────
136
+
137
+ def process_audio(audio_path, language_label: str, history: list) -> tuple:
138
+ """
139
+ Full pipeline: audio → Whisper → Gemma → (optional) memory update.
140
+ Returns: (updated_history, last_5_words_md, status_text)
141
+ """
142
+ if audio_path is None:
143
+ return history, _render_recent_words(), "⚠️ No audio recorded."
144
+
145
+ lang_code = _label_to_code(language_label)
146
+
147
+ # 1. Transcribe
148
+ status = _ensure_whisper()
149
+ if _whisper_model is None:
150
+ return history, _render_recent_words(), f"⏳ {status} — wait a moment and try again."
151
+
152
+ transcript = _transcribe(audio_path, lang_code)
153
+ if not transcript:
154
+ return history, _render_recent_words(), "⚠️ Could not transcribe audio."
155
+
156
+ # 2. Ask Gemma (with vocabulary context)
157
+ vocab_ctx = _memory.get_vocabulary_context()
158
+ llm_result = _gemma.chat(transcript, vocab_ctx)
159
+ intent = llm_result.get("intent", "conversation")
160
+ response = llm_result.get("response", "…")
161
+
162
+ # 3. If teaching intent → persist to memory
163
+ if intent == "teaching":
164
+ word = llm_result.get("word", transcript)
165
+ lang = llm_result.get("language", lang_code)
166
+ trans = llm_result.get("translation", "")
167
+ trans_l = llm_result.get("translation_language", "en")
168
+ if word and trans:
169
+ _memory.add_word_pair(
170
+ word=word,
171
+ language=lang,
172
+ translation=trans,
173
+ translation_language=trans_l,
174
+ source="user_taught",
175
+ )
176
+
177
+ # 4. Update chat history
178
+ history = history or []
179
+ history.append({
180
+ "role": "user",
181
+ "content": f"[{LANGUAGE_NAMES.get(lang_code, lang_code)}] {transcript}"
182
+ })
183
+ history.append({
184
+ "role": "assistant",
185
+ "content": response
186
+ })
187
+
188
+ status_msg = {
189
+ "teaching": "✅ Word learned and saved!",
190
+ "question": "💬 Answered from vocabulary.",
191
+ "conversation": "💬 Replied.",
192
+ "error": "⚠️ LLM error.",
193
+ }.get(intent, "💬 Replied.")
194
+
195
+ return history, _render_recent_words(), status_msg
196
+
197
+
198
+ def process_text(text: str, language_label: str, history: list) -> tuple:
199
+ """Same as process_audio but takes typed text (fallback path)."""
200
+ if not text.strip():
201
+ return history, _render_recent_words(), "⚠️ Please type something."
202
+
203
+ lang_code = _label_to_code(language_label)
204
+ vocab_ctx = _memory.get_vocabulary_context()
205
+ llm_result = _gemma.chat(text.strip(), vocab_ctx)
206
+ intent = llm_result.get("intent", "conversation")
207
+ response = llm_result.get("response", "…")
208
+
209
+ if intent == "teaching":
210
+ word = llm_result.get("word", text)
211
+ lang = llm_result.get("language", lang_code)
212
+ trans = llm_result.get("translation", "")
213
+ trans_l = llm_result.get("translation_language", "en")
214
+ if word and trans:
215
+ _memory.add_word_pair(word, lang, trans, trans_l, source="user_taught")
216
+
217
+ history = history or []
218
+ history.append({"role": "user", "content": text.strip()})
219
+ history.append({"role": "assistant", "content": response})
220
+
221
+ status_msg = {
222
+ "teaching": "✅ Word learned and saved!",
223
+ "question": "💬 Answered from vocabulary.",
224
+ "conversation": "💬 Replied.",
225
+ "error": "⚠️ LLM error.",
226
+ }.get(intent, "💬 Replied.")
227
+
228
+ return history, _render_recent_words(), status_msg
229
+
230
+
231
+ # ── Helpers ───────────────────────────────────────────────────────────────────
232
+
233
+ LANGUAGE_CHOICES = ["Bambara (bam)", "Fula (ful)", "French (fr)", "English (en)"]
234
+
235
+ def _label_to_code(label: str) -> str:
236
+ mapping = {
237
+ "Bambara (bam)": "bam",
238
+ "Fula (ful)": "ful",
239
+ "French (fr)": "fr",
240
+ "English (en)": "en",
241
+ }
242
+ return mapping.get(label, "bam")
243
+
244
+
245
+ def _render_recent_words() -> str:
246
+ recent = _memory.get_recent(5)
247
+ if not recent:
248
+ return "_No words learned yet. Start teaching me! Say something like: **'I ni ce means hello in Bambara'**_"
249
+ lines = ["### 📖 Last 5 words learned\n"]
250
+ for e in reversed(recent):
251
+ lang = LANGUAGE_NAMES.get(e.get("language", "?"), e.get("language", "?"))
252
+ word = e.get("word", "")
253
+ tr = e.get("translation", "")
254
+ tr_l = e.get("translation_language", "")
255
+ lines.append(f"**{word}** `[{lang}]` → {tr} `({tr_l})`")
256
+ return "\n\n".join(lines)
257
+
258
+
259
+ # ── UI ────────────────────────────────────────────────────────────────────────
260
+
261
+ def build_ui() -> gr.Blocks:
262
+ with gr.Blocks(title="Sahel-Voice-Lab", theme=gr.themes.Soft()) as demo:
263
+
264
+ gr.Markdown(
265
+ "# 🌍 Sahel-Voice-Lab — Internal Edition\n"
266
+ "**Phase 1 · The Memory Loop** \n"
267
+ "Teach me Bambara and Fula — I will remember every word you share."
268
+ )
269
+
270
+ with gr.Row():
271
+ # ── Left column: input ────────────────────────────────────────────
272
+ with gr.Column(scale=2):
273
+ status_box = gr.Textbox(
274
+ value=_whisper_status_label(),
275
+ label="Status",
276
+ interactive=False,
277
+ max_lines=1,
278
+ )
279
+ status_timer = gr.Timer(value=3)
280
+ status_timer.tick(fn=_whisper_status_label, outputs=status_box)
281
+
282
+ language_dd = gr.Dropdown(
283
+ choices=LANGUAGE_CHOICES,
284
+ value="Bambara (bam)",
285
+ label="Language you are speaking",
286
+ )
287
+
288
+ with gr.Tab("🎙️ Push-to-Talk"):
289
+ audio_input = gr.Audio(
290
+ sources=["microphone"],
291
+ type="filepath",
292
+ label="Hold to record — release to send",
293
+ )
294
+ talk_btn = gr.Button("▶ Send Recording", variant="primary", size="lg")
295
+
296
+ with gr.Tab("⌨️ Type instead"):
297
+ text_input = gr.Textbox(
298
+ lines=3,
299
+ placeholder=(
300
+ "Type a message or teach me a word.\n"
301
+ "Examples:\n"
302
+ " 'I ni ce means hello in Bambara'\n"
303
+ " 'How do you say goodbye in Fula?'"
304
+ ),
305
+ label="Message",
306
+ )
307
+ text_btn = gr.Button("▶ Send", variant="primary")
308
+
309
+ action_status = gr.Textbox(
310
+ label="Last action", interactive=False, max_lines=1
311
+ )
312
+
313
+ gr.Markdown(
314
+ "**Teaching tips:**\n"
315
+ "- Say or type: *'I ni ce means hello in Bambara'*\n"
316
+ "- Or: *'Jam waali veut dire bonjour en Fula'*\n"
317
+ "- Or: *'How do you say 'rain' in Bambara?'*\n\n"
318
+ "Every new word is saved to the Hub automatically."
319
+ )
320
+
321
+ # ── Right column: memory + chat ───────────────────────────────────
322
+ with gr.Column(scale=3):
323
+ recent_words = gr.Markdown(value=_render_recent_words())
324
+
325
+ gr.Markdown("---")
326
+
327
+ chatbot = gr.Chatbot(
328
+ label="Conversation",
329
+ height=420,
330
+ type="messages",
331
+ bubble_full_width=False,
332
+ )
333
+
334
+ clear_btn = gr.Button("🗑️ Clear conversation", size="sm", variant="secondary")
335
+
336
+ # ── Wiring ────────────────────────────────────────────────────────────
337
+ history_state = gr.State([])
338
+
339
+ talk_btn.click(
340
+ fn=process_audio,
341
+ inputs=[audio_input, language_dd, history_state],
342
+ outputs=[history_state, recent_words, action_status],
343
+ ).then(
344
+ fn=lambda h: h,
345
+ inputs=[history_state],
346
+ outputs=[chatbot],
347
+ )
348
+
349
+ text_btn.click(
350
+ fn=process_text,
351
+ inputs=[text_input, language_dd, history_state],
352
+ outputs=[history_state, recent_words, action_status],
353
+ ).then(
354
+ fn=lambda h: (h, ""),
355
+ inputs=[history_state],
356
+ outputs=[chatbot, text_input],
357
+ )
358
+
359
+ text_input.submit(
360
+ fn=process_text,
361
+ inputs=[text_input, language_dd, history_state],
362
+ outputs=[history_state, recent_words, action_status],
363
+ ).then(
364
+ fn=lambda h: (h, ""),
365
+ inputs=[history_state],
366
+ outputs=[chatbot, text_input],
367
+ )
368
+
369
+ clear_btn.click(
370
+ fn=lambda: ([], _render_recent_words(), ""),
371
+ outputs=[history_state, recent_words, action_status],
372
+ ).then(fn=lambda: [], outputs=[chatbot])
373
+
374
+ return demo
375
+
376
+
377
+ # ── Entry point ───────────────────────────────────────────────────────────────
378
+
379
+ # Load vocabulary at startup (background — non-blocking for the UI)
380
+ threading.Thread(target=_memory.load, daemon=True).start()
381
+ # Begin loading Whisper immediately
382
+ _ensure_whisper()
383
+
384
+ if __name__ == "__main__":
385
+ from dotenv import load_dotenv
386
+ load_dotenv()
387
+ HF_TOKEN = os.environ.get("HF_TOKEN")
388
+ FEEDBACK_REPO_ID = os.environ.get("FEEDBACK_REPO_ID", "ous-sow/sahel-agri-feedback")
389
+ WHISPER_MODEL_ID = os.environ.get("WHISPER_MODEL_ID", "openai/whisper-large-v3-turbo")
390
+ LLM_MODEL_ID = os.environ.get("LLM_MODEL_ID", "google/gemma-3-4b-it")
391
+
392
+ _memory._hf_token = HF_TOKEN
393
+ _memory._repo_id = FEEDBACK_REPO_ID
394
+ _gemma._hf_token = HF_TOKEN
395
+
396
+ print(f"STT model : {WHISPER_MODEL_ID}")
397
+ print(f"LLM model : {LLM_MODEL_ID}")
398
+ print(f"Store : {FEEDBACK_REPO_ID}")
399
+ print(f"HF_TOKEN : {'set' if HF_TOKEN else 'NOT SET — Hub push disabled'}")
400
+ print()
401
+
402
+ demo = build_ui()
403
+ demo.launch(
404
+ server_port=7860,
405
+ inbrowser=False,
406
+ share=False,
407
+ show_api=False,
408
+ ssr_mode=False,
409
+ )
data/vocabulary.jsonl ADDED
File without changes
src/llm/__init__.py ADDED
File without changes
src/llm/gemma_client.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GemmaClient — wraps the HuggingFace Serverless Inference API for Gemma.
3
+
4
+ The system prompt implements the 'adult-child' logic:
5
+ - The LLM is a child learning Bambara/Fula from the user (adult/teacher)
6
+ - vocabulary.jsonl is its primary memory / source of truth
7
+ - It detects TEACHING intent and returns structured JSON so MemoryManager
8
+ can persist the new word
9
+ - It answers QUESTIONS using the vocabulary it has learned
10
+
11
+ Model: configurable via LLM_MODEL_ID env var.
12
+ Default: google/gemma-3-4b-it (update to Gemma 4 when available on HF Hub)
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ import re
19
+ from typing import Optional
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ SYSTEM_PROMPT_TEMPLATE = """\
24
+ You are an AI language assistant learning Bambara and Fula — two West African languages. \
25
+ You behave like an eager child learner: you absorb every word the user teaches you, \
26
+ and you use what you have already learned to answer questions.
27
+
28
+ YOUR CURRENT VOCABULARY (your only source of truth):
29
+ {vocabulary_context}
30
+
31
+ RESPONSE RULES — always reply with a single valid JSON object, nothing else:
32
+
33
+ 1. If the user is TEACHING you a word or phrase (e.g. "I ni ce means hello" / \
34
+ "X se dit Y en bambara" / "X veut dire Y"), reply:
35
+ {{
36
+ "intent": "teaching",
37
+ "word": "<the word/phrase being taught>",
38
+ "language": "<bam | ful | fr | en>",
39
+ "translation": "<the translation given>",
40
+ "translation_language": "<bam | ful | fr | en>",
41
+ "response": "<warm acknowledgment in the same language the user used, \
42
+ 1-2 sentences, use the word in a sentence if possible>"
43
+ }}
44
+
45
+ 2. If the user is ASKING a question you can answer using the vocabulary:
46
+ {{
47
+ "intent": "question",
48
+ "response": "<answer using vocabulary — be honest if you don't know>"
49
+ }}
50
+
51
+ 3. For general CONVERSATION or GREETING:
52
+ {{
53
+ "intent": "conversation",
54
+ "response": "<natural, friendly reply — 1-3 sentences>"
55
+ }}
56
+
57
+ Always be warm, encouraging, and curious. If unsure of intent, choose "conversation".\
58
+ """
59
+
60
+
61
+ class GemmaClient:
62
+ """Calls Gemma via HF Serverless Inference API."""
63
+
64
+ def __init__(
65
+ self,
66
+ model_id: str = "google/gemma-3-4b-it",
67
+ hf_token: Optional[str] = None,
68
+ ) -> None:
69
+ self.model_id = model_id
70
+ self.hf_token = hf_token
71
+ self._client = None # lazy init
72
+
73
+ def _get_client(self):
74
+ if self._client is None:
75
+ from huggingface_hub import InferenceClient
76
+ self._client = InferenceClient(token=self.hf_token)
77
+ return self._client
78
+
79
+ def chat(self, user_text: str, vocabulary_context: str) -> dict:
80
+ """
81
+ Send a message and get a structured response back.
82
+ Returns a dict with at minimum: intent, response.
83
+ On any error returns: {"intent": "error", "response": <error message>}
84
+ """
85
+ system_prompt = SYSTEM_PROMPT_TEMPLATE.format(
86
+ vocabulary_context=vocabulary_context or "(no vocabulary yet)"
87
+ )
88
+
89
+ try:
90
+ client = self._get_client()
91
+ completion = client.chat_completion(
92
+ model=self.model_id,
93
+ messages=[
94
+ {"role": "system", "content": system_prompt},
95
+ {"role": "user", "content": user_text},
96
+ ],
97
+ max_tokens=512,
98
+ temperature=0.4,
99
+ )
100
+ raw = completion.choices[0].message.content.strip()
101
+ logger.debug("Gemma raw response: %s", raw[:200])
102
+ return self._parse(raw)
103
+
104
+ except Exception as exc:
105
+ logger.error("GemmaClient error: %s", exc)
106
+ return {
107
+ "intent": "error",
108
+ "response": f"(LLM unavailable: {exc})",
109
+ }
110
+
111
+ # ── Parsing ───────────────────────────────────────────────────────────────
112
+
113
+ def _parse(self, raw: str) -> dict:
114
+ """Extract JSON from the model output — handles markdown code fences."""
115
+ # Strip markdown code fences if present
116
+ text = raw.strip()
117
+ fence_match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
118
+ if fence_match:
119
+ text = fence_match.group(1)
120
+ else:
121
+ # Find first { ... } block
122
+ brace_match = re.search(r"\{.*\}", text, re.DOTALL)
123
+ if brace_match:
124
+ text = brace_match.group(0)
125
+
126
+ try:
127
+ data = json.loads(text)
128
+ if "intent" not in data:
129
+ data["intent"] = "conversation"
130
+ if "response" not in data:
131
+ data["response"] = raw # fall back to raw text
132
+ return data
133
+ except json.JSONDecodeError:
134
+ # Return the raw text as a conversation response
135
+ return {"intent": "conversation", "response": raw}
src/memory/__init__.py ADDED
File without changes
src/memory/memory_manager.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MemoryManager — persists the vocabulary the assistant has learned.
3
+
4
+ Storage:
5
+ - Local file : data/vocabulary.jsonl (fast read/write during session)
6
+ - HF Hub : ous-sow/sahel-agri-feedback → vocabulary.jsonl (survives restarts)
7
+
8
+ Each line in vocabulary.jsonl is a JSON object:
9
+ {
10
+ "timestamp": "2026-04-07T12:00:00Z",
11
+ "word": "I ni ce",
12
+ "language": "bam",
13
+ "translation": "Hello / Good day",
14
+ "translation_language":"en",
15
+ "source": "user_taught"
16
+ }
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import logging
22
+ import threading
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+ from typing import Optional
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ LOCAL_PATH = Path(__file__).parent.parent.parent / "data" / "vocabulary.jsonl"
30
+ HUB_FILENAME = "vocabulary.jsonl"
31
+
32
+
33
+ class MemoryManager:
34
+ """Thread-safe vocabulary store backed by HF Hub."""
35
+
36
+ def __init__(self, repo_id: str, hf_token: Optional[str] = None) -> None:
37
+ self.repo_id = repo_id
38
+ self.hf_token = hf_token
39
+ self._lock = threading.Lock()
40
+ self._entries: list[dict] = []
41
+ LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
42
+
43
+ # ── Load ──────────────────────────────────────────────────────────────────
44
+
45
+ def load(self) -> None:
46
+ """Pull vocabulary.jsonl from HF Hub then cache locally. Non-fatal on failure."""
47
+ if self.hf_token and self.repo_id:
48
+ try:
49
+ from huggingface_hub import hf_hub_download
50
+ local = hf_hub_download(
51
+ repo_id=self.repo_id,
52
+ filename=HUB_FILENAME,
53
+ repo_type="dataset",
54
+ token=self.hf_token,
55
+ force_download=True,
56
+ )
57
+ import shutil
58
+ shutil.copy2(local, LOCAL_PATH)
59
+ logger.info("MemoryManager: loaded vocabulary from Hub (%s)", self.repo_id)
60
+ except Exception as exc:
61
+ logger.warning("MemoryManager: could not load from Hub (%s) — using local", exc)
62
+
63
+ # Read local file (may have been just downloaded, or pre-existing from last session)
64
+ entries: list[dict] = []
65
+ if LOCAL_PATH.exists():
66
+ with open(LOCAL_PATH, encoding="utf-8") as f:
67
+ for line in f:
68
+ line = line.strip()
69
+ if line:
70
+ try:
71
+ entries.append(json.loads(line))
72
+ except json.JSONDecodeError:
73
+ pass
74
+
75
+ with self._lock:
76
+ self._entries = entries
77
+
78
+ logger.info("MemoryManager: %d vocabulary entries loaded", len(entries))
79
+
80
+ # ── Read ──────────────────────────────────────────────────────────────────
81
+
82
+ def get_recent(self, n: int = 5) -> list[dict]:
83
+ with self._lock:
84
+ return list(self._entries[-n:])
85
+
86
+ def get_all(self) -> list[dict]:
87
+ with self._lock:
88
+ return list(self._entries)
89
+
90
+ def count(self) -> int:
91
+ with self._lock:
92
+ return len(self._entries)
93
+
94
+ def get_vocabulary_context(self, max_entries: int = 150) -> str:
95
+ """Format vocabulary as a compact string for the LLM system prompt."""
96
+ with self._lock:
97
+ recent = self._entries[-max_entries:]
98
+ if not recent:
99
+ return "(no vocabulary learned yet)"
100
+ lines = []
101
+ for e in recent:
102
+ lang = e.get("language", "?")
103
+ word = e.get("word", "")
104
+ tr = e.get("translation", "")
105
+ tr_l = e.get("translation_language", "en")
106
+ lines.append(f" [{lang}] {word} = {tr} ({tr_l})")
107
+ return "\n".join(lines)
108
+
109
+ # ── Write ─────────────────────────────────────────────────────────────────
110
+
111
+ def add_word_pair(
112
+ self,
113
+ word: str,
114
+ language: str,
115
+ translation: str,
116
+ translation_language: str = "en",
117
+ source: str = "user_taught",
118
+ ) -> dict:
119
+ """
120
+ Append a word pair to local JSONL and push to HF Hub.
121
+ Returns the new entry dict.
122
+ """
123
+ entry = {
124
+ "timestamp": datetime.now(timezone.utc).isoformat(),
125
+ "word": word.strip(),
126
+ "language": language,
127
+ "translation": translation.strip(),
128
+ "translation_language": translation_language,
129
+ "source": source,
130
+ }
131
+
132
+ with self._lock:
133
+ self._entries.append(entry)
134
+ with open(LOCAL_PATH, "a", encoding="utf-8") as f:
135
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
136
+
137
+ # Push to Hub in background so UI is not blocked
138
+ threading.Thread(target=self._push_to_hub, daemon=True).start()
139
+
140
+ logger.info("MemoryManager: added [%s] %s = %s", language, word, translation)
141
+ return entry
142
+
143
+ def _push_to_hub(self) -> None:
144
+ """Upload the full vocabulary.jsonl to HF Hub."""
145
+ if not (self.hf_token and self.repo_id):
146
+ return
147
+ try:
148
+ from huggingface_hub import HfApi
149
+ api = HfApi(token=self.hf_token)
150
+ api.upload_file(
151
+ path_or_fileobj=str(LOCAL_PATH),
152
+ path_in_repo=HUB_FILENAME,
153
+ repo_id=self.repo_id,
154
+ repo_type="dataset",
155
+ )
156
+ logger.info("MemoryManager: pushed vocabulary to Hub")
157
+ except Exception as exc:
158
+ logger.warning("MemoryManager: Hub push failed: %s", exc)