Metadata-Version: 2.4
Name: clypso-chat
Version: 0.1.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Rust
Classifier: Topic :: Communications :: Chat
Classifier: Typing :: Typed
Requires-Dist: pytest>=8 ; extra == 'test'
Requires-Dist: numpy>=1.26 ; extra == 'test'
Provides-Extra: test
License-File: LICENSE
Summary: Clypso's live-chat readers (Twitch, Kick, YouTube) and spike detector, in Rust, for Python
Keywords: twitch,kick,youtube,live-chat,spike-detection,rust
Author: Abdullahmahi
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Issues, https://github.com/mr-Imran/clypso_chat/issues
Project-URL: Repository, https://github.com/mr-Imran/clypso_chat

# clypso_chat

Clypso's live-chat readers (Twitch, Kick, YouTube) and spike detector, written in Rust, used from Python.

It replaces the chat part of the engine (`live.py`: `twitch_chat`, `kick_chat`, `youtube_chat`, the parsers, `spike`,
`chat_quiet`, `loud_spike` and `Stream.tick`). It gives the **same answers** as that Python code, checked on thousands of
cases, and does the work with a fraction of the CPU, outside Python's GIL.

## What's inside

| Piece | What it does | Replaces in live.py |
|---|---|---|
| `spike`, `chat_quiet`, `loud_spike` | the spike and loudness detectors, numpy's arithmetic reproduced step for step | the same names |
| `twitch_line`, `kick_item`, `youtube_item` | one platform message → (author, text, time) | the same names |
| `Counter` | messages per second, closed seconds, the detector with its cooldown | `Stream.add_chat` counting + `Stream.tick` |
| `Hub` | every channel's chat reader on one small runtime: connects, parses, answers pings, reconnects, logs | the three reader threads |
| `Hub.events`, `twitch_event`, `kick_event`, `youtube_event` | subs, gift bombs, bits, raids and Kick hosts, Super Chats, memberships | new: live.py drops these |
| `signals`, `compact`, `norm` | per second: chatters, reaction messages, repeats; one line per reaction for an AI prompt | new |
| `clypso_chat.engine` | puts all of the above into a running `live.py`, with its Python code as the fallback | — |

## Measured (this laptop, 4 CPUs, Python 3.15; `python bench/bench.py`)

| | Python (live.py) | Rust | Faster |
|---|---|---|---|
| Twitch parsing, 200k lines | 0.79 s | 0.10 s | 7.6× |
| Kick parsing, 100k events | 0.61 s | 0.15 s | 4.0× |
| YouTube parsing, 50k actions | 0.34 s | 0.26 s | 1.3× |
| `spike()` per call (660 s of rates) | 178 µs | 30 µs | 6.0× |
| `loud_spike()` per call | 168 µs | 20 µs | 8.3× |
| one stream's hour at 50 msg/s (count + tick) | 0.48 s | 0.04 s | 11.3× |
| 1,000,000 Twitch messages (real-sized tags) over 40 streams, hub + engine pump into Streams | 14.9 s CPU | 2.58 s CPU | 5.8× |
| the same, counting and spikes in the hub | 14.9 s CPU | 1.03 s CPU | 14.5× |

Run against the real services (`bench/smoke.py`): Twitch read live chat over TLS, Kick's Pusher socket connected and
subscribed, YouTube read 77 messages in 30 s from a live stream.

How much CPU it uses: one OS thread for every channel (`threads=1`, more if asked) plus up to two short-lived helper
threads. On Clypso's real channels (7 streams, ~8 messages a second) the hub and the engine's pump together use about
0.1% of one core, almost all of it fixed cost (connections, YouTube's polling, the pump's wake-ups), not messages.

Where the CPU goes, and what keeps it low:
- Twitch: a line's ~330 bytes of tags are scanned with SIMD (`memchr`), ASCII byte by byte otherwise; only a non-ASCII
  character is decoded. Python's `\s`/`\w` rules are kept exactly (checked by the parity tests and a fuzzer).
- Kick: only `content`, `created_at` and `sender.username` are read out of each message, borrowed from the JSON text;
  badges, identity and metadata are skipped without being built. Any odd shape goes the general way, as before.
- The engine: `Hub.take` does `Stream.add_chat`'s work in Rust (numbering, the stored tuples, per-second counts), so
  each stream's new lines go in with one `deque.extend` under one lock. It is used only while live.py's `add_chat` reads
  word for word as expected; otherwise lines go through `add_chat` one at a time. The engine's hub doesn't count
  messages itself (`Hub(count=False)`): live.py's `Stream.tick` does.

## Install

Each release has one wheel per platform, good for every CPython ≥ 3.10 (the stable ABI, `abi3`):

| Platform | Wheel | Tested |
|---|---|---|
| Linux x86-64 (glibc ≥ 2.17, manylinux2014) | `manylinux_2_17_x86_64` | yes: the full test suite in CI and locally on CPython 3.10–3.15 |
| Linux ARM64 (glibc ≥ 2.28) | `manylinux_2_28_aarch64` | built only (cross-compiled) |
| macOS Apple Silicon | `macosx_11_0_arm64` | yes: the full test suite in CI |
| macOS Intel | `macosx_10_12_x86_64` | built only (cross-compiled) |
| Windows x86-64 | `win_amd64` | yes: the full test suite in CI |

```bash
pip install clypso_chat-0.1.0-<platform>.whl     # from the release's files (GitHub Actions → the release run → wheels)
pip install clypso-chat                           # once it is published to PyPI
```

Anywhere else (Alpine/musl, Windows ARM, other CPUs) pip falls back to the source distribution, which needs Rust
(`rustup`, stable) and a C compiler. To build a wheel yourself:

```bash
pip install maturin
maturin build --release -o dist          # → dist/clypso_chat-0.1.0-cp310-abi3-<this platform>.whl
pip install dist/clypso_chat-*.whl
```

A wheel built on a desktop Linux is tagged with that machine's glibc (e.g. `manylinux_2_34`) and won't install on older
systems; the release wheels are built in the manylinux2014 container (2_28 for ARM64) for that reason. Nothing to link at run time: TLS
is rustls with the ring provider and Mozilla's roots, no OpenSSL.

## Use

```python
import clypso_chat as cc

cc.spike(rates, L)                 # same as live.spike(rates, L)
cc.twitch_line(line)               # same as live.twitch_line(line)

with cc.Hub(L) as hub:             # L: live.py's [live] settings (defaults are Clypso's)
    hub.join("xqc", "twitch", "xqc")
    hub.join("adin", "kick", "adinross", room=875062)     # pass the chatroom id: see "Kick" below
    hub.join("speed", "youtube", "<live video id>")
    lines = hub.drain("xqc")       # [(author, text, epoch), ...] since the last drain
    moment = hub.tick("xqc")       # Stream.tick on the hub's own counts → the moment, or None
    hub.status("xqc")              # {connected, received, reconnects, last_error, events, ...}
    hub.logs()                     # ["adin kick chat dropped: ...", ...] for your own log
    hub.events("xqc")              # [{kind, user, amount, detail, text, ts}, ...] subs, gifts, bits, raids, Super Chats

cc.signals(chat)                   # [(second, messages, chatters, reaction messages, repeats), ...]
cc.compact(chat, max=160)          # [(author, text, ts, times said, people), ...]: a wall of 40 "KEKW" is one line
```

`chat` is `(author, text, ts)` tuples, or live.py's `Stream.chat` as it is (`(seq, ts, author, text)`).

### Events

| kind | Twitch | Kick | YouTube | amount |
|---|---|---|---|---|
| `sub` | sub, resub (`detail`: plan) | SubscriptionEvent | — | months |
| `gift` | a gift bomb (its single gifts aren't counted again), one gifted sub | GiftedSubscriptionsEvent | gifted memberships | subs |
| `bits` | a cheer (it is a chat line too, as before) | — | — | bits |
| `raid` | raid | StreamHostEvent | — | viewers |
| `superchat` | — | — | Super Chat, Super Sticker (`detail`: "$5.00") | the number in its currency |
| `member` | — | — | new or returning member | months |

Twitch's reader asks for `twitch.tv/commands` too (that's where these come from) and reconnects when Twitch says
`RECONNECT`. Kick's event names and fields are the ones kick.com's own page reads; they are not a documented API.

### Signals

`signals` counts, per second: messages; different chatters; messages with a reaction (`KEYWORDS`: "clip it", "KEKW",
"LUL", "W", "no way", "💀"... or your own list); and repeats, a line someone said in the last 30 s (emote walls,
copypasta). Lines are compared by `norm`: lower case, punctuation off, "LMAOOO" → "lmao", "KEKW KEKW KEKW" → "kekw".
`compact` folds a stretch down to one line per reaction in the order first said; over `max` it keeps the most repeated
(up to half) and an even spread of the rest.

Type hints are in `python/clypso_chat/_native.pyi`.

## Putting it into the engine

In `live.py`, after the readers and detectors are defined, before the engine starts:

```python
try:
    import clypso_chat.engine
    clypso_chat.engine.install(sys.modules[__name__])
except ImportError:              # no wheel on this machine: live.py's own Python readers run, as before
    pass
```

- `[live] rust_chat = false` in config.toml turns it off.
- Readers: `twitch_chat`, `kick_chat` and `youtube_chat` start a Rust reader and return. One `clypso-chat-pump` thread
  moves new lines into each `Stream` every 0.2 s (`Hub.take`: `add_chat`'s work for the whole batch, under one lock) and
  log lines into `live.log`. A reader stops when its stream goes
  offline or a newer reader takes over (`st.gen`), exactly when live.py's own thread would.
- Detectors and parsers: swapped for the Rust ones.
- Events: subs, gifts, bits, raids and Super Chats go into `Stream.events` (a deque of the last 500 dicts); a raid is
  also logged ("xqc raided by Raider with 900 viewers"). Nothing in live.py decides on them yet.
- Nothing else changes: `Stream`, its chat deque, the dashboard and the analyzer read the same fields as before.

This is the "engine pump" row in the table (5.8×). The next step, letting `Stream.tick` read the hub's counts
(`hub.tick`) instead of counting in Python, is the 14.5× row; it touches more of live.py, so it's left for its own change.
At Clypso's real chat rates either way is about 0.1% of a core.

In the engine's Dockerfile, a build stage makes the wheel and the engine image installs it:

```dockerfile
FROM ubuntu:26.04 AS chat
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates build-essential python3 python3-venv
RUN curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
COPY clypso_chat /src
RUN python3 -m venv /v && /v/bin/pip install maturin && cd /src && PATH=/root/.cargo/bin:$PATH /v/bin/maturin build --release -o /wheels

FROM ubuntu:26.04
# ... the engine's existing steps ...
COPY --from=chat /wheels /wheels
RUN .venv/bin/pip install /wheels/*.whl
```

## Kick

kick.com's channel API answers Rust's HTTP client with a Cloudflare 403 while Python's urllib gets through (Cloudflare
tells the TLS clients apart). So pass `room=` when you know it. `clypso_chat.engine` does: it asks `live.kick_room` (urllib,
with live.py's cache) first and hands the room over. Without a room the hub tries kick.com itself and retries.
The Pusher chat socket itself works from Rust. When Pusher answers 4001 or 4003 (kick.com moved to a new public key), the
log line says to set `[live] kick_pusher_key`.

A Kick or YouTube reader that keeps failing waits longer each time: 10 s, 20 s, 40 s ... up to 5 minutes, back to 10 s
after a connection that lasted a minute. A block or rate limit isn't hit again every 10 s.

## Where it differs from live.py, on purpose

- A message whose YouTube `timestampUsec` isn't a number is skipped. live.py raises, drops the connection and reconnects.
- A Kick time without a timezone is taken as "when it arrived". live.py reads it as the machine's local time.
- After Twitch or Kick closes the connection cleanly, the reader waits 1 s before reconnecting. live.py reconnects at once.
- Kick and YouTube readers back off after repeated failures (see Kick above); live.py retries every 10 s.
- A Twitch line's time is when it arrived, as in live.py (`add_chat` with no time).
- A Kick username that isn't text (never seen from Kick) comes back as text; live.py passes the raw JSON value on.

## Tests

```bash
cargo test                                 # Rust only, no Python needed
maturin develop --release && pytest        # 95 tests
python tests/make_reference.py ../REA/clipping/live.py   # refresh the copy of live.py the parity tests hold it to
```

- `tests/test_parity.py`: Rust against `tests/reference.py`, live.py's own functions copied word for word by
  `make_reference.py`. Thousands of random chats and sounds under several configs, a corpus of real and odd messages,
  random text with Python-only whitespace and non-Latin letters, and Counter against `Stream.tick` second by second. Every
  answer, and its type, must be the same.
- `tests/test_network.py`: the hub against local fakes of Twitch IRC, Kick's Pusher socket and channel API, and YouTube's
  chat feed: handshakes, parsing, pings, reconnects, errors in the log, leave/rejoin, overflow, a spike played in.
- `tests/test_events.py`: subs, gift bombs, bits, raids, Kick hosts and Super Chats through each reader; signals, compact.
- `tests/test_engine.py`: `clypso_chat.engine` against a stand-in live.py built on its real `Stream` code.
- `bench/bench.py`: the numbers above. `bench/smoke.py`: a few seconds of real chat.

## Releasing

`.github/workflows/ci.yml` runs on every push and pull request: `cargo test`, then the Python suite on Linux, macOS and
Windows against a freshly built wheel, then every release wheel and the source distribution. To release:

1. Bump `version` in `Cargo.toml` and `pyproject.toml` (they must match), commit, and merge to `main`.
2. Tag it: `git tag v0.1.1 && git push origin v0.1.1`. The tag's run builds everything, checks the tag matches the
   version, attaches the files to a GitHub Release and publishes them to PyPI.
3. To try a release first, run the workflow by hand (Actions → CI → Run workflow) with `testpypi`: it publishes the
   same files to TestPyPI.

Publishing uses PyPI's Trusted Publishing, so the repository holds no tokens. Once, before the first release: on
pypi.org (and test.pypi.org) add a "pending publisher" for project `clypso-chat`, owner `mr-Imran`, repository
`clypso_chat`, workflow `ci.yml`, environment `pypi` (`testpypi`), and create those two environments in the GitHub
repository's settings.

## Layout

```
src/detect.rs     spike, chat_quiet, loud_spike, Counter (numpy's arithmetic)
src/parse.rs      twitch_line, kick_item, youtube_item
src/events.rs     subs, gifts, bits, raids, Super Chats: twitch_event, kick_event, youtube_event
src/signals.rs    norm, signals, compact
src/net/          twitch.rs, kick.rs, youtube.rs: the readers; mod.rs: TLS, endpoints, HTTP, backoff
src/hub.rs        the Hub: feeds, runtime, drain, take, events, tick, status, logs
src/py.rs         the Python module (feature "python", turned on by maturin)
python/clypso_chat/   __init__.py, engine.py (the live.py adapter), _native.pyi
tests/            parity, network and engine tests, fakes, the live.py reference copy
bench/            bench.py, smoke.py
.github/workflows/ci.yml   tests on three systems, the wheels, the release
```

