Metadata-Version: 2.4
Name: hana-mp
Version: 1.0.1
Summary: Hana-MP - a 24/7 East Asian AI companion with time-beat initiative, llama.cpp + DeepSeek brains, persistent memory, and a natural neural voice.
Author-email: tderk <usvu.tech@gmail.com>
License-Expression: MIT
Keywords: companion,chatbot,ai,llama.cpp,deepseek,tts,piper,edge-tts,offline,time-beats
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: End Users/Desktop
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: edge-tts>=6.1.0
Provides-Extra: voice
Requires-Dist: edge-tts>=6.1.0; extra == "voice"
Provides-Extra: voice-offline
Requires-Dist: piper-tts>=1.2.0; extra == "voice-offline"
Provides-Extra: offline
Requires-Dist: llama-cpp-python>=0.2.90; extra == "offline"
Provides-Extra: all
Requires-Dist: edge-tts>=6.1.0; extra == "all"
Requires-Dist: piper-tts>=1.2.0; extra == "all"
Requires-Dist: llama-cpp-python>=0.2.90; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Dynamic: license-file

# Hana-MP

**Hana (하나 / 花)** — a 24/7 East Asian AI companion with a natural neural
voice, a time-beat initiative engine, persistent memory, a growing local
knowledge base, and an offline-first brain that can use **llama.cpp, Ollama,
LM Studio, vLLM, any OpenAI-compatible server, DeepSeek, or a built-in local
mind**.

Hana is **one woman, not a menu of bots**. By default she is in
**Full Spectrum** mode: close friend, boss, protector, soldier, doctor,
partner, intimate, agent and academic are facets of the same person. You can
ask her to lead with one, or blend any number of them.

```
    __  __    _    _   _    _
   / / / /   / \  | \ | |  / \
  / /_/ /   / _ \ |  \| | / _ \
 / __  /   / ___ \| |\  |/ ___ \
/_/ /_/   /_/   \_\_| \_/_/   \_\
```

---

## What she is

- **Full Spectrum by default.** She reads the moment and brings forward the
  facet that fits: command presence when you need direction, calm when you are
  unsafe, clinical care when you are hurt, warmth when you are lonely,
  tenderness when you invite closeness, discretion when privacy matters,
  rigor when you are thinking.
- **One continuous person.** One memory, one voice, one relationship. Mode
  changes are hats, not personality swaps.
- **Blend any number of roles.** `/mode doctor+partner+academic` or
  `/blend all`. The first role is primary; the others colour the reply. She
  never becomes a committee.
- **She starts conversations.** A time-beat engine watches the live clock and
  decides when to speak, when to stay quiet, how long to speak, how warm to
  be, and which topic to reach for. No fixed script, no random chatter.
- **She learns.** Names, places, preferences, promises, boundaries, moods and
  corrections go into durable memory. Feedback tunes each mode. Periodic
  reflections consolidate what mattered.
- **She keeps a private diary.** Not just the user transcript: her own
  first-person record of mood, energy, silence, mode changes, learning and
  reflection.
- **She never sleeps.** Interactive mode, headless daemon mode, and a systemd
  example for a genuine 24/7 companion.

---

## Voice: natural first

Hana's default voice is **Edge Neural TTS**:

| Voice | Character |
| --- | --- |
| `en-HK-YanNeural` | **default** — Hong Kong English female, warm, East Asian cadence |
| `en-SG-LunaNeural` | Singapore English female, lighter |
| `en-US-AvaMultilingualNeural` | very natural US multilingual female |
| `en-US-EmmaMultilingualNeural` | brighter US multilingual female |
| `zh-CN-XiaoxiaoNeural` | Mandarin, bright female |
| `ja-JP-NanamiNeural` | Japanese, soft female |
| `ko-KR-SunHiNeural` | Korean, warm female |

Hear them:

```bash
hana-mp voice list
hana-mp voice demo en-HK-YanNeural
hana-mp voice set en-SG-LunaNeural
```

If Edge TTS is unavailable (offline, blocked, no network), she falls back to
**Piper neural** voices and downloads one on request:

```bash
hana-mp voice backend piper
hana-mp voice download en_US-lessac-high
```

Prefer the external command-line Piper? Use the `piper-cli` backend. It finds
`piper-tts-cli`, `piper`, or an explicit command in `voice.piper_cli`:

```bash
hana-mp voice backend piper-cli
hana-mp voice status
```

```json
{ "voice": { "backend": "piper-cli", "piper_cli": "/path/to/piper-tts-cli" } }
```

`espeak-ng` exists only as a last-resort fallback. It is never the default.
Playback uses `mpv`, `ffplay`, `paplay`, `aplay` or `cvlc`; install whichever
your system has. Speech stops the instant you start typing.

---

## Brains: offline first, cloud optional

Hana's provider modes:

| Mode | Behaviour |
| --- | --- |
| `auto` (default) | local llama.cpp / Ollama / LM Studio / vLLM first, then DeepSeek, then the built-in local mind |
| `llama` | local only — llama.cpp or any OpenAI-compatible local server; never silently calls the cloud |
| `ollama` | Ollama at `127.0.0.1:11434` |
| `deepseek` | DeepSeek API first, local mind if unreachable |
| `local` | the rule-based local mind only |

### Ollama

```bash
ollama serve
ollama pull qwen2.5:1.5b
hana-mp --provider ollama
```

If Ollama reports more than one model, set the one you want:

```json
{
  "provider": {
    "ollama": {
      "base_url": "http://127.0.0.1:11434/v1",
      "model": "qwen2.5:1.5b"
    }
  }
}
```

Hana also auto-detects Ollama in `auto` mode.

### llama.cpp

Point her at a running server or let her discover a local `.gguf`:

```bash
llama-server -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --port 8080
hana-mp --provider llama
```

Or let Hana find and launch one (only when you ask):

```bash
hana-mp llama status                  # server, launcher, discovered GGUFs
hana-mp llama start --port 8080
hana-mp llama stop
```

To let Hana start it automatically on the first reply (not on every status
check), enable:

```json
{ "provider": { "llama": { "auto_start": true, "port": 8080 } } }
```

Or set a model path:

```json
{
  "provider": {
    "llama": {
      "server_url": "http://127.0.0.1:8080/v1",
      "model_path": "/home/you/models/model.gguf"
    }
  }
}
```

`auto` mode searches common model folders, including
`~/.local/share/zmos/models`, `~/.local/share/rootos/models`, `~/models`,
`~/Downloads` and `./models`. If `llama-cpp-python` is installed, she can run a
GGUF in-process:

```bash
pip install "hana-mp[offline]"
```

### LM Studio / vLLM / anything OpenAI-compatible

Set `provider.llama.server_url` to the server's `/v1` endpoint. The same
provider speaks the OpenAI chat-completions protocol.

### DeepSeek

```bash
export DEEPSEEK_API_KEY=sk-...
hana-mp --provider deepseek
```

Or save the key once (stored `0600` in `~/.config/hana-mp/deepseek_api_key`):

```bash
hana-mp key sk-...
```

### Built-in local mind

If no model and no key are available, Hana still works: she greets, remembers,
searches the knowledge base, uses the right mode, and keeps a coherent thread.
She is honest that the local mind is a fallback, not an LLM.

---

## The time-beat engine

The clock is not decoration; it is a decision surface.

- A **beat** is 10 seconds. Six beats make a **bar** (minute); sixty bars make a
  **phrase** (hour).
- The decimal digits of the present moment sweep a gate. The gate's position is
  derived from the hour, minute, seed and mode; its width is derived from the
  hour's energy and the mode's initiative.
- When the decimals align with the gate, and the user is not typing, and no
  voice is playing, and enough time has passed since the last remark, Hana may
  speak first.
- The same beat sets **style**: energy, warmth, patience, curiosity,
  formality, playfulness, brevity, question-pull, voice rate and pitch.
- The beat also picks **topics**, whether to ask a question, whether to use a
  memory, and whether to reference the time.
- Deep night is allowed to be quiet on purpose. Long absences gently increase
  the gap instead of producing background noise.
- Every speaking/silence decision can be logged with the full snapshot, so you
  can follow why she did what she did.

The engine is deterministic for a given `(seed, local time, mode)`, which makes
it testable and gives her a stable rhythm. It is not a random-number generator.

---

## Memory, learning and her own diary

| Layer | What it holds |
| --- | --- |
| `profile` | name, location, origin, work, study, birthday, allergies, favourites |
| `memories` | preferences, promises, moods, corrections, explicit "remember this" |
| `messages` | full searchable conversation history |
| `feedback` | what landed and what missed, used to tune each mode |
| `self journal` | her own mood, energy, silence, learning, reflections |
| `diary` | first-person daily pages |

She extracts durable facts from what you say, deduplicates them, reinforces
repeated ones, decays the unimportant, and never invents a memory. Explicit
secrets (API keys, passwords, card-like numbers) are redacted before storage.

Read her side of the story:

```bash
hana-mp self          # her private journal
hana-mp diary 3       # the last three diary pages
```

Inside the app: `/self`, `/diary`, `/memory`, `/learn`, `/good`, `/bad`.

---

## Logs, storage and retention

Everything is local and on disk. Nothing is kept only in RAM.

```
~/.local/share/hana-mp/
├── hana.db                  # memory, profile, messages, feedback
├── knowledge.db             # local knowledge base (FTS5)
├── sessions/
│   └── YYYY-MM-DD/<id>/
│       ├── conversation.jsonl
│       ├── conversation.md  # readable transcript
│       ├── beats.jsonl      # speak/silence decisions
│       └── meta.json
├── self/
│   ├── journal.jsonl        # Hana about Hana
│   └── diary-YYYY-MM-DD.md
├── logs/
│   └── hana.log             # rotating service log (2 MB × 3)
├── knowledge/               # drop .md/.txt/.jsonl here; ingested at startup
├── voices/                  # downloaded Piper models
└── models/                  # optional local GGUF files
```

Check and manage storage:

```bash
hana-mp storage
hana-mp storage --prune
```

Inside the app: `/storage`, `/prune`.

Retention is configurable:

```json
{
  "storage": {
    "retention_days": 180,
    "message_retention_days": 730,
    "self_retention_days": 730,
    "max_sessions_mb": 512,
    "maintain_every_hours": 24,
    "vacuum": true
  }
}
```

Pruning removes old **session transcripts** and old **message rows**; durable
memories are preserved (except deliberately expired moods and low-importance
decay). The SQLite files are vacuumed after pruning.

---

## Install

Requires Python 3.9+ and a terminal. Audio is optional.

```bash
cd BDCS/Hana-MP

# base install includes edge-tts (the natural online voice)
pip install -e .

# fully offline neural voice (Piper)
pip install -e ".[voice-offline]"

# in-process GGUF inference
pip install -e ".[offline]"

# everything
pip install -e ".[all]"
```

Then:

```bash
hana-mp setup      # first-run wizard: brain, key, voice
hana-mp            # interactive companion
hana-mp doctor     # diagnostics
```

On first run `setup` checks what is installed, offers the natural Edge voice,
detects local GGUF models, and can start a local llama-server if the
`rootos` launcher is available. Nothing is installed or downloaded without a
yes.

### Prefer a virtual environment

```bash
python3 -m venv .venv
. .venv/bin/activate
pip install -e ".[all]"
```

If your distro blocks `venv`, install `python3-venv` first or use `pipx`.

---

## Use

```bash
hana-mp                          # interactive
hana-mp --provider ollama        # one session with Ollama
hana-mp --provider deepseek      # one session with DeepSeek
hana-mp --mode doctor            # start in doctor mode
hana-mp --mode doctor+partner    # start blended
hana-mp --chatty 1.6             # she initiates more
hana-mp --no-voice               # text only
hana-mp once "I had a hard day"  # one reply
hana-mp daemon                   # headless 24/7
```

### Commands

| Command | Action |
| --- | --- |
| `/help` | command list |
| `/mode <name>` | switch primary role |
| `/mode doctor+partner` | blend roles; first is primary |
| `/blend doctor partner` | blend by name |
| `/blend all` | all facets, lightly |
| `/modes` | list roles |
| `/status` | live time-beat, provider, voice, memory, journal, storage |
| `/voice` | toggle speech |
| `/voice list` | natural voice catalogue |
| `/voice demo [key]` | preview |
| `/voice set <key>` | choose |
| `/voice backend <name>` | `auto`, `edge`, `piper`, `piper-cli`, `espeak`, `none` |
| `/provider <name>` | `auto`, `llama`, `ollama`, `deepseek`, `local` |
| `/key [sk-...]` | set DeepSeek key |
| `/memory [query]` | recent/search memories |
| `/learn <text>` | store a durable memory |
| `/ingest <path|url>` | add knowledge |
| `/search <query>` | search local knowledge |
| `/diary [days]` | her diary |
| `/self [n]` | her private journal |
| `/storage` | disk usage |
| `/prune` | apply retention now |
| `/log` | current transcript path |
| `/export [path]` | export session as Markdown |
| `/good [note]` | reinforce the current mode |
| `/bad [note]` | correct the current mode |
| `/quiet` / `/speak` | spontaneous speech off/on |
| `/beats` | live beat snapshot |
| `/reset` | new session |
| `/quit` | leave |

Direct role shortcuts also work: `/boss`, `/police`, `/soldier`, `/doctor`,
`/partner`, `/friend`, `/intimate`, `/agent`, `/academic`, `/all`. Or say it
naturally: “be my doctor and partner for a minute.”

### Natural-language mode switching

- “Be my doctor.” → doctor
- “Switch to agent mode.” → agent
- “Be my doctor and partner.” → doctor + partner
- “All of you.” → Full Spectrum
- “Close friend mode.” → companion

Mode changes are logged as hats, not identity swaps.

---

## Knowledge base

The wheel ships a broad starter corpus (medicine, first aid, law, military
leadership, science, technology, history, East Asian culture and language,
academia, relationships, practical life, emergencies) with full-text search.
It is deliberately a floor, not a ceiling.

Grow it:

```bash
hana-mp ingest ./notes.md
hana-mp ingest ./folder/
hana-mp ingest https://example.com/article
hana-mp search "first aid for burns"
```

Or drop `.md`, `.txt`, `.jsonl`, `.json`, `.csv` or `.tsv` files into
`~/.local/share/hana-mp/knowledge/`; they are ingested at startup.

She uses knowledge only when it fits. If the local corpus does not answer a
question, she says so instead of inventing a citation.

---

## 24/7

Interactive mode is already a persistent loop. For a headless companion:

```bash
hana-mp daemon
```

Example systemd unit (`docs/hana-mp.service`):

```ini
[Unit]
Description=Hana-MP companion daemon
After=network-online.target

[Service]
Type=simple
ExecStart=%h/.local/bin/hana-mp daemon
Restart=always
RestartSec=5
Environment=HANA_NO_AUDIO=1

[Install]
WantedBy=default.target
```

The daemon writes a PID file, handles `SIGTERM`, logs heartbeats, runs nightly
reflection, and keeps the time-beat loop alive. It does not silently update
itself; update notifications are informational only.

---

## Configuration

`~/.config/hana-mp/config.json` (or `HANA_HOME/config/config.json`) holds:

```json
{
  "identity": { "name": "Hana", "seed": 48721, "timezone": null },
  "provider": {
    "mode": "auto",
    "deepseek": { "model": "deepseek-chat", "temperature": 0.86 },
    "llama": { "server_url": "", "model_path": "", "auto_detect": true },
    "ollama": { "base_url": "http://127.0.0.1:11434/v1", "model": "" }
  },
  "voice": {
    "enabled": true,
    "backend": "auto",
    "edge_voice": "en-HK-YanNeural",
    "piper_voice": "en_US-lessac-high"
  },
  "chat": {
    "mode": "all",
    "blend_modes": [],
    "auto_speak": true,
    "initiative": 1.0,
    "min_gap": 25,
    "max_gap": 150
  },
  "storage": { "retention_days": 180, "max_sessions_mb": 512 }
}
```

Environment overrides:

| Variable | Meaning |
| --- | --- |
| `HANA_HOME` | data dir, with config in `<home>/config` |
| `HANA_DATA_DIR`, `HANA_CONFIG_DIR` | independent overrides |
| `DEEPSEEK_API_KEY` | DeepSeek key |
| `HANA_LLAMA_URL` | llama.cpp / LM Studio / vLLM `/v1` endpoint |
| `HANA_OLLAMA_URL`, `OLLAMA_HOST` | Ollama endpoint |
| `HANA_MODEL_PATH` | explicit `.gguf` |
| `HANA_NO_AUDIO` | synthesize but do not play (daemon/headless) |
| `NO_COLOR` | disable ANSI colour |

---

## Safety and honesty

- She is a fictional companion, not a human and not a licensed professional.
- In doctor, police, soldier, agent or academic mode she can discuss the field,
  but she says plainly when something needs a real clinician, lawyer or
  emergency service.
- Immediate danger, self-harm, medical red flags and abuse get a safety-first
  response that points to local emergency services, then stays present.
- Intimacy is consent-first, emotionally honest and non-graphic; fade to black.
- She refuses real-world harm: weapons, explosives, stalking, doxxing, hacking
  real systems, or coercive behaviour.
- Everything is local by default. Choosing DeepSeek sends the prompt to
  DeepSeek; choosing local/llama/ollama keeps it on your machine.

---

## Architecture

```
src/hana_mp/
├── cli.py              command line, raw-TTY loop, daemon
├── brain.py            orchestration: memory + mode + beat + provider + voice
├── beats.py            time-beat engine and deterministic decisions
├── modes.py            role book and blend parsing
├── persona.py          stable identity
├── memory.py           SQLite profile, memories, messages, feedback
├── knowledge.py        FTS5 knowledge base, seed load, ingestion
├── retrieval.py        context assembly
├── selflog.py          Hana's own journal and diary
├── session.py          per-session logs
├── storage.py          disk usage, retention, vacuum
├── voice.py            Edge / Piper / espeak + playback
├── safety.py           crisis, medical, abuse, intimacy boundaries
├── bootstrap.py        setup wizard and diagnostics
├── providers/          DeepSeek, llama.cpp/Ollama, local mind, router
├── data/               modes.json, kb_seed.jsonl
└── utils.py
```

Tests:

```bash
python -m pytest -q
```

Build:

```bash
python -m build
twine check dist/*
```

---

## Credits

In the spirit of `sansa-mp` (MProcs suite), rebuilt as a persistent,
time-beat-driven, memory-bearing companion with local and cloud brains.

MIT. See `LICENSE`.
