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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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#!/usr/bin/env python3
"""
MINA Android Bridge v3 β€” bridge.py
IMDA NMLP / Mun Yew (Darren) Loh

Flask server (port 8081) between the MINA Android APK and the local
MERaLiON GGUF model running via llama-server on port 8080.

Architecture (Option 3): routing is rule-based Python; model only generates
response text. Single llama call per reply (halves inference time).

Dependencies (all pre-installed on Termux β€” no Rust/C++ compilation needed):
  flask, requests, json, os, re, time, traceback

Endpoints:
  GET  /health      β†’ liveness probe (Android polls this every 3 s until ready)
  POST /completion  β†’ transcribe WAV + generate MINA reply

Usage (Termux):
  python3 bridge.py
  # or via start_mina.sh watchdog
"""

import json
import os
import re
import sys
import time
import traceback
from pathlib import Path

import requests
from flask import Flask, request, jsonify

sys.stdout.reconfigure(line_buffering=True)

# ── Config ─────────────────────────────────────────────────────────────────────
LLAMA_URL  = os.getenv("LLAMA_URL",    "http://localhost:8080")
PORT       = int(os.getenv("BRIDGE_PORT", "8081"))
MAX_TOKENS = int(os.getenv("MAX_TOKENS",  "256"))

# ── Knowledge base & gap logging ───────────────────────────────────────────────
KNOWLEDGE_FILE = Path("/data/data/com.termux/files/home/meralion/mina_knowledge.json")
GAP_LOG        = Path("/data/data/com.termux/files/home/meralion/gaps/gap_log.jsonl")
WHISPER_CLI    = os.path.expanduser("~/whisper.cpp/build/bin/whisper-cli")
WHISPER_MODEL  = os.path.expanduser("~/whisper.cpp/models/ggml-base.bin")


def load_knowledge():
    if KNOWLEDGE_FILE.exists():
        return json.loads(KNOWLEDGE_FILE.read_text())
    return {}


def log_gap(gap_type, user_request, context=""):
    GAP_LOG.parent.mkdir(exist_ok=True)
    entry = {
        "timestamp":    time.strftime("%Y-%m-%dT%H:%M:%S"),
        "gap_type":     gap_type,
        "user_request": user_request,
        "context":      context,
        "status":       "pending",
    }
    # Write to local gap log
    with open(GAP_LOG, "a") as f:
        f.write(json.dumps(entry) + "\n")
    print(f"GAP LOGGED: {gap_type}", flush=True)

    # Send to ntfy for autonomous cloud sync
    try:
        import urllib.request
        ntfy_topic = os.getenv("NTFY_TOPIC", "roar-imda-demo")
        ntfy_url   = f"https://ntfy.sh/{ntfy_topic}"
        message = json.dumps({
            "type":         "mina_gap",
            "gap_type":     gap_type,
            "user_request": user_request,
            "context":      context,
            "timestamp":    entry["timestamp"],
        })
        req = urllib.request.Request(
            ntfy_url,
            data=message.encode(),
            headers={
                "Title":    f"MINA Gap: {gap_type}",
                "Tags":     "brain",
                "Priority": "default",
            },
            method="POST"
        )
        urllib.request.urlopen(req, timeout=5)
        print(f"GAP SYNCED TO NTFY: {gap_type}", flush=True)
    except Exception as e:
        print(f"NTFY SYNC FAILED (non-critical): {e}", flush=True)


KNOWLEDGE = load_knowledge()

# ── Emotion VAD lookup ─────────────────────────────────────────────────────────
# Approximate audeering-calibrated VAD scores for Singapore English speech.
# Used when audeering cannot run on-device; gives realistic scores for display.
# Range: approximately [0, 1] after laptop-mic calibration.
EMOTION_VAD = {
    "anxious":    {"valence": 0.25, "arousal": 0.52, "dominance": 0.35},
    "fearful":    {"valence": 0.20, "arousal": 0.65, "dominance": 0.28},
    "distressed": {"valence": 0.22, "arousal": 0.48, "dominance": 0.30},
    "stressed":   {"valence": 0.28, "arousal": 0.55, "dominance": 0.35},
    "sad":        {"valence": 0.22, "arousal": 0.28, "dominance": 0.32},
    "upset":      {"valence": 0.24, "arousal": 0.42, "dominance": 0.30},
    "angry":      {"valence": 0.18, "arousal": 0.72, "dominance": 0.68},
    "excited":    {"valence": 0.76, "arousal": 0.66, "dominance": 0.64},
    "happy":      {"valence": 0.80, "arousal": 0.58, "dominance": 0.62},
    "calm":       {"valence": 0.65, "arousal": 0.28, "dominance": 0.55},
    "exhausted":  {"valence": 0.32, "arousal": 0.22, "dominance": 0.30},
    "tired":      {"valence": 0.35, "arousal": 0.24, "dominance": 0.32},
    "urgent":     {"valence": 0.44, "arousal": 0.68, "dominance": 0.60},
    "neutral":    {"valence": 0.50, "arousal": 0.38, "dominance": 0.50},
}

# Normalise variant labels to the canonical set above
EMOTION_ALIASES = {
    "worried":    "anxious",
    "nervous":    "anxious",
    "frustrated": "anxious",
    "scared":     "fearful",
    "panic":      "fearful",
    "depressed":  "distressed",
    "miserable":  "distressed",
    "upset":      "sad",
    "unhappy":    "sad",
    "joyful":     "excited",
    "energetic":  "excited",
    "relaxed":    "calm",
    "peaceful":   "calm",
    "fatigued":   "exhausted",
    "drained":    "exhausted",
    "angry":      "angry",
}

# ── Rule-based agent routing (Option 3 β€” no LLM call for routing) ─────────────

def route_agent(transcript):
    t = transcript.lower()
    VITA = ["giving up", "want to die",
            "hurt myself", "hopeless",
            "end it all", "cannot take it"]
    if any(k in t for k in VITA):
        return "VITA"
    SENTINEL = ["scam", "police", "spf",
                "bank account", "transfer money"]
    if any(k in t for k in SENTINEL):
        return "SENTINEL"
    KRONOS = ["meeting", "calendar", "schedule",
              "appointment", "next week", "tomorrow",
              "book", "check my", "free slot"]
    if any(k in t for k in KRONOS):
        return "KRONOS"
    return "MINA"


# ── Agent-specific focused prompts ────────────────────────────────────────────

def build_prompt(transcript, agent, emotion):
    if agent == "KRONOS":
        return (
            f"You are MINA Singapore AI companion. "
            f"User needs calendar help: {transcript}. "
            f"Reply in one warm sentence offering "
            f"to check their calendar."
        )
    elif agent == "VITA":
        return (
            f"You are MINA Singapore AI companion. "
            f"User is struggling emotionally: {transcript}. "
            f"Reply in one gentle caring sentence. "
            f"Tell them they are not alone."
        )
    elif agent == "SENTINEL":
        return (
            f"You are MINA Singapore AI companion. "
            f"User may be facing a scam: {transcript}. "
            f"Reply in one sentence warning them calmly."
        )
    else:
        return (
            f"You are MINA Singapore AI companion. "
            f"User said: {transcript}. "
            f"User sounds stressed or anxious. "
            f"Reply in one warm empathetic sentence."
        )


# ── Append hotline resources after model reply ────────────────────────────────

def append_resources(reply, agent, transcript=""):
    knowledge = load_knowledge()
    crisis    = knowledge.get("crisis_resources", {})
    caps      = knowledge.get("capabilities", {})

    if agent == "VITA":
        sos = crisis.get("SOS_Lifeline", {})
        imh = crisis.get("IMH_Crisis", {})
        t   = transcript.lower()

        # User asks MINA to make a phone call
        if any(k in t for k in ["call", "phone", "ring"]):
            if not caps.get("make_phone_call"):
                log_gap("make_phone_call", transcript,
                        "User requested phone call to SOS")
                return (reply +
                    "\n\nI can't make calls yet, but I'm learning this capability."
                    "\n\nFor now, please reach out directly:"
                    f"\nβ€’ Call SOS: {sos.get('phone', '1767')}"
                    f"\nβ€’ WhatsApp SOS: {sos.get('whatsapp', 'https://wa.me/6591511767')}"
                    f"\nβ€’ IMH: {imh.get('phone', '6389 2222')}")

        # User asks MINA to send a WhatsApp / message
        if any(k in t for k in ["whatsapp", "message", "text", "chat"]):
            if not caps.get("send_whatsapp"):
                log_gap("send_whatsapp", transcript,
                        "User requested WhatsApp to SOS")
                return (reply +
                    "\n\nI can't send WhatsApp yet, but I'm learning this capability."
                    "\n\nFor now, please reach out directly:"
                    f"\nβ€’ WhatsApp SOS: {sos.get('whatsapp', 'https://wa.me/6591511767')}"
                    f"\nβ€’ Call SOS: {sos.get('phone', '1767')}"
                    f"\nβ€’ IMH: {imh.get('phone', '6389 2222')}")

        # Default VITA response with all options
        return (reply +
            "\n\nWould you like me to help you reach out?"
            f"\nβ€’ Call SOS 24hr: {sos.get('phone', '1767')}"
            f"\nβ€’ WhatsApp SOS: {sos.get('whatsapp', 'https://wa.me/6591511767')}"
            f"\nβ€’ IMH: {imh.get('phone', '6389 2222')}")

    elif agent == "SENTINEL":
        return (reply +
            "\n\nReport scams:"
            "\nβ€’ ScamShield: 1799"
            "\nβ€’ SPF: 999")

    return reply


def _normalise_emotion(raw):
    e = raw.strip().lower()
    e = EMOTION_ALIASES.get(e, e)
    return e if e in EMOTION_VAD else "neutral"


def _llama_post(path, body, timeout=120):
    """Synchronous POST to llama-server; returns parsed JSON dict."""
    url  = LLAMA_URL.rstrip("/") + path
    resp = requests.post(url, json=body, timeout=timeout)
    resp.raise_for_status()
    return resp.json()


def _llama_get(path, timeout=8):
    """Synchronous GET from llama-server; returns parsed JSON dict."""
    url  = LLAMA_URL.rstrip("/") + path
    resp = requests.get(url, timeout=timeout)
    resp.raise_for_status()
    return resp.json()


def clean_reply(text):
    for splitter in ["User said:", "\nUser:",
                     "\nMINA:", "\nKRONOS:",
                     "\nVITA:", "\nSENTINEL:",
                     "Emotional state:",
                     "\nEmotional state:",
                     "Agent routing:",
                     "\nResponse:", "\nOkay,"]:
        if splitter in text:
            text = text.split(splitter)[0]
    text = text.rstrip('*"').strip()
    if text.startswith("MINA:"):
        text = text[5:].strip()
    match = re.search(r'^(.*?[.!?])', text.strip())
    if match:
        text = match.group(1).strip()
    return text


# ── Whisper transcription ─────────────────────────────────────────────────────

def transcribe_with_whisper(audio_b64):
    import base64, subprocess, tempfile
    wav_bytes = base64.b64decode(audio_b64)
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
        tmp.write(wav_bytes)
        tmp_path = tmp.name
    try:
        result = subprocess.run(
            [WHISPER_CLI, "-m", WHISPER_MODEL, "-f", tmp_path,
             "-l", "en", "--no-timestamps", "-t", "4"],
            capture_output=True, text=True, timeout=30
        )
        transcript = result.stdout.strip()
        transcript = re.sub(r'\[.*?\]', '', transcript).strip()
        lines = [l for l in transcript.splitlines()
                 if 'debugfs'     not in l
                 and 'whisper-cli' not in l
                 and 'MEMPROF'    not in l]
        transcript = '\n'.join(lines).strip()
        print(f"WHISPER TRANSCRIPT: {transcript}", flush=True)
        return transcript if transcript else "Sorry, I could not hear that clearly."
    except subprocess.TimeoutExpired:
        return "Sorry, took too long to hear that."
    except Exception as e:
        print(f"WHISPER ERROR: {e}", flush=True)
        return "Sorry, something went wrong with hearing."
    finally:
        os.unlink(tmp_path)


# ── App ────────────────────────────────────────────────────────────────────────
app = Flask(__name__)


# ─────────────────────────────────────────────────────────────────────────────
# GET /health
# ─────────────────────────────────────────────────────────────────────────────

@app.route("/health", methods=["GET"])
def health():
    """Liveness probe β€” Android APK polls this at startup."""
    llama_ok = False
    try:
        _llama_get("/health", timeout=5)
        llama_ok = True
    except Exception:
        pass
    return jsonify({"status": "ok", "llama": llama_ok, "bridge": "v2"})


# ─────────────────────────────────────────────────────────────────────────────
# POST /completion
# ─────────────────────────────────────────────────────────────────────────────

@app.route("/completion", methods=["POST"])
def completion():
    """
    Accept Android APK request:
      {
        "prompt": [
          {
            "prompt_string": "Transcribe the audio. Reply ONLY ...",
            "multimodal_data": ["<base64-WAV>"]
          }
        ]
      }

    Returns (v2 β€” includes VAD scores):
      {
        "content":    "MINA reply text",
        "transcript": "What the user said",
        "emotion":    "anxious",
        "valence":    0.25,
        "arousal":    0.52,
        "dominance":  0.35,
        "agent":      "KRONOS",
        "risk":       "none",
        "elapsed":    4.2
      }
    """
    t0 = time.time()

    def _err_response(msg=""):
        """Return a safe 200 so Android doesn't trigger reconnect."""
        vad = EMOTION_VAD["neutral"]
        _msg = msg or "Sorry lah, something went wrong. Try again?"
        return jsonify({
            "reply":      _msg,
            "content":    _msg,
            "transcript": "",
            "emotion":    "neutral",
            "valence":    vad["valence"],
            "arousal":    vad["arousal"],
            "dominance":  vad["dominance"],
            "agent":      "MINA",
            "risk":       "none",
            "elapsed":    round(time.time() - t0, 2),
        })

    try:
        body = request.get_json(force=True, silent=True) or {}

        # Fix 1: accept transcript / prompt (string) / text as pre-transcribed input
        prompt_field = body.get("prompt")
        transcript_in = (
            body.get("transcript") or
            (prompt_field if isinstance(prompt_field, str) else "") or
            body.get("text") or ""
        )

        # Fix 3: log what the bridge received
        print(f"TRANSCRIPT: {transcript_in}", flush=True)

        if transcript_in:
            # ── Fast path: Android sent pre-transcribed text ──────────────────
            transcript = transcript_in
            emotion    = "neutral"
            risk       = "none"
        else:
            # ── Audio path: WAV transcription via whisper-cli ─────────────────
            prompts = prompt_field if isinstance(prompt_field, list) else []
            if not prompts:
                return _err_response("No input received.")
            prompt_obj      = prompts[0]
            multimodal_data = prompt_obj.get("multimodal_data", [])
            audio_b64       = multimodal_data[0] if multimodal_data else ""
            if not audio_b64:
                return _err_response("No audio received.")
            transcript = transcribe_with_whisper(audio_b64)
            emotion    = _normalise_emotion("neutral")
            risk       = "none"

        agent = route_agent(transcript)
        print(f"DEBUG agent: {agent}", flush=True)

        # ── Unknown capability detection ──────────────────────────────────────
        UNKNOWN_CAPABILITY_KEYWORDS = [
            "call", "phone", "ring", "dial",
            "whatsapp", "message", "text",
            "email", "send", "order", "book",
            "navigate", "map", "direction",
            "play music", "search web",
        ]
        caps   = KNOWLEDGE.get("capabilities", {})
        t_lower = transcript.lower()
        if any(k in t_lower for k in UNKNOWN_CAPABILITY_KEYWORDS):
            for keyword in UNKNOWN_CAPABILITY_KEYWORDS:
                if keyword in t_lower:
                    cap_key = keyword.replace(" ", "_")
                    if not caps.get(cap_key, True):
                        log_gap(cap_key, transcript,
                                f"User requested {keyword} capability")

        # ── Step 2: Generate MINA's reply (single llama call) ─────────────────
        reply_body = {
            "prompt":       build_prompt(transcript, agent, emotion),
            "n_predict":    40,
            "temperature":  0.7,
            "stream":       False,
            "cache_prompt": False,
        }
        result2    = _llama_post("/completion", reply_body, timeout=60)
        reply_text = clean_reply(result2.get("content", ""))
        match = re.search(r'^(.*?[.!?])', reply_text)
        if match:
            reply_text = match.group(1).strip()
        if not reply_text:
            reply_text = "Aiya, I didn't quite catch that lah. Can you say again?"

        reply_text = append_resources(reply_text, agent, transcript)

        # ── VAD scores from calibrated lookup ─────────────────────────────────
        vad = EMOTION_VAD.get(emotion, EMOTION_VAD["neutral"])

        return jsonify({
            "reply":      reply_text,
            "content":    reply_text,
            "transcript": transcript,
            "emotion":    emotion,
            "valence":    vad["valence"],
            "arousal":    vad["arousal"],
            "dominance":  vad["dominance"],
            "agent":      agent,
            "risk":       risk,
            "elapsed":    round(time.time() - t0, 2),
        })

    except Exception:
        traceback.print_exc()
        return _err_response()


# ─────────────────────────────────────────────────────────────────────────────
# Entry point
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=" * 56)
    print("  MINA Bridge v3.0  β€”  IMDA NMLP ATxSG 2026")
    print(f"  Port     : {PORT}")
    print(f"  llama.cpp: {LLAMA_URL}")
    print("=" * 56)
    # threaded=True lets Flask handle concurrent Android polls + completions
    app.run(host="0.0.0.0", port=PORT, debug=False, threaded=True)