ARIA / brain /schema.py
QuerryRaspBerry's picture
inne emotki
ef5a0f7 verified
Raw History Blame Contribute Delete
5.1 kB
"""Event & bubble contracts (Python side). Mirrors aria-worker/src/events.js."""
import json
import re
# Internal event/bubble ids must never leak into visible text.
_ID_LEAK = re.compile(r'["\'โ€žโ€œโ€]?\b(?:evt|sys|bub|ac)_[A-Za-z0-9]+\b["\'โ€žโ€œโ€]?')
# Split a multi-sentence reply into separate messenger bubbles (chat style).
# Don't split right after a few common Polish abbreviations.
_ABBR = ("np", "itd", "itp", "tzn", "tj", "m.in", "dr", "mgr", "godz", "ok")
_SENT_SPLIT = re.compile(r'(?<=[.!?โ€ฆ])\s+')
def _split_sentences(text):
text = (text or "").strip()
if not text:
return []
out, buf = [], ""
for part in _SENT_SPLIT.split(text):
cand = (buf + " " + part).strip() if buf else part
low = buf.rstrip(".").split()[-1].lower() if buf else ""
if buf and low in _ABBR: # don't break after "np." etc.
buf = cand
continue
if buf:
out.append(buf)
buf = part
if buf:
out.append(buf)
return [s for s in (x.strip() for x in out) if s]
EVENT_TYPES = ("message", "image", "file", "system_idle")
BUBBLE_TYPES = ("response", "follow_up", "proactive", "reaction")
ALLOWED_REACTIONS = ("โค๏ธ", "๐Ÿ˜†", "๐Ÿ˜ฎ", "๐Ÿฅน", "๐Ÿ˜ข", "๐Ÿ˜ก")
BUBBLES_MAX = 6
BUBBLE_CHARS = 1200
def _messenger_style(text):
"""Mimic how people text: lowercase start, no trailing full stop.
Keeps '...', '?', '!', and all-caps tokens like 'XD'/'OK' intact."""
text = text.strip()
if not text:
return text
# strip any leaked internal id (e.g. evt_xxx), then tidy spacing
text = _ID_LEAK.sub("", text)
text = re.sub(r"\s{2,}", " ", text).strip()
if not text:
return text
# drop a single trailing period (but keep an ellipsis)
if text.endswith(".") and not text.endswith(".."):
text = text[:-1].rstrip()
# lowercase the first letter unless the first word is an all-caps token
first = text.split(" ", 1)[0]
if not (len(first) >= 2 and first.isupper()):
text = text[:1].lower() + text[1:]
return text
def sanitize_bubbles(raw, valid_event_ids):
"""Coerce whatever the model produced into a safe list of bubble dicts."""
arr = raw
if isinstance(raw, str):
arr = _extract_json_array(raw)
if not isinstance(arr, list):
arr = []
out = []
for b in arr:
if len(out) >= BUBBLES_MAX:
break
if not isinstance(b, dict):
continue
btype = b.get("type") if b.get("type") in BUBBLE_TYPES else "response"
target = b.get("target_event_id") or b.get("target")
if target not in valid_event_ids:
target = None
# quote / reply-to: which earlier message this bubble answers (shown as a quote)
reply_to = b.get("reply_to") or b.get("quote")
if reply_to not in valid_event_ids:
reply_to = None
# Models vary on the field name โ€” accept bubble/content/text/message/emoji.
raw_text = (b.get("bubble") or b.get("content") or b.get("text")
or b.get("message") or b.get("emoji") or "")
# Reaction: keep the raw emoji (no messenger styling); must be allowed + targeted.
if btype == "reaction":
emoji = str(raw_text).strip()
if emoji in ALLOWED_REACTIONS and target:
out.append({"bubble": emoji, "target_event_id": target, "type": "reaction"})
continue
# split a multi-sentence reply into separate short bubbles (chat style)
for i, piece in enumerate(_split_sentences(str(raw_text)[:BUBBLE_CHARS])):
if len(out) >= BUBBLES_MAX:
break
t = _messenger_style(piece)
if not t:
continue
out.append({"bubble": t, "target_event_id": target,
"reply_to": reply_to if i == 0 else None, # quote only on the first bubble
"type": btype if i == 0 else "follow_up"})
return out
def _extract_json_array(s: str):
"""Best-effort: pull the first JSON array out of a model response."""
s = s.strip()
if s.startswith("```"):
s = s.strip("`")
if s.lower().startswith("json"):
s = s[4:]
try:
return json.loads(s)
except Exception:
pass
start, depth, in_str, esc = -1, 0, False, False
for i, ch in enumerate(s):
if start == -1:
if ch == "[":
start, depth = i, 1
continue
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == '"':
in_str = False
else:
if ch == '"':
in_str = True
elif ch == "[":
depth += 1
elif ch == "]":
depth -= 1
if depth == 0:
try:
return json.loads(s[start:i + 1])
except Exception:
return []
return []