use serde_json::{json, Value};
#[derive(Debug, Clone, PartialEq)]
pub struct InferArgs {
pub model: crate::model_uri::ModelAddress,
pub prompt: String,
pub system: Option<String>,
pub max_tokens: Option<u64>,
pub broker: Option<String>,
pub file: Option<String>,
pub language: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ChatArgs {
pub model: crate::model_uri::ModelAddress,
pub system: Option<String>,
pub broker: Option<String>,
}
pub fn parse_infer_args(args: &[String]) -> Result<InferArgs, String> {
let mut model: Option<crate::model_uri::ModelAddress> = None;
let mut prompt: Option<String> = None;
let mut system: Option<String> = None;
let mut max_tokens: Option<u64> = None;
let mut broker: Option<String> = None;
let mut file: Option<String> = None;
let mut language: Option<String> = None;
let mut it = args.iter().peekable();
while let Some(arg) = it.next() {
match arg.as_str() {
"--file" => {
let v = it
.next()
.ok_or_else(|| "--file requires a value".to_string())?;
file = Some(v.clone());
}
"--language" => {
let v = it
.next()
.ok_or_else(|| "--language requires a value".to_string())?;
if !is_valid_language(v) {
return Err(format!(
"invalid --language '{v}': expected a 2-3 letter lowercase code such as 'en' or 'sn'"
));
}
language = Some(v.clone());
}
"-m" | "--prompt" => {
let v = it.next().ok_or_else(|| format!("{arg} requires a value"))?;
prompt = Some(v.clone());
}
"--max-tokens" => {
let v = it
.next()
.ok_or_else(|| "--max-tokens requires a value".to_string())?;
max_tokens = Some(
v.parse::<u64>()
.map_err(|_| format!("invalid --max-tokens value '{v}'"))?,
);
}
"--system" => {
let v = it
.next()
.ok_or_else(|| "--system requires a value".to_string())?;
system = Some(v.clone());
}
"--broker" => {
let v = it
.next()
.ok_or_else(|| "--broker requires a value".to_string())?;
broker = Some(v.clone());
}
other => {
if model.is_some() {
return Err(format!("unexpected argument '{other}'"));
}
let addr = crate::model_uri::parse_model_address(other)
.ok_or_else(|| format!("not a model address: '{other}'"))?;
model = Some(addr);
}
}
}
let model = model.ok_or_else(|| {
"zc infer requires a zc://<owner>/<name> or zc://<uuid> argument".to_string()
})?;
if file.is_some() && prompt.is_some() {
return Err("-m/--prompt and --file are mutually exclusive".to_string());
}
if file.is_none() && language.is_some() {
return Err("--language only applies with --file".to_string());
}
let prompt = match (&file, prompt) {
(Some(_), _) => String::new(),
(None, Some(p)) => p,
(None, None) => {
return Err("zc infer requires either -m/--prompt <text> or --file <audio>".to_string())
}
};
Ok(InferArgs {
model,
prompt,
system,
max_tokens,
broker,
file,
language,
})
}
pub fn parse_chat_args(args: &[String]) -> Result<ChatArgs, String> {
let mut model: Option<crate::model_uri::ModelAddress> = None;
let mut system: Option<String> = None;
let mut broker: Option<String> = None;
let mut it = args.iter().peekable();
while let Some(arg) = it.next() {
match arg.as_str() {
"--system" => {
let v = it
.next()
.ok_or_else(|| "--system requires a value".to_string())?;
system = Some(v.clone());
}
"--broker" => {
let v = it
.next()
.ok_or_else(|| "--broker requires a value".to_string())?;
broker = Some(v.clone());
}
other => {
if model.is_some() {
return Err(format!("unexpected argument '{other}'"));
}
let addr = crate::model_uri::parse_model_address(other)
.ok_or_else(|| format!("not a model address: '{other}'"))?;
model = Some(addr);
}
}
}
let model = model.ok_or_else(|| {
"zc chat requires a zc://<owner>/<name> or zc://<uuid> argument".to_string()
})?;
Ok(ChatArgs {
model,
system,
broker,
})
}
pub fn build_messages(prompt: &str, system: Option<&str>) -> Vec<Value> {
let mut messages = Vec::new();
if let Some(sys) = system {
messages.push(json!({"role": "system", "content": sys}));
}
messages.push(json!({"role": "user", "content": prompt}));
messages
}
pub fn build_infer_body(
model_uuid: &str,
prompt: &str,
system: Option<&str>,
max_tokens: Option<u64>,
) -> Value {
build_chat_body(model_uuid, &build_messages(prompt, system), max_tokens)
}
pub fn build_chat_body(model_uuid: &str, messages: &[Value], max_tokens: Option<u64>) -> Value {
let mut body = json!({
"model": format!("zc://{model_uuid}"),
"messages": messages,
});
if let Some(mt) = max_tokens {
body["max_tokens"] = json!(mt);
}
body
}
pub fn format_infer_output(resp: &Value) -> String {
let content = resp.get("content").and_then(|v| v.as_str()).unwrap_or("");
let total_tokens = resp
.get("usage")
.and_then(|u| u.get("total_tokens"))
.and_then(|v| v.as_u64())
.unwrap_or(0);
let charged = resp.get("charged").and_then(|v| v.as_f64()).unwrap_or(0.0);
let provider = resp
.get("provider")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
format!("{content}\n\n{total_tokens} tokens -> ¥{charged} (provider: {provider})")
}
pub fn format_infer_receipt(headers: &[(String, String)]) -> Option<String> {
let get = |name: &str| {
headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.trim().to_string())
};
let cost = get("X-Zakuro-Cost")?;
let mut lines = Vec::new();
if let Some(w) = get("X-Zakuro-Worker").filter(|w| !w.is_empty()) {
lines.push(("X-Zakuro-Worker", w));
}
let cost = match cost.parse::<f64>() {
Ok(c) => format!("¥{}", trim_decimal(c, 6)),
Err(_) => cost,
};
lines.push(("X-Zakuro-Cost", cost));
if let Some(left) = get("X-Zakuro-Balance") {
let left = match left.parse::<f64>() {
Ok(b) => crate::broker::balance::yen(b),
Err(_) => left,
};
lines.push(("X-Zakuro-Balance", left));
}
let w = lines.iter().map(|(k, _)| k.len()).max().unwrap_or(0) + 2;
Some(
lines
.iter()
.map(|(k, v)| format!("→ {k:<w$}{v}"))
.collect::<Vec<_>>()
.join("\n"),
)
}
fn trim_decimal(c: f64, places: usize) -> String {
let s = format!("{c:.places$}");
match s.contains('.') {
true => s.trim_end_matches('0').trim_end_matches('.').to_string(),
false => s,
}
}
pub fn format_infer_reply(resp: &Value, headers: &[(String, String)]) -> String {
match format_infer_receipt(headers) {
Some(receipt) => {
let content = resp.get("content").and_then(|v| v.as_str()).unwrap_or("");
format!("{content}\n\n{receipt}")
}
None => format_infer_output(resp),
}
}
pub fn format_infer_error(body: &str) -> String {
match serde_json::from_str::<Value>(body) {
Ok(v) => v
.get("error")
.and_then(|e| e.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| body.to_string()),
Err(_) => body.to_string(),
}
}
pub const HUB_DEFAULT_MAX_TOKENS: u64 = 256;
pub fn should_fall_back_to_hub(broker_explicit: bool, broker_error: &str) -> bool {
!broker_explicit && format_infer_error(broker_error).contains("no provider serving")
}
pub fn build_hub_body(messages: &[Value], max_tokens: Option<u64>) -> Value {
json!({
"messages": messages,
"max_tokens": max_tokens.unwrap_or(HUB_DEFAULT_MAX_TOKENS),
})
}
pub fn parse_hub_reply(body: &str) -> Result<(Value, Vec<(String, String)>), String> {
let v: Value = serde_json::from_str(body)
.map_err(|e| format!("parsing hub response: {e} (body: {body})"))?;
let content = v
.get("content")
.and_then(|c| c.as_str())
.ok_or_else(|| format!("hub response has no content (body: {body})"))?;
let decimal = |key: &str| match v.get(key) {
Some(Value::String(s)) => Some(s.trim().to_string()),
Some(Value::Number(n)) => Some(n.to_string()),
_ => None,
};
let charged = decimal("charged");
let mut resp = json!({
"content": content,
"usage": v.get("usage").cloned().unwrap_or_else(|| json!({})),
"provider": "hub",
});
if let Some(c) = charged.as_deref().and_then(|c| c.parse::<f64>().ok()) {
resp["charged"] = json!(c);
}
let mut headers = vec![("X-Zakuro-Worker".to_string(), "hub".to_string())];
if let Some(c) = charged {
headers.push(("X-Zakuro-Cost".to_string(), c));
}
if let Some(b) = decimal("balance") {
headers.push(("X-Zakuro-Balance".to_string(), b));
}
Ok((resp, headers))
}
pub fn format_hub_error(body: &str) -> String {
let msg = serde_json::from_str::<Value>(body)
.ok()
.and_then(|v| {
let d = v.get("detail")?;
if let Some(errs) = d.get("errors").and_then(|e| e.as_array()) {
let joined: Vec<&str> = errs.iter().filter_map(|e| e.as_str()).collect();
if !joined.is_empty() {
return Some(joined.join("; "));
}
}
d.as_str().map(|s| s.to_string())
})
.unwrap_or_else(|| body.trim().to_string());
format!("{msg} (hub)")
}
pub fn is_valid_language(s: &str) -> bool {
(2..=3).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_lowercase())
}
pub const MAX_AUDIO_BYTES: u64 = 512 * 1024 * 1024;
pub fn audio_content_type(path: &str) -> &'static str {
let ext = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
match ext.as_str() {
"wav" | "wave" => "audio/wav",
"mp3" => "audio/mpeg",
"flac" => "audio/flac",
"m4a" => "audio/mp4",
"ogg" | "oga" | "opus" => "audio/ogg",
"webm" => "audio/webm",
_ => "application/octet-stream",
}
}
pub fn build_multipart(
boundary: &str,
filename: &str,
content_type: &str,
audio: &[u8],
language: Option<&str>,
) -> (String, Vec<u8>) {
let safe: String = filename
.chars()
.map(|c| {
if matches!(c, '"' | '\r' | '\n' | '\\') {
'_'
} else {
c
}
})
.collect();
let mut body = Vec::with_capacity(audio.len() + 512);
if let Some(l) = language {
body.extend_from_slice(
format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"language\"\r\n\r\n{l}\r\n"
)
.as_bytes(),
);
}
body.extend_from_slice(
format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{safe}\"\r\nContent-Type: {content_type}\r\n\r\n"
)
.as_bytes(),
);
body.extend_from_slice(audio);
body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
(format!("multipart/form-data; boundary={boundary}"), body)
}
#[derive(Debug, Clone, PartialEq)]
pub struct TranscribeReply {
pub text: String,
pub language: Option<String>,
pub duration_s: Option<f64>,
pub billed_seconds: Option<f64>,
pub truncated: bool,
pub charged: Option<String>,
}
pub fn parse_transcribe_reply(body: &str) -> Result<TranscribeReply, String> {
let v: Value = serde_json::from_str(body)
.map_err(|e| format!("parsing hub transcribe reply: {e} (body: {body}) (hub)"))?;
let text = v
.get("text")
.and_then(|t| t.as_str())
.ok_or_else(|| format!("hub transcribe reply has no text (body: {body}) (hub)"))?
.to_string();
Ok(TranscribeReply {
text,
language: v.get("language").and_then(|x| x.as_str()).map(String::from),
duration_s: v.get("duration_s").and_then(|x| x.as_f64()),
billed_seconds: v.get("billed_seconds").and_then(|x| x.as_f64()),
truncated: v
.get("truncated")
.and_then(|x| x.as_bool())
.unwrap_or(false),
charged: match v.get("charged") {
Some(Value::String(s)) => Some(s.trim().to_string()),
Some(Value::Number(n)) => Some(n.to_string()),
_ => None,
},
})
}
pub fn format_transcribe_reply(r: &TranscribeReply) -> String {
let mut lines: Vec<(&str, String)> = Vec::new();
if let Some(l) = &r.language {
lines.push(("Language", l.clone()));
}
if let Some(d) = r.duration_s {
lines.push(("Duration", format!("{} s", trim_decimal(d, 2))));
}
if let Some(b) = r.billed_seconds {
lines.push(("Billed", format!("{} s", trim_decimal(b, 2))));
}
if let Some(c) = &r.charged {
let cost = match c.parse::<f64>() {
Ok(f) => trim_decimal(f, 6),
Err(_) => c.clone(),
};
lines.push(("Cost", format!("¥{cost}")));
}
let w = lines.iter().map(|(k, _)| k.len()).max().unwrap_or(0) + 2;
let mut out = r.text.trim().to_string();
if !lines.is_empty() {
out.push_str("\n\n");
out.push_str(
&lines
.iter()
.map(|(k, v)| format!("→ {k:<w$}{v}"))
.collect::<Vec<_>>()
.join("\n"),
);
}
if r.truncated {
out.push_str(
"\n\nWarning: the audio exceeds the 10-minute limit; only the first 10 minutes were transcribed.",
);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model_uri::ModelAddress;
const UUID: &str = "ae5f3db4-437a-40d1-93ec-c8258315d69a";
#[test]
fn parses_minimal_infer_args() {
let args = vec![
format!("zc://{UUID}"),
"-m".to_string(),
"hello".to_string(),
];
let parsed = parse_infer_args(&args).unwrap();
assert_eq!(parsed.model, ModelAddress::Uuid(UUID.to_string()));
assert_eq!(parsed.prompt, "hello");
assert_eq!(parsed.system, None);
assert_eq!(parsed.max_tokens, None);
assert_eq!(parsed.broker, None);
}
#[test]
fn parses_full_infer_args() {
let args = vec![
format!("zc://model-{UUID}"),
"--prompt".to_string(),
"hi there".to_string(),
"--max-tokens".to_string(),
"256".to_string(),
"--system".to_string(),
"be terse".to_string(),
"--broker".to_string(),
"http://localhost:9000".to_string(),
];
let parsed = parse_infer_args(&args).unwrap();
assert_eq!(parsed.model, ModelAddress::Uuid(UUID.to_string()));
assert_eq!(parsed.prompt, "hi there");
assert_eq!(parsed.system.as_deref(), Some("be terse"));
assert_eq!(parsed.max_tokens, Some(256));
assert_eq!(parsed.broker.as_deref(), Some("http://localhost:9000"));
}
#[test]
fn rejects_invalid_model_uri() {
let args = vec![
"zc://node-abc123".to_string(),
"-m".to_string(),
"hi".to_string(),
];
let err = parse_infer_args(&args).unwrap_err();
assert!(err.contains("not a model address"));
}
#[test]
fn rejects_missing_prompt() {
let args = vec![format!("zc://{UUID}")];
let err = parse_infer_args(&args).unwrap_err();
assert!(err.contains("--prompt"));
}
#[test]
fn rejects_missing_model() {
let args = vec!["-m".to_string(), "hi".to_string()];
let err = parse_infer_args(&args).unwrap_err();
assert!(err.contains("<owner>/<name>"), "{err}");
assert!(err.contains("zc://"), "{err}");
}
#[test]
fn parses_chat_args() {
let args = vec![
format!("zc://{UUID}"),
"--system".to_string(),
"be terse".to_string(),
];
let parsed = parse_chat_args(&args).unwrap();
assert_eq!(parsed.model, ModelAddress::Uuid(UUID.to_string()));
assert_eq!(parsed.system.as_deref(), Some("be terse"));
assert_eq!(parsed.broker, None);
}
#[test]
fn build_infer_body_without_system_or_max_tokens() {
let body = build_infer_body(UUID, "hello", None, None);
assert_eq!(body["model"], json!(format!("zc://{UUID}")));
assert_eq!(
body["messages"],
json!([{"role": "user", "content": "hello"}])
);
assert!(body.get("max_tokens").is_none());
}
#[test]
fn build_infer_body_with_system_and_max_tokens() {
let body = build_infer_body(UUID, "hello", Some("be terse"), Some(64));
assert_eq!(
body["messages"],
json!([
{"role": "system", "content": "be terse"},
{"role": "user", "content": "hello"}
])
);
assert_eq!(body["max_tokens"], json!(64));
}
#[test]
fn format_infer_output_renders_content_and_usage() {
let resp = json!({
"content": "Paris is the capital of France.",
"usage": {"prompt_tokens": 10, "completion_tokens": 8, "total_tokens": 18},
"provider": "specialized",
"charged": 0.0042
});
let out = format_infer_output(&resp);
assert!(out.starts_with("Paris is the capital of France."));
assert!(out.contains("18 tokens -> ¥0.0042 (provider: specialized)"));
}
#[test]
fn format_infer_output_defaults_on_missing_fields() {
let resp = json!({});
let out = format_infer_output(&resp);
assert!(out.contains("0 tokens -> ¥0 (provider: unknown)"));
}
fn hdr(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
#[test]
fn the_receipt_prints_worker_cost_and_balance_in_one_column() {
let headers = hdr(&[
("x-zakuro-request-id", "r1"),
("x-zakuro-worker", "gpu-04"),
("x-zakuro-cost", "0.012400"),
("x-zakuro-balance", "98.674900"),
]);
assert_eq!(
format_infer_receipt(&headers).unwrap(),
"→ X-Zakuro-Worker gpu-04\n\
→ X-Zakuro-Cost ¥0.0124\n\
→ X-Zakuro-Balance ¥98.6749"
);
}
#[test]
fn a_free_call_costs_zero_not_six_zeros() {
let headers = hdr(&[("X-Zakuro-Worker", "w"), ("X-Zakuro-Cost", "0.000000")]);
let r = format_infer_receipt(&headers).unwrap();
assert!(r.ends_with(" ¥0"), "{r}");
assert!(!r.contains("Balance"), "no balance, no line: {r}");
}
#[test]
fn without_receipt_headers_the_reply_falls_back_to_the_body() {
let resp =
json!({"content": "hi", "usage": {"total_tokens": 3}, "provider": "p", "charged": 0.0});
let out = format_infer_reply(&resp, &[]);
assert!(out.contains("3 tokens -> ¥0 (provider: p)"), "{out}");
let out = format_infer_reply(&resp, &hdr(&[("X-Zakuro-Cost", "0.5")]));
assert!(out.starts_with("hi\n\n→ X-Zakuro-Cost"), "{out}");
}
#[test]
fn format_infer_error_extracts_error_field() {
let body = r#"{"error": "model not found"}"#;
assert_eq!(format_infer_error(body), "model not found");
}
#[test]
fn format_infer_error_falls_back_to_raw_body() {
let body = "not json";
assert_eq!(format_infer_error(body), "not json");
}
#[test]
fn hub_body_defaults_max_tokens() {
let msgs = build_messages("hi", Some("sys"));
let b = build_hub_body(&msgs, None);
assert_eq!(b["max_tokens"], 256);
assert_eq!(b["messages"].as_array().unwrap().len(), 2);
assert!(b.get("model").is_none());
assert_eq!(build_hub_body(&msgs, Some(32))["max_tokens"], 32);
}
#[test]
fn hub_reply_parses_string_decimals() {
let body = r#"{"content":"hello","usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5},"charged":"0.001200","balance":"9.5"}"#;
let (resp, headers) = parse_hub_reply(body).unwrap();
assert_eq!(resp["content"], "hello");
assert_eq!(resp["provider"], "hub");
let out = format_infer_reply(&resp, &headers);
assert!(out.starts_with("hello\n\n"));
assert!(out.contains("X-Zakuro-Worker") && out.contains("hub"));
assert!(out.contains("¥0.0012"));
assert!(out.contains("¥9.5"));
assert!(format_infer_output(&resp).contains("5 tokens -> ¥0.0012 (provider: hub)"));
}
#[test]
fn hub_reply_rejects_garbage() {
assert!(parse_hub_reply("nope").is_err());
assert!(parse_hub_reply("{}").is_err());
}
#[test]
fn hub_errors_are_verbatim() {
assert_eq!(
format_hub_error(r#"{"detail":{"errors":["no committed runner for this model"]}}"#),
"no committed runner for this model (hub)"
);
assert_eq!(
format_hub_error(r#"{"detail":{"errors":["a","b"]}}"#),
"a; b (hub)"
);
assert_eq!(
format_hub_error(r#"{"detail":"Not found"}"#),
"Not found (hub)"
);
assert_eq!(format_hub_error("boom"), "boom (hub)");
}
#[test]
fn falls_back_only_on_no_provider_without_explicit_broker() {
let np = r#"{"error":"no provider serving zc://abc"}"#;
assert!(should_fall_back_to_hub(false, np));
assert!(!should_fall_back_to_hub(true, np));
assert!(!should_fall_back_to_hub(
false,
r#"{"error":"insufficient balance"}"#
));
assert!(!should_fall_back_to_hub(
false,
"broker request failed: timeout"
));
}
fn sv(a: &[&str]) -> Vec<String> {
a.iter().map(|s| s.to_string()).collect()
}
#[test]
fn file_and_prompt_are_exclusive() {
let a = sv(&[&format!("zc://{UUID}"), "-m", "hi", "--file", "a.wav"]);
assert!(parse_infer_args(&a)
.unwrap_err()
.contains("mutually exclusive"));
let a = sv(&[&format!("zc://{UUID}"), "--file", "a.wav", "-m", "hi"]);
assert!(parse_infer_args(&a)
.unwrap_err()
.contains("mutually exclusive"));
}
#[test]
fn neither_prompt_nor_file_is_a_usage_error() {
let a = sv(&[&format!("zc://{UUID}")]);
assert!(parse_infer_args(&a).unwrap_err().contains("--file"));
}
#[test]
fn parses_file_and_language() {
let a = sv(&[
&format!("zc://{UUID}"),
"--file",
"a.wav",
"--language",
"sn",
]);
let p = parse_infer_args(&a).unwrap();
assert_eq!(p.file.as_deref(), Some("a.wav"));
assert_eq!(p.language.as_deref(), Some("sn"));
assert_eq!(p.prompt, "");
}
#[test]
fn validates_language() {
for bad in ["S", "english", "EN", "e1", "", "sn-"] {
let a = sv(&[
&format!("zc://{UUID}"),
"--file",
"a.wav",
"--language",
bad,
]);
assert!(parse_infer_args(&a).is_err(), "{bad} should be rejected");
}
for ok in ["en", "sn", "lozi".get(..3).unwrap()] {
assert!(is_valid_language(ok));
}
let a = sv(&[&format!("zc://{UUID}"), "-m", "x", "--language", "en"]);
assert!(parse_infer_args(&a).unwrap_err().contains("--file"));
}
#[test]
fn content_type_from_extension() {
assert_eq!(audio_content_type("a.WAV"), "audio/wav");
assert_eq!(audio_content_type("/x/y.mp3"), "audio/mpeg");
assert_eq!(audio_content_type("a.flac"), "audio/flac");
assert_eq!(audio_content_type("a.m4a"), "audio/mp4");
assert_eq!(audio_content_type("a.ogg"), "audio/ogg");
assert_eq!(audio_content_type("a.webm"), "audio/webm");
assert_eq!(audio_content_type("a.bin"), "application/octet-stream");
assert_eq!(audio_content_type("noext"), "application/octet-stream");
}
#[test]
fn multipart_body_is_well_formed() {
let (ct, body) =
build_multipart("BND", "a\"b.wav", "audio/wav", &[0, 1, 2, 255], Some("sn"));
assert_eq!(ct, "multipart/form-data; boundary=BND");
let mut want = Vec::new();
want.extend_from_slice(
b"--BND\r\nContent-Disposition: form-data; name=\"language\"\r\n\r\nsn\r\n",
);
want.extend_from_slice(b"--BND\r\nContent-Disposition: form-data; name=\"file\"; filename=\"a_b.wav\"\r\nContent-Type: audio/wav\r\n\r\n");
want.extend_from_slice(&[0, 1, 2, 255]);
want.extend_from_slice(b"\r\n--BND--\r\n");
assert_eq!(body, want);
let (_, no_lang) = build_multipart("BND", "a.wav", "audio/wav", b"x", None);
assert!(!String::from_utf8_lossy(&no_lang).contains("language"));
}
#[test]
fn parses_transcribe_reply() {
let r = parse_transcribe_reply(
r#"{"text":" hello ","language":"en","duration_s":12.5,"billed_seconds":13,"truncated":true,"charged":"0.0130"}"#,
)
.unwrap();
assert_eq!(r.charged.as_deref(), Some("0.0130"));
assert!(r.truncated);
assert_eq!(r.billed_seconds, Some(13.0));
let out = format_transcribe_reply(&r);
assert!(out.starts_with("hello\n\n→ Language"));
assert!(out.contains("Duration 12.5 s"));
assert!(out.contains("Cost ¥0.013"));
assert!(out.contains("Warning: the audio exceeds the 10-minute limit"));
let r = parse_transcribe_reply(r#"{"text":"x"}"#).unwrap();
assert!(!r.truncated);
assert!(!format_transcribe_reply(&r).contains("Warning"));
assert!(parse_transcribe_reply("{}").is_err());
assert!(parse_transcribe_reply("nope").is_err());
}
#[test]
fn maps_transcribe_errors_verbatim() {
let e = format_hub_error(
r#"{"detail":{"errors":["This model transcribes audio. Use /transcribe."]}}"#,
);
assert_eq!(e, "This model transcribes audio. Use /transcribe. (hub)");
let e = format_hub_error(r#"{"detail":{"errors":["insufficient balance"]}}"#);
assert_eq!(e, "insufficient balance (hub)");
}
}