Compare commits

..

16 Commits

Author SHA1 Message Date
javis-bot
f05424e1b2 chore(app): version 0.1.36
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:08:35 +09:00
javis-bot
be09cfad81 fix(reply): what the user says they did is not refused as unsupported
The tool honesty rules ("if no tool can do it, say so") made the
model refuse actions the user only reported doing themselves: "알람
일곱 시로 맞춰놨어, 잘했지?" got "제가 도와드릴 수 없습니다". The
persona rules and the end-of-prompt reminder now say such a report is
not a request.

Measured on the service model (qwen3.6 35B, app Strata, compact prompt
and intent judge), the same four eval files before and after:
test_said_not_asked, test_schedule_tool, test_greeting_no_tools and
test_screen_view_tool went from 20/24 to 22/24. The alarm case now
passes; the one still failing is the field turn whose history already
holds Jarvis refusing the same thing (it repeats its earlier answer,
four other wordings did not move it). Piranesi fails before and after.
Adds the correctly heard field turn as a case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:08:18 +09:00
javis-bot
ac633c63ca fix(voice): no treble boost before transcription
The 12 dB shelf above 1 kHz from 0.1.34 made the user's speech worse.
Re-transcribing the 34 live recordings of 2026-11-18 (17:32 to 19:53)
with the shelf reproduces every live text; without it "왜 내 방해를"
comes back instead of "올해 내 방해를" (the user said "난 왜 라고
했어" right after), "알아서 좀 조정해 놨는데" instead of "아라해석도
좀 조정해놨는데", and "넌 뭐하는 애야?" instead of an empty text. No
utterance got clearly better with it. Reverts 9f62bfb and 04c23f9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:04:24 +09:00
javis-bot
499280504e test(evals): actions the user says they did are not refused
Field failure 2026-11-18: "너 말하는 속도 내가 조절해놨으니까 한번 말해보라고"
was answered "말하는 속도 조절 기능은 현재 지원하고 있지 않습니다". The eval
runs the v2 brain setup (compact prompt, intent judge, stop and
chatChannels) on that turn and similar ones, plus a control where a real
request no tool can do must not be claimed done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:59:46 +09:00
javis-bot
c816358552 chore(app): version 0.1.35
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:32:50 +09:00
javis-bot
9f5f3d891f fix(voice): spell Korean numbers out before MeloTTS reads them
MeloTTS's Korean front end read "60%" digit by digit ("육영퍼센트") when
the Windows MeCab build did not tag what followed as a bound noun, and its
sentence splitter broke "4.2미터" at the dot ("사. 이미터"). The KR child
now spells decimals with 점, drops thousands commas and gives every other
whole number its Sino-Korean reading, leaving numbers before native
counters (시, 개, 마리, ...) to MeloTTS's own counter rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:32:46 +09:00
javis-bot
04c23f9bf7 docs(voice): consonant shelf numbers measured with voiced masks
Re-measured as a final is levelled (Silero voiced windows): live 25 sure
utterances 5.04% -> 3.92% CER, FLEURS Korean test 5.11% -> 4.85%. The
shelf does not fix a wake word whose first consonant is not heard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:18:30 +09:00
javis-bot
49050b18a9 chore(app): version 0.1.34
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:09:12 +09:00
javis-bot
9f62bfb059 fix(voice): raise the consonant band by 12 dB before transcription
A dark microphone or a speaker who swallows first consonants and
sentence ends loses the band above 1 kHz first: in the live
recordings "자비스" came out as "아비스"/"다비스" and "서울" as "어우".
loudness_equalise now raises it with a one-octave shelf at 1 kHz.

Measured with large-v3-turbo: 25 sure live utterances 5.0% -> 3.4% CER,
FLEURS Korean test split (382 clips, held out) 5.16% -> 4.98%. The real
noise check stays at 108 clips with no text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:09:05 +09:00
javis-bot
e428aad58a chore(app): version 0.1.33
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:25:49 +09:00
javis-bot
a665dd8d21 revert(voice): back to upstream songbird 0.6.1, nothing was heard with the held-packet patch
With 0.1.32 (songbird vendored with packets of an unnamed SSRC held until
Discord's Speaking op names it) the bot heard nobody on the live server
from its 16:57 join on 2026-11-18, while 0.1.30 heard every request at
15:58 the same day, and the speaker's Discord was heard by everyone else.
The patch is the only receive change between the two, and the cause was
not found (it passed the two-bot test server runs), so it is removed and
the first ~100 ms of a speaker's first utterance after a join is lost
again, as in 0.1.30.

This reverts 81d1e26 and 9199ccb.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:24:58 +09:00
javis-bot
a5afdbb221 chore(app): version 0.1.32
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:22:30 +09:00
javis-bot
9199ccbd0e fix(voice): release held packets within 20 ms once the speaker is named
Held packets were only processed before the same SSRC's next packet, so
a short first utterance that ended before Discord's Speaking op came was
dropped after a second. The UDP task now also releases every newly named
SSRC's held packets on its 20 ms playout tick.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:22:30 +09:00
javis-bot
2a95f58a0e chore(app): version 0.1.31
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:15:23 +09:00
javis-bot
81d1e26f61 fix(voice): keep the first packets of a speaker until Discord names them
Discord names a speaker's SSRC in the Speaking op only the first time
they speak, and the op arrives after their first UDP packets. songbird
0.6.1 dropped the DAVE packets it could not decrypt yet, so the first
~100 ms of the first thing each person said after a join were lost
(live 2026-11-18: "자비스 서울 날씨 어때" arrived as "아비 서울날씨
어때", and the first call after the 01:20 start as "아비스").

songbird is vendored in app/vendor/songbird with one patch: packets of
an unnamed SSRC are held (1 s, 50 packets each, 32 SSRCs) and processed
in arrival order once it is named, and the Speaking event is sent before
the SSRC is named so handlers know the speaker first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:15:07 +09:00
javis-bot
88ee5ec2cb feat(weather): the app's log names the service that gave the weather
The source line (KMA, open-meteo or met.no for now; KMA and open-meteo
day counts for a forecast) only went to debug_log, which is off by
default and muted while the worker's brain answers, so a live answer
such as "흐림" could not be traced to its service. It now goes to the
llm log tab without the place or the key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:10:06 +09:00
13 changed files with 337 additions and 15 deletions

2
app/Cargo.lock generated
View File

@@ -1520,7 +1520,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "jarvis-app"
version = "0.1.30"
version = "0.1.36"
dependencies = [
"async-trait",
"base64 0.22.1",

View File

@@ -1,6 +1,6 @@
[package]
name = "jarvis-app"
version = "0.1.30"
version = "0.1.36"
edition = "2021"
rust-version = "1.85"
description = "Jarvis v2 Windows app core: Discord voice, voice worker supervisor, chat channels"

4
app/shell/Cargo.lock generated
View File

@@ -2637,7 +2637,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "jarvis-app"
version = "0.1.30"
version = "0.1.36"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -2666,7 +2666,7 @@ dependencies = [
[[package]]
name = "jarvis-shell"
version = "0.1.30"
version = "0.1.36"
dependencies = [
"jarvis-app",
"serde_json",

View File

@@ -1,6 +1,6 @@
[package]
name = "jarvis-shell"
version = "0.1.30"
version = "0.1.36"
edition = "2021"
rust-version = "1.85"
description = "Jarvis v2 management app window (Tauri 2 over the app core's AdminApi)"

View File

@@ -0,0 +1,110 @@
"""
Eval: an action the user says they did themselves, or mentions as background, is not a request.
Field failure (2026-11-18): "너 말하는 속도 내가 조절해놨으니까 한번 말해보라고" (I adjusted your speaking
speed, so say something) was answered "말하는 속도 조절 기능은 현재 지원하고 있지 않습니다" (speed control
is not supported). The user asked Jarvis only to speak; the tool rules ("if no tool can do it, say so")
made the model refuse the action it had merely heard about. The user reported many replies like it.
Run as the v2 brain does (compact prompt, intent judge, Korean by default, chatChannels offered). Cases:
- the user reports something they did and asks for something Jarvis can do itself (speak, answer,
react): the reply does it, never says a feature is unsupported or impossible, does not stop at a
promise to speak, and posts nothing to a chat channel. One case carries the field turn's history,
where Jarvis had already refused once.
- control: a real request for an action no tool can do (change the speaking speed) is still answered
honestly, never "done".
Judged by the model under test with a yes/no question per reply.
Run: EVAL_JUDGE_MODEL=... EVAL_JUDGE_BASE_URL=... python -m pytest evals/test_said_not_asked.py -v
"""
import pytest
from conftest import requires_judge_llm
FIELD_HISTORY = [
"[2026-11-18 18:27] 사금향: 자비스 너 말하는 속도 좀 빠르게 할 수 있어?",
"[2026-11-18 18:27] 자비스: 말하는 속도 조절 기능은 현재 지원하고 있지 않습니다.",
]
SAID_CASES = [
{"id": "speed-adjusted-field", "query": "너 말하는 속도 내가 조절해놨으니까 한번 말해보라고",
"recent": FIELD_HISTORY},
{"id": "adjusted-heard-right", "query": "알아서 좀 조정해 놨는데 한번 말해 볼래", "recent": []},
{"id": "speed-adjusted", "query": "너 말하는 속도 내가 조절해놨으니까 한번 말해보라고", "recent": []},
{"id": "volume-raised", "query": "자비스 볼륨 키워놨으니까 아무 말이나 해 봐", "recent": []},
{"id": "voice-changed", "query": "방금 설정에서 네 목소리 바꿔놨어, 한마디만 해 봐", "recent": []},
{"id": "mic-replaced", "query": "마이크 새로 바꿨는데 내 말 잘 들려?", "recent": []},
{"id": "alarm-set-myself", "query": "나 내일 아침 알람 일곱 시로 맞춰놨어, 잘했지?", "recent": []},
]
REFUSAL_JUDGE = (
"You check a voice assistant's reply. Answer only YES or NO.\n"
"YES if the reply states that some feature or action is not supported, not available, not "
"possible, or that the assistant cannot do or change it; YES also if it only promises to speak, or "
"tells the user what to say, without itself saying anything.\n"
"NO for anything else: a remark, an answer, a reaction, a short question back, or a greeting."
)
CLAIM_JUDGE = (
"You check a voice assistant's reply. Answer only YES or NO.\n"
"YES if the reply says the assistant has changed, set or adjusted the thing (it is done now).\n"
"NO if it says it cannot, asks something, or does not claim it was done."
)
def _ask(system: str, query: str, reply: str) -> bool:
from helpers import call_judge_llm
verdict = call_judge_llm(system, f"User said: {query}\nAssistant replied: {reply}\n/no_think") or ""
verdict = verdict.split("</think>")[-1].strip().upper()
return verdict.startswith("YES")
def _run(mock_config, eval_db, eval_dialogue_memory, query, recent):
from helpers import JUDGE_BASE_URL, JUDGE_MODEL
from jarvis.memory.history import HistoryContext
from jarvis.reply import turn_state
from jarvis.reply.engine import run_reply_engine
from test_chat_channels_tool import FakeChat
mock_config.ollama_base_url = JUDGE_BASE_URL
mock_config.ollama_chat_model = JUDGE_MODEL
mock_config.tts_engine = "melo"
mock_config.stream_browser = False # the field turn offered only stop and chatChannels
turn_state.reset()
turn_state.set_user("100")
chat = FakeChat()
turn_state.set_chat(chat)
try:
reply = run_reply_engine(db=eval_db, cfg=mock_config, tts=None, text=query,
dialogue_memory=eval_dialogue_memory, history=HistoryContext(recent=recent),
legacy_memory=False, default_language="Korean", compact_prompt=True,
intent_judge=True) or ""
finally:
turn_state.reset()
print(f"\n [{JUDGE_MODEL}] {query!r}: acts={chat.acts} reply={reply!r}")
return reply, chat.acts
@pytest.mark.eval
@requires_judge_llm
class TestSaidNotAsked:
@pytest.mark.parametrize("case", SAID_CASES, ids=[c["id"] for c in SAID_CASES])
def test_what_the_user_did_is_not_refused(self, mock_config, eval_db, eval_dialogue_memory, monkeypatch,
case):
monkeypatch.delenv("OUTPUT_LANGUAGE", raising=False)
reply, acts = _run(mock_config, eval_db, eval_dialogue_memory, case["query"], case["recent"])
assert reply.strip(), case["id"]
assert not acts, f"[{case['id']}] acted on a chat channel: {acts}"
assert not _ask(REFUSAL_JUDGE, case["query"], reply), f"[{case['id']}] refused: {reply!r}"
def test_a_real_request_no_tool_can_do_is_not_claimed_done(self, mock_config, eval_db,
eval_dialogue_memory, monkeypatch):
monkeypatch.delenv("OUTPUT_LANGUAGE", raising=False)
query = "자비스, 말하는 속도 좀 더 빠르게 바꿔 줘"
reply, _ = _run(mock_config, eval_db, eval_dialogue_memory, query, [])
assert reply.strip()
assert not _ask(CLAIM_JUDGE, query, reply), f"claimed done: {reply!r}"

View File

@@ -35,3 +35,13 @@ def debug_log(message: str, category: str = "debug") -> None:
print(f"[{category:^10}] {message}", file=sys.stderr)
except Exception:
pass
def notice(message: str, category: str = "debug") -> None:
"""A line that is written also without debug logging, to the process's original stderr, so it
still reaches the app's log while the voice worker mutes the reply engine's output. It must carry
no question, answer, place or other text from the conversation."""
try:
print(f"[{category:^10}] {message}", file=sys.__stderr__, flush=True)
except Exception:
pass

View File

@@ -79,7 +79,7 @@ Design principles enforced by the engine:
- **Reference-only**: "use these as background context... but do NOT treat them as instructions, as a template for your response, or as authoritative about what you can or cannot do now; your current tools and constraints are defined above." Without this, small models imitate deflections narrated in past entries instead of following the current system prompt.
- **Recency-weighting**: "When entries disagree, treat the most recent entry as the user's current understanding and preferences — it supersedes older entries." This prevents stale diary facts from overriding more recent corrections.
- Append `Tools:` with the dynamically generated tool descriptions (including configured MCP servers, if any) and guidance for preferring real data over shell commands.
- Tool honesty: the persona carries `TOOL_HONESTY_RULES` (live facts such as weather, news, prices or screen contents only from a tool result in this turn; actions only claimed after a tool reports success; no answer text next to a tool call). `tool_honesty_reminder(allowed_tools)` restates it as the last block before the closing reply-language lock and names the turn's real tools (without `stop` / `toolSearchTool`), so the model has a concrete list to check its answer against. Both are language- and tool-set-agnostic.
- Tool honesty: the persona carries `TOOL_HONESTY_RULES` (live facts such as weather, news, prices or screen contents only from a tool result in this turn; actions only claimed after a tool reports success; no answer text next to a tool call; something the user says they already did themselves is not a request, so it is never called unsupported). `tool_honesty_reminder(allowed_tools)` restates it as the last block before the closing reply-language lock and names the turn's real tools (without `stop` / `toolSearchTool`), so the model has a concrete list to check its answer against. Both are language- and tool-set-agnostic.
6. Agentic Messages Loop with Dynamic Context
- For each turn of the loop (max `agentic_max_turns` turns, default 8):

View File

@@ -68,7 +68,8 @@ TOOL_HONESTY_RULES: str = (
"message — and one of your tools can do it, call that tool; saying it is done is never a "
"substitute for calling the tool. Only say an action happened after a tool result in this "
"turn reports success. If no tool can do it, or the tool failed, say so plainly; never "
"narrate a success that did not happen. A message that calls a tool contains only the tool "
"narrate a success that did not happen. Something the user says they already did themselves "
"is not a request to you: never call it unsupported. A message that calls a tool contains only the tool "
"call: write no answer or confirmation next to it, and answer after you see the result."
)
@@ -248,7 +249,10 @@ def tool_honesty_reminder(tool_names) -> str:
f"must come from a tool call in this turn. Your tools this turn: {listed}. If one of "
"them can fetch the fact or do the action, call it now instead of answering. If none "
"of them can, say plainly that you cannot check or do that; never say something was "
"done unless a tool result in this turn says so."
"done unless a tool result in this turn says so. This is only about what the user asks "
"you to do now: something the user says they already did themselves is not a request, so "
"never call it unsupported or impossible; just do what they ask of you now, such as "
"talking or answering."
)

View File

@@ -7,7 +7,7 @@ from datetime import datetime, timedelta, timezone
import requests
from typing import Dict, Any, Optional
from ...debug import debug_log
from ...debug import debug_log, notice
from ...utils.location import get_location_info
from ..base import Tool, ToolContext
from ..types import ToolExecutionResult
@@ -674,8 +674,8 @@ class WeatherTool(Tool):
rest = [off for off in offsets if off not in days]
if rest:
days.update(_open_meteo_days(lat, lon, rest))
debug_log(f" 🌤️ forecast days {first}-{last}: {from_kma} from KMA, "
f"{len(days) - from_kma} from open-meteo", "tools")
# Which service gave the answer, in the app's log (no place: it comes from the question).
notice(f"weather days {first}-{last}: {from_kma} from KMA, {len(days) - from_kma} from open-meteo", "llm")
place = location_display.split(",")[0].strip() or location_display
return [_day_sentence(off, days[off], place, detail) for off in offsets if off in days]
@@ -863,12 +863,12 @@ class WeatherTool(Tool):
}
current: Dict[str, Any] = {}
source = "KMA"
kma_key = _kma_key_now()
if kma_key and country_code == "KR":
current = _kma_current(lat, lon, kma_key)
if current:
debug_log(" 🌤️ current weather from KMA", "tools")
if not current:
source = "open-meteo"
try:
weather_response = requests.get(weather_url, params=weather_params,
timeout=_OPEN_METEO_TIMEOUT_SEC)
@@ -877,12 +877,14 @@ class WeatherTool(Tool):
except Exception as e:
# Live 2026-11-18: the forecast server stopped answering while geocoding worked.
debug_log(f"open-meteo forecast failed ({type(e).__name__}); trying met.no", "tools")
source = "met.no"
current = _met_no_current(lat, lon)
if not current:
return ToolExecutionResult(
success=False,
reply_text=f"Weather data temporarily unavailable for {location_display}."
)
notice(f"weather now: {source}", "llm")
# Extract current weather values
temp_c = current.get("temperature_2m")

View File

@@ -24,12 +24,23 @@ import argparse
import importlib
import json
import os
import re
import struct
import sys
import types
MODEL_SPEED_MAX = 1.25
# MeloTTS's Korean front end (g2pkk) reads a number with native numerals only before these counters,
# and only when MeCab tags the counter. Any other number is spelled out only when MeCab tags what follows
# as a bound noun, which differs between MeCab builds (on Windows "60%" was read "육영퍼센트"); the rest
# goes digit by digit. Its sentence splitter also breaks at every dot and comma ("4.2" as "사. 이").
# Same list as g2pkk's BOUND_NOUNS: numbers before them are left for its counter rule.
NATIVE_COUNTERS = tuple("군데 권 개 그루 닢 대 두 마리 모 모금 뭇 발 발짝 방 번 벌 보루 살 수 술 시 쌈 움큼 "
"정 짝 채 척 첩 축 켤레 톨 통".split())
_DIGITS = "영일이삼사오육칠팔구"
_NUMBER = re.compile(r"(?<![\d.,])(\d{1,3}(?:,\d{3})+|\d+)(?:\.(\d+))?(?![\d,]\d)(?!\.\d)([가-힣]*)")
def split_speed(speed: float) -> tuple[float, float]:
"""(the model's speed, the stretch factor after it); their product is ``speed``."""
@@ -65,6 +76,39 @@ def stretch(audio, factor: float, rate: int, frame_ms: float = 30.0, search_ms:
return y[:n_out]
def sino_korean(num: str) -> str:
"""Sino-Korean reading of a whole number: 1234 is 천이백삼십사, 10000 is 만, 100000000 is 일억."""
n = int(num)
if n == 0:
return "영"
out = ""
for power, big in reversed(list(enumerate(("", "만", "억", "조", "경")))):
group = n // 10 ** (4 * power) % 10000
if not group:
continue
part = ""
for digit, unit in zip(f"{group:04d}", ("천", "백", "십", "")):
d = int(digit)
if d:
part += ("" if d == 1 and unit else _DIGITS[d]) + unit
out += ("" if part == "일" and big == "만" else part) + big
return out
def spell_numbers_kr(text: str) -> str:
"""Spell out the numbers MeloTTS would misread: decimals ("4.2" is 사점이) and every whole number
not followed by a native counter (those are left for MeloTTS, which reads "3시" as 세시)."""
def spell(m: re.Match) -> str:
whole, frac, after = m.group(1), m.group(2), m.group(3)
if frac is None and after.startswith(NATIVE_COUNTERS):
return m.group(0)
spoken = sino_korean(whole.replace(",", ""))
if frac is not None:
spoken += "점" + "".join(_DIGITS[int(d)] for d in frac)
return spoken + after
return _NUMBER.sub(spell, text)
def korean_only_patches() -> None:
"""MeloTTS imports its Japanese front end (module-level MeCab.Tagger()) even for Korean, and on
Windows g2pkk asks for ``eunjeon`` instead of python-mecab-ko. Same fix as the M0 kit."""
@@ -132,7 +176,10 @@ def main() -> int:
req = json.loads(line)
rate = int(req["rate"])
model_speed, factor = split_speed(float(req.get("speed", args.speed)))
audio = model.tts_to_file(str(req["text"]), speaker, None, speed=model_speed, quiet=True)
text = str(req["text"])
if args.language == "KR":
text = spell_numbers_kr(text)
audio = model.tts_to_file(text, speaker, None, speed=model_speed, quiet=True)
audio = stretch(audio, factor, native)
if rate != native:
from math import gcd

View File

@@ -108,6 +108,9 @@ its own streaming Silero VAD (512-sample windows, state kept between frames).
the gain kept between -20 and +40 dB, and peaks above 0.8 are soft-limited below 0.98 instead of
clipping. Measured: speech from -60 dBFS to clipped shouting was transcribed equally well, and quiet
speech under loud clicks or knocks better than with peak normalisation.
No treble boost: a 12 dB shelf above 1 kHz (0.1.34) helped FLEURS a little but, on the user's
own 34 live utterances of 2026-11-18, turned "왜" into "올해" and "알아서" into "아라해석" and
dropped a whole sentence, so it was removed again.
### Scheduling
@@ -180,6 +183,14 @@ is ready. Requests are served first come, first served by one TTS engine. `tts_c
request's unsent sentences, and `tts_done` follows with `cancelled: true`. A sentence that fails to
synthesise is reported with `error` (`code: "tts_failed"`) and the request ends with `failed: true`.
With `--melo-language KR` the MeloTTS child spells numbers out in Hangul before MeloTTS sees them,
because its Korean front end misreads them: a number it cannot tag as a counter is read digit by digit
(the tag depends on the MeCab build; on Windows "60%" was read "육영퍼센트"), and its own splitter
breaks at every dot and comma ("4.2미터" as "사. 이미터"). Decimals are read with 점 and one name per
digit after it (사점이), thousands commas are dropped, and every other whole number gets its
Sino-Korean reading (육십, 이천이십육), except before a counter MeloTTS reads with native numerals
(g2pkk's list: 시, 개, 마리, 살, ...), which stays for MeloTTS ("3시" is 세시).
Speed starts at `--melo-speed` and `tts_speed` changes it for every sentence made after it (a speed
outside 0.5-2.0 or not a number is `bad_message` and the last good one stays). MeloTTS itself speaks
up to 1.25: its own speed shortens every sound, and past that it drops them (five Korean sentences,
@@ -298,7 +309,9 @@ which carry Discord's own time.
highest chance of rain), then 중기예보 for the nearest of the KMA cities in `weather.py` and its region (중기기온,
중기육상). Days KMA does not give, and every KMA failure, come from open-meteo (now: then
met.no; later days: open-meteo's daily forecast only). The key is in KMA's URLs, so a failure is
logged by its kind only. `detail` (only when the user asks for more detail) adds the
logged by its kind only. Which service answered is printed without debug logging (category
`llm`, no place and no key): `weather now: KMA` (or `open-meteo`, `met.no`) and
`weather days <first>-<last>: <n> from KMA, <m> from open-meteo`. `detail` (only when the user asks for more detail) adds the
humidity, the wind in m/s and the rain amount: now the last hour's rain (KMA 초단기실황 RN1,
open-meteo `precipitation`; none from met.no), a 단기예보 day its mean humidity and strongest
wind, an open-meteo day its strongest wind and rain total; 중기예보 has none of these. A dry

View File

@@ -0,0 +1,87 @@
"""Numbers MeloTTS's Korean front end reads wrongly are spelled out before it sees them: a number it
cannot tag as a counter is read digit by digit ("60%" as "육영퍼센트"), and every dot or comma is a
sentence break for it ("4.2미터" as "사. 이미터")."""
from __future__ import annotations
import json
import os
import struct
import subprocess
import sys
import textwrap
import pytest
from voice_worker import melo_child
from voice_worker.melo_child import spell_numbers_kr
@pytest.mark.unit
@pytest.mark.parametrize("text, spoken", [
("습도 60%입니다.", "습도 육십%입니다."),
("습도 60퍼센트", "습도 육십퍼센트"),
("바람 초속 4.2미터", "바람 초속 사점이미터"),
("최고 25.5도, 최저 0.5도", "최고 이십오점오도, 최저 영점오도"),
("11월 19일, 2026년", "십일월 십구일, 이천이십육년"),
("1,234명", "천이백삼십사명"),
("10 100 1000 10000 110 20만 100000000", "십 백 천 만 백십 이십만 일억"),
("0, 7", "영, 칠"),
])
def test_numbers_are_spelled_as_they_are_read(text, spoken):
assert spell_numbers_kr(text) == spoken
@pytest.mark.unit
def test_numbers_before_native_counters_are_left_for_melo_to_read_natively():
# "3시" is "세시", "10개" is "열개", "5시간" is "다섯시간": MeloTTS's own counter rule reads these.
text = "3시 10개 5시간 2마리"
assert spell_numbers_kr(text) == text
FAKE_MELO = textwrap.dedent("""
import os
import numpy as np
class _Hps:
class data:
spk2id = {"KR": 0}
sampling_rate = 48000
class TTS:
def __init__(self, language, device):
self.hps = _Hps
def tts_to_file(self, text, speaker, path, speed=1.0, quiet=True):
with open(os.environ["FAKE_MELO_LOG"], "a", encoding="utf-8") as f:
f.write(text + "\\n")
return np.zeros(10)
""")
def read_frame(stream) -> dict:
(n,) = struct.unpack("<I", stream.read(4))
header = json.loads(stream.read(n))
stream.read(2 * header.get("samples", 0))
return header
@pytest.mark.unit
def test_the_korean_child_gives_melo_the_spelled_text(tmp_path):
(tmp_path / "melo").mkdir()
(tmp_path / "melo" / "__init__.py").write_text("")
(tmp_path / "melo" / "api.py").write_text(FAKE_MELO)
log = tmp_path / "texts.txt"
env = {**os.environ, "PYTHONPATH": str(tmp_path), "FAKE_MELO_LOG": str(log)}
proc = subprocess.Popen([sys.executable, melo_child.__file__, "--language", "KR", "--device", "cpu",
"--speed", "1.0"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, env=env)
try:
assert read_frame(proc.stdout)["ready"] is True
proc.stdin.write((json.dumps({"text": "바람 초속 4.2미터, 습도 60%", "rate": 48000}) + "\n").encode())
proc.stdin.flush()
assert read_frame(proc.stdout)["ok"] is True
finally:
proc.stdin.close()
proc.wait(timeout=10)
assert log.read_text(encoding="utf-8").splitlines()[-1] == "바람 초속 사점이미터, 습도 육십%"

View File

@@ -433,6 +433,29 @@ class TestWeatherTool:
assert WMO_CODES_KO[80] in result.reply_text
assert str(round(8.6)) in result.reply_text
@patch('requests.get')
def test_the_log_names_met_no_when_it_gave_the_weather_now(self, mock_get, capfd):
geo = Mock(status_code=200, raise_for_status=Mock())
geo.json.return_value = {"results": [{"latitude": 37.57, "longitude": 126.98,
"name": "서울", "country": "대한민국"}]}
met = Mock(status_code=200, raise_for_status=Mock())
met.json.return_value = {"properties": {"timeseries": [{"data": {
"instant": {"details": {"air_temperature": 8.6}},
"next_1_hours": {"summary": {"symbol_code": "cloudy"}}}}]}}
def get(url, *a, **k):
if "geocoding" in url:
return geo
if "open-meteo" in url:
raise requests.exceptions.Timeout("timed out")
return met
mock_get.side_effect = get
self.tool.run({"location": "Seoul"}, self.context)
err = capfd.readouterr().err
assert "weather now: met.no" in err and "서울" not in err
@pytest.mark.parametrize("symbol", ["lightsleet", "sleet_day", "heavysleetshowers_night"])
def test_met_no_sleet_stays_sleet_not_freezing_rain(self, symbol):
from src.jarvis.tools.builtin.weather import _met_no_wmo
@@ -722,6 +745,23 @@ class TestKmaWeather:
assert len(kma) == 2 and all(p["authKey"] == self.KEY for p in kma)
assert all((p["nx"], p["ny"]) == (60, 127) for p in kma)
@pytest.mark.parametrize("key, source", [(True, "KMA"), (False, "open-meteo")])
@patch('requests.get')
def test_the_log_names_the_service_that_gave_the_weather_now_and_not_the_place(
self, mock_get, key, source, monkeypatch, capfd):
"""Live 2026-11-18: "흐림" could have come from either service, and nothing said which."""
if key:
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
else:
monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False)
mock_get.side_effect = self._routes()
self.tool.run({"location": "Seoul"}, self.context)
err = capfd.readouterr().err
assert f"weather now: {source}" in err
assert "Seoul" not in err and self.KEY not in err
@patch('requests.get')
def test_precipitation_wins_over_the_sky(self, mock_get, monkeypatch):
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
@@ -1053,6 +1093,15 @@ class TestForecast:
assert "강수확률 80%" in result.reply_text
assert not any(self.KEY in str(c) for c in log.call_args_list)
@pytest.mark.parametrize("fail_kma, counts", [(False, "1 from KMA, 0 from open-meteo"),
(True, "0 from KMA, 1 from open-meteo")])
def test_the_log_says_how_many_forecast_days_each_service_gave(self, fail_kma, counts, monkeypatch, capfd):
self._run({"days_ahead": 1}, monkeypatch, fail_kma=fail_kma)
err = capfd.readouterr().err
assert f"weather days 1-1: {counts}" in err
assert "Seoul" not in err and self.KEY not in err
def test_outside_korea_the_forecast_is_open_meteos_daily_one(self, monkeypatch):
result, calls = self._run({"days_ahead": 1}, monkeypatch, country_code="JP")