ChessPenguin 0.8.5: translation with a ChatGPT subscription works
Some checks failed
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run
Release / version (push) Has been cancelled
Release / linux (push) Has been cancelled
Release / flatpak (push) Has been cancelled
Release / windows (push) Has been cancelled
Release / macos (push) Has been cancelled
Release / publish (push) Has been cancelled

The plan's /v1/models answers {"models": [{"slug", "visibility", "priority"}]},
not the API's {"data": [{"id"}]}: no model was found and requests went out
with an empty model (HTTP 400). Both shapes are read now and OpenAI's preferred
chat model is taken; a job without a model picks one itself. Check failures
show in Settings › Translation; translation errors go to chesspenguin.log. The
offer starts at a sentence or two of foreign text, and text in brackets is
translated (only [%…] commands are kept, and they never reach the model).

Verified with the owner's subscription: models listed, French comments
translated into Russian with their moves intact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-21 22:33:08 +03:00
parent 2d732e52f9
commit 3fd98b40da
7 changed files with 131 additions and 28 deletions

View file

@ -504,27 +504,61 @@ pub fn models() -> Result<Vec<String>, Failure> {
}
let v: Value =
serde_json::from_str(&body).map_err(|e| Failure::Service(status, e.to_string()))?;
let mut ids: Vec<String> = v
.get("data")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|m| {
m.get("visibility")
Ok(model_list(&v))
}
/// The listed models, OpenAI's preferred first. The plan's answer is
/// `{"models": [{"slug", "visibility", "priority", "supported_in_api"}]}`; the API's
/// usual `{"data": [{"id"}]}` is read too.
fn model_list(v: &Value) -> Vec<String> {
let mut found: Vec<(i64, String)> = Vec::new();
for (key, name) in [("models", "slug"), ("data", "id")] {
for m in v.get(key).and_then(Value::as_array).into_iter().flatten() {
let listed = m
.get("visibility")
.and_then(Value::as_str)
.is_none_or(|s| s == "list")
})
.filter_map(|m| m.get("id").and_then(Value::as_str).map(str::to_owned))
.collect();
ids.sort();
Ok(ids)
.is_none_or(|s| s == "list");
let api = m
.get("supported_in_api")
.and_then(Value::as_bool)
.unwrap_or(true);
if let (true, true, Some(id)) = (listed, api, m.get(name).and_then(Value::as_str)) {
let priority = m
.get("priority")
.and_then(Value::as_i64)
.unwrap_or(i64::MAX);
found.push((priority, id.to_owned()));
}
}
}
found.sort_by_key(|(p, _)| *p);
found.into_iter().map(|(_, id)| id).collect()
}
/// The model to start with: a small fast one if listed (translation needs no more).
pub fn default_model(models: &[String]) -> Option<String> {
["mini", "fast", "flash"]
// OpenAI's preferred chat model (the list comes in its order); models for other
// work (code review, search, sound, pictures) do not take a plain text request.
const OTHER: [&str; 12] = [
"codex",
"search",
"research",
"audio",
"realtime",
"image",
"tts",
"transcribe",
"embedding",
"moderation",
"computer",
"review",
];
models
.iter()
.find_map(|w| models.iter().find(|m| m.contains(w)))
.find(|m| {
let m = m.to_lowercase();
!OTHER.iter().any(|w| m.contains(w))
})
.or_else(|| models.first())
.cloned()
}
@ -709,6 +743,31 @@ mod tests {
assert_eq!(nonce_of(&t).as_deref(), Some("n1"));
}
#[test]
fn the_plan_model_list_is_read() {
// The shape the plan's /v1/models answers with (seen 2026-10-21).
let v: Value = serde_json::from_str(
r#"{"models": [
{"slug": "gpt-6-luna", "visibility": "list", "priority": 5, "supported_in_api": true},
{"slug": "codex-auto-review", "visibility": "hide", "priority": 0, "supported_in_api": true},
{"slug": "gpt-6.1-sol", "visibility": "list", "priority": 1, "supported_in_api": true},
{"slug": "gpt-reserve", "visibility": "hide", "priority": 3}
]}"#,
)
.unwrap();
let list = model_list(&v);
assert_eq!(list, vec!["gpt-6.1-sol", "gpt-6-luna"]);
assert_eq!(default_model(&list).as_deref(), Some("gpt-6.1-sol"));
let api: Value = serde_json::from_str(r#"{"data": [{"id": "gpt-x"}]}"#).unwrap();
assert_eq!(model_list(&api), vec!["gpt-x"]);
let m = |v: &[&str]| default_model(&v.iter().map(|s| s.to_string()).collect::<Vec<_>>());
assert_eq!(
m(&["gpt-6.1-codex", "gpt-6.1-sol"]),
Some("gpt-6.1-sol".into())
);
assert_eq!(m(&[]), None);
}
#[test]
fn the_plan_scope_is_checked() {
let t = Tokens {

View file

@ -430,7 +430,7 @@ pub fn plan(texts: &[String], target: Lang) -> Option<Plan> {
.map(|(i, _)| i)
.collect();
let foreign_letters: usize = foreign.iter().map(|&i| detected[i].0).sum();
if foreign.len() < 3 && foreign_letters < 150 {
if foreign.len() < 3 && foreign_letters < 60 {
return None;
}
let source = letters
@ -595,7 +595,7 @@ fn instructions(target: Lang) -> String {
Rules:\n\
1. Translate only the natural-language text of each comment into {lang}.\n\
2. Copy every chess move and square exactly as written, character for character: e4, Nf3, Bxe5+, exd8=Q#, O-O, O-O-O, 12.Nf3, 12...Nf6, the d-file, the e5-square. Never translate, transliterate or replace the piece letters K, Q, R, B, N inside moves, and never add or remove moves.\n\
3. Keep the names of people, events and places as written; keep numbers, results (1-0, ½-½), evaluation symbols (+-, =, ±, ∓, !, ?, !?, ?!), URLs and anything in square brackets.\n\
3. Keep the names of people, events and places as written; keep numbers, results (1-0, ½-½), evaluation symbols (+-, =, ±, ∓, !, ?, !?, ?!) and URLs. Text in brackets is text: translate it too.\n\
4. A part that is already in {lang} stays as it is.\n\
5. Use the chess terms {lang}-speaking players use. Glossary: {glossary}.\n\
6. Do not add, drop, explain, summarize or comment on anything. Keep the tone, the paragraph breaks and the meaning.\n\
@ -1012,7 +1012,7 @@ fn lang_code(l: Lang) -> &'static str {
/// The format version is part of the key: new instructions give new translations.
fn key(text: &str) -> String {
let mut h = Sha256::new();
h.update(b"v1\0");
h.update(b"v2\0");
h.update(text.as_bytes());
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
@ -1186,6 +1186,24 @@ fn run(
}
}
}
// ChatGPT without a model yet (the check after the sign-in did not get that far).
if let Backend::ChatGpt { model } = &mut backend
&& model.is_empty()
{
match crate::chatgpt::models() {
Ok(m) => match crate::chatgpt::default_model(&m) {
Some(d) => *model = d,
None => {
let _ = tx.send(Event::Failed(Failure::NoModel(String::new())));
return;
}
},
Err(e) => {
let _ = tx.send(Event::Failed(e));
return;
}
}
}
let backend = &backend;
let mut batches: Vec<Vec<(usize, &str)>> = Vec::new();
let mut chars = 0;
@ -1262,6 +1280,12 @@ fn run(
mod tests {
use super::*;
#[test]
#[ignore = "prints the instructions for a manual check"]
fn print_instructions() {
println!("{}", instructions(Lang::Ru));
}
#[test]
fn moves_are_found_in_text() {
let t = "After 12.Nf3 Bxe5+ 13.dxe5 (13.O-O!?) the e5-square is weak; 14...Kh8.";

View file

@ -228,11 +228,7 @@ impl Hub {
let (models, model) = match connection {
Connection::ChatGpt => match crate::chatgpt::models() {
Ok(m) => {
let pick = if m.contains(&wanted) {
Some(wanted)
} else {
crate::chatgpt::default_model(&m)
};
let pick = crate::chatgpt::default_model(&m).or(Some(wanted));
(m, pick.unwrap_or_default())
}
Err(e) => {
@ -371,6 +367,9 @@ impl Hub {
}
}
let ok = c.result.is_ok();
if let Err(e) = &c.result {
crate::graphics::log(&format!("translation check via {}: {e}", s.service_id()));
}
self.check_result = Some(c.result);
let flow = self.resume || (self.setup_open && self.step == Step::Checking);
self.resume = false;
@ -1142,6 +1141,12 @@ impl Hub {
});
}
ChatGptState::SignedOut | ChatGptState::Unknown => {
if let Some(Err(e)) = &self.check_result
&& active
{
ui.label(RichText::new(failure_text(e, s)).color(warn))
.on_hover_text(e.to_string());
}
if active && ui.button(tr("Check")).clicked() {
self.start_check(ui.ctx(), s, now);
}
@ -1635,6 +1640,7 @@ impl GameTranslation {
}
}
Event::Failed(f) => {
crate::graphics::log(&format!("translation via {}: {f}", self.job_service));
match f {
Failure::PlanLimit => hub.chatgpt = ChatGptState::Limit,
Failure::SignedOut => hub.chatgpt = ChatGptState::SignedOut,