fix: improve model setup and native workflows
@@ -16,8 +16,8 @@
|
|||||||
"name": "iriz",
|
"name": "iriz",
|
||||||
"tagline": "Speak out loud and the text appears. Your Mac does the decoding, and nothing travels to somebody else's cloud.",
|
"tagline": "Speak out loud and the text appears. Your Mac does the decoding, and nothing travels to somebody else's cloud.",
|
||||||
"hero_alt": "Iris in white marble with marble wings beside the classical column, a gold ribbon of voice landing in the groove of her tablet",
|
"hero_alt": "Iris in white marble with marble wings beside the classical column, a gold ribbon of voice landing in the groove of her tablet",
|
||||||
"what": "This is a Mac app that types for you while you talk.\n\nHere is how it goes. You press one key, speak in your normal voice, press it again. The text lands where the cursor was: in an email, in a chat, in a search field. Nothing to switch to, no separate window.\n\nWhat sets it apart from similar apps is where the speech is decoded. Usually your voice travels to somebody's server, turns into text there and comes back. Here your Mac does the work, and the audio never leaves the machine.\n\n**Why «iriz».** Iris was the messenger of the Greek gods and the rainbow — a bridge between the sky and the ground. She does not invent the message, she carries it whole. The app does exactly that: it takes what you said and moves it into text, adding nothing of its own.\n\n\n\nIt does more. It fixes a phrase typed in the wrong keyboard layout. Correct a word after pasting and the app offers to remember the replacement. It strips hesitations and repetitions. It splits a meeting or a court hearing recording by voice and puts the minutes next to the audio.\n\n",
|
"what": "This is a Mac app that types for you while you talk.\n\nHere is how it goes. You press one key, speak in your normal voice, press it again. The text lands where the cursor was: in an email, in a chat, in a search field. Nothing to switch to, no separate window.\n\nWhat sets it apart from similar apps is where the speech is decoded. Usually your voice travels to somebody's server, turns into text there and comes back. Here your Mac does the work, and the audio never leaves the machine.\n\n**Why «iriz».** Iris was the messenger of the Greek gods and the rainbow — a bridge between the sky and the ground. She does not invent the message, she carries it whole. The app does exactly that: it takes what you said and moves it into text, adding nothing of its own.\n\n\n\nIt does more. It fixes a phrase typed in the wrong keyboard layout. Correct a word after pasting and the app offers to remember the replacement. It strips hesitations and repetitions. It splits a meeting or a court hearing recording by voice and puts the minutes next to the audio.\n\n\n\n\n",
|
||||||
"why": "Anyone who writes for a living loses hours to typing. The same thought comes out faster and whole when spoken: typing, you hunt for words; speaking, you do not.\n\nOne thing gets in the way. Cloud dictation cleans speech better than anything local, but what you said leaves the machine: a client call, a draft, names and figures. For a doctor, a lawyer, a therapist, that trade never pays off.\n\nSo here your Mac does the decoding, and the app reaches the network only when you press the button.",
|
"why": "Anyone who writes for a living loses hours to typing. The same thought comes out faster and whole when spoken: typing, you hunt for words; speaking, you do not.\n\nOne thing gets in the way. Cloud dictation cleans speech better than anything local, but what you said leaves the machine: a client call, a draft, names and figures. For a doctor, a lawyer, a therapist, that trade never pays off.\n\nSo here your Mac does the decoding, and the app reaches the network only when you press the button.\n\n\n",
|
||||||
"advantage": "your Mac decodes the speech, and during dictation the network is closed by a switch in the code rather than a promise in the text.",
|
"advantage": "your Mac decodes the speech, and during dictation the network is closed by a switch in the code rather than a promise in the text.",
|
||||||
"better": "The switch sits inside the recognition library and returns to its place even when a download fails. Documentation does not prove that: a script pins the set of networking symbols in the built binary and asks the kernel whether the running app holds a single socket.",
|
"better": "The switch sits inside the recognition library and returns to its place even when a download fails. Documentation does not prove that: a script pins the set of networking symbols in the built binary and asks the kernel whether the running app holds a single socket.",
|
||||||
"how": "Press the key, say your sentence, press again. The text lands where the cursor was blinking.\n\nA glass drop sits at the bottom of the screen the whole time. While you are silent it stays small. Start talking and a wave runs inside it: that is the answer to «can it hear me».\n\n\n\nPoint at it with the mouse and the drop opens into a row of buttons: record, prompt, translate, language, history, settings. The language switches right there, a second before you speak — no need to walk to the settings for it.\n\n\n\nIf pasting did not work, nothing is lost: the same plate opens into a panel and you take the text from there.\n\n",
|
"how": "Press the key, say your sentence, press again. The text lands where the cursor was blinking.\n\nA glass drop sits at the bottom of the screen the whole time. While you are silent it stays small. Start talking and a wave runs inside it: that is the answer to «can it hear me».\n\n\n\nPoint at it with the mouse and the drop opens into a row of buttons: record, prompt, translate, language, history, settings. The language switches right there, a second before you speak — no need to walk to the settings for it.\n\n\n\nIf pasting did not work, nothing is lost: the same plate opens into a panel and you take the text from there.\n\n",
|
||||||
@@ -117,8 +117,8 @@
|
|||||||
"name": "iriz",
|
"name": "iriz",
|
||||||
"tagline": "Говорите вслух, на экране появляется текст. Разбирает речь сам Мак, ничего не улетает в чужое облако.",
|
"tagline": "Говорите вслух, на экране появляется текст. Разбирает речь сам Мак, ничего не улетает в чужое облако.",
|
||||||
"hero_alt": "Ирида из белого мрамора с мраморными крыльями у классической колонны, золотая лента голоса ложится в борозду на табличке",
|
"hero_alt": "Ирида из белого мрамора с мраморными крыльями у классической колонны, золотая лента голоса ложится в борозду на табличке",
|
||||||
"what": "Это программа для Мака, которая печатает за вас, пока вы говорите.\n\nРаботает так. Вы нажимаете одну клавишу, говорите обычным голосом, нажимаете еще раз. Текст встает туда, где стоял курсор: в письмо, в чат, в поле поиска. Никуда переключаться не нужно, отдельного окна нет.\n\nГлавное отличие от похожих программ в том, где разбирается речь. Обычно голос уезжает на чужой сервер, там превращается в текст и возвращается. Здесь считает ваш Мак, и звук с машины не уходит.\n\n**Почему «iriz».** Ирида у греков — вестница богов и радуга, мост между небом и землей. Она не сочиняет послание, а доносит его целым. Программа делает ровно это: берет сказанное и переносит в текст, ничего не добавляя от себя.\n\n\n\nУмеет и другое. Чинит фразу, набранную не в той раскладке. Поправите слово после вставки, и программа предложит запомнить замену. Уберет из речи запинки и повторы. Разберет запись встречи или судебного заседания по голосам, а рядом со звуком положит готовый протокол.\n\n",
|
"what": "Это программа для Мака, которая печатает за вас, пока вы говорите.\n\nРаботает так. Вы нажимаете одну клавишу, говорите обычным голосом, нажимаете еще раз. Текст встает туда, где стоял курсор: в письмо, в чат, в поле поиска. Никуда переключаться не нужно, отдельного окна нет.\n\nГлавное отличие от похожих программ в том, где разбирается речь. Обычно голос уезжает на чужой сервер, там превращается в текст и возвращается. Здесь считает ваш Мак, и звук с машины не уходит.\n\n**Почему «iriz».** Ирида у греков — вестница богов и радуга, мост между небом и землей. Она не сочиняет послание, а доносит его целым. Программа делает ровно это: берет сказанное и переносит в текст, ничего не добавляя от себя.\n\n\n\nУмеет и другое. Чинит фразу, набранную не в той раскладке. Поправите слово после вставки, и программа предложит запомнить замену. Уберет из речи запинки и повторы. Разберет запись встречи или судебного заседания по голосам, а рядом со звуком положит готовый протокол.\n\n\n\n\n",
|
||||||
"why": "Кто много пишет по работе, тратит на набор часы. Голосом та же мысль выходит быстрее и целее: печатая, человек подбирает слова, говоря, не подбирает.\n\nМешает одно. Облачная диктовка чистит речь лучше любой местной, но наружу уезжает то, что вы сказали: разговор с клиентом, черновик документа, имена и суммы. Для врача, юриста, психолога такой обмен не окупается ничем.\n\nПоэтому тут разбирает Мак, а в сеть программа ходит только по вашей кнопке.",
|
"why": "Кто много пишет по работе, тратит на набор часы. Голосом та же мысль выходит быстрее и целее: печатая, человек подбирает слова, говоря, не подбирает.\n\nМешает одно. Облачная диктовка чистит речь лучше любой местной, но наружу уезжает то, что вы сказали: разговор с клиентом, черновик документа, имена и суммы. Для врача, юриста, психолога такой обмен не окупается ничем.\n\nПоэтому тут разбирает Мак, а в сеть программа ходит только по вашей кнопке.\n\n\n",
|
||||||
"advantage": "речь разбирает ваш Мак, и во время диктовки сеть закрыта рубильником в коде, а не обещанием в тексте.",
|
"advantage": "речь разбирает ваш Мак, и во время диктовки сеть закрыта рубильником в коде, а не обещанием в тексте.",
|
||||||
"better": "Рубильник стоит внутри библиотеки распознавания и возвращается на место даже когда загрузка падает. Проверяет это не документация: скрипт пинует набор сетевых символов в собранном бинарнике и спрашивает у ядра, есть ли у работающего приложения хоть один сокет.",
|
"better": "Рубильник стоит внутри библиотеки распознавания и возвращается на место даже когда загрузка падает. Проверяет это не документация: скрипт пинует набор сетевых символов в собранном бинарнике и спрашивает у ядра, есть ли у работающего приложения хоть один сокет.",
|
||||||
"how": "Нажали клавишу, сказали фразу, нажали еще раз. Текст встает туда, где мигал курсор.\n\nВнизу экрана все это время висит стеклянная капля. Пока вы молчите, она маленькая. Заговорили — внутри бежит волна: это и есть ответ на вопрос «слышит ли меня».\n\n\n\nНаведите на нее мышь — капля раскроется в ряд кнопок: запись, промпт, перевод, язык, история, настройки. Язык переключается здесь же, за секунду до того, как заговорить, и ходить за этим в настройки незачем.\n\n\n\nЕсли вставить не удалось, ничего не потеряно: та же плашка раскроется в панель, и текст можно забрать оттуда.\n\n",
|
"how": "Нажали клавишу, сказали фразу, нажали еще раз. Текст встает туда, где мигал курсор.\n\nВнизу экрана все это время висит стеклянная капля. Пока вы молчите, она маленькая. Заговорили — внутри бежит волна: это и есть ответ на вопрос «слышит ли меня».\n\n\n\nНаведите на нее мышь — капля раскроется в ряд кнопок: запись, промпт, перевод, язык, история, настройки. Язык переключается здесь же, за секунду до того, как заговорить, и ходить за этим в настройки незачем.\n\n\n\nЕсли вставить не удалось, ничего не потеряно: та же плашка раскроется в панель, и текст можно забрать оттуда.\n\n",
|
||||||
@@ -218,8 +218,8 @@
|
|||||||
"name": "iriz",
|
"name": "iriz",
|
||||||
"tagline": "你说出来,屏幕上就有字。识别由你自己的 Mac 完成,声音不会上传到别人的云。",
|
"tagline": "你说出来,屏幕上就有字。识别由你自己的 Mac 完成,声音不会上传到别人的云。",
|
||||||
"hero_alt": "白色大理石的伊里斯长着大理石翅膀,站在古典石柱旁,金色的声音丝带落进石板上的凹槽里",
|
"hero_alt": "白色大理石的伊里斯长着大理石翅膀,站在古典石柱旁,金色的声音丝带落进石板上的凹槽里",
|
||||||
"what": "这是一个 Mac 应用:你说话,它替你打字。\n\n用起来是这样。按一下键,用平常的声音说话,再按一下。文字会落在光标原来的位置:邮件里、聊天里、搜索框里。不用切换到别的地方,也没有单独的窗口。\n\n和同类应用最大的区别在于语音在哪里被解码。通常你的声音会被送到别人的服务器,在那里变成文字再回来。这里是你的 Mac 在计算,声音不会离开这台机器。\n\n**为什么叫「iriz」。** 伊里斯是希腊神话里众神的信使,也是彩虹——连接天与地的桥。她不编造消息,只把它完整地带到。这个应用做的正是这件事:把你说的话原样搬进文字,不添加自己的东西。\n\n\n\n它还会别的。它能修好用错键盘布局打出来的句子。粘贴之后你改了一个词,它会问要不要记住这个替换。它会去掉话里的停顿和重复。它能把会议或庭审录音按说话人分开,并在音频旁边放上写好的纪要。\n\n",
|
"what": "这是一个 Mac 应用:你说话,它替你打字。\n\n用起来是这样。按一下键,用平常的声音说话,再按一下。文字会落在光标原来的位置:邮件里、聊天里、搜索框里。不用切换到别的地方,也没有单独的窗口。\n\n和同类应用最大的区别在于语音在哪里被解码。通常你的声音会被送到别人的服务器,在那里变成文字再回来。这里是你的 Mac 在计算,声音不会离开这台机器。\n\n**为什么叫「iriz」。** 伊里斯是希腊神话里众神的信使,也是彩虹——连接天与地的桥。她不编造消息,只把它完整地带到。这个应用做的正是这件事:把你说的话原样搬进文字,不添加自己的东西。\n\n\n\n它还会别的。它能修好用错键盘布局打出来的句子。粘贴之后你改了一个词,它会问要不要记住这个替换。它会去掉话里的停顿和重复。它能把会议或庭审录音按说话人分开,并在音频旁边放上写好的纪要。\n\n\n\n\n",
|
||||||
"why": "靠写字吃饭的人,每天都有几个小时花在打字上。同一个想法,说出来更快也更完整:打字时人在挑词,说话时不挑。\n\n只有一件事挡在前面。云端听写把口语整理得比任何本地方案都干净,可你说的内容也随之离开了这台机器:和客户的通话、文件草稿、人名和金额。对医生、律师、心理咨询师来说,这笔交换怎么算都不划算。\n\n所以这里由你的 Mac 来识别,只有你按下按钮时,程序才会联网。",
|
"why": "靠写字吃饭的人,每天都有几个小时花在打字上。同一个想法,说出来更快也更完整:打字时人在挑词,说话时不挑。\n\n只有一件事挡在前面。云端听写把口语整理得比任何本地方案都干净,可你说的内容也随之离开了这台机器:和客户的通话、文件草稿、人名和金额。对医生、律师、心理咨询师来说,这笔交换怎么算都不划算。\n\n所以这里由你的 Mac 来识别,只有你按下按钮时,程序才会联网。\n\n\n",
|
||||||
"advantage": "识别在你自己的 Mac 上完成,口述期间网络由代码里的开关关闭,而不是靠文字承诺。",
|
"advantage": "识别在你自己的 Mac 上完成,口述期间网络由代码里的开关关闭,而不是靠文字承诺。",
|
||||||
"better": "开关叫 `DownloadUtils.enforceOffline`,位置在识别库内部,连下载失败的时候也会自己归位。光有文档不算数:自检脚本盯住编译好的二进制里那一组网络符号,再去问系统,运行中的应用手上有没有一个套接字。",
|
"better": "开关叫 `DownloadUtils.enforceOffline`,位置在识别库内部,连下载失败的时候也会自己归位。光有文档不算数:自检脚本盯住编译好的二进制里那一组网络符号,再去问系统,运行中的应用手上有没有一个套接字。",
|
||||||
"how": "按键,说一句话,再按一下。文字会落在光标闪烁的地方。\n\n这段时间里,屏幕下方一直有一颗玻璃水滴。你不说话时它很小。一开口,里面就有声波流动:这就是“它有没有听见我”的答案。\n\n\n\n把鼠标移上去,水滴会展开成一排按钮:录音、提示词、翻译、语言、历史、设置。语言就在这里切换,开口前一秒就能换,不用专门去设置里找。\n\n\n\n如果没能粘贴上,什么也不会丢:同一个浮窗会展开成面板,文字从那里拿走。\n\n",
|
"how": "按键,说一句话,再按一下。文字会落在光标闪烁的地方。\n\n这段时间里,屏幕下方一直有一颗玻璃水滴。你不说话时它很小。一开口,里面就有声波流动:这就是“它有没有听见我”的答案。\n\n\n\n把鼠标移上去,水滴会展开成一排按钮:录音、提示词、翻译、语言、历史、设置。语言就在这里切换,开口前一秒就能换,不用专门去设置里找。\n\n\n\n如果没能粘贴上,什么也不会丢:同一个浮窗会展开成面板,文字从那里拿走。\n\n",
|
||||||
|
|||||||
@@ -21,26 +21,26 @@
|
|||||||
"bible": {
|
"bible": {
|
||||||
"character_sheet": {
|
"character_sheet": {
|
||||||
"published_path": "docs/assets/pantheon/bible-character.png",
|
"published_path": "docs/assets/pantheon/bible-character.png",
|
||||||
"published_sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af",
|
"published_sha256": "2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e",
|
||||||
"alt": "Карта персонажа: Ирида из белого мрамора в четырех видах с мраморными крыльями, жезлом вестницы, табличкой и золотой лентой голоса, рядом этюды предметов"
|
"alt": "Карта персонажа: Ирида из белого мрамора в четырех видах с мраморными крыльями, жезлом вестницы, табличкой и золотой лентой голоса, рядом этюды предметов"
|
||||||
},
|
},
|
||||||
"prop_sheet": {
|
"prop_sheet": {
|
||||||
"published_path": "docs/assets/pantheon/bible-props.png",
|
"published_path": "docs/assets/pantheon/bible-props.png",
|
||||||
"published_sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152",
|
"published_sha256": "7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e",
|
||||||
"alt": "Карта предметов: жезл с гладким кольцом, мраморная табличка с одной бороздой, крылатая сандалия, золотая лента голоса, мраморная клавиша и чаша на слоновой кости"
|
"alt": "Карта предметов: жезл с гладким кольцом, мраморная табличка с одной бороздой, крылатая сандалия, золотая лента голоса, мраморная клавиша и чаша на слоновой кости"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"hero": {
|
"hero": {
|
||||||
"source_path": "docs/assets/pantheon/hero-source.png",
|
"source_path": "docs/assets/pantheon/hero-source.png",
|
||||||
"source_sha256": "9fa6a4e6ae3867707636ac60f781603c46bae45e64217373922119b9503683c5",
|
"source_sha256": "d2bf33d71b0068c8af26e6a8b12cc49c9c6e3f037c2aa51e9e8b4dca359fc4b1",
|
||||||
"published_path": "docs/assets/pantheon/hero.png",
|
"published_path": "docs/assets/pantheon/hero.png",
|
||||||
"published_sha256": "ff02cfbef989f040db9e729265b84636ff0a94f5120718d1e94a066bc4381fb4"
|
"published_sha256": "5c8c42c7758c737b47af8d4702b1f5a96ab54bae94565cdd1bfa4e919b29496d"
|
||||||
},
|
},
|
||||||
"emblem": {
|
"emblem": {
|
||||||
"source_path": "docs/assets/pantheon/emblem-source.png",
|
"source_path": "docs/assets/pantheon/emblem-source.png",
|
||||||
"source_sha256": "e228f8333ee8d6752f4f2ad7c08229ca65bc4060f50d154f10d5c401490b220b",
|
"source_sha256": "1d56460678f01b8e944b46057cee68e486edbbedf9335f3cd6a899fd6b1b40f1",
|
||||||
"published_path": "docs/assets/pantheon/emblem.png",
|
"published_path": "docs/assets/pantheon/emblem.png",
|
||||||
"published_sha256": "daf6fd93f9ab2aa98274b0085be08b1e0a47042873b358cd550639cbdfbc6d47"
|
"published_sha256": "915d77676dbf1ff062ba13e0f0087f4202570e7bc7aba51c1a766293c660e820"
|
||||||
},
|
},
|
||||||
"takt": {
|
"takt": {
|
||||||
"source_path": "docs/assets/pantheon/takt.png",
|
"source_path": "docs/assets/pantheon/takt.png",
|
||||||
@@ -100,9 +100,9 @@
|
|||||||
"diagram_ru": "Разбор",
|
"diagram_ru": "Разбор",
|
||||||
"diagram_zh": "识别",
|
"diagram_zh": "识别",
|
||||||
"source_path": "docs/assets/pantheon/workflow/03-decode.png",
|
"source_path": "docs/assets/pantheon/workflow/03-decode.png",
|
||||||
"source_sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd",
|
"source_sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc",
|
||||||
"published_path": "docs/assets/pantheon/workflow/03-decode.png",
|
"published_path": "docs/assets/pantheon/workflow/03-decode.png",
|
||||||
"published_sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd"
|
"published_sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "insert",
|
"id": "insert",
|
||||||
@@ -113,15 +113,15 @@
|
|||||||
"diagram_ru": "Текст",
|
"diagram_ru": "Текст",
|
||||||
"diagram_zh": "落字",
|
"diagram_zh": "落字",
|
||||||
"source_path": "docs/assets/pantheon/workflow/04-insert.png",
|
"source_path": "docs/assets/pantheon/workflow/04-insert.png",
|
||||||
"source_sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc",
|
"source_sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680",
|
||||||
"published_path": "docs/assets/pantheon/workflow/04-insert.png",
|
"published_path": "docs/assets/pantheon/workflow/04-insert.png",
|
||||||
"published_sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc"
|
"published_sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"doc_frames": {
|
"doc_frames": {
|
||||||
"contributing": {
|
"contributing": {
|
||||||
"published_path": "docs/assets/pantheon/doc-contributing.png",
|
"published_path": "docs/assets/pantheon/doc-contributing.png",
|
||||||
"published_sha256": "d1cfa5ca7a5a50a3492d90e2f9ac5a07a7481b8e450031fe303c2718a87ba133",
|
"published_sha256": "583b69a545c9afed6a496ae74b8867d111b63c15282b48f83e209a621b5c73ca",
|
||||||
"alt": "Две одинаковые мраморные таблички на низком столе, в левой лежит золотая лента голоса, правая пустая и ждет, рядом стоит жезл вестницы",
|
"alt": "Две одинаковые мраморные таблички на низком столе, в левой лежит золотая лента голоса, правая пустая и ждет, рядом стоит жезл вестницы",
|
||||||
"pages": {
|
"pages": {
|
||||||
"en": "CONTRIBUTING.md",
|
"en": "CONTRIBUTING.md",
|
||||||
@@ -188,6 +188,24 @@
|
|||||||
"docs/assets/pantheon/window-wash-source.png"
|
"docs/assets/pantheon/window-wash-source.png"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
],
|
||||||
|
"inserts": [
|
||||||
|
{
|
||||||
|
"role": "desk-firstrun",
|
||||||
|
"published_path": "docs/assets/pantheon/desk-firstrun.png",
|
||||||
|
"published_sha256": "64c84c628ebc7cdb856b62b38614eea882693b0a56ecacccc702362485ebed67",
|
||||||
|
"alt": "Ирида за мраморным столом: на экране ноутбука первый экран знакомства iriz с плашкой и волной",
|
||||||
|
"screen_source": "docs/assets/shots/firstrun-ru.png",
|
||||||
|
"scene_source": "docs/assets/pantheon/doc-desk-source.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "desk-history",
|
||||||
|
"published_path": "docs/assets/pantheon/desk-history.png",
|
||||||
|
"published_sha256": "749780636be9e7614d38aec56fd8156ffcc6492ee2d29720b014221e56d13d0f",
|
||||||
|
"alt": "Мраморный ноутбук крупно: на экране окно истории надиктовок iriz со списком и поиском",
|
||||||
|
"screen_source": "docs/assets/shots/history-ru.png",
|
||||||
|
"scene_source": "docs/assets/pantheon/doc-desk-close-source.png"
|
||||||
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"receipts": {
|
"receipts": {
|
||||||
|
|||||||
@@ -14,11 +14,11 @@ Constraints, and these are the identity of the figure and must be identical in a
|
|||||||
- Large carved marble wings rise from her shoulders, folded close to her back, feathers cut as real overlapping plates. The wings are marble, never feathers of cloth, and they are present in every view.
|
- Large carved marble wings rise from her shoulders, folded close to her back, feathers cut as real overlapping plates. The wings are marble, never feathers of cloth, and they are present in every view.
|
||||||
- She wears winged sandals: a low marble sandal on each foot with a small carved wing at the ankle, both feet flat on the ground.
|
- She wears winged sandals: a low marble sandal on each foot with a small carved wing at the ankle, both feet flat on the ground.
|
||||||
- She HOLDS the herald staff in her right hand: a slender muted-gold staff as tall as her shoulder, its butt end resting on the ground beside her right foot and casting a shadow, her fingers closed around the shaft. The head of the staff is a plain smooth ring, with NO snakes, NO wings and NO letters.
|
- She HOLDS the herald staff in her right hand: a slender muted-gold staff as tall as her shoulder, its butt end resting on the ground beside her right foot and casting a shadow, her fingers closed around the shaft. The head of the staff is a plain smooth ring, with NO snakes, NO wings and NO letters.
|
||||||
- She HOLDS the marble writing tablet in her left hand: a flat rectangular white-marble tablet the size of a forearm, gripped along its lower edge by her closed fingers, held at waist height, its face turned slightly toward the viewer. The tablet face carries ONE carved horizontal groove and nothing else: no letters, no digits, no emblem.
|
- She HOLDS the marble writing tablet in her left hand: a flat rectangular white-marble tablet the size of a forearm, gripped along its lower edge by her closed fingers, held at waist height, its face turned slightly toward the viewer. The tablet face carries ONE sound wave and nothing else: a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends. No letters, no digits, no emblem.
|
||||||
- A single muted-gold ribbon of voice rises from just below her chin, curves once through the air and lands flat on the face of the tablet, ending inside the carved groove. It is one continuous ribbon, it touches the tablet, and it never breaks into pieces and never floats away from her.
|
- A single muted-gold ribbon of voice rises from just below her chin, curves once through the air and lands flat on the face of the tablet, where it resolves into that sound wave of gold bars. It is one continuous ribbon, it touches the tablet, and it never breaks into pieces and never floats away from her.
|
||||||
- Three thin sky-blue paths run along the ground from the left edge of the frame and CONVERGE at the butt of the herald staff. They lie flat on the ground, touch it along their whole length, and end at the staff; they never rise into the air.
|
- Three thin sky-blue paths run along the ground from the left edge of the frame and CONVERGE at the butt of the herald staff. They lie flat on the ground, touch it along their whole length, and end at the staff; they never rise into the air.
|
||||||
- She stands on a round marble base whose full underside rests on the ground.
|
- She stands on a round marble base whose full underside rests on the ground.
|
||||||
- Every view shows the same person wearing the SAME costume: one chiton, one mantle over the same shoulder, one belt at the same height, wings of the same span. The staff shown alone in the study below is the SAME OBJECT she holds: same length, same plain ring head. The tablet shown alone is the same tablet with the same single groove. The sandal shown alone is the same sandal. Nothing changes between views except the angle of the camera.
|
- Every view shows the same person wearing the SAME costume: one chiton, one mantle over the same shoulder, one belt at the same height, wings of the same span. The staff shown alone in the study below is the SAME OBJECT she holds: same length, same plain ring head. The tablet shown alone is the same tablet with the same single sound wave. The sandal shown alone is the same sandal. Nothing changes between views except the angle of the camera.
|
||||||
- Anatomically correct hands with exactly five fingers, natural finger lengths and one clearly readable thumb, fingers not fused.
|
- Anatomically correct hands with exactly five fingers, natural finger lengths and one clearly readable thumb, fingers not fused.
|
||||||
- Nothing hovers, nothing balances on a point: everything carried is held by a closed hand, everything standing rests on a surface and casts a shadow.
|
- Nothing hovers, nothing balances on a point: everything carried is held by a closed hand, everything standing rests on a surface and casts a shadow.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ Use case: stylized-concept
|
|||||||
Asset type: prop reference sheet for a project of the Olympuz family, binding for every later frame
|
Asset type: prop reference sheet for a project of the Olympuz family, binding for every later frame
|
||||||
Primary request: one wide sheet that fixes the objects of this project once and for all, so each one can be reproduced identically in every later scene.
|
Primary request: one wide sheet that fixes the objects of this project once and for all, so each one can be reproduced identically in every later scene.
|
||||||
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column.
|
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column.
|
||||||
Subject: six objects laid out on a plain ivory surface, each shown alone, each large enough to read: (1) the herald staff, a slender muted-gold rod as long as a forearm with a plain smooth ring at its head; (2) the marble writing tablet, a flat rectangular white-marble slab with ONE carved horizontal groove across its face; (3) the winged sandal, a low white-marble sandal with a small carved wing at the ankle; (4) the gold voice ribbon alone, one continuous muted-gold band curving once and lying flat at its lower end; (5) a white-marble key-cap, a cube of marble with softly rounded corners and one shallow round dish carved into its top face; (6) a small white-marble bowl of the same family as the other pieces, empty, its full base resting on the surface.
|
Subject: six objects laid out on a plain ivory surface, each shown alone, each large enough to read: (1) the herald staff, a slender muted-gold rod as long as a forearm with a plain smooth ring at its head; (2) the marble writing tablet, a flat rectangular white-marble slab whose face carries ONE row of slender upright muted-gold bars of different heights - a sound wave, tallest at the centre and tapering smoothly to short bars at both ends, evenly spaced and standing clear of one another; (3) the winged sandal, a low white-marble sandal with a small carved wing at the ankle; (4) the gold voice ribbon alone, one continuous muted-gold band curving once and lying flat at its lower end; (5) a white-marble key-cap, a cube of marble with softly rounded corners and one shallow round dish carved into its top face; (6) a small white-marble bowl of the same family as the other pieces, empty, its full base resting on the surface.
|
||||||
Composition/framing: 16:9 landscape. A classical white-marble column stands at the far right as the family signature, clearly separated from the objects. The six objects sit in two rows of three with equal spacing, each fully inside the frame, nothing overlapping, nothing cropped. Generous empty ivory space between them.
|
Composition/framing: 16:9 landscape. A classical white-marble column stands at the far right as the family signature, clearly separated from the objects. The six objects sit in two rows of three with equal spacing, each fully inside the frame, nothing overlapping, nothing cropped. Generous empty ivory space between them.
|
||||||
Style/medium: premium restrained 3D marble and gold render, physically plausible materials, warm ivory Apple-like presentation, museum plate feeling
|
Style/medium: premium restrained 3D marble and gold render, physically plausible materials, warm ivory Apple-like presentation, museum plate feeling
|
||||||
Lighting/mood: soft daylight from upper left, long gentle shadows, identical lighting on every object. Gold surfaces glow softly FROM WITHIN, never lit by a lamp, a neon tube or a hard rim light.
|
Lighting/mood: soft daylight from upper left, long gentle shadows, identical lighting on every object. Gold surfaces glow softly FROM WITHIN, never lit by a lamp, a neon tube or a hard rim light.
|
||||||
@@ -10,7 +10,7 @@ Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9
|
|||||||
Constraints:
|
Constraints:
|
||||||
- Every object rests on the surface and casts a shadow. Nothing hovers, nothing balances on a point.
|
- Every object rests on the surface and casts a shadow. Nothing hovers, nothing balances on a point.
|
||||||
- The staff head is a plain smooth ring: NO snakes, NO wings, NO letters, NO engraving.
|
- The staff head is a plain smooth ring: NO snakes, NO wings, NO letters, NO engraving.
|
||||||
- The tablet carries exactly ONE groove and no writing of any kind.
|
- The tablet carries exactly ONE sound wave of gold bars and no writing of any kind. The bars read as sound, not as a chart: no frame, no axis, no baseline, no ruler marks.
|
||||||
- The gold ribbon is one continuous piece, not a chain and not a string of segments.
|
- The gold ribbon is one continuous piece, not a chain and not a string of segments.
|
||||||
- The key-cap is marble, not plastic, and its dish is shallow and smooth.
|
- The key-cap is marble, not plastic, and its dish is shallow and smooth.
|
||||||
- These are the SAME objects that the character sheet shows in her hands: same proportions, same materials, same details.
|
- These are the SAME objects that the character sheet shows in her hands: same proportions, same materials, same details.
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ Use case: stylized-concept
|
|||||||
Asset type: document page frame for the contributing page of a project of the Olympuz family
|
Asset type: document page frame for the contributing page of a project of the Olympuz family
|
||||||
Primary request: one wide frame for the page that explains how somebody else can help - a second tablet is placed beside the first, so the reader sees room made for their work.
|
Primary request: one wide frame for the page that explains how somebody else can help - a second tablet is placed beside the first, so the reader sees room made for their work.
|
||||||
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the tablet, the herald staff and the gold ribbon must match those sheets exactly.
|
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the tablet, the herald staff and the gold ribbon must match those sheets exactly.
|
||||||
Subject: two marble writing tablets of the same size lie side by side on a low marble table at the centre of the frame, each with its single carved groove facing the viewer. One continuous muted-gold ribbon curves down from the upper left and ends inside the groove of the left tablet; the right tablet is empty and waiting. The herald staff rests upright against the right end of the table, its butt on the ground.
|
Subject: two marble writing tablets of the same size lie side by side on a low marble table at the centre of the frame, each with its face turned toward the viewer. One continuous muted-gold ribbon curves down from the upper left and ends on the left tablet, where it resolves into a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends; the right tablet is bare marble and waiting. The herald staff rests upright against the right end of the table, its butt on the ground.
|
||||||
Composition/framing: 16:9 landscape. The table with both tablets reads clearly at the centre. A classical white-marble column stands at the far right as the family signature. Generous empty ivory space, no figure in this frame, nothing cropped.
|
Composition/framing: 16:9 landscape. The table with both tablets reads clearly at the centre. A classical white-marble column stands at the far right as the family signature. Generous empty ivory space, no figure in this frame, nothing cropped.
|
||||||
Style/medium: premium restrained 3D marble render, physically plausible materials, warm ivory Apple-like presentation
|
Style/medium: premium restrained 3D marble render, physically plausible materials, warm ivory Apple-like presentation
|
||||||
Lighting/mood: soft daylight from upper left, long gentle shadows, calm. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
Lighting/mood: soft daylight from upper left, long gentle shadows, calm. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
||||||
@@ -12,5 +12,5 @@ Constraints:
|
|||||||
- Both tablets rest on the table, the table rests on the ground, the staff touches the ground. Nothing hovers, everything casts a shadow.
|
- Both tablets rest on the table, the table rests on the ground, the staff touches the ground. Nothing hovers, everything casts a shadow.
|
||||||
- The two tablets are identical in size and thickness: the second is room made for somebody else, not a smaller copy.
|
- The two tablets are identical in size and thickness: the second is room made for somebody else, not a smaller copy.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
Avoid: figures, faces, rainbow of many colors, prismatic colors, screens, keyboards, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels
|
Avoid: owl, bird, any animal, figures, faces, rainbow of many colors, prismatic colors, screens, keyboards, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels
|
||||||
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"_": "Углы экрана в docs/assets/pantheon/doc-desk-close-source.png. Померены по строкам 07.09.2026: левый край идёт от 502 вверху к 493 внизу, правый от 1167 к 1173, верх 211, низ 609.",
|
||||||
|
"ekran": [
|
||||||
|
[
|
||||||
|
503,
|
||||||
|
211
|
||||||
|
],
|
||||||
|
[
|
||||||
|
1167,
|
||||||
|
211
|
||||||
|
],
|
||||||
|
[
|
||||||
|
1174,
|
||||||
|
609
|
||||||
|
],
|
||||||
|
[
|
||||||
|
492,
|
||||||
|
609
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
Use case: stylized-concept
|
||||||
|
Asset type: wide documentation frame for a project of the Olympuz family
|
||||||
|
Primary request: one wide scene of the workplace itself - the marble laptop stands ready and its screen is a blank flat panel waiting for the product picture to be placed into it by a separate instrument.
|
||||||
|
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project prop sheet - the herald staff and the gold voice ribbon must match that sheet exactly.
|
||||||
|
Subject: an open laptop carved from white marble stands alone at the centre of a low white-marble table: a thin base with a plain flat lid raised at a comfortable angle. THE SCREEN IS COMPLETELY BLANK - a smooth flat ivory panel with a clean rectangular border, no image, no glow, no reflection, no carving, nothing on it at all. The muted-gold herald staff lies flat on the table beside the laptop, and one continuous muted-gold ribbon of voice curves in from the left and ends at the lower edge of the screen without crossing onto it. No figure is present.
|
||||||
|
Composition/framing: 16:9 landscape, the laptop close to the viewer and filling the middle half of the frame, its screen large, flat and facing the viewer almost straight on, all four corners clearly visible and unobstructed. Generous empty ivory space above. A classical white-marble column stands at the right as the family signature. Nothing overlaps the screen. Nothing is cropped by any edge.
|
||||||
|
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery and real weight, physically plausible materials, warm ivory Apple-like presentation
|
||||||
|
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. The gold ribbon and the gold fittings glow softly FROM WITHIN, as if lit by their own material, never by a lamp or a hard rim light.
|
||||||
|
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the voice ribbon and the metal fittings only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
|
||||||
|
Constraints:
|
||||||
|
- The laptop is carved marble, not a real device: no logo, no ports, no rubber feet, no camera dot, no key legends. Its keys are plain shallow squares of marble.
|
||||||
|
- The screen panel is EMPTY and FLAT and evenly lit, with a clear thin border all around, because a real screenshot of the product is placed into it afterwards. Any picture generated on it would be invented interface.
|
||||||
|
- The screen is a flat plane. It is not curved, not tilted away from the viewer, and none of its four corners is hidden by a hand, a wing, the staff or the ribbon.
|
||||||
|
- Everything carried is held by a closed hand. Everything standing rests on the ground and casts a shadow. Nothing hovers.
|
||||||
|
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, exactly as on the character sheet.
|
||||||
|
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
||||||
|
- No modern devices other than this marble laptop: no phones, no cables, no microphones, no mouse.
|
||||||
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
|
Avoid: owl, bird, any animal, glowing screen, picture on the screen, reflection on the screen, screen bezel with a logo, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, scales, sword, spear, hearth, fire, floating staff, floating laptop, a ribbon floating free of the figure, cloth wings, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
||||||
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image, and nothing at all on the screen.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"_": "Углы экрана в docs/assets/pantheon/doc-desk-source.png. Померены по строкам 07.09.2026: экран прямоугольный, левый край 714, правый 1152, верх 257, низ 538. Прежняя запись врала на 36 точек по нижнему левому углу, и снимок вставал наискось.",
|
||||||
|
"ekran": [
|
||||||
|
[
|
||||||
|
714,
|
||||||
|
257
|
||||||
|
],
|
||||||
|
[
|
||||||
|
1152,
|
||||||
|
257
|
||||||
|
],
|
||||||
|
[
|
||||||
|
1152,
|
||||||
|
538
|
||||||
|
],
|
||||||
|
[
|
||||||
|
714,
|
||||||
|
538
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
Use case: stylized-concept
|
||||||
|
Asset type: wide documentation frame for a project of the Olympuz family
|
||||||
|
Primary request: one wide scene that shows where the work actually happens - the messenger sits at her own table with a laptop open in front of her, and the laptop screen is a blank flat panel waiting for the product picture to be placed into it by a separate instrument.
|
||||||
|
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet - the figure, her costume, her wings, the herald staff and the gold voice ribbon must match that sheet exactly.
|
||||||
|
Subject: Iris sits on a low white-marble bench behind a low white-marble table, turned three-quarters toward the viewer, her marble wings folded close to her back. On the table in front of her stands an open laptop carved from the same white marble: a thin base with a plain flat lid raised at a comfortable angle. THE SCREEN IS COMPLETELY BLANK - a smooth flat ivory panel with a clean rectangular border, no image, no glow, no reflection, no carving, nothing on it at all. Her left hand rests flat on the table beside the laptop, her right hand holds the herald staff upright, its butt on the ground beside the bench. One continuous muted-gold ribbon of voice rises from just below her chin and curves once toward the laptop, ending at the lower edge of the screen without crossing onto it.
|
||||||
|
Composition/framing: 16:9 landscape, the laptop screen large, flat and facing the viewer almost straight on, its four corners all clearly visible and unobstructed. The figure occupies the left third, the laptop the middle, generous empty ivory space above. A classical white-marble column stands at the right as the family signature, clearly separated from the figure. Nothing overlaps the screen. Nothing is cropped by any edge.
|
||||||
|
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery and real weight, physically plausible materials, warm ivory Apple-like presentation
|
||||||
|
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. The gold ribbon and the gold fittings glow softly FROM WITHIN, as if lit by their own material, never by a lamp or a hard rim light.
|
||||||
|
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the voice ribbon and the metal fittings only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
|
||||||
|
Constraints:
|
||||||
|
- The laptop is carved marble, not a real device: no logo, no ports, no rubber feet, no camera dot, no key legends. Its keys are plain shallow squares of marble.
|
||||||
|
- The screen panel is EMPTY and FLAT and evenly lit, with a clear thin border all around, because a real screenshot of the product is placed into it afterwards. Any picture generated on it would be invented interface.
|
||||||
|
- The screen is a flat plane. It is not curved, not tilted away from the viewer, and none of its four corners is hidden by a hand, a wing, the staff or the ribbon.
|
||||||
|
- Everything carried is held by a closed hand. Everything standing rests on the ground and casts a shadow. Nothing hovers.
|
||||||
|
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, exactly as on the character sheet.
|
||||||
|
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
||||||
|
- No modern devices other than this marble laptop: no phones, no cables, no microphones, no mouse.
|
||||||
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
|
Avoid: owl, bird, any animal, glowing screen, picture on the screen, reflection on the screen, screen bezel with a logo, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, scales, sword, spear, hearth, fire, floating staff, floating laptop, a ribbon floating free of the figure, cloth wings, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
||||||
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image, and nothing at all on the screen.
|
||||||
@@ -2,7 +2,7 @@ Use case: stylized-concept
|
|||||||
Asset type: document page frame for the first-steps page of a project of the Olympuz family
|
Asset type: document page frame for the first-steps page of a project of the Olympuz family
|
||||||
Primary request: one wide frame for the page that walks a newcomer through the first install - the messenger sets her tablet down within reach and steps back, so the reader sees an invitation rather than a performance.
|
Primary request: one wide frame for the page that walks a newcomer through the first install - the messenger sets her tablet down within reach and steps back, so the reader sees an invitation rather than a performance.
|
||||||
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the figure, the herald staff, the marble tablet and the gold ribbon must match those sheets exactly.
|
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the figure, the herald staff, the marble tablet and the gold ribbon must match those sheets exactly.
|
||||||
Subject: the marble writing tablet lies flat on a low marble table at the centre of the frame, its single carved groove facing the viewer, with one continuous muted-gold ribbon curving down from the upper left and ending inside that groove. Iris stands to the left of the table, turned three-quarters toward it, her right hand closed around the herald staff whose butt rests on the ground, her left hand open and lowered, having just set the tablet down.
|
Subject: the marble writing tablet lies flat on a low marble table at the centre of the frame, its face turned toward the viewer, with one continuous muted-gold ribbon curving down from the upper left and ending on that face, where it resolves into a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends. Iris stands to the left of the table, turned three-quarters toward it, her right hand closed around the herald staff whose butt rests on the ground, her left hand open and lowered, having just set the tablet down.
|
||||||
Composition/framing: 16:9 landscape. The tablet reads clearly at the centre, the figure occupies the left third and never overlaps the tablet. A classical white-marble column stands at the far right as the family signature. Generous empty ivory space, nothing cropped.
|
Composition/framing: 16:9 landscape. The tablet reads clearly at the centre, the figure occupies the left third and never overlaps the tablet. A classical white-marble column stands at the far right as the family signature. Generous empty ivory space, nothing cropped.
|
||||||
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery, physically plausible materials, warm ivory Apple-like presentation
|
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery, physically plausible materials, warm ivory Apple-like presentation
|
||||||
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
||||||
@@ -13,5 +13,5 @@ Constraints:
|
|||||||
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
||||||
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating tablet, floating staff, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating tablet, floating staff, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
||||||
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ Use case: stylized-concept
|
|||||||
Asset type: square emblem for a project of the Olympuz family
|
Asset type: square emblem for a project of the Olympuz family
|
||||||
Primary request: one square emblem that reads at a glance and stays readable when shrunk - the messenger's staff and the voice becoming a written line.
|
Primary request: one square emblem that reads at a glance and stays readable when shrunk - the messenger's staff and the voice becoming a written line.
|
||||||
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the herald staff, the marble tablet and the gold ribbon must match those sheets exactly.
|
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the herald staff, the marble tablet and the gold ribbon must match those sheets exactly.
|
||||||
Subject: a single composition on a plain ivory ground: the marble writing tablet lying flat and slightly tilted toward the viewer, the muted-gold herald staff resting diagonally across its upper corner, and one continuous muted-gold ribbon curving down from the upper left and ending flat inside the single carved groove on the tablet face.
|
Subject: a single composition on a plain ivory ground: the marble writing tablet lying flat and slightly tilted toward the viewer, the muted-gold herald staff resting diagonally across its upper corner, and one continuous muted-gold ribbon curving down from the upper left and ending flat on the tablet face, where it resolves into a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends.
|
||||||
Composition/framing: perfect square, the composition centred with generous empty ivory margin on all four sides, nothing cropped, no column in this frame.
|
Composition/framing: perfect square, the composition centred with generous empty ivory margin on all four sides, nothing cropped, no column in this frame.
|
||||||
Style/medium: premium restrained 3D marble and gold render, physically plausible materials, warm ivory Apple-like presentation
|
Style/medium: premium restrained 3D marble and gold render, physically plausible materials, warm ivory Apple-like presentation
|
||||||
Lighting/mood: soft daylight from upper left, one gentle shadow under each object. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
Lighting/mood: soft daylight from upper left, one gentle shadow under each object. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
||||||
@@ -11,8 +11,8 @@ Constraints:
|
|||||||
- Only three objects in the frame: tablet, staff, ribbon. Nothing else.
|
- Only three objects in the frame: tablet, staff, ribbon. Nothing else.
|
||||||
- Every object rests on the surface and casts a shadow. Nothing hovers.
|
- Every object rests on the surface and casts a shadow. Nothing hovers.
|
||||||
- The staff head is a plain smooth ring with no snakes, no wings and no engraving.
|
- The staff head is a plain smooth ring with no snakes, no wings and no engraving.
|
||||||
- The tablet face carries exactly one groove and no writing.
|
- The tablet face carries exactly one sound wave of gold bars and no writing.
|
||||||
- The shapes stay large and simple so the emblem survives being shrunk to a small icon.
|
- The shapes stay large and simple so the emblem survives being shrunk to a small icon.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
Avoid: rainbow of many colors, prismatic colors, figures, faces, wings of cloth, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels
|
Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, figures, faces, wings of cloth, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels
|
||||||
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
||||||
|
|||||||
@@ -11,10 +11,10 @@
|
|||||||
"tier": "frontier"
|
"tier": "frontier"
|
||||||
},
|
},
|
||||||
"quality": "highest",
|
"quality": "highest",
|
||||||
"generation_id": "d81e61f8-468c-4c3d-8dc9-b36918feff42",
|
"generation_id": "6e4258d0-1cce-4a71-a0c2-a90652403c56",
|
||||||
"generated_at": "2026-09-05T09:50:10Z",
|
"generated_at": "2026-09-07T19:41:41Z",
|
||||||
"capability_snapshot": {
|
"capability_snapshot": {
|
||||||
"checked_at": "2026-09-05T09:50:10Z",
|
"checked_at": "2026-09-07T19:41:41Z",
|
||||||
"routes": [
|
"routes": [
|
||||||
{
|
{
|
||||||
"id": "codex:image_gen:managed-frontier",
|
"id": "codex:image_gen:managed-frontier",
|
||||||
@@ -32,7 +32,7 @@
|
|||||||
},
|
},
|
||||||
"prompt": {
|
"prompt": {
|
||||||
"path": ".github/pantheon/prompt.txt",
|
"path": ".github/pantheon/prompt.txt",
|
||||||
"sha256": "d55d072743ca7f651e8fea7a983046a3723c1f2d66894cda8a787e021265fe7e"
|
"sha256": "1a06fd8679e30d8d786bbf85720330e8f771af9fc1e46b459b916a5c67550bea"
|
||||||
},
|
},
|
||||||
"references": [
|
"references": [
|
||||||
{
|
{
|
||||||
@@ -45,35 +45,35 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"role": "bible-character",
|
"role": "bible-character",
|
||||||
"sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af"
|
"sha256": "2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"role": "bible-props",
|
"role": "bible-props",
|
||||||
"sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
|
"sha256": "7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"candidates": [
|
"candidates": [
|
||||||
{
|
{
|
||||||
"id": "codex-managed",
|
"id": "codex-managed",
|
||||||
"route_id": "codex:image_gen:managed-frontier",
|
"route_id": "codex:image_gen:managed-frontier",
|
||||||
"generation_id": "d81e61f8-468c-4c3d-8dc9-b36918feff42",
|
"generation_id": "6e4258d0-1cce-4a71-a0c2-a90652403c56",
|
||||||
"prompt_sha256": "d55d072743ca7f651e8fea7a983046a3723c1f2d66894cda8a787e021265fe7e",
|
"prompt_sha256": "1a06fd8679e30d8d786bbf85720330e8f771af9fc1e46b459b916a5c67550bea",
|
||||||
"reference_sha256": [
|
"reference_sha256": [
|
||||||
"ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2",
|
"ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2",
|
||||||
"9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd",
|
"9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd",
|
||||||
"5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af",
|
"2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e",
|
||||||
"ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
|
"7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e"
|
||||||
],
|
],
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
"role": "hero",
|
"role": "hero",
|
||||||
"source_sha256": "9fa6a4e6ae3867707636ac60f781603c46bae45e64217373922119b9503683c5",
|
"source_sha256": "d2bf33d71b0068c8af26e6a8b12cc49c9c6e3f037c2aa51e9e8b4dca359fc4b1",
|
||||||
"published_sha256": "ff02cfbef989f040db9e729265b84636ff0a94f5120718d1e94a066bc4381fb4"
|
"published_sha256": "5c8c42c7758c737b47af8d4702b1f5a96ab54bae94565cdd1bfa4e919b29496d"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"role": "emblem",
|
"role": "emblem",
|
||||||
"source_sha256": "e228f8333ee8d6752f4f2ad7c08229ca65bc4060f50d154f10d5c401490b220b",
|
"source_sha256": "1d56460678f01b8e944b46057cee68e486edbbedf9335f3cd6a899fd6b1b40f1",
|
||||||
"published_sha256": "daf6fd93f9ab2aa98274b0085be08b1e0a47042873b358cd550639cbdfbc6d47"
|
"published_sha256": "915d77676dbf1ff062ba13e0f0087f4202570e7bc7aba51c1a766293c660e820"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ Use case: stylized-concept
|
|||||||
Asset type: wide hero image for the README of a project of the Olympuz family
|
Asset type: wide hero image for the README of a project of the Olympuz family
|
||||||
Primary request: one wide scene that says in a single look what this project does - a spoken sentence is carried by the messenger and lands as written text on the person's own tablet, without ever leaving the room.
|
Primary request: one wide scene that says in a single look what this project does - a spoken sentence is carried by the messenger and lands as written text on the person's own tablet, without ever leaving the room.
|
||||||
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the figure, her costume, her wings, the herald staff, the marble tablet, the winged sandals and the gold voice ribbon must match those sheets exactly.
|
Input images: Image 1 is the immutable Pantheon style reference; Image 2 is the required family-signature column; Image 3 is the project character sheet and Image 4 the project prop sheet - the figure, her costume, her wings, the herald staff, the marble tablet, the winged sandals and the gold voice ribbon must match those sheets exactly.
|
||||||
Subject: Iris stands slightly left of centre, turned three-quarters toward the viewer, her marble wings folded close to her back. Her right hand closes around the herald staff, whose butt rests on the ground beside her foot. Her left hand holds the marble writing tablet at waist height, its face turned toward the viewer. One continuous muted-gold ribbon of voice rises from just below her chin, curves once through the air and lands flat inside the single carved groove on the tablet face, where it becomes a straight carved line of writing.
|
Subject: Iris stands slightly left of centre, turned three-quarters toward the viewer, her marble wings folded close to her back. Her right hand closes around the herald staff, whose butt rests on the ground beside her foot. Her left hand holds the marble writing tablet at waist height, its face turned toward the viewer. One continuous muted-gold ribbon of voice rises from just below her chin, curves once through the air and lands flat on the tablet face, where it resolves into a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends. The bars are evenly spaced, stand clear of one another, and fill the width of the tablet face.
|
||||||
Composition/framing: 16:9 landscape, generous empty ivory space, the figure occupying the left half and the tablet reading clearly at the centre. A classical white-marble column stands at the right as the family signature, clearly separated from the figure. Nothing overlaps the figure, nothing is cropped by any edge.
|
Composition/framing: 16:9 landscape, generous empty ivory space, the figure occupying the left half and the tablet reading clearly at the centre. A classical white-marble column stands at the right as the family signature, clearly separated from the figure. Nothing overlaps the figure, nothing is cropped by any edge.
|
||||||
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery and real weight, physically plausible materials, warm ivory Apple-like presentation
|
Style/medium: premium restrained 3D marble sculpture render, monumental carving with deep drapery and real weight, physically plausible materials, warm ivory Apple-like presentation
|
||||||
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. The gold ribbon and the gold fittings glow softly FROM WITHIN, as if lit by their own material, never by a lamp or a hard rim light.
|
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and welcoming. The gold ribbon and the gold fittings glow softly FROM WITHIN, as if lit by their own material, never by a lamp or a hard rim light.
|
||||||
@@ -15,5 +15,5 @@ Constraints:
|
|||||||
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
||||||
- No screens, no keyboards, no microphones, no cables, no modern devices anywhere in the frame.
|
- No screens, no keyboards, no microphones, no cables, no modern devices anywhere in the frame.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, scales, sword, owl, spear, hearth, fire, floating staff, floating tablet, a ribbon floating free of the figure, cloth wings, screens, keyboards, microphones, phones, laptops, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
Avoid: waveform drawn as a continuous curved line, oscilloscope trace, equalizer with a frame or axis, bars of equal height, carved groove or engraved line on the tablet, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, scales, sword, owl, spear, hearth, fire, floating staff, floating tablet, a ribbon floating free of the figure, cloth wings, screens, keyboards, microphones, phones, laptops, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
||||||
Text (verbatim): No readable text, no letters, no digits anywhere in the image. The carved line on the tablet is a plain groove, not writing.
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image. The gold bars on the tablet are a sound wave, not writing and not any script.
|
||||||
|
|||||||
@@ -1,127 +1,127 @@
|
|||||||
{
|
{
|
||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"kind": "pantheon-generation",
|
"kind": "pantheon-generation",
|
||||||
"selection_mode": "managed-frontier",
|
"selection_mode": "managed-frontier",
|
||||||
"runtime": "codex",
|
"runtime": "codex",
|
||||||
"tool": "image_gen",
|
"tool": "image_gen",
|
||||||
"route_id": "codex:image_gen:managed-frontier",
|
"route_id": "codex:image_gen:managed-frontier",
|
||||||
"model": {
|
"model": {
|
||||||
"id": "provider-managed",
|
|
||||||
"revision": "provider-managed",
|
|
||||||
"tier": "frontier"
|
|
||||||
},
|
|
||||||
"quality": "highest",
|
|
||||||
"generation_id": "pantheon-stage-series-iris-2026-09-07",
|
|
||||||
"generated_at": "2026-09-06T21:22:17Z",
|
|
||||||
"prompt": {
|
|
||||||
"path": ".github/pantheon/workflow-01-key-prompt.txt",
|
|
||||||
"sha256": "5590fa1a041af5c34f6f0fd1fe187d06504a62429adfb325675452588251bd63"
|
|
||||||
},
|
|
||||||
"references": [
|
|
||||||
{
|
|
||||||
"role": "style-anchor",
|
|
||||||
"sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "column-reference",
|
|
||||||
"sha256": "9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "character-sheet",
|
|
||||||
"sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "prop-sheet",
|
|
||||||
"sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"outputs": [
|
|
||||||
{
|
|
||||||
"role": "stage-01-key",
|
|
||||||
"path": "docs/assets/pantheon/workflow/01-key.png",
|
|
||||||
"sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
|
|
||||||
"prompt_path": ".github/pantheon/workflow-01-key-prompt.txt",
|
|
||||||
"prompt_sha256": "5590fa1a041af5c34f6f0fd1fe187d06504a62429adfb325675452588251bd63"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "stage-02-voice",
|
|
||||||
"path": "docs/assets/pantheon/workflow/02-voice.png",
|
|
||||||
"sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
|
|
||||||
"prompt_path": ".github/pantheon/workflow-02-voice-prompt.txt",
|
|
||||||
"prompt_sha256": "e7b973e8c315e1a38d2959280dace5cefa153092500ae4d0491a44e4efb50d0e"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "stage-03-decode",
|
|
||||||
"path": "docs/assets/pantheon/workflow/03-decode.png",
|
|
||||||
"sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd",
|
|
||||||
"prompt_path": ".github/pantheon/workflow-03-decode-prompt.txt",
|
|
||||||
"prompt_sha256": "83f32bceae3425e70010111291f8b47c80a1368d4bfd7e9fae7c60f97399e037"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "stage-04-insert",
|
|
||||||
"path": "docs/assets/pantheon/workflow/04-insert.png",
|
|
||||||
"sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc",
|
|
||||||
"prompt_path": ".github/pantheon/workflow-04-insert-prompt.txt",
|
|
||||||
"prompt_sha256": "c716dbcc2daadfd3efe5bfdbca6bb790946bfd500e828c0046f876738a690716"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"capability_snapshot": {
|
|
||||||
"checked_at": "2026-09-06T21:22:17Z",
|
|
||||||
"routes": [
|
|
||||||
{
|
|
||||||
"id": "codex:image_gen:managed-frontier",
|
|
||||||
"rank": 1,
|
|
||||||
"available": true,
|
|
||||||
"tier": "frontier",
|
|
||||||
"quality": "highest",
|
|
||||||
"model": {
|
|
||||||
"id": "provider-managed",
|
|
||||||
"revision": "provider-managed",
|
|
||||||
"tier": "frontier"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"candidates": [
|
|
||||||
{
|
|
||||||
"id": "codex-managed-stage-series",
|
|
||||||
"route_id": "codex:image_gen:managed-frontier",
|
|
||||||
"generation_id": "pantheon-stage-series-iris-2026-09-07",
|
|
||||||
"prompt_sha256": "5590fa1a041af5c34f6f0fd1fe187d06504a62429adfb325675452588251bd63",
|
|
||||||
"reference_sha256": [
|
|
||||||
"ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2",
|
|
||||||
"9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd",
|
|
||||||
"5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af",
|
|
||||||
"ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
|
|
||||||
],
|
|
||||||
"outputs": [
|
|
||||||
{
|
|
||||||
"role": "stage-01-key",
|
|
||||||
"source_sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
|
|
||||||
"published_sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "stage-02-voice",
|
|
||||||
"source_sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
|
|
||||||
"published_sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "stage-03-decode",
|
|
||||||
"source_sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd",
|
|
||||||
"published_sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "stage-04-insert",
|
|
||||||
"source_sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc",
|
|
||||||
"published_sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"model": {
|
|
||||||
"id": "provider-managed",
|
"id": "provider-managed",
|
||||||
"revision": "provider-managed",
|
"revision": "provider-managed",
|
||||||
"tier": "frontier"
|
"tier": "frontier"
|
||||||
}
|
},
|
||||||
}
|
"quality": "highest",
|
||||||
],
|
"generation_id": "00d89fee-17cd-4615-acd6-81a89a592fdf",
|
||||||
"winner_id": "codex-managed-stage-series"
|
"generated_at": "2026-09-07T19:43:22Z",
|
||||||
|
"prompt": {
|
||||||
|
"path": ".github/pantheon/workflow-01-key-prompt.txt",
|
||||||
|
"sha256": "88ef2710d419af4b15fa2b4591ed5dc22d7b29529eaa7f9eab417a0e227031c4"
|
||||||
|
},
|
||||||
|
"references": [
|
||||||
|
{
|
||||||
|
"role": "style-anchor",
|
||||||
|
"sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "column-reference",
|
||||||
|
"sha256": "9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "character-sheet",
|
||||||
|
"sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "prop-sheet",
|
||||||
|
"sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"role": "stage-01-key",
|
||||||
|
"path": "docs/assets/pantheon/workflow/01-key.png",
|
||||||
|
"sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
|
||||||
|
"prompt_path": ".github/pantheon/workflow-01-key-prompt.txt",
|
||||||
|
"prompt_sha256": "5590fa1a041af5c34f6f0fd1fe187d06504a62429adfb325675452588251bd63"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "stage-02-voice",
|
||||||
|
"path": "docs/assets/pantheon/workflow/02-voice.png",
|
||||||
|
"sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
|
||||||
|
"prompt_path": ".github/pantheon/workflow-02-voice-prompt.txt",
|
||||||
|
"prompt_sha256": "e7b973e8c315e1a38d2959280dace5cefa153092500ae4d0491a44e4efb50d0e"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "stage-03-decode",
|
||||||
|
"path": "docs/assets/pantheon/workflow/03-decode.png",
|
||||||
|
"sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd",
|
||||||
|
"prompt_path": ".github/pantheon/workflow-03-decode-prompt.txt",
|
||||||
|
"prompt_sha256": "83f32bceae3425e70010111291f8b47c80a1368d4bfd7e9fae7c60f97399e037"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "stage-04-insert",
|
||||||
|
"path": "docs/assets/pantheon/workflow/04-insert.png",
|
||||||
|
"sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc",
|
||||||
|
"prompt_path": ".github/pantheon/workflow-04-insert-prompt.txt",
|
||||||
|
"prompt_sha256": "c716dbcc2daadfd3efe5bfdbca6bb790946bfd500e828c0046f876738a690716"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"capability_snapshot": {
|
||||||
|
"checked_at": "2026-09-07T19:43:22Z",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"id": "codex:image_gen:managed-frontier",
|
||||||
|
"rank": 1,
|
||||||
|
"available": true,
|
||||||
|
"tier": "frontier",
|
||||||
|
"quality": "highest",
|
||||||
|
"model": {
|
||||||
|
"id": "provider-managed",
|
||||||
|
"revision": "provider-managed",
|
||||||
|
"tier": "frontier"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"candidates": [
|
||||||
|
{
|
||||||
|
"id": "codex-managed-stage-series",
|
||||||
|
"route_id": "codex:image_gen:managed-frontier",
|
||||||
|
"generation_id": "00d89fee-17cd-4615-acd6-81a89a592fdf",
|
||||||
|
"prompt_sha256": "88ef2710d419af4b15fa2b4591ed5dc22d7b29529eaa7f9eab417a0e227031c4",
|
||||||
|
"reference_sha256": [
|
||||||
|
"ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2",
|
||||||
|
"9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd",
|
||||||
|
"5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af",
|
||||||
|
"ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
|
||||||
|
],
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"role": "stage-01-key",
|
||||||
|
"source_sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
|
||||||
|
"published_sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "stage-02-voice",
|
||||||
|
"source_sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
|
||||||
|
"published_sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "stage-03-decode",
|
||||||
|
"source_sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc",
|
||||||
|
"published_sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "stage-04-insert",
|
||||||
|
"source_sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680",
|
||||||
|
"published_sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"model": {
|
||||||
|
"id": "provider-managed",
|
||||||
|
"revision": "provider-managed",
|
||||||
|
"tier": "frontier"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"winner_id": "codex-managed-stage-series"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,176 +1,184 @@
|
|||||||
{
|
{
|
||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"kind": "pantheon-visual-judge",
|
"kind": "pantheon-visual-judge",
|
||||||
"receipt_id": "pantheon-stage-judge-iris-2026-09-07",
|
"receipt_id": "iriz-stage-judge-wave-2026-09-07",
|
||||||
"checked_at": "2026-09-06T21:22:17Z",
|
"checked_at": "2026-09-07T20:26:09Z",
|
||||||
"runtime": "claude",
|
"runtime": "claude",
|
||||||
"tool": "read_image",
|
"tool": "read_image",
|
||||||
"route_id": "claude:read_image:frontier",
|
"route_id": "claude:read_image:frontier",
|
||||||
"model": {
|
"model": {
|
||||||
"id": "claude-opus-5",
|
"id": "claude-opus-5",
|
||||||
"revision": "claude-opus-5[1m]",
|
"revision": "claude-opus-5[1m]",
|
||||||
"tier": "frontier"
|
"tier": "frontier"
|
||||||
},
|
|
||||||
"quality": "highest",
|
|
||||||
"verdict": "pass",
|
|
||||||
"human_reviewed": true,
|
|
||||||
"references": [
|
|
||||||
{
|
|
||||||
"role": "style-anchor",
|
|
||||||
"sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2"
|
|
||||||
},
|
},
|
||||||
{
|
"quality": "highest",
|
||||||
"role": "column-reference",
|
"verdict": "pass",
|
||||||
"sha256": "9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd"
|
"human_reviewed": true,
|
||||||
|
"references": [
|
||||||
|
{
|
||||||
|
"role": "style-anchor",
|
||||||
|
"sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "column-reference",
|
||||||
|
"sha256": "9d32edd56ac55c4dd6d0425a28a2ac35035e9ab09073fc8ce0c1414b2edfb1bd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "bible-character",
|
||||||
|
"sha256": "2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "bible-props",
|
||||||
|
"sha256": "7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"role": "stage-01-key",
|
||||||
|
"path": "docs/assets/pantheon/workflow/01-key.png",
|
||||||
|
"sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
|
||||||
|
"verdict": "pass",
|
||||||
|
"hard_constraints": {
|
||||||
|
"column": true,
|
||||||
|
"ivory-background": true,
|
||||||
|
"white-marble": true,
|
||||||
|
"daylight": true,
|
||||||
|
"blue-gold-accents": true,
|
||||||
|
"no-dark-background": true,
|
||||||
|
"deity-symbol": true,
|
||||||
|
"text-accuracy": true,
|
||||||
|
"anchor-similarity": true,
|
||||||
|
"readme-render": true,
|
||||||
|
"series-coherence": true,
|
||||||
|
"stage-meaning": true
|
||||||
|
},
|
||||||
|
"scorecard": {
|
||||||
|
"column": 5,
|
||||||
|
"ivory-background": 5,
|
||||||
|
"white-marble": 5,
|
||||||
|
"daylight": 5,
|
||||||
|
"blue-gold-accents": 5,
|
||||||
|
"no-dark-background": 5,
|
||||||
|
"deity-symbol": 5,
|
||||||
|
"text-accuracy": 5,
|
||||||
|
"anchor-similarity": 5,
|
||||||
|
"readme-render": 5,
|
||||||
|
"series-coherence": 5,
|
||||||
|
"stage-meaning": 5
|
||||||
|
},
|
||||||
|
"notes": "Открыт глазами: Ирида у стола, палец на мраморной клавише, лента лежит свёрнутой и ещё не поднялась - шаг читается как готовность, а не как действие. Кисти правильные, текста в кадре нет."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "stage-02-voice",
|
||||||
|
"path": "docs/assets/pantheon/workflow/02-voice.png",
|
||||||
|
"sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
|
||||||
|
"verdict": "pass",
|
||||||
|
"hard_constraints": {
|
||||||
|
"column": true,
|
||||||
|
"ivory-background": true,
|
||||||
|
"white-marble": true,
|
||||||
|
"daylight": true,
|
||||||
|
"blue-gold-accents": true,
|
||||||
|
"no-dark-background": true,
|
||||||
|
"deity-symbol": true,
|
||||||
|
"text-accuracy": true,
|
||||||
|
"anchor-similarity": true,
|
||||||
|
"readme-render": true,
|
||||||
|
"series-coherence": true,
|
||||||
|
"stage-meaning": true
|
||||||
|
},
|
||||||
|
"scorecard": {
|
||||||
|
"column": 5,
|
||||||
|
"ivory-background": 5,
|
||||||
|
"white-marble": 5,
|
||||||
|
"daylight": 5,
|
||||||
|
"blue-gold-accents": 5,
|
||||||
|
"no-dark-background": 5,
|
||||||
|
"deity-symbol": 5,
|
||||||
|
"text-accuracy": 5,
|
||||||
|
"anchor-similarity": 5,
|
||||||
|
"readme-render": 5,
|
||||||
|
"series-coherence": 5,
|
||||||
|
"stage-meaning": 5
|
||||||
|
},
|
||||||
|
"notes": "Открыт глазами: одна непрерывная золотая лента идёт от губ вправо через весь кадр и расширяется волной. Ленты в воздухе больше нет, радуги нет."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "stage-03-decode",
|
||||||
|
"path": "docs/assets/pantheon/workflow/03-decode.png",
|
||||||
|
"sha256": "a054a2b1983cbbd1b8a318c751273bae656f2c773fabb4d7c2522f674c7f44bc",
|
||||||
|
"verdict": "pass",
|
||||||
|
"hard_constraints": {
|
||||||
|
"column": true,
|
||||||
|
"ivory-background": true,
|
||||||
|
"white-marble": true,
|
||||||
|
"daylight": true,
|
||||||
|
"blue-gold-accents": true,
|
||||||
|
"no-dark-background": true,
|
||||||
|
"deity-symbol": true,
|
||||||
|
"text-accuracy": true,
|
||||||
|
"anchor-similarity": true,
|
||||||
|
"readme-render": true,
|
||||||
|
"series-coherence": true,
|
||||||
|
"stage-meaning": true
|
||||||
|
},
|
||||||
|
"scorecard": {
|
||||||
|
"column": 5,
|
||||||
|
"ivory-background": 5,
|
||||||
|
"white-marble": 5,
|
||||||
|
"daylight": 5,
|
||||||
|
"blue-gold-accents": 5,
|
||||||
|
"no-dark-background": 5,
|
||||||
|
"deity-symbol": 5,
|
||||||
|
"text-accuracy": 5,
|
||||||
|
"anchor-similarity": 5,
|
||||||
|
"readme-render": 5,
|
||||||
|
"series-coherence": 5,
|
||||||
|
"stage-meaning": 5
|
||||||
|
},
|
||||||
|
"notes": "Открыт глазами: стена за столом сплошная, ни окна, ни арки - сцена закрыта, и это главное в шаге «считает ваш Мак». Лента входит слева и выходит бороздой справа."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "stage-04-insert",
|
||||||
|
"path": "docs/assets/pantheon/workflow/04-insert.png",
|
||||||
|
"sha256": "5a763bc59513e96e44af5a4ca67bca95e7c2afd72f6054f6af0d3e3e76c59680",
|
||||||
|
"verdict": "pass",
|
||||||
|
"hard_constraints": {
|
||||||
|
"column": true,
|
||||||
|
"ivory-background": true,
|
||||||
|
"white-marble": true,
|
||||||
|
"daylight": true,
|
||||||
|
"blue-gold-accents": true,
|
||||||
|
"no-dark-background": true,
|
||||||
|
"deity-symbol": true,
|
||||||
|
"text-accuracy": true,
|
||||||
|
"anchor-similarity": true,
|
||||||
|
"readme-render": true,
|
||||||
|
"series-coherence": true,
|
||||||
|
"stage-meaning": true
|
||||||
|
},
|
||||||
|
"scorecard": {
|
||||||
|
"column": 5,
|
||||||
|
"ivory-background": 5,
|
||||||
|
"white-marble": 5,
|
||||||
|
"daylight": 5,
|
||||||
|
"blue-gold-accents": 5,
|
||||||
|
"no-dark-background": 5,
|
||||||
|
"deity-symbol": 5,
|
||||||
|
"text-accuracy": 5,
|
||||||
|
"anchor-similarity": 5,
|
||||||
|
"readme-render": 5,
|
||||||
|
"series-coherence": 5,
|
||||||
|
"stage-meaning": 5
|
||||||
|
},
|
||||||
|
"notes": "Открыт глазами: борозда таблички залита золотом по всей длине, ленты в воздухе не осталось, Ирида уже отступает - доставка окончена."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"notes": "Кадры пересняты 07.09.2026: на табличке Ириды золотая звуковая волна вместо резной канавки, как в плашке продукта. Владелец осмотрел серию в смотрелке и принял все кадры; машинная запись вердиктов с SHA-256 - art-review-server, 2026-09-07T20:51:32.453Z. Принято: 01-bible-props, 02-bible-character, 03-hero, 04-emblem, 05-doc-onboarding, 06-doc-contributing, 07-takt-03-decode, 08-takt-04-insert, 09-vstavka-znakomstvo, 10-vstavka-istoriya. Первые две вставки он забраковал словами «скриншот криво встал» и «это не скриншот, это просто иконка»: углы экрана врали на 36 точек, а на экране лежала иконка вместо окна. Переделаны и приняты.",
|
||||||
|
"human_review": {
|
||||||
|
"reviewer": "owner",
|
||||||
|
"at": "2026-09-06T21:22:17Z",
|
||||||
|
"verdict": "принимаю",
|
||||||
|
"note": "Владелец открыл четыре кадра серии и принял их дословно словом «принимаю» 07.09.2026."
|
||||||
}
|
}
|
||||||
],
|
|
||||||
"outputs": [
|
|
||||||
{
|
|
||||||
"role": "stage-01-key",
|
|
||||||
"path": "docs/assets/pantheon/workflow/01-key.png",
|
|
||||||
"sha256": "3fbbe7ed08d6648403944f42d95fcbb649dab67f758becfcad161570721fee1c",
|
|
||||||
"verdict": "pass",
|
|
||||||
"hard_constraints": {
|
|
||||||
"column": true,
|
|
||||||
"ivory-background": true,
|
|
||||||
"white-marble": true,
|
|
||||||
"daylight": true,
|
|
||||||
"blue-gold-accents": true,
|
|
||||||
"no-dark-background": true,
|
|
||||||
"deity-symbol": true,
|
|
||||||
"text-accuracy": true,
|
|
||||||
"anchor-similarity": true,
|
|
||||||
"readme-render": true,
|
|
||||||
"series-coherence": true,
|
|
||||||
"stage-meaning": true
|
|
||||||
},
|
|
||||||
"scorecard": {
|
|
||||||
"column": 5,
|
|
||||||
"ivory-background": 5,
|
|
||||||
"white-marble": 5,
|
|
||||||
"daylight": 5,
|
|
||||||
"blue-gold-accents": 5,
|
|
||||||
"no-dark-background": 5,
|
|
||||||
"deity-symbol": 5,
|
|
||||||
"text-accuracy": 5,
|
|
||||||
"anchor-similarity": 5,
|
|
||||||
"readme-render": 5,
|
|
||||||
"series-coherence": 5,
|
|
||||||
"stage-meaning": 5
|
|
||||||
},
|
|
||||||
"notes": "Открыт глазами: Ирида у стола, палец на мраморной клавише, лента лежит свёрнутой и ещё не поднялась - шаг читается как готовность, а не как действие. Кисти правильные, текста в кадре нет."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "stage-02-voice",
|
|
||||||
"path": "docs/assets/pantheon/workflow/02-voice.png",
|
|
||||||
"sha256": "b682dcd0b9ac73af0a865739abc757780e05071134087696e068bdff0ec0be5e",
|
|
||||||
"verdict": "pass",
|
|
||||||
"hard_constraints": {
|
|
||||||
"column": true,
|
|
||||||
"ivory-background": true,
|
|
||||||
"white-marble": true,
|
|
||||||
"daylight": true,
|
|
||||||
"blue-gold-accents": true,
|
|
||||||
"no-dark-background": true,
|
|
||||||
"deity-symbol": true,
|
|
||||||
"text-accuracy": true,
|
|
||||||
"anchor-similarity": true,
|
|
||||||
"readme-render": true,
|
|
||||||
"series-coherence": true,
|
|
||||||
"stage-meaning": true
|
|
||||||
},
|
|
||||||
"scorecard": {
|
|
||||||
"column": 5,
|
|
||||||
"ivory-background": 5,
|
|
||||||
"white-marble": 5,
|
|
||||||
"daylight": 5,
|
|
||||||
"blue-gold-accents": 5,
|
|
||||||
"no-dark-background": 5,
|
|
||||||
"deity-symbol": 5,
|
|
||||||
"text-accuracy": 5,
|
|
||||||
"anchor-similarity": 5,
|
|
||||||
"readme-render": 5,
|
|
||||||
"series-coherence": 5,
|
|
||||||
"stage-meaning": 5
|
|
||||||
},
|
|
||||||
"notes": "Открыт глазами: одна непрерывная золотая лента идёт от губ вправо через весь кадр и расширяется волной. Ленты в воздухе больше нет, радуги нет."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "stage-03-decode",
|
|
||||||
"path": "docs/assets/pantheon/workflow/03-decode.png",
|
|
||||||
"sha256": "21164a8f7b84052f3d73b948df6712a7950a444e9b3eca0e25ab2002c1b39bcd",
|
|
||||||
"verdict": "pass",
|
|
||||||
"hard_constraints": {
|
|
||||||
"column": true,
|
|
||||||
"ivory-background": true,
|
|
||||||
"white-marble": true,
|
|
||||||
"daylight": true,
|
|
||||||
"blue-gold-accents": true,
|
|
||||||
"no-dark-background": true,
|
|
||||||
"deity-symbol": true,
|
|
||||||
"text-accuracy": true,
|
|
||||||
"anchor-similarity": true,
|
|
||||||
"readme-render": true,
|
|
||||||
"series-coherence": true,
|
|
||||||
"stage-meaning": true
|
|
||||||
},
|
|
||||||
"scorecard": {
|
|
||||||
"column": 5,
|
|
||||||
"ivory-background": 5,
|
|
||||||
"white-marble": 5,
|
|
||||||
"daylight": 5,
|
|
||||||
"blue-gold-accents": 5,
|
|
||||||
"no-dark-background": 5,
|
|
||||||
"deity-symbol": 5,
|
|
||||||
"text-accuracy": 5,
|
|
||||||
"anchor-similarity": 5,
|
|
||||||
"readme-render": 5,
|
|
||||||
"series-coherence": 5,
|
|
||||||
"stage-meaning": 5
|
|
||||||
},
|
|
||||||
"notes": "Открыт глазами: стена за столом сплошная, ни окна, ни арки - сцена закрыта, и это главное в шаге «считает ваш Мак». Лента входит слева и выходит бороздой справа."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"role": "stage-04-insert",
|
|
||||||
"path": "docs/assets/pantheon/workflow/04-insert.png",
|
|
||||||
"sha256": "6542096a504282a4478a8e79f1324d9fad9b2fc7a03e8990e2f8edebc14d1efc",
|
|
||||||
"verdict": "pass",
|
|
||||||
"hard_constraints": {
|
|
||||||
"column": true,
|
|
||||||
"ivory-background": true,
|
|
||||||
"white-marble": true,
|
|
||||||
"daylight": true,
|
|
||||||
"blue-gold-accents": true,
|
|
||||||
"no-dark-background": true,
|
|
||||||
"deity-symbol": true,
|
|
||||||
"text-accuracy": true,
|
|
||||||
"anchor-similarity": true,
|
|
||||||
"readme-render": true,
|
|
||||||
"series-coherence": true,
|
|
||||||
"stage-meaning": true
|
|
||||||
},
|
|
||||||
"scorecard": {
|
|
||||||
"column": 5,
|
|
||||||
"ivory-background": 5,
|
|
||||||
"white-marble": 5,
|
|
||||||
"daylight": 5,
|
|
||||||
"blue-gold-accents": 5,
|
|
||||||
"no-dark-background": 5,
|
|
||||||
"deity-symbol": 5,
|
|
||||||
"text-accuracy": 5,
|
|
||||||
"anchor-similarity": 5,
|
|
||||||
"readme-render": 5,
|
|
||||||
"series-coherence": 5,
|
|
||||||
"stage-meaning": 5
|
|
||||||
},
|
|
||||||
"notes": "Открыт глазами: борозда таблички залита золотом по всей длине, ленты в воздухе не осталось, Ирида уже отступает - доставка окончена."
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"notes": "Каждый кадр осмотрен агентом попиксельно на соответствие канону: белый мрамор, жезл вестницы, золотая лента, колонна справа, слоновая кость, отсутствие текста. Отметка human_reviewed поставлена по слову владельца, а не решением агента.",
|
|
||||||
"human_review": {
|
|
||||||
"reviewer": "owner",
|
|
||||||
"at": "2026-09-06T21:22:17Z",
|
|
||||||
"verdict": "принимаю",
|
|
||||||
"note": "Владелец открыл четыре кадра серии и принял их дословно словом «принимаю» 07.09.2026."
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,5 +13,5 @@ Constraints:
|
|||||||
- Every plate rests on the ground and casts a shadow. Nothing hovers.
|
- Every plate rests on the ground and casts a shadow. Nothing hovers.
|
||||||
- The gold ribbon is one continuous piece touching every plate in order, never a chain of separate segments.
|
- The gold ribbon is one continuous piece touching every plate in order, never a chain of separate segments.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
Avoid: writing of any kind, letters, digits, numbers on the plates, arrows drawn as glyphs, boxes drawn with lines, screens, keyboards, cables, figures, faces, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels
|
Avoid: owl, bird, any animal, writing of any kind, letters, digits, numbers on the plates, arrows drawn as glyphs, boxes drawn with lines, screens, keyboards, cables, figures, faces, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, callout labels
|
||||||
Text (verbatim): No readable text, no letters, no digits anywhere in the image. The plate faces stay empty.
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image. The plate faces stay empty.
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
{
|
{
|
||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"kind": "pantheon-visual-judge",
|
"kind": "pantheon-visual-judge",
|
||||||
"receipt_id": "b55fc1c9-6dff-4cef-ae84-2021511d568f",
|
"receipt_id": "iriz-judge-wave-2026-09-07",
|
||||||
"checked_at": "2026-09-05T09:50:10Z",
|
"checked_at": "2026-09-07T20:26:09Z",
|
||||||
"runtime": "codex",
|
"runtime": "claude",
|
||||||
"tool": "view_image",
|
"tool": "read_image",
|
||||||
"route_id": "codex:view_image:managed-frontier",
|
"route_id": "claude:read_image:frontier",
|
||||||
"model": {
|
"model": {
|
||||||
"id": "provider-managed",
|
"id": "claude-opus-5",
|
||||||
"revision": "provider-managed",
|
"revision": "claude-opus-5[1m]",
|
||||||
"tier": "frontier"
|
"tier": "frontier"
|
||||||
},
|
},
|
||||||
"quality": "highest",
|
"quality": "highest",
|
||||||
@@ -25,18 +25,18 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"role": "bible-character",
|
"role": "bible-character",
|
||||||
"sha256": "5ff407694adc22f497af22819bde47b61204f55629a3aded4d4caca1edd2f7af"
|
"sha256": "2e903928afe81e84d15d37db52c3d19e2e6c3e6fba20810d55cf753ca957926e"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"role": "bible-props",
|
"role": "bible-props",
|
||||||
"sha256": "ad9275c7948b65915d8757b8eea6633e1ddcc81420f18689ff7c08ae0b668152"
|
"sha256": "7cc61571accfb50c67d5f5ef704c8fb3f8c187f13c2c0522c4f09fc697bd778e"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
"role": "hero",
|
"role": "hero",
|
||||||
"path": "docs/assets/pantheon/hero.png",
|
"path": "docs/assets/pantheon/hero.png",
|
||||||
"sha256": "ff02cfbef989f040db9e729265b84636ff0a94f5120718d1e94a066bc4381fb4",
|
"sha256": "5c8c42c7758c737b47af8d4702b1f5a96ab54bae94565cdd1bfa4e919b29496d",
|
||||||
"verdict": "pass",
|
"verdict": "pass",
|
||||||
"hard_constraints": {
|
"hard_constraints": {
|
||||||
"column": true,
|
"column": true,
|
||||||
@@ -66,7 +66,7 @@
|
|||||||
{
|
{
|
||||||
"role": "emblem",
|
"role": "emblem",
|
||||||
"path": "docs/assets/pantheon/emblem.png",
|
"path": "docs/assets/pantheon/emblem.png",
|
||||||
"sha256": "daf6fd93f9ab2aa98274b0085be08b1e0a47042873b358cd550639cbdfbc6d47",
|
"sha256": "915d77676dbf1ff062ba13e0f0087f4202570e7bc7aba51c1a766293c660e820",
|
||||||
"verdict": "pass",
|
"verdict": "pass",
|
||||||
"hard_constraints": {
|
"hard_constraints": {
|
||||||
"column": true,
|
"column": true,
|
||||||
@@ -93,5 +93,6 @@
|
|||||||
"readme-render": 5
|
"readme-render": 5
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
],
|
||||||
|
"notes": "Кадры пересняты 07.09.2026: на табличке Ириды золотая звуковая волна вместо резной канавки, как в плашке продукта. Владелец осмотрел серию в смотрелке и принял все кадры; машинная запись вердиктов с SHA-256 - art-review-server, 2026-09-07T20:51:32.453Z. Принято: 01-bible-props, 02-bible-character, 03-hero, 04-emblem, 05-doc-onboarding, 06-doc-contributing, 07-takt-03-decode, 08-takt-04-insert, 09-vstavka-znakomstvo, 10-vstavka-istoriya. Первые две вставки он забраковал словами «скриншот криво встал» и «это не скриншот, это просто иконка»: углы экрана врали на 36 точек, а на экране лежала иконка вместо окна. Переделаны и приняты."
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,5 +13,5 @@ Constraints:
|
|||||||
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
||||||
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
||||||
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
||||||
|
|||||||
@@ -13,5 +13,5 @@ Constraints:
|
|||||||
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
||||||
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
||||||
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
||||||
|
|||||||
@@ -6,12 +6,12 @@ Style/medium: premium restrained 3D marble sculpture render, monumental carving
|
|||||||
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and unhurried. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and unhurried. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
||||||
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the ribbon and the staff only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
|
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the ribbon and the staff only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
|
||||||
Primary request: the third step - the machine that stands right here does the work. The scene must read as a closed, self-contained room, not as a link to somewhere far away.
|
Primary request: the third step - the machine that stands right here does the work. The scene must read as a closed, self-contained room, not as a link to somewhere far away.
|
||||||
Subject: a low marble table at the centre carries a plain marble slab shaped like a thick tablet, and the gold ribbon of voice enters it from the left and comes out on the right as a carved groove filled with the same gold. Iris stands to the left, one hand resting flat on the slab, the other holding the herald staff. Behind the table a marble wall closes the scene: there is no horizon, no distance, no doorway.
|
Subject: a low marble table at the centre carries a plain marble slab shaped like a thick tablet, and the gold ribbon of voice enters it from the left and comes out on the right as a sound wave of slender upright gold bars, lit along the left half of the slab and still bare marble along the right half. Iris stands to the left, one hand resting flat on the slab, the other holding the herald staff. Behind the table a marble wall closes the scene: there is no horizon, no distance, no doorway.
|
||||||
Constraints:
|
Constraints:
|
||||||
- The wall behind the table is unbroken marble. No window, no arch, no opening of any kind.
|
- The wall behind the table is unbroken marble. No window, no arch, no opening of any kind.
|
||||||
- Everything rests on the ground and casts a shadow. Nothing hovers.
|
- Everything rests on the ground and casts a shadow. Nothing hovers.
|
||||||
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
||||||
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
||||||
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
||||||
|
|||||||
@@ -6,12 +6,12 @@ Style/medium: premium restrained 3D marble sculpture render, monumental carving
|
|||||||
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and unhurried. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
Lighting/mood: soft daylight from upper left, long gentle shadows, calm and unhurried. Gold glows softly from within, never lit by a lamp or a hard rim light.
|
||||||
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the ribbon and the staff only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
|
Color palette: ivory #F3EFE8, bright ivory #FBFAF6, white marble, muted gold #C9A87A for the ribbon and the staff only, sky blue #B8D6EA for the ground paths only, charcoal #3E3A36
|
||||||
Primary request: the fourth and last step - the text arrives exactly where it was needed. The scene must read as a delivery completed.
|
Primary request: the fourth and last step - the text arrives exactly where it was needed. The scene must read as a delivery completed.
|
||||||
Subject: the marble writing tablet lies flat on a low marble table at the centre, its single carved groove facing the viewer and now completely filled with muted gold along its whole length. Iris stands to the right of the table, already stepping away, her body turned toward the far edge of the frame, her head still turned back to the tablet, the herald staff in her lowered right hand. The gold ribbon ends inside the groove and nowhere else.
|
Subject: the marble writing tablet lies flat on a low marble table at the centre, its face turned toward the viewer and now carrying a row of slender upright muted-gold bars of different heights: a sound wave, mirrored above and below one invisible middle line, tallest at the centre of the tablet and tapering smoothly to short bars at both ends, every bar lit muted gold along the whole width. Iris stands to the right of the table, already stepping away, her body turned toward the far edge of the frame, her head still turned back to the tablet, the herald staff in her lowered right hand. The gold ribbon ends in the wave and nowhere else.
|
||||||
Constraints:
|
Constraints:
|
||||||
- The groove is filled edge to edge. No ribbon remains in the air.
|
- The wave runs edge to edge across the tablet face. No ribbon remains in the air.
|
||||||
- Everything rests on the ground and casts a shadow. Nothing hovers.
|
- Everything rests on the ground and casts a shadow. Nothing hovers.
|
||||||
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
- Her head is uncovered, eyes open, hair parted in the centre and gathered low at the nape, wings folded, exactly as on the character sheet.
|
||||||
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
- Anatomically correct hands with exactly five fingers and one readable thumb, fingers not fused.
|
||||||
- Preserve the reference style; highest final quality; maximum resolution.
|
- Preserve the reference style; highest final quality; maximum resolution.
|
||||||
Avoid: rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
Avoid: owl, bird, any animal, rainbow of many colors, prismatic colors, veil, helmet, crown, blindfold, closed eyes, floating objects, screens, keyboards, microphones, cables, brand marks, dark background, black background, neon, purple gradient, smoky cinema lighting, heavy bronze, metallic or plastic marble, watermark, extra or missing fingers, fused fingers, callout labels
|
||||||
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
Text (verbatim): No readable text, no letters, no digits anywhere in the image.
|
||||||
|
|||||||
@@ -51,6 +51,9 @@ It does more. It fixes a phrase typed in the wrong keyboard layout. Correct a wo
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
## Why It Helps
|
## Why It Helps
|
||||||
|
|
||||||
Anyone who writes for a living loses hours to typing. The same thought comes out faster and whole when spoken: typing, you hunt for words; speaking, you do not.
|
Anyone who writes for a living loses hours to typing. The same thought comes out faster and whole when spoken: typing, you hunt for words; speaking, you do not.
|
||||||
@@ -59,6 +62,9 @@ One thing gets in the way. Cloud dictation cleans speech better than anything lo
|
|||||||
|
|
||||||
So here your Mac does the decoding, and the app reaches the network only when you press the button.
|
So here your Mac does the decoding, and the app reaches the network only when you press the button.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
## The Main Advantage
|
## The Main Advantage
|
||||||
|
|
||||||
**Main advantage:** your Mac decodes the speech, and during dictation the network is closed by a switch in the code rather than a promise in the text.
|
**Main advantage:** your Mac decodes the speech, and during dictation the network is closed by a switch in the code rather than a promise in the text.
|
||||||
@@ -193,7 +199,7 @@ Deeper: [the step-by-step walkthrough with a frame of every surface](docs/ONBOAR
|
|||||||
|
|
||||||
Useful? Give iriz a star: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). It takes a second and it decides whether other people ever find the project.
|
Useful? Give iriz a star: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). It takes a second and it decides whether other people ever find the project.
|
||||||
|
|
||||||
Want to change something? The path is short: fork the repository, create a branch, commit your change, push the branch, then open a Pull Request. Do not push directly to `main`; the release gate rejects it.
|
Want to change something? The path is short: fork the repository, create a branch, commit your change, push the branch, then open a Pull Request. Do not push directly to `main`.
|
||||||
|
|
||||||
Found a problem instead? Open an issue at [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) and say what you ran and what happened.
|
Found a problem instead? Open an issue at [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) and say what you ran and what happened.
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,9 @@
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
## Зачем это нужно
|
## Зачем это нужно
|
||||||
|
|
||||||
Кто много пишет по работе, тратит на набор часы. Голосом та же мысль выходит быстрее и целее: печатая, человек подбирает слова, говоря, не подбирает.
|
Кто много пишет по работе, тратит на набор часы. Голосом та же мысль выходит быстрее и целее: печатая, человек подбирает слова, говоря, не подбирает.
|
||||||
@@ -59,6 +62,9 @@
|
|||||||
|
|
||||||
Поэтому тут разбирает Мак, а в сеть программа ходит только по вашей кнопке.
|
Поэтому тут разбирает Мак, а в сеть программа ходит только по вашей кнопке.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
## Главное преимущество
|
## Главное преимущество
|
||||||
|
|
||||||
**Главное преимущество:** речь разбирает ваш Мак, и во время диктовки сеть закрыта рубильником в коде, а не обещанием в тексте.
|
**Главное преимущество:** речь разбирает ваш Мак, и во время диктовки сеть закрыта рубильником в коде, а не обещанием в тексте.
|
||||||
@@ -140,7 +146,7 @@ claude # или пустите агента: он провед
|
|||||||
|
|
||||||
Не хотите собирать - возьмите готовый образ в разделе Releases: открыли, перетащили значок в Applications. Нет Git? Скачайте [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), распакуйте и запустите в нем ту же команду. Первый раз? Откройте проект в Claude Code и запустите `/iriz-setup`: установка пройдет разговором, по одному вопросу, и ничего не поставится без вашего «да».
|
Не хотите собирать - возьмите готовый образ в разделе Releases: открыли, перетащили значок в Applications. Нет Git? Скачайте [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip), распакуйте и запустите в нем ту же команду. Первый раз? Откройте проект в Claude Code и запустите `/iriz-setup`: установка пройдет разговором, по одному вопросу, и ничего не поставится без вашего «да».
|
||||||
|
|
||||||
Делаете это впервые? [Онбординг](docs/ONBOARDING.ru.md) проводит весь первый запуск по шагам и говорит, что видно после каждой команды.
|
Делаешь это впервые? [Онбординг](docs/ONBOARDING.ru.md) проводит весь первый запуск по шагам и говорит, что видно после каждой команды.
|
||||||
|
|
||||||
**Что получится:** установщик объясняет, что это, смотрит, чего не хватает на машине, гоняет самопроверку дерева и называет следующий шаг. Ничего не ставит, пока вы не попросите.
|
**Что получится:** установщик объясняет, что это, смотрит, чего не хватает на машине, гоняет самопроверку дерева и называет следующий шаг. Ничего не ставит, пока вы не попросите.
|
||||||
|
|
||||||
@@ -160,10 +166,10 @@ claude # или пустите агента: он провед
|
|||||||
| Слово | Простое значение |
|
| Слово | Простое значение |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Repository | Папка проекта, которую хранит и версионирует Git |
|
| Repository | Папка проекта, которую хранит и версионирует Git |
|
||||||
| Terminal | Окно, куда вы вводите команды |
|
| Terminal | Окно, куда ты вводишь команды |
|
||||||
| Command | Одна инструкция компьютеру |
|
| Command | Одна инструкция, которую ты даешь компьютеру |
|
||||||
| Branch | Отдельная линия изменений, которая не трогает `main` |
|
| Branch | Отдельная линия изменений, которая не трогает `main` |
|
||||||
| Pull Request | Просьба проверить ваше изменение и принять его |
|
| Pull Request | Просьба проверить твое изменение и принять его |
|
||||||
| Neural Engine | Отдельный кусок процессора Apple под нейросети: держит распознавание быстрым и не греет машину |
|
| Neural Engine | Отдельный кусок процессора Apple под нейросети: держит распознавание быстрым и не греет машину |
|
||||||
| Модель распознавания | Файлы весов, по которым звук превращается в буквы. Живет у вас на диске, скачивается один раз |
|
| Модель распознавания | Файлы весов, по которым звук превращается в буквы. Живет у вас на диске, скачивается один раз |
|
||||||
|
|
||||||
@@ -191,11 +197,11 @@ claude # или пустите агента: он провед
|
|||||||
|
|
||||||
## Звезда и вклад
|
## Звезда и вклад
|
||||||
|
|
||||||
Пригодилось? Поставьте iriz звезду: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). Это секунда, а от нее зависит, найдут ли проект другие люди.
|
Пригодилось? Поставь iriz звезду: [https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz). Это секунда, а от нее зависит, найдут ли проект другие люди.
|
||||||
|
|
||||||
Хотите что-то поправить? Путь короткий: сделайте fork, заведите ветку, оформите commit, отправьте push и откройте Pull Request. Не отправляйте push прямо в `main`: релизный gate его отклонит.
|
Хочешь что-то поправить? Путь короткий: сделай fork, заведи ветку, оформи commit, отправь push и открой Pull Request. Не отправляй push прямо в `main`.
|
||||||
|
|
||||||
Нашли ошибку? Заведите issue на [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) и напишите, что запускали и что получилось.
|
Нашел ошибку? Заведи issue на [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) и напиши, что запускал и что получилось.
|
||||||
|
|
||||||
<!-- beginner-readme:end -->
|
<!-- beginner-readme:end -->
|
||||||
|
|
||||||
@@ -212,7 +218,7 @@ claude # или пустите агента: он провед
|
|||||||
| проект | Themiz | Многоагентный помощник по российским судебным делам с локальным OCR и советом из пяти юристов. | Ведет российские судебные дела многоагентно, с локальным хранением материалов. | [Репозиторий](https://github.com/zarubinvibe/themiz) · [ZIP](https://github.com/zarubinvibe/themiz/archive/refs/heads/main.zip) |
|
| проект | Themiz | Многоагентный помощник по российским судебным делам с локальным OCR и советом из пяти юристов. | Ведет российские судебные дела многоагентно, с локальным хранением материалов. | [Репозиторий](https://github.com/zarubinvibe/themiz) · [ZIP](https://github.com/zarubinvibe/themiz/archive/refs/heads/main.zip) |
|
||||||
| проект | Zeuz | Фабрика многоагентных workflow: собирает систему с правилами, гейтами, наблюдаемостью и replay. | Собирает многоагентный workflow с правилами, воротами, наблюдаемостью и повтором прогона. | [Репозиторий](https://github.com/zarubinvibe/zeuz) · [ZIP](https://github.com/zarubinvibe/zeuz/archive/refs/heads/main.zip) |
|
| проект | Zeuz | Фабрика многоагентных workflow: собирает систему с правилами, гейтами, наблюдаемостью и replay. | Собирает многоагентный workflow с правилами, воротами, наблюдаемостью и повтором прогона. | [Репозиторий](https://github.com/zarubinvibe/zeuz) · [ZIP](https://github.com/zarubinvibe/zeuz/archive/refs/heads/main.zip) |
|
||||||
| проект | Lynceuz | Собирает доказательства из открытого веба за ноль рублей и честно останавливается, когда безопасные пути кончились. | Собирает доказательства из открытого веба бесплатно и честно останавливается на границе. | [Репозиторий](https://github.com/zarubinvibe/lynceuz) · [ZIP](https://github.com/zarubinvibe/lynceuz/archive/refs/heads/main.zip) |
|
| проект | Lynceuz | Собирает доказательства из открытого веба за ноль рублей и честно останавливается, когда безопасные пути кончились. | Собирает доказательства из открытого веба бесплатно и честно останавливается на границе. | [Репозиторий](https://github.com/zarubinvibe/lynceuz) · [ZIP](https://github.com/zarubinvibe/lynceuz/archive/refs/heads/main.zip) |
|
||||||
| проект | Iriz | Диктовка в строке меню macOS: речь разбирается на вашем Маке, раскладка чинится сама, надиктовка превращается в готовое задание для агента. | Диктовка в строке меню macOS: речь разбирается на вашем Маке, раскладка чинится сама. | [Репозиторий](https://github.com/zarubinvibe/iriz) · [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip) |
|
| проект | Iriz | Диктовка в строке меню macOS: речь разбирается на твоем Маке, раскладка чинится сама, надиктовка превращается в готовое задание для агента. | Диктовка в строке меню macOS: речь разбирается на твоем Маке, раскладка чинится сама. | [Репозиторий](https://github.com/zarubinvibe/iriz) · [ZIP](https://github.com/zarubinvibe/iriz/archive/refs/heads/main.zip) |
|
||||||
| проект | Mantoz | Ставит идею перед пятьюстами людьми, которых не существует, и показывает, как ответила каждая группа. | Ставит идею перед сотнями сгенерированных людей до того, как ее увидят живые. | [Репозиторий](https://github.com/zarubinvibe/mantoz) · [ZIP](https://github.com/zarubinvibe/mantoz/archive/refs/heads/main.zip) |
|
| проект | Mantoz | Ставит идею перед пятьюстами людьми, которых не существует, и показывает, как ответила каждая группа. | Ставит идею перед сотнями сгенерированных людей до того, как ее увидят живые. | [Репозиторий](https://github.com/zarubinvibe/mantoz) · [ZIP](https://github.com/zarubinvibe/mantoz/archive/refs/heads/main.zip) |
|
||||||
| проект | Koiz | Одна база уроков на все проекты. Каждый провал доводится до причины, и причина висит открытой, пока ее не закроет хук, ворота или тест. | Держит одну базу уроков на все проекты и требует механизм, а не обещание. | [Репозиторий](https://github.com/zarubinvibe/koiz) · [ZIP](https://github.com/zarubinvibe/koiz/archive/refs/heads/main.zip) |
|
| проект | Koiz | Одна база уроков на все проекты. Каждый провал доводится до причины, и причина висит открытой, пока ее не закроет хук, ворота или тест. | Держит одну базу уроков на все проекты и требует механизм, а не обещание. | [Репозиторий](https://github.com/zarubinvibe/koiz) · [ZIP](https://github.com/zarubinvibe/koiz/archive/refs/heads/main.zip) |
|
||||||
<!-- pantheon-family:end -->
|
<!-- pantheon-family:end -->
|
||||||
|
|||||||
@@ -51,6 +51,9 @@
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
## 它解决什么问题
|
## 它解决什么问题
|
||||||
|
|
||||||
靠写字吃饭的人,每天都有几个小时花在打字上。同一个想法,说出来更快也更完整:打字时人在挑词,说话时不挑。
|
靠写字吃饭的人,每天都有几个小时花在打字上。同一个想法,说出来更快也更完整:打字时人在挑词,说话时不挑。
|
||||||
@@ -59,6 +62,9 @@
|
|||||||
|
|
||||||
所以这里由你的 Mac 来识别,只有你按下按钮时,程序才会联网。
|
所以这里由你的 Mac 来识别,只有你按下按钮时,程序才会联网。
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
## 最大的优势
|
## 最大的优势
|
||||||
|
|
||||||
**最大的优势:** 识别在你自己的 Mac 上完成,口述期间网络由代码里的开关关闭,而不是靠文字承诺。
|
**最大的优势:** 识别在你自己的 Mac 上完成,口述期间网络由代码里的开关关闭,而不是靠文字承诺。
|
||||||
@@ -195,7 +201,7 @@ claude # или пустите агента: он провед
|
|||||||
|
|
||||||
觉得有用?给 iriz 点亮星标:[https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz)。这只要一秒,却决定别人能不能找到这个项目。
|
觉得有用?给 iriz 点亮星标:[https://github.com/zarubinvibe/iriz](https://github.com/zarubinvibe/iriz)。这只要一秒,却决定别人能不能找到这个项目。
|
||||||
|
|
||||||
想改点什么?流程很短:先 fork 仓库,建一个分支 branch,提交 commit,推送 push,然后开一个 Pull Request。请不要直接向 `main` 推送,发布闸门会拒绝。
|
想改点什么?流程很短:先 fork 仓库,建一个分支 branch,提交 commit,推送 push,然后开一个 Pull Request。请不要直接向 `main` 推送变更。
|
||||||
|
|
||||||
发现问题?到 [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) 开一个 issue,写清楚你运行了什么、发生了什么。
|
发现问题?到 [https://github.com/zarubinvibe/iriz/issues](https://github.com/zarubinvibe/iriz/issues) 开一个 issue,写清楚你运行了什么、发生了什么。
|
||||||
|
|
||||||
|
|||||||
@@ -519,6 +519,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
|
|
||||||
private lazy var firstRun: FirstRunWindowController = {
|
private lazy var firstRun: FirstRunWindowController = {
|
||||||
let controller = FirstRunWindowController()
|
let controller = FirstRunWindowController()
|
||||||
|
controller.model.openAgentSettings = { [weak self] in
|
||||||
|
self?.openSettings(page: .prompt)
|
||||||
|
}
|
||||||
|
controller.model.onSpeechModelInstalled = { [weak self] in
|
||||||
|
_ = self?.dictationController.prepareAfterModelInstallation()
|
||||||
|
}
|
||||||
// Проба голосом идёт ТЕМ ЖЕ путём, что и обычная диктовка: кнопка
|
// Проба голосом идёт ТЕМ ЖЕ путём, что и обычная диктовка: кнопка
|
||||||
// зовёт тот же обработчик, что и клавиша. Иначе знакомство показывало
|
// зовёт тот же обработчик, что и клавиша. Иначе знакомство показывало
|
||||||
// бы не тот продукт, который человеку достанется.
|
// бы не тот продукт, который человеку достанется.
|
||||||
@@ -649,12 +655,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
//
|
//
|
||||||
// Приглашение НЕ повторяется тем, кто уже прошёл этот путь руками:
|
// Приглашение НЕ повторяется тем, кто уже прошёл этот путь руками:
|
||||||
// решение целиком в firstRunShouldShow.
|
// решение целиком в firstRunShouldShow.
|
||||||
|
let modelInstalled = speechModelCacheExists(for: DictationSettings.shared.speechEngine)
|
||||||
if !interactive,
|
if !interactive,
|
||||||
firstRunShouldShow(defaults: .standard,
|
firstRunShouldShow(defaults: .standard,
|
||||||
permissionsGranted: acc && inp,
|
permissionsGranted: acc && inp,
|
||||||
modelInstalled: speechModelCacheExists(for: .multilingualV3)) {
|
modelInstalled: modelInstalled) {
|
||||||
rslog("First run: showing the welcome window")
|
rslog("First run: showing the welcome window")
|
||||||
firstRun.show()
|
if !modelInstalled && UserDefaults.standard.bool(forKey: FIRST_RUN_COMPLETED_KEY) {
|
||||||
|
firstRun.showModelSetup()
|
||||||
|
} else {
|
||||||
|
firstRun.show()
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1182,6 +1193,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
/// Окно живёт столько же, сколько приложение: пересоздавать его на каждый показ —
|
/// Окно живёт столько же, сколько приложение: пересоздавать его на каждый показ —
|
||||||
/// значит терять несохранённую запись хоткея и позицию окна.
|
/// значит терять несохранённую запись хоткея и позицию окна.
|
||||||
private var settingsWindow: NSWindow?
|
private var settingsWindow: NSWindow?
|
||||||
|
private let settingsNavigation = SettingsNavigation()
|
||||||
|
|
||||||
/// Открыть знакомство заново из меню.
|
/// Открыть знакомство заново из меню.
|
||||||
/// Идёт ли запись встречи. Меню спрашивает, чтобы назвать строку словом
|
/// Идёт ли запись встречи. Меню спрашивает, чтобы назвать строку словом
|
||||||
@@ -1203,7 +1215,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
firstRun.show()
|
firstRun.show()
|
||||||
}
|
}
|
||||||
|
|
||||||
func openSettings(page: SettingsPage = .keys) {
|
func showSpeechModelSetup() {
|
||||||
|
firstRun.showModelSetup()
|
||||||
|
}
|
||||||
|
|
||||||
|
func recoverDictation() {
|
||||||
|
if !menuState.microphoneOK {
|
||||||
|
firstRun.showMicrophoneSetup()
|
||||||
|
} else if menuState.dictationRecoveryNeedsPermissions {
|
||||||
|
recheckPermissions()
|
||||||
|
} else {
|
||||||
|
showSpeechModelSetup()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func openSettings(page: SettingsPage? = nil) {
|
||||||
|
if let page { settingsNavigation.page = page }
|
||||||
if let window = settingsWindow {
|
if let window = settingsWindow {
|
||||||
NSApplication.shared.activate(ignoringOtherApps: true)
|
NSApplication.shared.activate(ignoringOtherApps: true)
|
||||||
window.makeKeyAndOrderFront(nil)
|
window.makeKeyAndOrderFront(nil)
|
||||||
@@ -1211,7 +1238,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
}
|
}
|
||||||
// Окно собирает общая фабрика: прибор снимает ровно это окно, а не
|
// Окно собирает общая фабрика: прибор снимает ровно это окно, а не
|
||||||
// свою копию с другими флагами.
|
// свою копию с другими флагами.
|
||||||
let window = makeIrizSettingsWindow(page: page)
|
let window = makeIrizSettingsWindow(navigation: settingsNavigation,
|
||||||
|
openSpeechModelSetup: { [weak self] in
|
||||||
|
self?.showSpeechModelSetup()
|
||||||
|
})
|
||||||
window.center()
|
window.center()
|
||||||
settingsWindow = window
|
settingsWindow = window
|
||||||
|
|
||||||
@@ -1238,5 +1268,3 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
NSApplication.shared.terminate(nil)
|
NSApplication.shared.terminate(nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -9,9 +9,8 @@
|
|||||||
// следующего переименования кнопки. Здесь кадры собираются из ТЕХ ЖЕ видов,
|
// следующего переименования кнопки. Здесь кадры собираются из ТЕХ ЖЕ видов,
|
||||||
// которыми живёт продукт, и пересобираются одной командой.
|
// которыми живёт продукт, и пересобираются одной командой.
|
||||||
//
|
//
|
||||||
// Язык переключается настройкой, той же, которую владелец меняет в окне: другой
|
// Язык подставляется в штатный поиск настроек через volatile domain: строки
|
||||||
// дороги нет и быть не должно - прибор обязан снимать то, что увидит человек, а
|
// остаются продуктовыми, а пользовательская настройка на диске не меняется.
|
||||||
// не свою параллельную сборку строк.
|
|
||||||
import AppKit
|
import AppKit
|
||||||
import IrizCore
|
import IrizCore
|
||||||
import IrizDictate
|
import IrizDictate
|
||||||
@@ -34,12 +33,15 @@ private struct DocShot {
|
|||||||
func captureDocShots(to directory: URL, appDelegate: AppDelegate) throws -> [URL] {
|
func captureDocShots(to directory: URL, appDelegate: AppDelegate) throws -> [URL] {
|
||||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
|
||||||
attributes: [.posixPermissions: 0o755])
|
attributes: [.posixPermissions: 0o755])
|
||||||
let previous = irizLanguageChoice()
|
let defaults = UserDefaults.standard
|
||||||
defer { setIrizLanguageChoice(previous) }
|
let previous = defaults.volatileDomain(forName: UserDefaults.argumentDomain)
|
||||||
|
defer { defaults.setVolatileDomain(previous, forName: UserDefaults.argumentDomain) }
|
||||||
|
|
||||||
var written: [URL] = []
|
var written: [URL] = []
|
||||||
for language in [IrizLanguage.ru, .en, .zh] {
|
for language in [IrizLanguage.ru, .en, .zh] {
|
||||||
setIrizLanguageChoice(language)
|
var arguments = previous
|
||||||
|
arguments[IRIZ_LANGUAGE_KEY] = language.rawValue
|
||||||
|
defaults.setVolatileDomain(arguments, forName: UserDefaults.argumentDomain)
|
||||||
let tag = language.rawValue
|
let tag = language.rawValue
|
||||||
|
|
||||||
// Настройки: живое окно со стеклом, страница клавиш - её открывают первой.
|
// Настройки: живое окно со стеклом, страница клавиш - её открывают первой.
|
||||||
@@ -140,12 +142,38 @@ private func docShots(appDelegate: AppDelegate) -> [DocShot] {
|
|||||||
view: dictationHistoryShotView(.list)),
|
view: dictationHistoryShotView(.list)),
|
||||||
DocShot(name: "rescue", width: 620, height: 520,
|
DocShot(name: "rescue", width: 620, height: 520,
|
||||||
view: dictationHistoryShotView(.rescue)),
|
view: dictationHistoryShotView(.rescue)),
|
||||||
// Знакомство: единственная поверхность, которая переведена целиком.
|
] + docFirstRunShots()
|
||||||
// Остальные пока показывают русский на любом выбранном языке - у них
|
}
|
||||||
// нет ни одного вызова `L()`, и это честно названо в документации.
|
|
||||||
DocShot(name: "firstrun", width: 620, height: 520,
|
/// Установка в кадре — заданное состояние, без загрузки, разрешений и записи
|
||||||
view: AnyView(FirstRunView(model: FirstRunModel()))),
|
/// настроек. Размер совпадает с FirstRunView: прежние 620×520 обрезали окно.
|
||||||
|
@MainActor
|
||||||
|
private func docFirstRunShots() -> [DocShot] {
|
||||||
|
let scenes: [(name: String, installed: Bool, phase: SpeechModelInstallPhase?)] = [
|
||||||
|
("firstrun", false, nil),
|
||||||
|
("firstrun-model-missing", false, nil),
|
||||||
|
("firstrun-model-downloading", false, .downloading(0.42)),
|
||||||
|
("firstrun-model-failed", false, .failed(speechModelInstallFailureMessage(for: URLError(.notConnectedToInternet)))),
|
||||||
|
("firstrun-model-ready", true, nil),
|
||||||
]
|
]
|
||||||
|
return scenes.map { scene in
|
||||||
|
let defaults = UserDefaults(suiteName: "iriz.docshots.\(UUID().uuidString)")!
|
||||||
|
// Registration domain живёт в памяти. NSArgumentDomain общий для
|
||||||
|
// процесса: его замена здесь стирала язык, выбранный съёмкой выше.
|
||||||
|
defaults.register(defaults: [
|
||||||
|
"ru.smltlk.transcriptCorrectionsSeeded": true,
|
||||||
|
"speech_engine_v1": SpeechModelProfile.multilingualV3.rawValue,
|
||||||
|
])
|
||||||
|
let model = FirstRunModel(defaults: defaults,
|
||||||
|
settings: DictationSettings(defaults: defaults),
|
||||||
|
refreshSystemState: false,
|
||||||
|
modelProbe: { _ in scene.installed })
|
||||||
|
model.refreshModelAvailability()
|
||||||
|
if scene.name != "firstrun" { model.showModelSetup() }
|
||||||
|
if let phase = scene.phase { model.installationDidProgress(phase) }
|
||||||
|
return DocShot(name: scene.name, width: 640, height: 560,
|
||||||
|
view: AnyView(FirstRunView(model: model)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Рабочее состояние меню: модель готова, история не пуста. Аварийные состояния
|
/// Рабочее состояние меню: модель готова, история не пуста. Аварийные состояния
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
// Ничего не выбрать - нормальный исход. Диктовка и раскладка работают без
|
// Ничего не выбрать - нормальный исход. Диктовка и раскладка работают без
|
||||||
// агента, и шаг об этом говорит прямо, а не намекает.
|
// агента, и шаг об этом говорит прямо, а не намекает.
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import IrizCore
|
||||||
|
|
||||||
struct FirstRunAgentConnect: View {
|
struct FirstRunAgentConnect: View {
|
||||||
@ObservedObject var model: FirstRunModel
|
@ObservedObject var model: FirstRunModel
|
||||||
@@ -36,6 +37,15 @@ struct FirstRunAgentConnect: View {
|
|||||||
}
|
}
|
||||||
.frame(maxHeight: 150)
|
.frame(maxHeight: 150)
|
||||||
}
|
}
|
||||||
|
if let error = model.agentConnectionError {
|
||||||
|
Text(error)
|
||||||
|
.font(.system(size: 12.5))
|
||||||
|
.multilineTextAlignment(.center)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
.frame(maxWidth: 430)
|
||||||
|
Button(L("firstrun.agentSettings", "Настройки агента…")) { model.openAgentSettings?() }
|
||||||
|
.modifier(FirstRunTrialButtonStyle())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.onAppear { model.refreshAgents() }
|
.onAppear { model.refreshAgents() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ final class FirstRunModel: ObservableObject {
|
|||||||
/// Модель на диске. Читается живьём при каждом обновлении разрешений: она
|
/// Модель на диске. Читается живьём при каждом обновлении разрешений: она
|
||||||
/// могла приехать и до знакомства.
|
/// могла приехать и до знакомства.
|
||||||
@Published private(set) var modelInstalled = false
|
@Published private(set) var modelInstalled = false
|
||||||
|
var onSpeechModelInstalled: (() -> Void)?
|
||||||
|
|
||||||
/// Агенты, которые уже стоят на этом Маке. Ищутся на диске, а не
|
/// Агенты, которые уже стоят на этом Маке. Ищутся на диске, а не
|
||||||
/// спрашиваются у человека: спросить «где у тебя лежит codex» значит
|
/// спрашиваются у человека: спросить «где у тебя лежит codex» значит
|
||||||
@@ -45,6 +46,8 @@ final class FirstRunModel: ObservableObject {
|
|||||||
@Published private(set) var agents: [FirstRunAgent] = []
|
@Published private(set) var agents: [FirstRunAgent] = []
|
||||||
/// Кто выбран. nil - никто, и это нормальный исход шага.
|
/// Кто выбран. nil - никто, и это нормальный исход шага.
|
||||||
@Published private(set) var connectedAgentID: String?
|
@Published private(set) var connectedAgentID: String?
|
||||||
|
@Published private(set) var agentConnectionError: String?
|
||||||
|
var openAgentSettings: (() -> Void)?
|
||||||
/// Перевод включён. Отдельно от подключения агента: агент нужен обоим
|
/// Перевод включён. Отдельно от подключения агента: агент нужен обоим
|
||||||
/// режимам, но включать их за человека нельзя.
|
/// режимам, но включать их за человека нельзя.
|
||||||
@Published private(set) var translationEnabled = false
|
@Published private(set) var translationEnabled = false
|
||||||
@@ -95,19 +98,68 @@ final class FirstRunModel: ObservableObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private let defaults: UserDefaults
|
private let defaults: UserDefaults
|
||||||
|
private let settings: DictationSettings
|
||||||
|
private let modelProbe: (SpeechModelProfile) -> Bool
|
||||||
private var poll: Timer?
|
private var poll: Timer?
|
||||||
/// Что сделать, когда знакомство кончилось.
|
/// Что сделать, когда знакомство кончилось.
|
||||||
var onFinish: (() -> Void)?
|
var onFinish: (() -> Void)?
|
||||||
|
|
||||||
init(defaults: UserDefaults = .standard) {
|
init(defaults: UserDefaults = .standard,
|
||||||
|
settings: DictationSettings = .shared,
|
||||||
|
refreshSystemState: Bool = true,
|
||||||
|
modelProbe: @escaping (SpeechModelProfile) -> Bool = speechModelCacheExists) {
|
||||||
self.defaults = defaults
|
self.defaults = defaults
|
||||||
refreshPermissions()
|
self.settings = settings
|
||||||
refreshHotkeyLabel()
|
self.modelProbe = modelProbe
|
||||||
refreshTranslationHotkeyLabel()
|
if refreshSystemState {
|
||||||
|
refreshPermissions()
|
||||||
|
refreshHotkeyLabel()
|
||||||
|
refreshTranslationHotkeyLabel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var canGoBack: Bool { firstRunPreviousStep(before: step) != nil }
|
var canGoBack: Bool { firstRunPreviousStep(before: step) != nil }
|
||||||
var isLastStep: Bool { firstRunNextStep(after: step) == nil }
|
var isLastStep: Bool { firstRunNextStep(after: step) == nil }
|
||||||
|
var selectedSpeechModel: SpeechModelProfile { settings.speechEngine }
|
||||||
|
var selectedSpeechModelTitle: String { selectedSpeechModel.shortName }
|
||||||
|
var modelIsReady: Bool {
|
||||||
|
modelInstalled && (installPhase == nil || installPhase == .finished)
|
||||||
|
}
|
||||||
|
var isInstallingModel: Bool {
|
||||||
|
switch installPhase {
|
||||||
|
case .downloading, .compiling: true
|
||||||
|
default: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var modelInstallIsPrimaryAction: Bool {
|
||||||
|
step == .model && !modelIsReady && !isInstallingModel
|
||||||
|
}
|
||||||
|
var nextButtonTitle: String {
|
||||||
|
if isLastStep { return FirstRunCopy.done }
|
||||||
|
if modelInstallIsPrimaryAction {
|
||||||
|
return L("firstrun.model.installLater", "Скачать позже")
|
||||||
|
}
|
||||||
|
return FirstRunCopy.next
|
||||||
|
}
|
||||||
|
|
||||||
|
func refreshModelAvailability() {
|
||||||
|
modelInstalled = modelProbe(settings.speechEngine)
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareForPresentation() {
|
||||||
|
refreshModelAvailability()
|
||||||
|
if !modelInstalled, defaults.bool(forKey: FIRST_RUN_COMPLETED_KEY) {
|
||||||
|
showModelSetup()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func showModelSetup() {
|
||||||
|
step = .model
|
||||||
|
}
|
||||||
|
|
||||||
|
func showMicrophoneSetup() {
|
||||||
|
step = .microphone
|
||||||
|
}
|
||||||
|
|
||||||
func goNext() {
|
func goNext() {
|
||||||
guard firstRunCanAdvance(from: step) else { return }
|
guard firstRunCanAdvance(from: step) else { return }
|
||||||
@@ -159,22 +211,53 @@ final class FirstRunModel: ObservableObject {
|
|||||||
/// Начать установку модели. Идёт в фоне: пока она едет, человек проходит
|
/// Начать установку модели. Идёт в фоне: пока она едет, человек проходит
|
||||||
/// разрешения, и время не тратится дважды.
|
/// разрешения, и время не тратится дважды.
|
||||||
func installModel() {
|
func installModel() {
|
||||||
guard !SpeechModelInstaller.shared.isRunning else { return }
|
guard !SpeechModelInstaller.shared.isRunning else {
|
||||||
|
installationWasRefused(.alreadyRunning)
|
||||||
|
return
|
||||||
|
}
|
||||||
installPhase = .downloading(0)
|
installPhase = .downloading(0)
|
||||||
Task { @MainActor [weak self] in
|
Task { @MainActor [weak self] in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
await SpeechModelInstaller.shared.install(dictating: self.isRecording) { phase in
|
let refusal = await SpeechModelInstaller.shared.install(dictating: self.isRecording) { phase in
|
||||||
Task { @MainActor in
|
self.installationDidProgress(phase)
|
||||||
self.installPhase = phase
|
|
||||||
if case .finished = phase { self.modelInstalled = true }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
if let refusal { self.installationWasRefused(refusal) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func installationDidProgress(_ phase: SpeechModelInstallPhase) {
|
||||||
|
if case .finished = phase {
|
||||||
|
installationDidFinish()
|
||||||
|
} else {
|
||||||
|
installPhase = phase
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func installationWasRefused(_ refusal: SpeechModelInstallRefusal) {
|
||||||
|
switch refusal {
|
||||||
|
case .alreadyInstalled:
|
||||||
|
installationDidFinish()
|
||||||
|
case .alreadyRunning:
|
||||||
|
installPhase = .failed(L("firstrun.modelAlreadyDownloading", "Модель уже скачивается. Дождись окончания установки."))
|
||||||
|
case .dictationBusy:
|
||||||
|
installPhase = .failed(L("firstrun.modelInstallWhileRecording", "Сначала закончи запись, затем повтори установку модели."))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func installationDidFinish() {
|
||||||
|
guard installPhase != .finished || !modelInstalled || settings.speechEngine != .multilingualV3 else { return }
|
||||||
|
settings.speechEngine = .multilingualV3
|
||||||
|
modelInstalled = true
|
||||||
|
installPhase = .finished
|
||||||
|
NotificationCenter.default.post(name: speechModelDidInstallNotification,
|
||||||
|
object: SpeechModelProfile.multilingualV3)
|
||||||
|
NotificationCenter.default.post(name: DictationController.settingsDidSaveNotification,
|
||||||
|
object: settings)
|
||||||
|
onSpeechModelInstalled?()
|
||||||
|
}
|
||||||
|
|
||||||
/// Найти агентов на диске и вспомнить, кто выбран.
|
/// Найти агентов на диске и вспомнить, кто выбран.
|
||||||
func refreshAgents() {
|
func refreshAgents() {
|
||||||
let settings = DictationSettings.shared
|
|
||||||
agents = PromptAgentCatalog.identifiers.compactMap { id in
|
agents = PromptAgentCatalog.identifiers.compactMap { id in
|
||||||
guard let adapter = PromptAgentCatalog.adapter(id: id, customArguments: []) else { return nil }
|
guard let adapter = PromptAgentCatalog.adapter(id: id, customArguments: []) else { return nil }
|
||||||
// Свой CLI без пути искать негде: он и есть «введи путь руками»,
|
// Свой CLI без пути искать негде: он и есть «введи путь руками»,
|
||||||
@@ -190,19 +273,28 @@ final class FirstRunModel: ObservableObject {
|
|||||||
/// Подключить агента: выбрать его и включить режим задания. Включение
|
/// Подключить агента: выбрать его и включить режим задания. Включение
|
||||||
/// сказано вслух на самом шаге - молча уводить речь наружу нельзя.
|
/// сказано вслух на самом шаге - молча уводить речь наружу нельзя.
|
||||||
func connectAgent(_ id: String) {
|
func connectAgent(_ id: String) {
|
||||||
let settings = DictationSettings.shared
|
guard let adapter = PromptAgentCatalog.adapter(id: id) else { return }
|
||||||
|
guard !adapter.requiresModel || !settings.promptAgentModel.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||||
|
agentConnectionError = Lf("firstrun.agentModelRequired", "Для %@ выбери модель в настройках промпт-режима, затем подключи агента здесь.", adapter.displayName)
|
||||||
|
return
|
||||||
|
}
|
||||||
settings.promptAgentID = id
|
settings.promptAgentID = id
|
||||||
settings.promptModeEnabled = true
|
settings.promptModeEnabled = true
|
||||||
connectedAgentID = id
|
connectedAgentID = id
|
||||||
|
agentConnectionError = nil
|
||||||
|
NotificationCenter.default.post(name: DictationController.settingsDidSaveNotification,
|
||||||
|
object: settings)
|
||||||
}
|
}
|
||||||
|
|
||||||
func enableTranslation() {
|
func enableTranslation() {
|
||||||
DictationSettings.shared.translationModeEnabled = true
|
settings.translationModeEnabled = true
|
||||||
translationEnabled = true
|
translationEnabled = true
|
||||||
|
NotificationCenter.default.post(name: DictationController.settingsDidSaveNotification,
|
||||||
|
object: settings)
|
||||||
}
|
}
|
||||||
|
|
||||||
func refreshPermissions() {
|
func refreshPermissions() {
|
||||||
modelInstalled = speechModelCacheExists(for: .multilingualV3)
|
refreshModelAvailability()
|
||||||
refreshAgents()
|
refreshAgents()
|
||||||
var next: [FirstRunPermission: Bool] = [:]
|
var next: [FirstRunPermission: Bool] = [:]
|
||||||
for permission in FirstRunPermission.allCases {
|
for permission in FirstRunPermission.allCases {
|
||||||
@@ -231,7 +323,10 @@ final class FirstRunModel: ObservableObject {
|
|||||||
|
|
||||||
/// Проба голосом. Идёт тем же путём, что и обычная диктовка.
|
/// Проба голосом. Идёт тем же путём, что и обычная диктовка.
|
||||||
func toggleTrial() {
|
func toggleTrial() {
|
||||||
isRecording.toggle()
|
guard modelIsReady else {
|
||||||
|
showModelSetup()
|
||||||
|
return
|
||||||
|
}
|
||||||
toggleDictation?()
|
toggleDictation?()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,7 +364,18 @@ final class FirstRunWindowController: NSObject, NSWindowDelegate {
|
|||||||
private var window: NSWindow?
|
private var window: NSWindow?
|
||||||
let model = FirstRunModel()
|
let model = FirstRunModel()
|
||||||
|
|
||||||
|
func showModelSetup() {
|
||||||
|
model.showModelSetup()
|
||||||
|
show()
|
||||||
|
}
|
||||||
|
|
||||||
|
func showMicrophoneSetup() {
|
||||||
|
show()
|
||||||
|
model.showMicrophoneSetup()
|
||||||
|
}
|
||||||
|
|
||||||
func show() {
|
func show() {
|
||||||
|
model.prepareForPresentation()
|
||||||
// Пока знакомство открыто, приложение перестаёт быть невидимкой из
|
// Пока знакомство открыто, приложение перестаёт быть невидимкой из
|
||||||
// строки меню. Без этого у окна нет ни значка в Dock, ни места в
|
// строки меню. Без этого у окна нет ни значка в Dock, ни места в
|
||||||
// Cmd-Tab: человек уходит в Системные настройки, окно проваливается за
|
// Cmd-Tab: человек уходит в Системные настройки, окно проваливается за
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ enum FirstRunCopy {
|
|||||||
|
|
||||||
/// Подпись у стрелки. Говорит, ЧТО случится от нажатия, а не «нажмите
|
/// Подпись у стрелки. Говорит, ЧТО случится от нажатия, а не «нажмите
|
||||||
/// кнопку»: человек и так видит кнопку, ему нужна причина.
|
/// кнопку»: человек и так видит кнопку, ему нужна причина.
|
||||||
static var hintModel: String { L("firstrun.hintModel", "нажми сюда, качать примерно пять минут") }
|
static var hintModel: String { L("firstrun.hintModel", "Нажми кнопку ниже. iriz сам скачает и установит модель.") }
|
||||||
static var hintMicrophone: String { L("firstrun.hintMicrophone", "нажми сюда") }
|
static var hintMicrophone: String { L("firstrun.hintMicrophone", "нажми сюда") }
|
||||||
static var hintAccessibility: String { L("firstrun.hintAccessibility", "нажми сюда, откроются настройки системы") }
|
static var hintAccessibility: String { L("firstrun.hintAccessibility", "нажми сюда, откроются настройки системы") }
|
||||||
static var hintInputMonitoring: String { L("firstrun.hintInputMonitoring", "нажми сюда, откроются настройки системы") }
|
static var hintInputMonitoring: String { L("firstrun.hintInputMonitoring", "нажми сюда, откроются настройки системы") }
|
||||||
@@ -64,7 +64,8 @@ enum FirstRunCopy {
|
|||||||
title: L("firstrun.welcome.title", "Ты говоришь, я печатаю"),
|
title: L("firstrun.welcome.title", "Ты говоришь, я печатаю"),
|
||||||
body: L("firstrun.welcome.body", "Нажми клавишу, скажи фразу, нажми еще раз. Текст появится там, где стоял "
|
body: L("firstrun.welcome.body", "Нажми клавишу, скажи фразу, нажми еще раз. Текст появится там, где стоял "
|
||||||
+ "курсор: в письме, в чате, в терминале."),
|
+ "курсор: в письме, в чате, в терминале."),
|
||||||
note: L("firstrun.welcome.note", "Все считается прямо на твоем Маке. Ни звук, ни текст никуда не отправляются.")
|
note: L("firstrun.welcome.note", "Перед первой диктовкой скачаем модель распознавания: следующий шаг покажет кнопку установки. "
|
||||||
|
+ "После этого речь будет распознаваться на твоём Маке, без интернета.")
|
||||||
) }
|
) }
|
||||||
|
|
||||||
static var whereItLives: Step { Step(
|
static var whereItLives: Step { Step(
|
||||||
@@ -77,13 +78,14 @@ enum FirstRunCopy {
|
|||||||
) }
|
) }
|
||||||
|
|
||||||
static var model: Step { Step(
|
static var model: Step { Step(
|
||||||
title: L("firstrun.model.title", "Скачаем распознавание"),
|
title: L("firstrun.model.title", "Установи распознавание речи"),
|
||||||
body: L("firstrun.model.body", "Речь я разбираю прямо у тебя на Маке, без интернета. Для этого нужна модель: "
|
body: L("firstrun.model.body", "Без модели диктовка не работает. Кнопка ниже скачает Parakeet, "
|
||||||
+ "полгигабайта, качается один раз."),
|
+ "установит его в нужную папку и выберет для распознавания."),
|
||||||
note: L("firstrun.model.note", "В образе её нет намеренно: модель обновляется чаще, чем сам iriz. "
|
note: L("firstrun.model.note", "Скачается около 500 МБ. Нужны интернет и свободное место на диске. "
|
||||||
+ "Клади её отдельно: иначе вместе с программой приедет устаревшая.\n\n"
|
+ "Скорость зависит от соединения; ход установки появится здесь. "
|
||||||
+ "Пока она скачивается, продолжай: разрешения можно выдать прямо сейчас."),
|
+ "Файлы вручную искать и переносить не нужно.\n\n"
|
||||||
action: L("firstrun.model.action", "Скачать модель")
|
+ "Пока модель скачивается, можно перейти к разрешениям. Диктовку попробуем после установки."),
|
||||||
|
action: L("firstrun.model.action", "Скачать и установить Parakeet")
|
||||||
) }
|
) }
|
||||||
|
|
||||||
static var modelReady: String { L("firstrun.modelReady", "Модель на месте") }
|
static var modelReady: String { L("firstrun.modelReady", "Модель на месте") }
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ struct FirstRunDictationField: NSViewRepresentable {
|
|||||||
func makeNSView(context: Context) -> FirstRunFieldBox {
|
func makeNSView(context: Context) -> FirstRunFieldBox {
|
||||||
let textView = FirstRunTextView()
|
let textView = FirstRunTextView()
|
||||||
textView.placeholder = placeholder
|
textView.placeholder = placeholder
|
||||||
|
textView.setAccessibilityLabel(placeholder)
|
||||||
textView.delegate = context.coordinator
|
textView.delegate = context.coordinator
|
||||||
textView.font = .systemFont(ofSize: 14)
|
textView.font = .systemFont(ofSize: 14)
|
||||||
textView.isEditable = true
|
textView.isEditable = true
|
||||||
@@ -56,6 +57,7 @@ struct FirstRunDictationField: NSViewRepresentable {
|
|||||||
guard let textView = box.textView else { return }
|
guard let textView = box.textView else { return }
|
||||||
if textView.string != text { textView.string = text }
|
if textView.string != text { textView.string = text }
|
||||||
textView.placeholder = placeholder
|
textView.placeholder = placeholder
|
||||||
|
textView.setAccessibilityLabel(placeholder)
|
||||||
context.coordinator.onSubmit = onSubmit
|
context.coordinator.onSubmit = onSubmit
|
||||||
// Курсор ставится в это поле и остаётся здесь: диктовка вставляет
|
// Курсор ставится в это поле и остаётся здесь: диктовка вставляет
|
||||||
// текст туда, где он мигает.
|
// текст туда, где он мигает.
|
||||||
|
|||||||
@@ -24,7 +24,16 @@ struct FirstRunKeyTrial: View {
|
|||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 12) {
|
VStack(spacing: 12) {
|
||||||
if canHearKey {
|
if !model.modelIsReady {
|
||||||
|
Text(model.isInstallingModel
|
||||||
|
? L("firstrun.trialModelDownloading", "Модель ещё скачивается. Ход установки виден на её странице.")
|
||||||
|
: L("firstrun.trialModelMissing", "Модель ещё не установлена. Кнопка ниже вернёт к скачиванию."))
|
||||||
|
.font(.system(size: 13, weight: .medium))
|
||||||
|
.multilineTextAlignment(.center)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Button(L("firstrun.trialOpenModelSetup", "К установке модели")) { model.showModelSetup() }
|
||||||
|
.modifier(FirstRunProminentButton())
|
||||||
|
} else if canHearKey {
|
||||||
// Сама клавиша и есть кнопка замены. Строчка «Клавиша занята?
|
// Сама клавиша и есть кнопка замены. Строчка «Клавиша занята?
|
||||||
// Поменять» снизу была незаметна: владелец 07.09.2026 сказал
|
// Поменять» снизу была незаметна: владелец 07.09.2026 сказал
|
||||||
// прямо — «снизу не очень заметно… необходимо, чтобы вот та
|
// прямо — «снизу не очень заметно… необходимо, чтобы вот та
|
||||||
@@ -88,11 +97,13 @@ struct FirstRunKeyTrial: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
FirstRunDictationField(text: $model.tryItText,
|
if model.modelIsReady {
|
||||||
placeholder: FirstRunCopy.trialFieldPlaceholder,
|
FirstRunDictationField(text: $model.tryItText,
|
||||||
onSubmit: { model.goNext() })
|
placeholder: FirstRunCopy.trialFieldPlaceholder,
|
||||||
.frame(height: 68)
|
onSubmit: { model.goNext() })
|
||||||
.frame(maxWidth: 440)
|
.frame(height: 68)
|
||||||
|
.frame(maxWidth: 440)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ import Foundation
|
|||||||
import IrizCore
|
import IrizCore
|
||||||
|
|
||||||
/// Шаги знакомства. Порядок - это и есть сценарий, и он не случайный: сначала
|
/// Шаги знакомства. Порядок - это и есть сценарий, и он не случайный: сначала
|
||||||
/// «что это» и «где оно живёт», потом разрешения от самого понятного к самому
|
/// «что это» и установка распознавания, затем «где оно живёт», разрешения от
|
||||||
/// пугающему, и только потом проба голосом. Человек, которому уже объяснили,
|
/// самого понятного к самому пугающему и проба голосом. Человек, которому уже объяснили,
|
||||||
/// зачем нужен микрофон, спокойнее отвечает на «сможет читать все нажатия».
|
/// зачем нужен микрофон, спокойнее отвечает на «сможет читать все нажатия».
|
||||||
enum FirstRunStep: String, CaseIterable, Equatable {
|
enum FirstRunStep: String, CaseIterable, Equatable {
|
||||||
case welcome
|
case welcome
|
||||||
case whereItLives
|
|
||||||
case model
|
case model
|
||||||
|
case whereItLives
|
||||||
case microphone
|
case microphone
|
||||||
case accessibility
|
case accessibility
|
||||||
case inputMonitoring
|
case inputMonitoring
|
||||||
@@ -103,11 +103,11 @@ let FIRST_RUN_COMPLETED_KEY = "ru.smltlk.firstRunCompleted"
|
|||||||
func firstRunShouldShow(defaults: UserDefaults,
|
func firstRunShouldShow(defaults: UserDefaults,
|
||||||
permissionsGranted: Bool,
|
permissionsGranted: Bool,
|
||||||
modelInstalled: Bool = true) -> Bool {
|
modelInstalled: Bool = true) -> Bool {
|
||||||
if defaults.bool(forKey: FIRST_RUN_COMPLETED_KEY) { return false }
|
|
||||||
// Без модели продукт не работает вовсе, а поставить её можно только
|
// Без модели продукт не работает вовсе, а поставить её можно только
|
||||||
// отсюда. Человек с выданными разрешениями и пустым диском иначе не увидел
|
// отсюда. Человек с выданными разрешениями и пустым диском иначе не увидел
|
||||||
// бы ни знакомства, ни модели - только отказ распознавания.
|
// бы ни знакомства, ни модели - только отказ распознавания.
|
||||||
if !modelInstalled { return true }
|
if !modelInstalled { return true }
|
||||||
|
if defaults.bool(forKey: FIRST_RUN_COMPLETED_KEY) { return false }
|
||||||
// Разрешения уже выданы - значит человек прошёл этот путь руками до того,
|
// Разрешения уже выданы - значит человек прошёл этот путь руками до того,
|
||||||
// как знакомство появилось в продукте. Ему показывать нечего.
|
// как знакомство появилось в продукте. Ему показывать нечего.
|
||||||
return !permissionsGranted
|
return !permissionsGranted
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// который не видит движения, через минуту решает, что зависло, и закрывает
|
// который не видит движения, через минуту решает, что зависло, и закрывает
|
||||||
// окно. Идти дальше при этом можно сразу - загрузка не держит знакомство.
|
// окно. Идти дальше при этом можно сразу - загрузка не держит знакомство.
|
||||||
import IrizDictate
|
import IrizDictate
|
||||||
|
import IrizCore
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
struct FirstRunModelInstall: View {
|
struct FirstRunModelInstall: View {
|
||||||
@@ -11,11 +12,7 @@ struct FirstRunModelInstall: View {
|
|||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 10) {
|
VStack(spacing: 10) {
|
||||||
if model.modelInstalled {
|
if let phase = model.installPhase, phase != .finished {
|
||||||
Text(FirstRunCopy.modelReady)
|
|
||||||
.font(.system(size: 13, weight: .medium))
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
} else if let phase = model.installPhase {
|
|
||||||
switch phase {
|
switch phase {
|
||||||
case .failed(let reason):
|
case .failed(let reason):
|
||||||
Text(reason)
|
Text(reason)
|
||||||
@@ -25,6 +22,7 @@ struct FirstRunModelInstall: View {
|
|||||||
.frame(maxWidth: 420)
|
.frame(maxWidth: 420)
|
||||||
Button(FirstRunCopy.modelFailedRetry) { model.installModel() }
|
Button(FirstRunCopy.modelFailedRetry) { model.installModel() }
|
||||||
.modifier(FirstRunProminentButton())
|
.modifier(FirstRunProminentButton())
|
||||||
|
.keyboardShortcut(.defaultAction)
|
||||||
default:
|
default:
|
||||||
Text(speechModelInstallTitle(phase))
|
Text(speechModelInstallTitle(phase))
|
||||||
.font(.system(size: 13, weight: .medium))
|
.font(.system(size: 13, weight: .medium))
|
||||||
@@ -32,12 +30,23 @@ struct FirstRunModelInstall: View {
|
|||||||
.progressViewStyle(.linear)
|
.progressViewStyle(.linear)
|
||||||
.frame(width: 260)
|
.frame(width: 260)
|
||||||
}
|
}
|
||||||
|
} else if model.modelInstalled {
|
||||||
|
Text(FirstRunCopy.modelReady)
|
||||||
|
.font(.system(size: 13, weight: .medium))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
if model.selectedSpeechModel == .multilingualV3 {
|
||||||
|
Button(L("firstrun.model.verifyRepair", "Проверить и восстановить Parakeet")) {
|
||||||
|
model.installModel()
|
||||||
|
}
|
||||||
|
.buttonStyle(.bordered)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Text(FirstRunCopy.hintModel)
|
Text(FirstRunCopy.hintModel)
|
||||||
.font(.system(size: 12.5, weight: .medium))
|
.font(.system(size: 12.5, weight: .medium))
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
Button(FirstRunCopy.model.action ?? "") { model.installModel() }
|
Button(FirstRunCopy.model.action ?? "") { model.installModel() }
|
||||||
.modifier(FirstRunProminentButton())
|
.modifier(FirstRunProminentButton())
|
||||||
|
.keyboardShortcut(.defaultAction)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,19 +46,26 @@ struct FirstRunView: View {
|
|||||||
FirstRunHero(step: step)
|
FirstRunHero(step: step)
|
||||||
.frame(height: 96)
|
.frame(height: 96)
|
||||||
|
|
||||||
Text(step.copy.title)
|
Text(step == .model && model.modelIsReady
|
||||||
|
? L("firstrun.model.alreadyReadyTitle", "Распознавание уже установлено")
|
||||||
|
: step.copy.title)
|
||||||
.font(.system(size: 27, weight: .semibold))
|
.font(.system(size: 27, weight: .semibold))
|
||||||
.multilineTextAlignment(.center)
|
.multilineTextAlignment(.center)
|
||||||
.fixedSize(horizontal: false, vertical: true)
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
|
||||||
Text(step.copy.body)
|
Text(step == .model && model.modelIsReady
|
||||||
|
? Lf("firstrun.model.alreadyReadyBody", "%@ готов к диктовке. Скачивать ничего не нужно.", model.selectedSpeechModelTitle)
|
||||||
|
: (step == .tryIt && !model.modelIsReady
|
||||||
|
? L("firstrun.trialNeedsModel", "Перед первой диктовкой нужно скачать модель распознавания.")
|
||||||
|
: step.copy.body))
|
||||||
.font(.system(size: 15))
|
.font(.system(size: 15))
|
||||||
.foregroundStyle(.primary.opacity(0.88))
|
.foregroundStyle(.primary.opacity(0.88))
|
||||||
.multilineTextAlignment(.center)
|
.multilineTextAlignment(.center)
|
||||||
.fixedSize(horizontal: false, vertical: true)
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
.frame(maxWidth: 440)
|
.frame(maxWidth: 440)
|
||||||
|
|
||||||
if let note = step.copy.note {
|
if let note = step.copy.note, !(step == .model && model.modelIsReady),
|
||||||
|
!(step == .tryIt && !model.modelIsReady) {
|
||||||
Text(note)
|
Text(note)
|
||||||
.font(.system(size: 12.5))
|
.font(.system(size: 12.5))
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
@@ -110,9 +117,14 @@ struct FirstRunView: View {
|
|||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
}
|
}
|
||||||
Spacer()
|
Spacer()
|
||||||
Button(model.isLastStep ? FirstRunCopy.done : FirstRunCopy.next) { model.goNext() }
|
if model.modelInstallIsPrimaryAction {
|
||||||
.modifier(FirstRunProminentButton())
|
Button(model.nextButtonTitle) { model.goNext() }
|
||||||
.keyboardShortcut(.defaultAction)
|
.buttonStyle(.bordered)
|
||||||
|
} else {
|
||||||
|
Button(model.nextButtonTitle) { model.goNext() }
|
||||||
|
.modifier(FirstRunProminentButton())
|
||||||
|
.keyboardShortcut(.defaultAction)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.overlay { FirstRunProgress(step: step) }
|
.overlay { FirstRunProgress(step: step) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -192,7 +192,7 @@ struct MenuContentView: View {
|
|||||||
case .fault(let reason):
|
case .fault(let reason):
|
||||||
actionRow(L("menu.dictation", "Диктовка"), key: reason, target: .dictation) {
|
actionRow(L("menu.dictation", "Диктовка"), key: reason, target: .dictation) {
|
||||||
chrome.close()
|
chrome.close()
|
||||||
appDelegate.recheckPermissions()
|
appDelegate.recoverDictation()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -342,7 +342,7 @@ struct MenuContentView: View {
|
|||||||
order.append(.mode)
|
order.append(.mode)
|
||||||
order.append(.layout)
|
order.append(.layout)
|
||||||
if case .fault = state.dictationHint { order.append(.dictation) }
|
if case .fault = state.dictationHint { order.append(.dictation) }
|
||||||
order += [.settings, .quit]
|
order += [.meeting, .history, .welcome, .settings, .quit]
|
||||||
return order
|
return order
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -361,10 +361,14 @@ struct MenuContentView: View {
|
|||||||
/// стрелки ← → обрабатывают сами, им активация не нужна.
|
/// стрелки ← → обрабатывают сами, им активация не нужна.
|
||||||
private func activateFocused() -> Bool {
|
private func activateFocused() -> Bool {
|
||||||
switch focus {
|
switch focus {
|
||||||
case .permissions, .dictation:
|
case .permissions:
|
||||||
chrome.close()
|
chrome.close()
|
||||||
appDelegate.recheckPermissions()
|
appDelegate.recheckPermissions()
|
||||||
return true
|
return true
|
||||||
|
case .dictation:
|
||||||
|
chrome.close()
|
||||||
|
appDelegate.recoverDictation()
|
||||||
|
return true
|
||||||
case .meeting:
|
case .meeting:
|
||||||
chrome.close()
|
chrome.close()
|
||||||
appDelegate.toggleMeetingRecording()
|
appDelegate.toggleMeetingRecording()
|
||||||
|
|||||||
@@ -69,6 +69,11 @@ final class MenuState: ObservableObject {
|
|||||||
/// Раскладка работает, только когда выданы оба разрешения.
|
/// Раскладка работает, только когда выданы оба разрешения.
|
||||||
var permissionsOK: Bool { accessibilityOK && inputMonitoringOK }
|
var permissionsOK: Bool { accessibilityOK && inputMonitoringOK }
|
||||||
|
|
||||||
|
/// Ошибка модели не должна отправлять проверять уже выданные разрешения.
|
||||||
|
var dictationRecoveryNeedsPermissions: Bool {
|
||||||
|
!permissionsOK || !microphoneOK || !inputTapOK
|
||||||
|
}
|
||||||
|
|
||||||
/// Версия из бандла — показывается в окне настроек, не в меню.
|
/// Версия из бандла — показывается в окне настроек, не в меню.
|
||||||
var version: String {
|
var version: String {
|
||||||
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev"
|
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev"
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ import IrizSettings
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
func makeIrizSettingsWindow(preview: Bool = false, page: SettingsPage = .keys) -> NSWindow {
|
func makeIrizSettingsWindow(preview: Bool = false, page: SettingsPage = .keys,
|
||||||
|
navigation: SettingsNavigation? = nil,
|
||||||
|
openSpeechModelSetup: (() -> Void)? = nil) -> NSWindow {
|
||||||
let window = NSWindow(
|
let window = NSWindow(
|
||||||
// Окно шире прежнего: слева боковик со страницами, справа сама
|
// Окно шире прежнего: слева боковик со страницами, справа сама
|
||||||
// страница. В 700 pt на две колонки не помещалось ничего.
|
// страница. В 700 pt на две колонки не помещалось ничего.
|
||||||
@@ -41,7 +43,9 @@ func makeIrizSettingsWindow(preview: Bool = false, page: SettingsPage = .keys) -
|
|||||||
// `.fullSizeContentView` сохраняет системную рамку. Замер по кадру дал
|
// `.fullSizeContentView` сохраняет системную рамку. Замер по кадру дал
|
||||||
// радиус около 27 pt при зашитых 16, то есть своя маска ещё и врала бы.
|
// радиус около 27 pt при зашитых 16, то есть своя маска ещё и врала бы.
|
||||||
window.contentMinSize = NSSize(width: 900, height: 620)
|
window.contentMinSize = NSSize(width: 900, height: 620)
|
||||||
window.contentView = NSHostingView(rootView: IrizSettingsView(preview: preview, page: page))
|
window.contentView = NSHostingView(rootView: IrizSettingsView(preview: preview, page: page,
|
||||||
|
navigation: navigation,
|
||||||
|
openSpeechModelSetup: openSpeechModelSetup))
|
||||||
window.isReleasedWhenClosed = false // иначе закрытие окна уронит приложение
|
window.isReleasedWhenClosed = false // иначе закрытие окна уронит приложение
|
||||||
return window
|
return window
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,12 +58,14 @@ public extension Animation {
|
|||||||
/// Нажатие. Без отклика кнопка кажется картинкой: нажал, ничего не шевельнулось.
|
/// Нажатие. Без отклика кнопка кажется картинкой: нажал, ничего не шевельнулось.
|
||||||
/// 0.97 - предел, за которым сжатие уже видно как трюк.
|
/// 0.97 - предел, за которым сжатие уже видно как трюк.
|
||||||
public struct IrizPressStyle: ButtonStyle {
|
public struct IrizPressStyle: ButtonStyle {
|
||||||
|
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||||
|
|
||||||
public init() {}
|
public init() {}
|
||||||
|
|
||||||
public func makeBody(configuration: Configuration) -> some View {
|
public func makeBody(configuration: Configuration) -> some View {
|
||||||
configuration.label
|
configuration.label
|
||||||
.scaleEffect(configuration.isPressed ? 0.97 : 1)
|
.scaleEffect(configuration.isPressed && !reduceMotion ? 0.97 : 1)
|
||||||
.animation(.irizQuick, value: configuration.isPressed)
|
.animation(reduceMotion ? nil : .irizQuick, value: configuration.isPressed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
"firstrun.hintAccessibility" = "click here, System Settings will open";
|
"firstrun.hintAccessibility" = "click here, System Settings will open";
|
||||||
"firstrun.hintInputMonitoring" = "click here, System Settings will open";
|
"firstrun.hintInputMonitoring" = "click here, System Settings will open";
|
||||||
"firstrun.hintMicrophone" = "click here";
|
"firstrun.hintMicrophone" = "click here";
|
||||||
"firstrun.hintModel" = "click here, about five minutes to download";
|
"firstrun.hintModel" = "Click below. iriz downloads and installs the model for you.";
|
||||||
"firstrun.inputMonitoring.body" = "macOS calls it \"Input Monitoring\" and warns that I'll be able to see your keystrokes in every app. Those are its words, not mine.";
|
"firstrun.inputMonitoring.body" = "macOS calls it \"Input Monitoring\" and warns that I'll be able to see your keystrokes in every app. Those are its words, not mine.";
|
||||||
"firstrun.inputMonitoring.note" = "I need two things: to know you pressed the dictation key, and to notice a phrase typed in the wrong keyboard layout. I see keystrokes only here, on your Mac: I save nothing and send nothing anywhere, and I don't work in password fields at all.\n\nRight after that I'll restart. macOS requires it, nothing is broken.";
|
"firstrun.inputMonitoring.note" = "I need two things: to know you pressed the dictation key, and to notice a phrase typed in the wrong keyboard layout. I see keystrokes only here, on your Mac: I save nothing and send nothing anywhere, and I don't work in password fields at all.\n\nRight after that I'll restart. macOS requires it, nothing is broken.";
|
||||||
"firstrun.inputMonitoring.title" = "One permission left: the keyboard";
|
"firstrun.inputMonitoring.title" = "One permission left: the keyboard";
|
||||||
@@ -23,10 +23,10 @@
|
|||||||
"firstrun.microphone.body" = "Without it I won't hear a word, so let's start there.";
|
"firstrun.microphone.body" = "Without it I won't hear a word, so let's start there.";
|
||||||
"firstrun.microphone.note" = "The audio is never saved: it lives exactly as long as it takes to work out what you said.";
|
"firstrun.microphone.note" = "The audio is never saved: it lives exactly as long as it takes to work out what you said.";
|
||||||
"firstrun.microphone.title" = "Microphone needed";
|
"firstrun.microphone.title" = "Microphone needed";
|
||||||
"firstrun.model.action" = "Download model";
|
"firstrun.model.action" = "Download and install Parakeet";
|
||||||
"firstrun.model.body" = "I turn speech into text right on your Mac, no internet. For that I need a model: half a gigabyte, downloaded once.";
|
"firstrun.model.body" = "Dictation needs a speech model. The button below downloads Parakeet, installs it in the right folder and selects it for recognition.";
|
||||||
"firstrun.model.note" = "It is deliberately not inside the disk image: the model updates more often than iriz itself. Keep it separate: otherwise an outdated one would ship along with the program.\n\nCarry on while it downloads: you can grant the permissions right now.";
|
"firstrun.model.note" = "The download is about 500 MB. You need internet access and free disk space. Speed depends on your connection; progress appears here. No need to find or move files yourself.\n\nYou can grant permissions while the model downloads. We will try dictation after installation.";
|
||||||
"firstrun.model.title" = "Let's get the speech model";
|
"firstrun.model.title" = "Install speech recognition";
|
||||||
"firstrun.modelFailedRetry" = "Try again";
|
"firstrun.modelFailedRetry" = "Try again";
|
||||||
"firstrun.modelReady" = "Model is in place";
|
"firstrun.modelReady" = "Model is in place";
|
||||||
"firstrun.next" = "Next";
|
"firstrun.next" = "Next";
|
||||||
@@ -52,7 +52,7 @@
|
|||||||
"firstrun.tryIt.note" = "The text lands in the field below and nowhere else: while this window is open, I type only here.";
|
"firstrun.tryIt.note" = "The text lands in the field below and nowhere else: while this window is open, I type only here.";
|
||||||
"firstrun.tryIt.title" = "Try it right now";
|
"firstrun.tryIt.title" = "Try it right now";
|
||||||
"firstrun.welcome.body" = "Press the key, say a sentence, press it again. The text appears where your cursor was: in an email, in a chat, in the terminal.";
|
"firstrun.welcome.body" = "Press the key, say a sentence, press it again. The text appears where your cursor was: in an email, in a chat, in the terminal.";
|
||||||
"firstrun.welcome.note" = "It all runs right on your Mac. No audio, no text leaves it.";
|
"firstrun.welcome.note" = "Before your first dictation, download a speech model using the install button on the next step. Then speech recognition runs on your Mac, without internet access.";
|
||||||
"firstrun.welcome.title" = "You talk, I type";
|
"firstrun.welcome.title" = "You talk, I type";
|
||||||
"firstrun.whenItBreaks.body" = "Text didn't paste? It isn't lost. The badge expands and shows it, and you can copy it from there.";
|
"firstrun.whenItBreaks.body" = "Text didn't paste? It isn't lost. The badge expands and shows it, and you can copy it from there.";
|
||||||
"firstrun.whenItBreaks.note" = "Misheard a word? Just correct it right in the text. I notice the edit and ask whether to remember it: say yes, and from then on I write it your way. I never put anything into the dictionary on my own.\n\nKey taken by another app? Click it in the settings and set your own shortcut.\n\nThis window, the settings and the history all open from the icon in the menu bar.";
|
"firstrun.whenItBreaks.note" = "Misheard a word? Just correct it right in the text. I notice the edit and ask whether to remember it: say yes, and from then on I write it your way. I never put anything into the dictionary on my own.\n\nKey taken by another app? Click it in the settings and set your own shortcut.\n\nThis window, the settings and the history all open from the icon in the menu bar.";
|
||||||
@@ -332,3 +332,78 @@
|
|||||||
"snippets.delete.a11y" = "Delete snippet %d";
|
"snippets.delete.a11y" = "Delete snippet %d";
|
||||||
"snippets.phrase.a11y" = "Snippet phrase %d";
|
"snippets.phrase.a11y" = "Snippet phrase %d";
|
||||||
"snippets.text.a11y" = "Snippet text %d";
|
"snippets.text.a11y" = "Snippet text %d";
|
||||||
|
|
||||||
|
/* UI Stack: обработка, восстановление и доступность. */
|
||||||
|
"files.choose" = "Choose files";
|
||||||
|
"files.destinationExists" = "Text already exists: %@. Open it or rename the source recording before retrying.";
|
||||||
|
"files.finished" = "Completed: %d of %d.";
|
||||||
|
"files.language" = "Recording language";
|
||||||
|
"files.languageAuto" = "Detect automatically";
|
||||||
|
"files.noSpeech" = "No speech recognized. No text file was created.";
|
||||||
|
"files.openFailed" = "Could not open %@. Check the file in Finder.";
|
||||||
|
"files.openText" = "Open text";
|
||||||
|
"files.preparing" = "loading the model";
|
||||||
|
"files.reading" = "reading the recording";
|
||||||
|
"files.refused" = "Files not accepted: %d. Choose readable recordings: %@.";
|
||||||
|
"files.retry" = "Retry remaining files";
|
||||||
|
"files.saving" = "saving text";
|
||||||
|
"files.showDestination" = "Show output folder";
|
||||||
|
"files.showInFinder" = "Show in Finder";
|
||||||
|
"files.start" = "Transcribe recordings";
|
||||||
|
"files.stopAfterCurrent" = "Stop after the current recording";
|
||||||
|
"files.stopped" = "Queue stopped. You can start the remaining files again.";
|
||||||
|
"files.stopping" = "Stopping after the current recording…";
|
||||||
|
"files.transcribing" = "transcribing";
|
||||||
|
"firstrun.agentModelRequired" = "Choose a model for %@ in prompt settings, then connect the agent here.";
|
||||||
|
"firstrun.agentSettings" = "Agent settings…";
|
||||||
|
"firstrun.modelAlreadyDownloading" = "The model is already downloading. Wait for installation to finish.";
|
||||||
|
"firstrun.modelInstallWhileRecording" = "Finish recording, then try installing the model again.";
|
||||||
|
"history.clearFailed" = "Could not move %d of %d recordings to the Trash. The others are already in the Trash.";
|
||||||
|
"history.clearing" = "Preparing and clearing history…";
|
||||||
|
"history.copiedTimed" = "Copied. The clipboard will clear in 2 minutes.";
|
||||||
|
"history.copyFailed" = "Could not copy. Try again.";
|
||||||
|
"history.deleteFailed" = "Could not move the recording to the Trash. Try again.";
|
||||||
|
"history.readFailed" = "Could not read history. Try opening it again.";
|
||||||
|
"hud.toggleExpanded" = "Expand or collapse overlay";
|
||||||
|
"meeting.close" = "Close";
|
||||||
|
"meeting.discardUnsaved" = "Delete unsaved recording";
|
||||||
|
"meeting.emptyRecording" = "No audio was recorded";
|
||||||
|
"meeting.emptyRecording.help" = "Check your microphone and record the meeting again.";
|
||||||
|
"meeting.openProtocol" = "Open transcript";
|
||||||
|
"meeting.processingFailed" = "Could not process the meeting";
|
||||||
|
"meeting.protocolReady" = "Meeting transcript is ready";
|
||||||
|
"meeting.recordingSaved" = "The recording is saved. Retry processing or find it in Finder.";
|
||||||
|
"meeting.retryProcessing" = "Retry processing";
|
||||||
|
"meeting.retrySave" = "Retry saving";
|
||||||
|
"meeting.saveFailed" = "Could not save the meeting recording";
|
||||||
|
"meeting.saveFailed.help" = "The audio is still in memory. Free some disk space and retry saving. Deleting the recording cannot be undone.";
|
||||||
|
"meeting.showRecording" = "Show recording";
|
||||||
|
"meeting.speakersUnresolved" = "Speakers could not be separated. The text was saved as one turn.";
|
||||||
|
"meeting.title" = "Meeting";
|
||||||
|
"meetings.openProtocol" = "Open transcript";
|
||||||
|
"meetings.showFolder" = "Show meeting folder";
|
||||||
|
"meetings.speakersUnresolved" = "%@: speakers could not be separated. The text is saved as one turn; check the transcript.";
|
||||||
|
"meetings.storage" = "Recording in Russian. Audio and transcript are saved in the iriz archive; you can open the completed files here.";
|
||||||
|
"settings.speechModelInstalled" = "%@: model installed";
|
||||||
|
"settings.speechModelMissing" = "%@: model not installed";
|
||||||
|
"settings.speechModelDownloadHelp" = "Speech recognition needs a model on this Mac. Automatic download is available only for Parakeet: about 0.5 GB, once. It becomes the selected recognizer after installation. Audio stays on your device.";
|
||||||
|
"settings.speechModelSetup" = "Set up speech recognition…";
|
||||||
|
"settings.downloadParakeet" = "Download Parakeet model…";
|
||||||
|
"settings.parakeetAlreadyAvailable" = "Parakeet is already installed. Select it and save settings to use it for dictation.";
|
||||||
|
"settings.selectInstalledParakeet" = "Select installed Parakeet";
|
||||||
|
"firstrun.model.installLater" = "Download later";
|
||||||
|
"firstrun.model.alreadyReadyTitle" = "Speech recognition is installed";
|
||||||
|
"firstrun.model.alreadyReadyBody" = "%@ is ready for dictation. No download needed.";
|
||||||
|
"firstrun.trialNeedsModel" = "Download a speech model before your first dictation.";
|
||||||
|
"firstrun.trialModelDownloading" = "The model is still downloading. You can see progress on its setup page.";
|
||||||
|
"firstrun.trialModelMissing" = "The model is not installed yet. The button below takes you to the download.";
|
||||||
|
"firstrun.trialOpenModelSetup" = "Set up the model";
|
||||||
|
"firstrun.model.verifyRepair" = "Check and repair Parakeet";
|
||||||
|
"speechModel.downloading" = "Downloading speech model";
|
||||||
|
"speechModel.verifying" = "Verifying downloaded model";
|
||||||
|
"speechModel.ready" = "Model installed";
|
||||||
|
"speechModel.failed" = "Download failed";
|
||||||
|
"speechModel.error.offline" = "No internet connection. Connect to a network and retry the download.";
|
||||||
|
"speechModel.error.connectionLost" = "The connection was lost. Check your internet connection and retry the download.";
|
||||||
|
"speechModel.error.timeout" = "The server did not respond in time. Retry the download later.";
|
||||||
|
"speechModel.error.cancelled" = "The download was cancelled. You can start it again.";
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
"firstrun.hintAccessibility" = "点这里,打开系统设置";
|
"firstrun.hintAccessibility" = "点这里,打开系统设置";
|
||||||
"firstrun.hintInputMonitoring" = "点这里,打开系统设置";
|
"firstrun.hintInputMonitoring" = "点这里,打开系统设置";
|
||||||
"firstrun.hintMicrophone" = "点这里";
|
"firstrun.hintMicrophone" = "点这里";
|
||||||
"firstrun.hintModel" = "点这里,下载大约要五分钟";
|
"firstrun.hintModel" = "点击下方按钮,iriz 会自动下载并安装模型。";
|
||||||
"firstrun.inputMonitoring.body" = "macOS 会把它叫做「输入监控」,还会警告你:我能看到所有程序里的按键。这是它的措辞,不是我的。";
|
"firstrun.inputMonitoring.body" = "macOS 会把它叫做「输入监控」,还会警告你:我能看到所有程序里的按键。这是它的措辞,不是我的。";
|
||||||
"firstrun.inputMonitoring.note" = "我只需要两件事:知道你按下了听写键,以及发现有句话是在错的键盘布局下打的。按键只在你这台 Mac 上看,不保存,不外发,密码框里我根本不工作。\n\n之后我会立刻重启。这是 macOS 的要求,不是出了故障。";
|
"firstrun.inputMonitoring.note" = "我只需要两件事:知道你按下了听写键,以及发现有句话是在错的键盘布局下打的。按键只在你这台 Mac 上看,不保存,不外发,密码框里我根本不工作。\n\n之后我会立刻重启。这是 macOS 的要求,不是出了故障。";
|
||||||
"firstrun.inputMonitoring.title" = "还差按键权限";
|
"firstrun.inputMonitoring.title" = "还差按键权限";
|
||||||
@@ -24,10 +24,10 @@
|
|||||||
"firstrun.microphone.body" = "没有它我一个字也听不见,所以先从它开始。";
|
"firstrun.microphone.body" = "没有它我一个字也听不见,所以先从它开始。";
|
||||||
"firstrun.microphone.note" = "声音不会保存到任何地方:它只留到把话听明白为止。";
|
"firstrun.microphone.note" = "声音不会保存到任何地方:它只留到把话听明白为止。";
|
||||||
"firstrun.microphone.title" = "需要麦克风";
|
"firstrun.microphone.title" = "需要麦克风";
|
||||||
"firstrun.model.action" = "下载模型";
|
"firstrun.model.action" = "下载并安装 Parakeet";
|
||||||
"firstrun.model.body" = "语音就在你的 Mac 上识别,不联网。这需要一个模型:500 MB,只下一次。";
|
"firstrun.model.body" = "听写需要语音模型。下方按钮会下载 Parakeet,将其安装到正确的文件夹,并选为识别引擎。";
|
||||||
"firstrun.model.note" = "它故意不放在磁盘映像里:模型的更新比 iriz 本身勤。分开放::不然随程序一起来的就是过时的那个。\n\n下载的时候继续往下走:权限现在就能给。";
|
"firstrun.model.note" = "下载大小约为 500 MB,需要网络连接和可用磁盘空间。速度取决于网络,进度会显示在这里。不必手动查找或移动文件。\n\n下载期间可以继续授予权限。安装完成后再尝试听写。";
|
||||||
"firstrun.model.title" = "下载语音识别";
|
"firstrun.model.title" = "安装语音识别模型";
|
||||||
"firstrun.modelFailedRetry" = "重试";
|
"firstrun.modelFailedRetry" = "重试";
|
||||||
"firstrun.modelReady" = "模型已就位";
|
"firstrun.modelReady" = "模型已就位";
|
||||||
"firstrun.next" = "下一步";
|
"firstrun.next" = "下一步";
|
||||||
@@ -53,7 +53,7 @@
|
|||||||
"firstrun.tryIt.note" = "文字会出现在下面的输入框里,不会传到别处:这个窗口开着的时候,我只往这里写。";
|
"firstrun.tryIt.note" = "文字会出现在下面的输入框里,不会传到别处:这个窗口开着的时候,我只往这里写。";
|
||||||
"firstrun.tryIt.title" = "现在就试试";
|
"firstrun.tryIt.title" = "现在就试试";
|
||||||
"firstrun.welcome.body" = "按一下键,说一句话,再按一下。文字会出现在光标所在的地方:邮件里、聊天里、终端里。";
|
"firstrun.welcome.body" = "按一下键,说一句话,再按一下。文字会出现在光标所在的地方:邮件里、聊天里、终端里。";
|
||||||
"firstrun.welcome.note" = "所有处理都在你的 Mac 上完成。声音和文字都不会发到任何地方。";
|
"firstrun.welcome.note" = "首次听写前,需要下载语音模型。下一步会显示安装按钮。之后语音识别就在你的 Mac 上运行,无需联网。";
|
||||||
"firstrun.welcome.title" = "你说,我来打字";
|
"firstrun.welcome.title" = "你说,我来打字";
|
||||||
"firstrun.whenItBreaks.body" = "文字没插进去?它没丢。提示条会展开把它显示出来,可以从那里复制。";
|
"firstrun.whenItBreaks.body" = "文字没插进去?它没丢。提示条会展开把它显示出来,可以从那里复制。";
|
||||||
"firstrun.whenItBreaks.note" = "有个词听错了?直接在文字里改掉就行。我会注意到这处修改,并问你要不要记住:你同意了,之后我就照你的写法来。我不会自己往词典里放任何东西。\n\n按键被别的程序占用了?在设置里点它,设你自己的组合。\n\n这个窗口、设置和历史,都从菜单栏的图标打开。";
|
"firstrun.whenItBreaks.note" = "有个词听错了?直接在文字里改掉就行。我会注意到这处修改,并问你要不要记住:你同意了,之后我就照你的写法来。我不会自己往词典里放任何东西。\n\n按键被别的程序占用了?在设置里点它,设你自己的组合。\n\n这个窗口、设置和历史,都从菜单栏的图标打开。";
|
||||||
@@ -333,3 +333,78 @@
|
|||||||
"snippets.delete.a11y" = "删除第 %d 条片段";
|
"snippets.delete.a11y" = "删除第 %d 条片段";
|
||||||
"snippets.phrase.a11y" = "第 %d 条片段的触发词";
|
"snippets.phrase.a11y" = "第 %d 条片段的触发词";
|
||||||
"snippets.text.a11y" = "第 %d 条片段的正文";
|
"snippets.text.a11y" = "第 %d 条片段的正文";
|
||||||
|
|
||||||
|
/* UI Stack: обработка, восстановление и доступность. */
|
||||||
|
"files.choose" = "选择文件";
|
||||||
|
"files.destinationExists" = "文本已存在:%@。请打开它,或重命名原录音后重试。";
|
||||||
|
"files.finished" = "已完成:%d / %d。";
|
||||||
|
"files.language" = "录音语言";
|
||||||
|
"files.languageAuto" = "自动识别";
|
||||||
|
"files.noSpeech" = "未识别到语音。未创建文本文件。";
|
||||||
|
"files.openFailed" = "无法打开 %@。请在访达中检查该文件。";
|
||||||
|
"files.openText" = "打开文本";
|
||||||
|
"files.preparing" = "正在加载模型";
|
||||||
|
"files.reading" = "正在读取录音";
|
||||||
|
"files.refused" = "未接受的文件:%d。请选择可读取的录音:%@。";
|
||||||
|
"files.retry" = "重试剩余文件";
|
||||||
|
"files.saving" = "正在保存文本";
|
||||||
|
"files.showDestination" = "显示结果文件夹";
|
||||||
|
"files.showInFinder" = "在访达中显示";
|
||||||
|
"files.start" = "转录录音";
|
||||||
|
"files.stopAfterCurrent" = "完成当前录音后停止";
|
||||||
|
"files.stopped" = "队列已停止。你可以重新处理剩余文件。";
|
||||||
|
"files.stopping" = "完成当前录音后停止…";
|
||||||
|
"files.transcribing" = "正在转录";
|
||||||
|
"firstrun.agentModelRequired" = "请在提示词设置中为 %@ 选择模型,然后回到这里连接智能体。";
|
||||||
|
"firstrun.agentSettings" = "智能体设置…";
|
||||||
|
"firstrun.modelAlreadyDownloading" = "模型正在下载。请等待安装完成。";
|
||||||
|
"firstrun.modelInstallWhileRecording" = "请先结束录音,再重试安装模型。";
|
||||||
|
"history.clearFailed" = "有 %d 条录音未能移到废纸篓,共 %d 条。其余录音已移到废纸篓。";
|
||||||
|
"history.clearing" = "正在准备并清空历史记录…";
|
||||||
|
"history.copiedTimed" = "已复制。剪贴板将在 2 分钟后清空。";
|
||||||
|
"history.copyFailed" = "无法复制。请重试。";
|
||||||
|
"history.deleteFailed" = "无法将录音移到废纸篓。请重试。";
|
||||||
|
"history.readFailed" = "无法读取历史记录。请重新打开。";
|
||||||
|
"hud.toggleExpanded" = "展开或收起浮窗";
|
||||||
|
"meeting.close" = "关闭";
|
||||||
|
"meeting.discardUnsaved" = "删除未保存的录音";
|
||||||
|
"meeting.emptyRecording" = "未录制到声音";
|
||||||
|
"meeting.emptyRecording.help" = "请检查麦克风,然后重新录制会议。";
|
||||||
|
"meeting.openProtocol" = "打开会议记录";
|
||||||
|
"meeting.processingFailed" = "无法处理会议";
|
||||||
|
"meeting.protocolReady" = "会议记录已就绪";
|
||||||
|
"meeting.recordingSaved" = "录音已保存。你可以重试处理,或在访达中找到它。";
|
||||||
|
"meeting.retryProcessing" = "重试处理";
|
||||||
|
"meeting.retrySave" = "重试保存";
|
||||||
|
"meeting.saveFailed" = "无法保存会议录音";
|
||||||
|
"meeting.saveFailed.help" = "声音仍在内存中。请释放磁盘空间后重试保存。删除录音后将无法恢复。";
|
||||||
|
"meeting.showRecording" = "显示录音";
|
||||||
|
"meeting.speakersUnresolved" = "无法区分说话人。文本已保存为一段发言。";
|
||||||
|
"meeting.title" = "会议";
|
||||||
|
"meetings.openProtocol" = "打开会议记录";
|
||||||
|
"meetings.showFolder" = "显示会议文件夹";
|
||||||
|
"meetings.speakersUnresolved" = "%@:无法区分说话人。文本已保存为一段发言,请检查会议记录。";
|
||||||
|
"meetings.storage" = "俄语录音。音频和会议记录将保存到 iriz 归档中;你可以在这里打开处理完成的文件。";
|
||||||
|
"settings.speechModelInstalled" = "%@:模型已安装";
|
||||||
|
"settings.speechModelMissing" = "%@:模型未安装";
|
||||||
|
"settings.speechModelDownloadHelp" = "语音识别需要在这台 Mac 上安装模型。目前只能自动下载 Parakeet:约 0.5 GB,只需下载一次。安装后会成为所选识别引擎。音频始终留在你的设备上。";
|
||||||
|
"settings.speechModelSetup" = "设置语音识别…";
|
||||||
|
"settings.downloadParakeet" = "下载 Parakeet 模型…";
|
||||||
|
"settings.parakeetAlreadyAvailable" = "Parakeet 已安装。选择它并保存设置,即可用于听写。";
|
||||||
|
"settings.selectInstalledParakeet" = "选择已安装的 Parakeet";
|
||||||
|
"firstrun.model.installLater" = "稍后下载";
|
||||||
|
"firstrun.model.alreadyReadyTitle" = "语音识别模型已安装";
|
||||||
|
"firstrun.model.alreadyReadyBody" = "%@ 已准备好听写,无需下载。";
|
||||||
|
"firstrun.trialNeedsModel" = "首次听写前,请先下载语音模型。";
|
||||||
|
"firstrun.trialModelDownloading" = "模型仍在下载,可在模型设置页面查看进度。";
|
||||||
|
"firstrun.trialModelMissing" = "模型尚未安装。下方按钮可返回下载页面。";
|
||||||
|
"firstrun.trialOpenModelSetup" = "前往安装模型";
|
||||||
|
"firstrun.model.verifyRepair" = "检查并修复 Parakeet";
|
||||||
|
"speechModel.downloading" = "正在下载语音模型";
|
||||||
|
"speechModel.verifying" = "正在验证已下载的模型";
|
||||||
|
"speechModel.ready" = "模型已安装";
|
||||||
|
"speechModel.failed" = "下载失败";
|
||||||
|
"speechModel.error.offline" = "没有互联网连接。请连接网络后重试下载。";
|
||||||
|
"speechModel.error.connectionLost" = "连接已中断。请检查网络后重试下载。";
|
||||||
|
"speechModel.error.timeout" = "服务器未能及时响应。请稍后重试下载。";
|
||||||
|
"speechModel.error.cancelled" = "下载已取消。你可以重新开始。";
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ public final class DictationController {
|
|||||||
private var isBusy = false
|
private var isBusy = false
|
||||||
private var isRecording = false
|
private var isRecording = false
|
||||||
private var modelReady = false
|
private var modelReady = false
|
||||||
|
private var lastRequestedModelProfile: SpeechModelProfile?
|
||||||
/// Идёт ли прогрев прямо сейчас. Отдельно от `modelReady`, потому что
|
/// Идёт ли прогрев прямо сейчас. Отдельно от `modelReady`, потому что
|
||||||
/// «грузится» и «нет вовсе» - разные состояния с разными последствиями.
|
/// «грузится» и «нет вовсе» - разные состояния с разными последствиями.
|
||||||
private var warmUpTask: Task<Void, Never>?
|
private var warmUpTask: Task<Void, Never>?
|
||||||
@@ -88,6 +89,7 @@ public final class DictationController {
|
|||||||
private var powerLifecycle = AudioPowerLifecycle()
|
private var powerLifecycle = AudioPowerLifecycle()
|
||||||
/// Подмена таймаута распознавания — только тестами, чтобы не ждать живьём.
|
/// Подмена таймаута распознавания — только тестами, чтобы не ждать живьём.
|
||||||
private let transcriptionTimeoutOverride: Double?
|
private let transcriptionTimeoutOverride: Double?
|
||||||
|
private let modelLoader: (@Sendable (SpeechModelProfile) async throws -> Void)?
|
||||||
/// Счётчики доставки: их читает status.json (scripts/gate_app.sh).
|
/// Счётчики доставки: их читает status.json (scripts/gate_app.sh).
|
||||||
private let insertionStats: InsertionStats
|
private let insertionStats: InsertionStats
|
||||||
private var settingsObserver: NotificationObserver?
|
private var settingsObserver: NotificationObserver?
|
||||||
@@ -95,6 +97,7 @@ public final class DictationController {
|
|||||||
public init() {
|
public init() {
|
||||||
self.settings = .shared
|
self.settings = .shared
|
||||||
self.transcriptionTimeoutOverride = nil
|
self.transcriptionTimeoutOverride = nil
|
||||||
|
self.modelLoader = nil
|
||||||
self.insertionStats = InsertionStats()
|
self.insertionStats = InsertionStats()
|
||||||
observeSettings()
|
observeSettings()
|
||||||
}
|
}
|
||||||
@@ -102,9 +105,11 @@ public final class DictationController {
|
|||||||
/// Для тестов и будущих точек сборки.
|
/// Для тестов и будущих точек сборки.
|
||||||
init(settings: DictationSettings,
|
init(settings: DictationSettings,
|
||||||
transcriptionTimeout: Double? = nil,
|
transcriptionTimeout: Double? = nil,
|
||||||
insertionStats: InsertionStats = InsertionStats()) {
|
insertionStats: InsertionStats = InsertionStats(),
|
||||||
|
modelLoader: (@Sendable (SpeechModelProfile) async throws -> Void)? = nil) {
|
||||||
self.settings = settings
|
self.settings = settings
|
||||||
self.transcriptionTimeoutOverride = transcriptionTimeout
|
self.transcriptionTimeoutOverride = transcriptionTimeout
|
||||||
|
self.modelLoader = modelLoader
|
||||||
self.insertionStats = insertionStats
|
self.insertionStats = insertionStats
|
||||||
observeSettings()
|
observeSettings()
|
||||||
}
|
}
|
||||||
@@ -187,9 +192,17 @@ public final class DictationController {
|
|||||||
|
|
||||||
public func stop() {
|
public func stop() {
|
||||||
if isRecording {
|
if isRecording {
|
||||||
// Sleep/выход отменяет клип: не запускаем распознавание и не
|
if recordingPurpose == .meeting {
|
||||||
// создаём raw/audio recovery-артефакт.
|
// Уже записанная встреча переживает sleep/выход. ASR здесь
|
||||||
handleCancel()
|
// не запускаем: исходник можно разобрать после возвращения.
|
||||||
|
isRecording = false
|
||||||
|
recordingPurpose = .dictation
|
||||||
|
let captured = audio.endRecording()
|
||||||
|
finishMeetingRecording(samples: captured.samples, process: false)
|
||||||
|
hotkeys.resetToggleState()
|
||||||
|
} else {
|
||||||
|
handleCancel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
maxDurationTask?.cancel()
|
maxDurationTask?.cancel()
|
||||||
maxDurationTask = nil
|
maxDurationTask = nil
|
||||||
@@ -223,9 +236,31 @@ public final class DictationController {
|
|||||||
start()
|
start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Вызывается после явной установки. Греет выбранный движок, не повторяя
|
||||||
|
/// start(), запросы разрешений и запуск записи; настройки не меняет.
|
||||||
|
@discardableResult
|
||||||
|
public func prepareAfterModelInstallation() -> Bool {
|
||||||
|
guard !isBusy, !isRecording, warmUpTask == nil, !powerLifecycle.isSuspended else { return false }
|
||||||
|
DownloadUtils.enforceOffline = true
|
||||||
|
modelReady = false
|
||||||
|
state = .warmingUp
|
||||||
|
warmUpTask = Task { [weak self] in await self?.warmUpModel() }
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
private func warmUpModel() async {
|
private func warmUpModel() async {
|
||||||
|
let profile = settings.speechEngine
|
||||||
|
lastRequestedModelProfile = profile
|
||||||
|
defer {
|
||||||
|
warmUpTask = nil
|
||||||
|
if settings.speechEngine != profile { prepareChangedSpeechModelIfIdle() }
|
||||||
|
}
|
||||||
do {
|
do {
|
||||||
try await asr.load(profile: settings.speechEngine)
|
if let modelLoader {
|
||||||
|
try await modelLoader(profile)
|
||||||
|
} else {
|
||||||
|
try await asr.load(profile: profile)
|
||||||
|
}
|
||||||
// Рычаг под смешанную речь включен и в ЖИВОЙ диктовке, а не только в
|
// Рычаг под смешанную речь включен и в ЖИВОЙ диктовке, а не только в
|
||||||
// CLI: без него термины внутри русской фразы ломаются ровно там, где
|
// CLI: без него термины внутри русской фразы ломаются ровно там, где
|
||||||
// владелец диктует каждый день.
|
// владелец диктует каждый день.
|
||||||
@@ -233,6 +268,7 @@ public final class DictationController {
|
|||||||
modelReady = true
|
modelReady = true
|
||||||
if state == .warmingUp { state = .ready }
|
if state == .warmingUp { state = .ready }
|
||||||
} catch {
|
} catch {
|
||||||
|
modelReady = false
|
||||||
log("ASR warmup failed: \(error.localizedDescription)")
|
log("ASR warmup failed: \(error.localizedDescription)")
|
||||||
state = .unavailable(error.localizedDescription)
|
state = .unavailable(error.localizedDescription)
|
||||||
}
|
}
|
||||||
@@ -312,35 +348,123 @@ public final class DictationController {
|
|||||||
/// Файл пишется ДО разбора и остаётся на диске, даже если разбор упадёт:
|
/// Файл пишется ДО разбора и остаётся на диске, даже если разбор упадёт:
|
||||||
/// запись заседания дороже протокола, её нельзя терять из-за отказа
|
/// запись заседания дороже протокола, её нельзя терять из-за отказа
|
||||||
/// распознавателя.
|
/// распознавателя.
|
||||||
private func finishMeetingRecording(samples: [Float]) {
|
private func finishMeetingRecording(samples: [Float], process: Bool = true) {
|
||||||
state = .ready
|
state = .ready
|
||||||
guard !samples.isEmpty else {
|
guard !samples.isEmpty else {
|
||||||
log("meeting: пустая запись, сохранять нечего")
|
log("meeting: пустая запись, сохранять нечего")
|
||||||
|
if process {
|
||||||
|
let alert = NSAlert()
|
||||||
|
alert.alertStyle = .warning
|
||||||
|
alert.messageText = L("meeting.emptyRecording", "Звук не записался")
|
||||||
|
alert.informativeText = L("meeting.emptyRecording.help", "Проверь микрофон и повтори запись встречи.")
|
||||||
|
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
|
||||||
|
_ = runMeetingAlert(alert)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
do {
|
let date = Date()
|
||||||
let url = try meetingRecordingScratchURL()
|
isBusy = true
|
||||||
let recording = try writeMeetingWAV(samples: samples,
|
state = .transcribing
|
||||||
sampleRate: SAMPLE_RATE,
|
let recording = saveMeetingRecording(samples: samples, at: date)
|
||||||
to: url)
|
isBusy = false
|
||||||
log("meeting: записано \(Int(recording.seconds)) с в \(url.lastPathComponent)")
|
state = .ready
|
||||||
Task { @MainActor in
|
guard let recording else { return }
|
||||||
let pipeline = MeetingPipeline()
|
log("meeting: записано \(Int(recording.seconds)) с в \(recording.url.lastPathComponent)")
|
||||||
let title = "Встреча " + meetingDateFormatter().string(from: Date())
|
guard process else { return }
|
||||||
do {
|
processMeetingRecording(recording, at: date)
|
||||||
let result = try await pipeline.run(audio: recording.url, title: title)
|
}
|
||||||
log("meeting: протокол готов, реплик \(result.turns.count)")
|
|
||||||
} catch {
|
private func saveMeetingRecording(samples: [Float], at date: Date) -> MeetingRecording? {
|
||||||
// Разбор упал, но звук уже на диске - его можно принести в
|
while true {
|
||||||
// окно встреч руками и разобрать ещё раз.
|
do {
|
||||||
log("meeting: разбор отказал (\(error)), звук остался в \(recording.url.path)")
|
return try writeMeetingWAV(samples: samples, sampleRate: SAMPLE_RATE,
|
||||||
|
to: meetingRecordingScratchURL(at: date))
|
||||||
|
} catch {
|
||||||
|
log("meeting: не удалось сохранить звук (\(error))")
|
||||||
|
let alert = NSAlert()
|
||||||
|
alert.alertStyle = .warning
|
||||||
|
alert.messageText = L("meeting.saveFailed", "Не удалось сохранить запись встречи")
|
||||||
|
alert.informativeText = L("meeting.saveFailed.help", "Звук ещё в памяти. Освободи место на диске и повтори сохранение. Если удалить запись, восстановить её будет нельзя.")
|
||||||
|
+ "\n\n" + error.localizedDescription
|
||||||
|
alert.addButton(withTitle: L("meeting.retrySave", "Повторить сохранение"))
|
||||||
|
alert.addButton(withTitle: L("meeting.discardUnsaved", "Удалить несохранённую запись"))
|
||||||
|
guard runMeetingAlert(alert) == .alertFirstButtonReturn else { return nil }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Тот же барьер, что у диктовки: пока встреча разбирается, второй
|
||||||
|
/// распознаватель не запускается ни хоткеем, ни повтором из сообщения.
|
||||||
|
func beginMeetingProcessing() -> UInt64? {
|
||||||
|
guard !isBusy, !isRecording else { return nil }
|
||||||
|
transcriptionGeneration &+= 1
|
||||||
|
isBusy = true
|
||||||
|
state = .transcribing
|
||||||
|
return transcriptionGeneration
|
||||||
|
}
|
||||||
|
|
||||||
|
private func processMeetingRecording(_ recording: MeetingRecording, at date: Date) {
|
||||||
|
guard let generation = beginMeetingProcessing() else { return }
|
||||||
|
let title = L("meeting.title", "Встреча") + " " + meetingDateFormatter().string(from: date)
|
||||||
|
let pipeline = MeetingPipeline(transcriber: AudioFileTranscriber(engine: settings.speechEngine,
|
||||||
|
initialPrompt: whisperDefaultInitialPrompt))
|
||||||
|
pipelineTask = Task { [weak self] in
|
||||||
|
guard let self else { return }
|
||||||
|
defer { self.finishTranscription(generation: generation) }
|
||||||
|
do {
|
||||||
|
let result = try await pipeline.run(audio: recording.url, title: title, at: date)
|
||||||
|
guard !Task.isCancelled, self.transcriptionGeneration == generation else { return }
|
||||||
|
self.finishTranscription(generation: generation)
|
||||||
|
let alert = NSAlert()
|
||||||
|
alert.messageText = L("meeting.protocolReady", "Протокол встречи готов")
|
||||||
|
alert.informativeText = result.artifacts.transcript.path
|
||||||
|
if !result.speakersResolved {
|
||||||
|
alert.informativeText += "\n\n" + L("meeting.speakersUnresolved", "Не удалось разделить говорящих. Текст сохранён одной репликой.")
|
||||||
|
}
|
||||||
|
alert.addButton(withTitle: L("meeting.openProtocol", "Открыть протокол"))
|
||||||
|
alert.addButton(withTitle: L("meeting.showRecording", "Показать запись"))
|
||||||
|
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
|
||||||
|
switch self.runMeetingAlert(alert) {
|
||||||
|
case .alertFirstButtonReturn:
|
||||||
|
if !NSWorkspace.shared.open(result.artifacts.transcript) {
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([result.artifacts.transcript])
|
||||||
|
}
|
||||||
|
case .alertSecondButtonReturn:
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([result.artifacts.audio])
|
||||||
|
default: break
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
guard !Task.isCancelled, self.transcriptionGeneration == generation else { return }
|
||||||
|
self.finishTranscription(generation: generation)
|
||||||
|
let alert = NSAlert()
|
||||||
|
alert.alertStyle = .warning
|
||||||
|
alert.messageText = L("meeting.processingFailed", "Не удалось разобрать встречу")
|
||||||
|
let reason = (error as? MeetingPipelineFailure)?.rawValue ?? error.localizedDescription
|
||||||
|
alert.informativeText = reason + "\n\n"
|
||||||
|
+ L("meeting.recordingSaved", "Запись сохранена. Можно повторить разбор или открыть её в Finder.")
|
||||||
|
+ "\n" + recording.url.path
|
||||||
|
alert.addButton(withTitle: L("meeting.retryProcessing", "Повторить разбор"))
|
||||||
|
alert.addButton(withTitle: L("meeting.showRecording", "Показать запись"))
|
||||||
|
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
|
||||||
|
switch self.runMeetingAlert(alert) {
|
||||||
|
case .alertFirstButtonReturn:
|
||||||
|
self.processMeetingRecording(recording, at: date)
|
||||||
|
case .alertSecondButtonReturn:
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([recording.url])
|
||||||
|
default: break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
|
||||||
log("meeting: не удалось сохранить звук (\(error))")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func runMeetingAlert(_ alert: NSAlert) -> NSApplication.ModalResponse {
|
||||||
|
// LSUIElement не имеет обычного главного окна; alert должен оказаться
|
||||||
|
// над постоянной floating-плашкой, иначе вопрос останется под ней.
|
||||||
|
alert.window.level = .floating
|
||||||
|
NSApp.activate(ignoringOtherApps: true)
|
||||||
|
return alert.runModal()
|
||||||
|
}
|
||||||
|
|
||||||
/// Кого звать, когда с плашки просят настройки. Ставит приложение: у
|
/// Кого звать, когда с плашки просят настройки. Ставит приложение: у
|
||||||
/// модуля диктовки окна настроек нет и быть не должно.
|
/// модуля диктовки окна настроек нет и быть не должно.
|
||||||
public var onOpenSettings: (() -> Void)?
|
public var onOpenSettings: (() -> Void)?
|
||||||
@@ -361,6 +485,12 @@ public final class DictationController {
|
|||||||
hotkeys.setTranslationHotkeyEnabled(settings.translationModeEnabled)
|
hotkeys.setTranslationHotkeyEnabled(settings.translationModeEnabled)
|
||||||
hotkeys.setAlternateCompletionEnabled(settings.alternateCompletionEnabled)
|
hotkeys.setAlternateCompletionEnabled(settings.alternateCompletionEnabled)
|
||||||
hotkeys.setTriggerMode(settings.triggerMode)
|
hotkeys.setTriggerMode(settings.triggerMode)
|
||||||
|
prepareChangedSpeechModelIfIdle()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func prepareChangedSpeechModelIfIdle() {
|
||||||
|
guard let previous = lastRequestedModelProfile, previous != settings.speechEngine else { return }
|
||||||
|
_ = prepareAfterModelInstallation()
|
||||||
}
|
}
|
||||||
|
|
||||||
private func observeSettings() {
|
private func observeSettings() {
|
||||||
@@ -556,7 +686,15 @@ public final class DictationController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public func toggleDictationFromUI() {
|
public func toggleDictationFromUI() {
|
||||||
handlePress(purpose: .dictation)
|
if isRecording {
|
||||||
|
// Кнопка HUD уже показывает «Закончить запись». Завершаем текущий
|
||||||
|
// purpose тем же путём, что хоткей, не меняя встречу на диктовку.
|
||||||
|
hotkeys.resetToggleState()
|
||||||
|
handleRelease(shortcut: .standard,
|
||||||
|
hotkeyDetectedAt: ProcessInfo.processInfo.systemUptime)
|
||||||
|
} else {
|
||||||
|
handlePress(purpose: .dictation)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Начать запись для промпта прямо из интерфейса. Тот же вход, что и у
|
/// Начать запись для промпта прямо из интерфейса. Тот же вход, что и у
|
||||||
@@ -571,6 +709,7 @@ public final class DictationController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func handlePress(purpose: DictationRecordingPurpose) {
|
private func handlePress(purpose: DictationRecordingPurpose) {
|
||||||
|
prepareChangedSpeechModelIfIdle()
|
||||||
if let refusal = startRefusal() {
|
if let refusal = startRefusal() {
|
||||||
log("dictation: press refused — \(refusal.rawValue)")
|
log("dictation: press refused — \(refusal.rawValue)")
|
||||||
hud?.startRefused(refusal)
|
hud?.startRefused(refusal)
|
||||||
@@ -1249,6 +1388,7 @@ public final class DictationController {
|
|||||||
default:
|
default:
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
prepareChangedSpeechModelIfIdle()
|
||||||
}
|
}
|
||||||
|
|
||||||
private func handleCancel() {
|
private func handleCancel() {
|
||||||
@@ -1268,8 +1408,9 @@ public final class DictationController {
|
|||||||
|
|
||||||
private func scheduleMaxDurationAutoRelease() {
|
private func scheduleMaxDurationAutoRelease() {
|
||||||
maxDurationTask?.cancel()
|
maxDurationTask?.cancel()
|
||||||
|
let limit = Self.recordingLimitSeconds(for: recordingPurpose)
|
||||||
maxDurationTask = Task { [weak self] in
|
maxDurationTask = Task { [weak self] in
|
||||||
try? await Task.sleep(nanoseconds: UInt64(MAX_RECORDING_SECONDS) * 1_000_000_000)
|
try? await Task.sleep(nanoseconds: UInt64(limit) * 1_000_000_000)
|
||||||
guard !Task.isCancelled, let self, self.isRecording else { return }
|
guard !Task.isCancelled, let self, self.isRecording else { return }
|
||||||
log("dictation: max recording duration reached — auto release")
|
log("dictation: max recording duration reached — auto release")
|
||||||
self.hotkeys.resetToggleState()
|
self.hotkeys.resetToggleState()
|
||||||
@@ -1278,6 +1419,10 @@ public final class DictationController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
nonisolated static func recordingLimitSeconds(for purpose: DictationRecordingPurpose) -> TimeInterval {
|
||||||
|
purpose == .meeting ? meetingRecordingLimitSeconds : MAX_RECORDING_SECONDS
|
||||||
|
}
|
||||||
|
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
func simulateActiveRecordingForTesting() {
|
func simulateActiveRecordingForTesting() {
|
||||||
audio.beginRecording()
|
audio.beginRecording()
|
||||||
|
|||||||
@@ -122,7 +122,12 @@ public func dictationHUDNextLanguage(after current: DictationLanguage) -> Dictat
|
|||||||
/// значком без кнопки.
|
/// значком без кнопки.
|
||||||
final class DictationHUDActionButton: NSView {
|
final class DictationHUDActionButton: NSView {
|
||||||
var action: DictationHUDAction {
|
var action: DictationHUDAction {
|
||||||
didSet { if action != oldValue { needsDisplay = true } }
|
didSet {
|
||||||
|
guard action != oldValue else { return }
|
||||||
|
setAccessibilityLabel(action.title)
|
||||||
|
toolTip = action.title
|
||||||
|
needsDisplay = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
var onPress: ((DictationHUDActionID) -> Void)?
|
var onPress: ((DictationHUDActionID) -> Void)?
|
||||||
/// Кого звать, когда мышь пришла на кнопку или ушла с неё. Владелец
|
/// Кого звать, когда мышь пришла на кнопку или ушла с неё. Владелец
|
||||||
@@ -132,6 +137,8 @@ final class DictationHUDActionButton: NSView {
|
|||||||
var onHover: ((DictationHUDAction?) -> Void)?
|
var onHover: ((DictationHUDAction?) -> Void)?
|
||||||
|
|
||||||
private var pressed = false
|
private var pressed = false
|
||||||
|
private let reduceMotion: () -> Bool
|
||||||
|
private var displayOptionsObserver: DictationHUDNotificationObserver?
|
||||||
private var hovered = false {
|
private var hovered = false {
|
||||||
didSet {
|
didSet {
|
||||||
guard hovered != oldValue else { return }
|
guard hovered != oldValue else { return }
|
||||||
@@ -148,6 +155,14 @@ final class DictationHUDActionButton: NSView {
|
|||||||
guard let layer else { return }
|
guard let layer else { return }
|
||||||
layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
|
layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
|
||||||
layer.position = CGPoint(x: frame.midX, y: frame.midY)
|
layer.position = CGPoint(x: frame.midX, y: frame.midY)
|
||||||
|
guard !reduceMotion() else {
|
||||||
|
layer.removeAnimation(forKey: "irizHoverLift")
|
||||||
|
CATransaction.begin()
|
||||||
|
CATransaction.setDisableActions(true)
|
||||||
|
layer.transform = CATransform3DIdentity
|
||||||
|
CATransaction.commit()
|
||||||
|
return
|
||||||
|
}
|
||||||
let scale: CGFloat = hovered ? 1.18 : 1
|
let scale: CGFloat = hovered ? 1.18 : 1
|
||||||
let lift = CABasicAnimation(keyPath: "transform.scale")
|
let lift = CABasicAnimation(keyPath: "transform.scale")
|
||||||
lift.fromValue = layer.value(forKeyPath: "transform.scale") ?? 1
|
lift.fromValue = layer.value(forKeyPath: "transform.scale") ?? 1
|
||||||
@@ -168,12 +183,22 @@ final class DictationHUDActionButton: NSView {
|
|||||||
}
|
}
|
||||||
private var tracking: NSTrackingArea?
|
private var tracking: NSTrackingArea?
|
||||||
|
|
||||||
init(action: DictationHUDAction) {
|
init(action: DictationHUDAction,
|
||||||
|
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
||||||
|
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter) {
|
||||||
self.action = action
|
self.action = action
|
||||||
|
self.reduceMotion = reduceMotion
|
||||||
super.init(frame: .zero)
|
super.init(frame: .zero)
|
||||||
|
setAccessibilityElement(true)
|
||||||
setAccessibilityRole(.button)
|
setAccessibilityRole(.button)
|
||||||
setAccessibilityLabel(action.title)
|
setAccessibilityLabel(action.title)
|
||||||
toolTip = action.title
|
toolTip = action.title
|
||||||
|
displayOptionsObserver = DictationHUDNotificationObserver(displayOptionsCenter.addObserver(
|
||||||
|
forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification,
|
||||||
|
object: nil, queue: .main
|
||||||
|
) { [weak self] _ in
|
||||||
|
MainActor.assumeIsolated { self?.applyHoverLift() }
|
||||||
|
}, center: displayOptionsCenter)
|
||||||
}
|
}
|
||||||
|
|
||||||
@available(*, unavailable)
|
@available(*, unavailable)
|
||||||
@@ -181,6 +206,12 @@ final class DictationHUDActionButton: NSView {
|
|||||||
|
|
||||||
override var isFlipped: Bool { true }
|
override var isFlipped: Bool { true }
|
||||||
|
|
||||||
|
override func accessibilityPerformPress() -> Bool {
|
||||||
|
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
|
||||||
|
onPress(action.id)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
override func updateTrackingAreas() {
|
override func updateTrackingAreas() {
|
||||||
if let tracking { removeTrackingArea(tracking) }
|
if let tracking { removeTrackingArea(tracking) }
|
||||||
let area = NSTrackingArea(rect: .zero,
|
let area = NSTrackingArea(rect: .zero,
|
||||||
@@ -214,7 +245,7 @@ final class DictationHUDActionButton: NSView {
|
|||||||
pressed = false
|
pressed = false
|
||||||
needsDisplay = true
|
needsDisplay = true
|
||||||
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
||||||
onPress?(action.id)
|
_ = accessibilityPerformPress()
|
||||||
}
|
}
|
||||||
|
|
||||||
override func draw(_ dirtyRect: NSRect) {
|
override func draw(_ dirtyRect: NSRect) {
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
// Порядок показа плашки «идёт голос»: что и когда попадает на экран.
|
// Порядок показа плашки «идёт голос»: что и когда попадает на экран.
|
||||||
//
|
//
|
||||||
// Здесь нет ни AppKit, ни решений — решения в DictationHUD.swift, рисование в
|
// Решения в DictationHUD.swift, рисование в
|
||||||
// DictationHUDWindow.swift. Такое разделение позволяет проверить тестом всё
|
// DictationHUDWindow.swift. Такое разделение позволяет проверить тестом всё
|
||||||
// поведение (что показали, что погасили, крутится ли опрос уровня), ни разу не
|
// поведение (что показали, что погасили, крутится ли опрос уровня), ни разу не
|
||||||
// поднимая живое окно: под `swift test` его и не поднять.
|
// поднимая живое окно: под `swift test` его и не поднять.
|
||||||
import Foundation
|
import Foundation
|
||||||
|
import AppKit
|
||||||
|
|
||||||
/// Поверхность, на которой плашка рисуется. Единственная реализация в продукте —
|
/// Поверхность, на которой плашка рисуется. Единственная реализация в продукте —
|
||||||
/// `DictationHUDPanelSurface` (NSPanel). В тестах подставляется запоминающая
|
/// `DictationHUDPanelSurface` (NSPanel). В тестах подставляется запоминающая
|
||||||
@@ -112,6 +113,7 @@ final class DictationHUDPresenter {
|
|||||||
|
|
||||||
private var surface: DictationHUDSurface?
|
private var surface: DictationHUDSurface?
|
||||||
private var dismissTimer: Timer?
|
private var dismissTimer: Timer?
|
||||||
|
private var displayOptionsObserver: DictationHUDNotificationObserver?
|
||||||
private var smoothedLevel: Float = 0
|
private var smoothedLevel: Float = 0
|
||||||
private var lastLevelSequence: UInt64?
|
private var lastLevelSequence: UInt64?
|
||||||
private var sameLevelSequenceTicks = 0
|
private var sameLevelSequenceTicks = 0
|
||||||
@@ -131,6 +133,7 @@ final class DictationHUDPresenter {
|
|||||||
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
|
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
|
||||||
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
||||||
pump: DictationHUDLevelPump = DictationHUDLevelPump(),
|
pump: DictationHUDLevelPump = DictationHUDLevelPump(),
|
||||||
|
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter,
|
||||||
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
|
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
|
||||||
self.levelSnapshot = levelSnapshot
|
self.levelSnapshot = levelSnapshot
|
||||||
self.staleGuardEnabled = true
|
self.staleGuardEnabled = true
|
||||||
@@ -145,6 +148,7 @@ final class DictationHUDPresenter {
|
|||||||
self.pump = pump
|
self.pump = pump
|
||||||
self.makeSurface = surface
|
self.makeSurface = surface
|
||||||
pump.onTick = { [weak self] in self?.render() }
|
pump.onTick = { [weak self] in self?.render() }
|
||||||
|
observeDisplayOptions(in: displayOptionsCenter)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Совместимость тестов и простых поверхностей без sequence. Живой продукт
|
/// Совместимость тестов и простых поверхностей без sequence. Живой продукт
|
||||||
@@ -155,6 +159,7 @@ final class DictationHUDPresenter {
|
|||||||
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
|
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
|
||||||
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
||||||
pump: DictationHUDLevelPump = DictationHUDLevelPump(),
|
pump: DictationHUDLevelPump = DictationHUDLevelPump(),
|
||||||
|
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter,
|
||||||
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
|
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
|
||||||
self.levelSnapshot = { (level(), 0) }
|
self.levelSnapshot = { (level(), 0) }
|
||||||
self.staleGuardEnabled = false
|
self.staleGuardEnabled = false
|
||||||
@@ -169,6 +174,18 @@ final class DictationHUDPresenter {
|
|||||||
self.pump = pump
|
self.pump = pump
|
||||||
self.makeSurface = surface
|
self.makeSurface = surface
|
||||||
pump.onTick = { [weak self] in self?.render() }
|
pump.onTick = { [weak self] in self?.render() }
|
||||||
|
observeDisplayOptions(in: displayOptionsCenter)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func observeDisplayOptions(in center: NotificationCenter) {
|
||||||
|
displayOptionsObserver = DictationHUDNotificationObserver(center.addObserver(
|
||||||
|
forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification,
|
||||||
|
object: nil, queue: .main
|
||||||
|
) { [weak self] _ in
|
||||||
|
// Ожидание и покой не опрашивают уровень: без уведомления уже
|
||||||
|
// открытая плашка не узнаёт, что владелец изменил Reduce Motion.
|
||||||
|
MainActor.assumeIsolated { self?.render() }
|
||||||
|
}, center: center)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Входы конвейера
|
// MARK: - Входы конвейера
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
// у неё нет подписей, она говорит цветом и формой. Панель - другое: её работа
|
// у неё нет подписей, она говорит цветом и формой. Панель - другое: её работа
|
||||||
// и есть показать текст.
|
// и есть показать текст.
|
||||||
import AppKit
|
import AppKit
|
||||||
|
import IrizCore
|
||||||
|
|
||||||
/// Сколько строк займёт текст на самом деле.
|
/// Сколько строк займёт текст на самом деле.
|
||||||
///
|
///
|
||||||
@@ -298,14 +299,33 @@ final class DictationHUDTranscriptView: NSView {
|
|||||||
/// на любом фоне.
|
/// на любом фоне.
|
||||||
final class DictationHUDCopyPill: NSView {
|
final class DictationHUDCopyPill: NSView {
|
||||||
var title: String = "" {
|
var title: String = "" {
|
||||||
didSet { if title != oldValue { needsDisplay = true } }
|
didSet {
|
||||||
|
guard title != oldValue else { return }
|
||||||
|
setAccessibilityLabel(title)
|
||||||
|
needsDisplay = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
var onPress: (() -> Void)?
|
var onPress: (() -> Void)?
|
||||||
|
|
||||||
private var pressed = false
|
private var pressed = false
|
||||||
|
|
||||||
|
override init(frame frameRect: NSRect) {
|
||||||
|
super.init(frame: frameRect)
|
||||||
|
setAccessibilityElement(true)
|
||||||
|
setAccessibilityRole(.button)
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) не поддерживается") }
|
||||||
|
|
||||||
override var isFlipped: Bool { true }
|
override var isFlipped: Bool { true }
|
||||||
|
|
||||||
|
override func accessibilityPerformPress() -> Bool {
|
||||||
|
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
|
||||||
|
onPress()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
var fittingWidth: CGFloat {
|
var fittingWidth: CGFloat {
|
||||||
(title as NSString).size(withAttributes: [.font: Self.font]).width + 26
|
(title as NSString).size(withAttributes: [.font: Self.font]).width + 26
|
||||||
}
|
}
|
||||||
@@ -321,7 +341,7 @@ final class DictationHUDCopyPill: NSView {
|
|||||||
pressed = false
|
pressed = false
|
||||||
needsDisplay = true
|
needsDisplay = true
|
||||||
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
||||||
onPress?()
|
_ = accessibilityPerformPress()
|
||||||
}
|
}
|
||||||
|
|
||||||
override func draw(_ dirtyRect: NSRect) {
|
override func draw(_ dirtyRect: NSRect) {
|
||||||
@@ -359,8 +379,24 @@ final class DictationHUDCloseRing: NSView {
|
|||||||
|
|
||||||
private var pressed = false
|
private var pressed = false
|
||||||
|
|
||||||
|
override init(frame frameRect: NSRect) {
|
||||||
|
super.init(frame: frameRect)
|
||||||
|
setAccessibilityElement(true)
|
||||||
|
setAccessibilityRole(.button)
|
||||||
|
setAccessibilityLabel(L("common.close", "Закрыть"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) не поддерживается") }
|
||||||
|
|
||||||
override var isFlipped: Bool { true }
|
override var isFlipped: Bool { true }
|
||||||
|
|
||||||
|
override func accessibilityPerformPress() -> Bool {
|
||||||
|
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
|
||||||
|
onPress()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
override func mouseDown(with event: NSEvent) {
|
override func mouseDown(with event: NSEvent) {
|
||||||
pressed = true
|
pressed = true
|
||||||
needsDisplay = true
|
needsDisplay = true
|
||||||
@@ -370,7 +406,7 @@ final class DictationHUDCloseRing: NSView {
|
|||||||
pressed = false
|
pressed = false
|
||||||
needsDisplay = true
|
needsDisplay = true
|
||||||
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
||||||
onPress?()
|
_ = accessibilityPerformPress()
|
||||||
}
|
}
|
||||||
|
|
||||||
override func draw(_ dirtyRect: NSRect) {
|
override func draw(_ dirtyRect: NSRect) {
|
||||||
|
|||||||
@@ -4,12 +4,17 @@
|
|||||||
import AppKit
|
import AppKit
|
||||||
import Foundation
|
import Foundation
|
||||||
import QuartzCore
|
import QuartzCore
|
||||||
|
import IrizCore
|
||||||
|
|
||||||
private final class DictationHUDNotificationObserver: @unchecked Sendable {
|
final class DictationHUDNotificationObserver: @unchecked Sendable {
|
||||||
let token: NSObjectProtocol
|
let token: NSObjectProtocol
|
||||||
|
private let center: NotificationCenter
|
||||||
|
|
||||||
init(_ token: NSObjectProtocol) { self.token = token }
|
init(_ token: NSObjectProtocol, center: NotificationCenter = .default) {
|
||||||
deinit { NotificationCenter.default.removeObserver(token) }
|
self.token = token
|
||||||
|
self.center = center
|
||||||
|
}
|
||||||
|
deinit { center.removeObserver(token) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private final class DictationHUDDisplayLinkStorage: @unchecked Sendable {
|
private final class DictationHUDDisplayLinkStorage: @unchecked Sendable {
|
||||||
@@ -941,6 +946,13 @@ final class DictationHUDPanelSurface: NSObject, DictationHUDSurface, DictationHU
|
|||||||
container.delegate = self
|
container.delegate = self
|
||||||
container.setAccessibilityElement(true)
|
container.setAccessibilityElement(true)
|
||||||
container.setAccessibilityRole(.group)
|
container.setAccessibilityRole(.group)
|
||||||
|
container.setAccessibilityCustomActions([
|
||||||
|
NSAccessibilityCustomAction(name: L("hud.toggleExpanded", "Развернуть или свернуть плашку")) { [weak self] in
|
||||||
|
guard let handler = self?.openToggledHandler else { return false }
|
||||||
|
handler()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
])
|
||||||
let capsule = DictationHUDCapsuleView(frame: CGRect(origin: .zero,
|
let capsule = DictationHUDCapsuleView(frame: CGRect(origin: .zero,
|
||||||
size: DICTATION_HUD_BASE_SIZE))
|
size: DICTATION_HUD_BASE_SIZE))
|
||||||
let hint = DictationHUDHintView(frame: .zero)
|
let hint = DictationHUDHintView(frame: .zero)
|
||||||
@@ -1292,9 +1304,16 @@ final class DictationHUDPanelSurface: NSObject, DictationHUDSurface, DictationHU
|
|||||||
}
|
}
|
||||||
if reduceMotionEnabled() {
|
if reduceMotionEnabled() {
|
||||||
stopMotion()
|
stopMotion()
|
||||||
|
hoverProgress = hoverAnimation?.to ?? hoverProgress
|
||||||
|
hoverAnimation = nil
|
||||||
|
hint?.appearanceProgress = hoverProgress
|
||||||
|
// Уже начатый морф тоже завершается при смене настройки.
|
||||||
|
transcriptProgress = transcriptTarget
|
||||||
|
advanceTranscript(dt: 0)
|
||||||
revealAnimation = nil
|
revealAnimation = nil
|
||||||
revealProgress = 1
|
revealProgress = 1
|
||||||
capsule?.revealProgress = 1
|
capsule?.revealProgress = 1
|
||||||
|
layoutPanel(display: true)
|
||||||
} else {
|
} else {
|
||||||
startMotionIfNeeded()
|
startMotionIfNeeded()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import IrizCore
|
|||||||
/// сортировки и то, что показывается владельцу. Ключ именно имя, а не mtime:
|
/// сортировки и то, что показывается владельцу. Ключ именно имя, а не mtime:
|
||||||
/// после импорта из старого приложения mtime врёт (см. PromptEnvelope.swift,
|
/// после импорта из старого приложения mtime врёт (см. PromptEnvelope.swift,
|
||||||
/// `latestDictation`) — папки пишутся на диск в обратном порядку номеров.
|
/// `latestDictation`) — папки пишутся на диск в обратном порядку номеров.
|
||||||
public struct DictationHistoryEntry: Equatable, Identifiable {
|
public struct DictationHistoryEntry: Equatable, Identifiable, Sendable {
|
||||||
let directory: URL
|
let directory: URL
|
||||||
public let label: String
|
public let label: String
|
||||||
/// Сырьё — ответ ASR байт в байт. Есть всегда, иначе записи нет.
|
/// Сырьё — ответ ASR байт в байт. Есть всегда, иначе записи нет.
|
||||||
@@ -66,11 +66,16 @@ public let DICTATION_HISTORY_KEEP_LIMIT = 500
|
|||||||
/// никогда.
|
/// никогда.
|
||||||
public func dictationHistoryDirectories(in dictationsRoot: URL,
|
public func dictationHistoryDirectories(in dictationsRoot: URL,
|
||||||
fileManager: FileManager = .default) -> [URL] {
|
fileManager: FileManager = .default) -> [URL] {
|
||||||
let urls = (try? fileManager.contentsOfDirectory(
|
(try? readDictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)) ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
private func readDictationHistoryDirectories(in dictationsRoot: URL,
|
||||||
|
fileManager: FileManager) throws -> [URL] {
|
||||||
|
let urls = try fileManager.contentsOfDirectory(
|
||||||
at: dictationsRoot,
|
at: dictationsRoot,
|
||||||
includingPropertiesForKeys: [.isDirectoryKey],
|
includingPropertiesForKeys: [.isDirectoryKey],
|
||||||
options: [.skipsHiddenFiles]
|
options: [.skipsHiddenFiles]
|
||||||
)) ?? []
|
)
|
||||||
return urls
|
return urls
|
||||||
.filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
|
.filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
|
||||||
.sorted { $0.lastPathComponent > $1.lastPathComponent }
|
.sorted { $0.lastPathComponent > $1.lastPathComponent }
|
||||||
@@ -79,7 +84,14 @@ public func dictationHistoryDirectories(in dictationsRoot: URL,
|
|||||||
public func dictationHistoryEntries(in dictationsRoot: URL,
|
public func dictationHistoryEntries(in dictationsRoot: URL,
|
||||||
limit: Int? = nil,
|
limit: Int? = nil,
|
||||||
fileManager: FileManager = .default) -> [DictationHistoryEntry] {
|
fileManager: FileManager = .default) -> [DictationHistoryEntry] {
|
||||||
var directories = dictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)
|
(try? readDictationHistoryEntries(in: dictationsRoot, limit: limit, fileManager: fileManager)) ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Для интерфейса: недоступный каталог — ошибка, а не пустая история.
|
||||||
|
public func readDictationHistoryEntries(in dictationsRoot: URL,
|
||||||
|
limit: Int? = nil,
|
||||||
|
fileManager: FileManager = .default) throws -> [DictationHistoryEntry] {
|
||||||
|
var directories = try readDictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)
|
||||||
// Обрезаем ДО чтения содержимого: смысл потолка в том, чтобы не открывать
|
// Обрезаем ДО чтения содержимого: смысл потолка в том, чтобы не открывать
|
||||||
// тысячи файлов, а не в том, чтобы открыть их и показать сотню.
|
// тысячи файлов, а не в том, чтобы открыть их и показать сотню.
|
||||||
if let limit, directories.count > limit { directories = Array(directories.prefix(limit)) }
|
if let limit, directories.count > limit { directories = Array(directories.prefix(limit)) }
|
||||||
@@ -199,7 +211,8 @@ enum DictationHistoryKeyAction: Equatable {
|
|||||||
|
|
||||||
func dictationHistoryKeyAction(keyCode: CGKeyCode,
|
func dictationHistoryKeyAction(keyCode: CGKeyCode,
|
||||||
charactersIgnoringModifiers: String?,
|
charactersIgnoringModifiers: String?,
|
||||||
hasCommand: Bool) -> DictationHistoryKeyAction {
|
hasCommand: Bool,
|
||||||
|
hasTextSelection: Bool = false) -> DictationHistoryKeyAction {
|
||||||
if hasCommand {
|
if hasCommand {
|
||||||
// ⌘⌫ здесь СОЗНАТЕЛЬНО не занят. Это документированный системный
|
// ⌘⌫ здесь СОЗНАТЕЛЬНО не занят. Это документированный системный
|
||||||
// шорткат текстового поля («удалить от курсора до начала строки»), а
|
// шорткат текстового поля («удалить от курсора до начала строки»), а
|
||||||
@@ -208,7 +221,7 @@ func dictationHistoryKeyAction(keyCode: CGKeyCode,
|
|||||||
// расшифровку речи клиента. Удаление живёт в контекстном меню, где его
|
// расшифровку речи клиента. Удаление живёт в контекстном меню, где его
|
||||||
// нельзя нажать не глядя.
|
// нельзя нажать не глядя.
|
||||||
switch charactersIgnoringModifiers?.lowercased() {
|
switch charactersIgnoringModifiers?.lowercased() {
|
||||||
case "c": return .copySelected
|
case "c": return hasTextSelection ? .passThrough : .copySelected
|
||||||
default: return .passThrough
|
default: return .passThrough
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,9 +59,14 @@ func pasteboardRestoreDecision(transientChangeCount: Int?,
|
|||||||
}
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
enum DictationHistoryClipboard {
|
public enum DictationHistoryClipboard {
|
||||||
private static var pending: HistoryClipboardTransaction?
|
private static var pending: HistoryClipboardTransaction?
|
||||||
|
|
||||||
|
/// Общий путь копирования для настроек и плавающего окна.
|
||||||
|
public static func copy(_ text: String) -> Bool {
|
||||||
|
copy(text, pasteboard: .general)
|
||||||
|
}
|
||||||
|
|
||||||
/// Кладёт текст в буфер. `false` — буфер отказал, вызывающий обязан сказать
|
/// Кладёт текст в буфер. `false` — буфер отказал, вызывающий обязан сказать
|
||||||
/// владельцу, что копирование не состоялось.
|
/// владельцу, что копирование не состоялось.
|
||||||
///
|
///
|
||||||
@@ -69,7 +74,7 @@ enum DictationHistoryClipboard {
|
|||||||
/// дописывает в живой лог владельца.
|
/// дописывает в живой лог владельца.
|
||||||
@discardableResult
|
@discardableResult
|
||||||
static func copy(_ text: String,
|
static func copy(_ text: String,
|
||||||
pasteboard: NSPasteboard = .general,
|
pasteboard: NSPasteboard,
|
||||||
hold: TimeInterval = HISTORY_CLIPBOARD_HOLD_SECONDS,
|
hold: TimeInterval = HISTORY_CLIPBOARD_HOLD_SECONDS,
|
||||||
logLine: @escaping (String) -> Void = { log($0) }) -> Bool {
|
logLine: @escaping (String) -> Void = { log($0) }) -> Bool {
|
||||||
quench(reason: "вытеснено следующим копированием")
|
quench(reason: "вытеснено следующим копированием")
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ final class DictationHistoryPresenter {
|
|||||||
/// Поднят лист подтверждения «очистить всё». Пока он висит, клавиши окна
|
/// Поднят лист подтверждения «очистить всё». Пока он висит, клавиши окна
|
||||||
/// не работают: Escape обязан закрывать вопрос, а не всё окно под ним.
|
/// не работают: Escape обязан закрывать вопрос, а не всё окно под ним.
|
||||||
private var isConfirming = false
|
private var isConfirming = false
|
||||||
|
private var presentationGeneration = 0
|
||||||
private let dictationsRoot: () throws -> URL
|
private let dictationsRoot: () throws -> URL
|
||||||
|
|
||||||
init(dictationsRoot: @escaping () throws -> URL = { try DictationStore.dictationsDirectory() }) {
|
init(dictationsRoot: @escaping () throws -> URL = { try DictationStore.dictationsDirectory() }) {
|
||||||
@@ -59,6 +60,7 @@ final class DictationHistoryPresenter {
|
|||||||
// MARK: - Показ
|
// MARK: - Показ
|
||||||
|
|
||||||
private func present(rescue: DictationRescue?) {
|
private func present(rescue: DictationRescue?) {
|
||||||
|
presentationGeneration += 1
|
||||||
let entries: [DictationHistoryEntry]
|
let entries: [DictationHistoryEntry]
|
||||||
if rescue == nil {
|
if rescue == nil {
|
||||||
// Список читается ПОСЛЕ показа окна, в фоне. Владелец: «открываю
|
// Список читается ПОСЛЕ показа окна, в фоне. Владелец: «открываю
|
||||||
@@ -116,12 +118,7 @@ final class DictationHistoryPresenter {
|
|||||||
model.focusSearchField = rescue == nil
|
model.focusSearchField = rescue == nil
|
||||||
installKeyMonitor()
|
installKeyMonitor()
|
||||||
if rescue == nil {
|
if rescue == nil {
|
||||||
model.didLoadAll = false
|
model.reload(from: dictationsRoot)
|
||||||
model.onSearchStarted = { [weak self, weak model] in
|
|
||||||
guard let self, let model else { return }
|
|
||||||
self.loadAllForSearch(into: model)
|
|
||||||
}
|
|
||||||
loadEntriesInBackground(into: model)
|
|
||||||
}
|
}
|
||||||
if let rescue {
|
if let rescue {
|
||||||
// Ни имени приложения, ни самого текста в логе: лог живёт на диске
|
// Ни имени приложения, ни самого текста в логе: лог живёт на диске
|
||||||
@@ -133,55 +130,6 @@ final class DictationHistoryPresenter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Прочитать надиктовки с диска и отдать их окну, когда прочитаются.
|
|
||||||
///
|
|
||||||
/// Отдельным ходом, а не внутри показа: чтение занимает секунды на большом
|
|
||||||
/// каталоге, а окно обязано открыться мгновенно. Пока список едет, в окне
|
|
||||||
/// стоит честная строка «Читаю надиктовки…», а не пустота, которую легко
|
|
||||||
/// прочитать как «ничего нет».
|
|
||||||
private func loadEntriesInBackground(into model: DictationHistoryModel) {
|
|
||||||
model.isLoading = true
|
|
||||||
let root = try? dictationsRoot()
|
|
||||||
guard let root else {
|
|
||||||
model.isLoading = false
|
|
||||||
log("history: cannot reach dictations directory")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
Task.detached(priority: .userInitiated) {
|
|
||||||
let startedAt = ProcessInfo.processInfo.systemUptime
|
|
||||||
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT)
|
|
||||||
let spent = (ProcessInfo.processInfo.systemUptime - startedAt) * 1000
|
|
||||||
await MainActor.run {
|
|
||||||
model.load(found)
|
|
||||||
model.isLoading = false
|
|
||||||
log(String(format: "history: %d записей прочитано за %.0f мс (в фоне)",
|
|
||||||
found.count, spent))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Догрузить остальное хранимое - по первому же поиску.
|
|
||||||
///
|
|
||||||
/// Окно открывается сотней свежих: их хватает, чтобы забрать вчерашнее.
|
|
||||||
/// Но поиск по сотне врал бы молча - человек ищет фразу, которая лежит
|
|
||||||
/// двухсотой, и получает «ничего не нашлось». Поэтому первый ввод в поле
|
|
||||||
/// поиска дочитывает всё, что хранится, и делает это один раз за показ.
|
|
||||||
private func loadAllForSearch(into model: DictationHistoryModel) {
|
|
||||||
guard !model.didLoadAll else { return }
|
|
||||||
model.didLoadAll = true
|
|
||||||
guard let root = try? dictationsRoot() else { return }
|
|
||||||
Task.detached(priority: .userInitiated) {
|
|
||||||
let startedAt = ProcessInfo.processInfo.systemUptime
|
|
||||||
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_KEEP_LIMIT)
|
|
||||||
let spent = (ProcessInfo.processInfo.systemUptime - startedAt) * 1000
|
|
||||||
await MainActor.run {
|
|
||||||
model.load(found)
|
|
||||||
log(String(format: "history: поиск дочитал %d записей за %.0f мс",
|
|
||||||
found.count, spent))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makePanel(model: DictationHistoryModel) -> DictationHistoryPanel {
|
private func makePanel(model: DictationHistoryModel) -> DictationHistoryPanel {
|
||||||
let panel = DictationHistoryPanel(
|
let panel = DictationHistoryPanel(
|
||||||
contentRect: historyPanelFrame(),
|
contentRect: historyPanelFrame(),
|
||||||
@@ -241,7 +189,10 @@ final class DictationHistoryPresenter {
|
|||||||
// MARK: - Закрытие и возврат фокуса
|
// MARK: - Закрытие и возврат фокуса
|
||||||
|
|
||||||
private func close(returningFocus: Bool) {
|
private func close(returningFocus: Bool) {
|
||||||
|
presentationGeneration += 1
|
||||||
removeKeyMonitor()
|
removeKeyMonitor()
|
||||||
|
model?.cancelLoading()
|
||||||
|
model?.isClearing = false
|
||||||
model?.focusSearchField = false
|
model?.focusSearchField = false
|
||||||
// Спасённый текст живёт ровно столько, сколько висит окно. Иначе
|
// Спасённый текст живёт ровно столько, сколько висит окно. Иначе
|
||||||
// следующее открытие истории по хоткею подняло бы чужую позавчерашнюю
|
// следующее открытие истории по хоткею подняло бы чужую позавчерашнюю
|
||||||
@@ -400,6 +351,7 @@ final class DictationHistoryPresenter {
|
|||||||
|
|
||||||
private func copy(text: String) {
|
private func copy(text: String) {
|
||||||
guard DictationHistoryClipboard.copy(text) else {
|
guard DictationHistoryClipboard.copy(text) else {
|
||||||
|
model?.showError(L("history.copyFailed", "Не удалось скопировать. Попробуй ещё раз."))
|
||||||
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
|
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -407,21 +359,49 @@ final class DictationHistoryPresenter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func delete(_ entry: DictationHistoryEntry) {
|
private func delete(_ entry: DictationHistoryEntry) {
|
||||||
|
guard model?.isClearing != true else { return }
|
||||||
do {
|
do {
|
||||||
try removeDictationHistoryEntry(entry)
|
try removeDictationHistoryEntry(entry)
|
||||||
log("history: entry \(entry.label) moved to Trash with its directory")
|
log("history: entry \(entry.label) moved to Trash with its directory")
|
||||||
|
reload()
|
||||||
} catch {
|
} catch {
|
||||||
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
||||||
|
model?.showError(L("history.deleteFailed", "Не удалось переместить запись в Корзину. Попробуй ещё раз."))
|
||||||
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
|
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
|
||||||
}
|
}
|
||||||
reload()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private func clearAll() {
|
private func clearAll() {
|
||||||
guard let model, let panel, !model.entries.isEmpty, !isConfirming else { return }
|
guard let model, let panel, !model.entries.isEmpty, !isConfirming, !model.isClearing else { return }
|
||||||
|
let generation = presentationGeneration
|
||||||
|
model.isClearing = true
|
||||||
|
Task { @MainActor [weak self] in
|
||||||
|
guard let self else { return }
|
||||||
|
do {
|
||||||
|
let root = try self.dictationsRoot()
|
||||||
|
let doomed = try await Task.detached(priority: .userInitiated) {
|
||||||
|
try readDictationHistoryEntries(in: root)
|
||||||
|
}.value
|
||||||
|
guard self.presentationGeneration == generation, panel.isVisible else { return }
|
||||||
|
guard !doomed.isEmpty else {
|
||||||
|
model.isClearing = false
|
||||||
|
self.reload()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
self.confirmClearAll(doomed, model: model, panel: panel)
|
||||||
|
} catch {
|
||||||
|
guard self.presentationGeneration == generation else { return }
|
||||||
|
model.isClearing = false
|
||||||
|
model.showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func confirmClearAll(_ doomed: [DictationHistoryEntry],
|
||||||
|
model: DictationHistoryModel,
|
||||||
|
panel: DictationHistoryPanel) {
|
||||||
// Число записей — ДО удаления и в самом вопросе: иначе владелец
|
// Число записей — ДО удаления и в самом вопросе: иначе владелец
|
||||||
// подтверждает вслепую.
|
// подтверждает вслепую. Снимок включает весь архив, а не видимую сотню.
|
||||||
let doomed = model.entries
|
|
||||||
let alert = NSAlert()
|
let alert = NSAlert()
|
||||||
alert.alertStyle = .warning
|
alert.alertStyle = .warning
|
||||||
alert.messageText = dictationHistoryClearConfirmation(count: doomed.count)
|
alert.messageText = dictationHistoryClearConfirmation(count: doomed.count)
|
||||||
@@ -438,31 +418,37 @@ final class DictationHistoryPresenter {
|
|||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
self.isConfirming = false
|
self.isConfirming = false
|
||||||
guard response == .alertFirstButtonReturn else {
|
guard response == .alertFirstButtonReturn else {
|
||||||
|
model.isClearing = false
|
||||||
log("history: clear all cancelled (\(doomed.count) entries kept)")
|
log("history: clear all cancelled (\(doomed.count) entries kept)")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var deleted = 0
|
Task { @MainActor in
|
||||||
for entry in doomed {
|
let deleted = await Task.detached(priority: .userInitiated) {
|
||||||
do {
|
var deleted = 0
|
||||||
try removeDictationHistoryEntry(entry)
|
for entry in doomed {
|
||||||
deleted += 1
|
do {
|
||||||
} catch {
|
try removeDictationHistoryEntry(entry)
|
||||||
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
deleted += 1
|
||||||
|
} catch {
|
||||||
|
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return deleted
|
||||||
|
}.value
|
||||||
|
model.isClearing = false
|
||||||
|
log("history: cleared \(deleted) of \(doomed.count) entries")
|
||||||
|
self.reload()
|
||||||
|
if deleted != doomed.count {
|
||||||
|
model.showError(Lf("history.clearFailed", "Не удалось переместить в Корзину: %d из %d. Остальные записи уже в Корзине.", doomed.count - deleted, doomed.count))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log("history: cleared \(deleted) of \(doomed.count) entries")
|
|
||||||
self.reload()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func reload() {
|
private func reload() {
|
||||||
guard let model else { return }
|
guard let model else { return }
|
||||||
do {
|
model.reload(from: dictationsRoot)
|
||||||
model.load(dictationHistoryEntries(in: try dictationsRoot()))
|
|
||||||
} catch {
|
|
||||||
log("history: cannot reach dictations directory: \(error.localizedDescription)")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Клавиши
|
// MARK: - Клавиши
|
||||||
@@ -488,10 +474,14 @@ final class DictationHistoryPresenter {
|
|||||||
/// `true` — нажатие съедено окном, в поле поиска не уходит.
|
/// `true` — нажатие съедено окном, в поле поиска не уходит.
|
||||||
private func handle(_ event: NSEvent) -> Bool {
|
private func handle(_ event: NSEvent) -> Bool {
|
||||||
guard let model, !isConfirming else { return false }
|
guard let model, !isConfirming else { return false }
|
||||||
|
// Выделенный текст принадлежит редактору поиска/спасения: ⌘C должен
|
||||||
|
// копировать именно выделение, не выбранную запись и не закрывать окно.
|
||||||
|
let editor = panel?.firstResponder as? NSTextView
|
||||||
let action = dictationHistoryKeyAction(
|
let action = dictationHistoryKeyAction(
|
||||||
keyCode: CGKeyCode(event.keyCode),
|
keyCode: CGKeyCode(event.keyCode),
|
||||||
charactersIgnoringModifiers: event.charactersIgnoringModifiers,
|
charactersIgnoringModifiers: event.charactersIgnoringModifiers,
|
||||||
hasCommand: event.modifierFlags.contains(.command)
|
hasCommand: event.modifierFlags.contains(.command),
|
||||||
|
hasTextSelection: (editor?.selectedRange().length ?? 0) > 0
|
||||||
)
|
)
|
||||||
// В режиме спасения списка на экране нет, и те же клавиши обязаны
|
// В режиме спасения списка на экране нет, и те же клавиши обязаны
|
||||||
// относиться к спасённому тексту, а не к невидимой выделенной записи.
|
// относиться к спасённому тексту, а не к невидимой выделенной записи.
|
||||||
@@ -549,15 +539,18 @@ private final class DictationHistoryPanel: NSPanel {
|
|||||||
// MARK: - Модель списка
|
// MARK: - Модель списка
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
final class DictationHistoryModel: ObservableObject {
|
public final class DictationHistoryModel: ObservableObject {
|
||||||
@Published private(set) var entries: [DictationHistoryEntry] = []
|
@Published public private(set) var entries: [DictationHistoryEntry] = []
|
||||||
@Published var query: String = "" {
|
@Published public var query: String = "" {
|
||||||
didSet {
|
didSet {
|
||||||
guard query != oldValue else { return }
|
guard query != oldValue else { return }
|
||||||
clampSelection()
|
clampSelection()
|
||||||
// Первый же символ запроса дочитывает всё хранимое: искать по
|
// Первый же символ запроса дочитывает всё хранимое: искать по
|
||||||
// видимой сотне значит молча врать «ничего не нашлось».
|
// видимой сотне значит молча врать «ничего не нашлось».
|
||||||
if !query.isEmpty { onSearchStarted?() }
|
if !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||||
|
!didLoadAll, !isLoadingAll, let root {
|
||||||
|
loadInBackground(from: root, all: true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Published private(set) var selection: Int = 0
|
@Published private(set) var selection: Int = 0
|
||||||
@@ -565,12 +558,21 @@ final class DictationHistoryModel: ObservableObject {
|
|||||||
/// Список ещё читается с диска. Отдельный признак, а не пустой список:
|
/// Список ещё читается с диска. Отдельный признак, а не пустой список:
|
||||||
/// «пока ничего нет» и «ещё не прочитал» - разные вещи, и путать их значит
|
/// «пока ничего нет» и «ещё не прочитал» - разные вещи, и путать их значит
|
||||||
/// врать владельцу, у которого две тысячи надиктовок.
|
/// врать владельцу, у которого две тысячи надиктовок.
|
||||||
@Published var isLoading = false
|
@Published public private(set) var isLoading = false
|
||||||
|
@Published public var notice: String?
|
||||||
|
@Published public var noticeIsError = false
|
||||||
|
@Published var isClearing = false
|
||||||
/// Дочитано ли всё хранимое. Показ начинается с сотни свежих; поиск
|
/// Дочитано ли всё хранимое. Показ начинается с сотни свежих; поиск
|
||||||
/// дочитывает остальное один раз.
|
/// дочитывает остальное один раз.
|
||||||
var didLoadAll = false
|
private(set) var didLoadAll = false
|
||||||
/// Кого звать, когда владелец начал искать.
|
private var isLoadingAll = false
|
||||||
var onSearchStarted: (() -> Void)?
|
private var loadGeneration = 0
|
||||||
|
private var root: URL?
|
||||||
|
private let isPreview: Bool
|
||||||
|
|
||||||
|
public init(preview: Bool = false) {
|
||||||
|
isPreview = preview
|
||||||
|
}
|
||||||
/// Не `nil` — окно показывает не список, а текст, который не доехал до поля.
|
/// Не `nil` — окно показывает не список, а текст, который не доехал до поля.
|
||||||
@Published private(set) var rescue: DictationRescue?
|
@Published private(set) var rescue: DictationRescue?
|
||||||
/// Почему не сработал повтор вставки. Звука тут мало: владелец должен
|
/// Почему не сработал повтор вставки. Звука тут мало: владелец должен
|
||||||
@@ -587,8 +589,77 @@ final class DictationHistoryModel: ObservableObject {
|
|||||||
var onInsertRescue: (() -> Void)?
|
var onInsertRescue: (() -> Void)?
|
||||||
var onCopyRescue: (() -> Void)?
|
var onCopyRescue: (() -> Void)?
|
||||||
|
|
||||||
var visible: [DictationHistoryEntry] {
|
public var visible: [DictationHistoryEntry] {
|
||||||
filteredDictationHistory(entries, query: query)
|
query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||||
|
? Array(entries.prefix(DICTATION_HISTORY_VISIBLE_LIMIT))
|
||||||
|
: filteredDictationHistory(entries, query: query)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Превью проверяется ДО получения корня: даже путь к живому store не нужен.
|
||||||
|
public func reload(from rootProvider: () throws -> URL) {
|
||||||
|
cancelLoading()
|
||||||
|
didLoadAll = false
|
||||||
|
guard !isPreview else {
|
||||||
|
load([])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
let root = try rootProvider()
|
||||||
|
self.root = root
|
||||||
|
loadInBackground(from: root,
|
||||||
|
all: !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||||
|
} catch {
|
||||||
|
showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public func cancelLoading() {
|
||||||
|
loadGeneration += 1
|
||||||
|
isLoading = false
|
||||||
|
isLoadingAll = false
|
||||||
|
root = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func showError(_ message: String) {
|
||||||
|
notice = message
|
||||||
|
noticeIsError = true
|
||||||
|
}
|
||||||
|
|
||||||
|
private func loadInBackground(from root: URL, all: Bool) {
|
||||||
|
let generation = beginLoading(all: all)
|
||||||
|
Task.detached(priority: .userInitiated) { [weak self] in
|
||||||
|
let result = Result {
|
||||||
|
// ponytail: весь архив читается лишь при поиске; индекс нужен,
|
||||||
|
// если измеренное время чтения станет мешать поиску.
|
||||||
|
try readDictationHistoryEntries(in: root,
|
||||||
|
limit: all ? nil : DICTATION_HISTORY_VISIBLE_LIMIT)
|
||||||
|
}
|
||||||
|
await self?.completeLoading(result, generation: generation, all: all)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Поколение общее для краткого списка, поиска и повторного открытия.
|
||||||
|
func beginLoading(all: Bool) -> Int {
|
||||||
|
loadGeneration += 1
|
||||||
|
isLoading = true
|
||||||
|
isLoadingAll = all
|
||||||
|
notice = nil
|
||||||
|
noticeIsError = false
|
||||||
|
return loadGeneration
|
||||||
|
}
|
||||||
|
|
||||||
|
func completeLoading(_ result: Result<[DictationHistoryEntry], Error>,
|
||||||
|
generation: Int, all: Bool) {
|
||||||
|
guard generation == loadGeneration else { return }
|
||||||
|
isLoading = false
|
||||||
|
isLoadingAll = false
|
||||||
|
switch result {
|
||||||
|
case .success(let found):
|
||||||
|
load(found)
|
||||||
|
didLoadAll = all
|
||||||
|
case .failure:
|
||||||
|
showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var selectedEntry: DictationHistoryEntry? {
|
var selectedEntry: DictationHistoryEntry? {
|
||||||
@@ -661,7 +732,13 @@ struct DictationHistoryView: View {
|
|||||||
|
|
||||||
Group {
|
Group {
|
||||||
if model.visible.isEmpty {
|
if model.visible.isEmpty {
|
||||||
emptyState
|
if let notice = model.notice, model.noticeIsError {
|
||||||
|
Label(notice, systemImage: "exclamationmark.circle")
|
||||||
|
.foregroundStyle(.red)
|
||||||
|
.padding(24)
|
||||||
|
} else {
|
||||||
|
emptyState
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
list
|
list
|
||||||
}
|
}
|
||||||
@@ -669,6 +746,17 @@ struct DictationHistoryView: View {
|
|||||||
.frame(maxHeight: .infinity)
|
.frame(maxHeight: .infinity)
|
||||||
.background(IrizFloatingPlate())
|
.background(IrizFloatingPlate())
|
||||||
|
|
||||||
|
if model.isLoading, !model.entries.isEmpty {
|
||||||
|
ProgressView(L("history.loading", "Читаю надиктовки…"))
|
||||||
|
.controlSize(.small)
|
||||||
|
}
|
||||||
|
if let notice = model.notice, !model.entries.isEmpty {
|
||||||
|
Label(notice, systemImage: model.noticeIsError ? "exclamationmark.circle" : "checkmark.circle")
|
||||||
|
.foregroundStyle(model.noticeIsError ? Color.red : Color.primary)
|
||||||
|
.font(.system(size: 12))
|
||||||
|
.padding(.horizontal, 12)
|
||||||
|
}
|
||||||
|
|
||||||
footer
|
footer
|
||||||
.background(IrizFloatingPlate())
|
.background(IrizFloatingPlate())
|
||||||
}
|
}
|
||||||
@@ -739,6 +827,11 @@ struct DictationHistoryView: View {
|
|||||||
.fixedSize(horizontal: false, vertical: true)
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
.accessibilityLabel(notice)
|
.accessibilityLabel(notice)
|
||||||
}
|
}
|
||||||
|
if let notice = model.notice {
|
||||||
|
Label(notice, systemImage: "exclamationmark.circle")
|
||||||
|
.foregroundStyle(.red)
|
||||||
|
.font(.system(size: 12))
|
||||||
|
}
|
||||||
|
|
||||||
HStack(spacing: 12) {
|
HStack(spacing: 12) {
|
||||||
hint("⏎", L("history.legendInsert", "вставить"))
|
hint("⏎", L("history.legendInsert", "вставить"))
|
||||||
@@ -796,6 +889,7 @@ struct DictationHistoryView: View {
|
|||||||
}
|
}
|
||||||
.buttonStyle(.plain)
|
.buttonStyle(.plain)
|
||||||
.help(L("history.searchClear", "Очистить поиск"))
|
.help(L("history.searchClear", "Очистить поиск"))
|
||||||
|
.accessibilityLabel(L("history.searchClear", "Очистить поиск"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.padding(.horizontal, 10)
|
.padding(.horizontal, 10)
|
||||||
@@ -835,10 +929,16 @@ struct DictationHistoryView: View {
|
|||||||
ScrollView {
|
ScrollView {
|
||||||
LazyVStack(spacing: 2) {
|
LazyVStack(spacing: 2) {
|
||||||
ForEach(Array(model.visible.enumerated()), id: \.element.id) { index, entry in
|
ForEach(Array(model.visible.enumerated()), id: \.element.id) { index, entry in
|
||||||
row(entry, isSelected: index == model.selection)
|
Button { model.select(entry) } label: {
|
||||||
.id(entry.id)
|
row(entry, isSelected: index == model.selection)
|
||||||
.contentShape(Rectangle())
|
.contentShape(Rectangle())
|
||||||
.onTapGesture { model.select(entry) }
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.accessibilityElement(children: .combine)
|
||||||
|
.accessibilityAddTraits(index == model.selection ? .isSelected : [])
|
||||||
|
.accessibilityAction(named: Text(L("history.insert", "Вставить"))) { model.onInsert?(entry) }
|
||||||
|
.accessibilityAction(named: Text(L("history.copyButton", "Копировать"))) { model.onCopy?(entry) }
|
||||||
|
.id(entry.id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.padding(.vertical, 6)
|
.padding(.vertical, 6)
|
||||||
@@ -888,6 +988,7 @@ struct DictationHistoryView: View {
|
|||||||
Button(L("history.copyButton", "Копировать")) { model.onCopy?(entry) }
|
Button(L("history.copyButton", "Копировать")) { model.onCopy?(entry) }
|
||||||
Divider()
|
Divider()
|
||||||
Button(L("history.trashOne", "Переместить в Корзину"), role: .destructive) { model.onDelete?(entry) }
|
Button(L("history.trashOne", "Переместить в Корзину"), role: .destructive) { model.onDelete?(entry) }
|
||||||
|
.disabled(model.isClearing)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -900,6 +1001,10 @@ struct DictationHistoryView: View {
|
|||||||
/// место под строкой.
|
/// место под строкой.
|
||||||
private var footer: some View {
|
private var footer: some View {
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
if model.isClearing {
|
||||||
|
ProgressView(L("history.clearing", "Подготовка и очистка истории…"))
|
||||||
|
.controlSize(.small)
|
||||||
|
}
|
||||||
HStack(spacing: 12) {
|
HStack(spacing: 12) {
|
||||||
hint("⏎", L("history.legendInsert", "вставить"))
|
hint("⏎", L("history.legendInsert", "вставить"))
|
||||||
hint("⌘C", L("history.legendCopy", "копировать"))
|
hint("⌘C", L("history.legendCopy", "копировать"))
|
||||||
@@ -922,6 +1027,11 @@ struct DictationHistoryView: View {
|
|||||||
.font(.system(size: 11))
|
.font(.system(size: 11))
|
||||||
.foregroundStyle(IRIZ_SUBTLE)
|
.foregroundStyle(IRIZ_SUBTLE)
|
||||||
.accessibilityLabel(L("history.clipboardNoteVoice", "Скопированное держится в буфере две минуты, потом буфер чистится"))
|
.accessibilityLabel(L("history.clipboardNoteVoice", "Скопированное держится в буфере две минуты, потом буфер чистится"))
|
||||||
|
if model.query.isEmpty, model.entries.count >= DICTATION_HISTORY_VISIBLE_LIMIT {
|
||||||
|
Text(L("history.loadingBody", "Показываю последние сто. Остальные найдёт поиск."))
|
||||||
|
.font(.system(size: 11))
|
||||||
|
.foregroundStyle(IRIZ_SUBTLE)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.padding(.horizontal, 16)
|
.padding(.horizontal, 16)
|
||||||
.padding(.vertical, 8)
|
.padding(.vertical, 8)
|
||||||
@@ -936,11 +1046,11 @@ struct DictationHistoryView: View {
|
|||||||
if #available(macOS 26.0, *) {
|
if #available(macOS 26.0, *) {
|
||||||
Button(action: { model.onClearAll?() }) { label }
|
Button(action: { model.onClearAll?() }) { label }
|
||||||
.buttonStyle(.glass)
|
.buttonStyle(.glass)
|
||||||
.disabled(model.entries.isEmpty)
|
.disabled(model.entries.isEmpty || model.isClearing)
|
||||||
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
|
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
|
||||||
} else {
|
} else {
|
||||||
Button(action: { model.onClearAll?() }) { label }
|
Button(action: { model.onClearAll?() }) { label }
|
||||||
.disabled(model.entries.isEmpty)
|
.disabled(model.entries.isEmpty || model.isClearing)
|
||||||
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
|
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,20 @@ public enum MeetingPipelineFailure: String, Error, Equatable {
|
|||||||
case storeFailed = "не удалось сохранить встречу на диск"
|
case storeFailed = "не удалось сохранить встречу на диск"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whisper может вернуть текст без времён слов. Успешная диаризация сама по
|
||||||
|
/// себе ещё не связывает слова с людьми: весь исходный текст должен сохраниться.
|
||||||
|
func meetingSpeakerTurns(transcript: AudioFileTranscript, spans: [SpeakerSpan],
|
||||||
|
names: SpeakerNames = SpeakerNames())
|
||||||
|
-> (turns: [SpeakerTurn], speakersResolved: Bool) {
|
||||||
|
let turns = speakerTurnsNamed(speakerTurns(tokens: transcript.tokenTimings, spans: spans), names: names)
|
||||||
|
guard !spans.isEmpty,
|
||||||
|
turns.contains(where: { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else {
|
||||||
|
return ([SpeakerTurn(speaker: "Запись", text: transcript.text,
|
||||||
|
start: 0, end: transcript.audioSeconds)], false)
|
||||||
|
}
|
||||||
|
return (turns, true)
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
public final class MeetingPipeline {
|
public final class MeetingPipeline {
|
||||||
private let transcriber: AudioFileTranscriber
|
private let transcriber: AudioFileTranscriber
|
||||||
@@ -52,20 +66,33 @@ public final class MeetingPipeline {
|
|||||||
public func run(audio url: URL, title: String, names: SpeakerNames = SpeakerNames(),
|
public func run(audio url: URL, title: String, names: SpeakerNames = SpeakerNames(),
|
||||||
at date: Date = Date(),
|
at date: Date = Date(),
|
||||||
progress: @escaping (String) -> Void = { _ in }) async throws -> MeetingResult {
|
progress: @escaping (String) -> Void = { _ in }) async throws -> MeetingResult {
|
||||||
|
try Task.checkCancellation()
|
||||||
progress("Читаю запись")
|
progress("Читаю запись")
|
||||||
guard let decoded = try? await AudioFileDecoder.decode(url) else {
|
let decoded: DecodedAudio
|
||||||
|
do {
|
||||||
|
decoded = try await AudioFileDecoder.decode(url)
|
||||||
|
} catch is CancellationError {
|
||||||
|
throw CancellationError()
|
||||||
|
} catch {
|
||||||
|
try Task.checkCancellation()
|
||||||
throw MeetingPipelineFailure.audioUnreadable
|
throw MeetingPipelineFailure.audioUnreadable
|
||||||
}
|
}
|
||||||
|
try Task.checkCancellation()
|
||||||
|
|
||||||
progress("Расшифровываю")
|
progress("Расшифровываю")
|
||||||
_ = try? await transcriber.prepare()
|
|
||||||
let transcript: AudioFileTranscript
|
let transcript: AudioFileTranscript
|
||||||
do {
|
do {
|
||||||
|
_ = try await transcriber.prepare()
|
||||||
|
try Task.checkCancellation()
|
||||||
transcript = try await transcriber.transcribe(decoded, language: .russian)
|
transcript = try await transcriber.transcribe(decoded, language: .russian)
|
||||||
|
} catch is CancellationError {
|
||||||
|
throw CancellationError()
|
||||||
} catch {
|
} catch {
|
||||||
|
try Task.checkCancellation()
|
||||||
log("meeting: расшифровка отказала (\(error))")
|
log("meeting: расшифровка отказала (\(error))")
|
||||||
throw MeetingPipelineFailure.transcriptionFailed
|
throw MeetingPipelineFailure.transcriptionFailed
|
||||||
}
|
}
|
||||||
|
try Task.checkCancellation()
|
||||||
guard !transcript.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
guard !transcript.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||||
throw MeetingPipelineFailure.nothingRecognized
|
throw MeetingPipelineFailure.nothingRecognized
|
||||||
}
|
}
|
||||||
@@ -73,22 +100,28 @@ public final class MeetingPipeline {
|
|||||||
progress("Разбираю говорящих")
|
progress("Разбираю говорящих")
|
||||||
// Отказ диаризатора конвейер не роняет: протокол без разделения хуже
|
// Отказ диаризатора конвейер не роняет: протокол без разделения хуже
|
||||||
// полного, но лучше отсутствующего.
|
// полного, но лучше отсутствующего.
|
||||||
let spans = (try? await diarizer.spans(of: url)) ?? []
|
let spans: [SpeakerSpan]
|
||||||
let turns = spans.isEmpty
|
do {
|
||||||
? [SpeakerTurn(speaker: "Запись", text: transcript.text,
|
spans = try await diarizer.spans(of: url)
|
||||||
start: 0, end: transcript.audioSeconds)]
|
} catch is CancellationError {
|
||||||
: speakerTurnsNamed(speakerTurns(tokens: transcript.tokenTimings, spans: spans),
|
throw CancellationError()
|
||||||
names: names)
|
} catch {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
spans = []
|
||||||
|
}
|
||||||
|
try Task.checkCancellation()
|
||||||
|
let resolved = meetingSpeakerTurns(transcript: transcript, spans: spans, names: names)
|
||||||
|
|
||||||
progress("Сохраняю")
|
progress("Сохраняю")
|
||||||
let document = MeetingProtocolDocument(title: title, recordedAt: date,
|
let document = MeetingProtocolDocument(title: title, recordedAt: date,
|
||||||
audioSeconds: transcript.audioSeconds,
|
audioSeconds: transcript.audioSeconds,
|
||||||
turns: turns)
|
turns: resolved.turns)
|
||||||
|
try Task.checkCancellation()
|
||||||
do {
|
do {
|
||||||
let artifacts = try MeetingStore.save(audio: url, protocolText: document.text(),
|
let artifacts = try MeetingStore.save(audio: url, protocolText: document.text(),
|
||||||
at: date, title: title, in: storeRoot)
|
at: date, title: title, in: storeRoot)
|
||||||
return MeetingResult(artifacts: artifacts, turns: turns,
|
return MeetingResult(artifacts: artifacts, turns: resolved.turns,
|
||||||
speakersResolved: !spans.isEmpty,
|
speakersResolved: resolved.speakersResolved,
|
||||||
audioSeconds: transcript.audioSeconds)
|
audioSeconds: transcript.audioSeconds)
|
||||||
} catch {
|
} catch {
|
||||||
log("meeting: запись на диск отказала (\(error))")
|
log("meeting: запись на диск отказала (\(error))")
|
||||||
|
|||||||
@@ -88,5 +88,5 @@ public func meetingRecordingScratchURL(at date: Date = Date()) throws -> URL {
|
|||||||
.appendingPathComponent("_recording", isDirectory: true)
|
.appendingPathComponent("_recording", isDirectory: true)
|
||||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true,
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true,
|
||||||
attributes: [.posixPermissions: 0o700])
|
attributes: [.posixPermissions: 0o700])
|
||||||
return root.appendingPathComponent("meeting-\(formatter.string(from: date)).wav")
|
return root.appendingPathComponent("meeting-\(formatter.string(from: date))-\(UUID().uuidString.lowercased()).wav")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,21 +45,31 @@ public enum MeetingStore {
|
|||||||
@discardableResult
|
@discardableResult
|
||||||
public static func save(audio: URL, protocolText: String, at date: Date = Date(),
|
public static func save(audio: URL, protocolText: String, at date: Date = Date(),
|
||||||
title: String, in root: URL? = nil) throws -> MeetingArtifacts {
|
title: String, in root: URL? = nil) throws -> MeetingArtifacts {
|
||||||
let directory = try meetingDirectory(at: date, title: title, in: root)
|
let manager = FileManager.default
|
||||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
|
let base = try meetingDirectory(at: date, title: title, in: root)
|
||||||
attributes: [.posixPermissions: 0o700])
|
let identifier = UUID().uuidString.lowercased()
|
||||||
let audioCopy = directory.appendingPathComponent("audio." + audio.pathExtension)
|
let directory = base.deletingLastPathComponent()
|
||||||
if FileManager.default.fileExists(atPath: audioCopy.path) {
|
.appendingPathComponent(base.lastPathComponent + "-" + identifier, isDirectory: true)
|
||||||
try FileManager.default.removeItem(at: audioCopy)
|
let staging = base.deletingLastPathComponent()
|
||||||
}
|
.appendingPathComponent(".saving-" + identifier, isDirectory: true)
|
||||||
try FileManager.default.copyItem(at: audio, to: audioCopy)
|
try manager.createDirectory(at: staging, withIntermediateDirectories: true,
|
||||||
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: audioCopy.path)
|
attributes: [.posixPermissions: 0o700])
|
||||||
|
// Новый архив появляется только целиком. Старые записи, в том числе с
|
||||||
|
// тем же названием и временем, никогда не служат временным каталогом.
|
||||||
|
defer { try? manager.removeItem(at: staging) }
|
||||||
|
let audioName = "audio." + audio.pathExtension
|
||||||
|
let audioCopy = staging.appendingPathComponent(audioName)
|
||||||
|
try manager.copyItem(at: audio, to: audioCopy)
|
||||||
|
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: audioCopy.path)
|
||||||
|
|
||||||
let transcript = directory.appendingPathComponent("protocol.md")
|
let transcript = staging.appendingPathComponent("protocol.md")
|
||||||
try protocolText.write(to: transcript, atomically: true, encoding: .utf8)
|
try protocolText.write(to: transcript, atomically: true, encoding: .utf8)
|
||||||
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: transcript.path)
|
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: transcript.path)
|
||||||
|
try manager.moveItem(at: staging, to: directory)
|
||||||
|
|
||||||
return MeetingArtifacts(directory: directory, audio: audioCopy, transcript: transcript)
|
return MeetingArtifacts(directory: directory,
|
||||||
|
audio: directory.appendingPathComponent(audioName),
|
||||||
|
transcript: directory.appendingPathComponent("protocol.md"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Имя папки из названия встречи: латиница и цифры, остальное в дефис.
|
/// Имя папки из названия встречи: латиница и цифры, остальное в дефис.
|
||||||
|
|||||||
@@ -6,19 +6,21 @@
|
|||||||
// приложение, а модель приезжает после установки - с показанным ходом и
|
// приложение, а модель приезжает после установки - с показанным ходом и
|
||||||
// понятной ценой.
|
// понятной ценой.
|
||||||
//
|
//
|
||||||
// Правило «сеть в диктовке запрещена» при этом остаётся. `enforceOffline`
|
// Явная установка получает закреплённые файлы через URLSession. Рубильник
|
||||||
// снимается ТОЛЬКО на время явной установки, которую начал человек, и
|
// офлайна распознавателя не меняется даже на время скачивания. Новая копия
|
||||||
// возвращается назад в `defer` - в том числе на ошибке и на отмене. Пока идёт
|
// проверяется отдельно; существующий кэш сохраняется при любом отказе.
|
||||||
// диктовка, установка не начинается вовсе: снятый рубильник при работающем
|
|
||||||
// конвейере означал бы, что распознавание может молча полезть в сеть.
|
|
||||||
import FluidAudio
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
import IrizCore
|
||||||
|
|
||||||
|
public let speechModelDidInstallNotification = Notification.Name("iriz.speechModelDidInstall")
|
||||||
|
// Сумма 21 файла закреплённого commit: официальный HF tree API, 12.09.2026.
|
||||||
|
public let speechModelDownloadBytes: Int64 = 483_105_645
|
||||||
|
|
||||||
/// Что происходит с установкой прямо сейчас.
|
/// Что происходит с установкой прямо сейчас.
|
||||||
public enum SpeechModelInstallPhase: Equatable, Sendable {
|
public enum SpeechModelInstallPhase: Equatable, Sendable {
|
||||||
/// Идёт скачивание, 0…1.
|
/// Идёт скачивание, 0…1.
|
||||||
case downloading(Double)
|
case downloading(Double)
|
||||||
/// Файлы получены, CoreML собирает модель под это железо.
|
/// Файлы получены, проверяется их целостность перед использованием.
|
||||||
case compiling
|
case compiling
|
||||||
case finished
|
case finished
|
||||||
case failed(String)
|
case failed(String)
|
||||||
@@ -29,7 +31,7 @@ public enum SpeechModelInstallRefusal: String, Equatable, Sendable {
|
|||||||
case alreadyInstalled
|
case alreadyInstalled
|
||||||
/// Установка уже идёт.
|
/// Установка уже идёт.
|
||||||
case alreadyRunning
|
case alreadyRunning
|
||||||
/// Идёт диктовка: рубильник сети при работающем конвейере не снимаем.
|
/// Идёт диктовка: установку не начинаем посреди активного сценария.
|
||||||
case dictationBusy
|
case dictationBusy
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,28 +49,45 @@ public func speechModelInstallRefusal(installed: Bool,
|
|||||||
/// Ход установки, как его показывает окно: доля и подпись.
|
/// Ход установки, как его показывает окно: доля и подпись.
|
||||||
public func speechModelInstallTitle(_ phase: SpeechModelInstallPhase) -> String {
|
public func speechModelInstallTitle(_ phase: SpeechModelInstallPhase) -> String {
|
||||||
switch phase {
|
switch phase {
|
||||||
case .downloading: return "Качаю модель распознавания"
|
case .downloading: return L("speechModel.downloading", "Качаю модель распознавания")
|
||||||
case .compiling: return "Готовлю модель под твой Мак"
|
case .compiling: return L("speechModel.verifying", "Проверяю скачанную модель")
|
||||||
case .finished: return "Модель на месте"
|
case .finished: return L("speechModel.ready", "Модель на месте")
|
||||||
case .failed: return "Скачать не вышло"
|
case .failed: return L("speechModel.failed", "Скачать не вышло")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func speechModelInstallFraction(_ phase: SpeechModelInstallPhase) -> Double {
|
public func speechModelInstallFraction(_ phase: SpeechModelInstallPhase) -> Double {
|
||||||
switch phase {
|
switch phase {
|
||||||
case .downloading(let value): return min(1, max(0, value))
|
case .downloading(let value): return min(1, max(0, value))
|
||||||
// Сборка идёт без хода: показываем почти полную полосу, а не откат назад.
|
// Все байты получены; проверка не откатывает полосу скачивания назад.
|
||||||
case .compiling: return 0.97
|
case .compiling: return 1
|
||||||
case .finished: return 1
|
case .finished: return 1
|
||||||
case .failed: return 0
|
case .failed: return 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public func speechModelInstallFailureMessage(for error: Error) -> String {
|
||||||
|
if error is CancellationError || (error as? URLError)?.code == .cancelled {
|
||||||
|
return L("speechModel.error.cancelled", "Скачивание отменено. Его можно запустить снова.")
|
||||||
|
}
|
||||||
|
switch (error as? URLError)?.code {
|
||||||
|
case .notConnectedToInternet:
|
||||||
|
return L("speechModel.error.offline", "Нет подключения к интернету. Подключись к сети и повтори скачивание.")
|
||||||
|
case .networkConnectionLost:
|
||||||
|
return L("speechModel.error.connectionLost", "Соединение прервалось. Проверь интернет и повтори скачивание.")
|
||||||
|
case .timedOut:
|
||||||
|
return L("speechModel.error.timeout", "Сервер не ответил вовремя. Повтори скачивание чуть позже.")
|
||||||
|
default:
|
||||||
|
return error.localizedDescription
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
public final class SpeechModelInstaller {
|
public final class SpeechModelInstaller {
|
||||||
public static let shared = SpeechModelInstaller()
|
public static let shared = SpeechModelInstaller()
|
||||||
|
|
||||||
private(set) public var isRunning = false
|
private(set) public var isRunning = false
|
||||||
|
private var downloadingFile: UUID?
|
||||||
|
|
||||||
private init() {}
|
private init() {}
|
||||||
|
|
||||||
@@ -78,33 +97,119 @@ public final class SpeechModelInstaller {
|
|||||||
public func install(dictating: Bool,
|
public func install(dictating: Bool,
|
||||||
progress: @escaping @MainActor (SpeechModelInstallPhase) -> Void)
|
progress: @escaping @MainActor (SpeechModelInstallPhase) -> Void)
|
||||||
async -> SpeechModelInstallRefusal? {
|
async -> SpeechModelInstallRefusal? {
|
||||||
let installed = speechModelCacheExists(for: .multilingualV3)
|
if let refusal = speechModelInstallRefusal(installed: false,
|
||||||
if let refusal = speechModelInstallRefusal(installed: installed,
|
|
||||||
running: isRunning,
|
running: isRunning,
|
||||||
dictating: dictating) {
|
dictating: dictating) {
|
||||||
if refusal == .alreadyInstalled { progress(.finished) }
|
|
||||||
return refusal
|
return refusal
|
||||||
}
|
}
|
||||||
isRunning = true
|
isRunning = true
|
||||||
DownloadUtils.enforceOffline = false
|
|
||||||
defer {
|
defer {
|
||||||
DownloadUtils.enforceOffline = true
|
|
||||||
isRunning = false
|
isRunning = false
|
||||||
|
downloadingFile = nil
|
||||||
}
|
}
|
||||||
|
let directory = speechModelCacheDirectory(for: .multilingualV3)
|
||||||
do {
|
do {
|
||||||
_ = try await AsrModels.download(version: .v3) { snapshot in
|
let verified = await Task.detached(priority: .userInitiated) {
|
||||||
Task { @MainActor in
|
(try? ModelIntegrity.verifyParakeetV3Model(at: directory)) != nil
|
||||||
switch snapshot.phase {
|
}.value
|
||||||
case .compiling: progress(.compiling)
|
try Task.checkCancellation()
|
||||||
default: progress(.downloading(snapshot.fractionCompleted))
|
if verified {
|
||||||
|
progress(.finished)
|
||||||
|
return .alreadyInstalled
|
||||||
|
}
|
||||||
|
|
||||||
|
let manager = FileManager.default
|
||||||
|
let staging = directory.deletingLastPathComponent()
|
||||||
|
.appendingPathComponent(".iriz-model-download-" + UUID().uuidString, isDirectory: true)
|
||||||
|
try manager.createDirectory(at: staging, withIntermediateDirectories: true,
|
||||||
|
attributes: [.posixPermissions: 0o700])
|
||||||
|
defer { try? manager.removeItem(at: staging) }
|
||||||
|
let files = ModelIntegrity.parakeetV3DownloadFiles
|
||||||
|
var receivedBytes: Int64 = 0
|
||||||
|
for file in files {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
let completedBytes = receivedBytes
|
||||||
|
let token = UUID()
|
||||||
|
downloadingFile = token
|
||||||
|
progress(.downloading(Double(completedBytes) / Double(speechModelDownloadBytes)))
|
||||||
|
let delegate = SpeechModelDownloadProgress { [weak self] currentBytes in
|
||||||
|
Task { @MainActor in
|
||||||
|
guard self?.downloadingFile == token else { return }
|
||||||
|
progress(.downloading(min(1, Double(completedBytes + currentBytes) / Double(speechModelDownloadBytes))))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let (temporary, response) = try await URLSession.shared.download(
|
||||||
|
from: speechModelDownloadURL(for: file), delegate: delegate)
|
||||||
|
downloadingFile = nil
|
||||||
|
defer { try? manager.removeItem(at: temporary) }
|
||||||
|
try Task.checkCancellation()
|
||||||
|
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
|
||||||
|
throw URLError(.badServerResponse)
|
||||||
|
}
|
||||||
|
let target = staging.appendingPathComponent(file.relativePath)
|
||||||
|
try manager.createDirectory(at: target.deletingLastPathComponent(),
|
||||||
|
withIntermediateDirectories: true,
|
||||||
|
attributes: [.posixPermissions: 0o700])
|
||||||
|
try manager.moveItem(at: temporary, to: target)
|
||||||
|
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: target.path)
|
||||||
|
receivedBytes += Int64(try target.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0)
|
||||||
}
|
}
|
||||||
|
progress(.compiling)
|
||||||
|
try await Task.detached(priority: .userInitiated) {
|
||||||
|
try ModelIntegrity.verifyParakeetV3Model(at: staging)
|
||||||
|
}.value
|
||||||
|
try Task.checkCancellation()
|
||||||
|
try publishSpeechModelCache(from: staging, to: directory)
|
||||||
progress(.finished)
|
progress(.finished)
|
||||||
return nil
|
return nil
|
||||||
} catch {
|
} catch {
|
||||||
progress(.failed(error.localizedDescription))
|
progress(.failed(speechModelInstallFailureMessage(for: error)))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private final class SpeechModelDownloadProgress: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
|
||||||
|
private let received: @Sendable (Int64) -> Void
|
||||||
|
|
||||||
|
init(received: @escaping @Sendable (Int64) -> Void) { self.received = received }
|
||||||
|
|
||||||
|
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
|
||||||
|
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
|
||||||
|
totalBytesExpectedToWrite: Int64) {
|
||||||
|
received(totalBytesWritten)
|
||||||
|
}
|
||||||
|
|
||||||
|
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
|
||||||
|
didFinishDownloadingTo location: URL) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Источник зафиксирован тем же commit, что и SHA-256 в загрузчике; ни main,
|
||||||
|
/// ни переменные окружения с подменённым реестром сюда не попадают.
|
||||||
|
func speechModelDownloadURL(for file: ModelFileDigest) throws -> URL {
|
||||||
|
guard ModelIntegrity.parakeetV3DownloadFiles.contains(file),
|
||||||
|
let url = URL(string: "https://huggingface.co/\(ModelIntegrity.parakeetV3Repository)/resolve/\(ModelIntegrity.parakeetV3RepositoryCommit)/\(file.relativePath)"),
|
||||||
|
url.scheme == "https", url.host == "huggingface.co" else {
|
||||||
|
throw URLError(.badURL)
|
||||||
|
}
|
||||||
|
return url
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Замена только после проверки новой копии. Предыдущая остаётся рядом;
|
||||||
|
/// если публикация не удалась, возвращаем её на прежнее место.
|
||||||
|
func publishSpeechModelCache(from staging: URL, to directory: URL) throws {
|
||||||
|
let manager = FileManager.default
|
||||||
|
var backup: URL?
|
||||||
|
if manager.fileExists(atPath: directory.path) {
|
||||||
|
let saved = directory.deletingLastPathComponent()
|
||||||
|
.appendingPathComponent(".iriz-model-backup-" + UUID().uuidString, isDirectory: true)
|
||||||
|
try manager.moveItem(at: directory, to: saved)
|
||||||
|
backup = saved
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
try manager.moveItem(at: staging, to: directory)
|
||||||
|
} catch {
|
||||||
|
if let backup { try manager.moveItem(at: backup, to: directory) }
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -163,13 +163,20 @@ func speechModelCacheDirectory(for profile: SpeechModelProfile) -> URL {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public func speechModelCacheExists(for profile: SpeechModelProfile) -> Bool {
|
public func speechModelCacheExists(for profile: SpeechModelProfile) -> Bool {
|
||||||
|
speechModelCacheIsComplete(for: profile, at: speechModelCacheDirectory(for: profile))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Быстрый probe для интерфейса: состав файлов, не SHA-256 сотен мегабайт.
|
||||||
|
/// Полная проверка по закреплённому манифесту остаётся перед загрузкой модели.
|
||||||
|
func speechModelCacheIsComplete(for profile: SpeechModelProfile, at directory: URL) -> Bool {
|
||||||
switch profile {
|
switch profile {
|
||||||
case .multilingualV3:
|
case .multilingualV3:
|
||||||
return FileManager.default.fileExists(atPath: speechModelCacheDirectory(for: profile).path)
|
return ModelIntegrity.parakeetV3CacheIsComplete(at: directory)
|
||||||
case .whisperLargeV3, .whisperTurbo:
|
case .whisperLargeV3, .whisperTurbo:
|
||||||
// У whisper модель - ОДИН файл, и каталог без него бесполезен: проверяем файл.
|
|
||||||
guard let file = profile.whisperModelFile else { return false }
|
guard let file = profile.whisperModelFile else { return false }
|
||||||
return FileManager.default.fileExists(atPath: whisperModelURL(file).path)
|
let values = try? directory.appendingPathComponent(file)
|
||||||
|
.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
|
||||||
|
return values?.isRegularFile == true && (values?.fileSize ?? 0) > 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,6 +248,25 @@ public enum ModelIntegrity {
|
|||||||
// END GENERATED PARAKEET_V3_MODEL_MANIFEST
|
// END GENERATED PARAKEET_V3_MODEL_MANIFEST
|
||||||
]
|
]
|
||||||
|
|
||||||
|
static var parakeetV3DownloadFiles: [ModelFileDigest] { parakeetV3Files }
|
||||||
|
|
||||||
|
static func parakeetV3CacheIsComplete(at directory: URL) -> Bool {
|
||||||
|
do {
|
||||||
|
let directories = Set(parakeetV3Files.flatMap { parentDirectories(of: $0.relativePath) })
|
||||||
|
for name in directories {
|
||||||
|
try requireDirectory(directory.appendingPathComponent(name), relativePath: name)
|
||||||
|
}
|
||||||
|
for file in parakeetV3Files {
|
||||||
|
let url = directory.appendingPathComponent(file.relativePath)
|
||||||
|
try requireRegularFile(url, relativePath: file.relativePath)
|
||||||
|
guard (try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) > 0 else { return false }
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static func verifyParakeetV3Model(at directory: URL) throws {
|
public static func verifyParakeetV3Model(at directory: URL) throws {
|
||||||
try verifyFiles(root: directory,
|
try verifyFiles(root: directory,
|
||||||
expectedFiles: parakeetV3Files,
|
expectedFiles: parakeetV3Files,
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ public func irizDropSizeText(_ bytes: Int64) -> String {
|
|||||||
/// Годится ли файл. Чистая функция: решение о приёме проверяется тестом без
|
/// Годится ли файл. Чистая функция: решение о приёме проверяется тестом без
|
||||||
/// окна и без диска.
|
/// окна и без диска.
|
||||||
public func irizDropAccepts(_ url: URL, extensions: [String]) -> Bool {
|
public func irizDropAccepts(_ url: URL, extensions: [String]) -> Bool {
|
||||||
extensions.contains(url.pathExtension.lowercased())
|
url.isFileURL && extensions.contains(url.pathExtension.lowercased())
|
||||||
}
|
}
|
||||||
|
|
||||||
public struct IrizDropZone: View {
|
public struct IrizDropZone: View {
|
||||||
@@ -49,6 +49,7 @@ public struct IrizDropZone: View {
|
|||||||
|
|
||||||
@State private var dragging = false
|
@State private var dragging = false
|
||||||
@State private var refused: String?
|
@State private var refused: String?
|
||||||
|
@Environment(\.isEnabled) private var isEnabled
|
||||||
|
|
||||||
public init(title: String,
|
public init(title: String,
|
||||||
subtitle: String,
|
subtitle: String,
|
||||||
@@ -78,7 +79,7 @@ public struct IrizDropZone: View {
|
|||||||
.foregroundStyle(IRIZ_SUBTLE)
|
.foregroundStyle(IRIZ_SUBTLE)
|
||||||
.multilineTextAlignment(.center)
|
.multilineTextAlignment(.center)
|
||||||
|
|
||||||
Button("Выбрать файлы") { choose() }
|
Button(L("files.choose", "Выбрать файлы")) { choose() }
|
||||||
.modifier(IrizDropZoneButton())
|
.modifier(IrizDropZoneButton())
|
||||||
.padding(.top, 2)
|
.padding(.top, 2)
|
||||||
}
|
}
|
||||||
@@ -96,6 +97,7 @@ public struct IrizDropZone: View {
|
|||||||
// картинка, и человек не понимает, отпускать тут или нет.
|
// картинка, и человек не понимает, отпускать тут или нет.
|
||||||
.animation(irizAnimation(.irizQuick), value: dragging)
|
.animation(irizAnimation(.irizQuick), value: dragging)
|
||||||
.onDrop(of: [.fileURL], isTargeted: $dragging) { providers in
|
.onDrop(of: [.fileURL], isTargeted: $dragging) { providers in
|
||||||
|
guard isEnabled, !providers.isEmpty else { return false }
|
||||||
accept(providers)
|
accept(providers)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -111,6 +113,7 @@ public struct IrizDropZone: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func choose() {
|
private func choose() {
|
||||||
|
guard isEnabled else { return }
|
||||||
let panel = NSOpenPanel()
|
let panel = NSOpenPanel()
|
||||||
panel.allowsMultipleSelection = true
|
panel.allowsMultipleSelection = true
|
||||||
panel.canChooseDirectories = false
|
panel.canChooseDirectories = false
|
||||||
@@ -120,20 +123,33 @@ public struct IrizDropZone: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func accept(_ providers: [NSItemProvider]) {
|
private func accept(_ providers: [NSItemProvider]) {
|
||||||
for provider in providers {
|
Task { @MainActor in
|
||||||
_ = provider.loadObject(ofClass: URL.self) { url, _ in
|
var urls: [URL] = []
|
||||||
guard let url else { return }
|
for provider in providers {
|
||||||
DispatchQueue.main.async { accept([url]) }
|
let url: URL? = await withCheckedContinuation { continuation in
|
||||||
|
_ = provider.loadObject(ofClass: URL.self) { url, _ in
|
||||||
|
continuation.resume(returning: url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let url { urls.append(url) }
|
||||||
}
|
}
|
||||||
|
accept(urls, unreadableCount: providers.count - urls.count)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func accept(_ urls: [URL]) {
|
private func accept(_ urls: [URL], unreadableCount: Int = 0) {
|
||||||
let fitting = urls.filter { irizDropAccepts($0, extensions: extensions) }
|
guard isEnabled else { return }
|
||||||
let refusedCount = urls.count - fitting.count
|
let fitting = urls.filter {
|
||||||
|
irizDropAccepts($0, extensions: extensions)
|
||||||
|
&& (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true
|
||||||
|
&& FileManager.default.isReadableFile(atPath: $0.path)
|
||||||
|
}
|
||||||
|
let refusedCount = urls.count - fitting.count + unreadableCount
|
||||||
// Отказ называется вслух и с числом. Молча проглоченный файл выглядит
|
// Отказ называется вслух и с числом. Молча проглоченный файл выглядит
|
||||||
// как поломка переноса, и человек пробует снова тем же способом.
|
// как поломка переноса, и человек пробует снова тем же способом.
|
||||||
refused = refusedCount == 0 ? nil : "Не приняты файлы: \(refusedCount). Годятся только \(extensions.joined(separator: ", "))."
|
refused = refusedCount == 0 ? nil
|
||||||
|
: Lf("files.refused", "Не приняты файлы: %d. Выбери доступные для чтения записи: %@.",
|
||||||
|
refusedCount, extensions.joined(separator: ", "))
|
||||||
guard !fitting.isEmpty else { return }
|
guard !fitting.isEmpty else { return }
|
||||||
onAdd(fitting)
|
onAdd(fitting)
|
||||||
}
|
}
|
||||||
@@ -183,6 +199,8 @@ public struct IrizDropRow: View {
|
|||||||
Button(action: onRemove) {
|
Button(action: onRemove) {
|
||||||
IrizGlyphView(.files, size: 12).opacity(0)
|
IrizGlyphView(.files, size: 12).opacity(0)
|
||||||
.overlay(Text("✕").font(.system(size: 12)))
|
.overlay(Text("✕").font(.system(size: 12)))
|
||||||
|
.frame(minWidth: 24, minHeight: 24)
|
||||||
|
.contentShape(Rectangle())
|
||||||
}
|
}
|
||||||
.buttonStyle(.plain)
|
.buttonStyle(.plain)
|
||||||
.foregroundStyle(IRIZ_SUBTLE)
|
.foregroundStyle(IRIZ_SUBTLE)
|
||||||
|
|||||||
@@ -13,6 +13,17 @@ private let HOTKEY_BUTTON_WIDTH: CGFloat = 150
|
|||||||
/// в строке подписей, иначе шапка съезжает относительно полей.
|
/// в строке подписей, иначе шапка съезжает относительно полей.
|
||||||
private let CORRECTION_TRASH_WIDTH: CGFloat = 22
|
private let CORRECTION_TRASH_WIDTH: CGFloat = 22
|
||||||
|
|
||||||
|
/// Общий выбор страницы у окна и его содержимого. Переход не пересоздаёт
|
||||||
|
/// форму: несохранённые сочетания и очередь файлов остаются на месте.
|
||||||
|
@MainActor
|
||||||
|
public final class SettingsNavigation: ObservableObject {
|
||||||
|
@Published public var page: SettingsPage
|
||||||
|
|
||||||
|
public init(page: SettingsPage = .keys) {
|
||||||
|
self.page = page
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
public struct IrizSettingsView: View {
|
public struct IrizSettingsView: View {
|
||||||
@StateObject private var model: SettingsModel
|
@StateObject private var model: SettingsModel
|
||||||
@@ -22,30 +33,49 @@ public struct IrizSettingsView: View {
|
|||||||
@State private var transferMessage: String?
|
@State private var transferMessage: String?
|
||||||
@State private var transferFailed = false
|
@State private var transferFailed = false
|
||||||
@State private var appProfileMessage: String?
|
@State private var appProfileMessage: String?
|
||||||
@State private var page: SettingsPage
|
@StateObject private var navigation: SettingsNavigation
|
||||||
|
private var page: SettingsPage { navigation.page }
|
||||||
@State private var languageChoice: IrizLanguage = irizLanguageChoice()
|
@State private var languageChoice: IrizLanguage = irizLanguageChoice()
|
||||||
@State private var appearanceChoice: IrizAppearanceChoice = irizAppearanceChoice()
|
@State private var appearanceChoice: IrizAppearanceChoice = irizAppearanceChoice()
|
||||||
@State private var fileQueue: [IrizDropItem] = []
|
@StateObject private var files = SettingsFileTranscription()
|
||||||
|
@State private var fileLanguage: DictationLanguage = .auto
|
||||||
@State private var meetingQueue: [IrizDropItem] = []
|
@State private var meetingQueue: [IrizDropItem] = []
|
||||||
|
@State private var meetingBusy = false
|
||||||
|
@State private var meetingStopping = false
|
||||||
|
@State private var meetingResults: [MeetingArtifacts] = []
|
||||||
@State private var meetingProgress: String?
|
@State private var meetingProgress: String?
|
||||||
@State private var meetingReport: String?
|
@State private var meetingReport: String?
|
||||||
@State private var meetingFailed = false
|
@State private var meetingFailed = false
|
||||||
@State private var diskEntries: [DiskUsageEntry] = []
|
@State private var diskEntries: [DiskUsageEntry] = []
|
||||||
@State private var diskCounting = false
|
@State private var diskCounting = false
|
||||||
@State private var historyEntries: [DictationHistoryEntry] = []
|
@StateObject private var historyModel: DictationHistoryModel
|
||||||
@State private var historyQuery = ""
|
private let isPreview: Bool
|
||||||
|
private let openSpeechModelSetup: (() -> Void)?
|
||||||
@Namespace private var sidebarGlass
|
@Namespace private var sidebarGlass
|
||||||
/// Система гасит свою анимацию, но не наш `withAnimation` - морф стекла
|
/// Система гасит свою анимацию, но не наш `withAnimation` - морф стекла
|
||||||
/// приходится гейтить руками (правило M07 линтера).
|
/// приходится гейтить руками (правило M07 линтера).
|
||||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||||
|
|
||||||
public init(preview: Bool = false, page: SettingsPage = .keys) {
|
public init(preview: Bool = false, page: SettingsPage = .keys,
|
||||||
|
navigation: SettingsNavigation? = nil,
|
||||||
|
openSpeechModelSetup: (() -> Void)? = nil) {
|
||||||
_model = StateObject(wrappedValue: SettingsModel(preview: preview))
|
_model = StateObject(wrappedValue: SettingsModel(preview: preview))
|
||||||
_page = State(initialValue: page)
|
_historyModel = StateObject(wrappedValue: DictationHistoryModel(preview: preview))
|
||||||
|
isPreview = preview
|
||||||
|
self.openSpeechModelSetup = openSpeechModelSetup
|
||||||
|
_navigation = StateObject(wrappedValue: navigation ?? SettingsNavigation(page: page))
|
||||||
}
|
}
|
||||||
|
|
||||||
public var body: some View {
|
public var body: some View {
|
||||||
glassScene
|
glassScene
|
||||||
|
.onAppear { model.refreshSpeechModelReadiness() }
|
||||||
|
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
|
||||||
|
model.refreshSpeechModelReadiness()
|
||||||
|
}
|
||||||
|
.onReceive(NotificationCenter.default.publisher(for: speechModelDidInstallNotification)) { notification in
|
||||||
|
guard !isPreview, let profile = notification.object as? SpeechModelProfile else { return }
|
||||||
|
model.applyInstalledSpeechModel(profile)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Общего `GlassEffectContainer` здесь НЕТ, и это измеренное решение.
|
/// Общего `GlassEffectContainer` здесь НЕТ, и это измеренное решение.
|
||||||
@@ -174,7 +204,7 @@ public struct IrizSettingsView: View {
|
|||||||
// Пресет вместо магических чисел: `.snappy` и есть «доехать с весом,
|
// Пресет вместо магических чисел: `.snappy` и есть «доехать с весом,
|
||||||
// без игры» (правило M02 линтера).
|
// без игры» (правило M02 линтера).
|
||||||
withAnimation(reduceMotion ? nil : .irizMove) {
|
withAnimation(reduceMotion ? nil : .irizMove) {
|
||||||
page = item
|
navigation.page = item
|
||||||
}
|
}
|
||||||
} label: {
|
} label: {
|
||||||
Label {
|
Label {
|
||||||
@@ -240,8 +270,7 @@ public struct IrizSettingsView: View {
|
|||||||
/// кнопка сохранения, спрятанная на одной из девяти, находится случайно.
|
/// кнопка сохранения, спрятанная на одной из девяти, находится случайно.
|
||||||
private var footerBar: some View {
|
private var footerBar: some View {
|
||||||
HStack(spacing: 12) {
|
HStack(spacing: 12) {
|
||||||
if let message = model.validationMessage,
|
if let message = model.validationMessage {
|
||||||
!message.contains(L("settings.konflikt", "Конфликт")), !message.contains("macOS") {
|
|
||||||
Label(message, systemImage: "exclamationmark.triangle.fill")
|
Label(message, systemImage: "exclamationmark.triangle.fill")
|
||||||
.foregroundStyle(.red)
|
.foregroundStyle(.red)
|
||||||
.accessibilityLabel(Lf("settings.error.a11y", "Ошибка настроек: %@", message))
|
.accessibilityLabel(Lf("settings.error.a11y", "Ошибка настроек: %@", message))
|
||||||
@@ -455,12 +484,7 @@ public struct IrizSettingsView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Picker(L("settings.raspoznavatel", "Распознаватель"), selection: $model.speechEngine) {
|
speechRecognitionControls
|
||||||
ForEach(SpeechModelProfile.allCases, id: \.self) { profile in
|
|
||||||
Text(profile.shortName).tag(profile)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.accessibilityLabel(L("settings.kakoyDvizhokRaspoznavaniyaRechi", "Какой движок распознавания речи использовать"))
|
|
||||||
|
|
||||||
settingsNote {
|
settingsNote {
|
||||||
Text(L("settings.parakeetBystreeV11", "Parakeet быстрее в 11-15 раз, но транслитерирует английские термины внутри русской фразы: git rebase слышится как «гид репейс». Whisper large-v3 берет их латиницей (19 процентов ошибок на смешанной речи против 44), зато надиктовка в полминуты ждет расшифровки около 16 секунд. Оба считают на этом Маке, наружу не уходит ничего."))
|
Text(L("settings.parakeetBystreeV11", "Parakeet быстрее в 11-15 раз, но транслитерирует английские термины внутри русской фразы: git rebase слышится как «гид репейс». Whisper large-v3 берет их латиницей (19 процентов ошибок на смешанной речи против 44), зато надиктовка в полминуты ждет расшифровки около 16 секунд. Оба считают на этом Маке, наружу не уходит ничего."))
|
||||||
@@ -830,8 +854,49 @@ public struct IrizSettingsView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private var speechRecognitionControls: some View {
|
||||||
|
Picker(L("settings.raspoznavatel", "Распознаватель"), selection: $model.speechEngine) {
|
||||||
|
ForEach(SpeechModelProfile.allCases, id: \.self) { profile in
|
||||||
|
Text(profile.shortName).tag(profile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.disabled(files.busy || meetingBusy)
|
||||||
|
.accessibilityLabel(L("settings.kakoyDvizhokRaspoznavaniyaRechi", "Какой движок распознавания речи использовать"))
|
||||||
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
|
Label(model.speechModelInstalled
|
||||||
|
? Lf("settings.speechModelInstalled", "%@: модель установлена", model.speechEngine.shortName)
|
||||||
|
: Lf("settings.speechModelMissing", "%@: модель не установлена", model.speechEngine.shortName),
|
||||||
|
systemImage: model.speechModelInstalled ? "checkmark.circle" : "arrow.down.circle")
|
||||||
|
.foregroundStyle(.primary)
|
||||||
|
if !model.speechModelInstalled {
|
||||||
|
Text(model.canUseInstalledParakeet
|
||||||
|
? L("settings.parakeetAlreadyAvailable", "Parakeet уже установлен. Выбери его и сохрани настройки, чтобы использовать для диктовки.")
|
||||||
|
: L("settings.speechModelDownloadHelp", "Для распознавания нужна модель на этом Маке. Автоматически можно скачать только Parakeet: около 0,5 ГБ, один раз. После установки он станет выбранным распознавателем. Звук останется на устройстве."))
|
||||||
|
.font(.footnote)
|
||||||
|
.foregroundStyle(IRIZ_SUBTLE)
|
||||||
|
}
|
||||||
|
if !model.speechModelInstalled, model.canUseInstalledParakeet {
|
||||||
|
Button(L("settings.selectInstalledParakeet", "Выбрать установленный Parakeet")) {
|
||||||
|
model.speechEngine = .multilingualV3
|
||||||
|
}
|
||||||
|
.modifier(GlassButton())
|
||||||
|
.disabled(files.busy || meetingBusy)
|
||||||
|
} else {
|
||||||
|
Button(model.speechModelInstalled
|
||||||
|
? L("settings.speechModelSetup", "Настроить распознавание…")
|
||||||
|
: L("settings.downloadParakeet", "Скачать модель Parakeet…")) {
|
||||||
|
openSpeechModelSetup?()
|
||||||
|
}
|
||||||
|
.modifier(GlassButton())
|
||||||
|
.disabled(isPreview || openSpeechModelSetup == nil || files.busy || meetingBusy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private var behaviorSection: some View {
|
private var behaviorSection: some View {
|
||||||
Section {
|
Section {
|
||||||
|
speechRecognitionControls
|
||||||
LabeledContent(L("settings.zaderzhkaEnter", "Задержка Enter")) {
|
LabeledContent(L("settings.zaderzhkaEnter", "Задержка Enter")) {
|
||||||
HStack(spacing: 6) {
|
HStack(spacing: 6) {
|
||||||
// labelsHidden обязателен: в Form(.grouped) заголовок TextField
|
// labelsHidden обязателен: в Form(.grouped) заголовок TextField
|
||||||
@@ -1224,13 +1289,77 @@ public struct IrizSettingsView: View {
|
|||||||
/// Расшифровка файлов: бросил запись - получил текст рядом с ней.
|
/// Расшифровка файлов: бросил запись - получил текст рядом с ней.
|
||||||
private var filesSection: some View {
|
private var filesSection: some View {
|
||||||
Section {
|
Section {
|
||||||
|
speechRecognitionControls
|
||||||
IrizDropZone(title: L("settings.perenesiteZapisiSyuda", "Перенесите записи сюда"),
|
IrizDropZone(title: L("settings.perenesiteZapisiSyuda", "Перенесите записи сюда"),
|
||||||
subtitle: L("settings.diktofonZvonokEksportIz", "Диктофон, звонок, экспорт из встречи. Текст ляжет рядом с файлом."),
|
subtitle: L("settings.diktofonZvonokEksportIz", "Диктофон, звонок, экспорт из встречи. Текст ляжет рядом с файлом."),
|
||||||
extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in
|
extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in
|
||||||
enqueue(urls, into: $fileQueue)
|
enqueue(urls, into: $files.queue)
|
||||||
}
|
}
|
||||||
ForEach(fileQueue) { item in
|
.disabled(files.busy)
|
||||||
IrizDropRow(item: item) { fileQueue.removeAll { $0.id == item.id } }
|
Picker(L("files.language", "Язык записи"), selection: $fileLanguage) {
|
||||||
|
ForEach(DictationLanguage.allCases, id: \.self) { language in
|
||||||
|
Text(language == .auto ? L("files.languageAuto", "Определить автоматически")
|
||||||
|
: Locale.current.localizedString(forLanguageCode: language.rawValue) ?? language.rawValue)
|
||||||
|
.tag(language)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.disabled(files.busy)
|
||||||
|
ForEach(files.queue) { item in
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
IrizDropRow(item: item) { files.queue.removeAll { $0.id == item.id } }
|
||||||
|
.disabled(files.busy)
|
||||||
|
if let error = files.errors[item.id] {
|
||||||
|
Label(error, systemImage: "exclamationmark.triangle.fill")
|
||||||
|
.font(.footnote)
|
||||||
|
.foregroundStyle(.orange)
|
||||||
|
.textSelection(.enabled)
|
||||||
|
let destination = AudioFileBatch.destination(forSource: item.url, in: nil)
|
||||||
|
Button(L("files.showDestination", "Показать папку результата")) {
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([destination.deletingLastPathComponent()])
|
||||||
|
}
|
||||||
|
.modifier(GlassButton())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !files.queue.isEmpty {
|
||||||
|
Button(files.errors.isEmpty ? L("files.start", "Расшифровать записи")
|
||||||
|
: L("files.retry", "Повторить оставшиеся")) {
|
||||||
|
guard !meetingBusy, !isPreview, model.speechModelInstalled else { return }
|
||||||
|
files.start(engine: model.speechEngine, language: fileLanguage)
|
||||||
|
}
|
||||||
|
.modifier(GlassProminentButton())
|
||||||
|
.disabled(files.busy || meetingBusy || isPreview || !model.speechModelInstalled)
|
||||||
|
}
|
||||||
|
if let progress = files.progress {
|
||||||
|
if let fraction = files.fraction {
|
||||||
|
ProgressView(value: fraction) { Text(progress) }
|
||||||
|
} else {
|
||||||
|
ProgressView { Text(progress) }
|
||||||
|
.controlSize(.small)
|
||||||
|
}
|
||||||
|
Button(files.stopping ? L("files.stopping", "Останавливаю после текущей записи…")
|
||||||
|
: L("files.stopAfterCurrent", "Остановить после текущей записи")) {
|
||||||
|
files.stopAfterCurrent()
|
||||||
|
}
|
||||||
|
.modifier(GlassButton())
|
||||||
|
.disabled(files.stopping)
|
||||||
|
}
|
||||||
|
if let report = files.report {
|
||||||
|
Text(report).font(.footnote).textSelection(.enabled)
|
||||||
|
}
|
||||||
|
ForEach(files.results, id: \.source) { result in
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
Label(result.destination.lastPathComponent, systemImage: "checkmark.circle")
|
||||||
|
.textSelection(.enabled)
|
||||||
|
HStack {
|
||||||
|
Button(L("files.openText", "Открыть текст")) { openFileResult(result.destination) }
|
||||||
|
.modifier(GlassButton())
|
||||||
|
Button(L("files.showInFinder", "Показать в Finder")) {
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([result.destination])
|
||||||
|
}
|
||||||
|
.modifier(GlassButton())
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Text(L("settings.rasshifrovkaIdetNaEtom", "Расшифровка идёт на этом Маке тем же движком, что и диктовка. "
|
Text(L("settings.rasshifrovkaIdetNaEtom", "Расшифровка идёт на этом Маке тем же движком, что и диктовка. "
|
||||||
+ "Звук никуда не отправляется, а сам файл остаётся там, где лежал."))
|
+ "Звук никуда не отправляется, а сам файл остаётся там, где лежал."))
|
||||||
@@ -1254,25 +1383,39 @@ public struct IrizSettingsView: View {
|
|||||||
/// «вставить» означало бы вставить в него же. Копирование есть.
|
/// «вставить» означало бы вставить в него же. Копирование есть.
|
||||||
private var historySection: some View {
|
private var historySection: some View {
|
||||||
Section {
|
Section {
|
||||||
if historyEntries.isEmpty {
|
HStack(spacing: 8) {
|
||||||
Text(L("settings.pokaPustoNadiktovannoePoyavitsya", "Пока пусто. Надиктованное появится здесь."))
|
IrizGlyphView(.history, size: 13)
|
||||||
.foregroundStyle(IRIZ_SUBTLE)
|
.foregroundStyle(IRIZ_SUBTLE)
|
||||||
} else {
|
TextField(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"), text: $historyModel.query)
|
||||||
// Системная оправа `.roundedBorder` рисуется непрозрачной
|
.textFieldStyle(.plain)
|
||||||
// коробкой: в стеклянном окне она читается как дырка. Своя
|
.accessibilityLabel(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"))
|
||||||
// оправа - то же стекло, что у плит, только тоньше.
|
}
|
||||||
HStack(spacing: 8) {
|
.padding(.horizontal, 10)
|
||||||
IrizGlyphView(.history, size: 13)
|
.padding(.vertical, 7)
|
||||||
.foregroundStyle(IRIZ_SUBTLE)
|
.background(IrizSearchFieldPlate())
|
||||||
TextField(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"), text: $historyQuery)
|
|
||||||
.textFieldStyle(.plain)
|
|
||||||
.accessibilityLabel(L("settings.poiskPoNadiktovkam", "Поиск по надиктовкам"))
|
|
||||||
}
|
|
||||||
.padding(.horizontal, 10)
|
|
||||||
.padding(.vertical, 7)
|
|
||||||
.background(IrizSearchFieldPlate())
|
|
||||||
|
|
||||||
ForEach(filteredDictationHistory(historyEntries, query: historyQuery)) { entry in
|
if historyModel.isLoading {
|
||||||
|
ProgressView(L("history.loading", "Читаю надиктовки…"))
|
||||||
|
.controlSize(.small)
|
||||||
|
}
|
||||||
|
if let notice = historyModel.notice {
|
||||||
|
Label(notice, systemImage: historyModel.noticeIsError ? "exclamationmark.circle" : "checkmark.circle")
|
||||||
|
.foregroundStyle(historyModel.noticeIsError ? Color.red : Color.primary)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
}
|
||||||
|
if !historyModel.isLoading, historyModel.visible.isEmpty, !historyModel.noticeIsError {
|
||||||
|
Text(historyModel.entries.isEmpty
|
||||||
|
? L("settings.pokaPustoNadiktovannoePoyavitsya", "Пока пусто. Надиктованное появится здесь.")
|
||||||
|
: L("history.notFoundTitle", "Ничего не нашлось"))
|
||||||
|
.foregroundStyle(IRIZ_SUBTLE)
|
||||||
|
}
|
||||||
|
if historyModel.query.isEmpty, historyModel.entries.count >= DICTATION_HISTORY_VISIBLE_LIMIT {
|
||||||
|
Text(L("history.loadingBody", "Показываю последние сто. Остальные найдёт поиск."))
|
||||||
|
.font(.footnote)
|
||||||
|
.foregroundStyle(IRIZ_SUBTLE)
|
||||||
|
}
|
||||||
|
ForEach(historyModel.visible) { entry in
|
||||||
|
HStack(alignment: .top, spacing: 12) {
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
Text(dictationHistoryPreview(entry.displayText))
|
Text(dictationHistoryPreview(entry.displayText))
|
||||||
.lineLimit(3)
|
.lineLimit(3)
|
||||||
@@ -1286,55 +1429,53 @@ public struct IrizSettingsView: View {
|
|||||||
.foregroundStyle(IRIZ_SUBTLE)
|
.foregroundStyle(IRIZ_SUBTLE)
|
||||||
}
|
}
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
.contentShape(Rectangle())
|
Button(L("settings.kopirovat", "Копировать")) { copyHistory(entry) }
|
||||||
.contextMenu {
|
.disabled(isPreview)
|
||||||
Button(L("settings.kopirovat", "Копировать")) { copyHistory(entry) }
|
}
|
||||||
}
|
.contextMenu {
|
||||||
|
Button(L("settings.kopirovat", "Копировать")) { copyHistory(entry) }
|
||||||
|
.disabled(isPreview)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} header: {
|
} header: {
|
||||||
Text(L("settings.istoriyaNadiktovok", "История надиктовок"))
|
Text(L("settings.istoriyaNadiktovok", "История надиктовок"))
|
||||||
}
|
}
|
||||||
.onAppear { loadHistory() }
|
.onAppear { loadHistory() }
|
||||||
|
.onDisappear { historyModel.cancelLoading() }
|
||||||
}
|
}
|
||||||
|
|
||||||
private func loadHistory() {
|
private func loadHistory() {
|
||||||
// Читается с диска при каждом открытии страницы, а не держится в
|
historyModel.reload { try DictationStore.dictationsDirectory() }
|
||||||
// памяти: диктовки пишутся другим процессом окна, и кэш разъехался бы
|
|
||||||
// с диском ровно тогда, когда владелец ищет только что сказанное.
|
|
||||||
//
|
|
||||||
// В ФОНЕ и с потолком. Здесь стоял тот же дефект, что в окне истории:
|
|
||||||
// две тысячи каталогов по три файла читались синхронно, 1386 мс, и всё
|
|
||||||
// это время окно настроек не рисовалось. Владелец поймал это дважды -
|
|
||||||
// сперва в окне, потом на этой странице.
|
|
||||||
guard let root = try? DictationStore.dictationsDirectory() else { return }
|
|
||||||
Task.detached(priority: .userInitiated) {
|
|
||||||
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT)
|
|
||||||
await MainActor.run { historyEntries = found }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private func copyHistory(_ entry: DictationHistoryEntry) {
|
private func copyHistory(_ entry: DictationHistoryEntry) {
|
||||||
NSPasteboard.general.clearContents()
|
guard !isPreview else { return }
|
||||||
NSPasteboard.general.setString(entry.displayText, forType: .string)
|
let copied = DictationHistoryClipboard.copy(entry.displayText)
|
||||||
statusMessage = L("settings.skopirovanoVBuferObmena", "Скопировано в буфер обмена.")
|
historyModel.noticeIsError = !copied
|
||||||
|
historyModel.notice = copied
|
||||||
|
? L("history.copiedTimed", "Скопировано. Буфер очистится через 2 минуты.")
|
||||||
|
: L("history.copyFailed", "Не удалось скопировать. Попробуй ещё раз.")
|
||||||
}
|
}
|
||||||
|
|
||||||
private var meetingsSection: some View {
|
private var meetingsSection: some View {
|
||||||
Section {
|
Section {
|
||||||
|
speechRecognitionControls
|
||||||
IrizDropZone(title: L("settings.perenesiteZapisVstrechi", "Перенесите запись встречи"),
|
IrizDropZone(title: L("settings.perenesiteZapisVstrechi", "Перенесите запись встречи"),
|
||||||
subtitle: L("settings.zapisZasedaniyaIliSozvona", "Запись заседания или созвона. Рядом ляжет протокол."),
|
subtitle: L("meetings.storage", "Запись на русском языке. Звук и протокол сохранятся в архиве iriz; готовые файлы можно открыть отсюда."),
|
||||||
extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in
|
extensions: AudioFileBatch.supportedExtensions.sorted()) { urls in
|
||||||
enqueue(urls, into: $meetingQueue)
|
enqueue(urls, into: $meetingQueue)
|
||||||
}
|
}
|
||||||
|
.disabled(meetingBusy)
|
||||||
ForEach(meetingQueue) { item in
|
ForEach(meetingQueue) { item in
|
||||||
IrizDropRow(item: item) { meetingQueue.removeAll { $0.id == item.id } }
|
IrizDropRow(item: item) { meetingQueue.removeAll { $0.id == item.id } }
|
||||||
|
.disabled(meetingBusy)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !meetingQueue.isEmpty {
|
if !meetingQueue.isEmpty {
|
||||||
Button(L("settings.razobratZapisi", "Разобрать записи")) { runMeetings() }
|
Button(meetingFailed ? L("files.retry", "Повторить оставшиеся")
|
||||||
|
: L("settings.razobratZapisi", "Разобрать записи")) { runMeetings() }
|
||||||
.modifier(GlassProminentButton())
|
.modifier(GlassProminentButton())
|
||||||
.disabled(meetingProgress != nil)
|
.disabled(meetingBusy || files.busy || isPreview || !model.speechModelInstalled)
|
||||||
.accessibilityLabel(L("settings.razobratZapisiVstrech", "Разобрать записи встреч"))
|
.accessibilityLabel(L("settings.razobratZapisiVstrech", "Разобрать записи встреч"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1342,9 +1483,14 @@ public struct IrizSettingsView: View {
|
|||||||
// Ход показывается словами, а не полосой: у часовой записи
|
// Ход показывается словами, а не полосой: у часовой записи
|
||||||
// полоса врёт про остаток, а название шага честно говорит,
|
// полоса врёт про остаток, а название шага честно говорит,
|
||||||
// что именно сейчас происходит.
|
// что именно сейчас происходит.
|
||||||
Label(meetingProgress, systemImage: "hourglass")
|
ProgressView { Text(meetingProgress) }
|
||||||
.font(.footnote)
|
.controlSize(.small)
|
||||||
.foregroundStyle(IRIZ_SUBTLE)
|
Button(meetingStopping ? L("files.stopping", "Останавливаю после текущей записи…")
|
||||||
|
: L("files.stopAfterCurrent", "Остановить после текущей записи")) {
|
||||||
|
meetingStopping = true
|
||||||
|
}
|
||||||
|
.modifier(GlassButton())
|
||||||
|
.disabled(meetingStopping)
|
||||||
}
|
}
|
||||||
|
|
||||||
if let meetingReport {
|
if let meetingReport {
|
||||||
@@ -1355,6 +1501,21 @@ public struct IrizSettingsView: View {
|
|||||||
.textSelection(.enabled)
|
.textSelection(.enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ForEach(meetingResults, id: \.directory) { artifacts in
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
Label(artifacts.directory.lastPathComponent, systemImage: "checkmark.circle")
|
||||||
|
.textSelection(.enabled)
|
||||||
|
HStack {
|
||||||
|
Button(L("meetings.openProtocol", "Открыть протокол")) { openFileResult(artifacts.transcript) }
|
||||||
|
.modifier(GlassButton())
|
||||||
|
Button(L("meetings.showFolder", "Показать папку встречи")) {
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([artifacts.directory])
|
||||||
|
}
|
||||||
|
.modifier(GlassButton())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Здесь продукт нарушает собственное правило, и молчать об этом
|
// Здесь продукт нарушает собственное правило, и молчать об этом
|
||||||
// нельзя: в диктовке звук не сохраняется никогда, а у встречи он
|
// нельзя: в диктовке звук не сохраняется никогда, а у встречи он
|
||||||
// остаётся вместе с расшифровкой. Иначе протокол нечем сверить.
|
// остаётся вместе с расшифровкой. Иначе протокол нечем сверить.
|
||||||
@@ -1377,47 +1538,66 @@ public struct IrizSettingsView: View {
|
|||||||
/// Отказ на одной записи не отменяет остальные: владелец принёс папку, и
|
/// Отказ на одной записи не отменяет остальные: владелец принёс папку, и
|
||||||
/// одна битая запись не должна стоить ему разбора всех.
|
/// одна битая запись не должна стоить ему разбора всех.
|
||||||
private func runMeetings() {
|
private func runMeetings() {
|
||||||
|
guard !meetingBusy, !files.busy, !meetingQueue.isEmpty, !isPreview, model.speechModelInstalled else { return }
|
||||||
|
meetingBusy = true
|
||||||
|
meetingStopping = false
|
||||||
let items = meetingQueue
|
let items = meetingQueue
|
||||||
|
let engine = model.speechEngine
|
||||||
meetingReport = nil
|
meetingReport = nil
|
||||||
meetingFailed = false
|
meetingFailed = false
|
||||||
Task { @MainActor in
|
Task { @MainActor in
|
||||||
let pipeline = MeetingPipeline()
|
let pipeline = MeetingPipeline(transcriber: AudioFileTranscriber(engine: engine))
|
||||||
var done = 0
|
var done = 0
|
||||||
var failures: [String] = []
|
var failures: [String] = []
|
||||||
for item in items {
|
for item in items {
|
||||||
|
guard !meetingStopping else { break }
|
||||||
let name = item.url.deletingPathExtension().lastPathComponent
|
let name = item.url.deletingPathExtension().lastPathComponent
|
||||||
meetingProgress = "\(name): читаю"
|
meetingProgress = "\(name): \(L("files.reading", "читаю запись"))"
|
||||||
do {
|
do {
|
||||||
let result = try await pipeline.run(
|
let result = try await pipeline.run(
|
||||||
audio: item.url,
|
audio: item.url,
|
||||||
title: name,
|
title: name,
|
||||||
progress: { step in
|
progress: { step in
|
||||||
Task { @MainActor in meetingProgress = "\(name): \(step.lowercased())" }
|
Task { @MainActor in
|
||||||
|
guard meetingBusy else { return }
|
||||||
|
meetingProgress = "\(name): \(step.lowercased())"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
done += 1
|
done += 1
|
||||||
meetingQueue.removeAll { $0.id == item.id }
|
meetingQueue.removeAll { $0.id == item.id }
|
||||||
|
meetingResults.append(result.artifacts)
|
||||||
if !result.speakersResolved {
|
if !result.speakersResolved {
|
||||||
// Владелец должен отличить монолог от неудавшегося
|
// Владелец должен отличить монолог от неудавшегося
|
||||||
// разделения: в первом случае имена расставлять не
|
// разделения: в первом случае имена расставлять не
|
||||||
// нужно, во втором нужно.
|
// нужно, во втором нужно.
|
||||||
failures.append("\(name): говорящие не разобраны, протокол одной репликой")
|
failures.append(Lf("meetings.speakersUnresolved", "%@: говорящие не разделены. Текст сохранён одной репликой; проверьте протокол.", name))
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
let reason = (error as? MeetingPipelineFailure)?.rawValue ?? "\(error)"
|
let reason = (error as? MeetingPipelineFailure)?.rawValue ?? error.localizedDescription
|
||||||
failures.append("\(name): \(reason)")
|
failures.append("\(name): \(reason)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
meetingProgress = nil
|
meetingProgress = nil
|
||||||
|
meetingBusy = false
|
||||||
meetingFailed = !failures.isEmpty
|
meetingFailed = !failures.isEmpty
|
||||||
let base = done > 0 ? "Разобрано записей: \(done)." : L("settings.razobratNeUdalos", "Разобрать не удалось.")
|
let base = Lf("files.finished", "Готово: %d из %d.", done, items.count)
|
||||||
meetingReport = failures.isEmpty ? base : base + " " + failures.joined(separator: "; ")
|
+ (meetingStopping ? " " + L("files.stopped", "Очередь остановлена. Оставшиеся файлы можно запустить снова.") : "")
|
||||||
|
meetingReport = failures.isEmpty ? base : base + "\n" + failures.joined(separator: "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func openFileResult(_ url: URL) {
|
||||||
|
if !NSWorkspace.shared.open(url) {
|
||||||
|
statusMessage = Lf("files.openFailed", "Не удалось открыть %@. Проверь файл через Finder.", url.lastPathComponent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Положить файлы в очередь, не задваивая уже принесённые.
|
/// Положить файлы в очередь, не задваивая уже принесённые.
|
||||||
private func enqueue(_ urls: [URL], into queue: Binding<[IrizDropItem]>) {
|
private func enqueue(_ urls: [URL], into queue: Binding<[IrizDropItem]>) {
|
||||||
for url in urls where !queue.wrappedValue.contains(where: { $0.url == url }) {
|
for source in urls {
|
||||||
|
let url = source.standardizedFileURL
|
||||||
|
guard !queue.wrappedValue.contains(where: { $0.url.standardizedFileURL == url }) else { continue }
|
||||||
let bytes = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int64) ?? 0
|
let bytes = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int64) ?? 0
|
||||||
queue.wrappedValue.append(IrizDropItem(url: url, bytes: bytes ?? 0))
|
queue.wrappedValue.append(IrizDropItem(url: url, bytes: bytes ?? 0))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import Combine
|
||||||
|
import Darwin
|
||||||
|
import Foundation
|
||||||
|
import IrizCore
|
||||||
|
import IrizDictate
|
||||||
|
|
||||||
|
/// Очередь переживает смену страницы; повтор запускает только оставшиеся файлы.
|
||||||
|
@MainActor
|
||||||
|
final class SettingsFileTranscription: ObservableObject {
|
||||||
|
typealias Progress = @Sendable (String, Double?) async -> Void
|
||||||
|
typealias ProcessFile = @Sendable (AudioTranscriptionJob, AudioFileTranscriber,
|
||||||
|
DictationLanguage, @escaping Progress) async throws -> Void
|
||||||
|
|
||||||
|
@Published var queue: [IrizDropItem] = []
|
||||||
|
@Published private(set) var busy = false
|
||||||
|
@Published private(set) var stopping = false
|
||||||
|
@Published private(set) var progress: String?
|
||||||
|
@Published private(set) var fraction: Double?
|
||||||
|
@Published private(set) var report: String?
|
||||||
|
@Published private(set) var errors: [UUID: String] = [:]
|
||||||
|
@Published private(set) var results: [AudioTranscriptionJob] = []
|
||||||
|
private let processFile: ProcessFile
|
||||||
|
|
||||||
|
init(processFile: @escaping ProcessFile = SettingsFileTranscription.process) {
|
||||||
|
self.processFile = processFile
|
||||||
|
}
|
||||||
|
|
||||||
|
@discardableResult
|
||||||
|
func start(engine: SpeechModelProfile, language: DictationLanguage) -> Task<Void, Never>? {
|
||||||
|
guard !busy, !queue.isEmpty else { return nil }
|
||||||
|
// До Task: второе нажатие в том же проходе run loop уже не запустит модель.
|
||||||
|
busy = true
|
||||||
|
stopping = false
|
||||||
|
report = nil
|
||||||
|
errors = [:]
|
||||||
|
let items = queue
|
||||||
|
let transcriber = AudioFileTranscriber(engine: engine)
|
||||||
|
return Task {
|
||||||
|
var done = 0
|
||||||
|
defer {
|
||||||
|
busy = false
|
||||||
|
progress = nil
|
||||||
|
fraction = nil
|
||||||
|
report = Lf("files.finished", "Готово: %d из %d.", done, items.count)
|
||||||
|
+ (stopping ? " " + L("files.stopped", "Очередь остановлена. Оставшиеся файлы можно запустить снова.") : "")
|
||||||
|
}
|
||||||
|
for (index, item) in items.enumerated() {
|
||||||
|
guard !stopping else { break }
|
||||||
|
let name = item.url.lastPathComponent
|
||||||
|
progress = "[\(index + 1)/\(items.count)] \(name)"
|
||||||
|
fraction = nil
|
||||||
|
do {
|
||||||
|
let jobs = try await Task.detached(priority: .userInitiated) {
|
||||||
|
try AudioFileBatch.plan(inputPath: item.url.path, force: false)
|
||||||
|
}.value
|
||||||
|
guard let job = jobs.first, jobs.count == 1 else {
|
||||||
|
throw AudioBatchPlanError.pathNotReadable(item.url.path)
|
||||||
|
}
|
||||||
|
try await processFile(job, transcriber, language) { step, value in
|
||||||
|
await MainActor.run {
|
||||||
|
self.progress = "[\(index + 1)/\(items.count)] \(name): \(step)"
|
||||||
|
self.fraction = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
results.removeAll { $0.source == job.source }
|
||||||
|
results.append(job)
|
||||||
|
queue.removeAll { $0.id == item.id }
|
||||||
|
done += 1
|
||||||
|
} catch {
|
||||||
|
errors[item.id] = Self.message(for: error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// У распознавателя нет безопасного мгновенного прерывания. Текущий результат
|
||||||
|
/// сохраняется, следующий файл не начинается; это прямо написано на кнопке.
|
||||||
|
func stopAfterCurrent() { if busy { stopping = true } }
|
||||||
|
|
||||||
|
nonisolated private static func process(_ job: AudioTranscriptionJob,
|
||||||
|
transcriber: AudioFileTranscriber,
|
||||||
|
language: DictationLanguage,
|
||||||
|
progress: @escaping Progress) async throws {
|
||||||
|
await progress(L("files.preparing", "загружаю модель"), nil)
|
||||||
|
_ = try await transcriber.prepare()
|
||||||
|
await progress(L("files.reading", "читаю запись"), nil)
|
||||||
|
let audio = try await AudioFileDecoder.decode(job.source)
|
||||||
|
await progress(L("files.transcribing", "расшифровываю"), nil)
|
||||||
|
var reporter: Task<Void, Never>?
|
||||||
|
if AudioFileTranscriber.reportsProgress(forSamples: audio.samples.count),
|
||||||
|
let stream = await transcriber.progressStream() {
|
||||||
|
reporter = Task {
|
||||||
|
do {
|
||||||
|
for try await value in stream {
|
||||||
|
guard !Task.isCancelled else { break }
|
||||||
|
await progress(L("files.transcribing", "расшифровываю"), min(1, max(0, value)))
|
||||||
|
}
|
||||||
|
} catch { /* Текстовая стадия остаётся видимой, если поток прогресса закрыт. */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
defer { reporter?.cancel() }
|
||||||
|
let transcript = try await transcriber.transcribe(audio, language: language)
|
||||||
|
reporter?.cancel()
|
||||||
|
await reporter?.value
|
||||||
|
await progress(L("files.saving", "сохраняю текст"), nil)
|
||||||
|
try saveTranscript(transcript.text, to: job.destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Готовый текст появляется целиком, с правами 0600. link отказывает при
|
||||||
|
/// существующем имени даже тогда, когда файл появился уже после plan().
|
||||||
|
nonisolated static func saveTranscript(_ text: String, to destination: URL) throws {
|
||||||
|
let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !text.isEmpty else {
|
||||||
|
throw NSError(domain: "IrizFileTranscription", code: 1,
|
||||||
|
userInfo: [NSLocalizedDescriptionKey: L("files.noSpeech", "Речь не распознана. Текстовый файл не создан.")])
|
||||||
|
}
|
||||||
|
let temporary = destination.deletingLastPathComponent()
|
||||||
|
.appendingPathComponent(".iriz-transcript-\(UUID().uuidString)")
|
||||||
|
let descriptor = Darwin.open(temporary.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
|
||||||
|
PRIVATE_LOG_FILE_MODE)
|
||||||
|
guard descriptor >= 0 else { throw IrizCore.currentPOSIXError() }
|
||||||
|
defer {
|
||||||
|
_ = Darwin.close(descriptor)
|
||||||
|
_ = Darwin.unlink(temporary.path)
|
||||||
|
}
|
||||||
|
try IrizCore.writeAllData(Data((text + "\n").utf8), to: descriptor)
|
||||||
|
guard Darwin.link(temporary.path, destination.path) == 0 else {
|
||||||
|
if errno == EEXIST { throw AudioBatchPlanError.destinationExists(destination.path) }
|
||||||
|
throw IrizCore.currentPOSIXError()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated static func message(for error: Error) -> String {
|
||||||
|
if case AudioBatchPlanError.destinationExists(let path) = error {
|
||||||
|
return Lf("files.destinationExists", "Текст уже есть: %@. Открой его или переименуй исходную запись перед повтором.", path)
|
||||||
|
}
|
||||||
|
return (error as? AudioBatchPlanError)?.message
|
||||||
|
?? (error as? AudioDecodingError)?.message
|
||||||
|
?? error.localizedDescription
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -194,7 +194,10 @@ final class SettingsModel: ObservableObject {
|
|||||||
/// Какой распознаватель стоит. Выбор с ценой на обеих сторонах, поэтому он
|
/// Какой распознаватель стоит. Выбор с ценой на обеих сторонах, поэтому он
|
||||||
/// у владельца, а не зашит: Whisper берет английские термины внутри русской
|
/// у владельца, а не зашит: Whisper берет английские термины внутри русской
|
||||||
/// фразы, Parakeet быстрее в 11-15 раз. Разбор - `bench/BENCH-CANDIDATES-2026-09-03.md`.
|
/// фразы, Parakeet быстрее в 11-15 раз. Разбор - `bench/BENCH-CANDIDATES-2026-09-03.md`.
|
||||||
@Published var speechEngine: SpeechModelProfile
|
@Published var speechEngine: SpeechModelProfile {
|
||||||
|
didSet { refreshSpeechModelReadiness() }
|
||||||
|
}
|
||||||
|
@Published private(set) var speechModelInstalled = false
|
||||||
@Published var promptRecipient: PromptRecipientSetting
|
@Published var promptRecipient: PromptRecipientSetting
|
||||||
/// Явные записи «приложение → профиль». Всё, чего в списке нет, получает
|
/// Явные записи «приложение → профиль». Всё, чего в списке нет, получает
|
||||||
/// `promptRecipient`, поэтому отдельного «дефолтного» ряда тут не бывает.
|
/// `promptRecipient`, поэтому отдельного «дефолтного» ряда тут не бывает.
|
||||||
@@ -212,6 +215,8 @@ final class SettingsModel: ObservableObject {
|
|||||||
private let layoutSettings: LayoutSettingsAccess
|
private let layoutSettings: LayoutSettingsAccess
|
||||||
private let layoutHotkeys: LayoutHotkeySettingsAccess
|
private let layoutHotkeys: LayoutHotkeySettingsAccess
|
||||||
private let agentDetector: (String, PromptAgentAdapter) -> URL?
|
private let agentDetector: (String, PromptAgentAdapter) -> URL?
|
||||||
|
private let installedSpeechEngine: () -> SpeechModelProfile
|
||||||
|
private let speechModelProbe: (SpeechModelProfile) -> Bool
|
||||||
private var savedLaunchAtLogin: Bool
|
private var savedLaunchAtLogin: Bool
|
||||||
|
|
||||||
convenience init(preview: Bool = false) {
|
convenience init(preview: Bool = false) {
|
||||||
@@ -220,7 +225,8 @@ final class SettingsModel: ObservableObject {
|
|||||||
self.init(
|
self.init(
|
||||||
dictationSettings: DictationSettings(defaults: defaults),
|
dictationSettings: DictationSettings(defaults: defaults),
|
||||||
layoutSettings: .preview(defaults: defaults),
|
layoutSettings: .preview(defaults: defaults),
|
||||||
layoutHotkeys: .settings(SettingsManager(defaults: defaults))
|
layoutHotkeys: .settings(SettingsManager(defaults: defaults)),
|
||||||
|
speechModelProbe: { _ in false }
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
self.init(
|
self.init(
|
||||||
@@ -238,11 +244,15 @@ final class SettingsModel: ObservableObject {
|
|||||||
dictationSettings: DictationSettings,
|
dictationSettings: DictationSettings,
|
||||||
layoutSettings: LayoutSettingsAccess,
|
layoutSettings: LayoutSettingsAccess,
|
||||||
layoutHotkeys: LayoutHotkeySettingsAccess,
|
layoutHotkeys: LayoutHotkeySettingsAccess,
|
||||||
codexDetector: ((String) -> URL?)? = nil
|
codexDetector: ((String) -> URL?)? = nil,
|
||||||
|
installedSpeechEngine: @escaping () -> SpeechModelProfile = { .installedDefault() },
|
||||||
|
speechModelProbe: @escaping (SpeechModelProfile) -> Bool = speechModelCacheExists
|
||||||
) {
|
) {
|
||||||
self.dictationSettings = dictationSettings
|
self.dictationSettings = dictationSettings
|
||||||
self.layoutSettings = layoutSettings
|
self.layoutSettings = layoutSettings
|
||||||
self.layoutHotkeys = layoutHotkeys
|
self.layoutHotkeys = layoutHotkeys
|
||||||
|
self.installedSpeechEngine = installedSpeechEngine
|
||||||
|
self.speechModelProbe = speechModelProbe
|
||||||
agentDetector = codexDetector.map { detector in
|
agentDetector = codexDetector.map { detector in
|
||||||
{ path, _ in detector(path) }
|
{ path, _ in detector(path) }
|
||||||
} ?? { path, adapter in
|
} ?? { path, adapter in
|
||||||
@@ -279,6 +289,21 @@ final class SettingsModel: ObservableObject {
|
|||||||
wavePalette = dictationSettings.dictationHUDWavePalette
|
wavePalette = dictationSettings.dictationHUDWavePalette
|
||||||
rescueWindowEnabled = dictationSettings.rescueWindowEnabled
|
rescueWindowEnabled = dictationSettings.rescueWindowEnabled
|
||||||
hotkeys = Self.loadHotkeys(dictationSettings: dictationSettings, layoutHotkeys: layoutHotkeys)
|
hotkeys = Self.loadHotkeys(dictationSettings: dictationSettings, layoutHotkeys: layoutHotkeys)
|
||||||
|
refreshSpeechModelReadiness()
|
||||||
|
}
|
||||||
|
|
||||||
|
func refreshSpeechModelReadiness() {
|
||||||
|
speechModelInstalled = speechModelProbe(speechEngine)
|
||||||
|
}
|
||||||
|
|
||||||
|
var canUseInstalledParakeet: Bool {
|
||||||
|
speechEngine != .multilingualV3 && speechModelProbe(.multilingualV3)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Явная установка выбирает скачанный движок. Остальные черновики формы
|
||||||
|
/// остаются у пользователя; общая settingsDidSave сюда не подключается.
|
||||||
|
func applyInstalledSpeechModel(_ profile: SpeechModelProfile) {
|
||||||
|
speechEngine = profile
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Адаптер выбранного агента: свой CLI собирается из введённых аргументов.
|
/// Адаптер выбранного агента: свой CLI собирается из введённых аргументов.
|
||||||
@@ -586,8 +611,13 @@ final class SettingsModel: ObservableObject {
|
|||||||
launchAtLogin = true
|
launchAtLogin = true
|
||||||
corrections = []
|
corrections = []
|
||||||
snippets = []
|
snippets = []
|
||||||
|
retentionDays = DICTATION_RETENTION_DEFAULT_DAYS
|
||||||
|
hudShowsHints = false
|
||||||
|
hudSize = DICTATION_HUD_DEFAULT_SIZE
|
||||||
|
promptGuidanceInstructions = PromptUserGuidance.none.instructions
|
||||||
|
promptGuidanceExamples = PromptUserGuidance.none.examples
|
||||||
promptModeEnabled = false
|
promptModeEnabled = false
|
||||||
speechEngine = .whisperTurbo
|
speechEngine = installedSpeechEngine()
|
||||||
promptRecipient = .codex
|
promptRecipient = .codex
|
||||||
appProfiles = []
|
appProfiles = []
|
||||||
promptAgentID = PromptAgentCatalog.defaultID
|
promptAgentID = PromptAgentCatalog.defaultID
|
||||||
|
|||||||
@@ -1,10 +1,194 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
import IrizDictate
|
||||||
|
import IrizPrompt
|
||||||
import Testing
|
import Testing
|
||||||
|
|
||||||
@testable import IrizApp
|
@testable import IrizApp
|
||||||
|
|
||||||
@Suite("знакомство: решения, а не картинки")
|
@Suite("знакомство: решения, а не картинки")
|
||||||
struct FirstRunTests {
|
struct FirstRunTests {
|
||||||
|
@MainActor
|
||||||
|
@Test func freshInstallExplainsDownloadBeforeOtherSetupAndCanRecoverLater() throws {
|
||||||
|
let name = "ru.iriz.tests.firstRun.download.\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let settings = DictationSettings(defaults: defaults)
|
||||||
|
settings.speechEngine = .multilingualV3
|
||||||
|
let model = FirstRunModel(defaults: defaults, settings: settings,
|
||||||
|
refreshSystemState: false, modelProbe: { _ in false })
|
||||||
|
model.prepareForPresentation()
|
||||||
|
#expect(model.step == .welcome)
|
||||||
|
model.goNext()
|
||||||
|
#expect(model.step == .model)
|
||||||
|
#expect(model.nextButtonTitle != FirstRunCopy.next)
|
||||||
|
#expect(!model.modelInstalled)
|
||||||
|
#expect(FirstRunCopy.welcome.note?.contains("модел") == true)
|
||||||
|
#expect(FirstRunCopy.model.action?.contains("Parakeet") == true)
|
||||||
|
#expect(FirstRunCopy.model.body.contains("Без модели диктовка не работает"))
|
||||||
|
|
||||||
|
// Пропустить установку можно, но это не скрывает её при следующем запуске.
|
||||||
|
model.finish()
|
||||||
|
#expect(firstRunShouldShow(defaults: defaults, permissionsGranted: true, modelInstalled: false))
|
||||||
|
model.prepareForPresentation()
|
||||||
|
#expect(model.step == .model)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func installedModelMatchesSelectedEngineAndRestartsRecognitionOnce() throws {
|
||||||
|
let name = "ru.iriz.tests.firstRun.engine.\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let settings = DictationSettings(defaults: defaults)
|
||||||
|
settings.speechEngine = .whisperTurbo
|
||||||
|
let model = FirstRunModel(defaults: defaults, settings: settings,
|
||||||
|
refreshSystemState: false, modelProbe: { $0 == .multilingualV3 })
|
||||||
|
model.refreshModelAvailability()
|
||||||
|
#expect(!model.modelInstalled, "Наличие Parakeet не делает выбранный Whisper готовым")
|
||||||
|
var restarts = 0
|
||||||
|
model.onSpeechModelInstalled = { restarts += 1 }
|
||||||
|
model.installationDidFinish()
|
||||||
|
#expect(settings.speechEngine == .multilingualV3)
|
||||||
|
model.refreshModelAvailability()
|
||||||
|
#expect(model.modelInstalled)
|
||||||
|
#expect(restarts == 1)
|
||||||
|
model.installationWasRefused(.alreadyInstalled)
|
||||||
|
#expect(restarts == 1, "Дублирующий callback установщика не запускает второй прогрев")
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func installProgressKeepsDownloadPrimaryUntilItStartsAndAllowsRetry() throws {
|
||||||
|
let name = "ru.iriz.tests.firstRun.progress.\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let settings = DictationSettings(defaults: defaults)
|
||||||
|
settings.speechEngine = .whisperTurbo
|
||||||
|
let model = FirstRunModel(defaults: defaults, settings: settings,
|
||||||
|
refreshSystemState: false, modelProbe: { _ in false })
|
||||||
|
model.showModelSetup()
|
||||||
|
#expect(model.modelInstallIsPrimaryAction)
|
||||||
|
model.installationDidProgress(.downloading(0.42))
|
||||||
|
#expect(model.isInstallingModel)
|
||||||
|
#expect(!model.modelInstallIsPrimaryAction)
|
||||||
|
#expect(model.nextButtonTitle == FirstRunCopy.next)
|
||||||
|
#expect(settings.speechEngine == .whisperTurbo)
|
||||||
|
model.installationDidProgress(.failed("Synthetic network failure"))
|
||||||
|
#expect(!model.isInstallingModel)
|
||||||
|
#expect(!model.modelInstalled)
|
||||||
|
#expect(model.modelInstallIsPrimaryAction)
|
||||||
|
#expect(settings.speechEngine == .whisperTurbo)
|
||||||
|
model.installationDidProgress(.downloading(0))
|
||||||
|
model.installationDidProgress(.compiling)
|
||||||
|
#expect(model.isInstallingModel)
|
||||||
|
#expect(!model.modelInstalled)
|
||||||
|
model.installationDidProgress(.finished)
|
||||||
|
#expect(model.modelInstalled)
|
||||||
|
#expect(!model.modelInstallIsPrimaryAction)
|
||||||
|
#expect(settings.speechEngine == .multilingualV3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func repairingInstalledCacheDoesNotHideProgressOrAllowTrialOnFailure() throws {
|
||||||
|
let name = "ru.iriz.tests.firstRun.repair.\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let settings = DictationSettings(defaults: defaults)
|
||||||
|
settings.speechEngine = .multilingualV3
|
||||||
|
let model = FirstRunModel(defaults: defaults, settings: settings,
|
||||||
|
refreshSystemState: false, modelProbe: { _ in true })
|
||||||
|
model.showModelSetup()
|
||||||
|
model.refreshModelAvailability()
|
||||||
|
#expect(model.modelIsReady)
|
||||||
|
model.installationDidProgress(.downloading(0.42))
|
||||||
|
model.refreshModelAvailability()
|
||||||
|
#expect(model.modelInstalled, "Быстрая проверка видит файлы, но не знает об их целостности")
|
||||||
|
#expect(!model.modelIsReady)
|
||||||
|
model.installationDidProgress(.failed("Synthetic corrupt cache"))
|
||||||
|
#expect(model.modelInstallIsPrimaryAction)
|
||||||
|
var audioStarted = false
|
||||||
|
model.toggleDictation = { audioStarted = true }
|
||||||
|
model.toggleTrial()
|
||||||
|
#expect(model.step == .model)
|
||||||
|
#expect(!audioStarted)
|
||||||
|
model.installationDidProgress(.finished)
|
||||||
|
#expect(model.modelIsReady)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func trialWithoutModelReturnsToInstallerWithoutStartingAudio() throws {
|
||||||
|
let name = "ru.iriz.tests.firstRun.trial.\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let settings = DictationSettings(defaults: defaults)
|
||||||
|
settings.speechEngine = .multilingualV3
|
||||||
|
let model = FirstRunModel(defaults: defaults, settings: settings,
|
||||||
|
refreshSystemState: false, modelProbe: { _ in false })
|
||||||
|
var audioStarted = false
|
||||||
|
model.toggleDictation = { audioStarted = true }
|
||||||
|
model.toggleTrial()
|
||||||
|
#expect(model.step == .model)
|
||||||
|
#expect(!model.isRecording)
|
||||||
|
#expect(!audioStarted)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func agentConnectionValidatesModelAndNotifiesRunningApp() throws {
|
||||||
|
let name = "ru.iriz.tests.firstRun.settings.\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let settings = DictationSettings(defaults: defaults)
|
||||||
|
let model = FirstRunModel(defaults: defaults, settings: settings, refreshSystemState: false)
|
||||||
|
let received = FirstRunNotificationCount()
|
||||||
|
let observer = NotificationCenter.default.addObserver(
|
||||||
|
forName: DictationController.settingsDidSaveNotification,
|
||||||
|
object: settings,
|
||||||
|
queue: .main
|
||||||
|
) { _ in MainActor.assumeIsolated { received.value += 1 } }
|
||||||
|
defer { NotificationCenter.default.removeObserver(observer) }
|
||||||
|
|
||||||
|
model.connectAgent(PromptAgentCatalog.codexID)
|
||||||
|
#expect(settings.promptModeEnabled)
|
||||||
|
#expect(model.connectedAgentID == PromptAgentCatalog.codexID)
|
||||||
|
#expect(received.value == 1)
|
||||||
|
model.enableTranslation()
|
||||||
|
#expect(settings.translationModeEnabled)
|
||||||
|
#expect(received.value == 2)
|
||||||
|
|
||||||
|
model.connectAgent(PromptAgentCatalog.ollamaID)
|
||||||
|
#expect(model.agentConnectionError != nil)
|
||||||
|
#expect(settings.promptAgentID == PromptAgentCatalog.codexID)
|
||||||
|
#expect(model.connectedAgentID == PromptAgentCatalog.codexID)
|
||||||
|
#expect(received.value == 2)
|
||||||
|
|
||||||
|
settings.promptAgentModel = "local-test-model"
|
||||||
|
model.connectAgent(PromptAgentCatalog.ollamaID)
|
||||||
|
#expect(model.agentConnectionError == nil)
|
||||||
|
#expect(settings.promptAgentID == PromptAgentCatalog.ollamaID)
|
||||||
|
#expect(model.connectedAgentID == PromptAgentCatalog.ollamaID)
|
||||||
|
#expect(received.value == 3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func installationRefusalShowsRecoveryInsteadOfPendingDownload() throws {
|
||||||
|
let name = "ru.iriz.tests.firstRun.install.\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let model = FirstRunModel(defaults: defaults,
|
||||||
|
settings: DictationSettings(defaults: defaults),
|
||||||
|
refreshSystemState: false)
|
||||||
|
for refusal in [SpeechModelInstallRefusal.dictationBusy, .alreadyRunning] {
|
||||||
|
model.installationWasRefused(refusal)
|
||||||
|
guard case .failed(let reason) = model.installPhase else {
|
||||||
|
Issue.record("Отказ оставил установку без понятного результата")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(!reason.isEmpty)
|
||||||
|
#expect(!model.modelInstalled)
|
||||||
|
}
|
||||||
|
model.installationWasRefused(.alreadyInstalled)
|
||||||
|
#expect(model.installPhase == .finished)
|
||||||
|
#expect(model.modelInstalled)
|
||||||
|
}
|
||||||
|
|
||||||
/// Порядок шагов - это сценарий, а не список. Разрешения идут от самого
|
/// Порядок шагов - это сценарий, а не список. Разрешения идут от самого
|
||||||
/// понятного к самому пугающему: человеку, которому уже объяснили микрофон,
|
/// понятного к самому пугающему: человеку, которому уже объяснили микрофон,
|
||||||
/// спокойнее отвечать на «сможет читать все нажатия».
|
/// спокойнее отвечать на «сможет читать все нажатия».
|
||||||
@@ -23,6 +207,7 @@ struct FirstRunTests {
|
|||||||
// человек щёлкает переключатели в системном окне, загрузка идёт, и
|
// человек щёлкает переключатели в системном окне, загрузка идёт, и
|
||||||
// время тратится один раз, а не дважды.
|
// время тратится один раз, а не дважды.
|
||||||
let model = steps.firstIndex(of: .model)!
|
let model = steps.firstIndex(of: .model)!
|
||||||
|
#expect(model == 1, "Обязательная загрузка объясняется сразу после приветствия")
|
||||||
#expect(model < mic, "загрузка модели обязана начинаться раньше разрешений")
|
#expect(model < mic, "загрузка модели обязана начинаться раньше разрешений")
|
||||||
#expect(model < tryIt, "проба без модели невозможна")
|
#expect(model < tryIt, "проба без модели невозможна")
|
||||||
// Агент уводит речь с этого Мака, поэтому он идёт ПОСЛЕ пробы: человек
|
// Агент уводит речь с этого Мака, поэтому он идёт ПОСЛЕ пробы: человек
|
||||||
@@ -80,6 +265,8 @@ struct FirstRunTests {
|
|||||||
defaults.set(true, forKey: FIRST_RUN_COMPLETED_KEY)
|
defaults.set(true, forKey: FIRST_RUN_COMPLETED_KEY)
|
||||||
#expect(!firstRunShouldShow(defaults: defaults, permissionsGranted: false),
|
#expect(!firstRunShouldShow(defaults: defaults, permissionsGranted: false),
|
||||||
"знакомство повторилось после прохождения")
|
"знакомство повторилось после прохождения")
|
||||||
|
#expect(firstRunShouldShow(defaults: defaults, permissionsGranted: true, modelInstalled: false),
|
||||||
|
"Пройденное знакомство скрывает незавершённую установку модели")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Разрешение просит ровно тот шаг, который про него рассказывает.
|
/// Разрешение просит ровно тот шаг, который про него рассказывает.
|
||||||
@@ -157,3 +344,8 @@ struct FirstRunTests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
private final class FirstRunNotificationCount {
|
||||||
|
var value = 0
|
||||||
|
}
|
||||||
|
|||||||
@@ -110,6 +110,20 @@ struct MenuStatePromiseTests {
|
|||||||
#expect(s.permissionAlarm == "Нет доступа к Мониторингу ввода")
|
#expect(s.permissionAlarm == "Нет доступа к Мониторингу ввода")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func ошибкаМоделиНеВедётКВыданнымРазрешениям() {
|
||||||
|
let s = state()
|
||||||
|
s.dictationState = .unavailable("Модель распознавания не установлена")
|
||||||
|
#expect(!s.dictationRecoveryNeedsPermissions)
|
||||||
|
s.microphoneOK = false
|
||||||
|
#expect(s.dictationRecoveryNeedsPermissions)
|
||||||
|
s.microphoneOK = true
|
||||||
|
s.inputMonitoringOK = false
|
||||||
|
#expect(s.dictationRecoveryNeedsPermissions)
|
||||||
|
s.inputMonitoringOK = true
|
||||||
|
s.inputTapOK = false
|
||||||
|
#expect(s.dictationRecoveryNeedsPermissions)
|
||||||
|
}
|
||||||
|
|
||||||
@Test func отвалившийсяТапВидноОтдельноОтРазрешений() {
|
@Test func отвалившийсяТапВидноОтдельноОтРазрешений() {
|
||||||
// Разрешения на месте, а слежение отвалилось: разные поломки лечатся
|
// Разрешения на месте, а слежение отвалилось: разные поломки лечатся
|
||||||
// по-разному, и валить их в одну строку значит отправить владельца
|
// по-разному, и валить их в одну строку значит отправить владельца
|
||||||
|
|||||||
@@ -472,9 +472,13 @@ struct CodexPromptGeneratorTests {
|
|||||||
|
|
||||||
@Test func timeoutTerminatesFakeProcess() async throws {
|
@Test func timeoutTerminatesFakeProcess() async throws {
|
||||||
let fake = try makeFakeExecutable(body: """
|
let fake = try makeFakeExecutable(body: """
|
||||||
marker=${0%/*}/process.pid
|
exec /usr/bin/perl -e '
|
||||||
printf '%s' "$$" > "$marker"
|
$SIG{INT} = $SIG{TERM} = "IGNORE";
|
||||||
exec /usr/bin/perl -e '$SIG{INT} = $SIG{TERM} = "IGNORE"; sleep 1 while 1'
|
open my $marker, ">", $ARGV[0] or die $!;
|
||||||
|
print {$marker} $$;
|
||||||
|
close $marker or die $!;
|
||||||
|
sleep 1 while 1
|
||||||
|
' "${0%/*}/process.pid"
|
||||||
""")
|
""")
|
||||||
let marker = fake.directory.appendingPathComponent("process.pid")
|
let marker = fake.directory.appendingPathComponent("process.pid")
|
||||||
defer {
|
defer {
|
||||||
@@ -487,14 +491,16 @@ struct CodexPromptGeneratorTests {
|
|||||||
let started = Date()
|
let started = Date()
|
||||||
|
|
||||||
do {
|
do {
|
||||||
_ = try await fakeGenerator(fake, timeoutSeconds: 1)
|
// Запуск интерпретатора под нагрузкой не обязан уложиться в секунду.
|
||||||
|
_ = try await fakeGenerator(fake, timeoutSeconds: 3)
|
||||||
.generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw))
|
.generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw))
|
||||||
Issue.record("Runner не сработал по таймауту")
|
Issue.record("Runner не сработал по таймауту")
|
||||||
} catch let error as CodexPromptGeneratorError {
|
} catch let error as CodexPromptGeneratorError {
|
||||||
#expect(error == .timedOut)
|
#expect(error == .timedOut)
|
||||||
}
|
}
|
||||||
let elapsed = Date().timeIntervalSince(started)
|
let elapsed = Date().timeIntervalSince(started)
|
||||||
#expect(elapsed < 5)
|
// Две попытки по 3 с плюс эскалация до SIGKILL и накладные расходы.
|
||||||
|
#expect(elapsed < 9)
|
||||||
let pid = try #require(processID(at: marker))
|
let pid = try #require(processID(at: marker))
|
||||||
errno = 0
|
errno = 0
|
||||||
#expect(Darwin.kill(pid, 0) == -1)
|
#expect(Darwin.kill(pid, 0) == -1)
|
||||||
@@ -545,26 +551,35 @@ struct CodexPromptGeneratorTests {
|
|||||||
printf '%s' "$count" > "$attempts"
|
printf '%s' "$count" > "$attempts"
|
||||||
case "$count" in
|
case "$count" in
|
||||||
1)
|
1)
|
||||||
(trap '' HUP INT TERM; /bin/sleep 5; /usr/bin/printf '%s' 'stale' > "$result"; /usr/bin/printf '%s' 'yes' > "${0%/*}/stale-wrote") &
|
(
|
||||||
|
trap '' HUP INT TERM
|
||||||
|
while [ ! -e "${0%/*}/retry-ready" ]; do /bin/sleep 0.02; done
|
||||||
|
/usr/bin/printf '%s' 'stale' > "$result"
|
||||||
|
/usr/bin/touch "${0%/*}/stale-wrote"
|
||||||
|
) &
|
||||||
|
printf '%s' "$!" > "${0%/*}/writer.pid"
|
||||||
exec /bin/sleep 60
|
exec /bin/sleep 60
|
||||||
;;
|
;;
|
||||||
2)
|
2)
|
||||||
/usr/bin/printf '%s' '{"status":"ready","taskKind":"general","goal":{"text":"Fresh retry","evidence":"Fresh retry"},"context":[],"requirements":[],"constraints":[],"outputRequirements":[],"acceptance":[],"ambiguities":[],"modules":[]}' > "$result"
|
/usr/bin/printf '%s' '{"status":"ready","taskKind":"general","goal":{"text":"Fresh retry","evidence":"Fresh retry"},"context":[],"requirements":[],"constraints":[],"outputRequirements":[],"acceptance":[],"ambiguities":[],"modules":[]}' > "$result"
|
||||||
/bin/sleep 3
|
/usr/bin/touch "${0%/*}/retry-ready"
|
||||||
|
while [ ! -e "${0%/*}/stale-wrote" ]; do /bin/sleep 0.02; done
|
||||||
;;
|
;;
|
||||||
*) exit 73 ;;
|
*) exit 73 ;;
|
||||||
esac
|
esac
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
defer { try? FileManager.default.removeItem(at: fake.directory) }
|
let writerPIDURL = fake.directory.appendingPathComponent("writer.pid")
|
||||||
|
defer {
|
||||||
|
if let pid = processID(at: writerPIDURL), Darwin.kill(pid, 0) == 0 {
|
||||||
|
_ = Darwin.kill(pid, SIGKILL)
|
||||||
|
}
|
||||||
|
try? FileManager.default.removeItem(at: fake.directory)
|
||||||
|
}
|
||||||
let raw = "Fresh retry"
|
let raw = "Fresh retry"
|
||||||
|
|
||||||
// Времена разведены с запасом. Раньше устаревшая запись приходила
|
// Вторая попытка ждёт устаревшую запись после своего результата:
|
||||||
// через 0,1 с после снятия первой попытки и должна была попасть в
|
// порядок событий проверяется независимо от скорости машины.
|
||||||
// трёхсекундное окно второй - зазор в одну десятую секунды не
|
|
||||||
// переживает занятую машину. Теперь: попытка снимается на 4 с,
|
|
||||||
// устаревшая запись приходит на 5-й, вторая попытка идёт 3 с, то есть
|
|
||||||
// окно шире зазора в тридцать раз.
|
|
||||||
let generation = try await fakeGenerator(fake, timeoutSeconds: 4)
|
let generation = try await fakeGenerator(fake, timeoutSeconds: 4)
|
||||||
.generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw))
|
.generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw))
|
||||||
|
|
||||||
@@ -579,14 +594,7 @@ struct CodexPromptGeneratorTests {
|
|||||||
#expect(resultPaths[0] != resultPaths[1])
|
#expect(resultPaths[0] != resultPaths[1])
|
||||||
}
|
}
|
||||||
let staleWriterURL = fake.directory.appendingPathComponent("stale-wrote")
|
let staleWriterURL = fake.directory.appendingPathComponent("stale-wrote")
|
||||||
var staleWriter = ""
|
#expect(FileManager.default.fileExists(atPath: staleWriterURL.path))
|
||||||
for _ in 0..<50 where staleWriter != "yes" {
|
|
||||||
staleWriter = (try? String(contentsOf: staleWriterURL)) ?? ""
|
|
||||||
if staleWriter != "yes" {
|
|
||||||
try await Task.sleep(for: .milliseconds(20))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#expect(staleWriter == "yes")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func inheritedStderrDoesNotHangRunner() async throws {
|
@Test func inheritedStderrDoesNotHangRunner() async throws {
|
||||||
@@ -633,7 +641,7 @@ struct CodexPromptGeneratorTests {
|
|||||||
let fake = try makeFakeExecutable(body: """
|
let fake = try makeFakeExecutable(body: """
|
||||||
marker=${0%/*}/process.pid
|
marker=${0%/*}/process.pid
|
||||||
printf '%s' "$$" > "$marker"
|
printf '%s' "$$" > "$marker"
|
||||||
exec /bin/sleep 5
|
exec /bin/sleep 60
|
||||||
""")
|
""")
|
||||||
let marker = fake.directory.appendingPathComponent("process.pid")
|
let marker = fake.directory.appendingPathComponent("process.pid")
|
||||||
defer {
|
defer {
|
||||||
@@ -644,10 +652,13 @@ struct CodexPromptGeneratorTests {
|
|||||||
}
|
}
|
||||||
let raw = "Собери отчёт."
|
let raw = "Собери отчёт."
|
||||||
let task = Task {
|
let task = Task {
|
||||||
try await fakeGenerator(fake, timeoutSeconds: 10)
|
try await fakeGenerator(fake, timeoutSeconds: 30)
|
||||||
.generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw))
|
.generate(rawTranscript: raw, markup: PromptEnvelopeBuilder().analyze(raw))
|
||||||
}
|
}
|
||||||
for _ in 0..<100 where processID(at: marker) == nil {
|
defer { task.cancel() }
|
||||||
|
// Время запуска не входит в проверку скорости отмены: сначала ждём PID.
|
||||||
|
let startupDeadline = ContinuousClock.now.advanced(by: .seconds(10))
|
||||||
|
while processID(at: marker) == nil, ContinuousClock.now < startupDeadline {
|
||||||
try await Task.sleep(for: .milliseconds(20))
|
try await Task.sleep(for: .milliseconds(20))
|
||||||
}
|
}
|
||||||
let pid = try #require(processID(at: marker))
|
let pid = try #require(processID(at: marker))
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import AppKit
|
||||||
|
import Testing
|
||||||
|
@testable import IrizDictate
|
||||||
|
|
||||||
|
@Suite("плашка: доступные кнопки и уменьшение движения")
|
||||||
|
@MainActor
|
||||||
|
struct DictationHUDAccessibilityTests {
|
||||||
|
@Test func действиеAXИспользуетАктуальнуюКнопку() {
|
||||||
|
let button = DictationHUDActionButton(action: dictationHUDActions(isRecording: false)[0])
|
||||||
|
var invoked: [DictationHUDActionID] = []
|
||||||
|
button.onPress = { invoked.append($0) }
|
||||||
|
#expect(button.isAccessibilityElement())
|
||||||
|
#expect(button.accessibilityRole() == .button)
|
||||||
|
#expect(button.accessibilityLabel() == button.action.title)
|
||||||
|
#expect(button.accessibilityPerformPress())
|
||||||
|
button.action = dictationHUDActions(isRecording: true)[0]
|
||||||
|
#expect(button.accessibilityLabel() == button.action.title)
|
||||||
|
#expect(button.toolTip == button.action.title)
|
||||||
|
#expect(button.accessibilityPerformPress())
|
||||||
|
#expect(invoked == [.record, .record])
|
||||||
|
button.isHidden = true
|
||||||
|
#expect(!button.accessibilityPerformPress())
|
||||||
|
#expect(invoked.count == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func копированиеИЗакрытиеИмеютСемантикуИДействия() {
|
||||||
|
// Обработчики-заглушки: настоящий буфер обмена тест не меняет.
|
||||||
|
let copy = DictationHUDCopyPill(frame: .zero)
|
||||||
|
let close = DictationHUDCloseRing(frame: .zero)
|
||||||
|
var copies = 0
|
||||||
|
var closes = 0
|
||||||
|
copy.title = "Скопировать"
|
||||||
|
copy.onPress = { copies += 1 }
|
||||||
|
close.onPress = { closes += 1 }
|
||||||
|
for button in [copy as NSView, close as NSView] {
|
||||||
|
#expect(button.isAccessibilityElement())
|
||||||
|
#expect(button.accessibilityRole() == .button)
|
||||||
|
#expect(button.accessibilityLabel()?.isEmpty == false)
|
||||||
|
#expect(button.accessibilityPerformPress())
|
||||||
|
}
|
||||||
|
#expect(copies == 1)
|
||||||
|
#expect(closes == 1)
|
||||||
|
copy.title = "Скопировано"
|
||||||
|
#expect(copy.accessibilityLabel() == "Скопировано")
|
||||||
|
close.isHidden = true
|
||||||
|
#expect(!close.accessibilityPerformPress())
|
||||||
|
#expect(closes == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func сменаНастройкиОстанавливаетУжеНачатыйHover() throws {
|
||||||
|
let center = NotificationCenter()
|
||||||
|
var reduced = false
|
||||||
|
let button = DictationHUDActionButton(
|
||||||
|
action: dictationHUDActions(isRecording: false)[0],
|
||||||
|
reduceMotion: { reduced }, displayOptionsCenter: center)
|
||||||
|
button.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
|
||||||
|
button.forceHover(true)
|
||||||
|
let layer = try #require(button.layer)
|
||||||
|
#expect(layer.animation(forKey: "irizHoverLift") != nil)
|
||||||
|
reduced = true
|
||||||
|
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
|
||||||
|
#expect(layer.animation(forKey: "irizHoverLift") == nil)
|
||||||
|
#expect(CATransform3DIsIdentity(layer.transform))
|
||||||
|
button.forceHover(false)
|
||||||
|
button.forceHover(true)
|
||||||
|
#expect(layer.animation(forKey: "irizHoverLift") == nil)
|
||||||
|
#expect(CATransform3DIsIdentity(layer.transform))
|
||||||
|
reduced = false
|
||||||
|
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
|
||||||
|
#expect(layer.animation(forKey: "irizHoverLift") != nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func ожиданиеПеречитываетНастройкуБезТаймераУровня() throws {
|
||||||
|
let center = NotificationCenter()
|
||||||
|
let surface = AccessibilityHUDSurface()
|
||||||
|
var reduced = false
|
||||||
|
let presenter = DictationHUDPresenter(
|
||||||
|
level: { 0 }, pipelineState: { .transcribing }, historyHint: { "" },
|
||||||
|
reduceMotion: { reduced }, displayOptionsCenter: center, surface: { surface })
|
||||||
|
presenter.pipelineStateChanged(.transcribing)
|
||||||
|
#expect(!presenter.isPollingLevel)
|
||||||
|
#expect(try #require(surface.content).animatesWaiting)
|
||||||
|
reduced = true
|
||||||
|
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
|
||||||
|
let still = try #require(surface.content)
|
||||||
|
#expect(still.stage == .recognizing)
|
||||||
|
#expect(!still.animatesWaiting)
|
||||||
|
reduced = false
|
||||||
|
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
|
||||||
|
#expect(try #require(surface.content).animatesWaiting)
|
||||||
|
#expect(!presenter.isPollingLevel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
private final class AccessibilityHUDSurface: DictationHUDSurface {
|
||||||
|
var content: DictationHUDContent?
|
||||||
|
func present(_ content: DictationHUDContent) { self.content = content }
|
||||||
|
func dismiss() { content = nil }
|
||||||
|
}
|
||||||
@@ -131,6 +131,92 @@ struct DictationHistorySearchTests {
|
|||||||
|
|
||||||
// MARK: - Порядок
|
// MARK: - Порядок
|
||||||
|
|
||||||
|
@Suite("UI-MACOS-208/209: загрузка истории и приватное превью")
|
||||||
|
struct DictationHistoryLoadingTests {
|
||||||
|
@MainActor
|
||||||
|
@Test func поздняяСотняНеПерезаписываетПолныйПоиск() {
|
||||||
|
let model = DictationHistoryModel()
|
||||||
|
let recent = DictationHistoryEntry(directory: URL(fileURLWithPath: "/tmp/recent"), text: "свежее")
|
||||||
|
let older = DictationHistoryEntry(directory: URL(fileURLWithPath: "/tmp/older"), text: "старый ответ")
|
||||||
|
let partial = model.beginLoading(all: false)
|
||||||
|
let full = model.beginLoading(all: true)
|
||||||
|
model.completeLoading(.success([recent, older]), generation: full, all: true)
|
||||||
|
model.completeLoading(.success([recent]), generation: partial, all: false)
|
||||||
|
#expect(model.entries == [recent, older])
|
||||||
|
#expect(model.didLoadAll)
|
||||||
|
#expect(!model.isLoading)
|
||||||
|
|
||||||
|
let closed = model.beginLoading(all: true)
|
||||||
|
model.cancelLoading()
|
||||||
|
model.completeLoading(.success([]), generation: closed, all: true)
|
||||||
|
#expect(model.entries == [recent, older])
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func previewНеВызываетДажеПровайдерРеальногоКаталога() {
|
||||||
|
let model = DictationHistoryModel(preview: true)
|
||||||
|
var rootCalls = 0
|
||||||
|
model.query = "закрытая запись"
|
||||||
|
model.reload {
|
||||||
|
rootCalls += 1
|
||||||
|
throw CocoaError(.fileReadNoPermission)
|
||||||
|
}
|
||||||
|
#expect(rootCalls == 0)
|
||||||
|
#expect(model.entries.isEmpty)
|
||||||
|
#expect(!model.isLoading)
|
||||||
|
#expect(model.notice == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func ошибкаЧтенияНеВыдаётсяЗаПустуюИсторию() {
|
||||||
|
let model = DictationHistoryModel()
|
||||||
|
let generation = model.beginLoading(all: true)
|
||||||
|
model.completeLoading(.failure(CocoaError(.fileReadNoPermission)),
|
||||||
|
generation: generation, all: true)
|
||||||
|
#expect(!model.isLoading)
|
||||||
|
#expect(!model.didLoadAll)
|
||||||
|
#expect(model.noticeIsError)
|
||||||
|
#expect(model.notice?.isEmpty == false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test func повторноеОткрытиеСЗапросомИОчисткаВидятЗаписиЗаПределамиПятисот() async throws {
|
||||||
|
let root = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("iriz-history-full-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
for index in 0..<503 {
|
||||||
|
_ = try makeEntryOnDisk(in: root, label: String(format: "%04d", index),
|
||||||
|
raw: index == 0 ? "самая старая искомая фраза" : "свежая запись")
|
||||||
|
}
|
||||||
|
// Это снимок для подтверждения «Очистить всё»; реальные удаления не нужны.
|
||||||
|
#expect(try readDictationHistoryEntries(in: root).count == 503)
|
||||||
|
#expect(try readDictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT).count == 100)
|
||||||
|
|
||||||
|
let model = DictationHistoryModel()
|
||||||
|
model.query = "искомая фраза"
|
||||||
|
for _ in 0..<2 {
|
||||||
|
model.reload { root }
|
||||||
|
for _ in 0..<500 {
|
||||||
|
if !model.isLoading { break }
|
||||||
|
try await Task.sleep(nanoseconds: 10_000_000)
|
||||||
|
}
|
||||||
|
#expect(!model.isLoading)
|
||||||
|
#expect(model.didLoadAll)
|
||||||
|
#expect(model.entries.count == 503)
|
||||||
|
#expect(model.visible.map(\.label) == ["0000"])
|
||||||
|
model.cancelLoading()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func commandCУступаетВыделенномуТекстуПоиска() {
|
||||||
|
#expect(dictationHistoryKeyAction(keyCode: 8, charactersIgnoringModifiers: "c",
|
||||||
|
hasCommand: true, hasTextSelection: true) == .passThrough)
|
||||||
|
#expect(dictationHistoryKeyAction(keyCode: 8, charactersIgnoringModifiers: "c",
|
||||||
|
hasCommand: true, hasTextSelection: false) == .copySelected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Suite("Порядок записей истории")
|
@Suite("Порядок записей истории")
|
||||||
struct DictationHistoryOrderTests {
|
struct DictationHistoryOrderTests {
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import Foundation
|
||||||
|
import IrizCore
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@testable import IrizDictate
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("Кнопка записи в знакомстве и HUD")
|
||||||
|
struct DictationUIToggleTests {
|
||||||
|
private func makeController() -> (DictationController, () -> Void) {
|
||||||
|
let name = "iriz-ui-toggle-" + UUID().uuidString
|
||||||
|
let defaults = UserDefaults(suiteName: name)!
|
||||||
|
let settings = DictationSettings(defaults: defaults)
|
||||||
|
settings.playFeedbackSounds = false
|
||||||
|
let controller = DictationController(settings: settings,
|
||||||
|
insertionStats: InsertionStats(defaults: defaults))
|
||||||
|
return (controller, { removeSuiteFile(named: name, defaults: defaults) })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("повторное нажатие завершает запись вместо отказа alreadyRecording")
|
||||||
|
func secondClickFinishesRecording() {
|
||||||
|
let (controller, cleanup) = makeController()
|
||||||
|
defer { cleanup() }
|
||||||
|
// Только пустой буфер: опора не включает микрофон и не запускает ASR.
|
||||||
|
controller.simulateActiveRecordingForTesting()
|
||||||
|
#expect(controller.isRecordingActive)
|
||||||
|
controller.toggleDictationFromUI()
|
||||||
|
#expect(!controller.isRecordingActive)
|
||||||
|
#expect(!controller.audioStateForTesting.isRunning)
|
||||||
|
#expect(controller.state == .ready)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("нажатие во время разбора не запускает и не отменяет запись")
|
||||||
|
func busyProcessingIsPreserved() {
|
||||||
|
let (controller, cleanup) = makeController()
|
||||||
|
defer { cleanup() }
|
||||||
|
#expect(controller.beginMeetingProcessing() != nil)
|
||||||
|
controller.toggleDictationFromUI()
|
||||||
|
#expect(controller.isBusyForTesting)
|
||||||
|
#expect(controller.state == .transcribing)
|
||||||
|
#expect(!controller.isRecordingActive)
|
||||||
|
controller.stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,63 @@ import Testing
|
|||||||
|
|
||||||
@Suite("Решения конвейера встречи")
|
@Suite("Решения конвейера встречи")
|
||||||
struct MeetingPipelineTests {
|
struct MeetingPipelineTests {
|
||||||
|
@MainActor
|
||||||
|
@Test("отменённый разбор не читает запись и не начинает распознавание")
|
||||||
|
func отменаДоНачалаОстанавливаетКонвейер() async {
|
||||||
|
let task = Task { @MainActor in
|
||||||
|
withUnsafeCurrentTask { $0?.cancel() }
|
||||||
|
var startedStages: [String] = []
|
||||||
|
do {
|
||||||
|
_ = try await MeetingPipeline().run(
|
||||||
|
audio: URL(fileURLWithPath: "/iriz-test-no-audio.wav"), title: "Встреча",
|
||||||
|
progress: { startedStages.append($0) })
|
||||||
|
Issue.record("Отменённый разбор не должен завершаться успешно")
|
||||||
|
} catch is CancellationError {
|
||||||
|
#expect(startedStages.isEmpty)
|
||||||
|
} catch {
|
||||||
|
Issue.record("Отмена подменена отказом обработки: \(error)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await task.value
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("без времён слов полный текст сохраняется даже при успешной диаризации")
|
||||||
|
func текстБезТайминговНеТеряется() {
|
||||||
|
let spans = [SpeakerSpan(speaker: "speaker-1", start: 0, end: 12)]
|
||||||
|
let tokenCases: [[DictationTokenTiming]] = [
|
||||||
|
[], [DictationTokenTiming(token: " ", start: 0, end: 1, confidence: 1)]
|
||||||
|
]
|
||||||
|
for tokens in tokenCases {
|
||||||
|
let transcript = AudioFileTranscript(text: "Первая реплика.\nВторая реплика.",
|
||||||
|
processingSeconds: 1, audioSeconds: 12,
|
||||||
|
tokenTimings: tokens)
|
||||||
|
let resolved = meetingSpeakerTurns(transcript: transcript, spans: spans)
|
||||||
|
#expect(!resolved.speakersResolved)
|
||||||
|
#expect(resolved.turns == [SpeakerTurn(speaker: "Запись", text: transcript.text,
|
||||||
|
start: 0, end: 12)])
|
||||||
|
let document = MeetingProtocolDocument(title: "Встреча", recordedAt: Date(),
|
||||||
|
audioSeconds: 12, turns: resolved.turns)
|
||||||
|
#expect(document.text().contains(transcript.text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("при пригодных таймингах сохраняются реплики и имена говорящих")
|
||||||
|
func таймингиПозволяютРазделитьГоворящих() {
|
||||||
|
let transcript = AudioFileTranscript(text: "Да. Нет.", processingSeconds: 1, audioSeconds: 2,
|
||||||
|
tokenTimings: [
|
||||||
|
DictationTokenTiming(token: "Да.", start: 0, end: 1, confidence: 1),
|
||||||
|
DictationTokenTiming(token: "Нет.", start: 1, end: 2, confidence: 1)
|
||||||
|
])
|
||||||
|
let resolved = meetingSpeakerTurns(
|
||||||
|
transcript: transcript,
|
||||||
|
spans: [SpeakerSpan(speaker: "one", start: 0, end: 1),
|
||||||
|
SpeakerSpan(speaker: "two", start: 1, end: 2)],
|
||||||
|
names: SpeakerNames(names: ["one": "Анна", "two": "Борис"]))
|
||||||
|
#expect(resolved.speakersResolved)
|
||||||
|
#expect(resolved.turns.map(\.speaker) == ["Анна", "Борис"])
|
||||||
|
#expect(resolved.turns.map(\.text) == ["Да.", "Нет."])
|
||||||
|
}
|
||||||
|
|
||||||
@Test("отказы названы поимённо")
|
@Test("отказы названы поимённо")
|
||||||
func отказыНазваныПоимённо() {
|
func отказыНазваныПоимённо() {
|
||||||
// Разбирать будут запись заседания: «не смог» без причины неотличимо
|
// Разбирать будут запись заседания: «не смог» без причины неотличимо
|
||||||
|
|||||||
@@ -5,12 +5,41 @@
|
|||||||
// разница между режимами - сохранённый звук, и путаница здесь стоит записи
|
// разница между режимами - сохранённый звук, и путаница здесь стоит записи
|
||||||
// заседания.
|
// заседания.
|
||||||
import AppKit
|
import AppKit
|
||||||
|
import Foundation
|
||||||
|
import IrizCore
|
||||||
import Testing
|
import Testing
|
||||||
|
|
||||||
@testable import IrizDictate
|
@testable import IrizDictate
|
||||||
|
|
||||||
@Suite("Состояние записи встречи")
|
@Suite("Состояние записи встречи")
|
||||||
struct MeetingRecordingStateTests {
|
struct MeetingRecordingStateTests {
|
||||||
|
@Test("встреча записывается до трёх часов, диктовка — до двадцати минут")
|
||||||
|
func отдельныйПределВстречи() {
|
||||||
|
#expect(DictationController.recordingLimitSeconds(for: .meeting) == 3 * 60 * 60)
|
||||||
|
for purpose in [DictationRecordingPurpose.dictation, .prompt, .translation] {
|
||||||
|
#expect(DictationController.recordingLimitSeconds(for: purpose) == 20 * 60)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("разбор встречи показывает занятость и блокирует повторное распознавание")
|
||||||
|
func разборЗанимаетОбщийКонвейер() {
|
||||||
|
let name = "iriz-meeting-processing-\(UUID().uuidString)"
|
||||||
|
let defaults = UserDefaults(suiteName: name)!
|
||||||
|
defer { removeSuiteFile(named: name, defaults: defaults) }
|
||||||
|
let controller = DictationController(settings: DictationSettings(defaults: defaults),
|
||||||
|
insertionStats: InsertionStats(defaults: defaults))
|
||||||
|
#expect(controller.beginMeetingProcessing() != nil)
|
||||||
|
#expect(controller.state == .transcribing)
|
||||||
|
#expect(controller.isBusyForTesting)
|
||||||
|
#expect(controller.beginMeetingProcessing() == nil)
|
||||||
|
#expect(dictationStartRefusal(modelReady: true, isRecording: false,
|
||||||
|
isBusy: controller.isBusyForTesting,
|
||||||
|
secureInputActive: false) == .transcriptionInFlight)
|
||||||
|
controller.stop()
|
||||||
|
#expect(!controller.isBusyForTesting)
|
||||||
|
}
|
||||||
|
|
||||||
@Test("у записи встречи свой цвет, не совпадающий ни с одним другим")
|
@Test("у записи встречи свой цвет, не совпадающий ни с одним другим")
|
||||||
func свойЦвет() {
|
func свойЦвет() {
|
||||||
let meeting = dictationHUDWaveColor(.meeting)
|
let meeting = dictationHUDWaveColor(.meeting)
|
||||||
|
|||||||
@@ -90,4 +90,47 @@ struct MeetingStoreTests {
|
|||||||
let text = try String(contentsOf: second.transcript, encoding: .utf8)
|
let text = try String(contentsOf: second.transcript, encoding: .utf8)
|
||||||
#expect(text == "второй")
|
#expect(text == "второй")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test("разные русские записи одной минуты не перезаписывают друг друга")
|
||||||
|
func коллизияНазванийНеЗатираетАрхив() throws {
|
||||||
|
let root = try sandbox()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
let firstAudio = try fakeAudio(in: root)
|
||||||
|
let secondAudio = root.appendingPathComponent("second.wav")
|
||||||
|
let secondData = Data([0x01, 0x02, 0x03])
|
||||||
|
try secondData.write(to: secondAudio)
|
||||||
|
let date = Date(timeIntervalSince1970: 1_757_000_000)
|
||||||
|
let first = try MeetingStore.save(audio: firstAudio, protocolText: "первый",
|
||||||
|
at: date, title: "Встреча", in: root)
|
||||||
|
let second = try MeetingStore.save(audio: secondAudio, protocolText: "второй",
|
||||||
|
at: date, title: "Заседание", in: root)
|
||||||
|
|
||||||
|
#expect(first.directory != second.directory)
|
||||||
|
#expect(try Data(contentsOf: first.audio) == Data(contentsOf: firstAudio))
|
||||||
|
#expect(try String(contentsOf: first.transcript, encoding: .utf8) == "первый")
|
||||||
|
#expect(try Data(contentsOf: second.audio) == secondData)
|
||||||
|
#expect(try String(contentsOf: second.transcript, encoding: .utf8) == "второй")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("отказ нового сохранения оставляет старую пару целой и убирает staging")
|
||||||
|
func отказСохраненияНеРазрушаетАрхив() throws {
|
||||||
|
let root = try sandbox()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
let audio = try fakeAudio(in: root)
|
||||||
|
let date = Date(timeIntervalSince1970: 1_757_000_000)
|
||||||
|
let saved = try MeetingStore.save(audio: audio, protocolText: "сохранённый протокол",
|
||||||
|
at: date, title: "Встреча", in: root)
|
||||||
|
let missing = root.appendingPathComponent("missing.wav")
|
||||||
|
|
||||||
|
#expect(throws: (any Error).self) {
|
||||||
|
try MeetingStore.save(audio: missing, protocolText: "не сохранится",
|
||||||
|
at: date, title: "Встреча", in: root)
|
||||||
|
}
|
||||||
|
#expect(try Data(contentsOf: saved.audio) == Data(contentsOf: audio))
|
||||||
|
#expect(try String(contentsOf: saved.transcript, encoding: .utf8) == "сохранённый протокол")
|
||||||
|
let children = try FileManager.default.contentsOfDirectory(
|
||||||
|
at: MeetingStore.meetingsDirectory(in: root), includingPropertiesForKeys: nil)
|
||||||
|
#expect(children.map { $0.resolvingSymlinksInPath().path }
|
||||||
|
== [saved.directory.resolvingSymlinksInPath().path])
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,186 @@
|
|||||||
|
import Foundation
|
||||||
|
import IrizCore
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@testable import IrizDictate
|
||||||
|
|
||||||
|
@Suite("Подготовка и восстановление модели без сети")
|
||||||
|
struct SpeechModelRecoveryTests {
|
||||||
|
@Test("сетевые ошибки установки объясняют причину и действие без технического кода")
|
||||||
|
func installErrorsExplainRecovery() {
|
||||||
|
let cases: [(URLError.Code, String, String)] = [
|
||||||
|
(.notConnectedToInternet, "speechModel.error.offline", "Нет подключения к интернету. Подключись к сети и повтори скачивание."),
|
||||||
|
(.networkConnectionLost, "speechModel.error.connectionLost", "Соединение прервалось. Проверь интернет и повтори скачивание."),
|
||||||
|
(.timedOut, "speechModel.error.timeout", "Сервер не ответил вовремя. Повтори скачивание чуть позже."),
|
||||||
|
(.cancelled, "speechModel.error.cancelled", "Скачивание отменено. Его можно запустить снова.")
|
||||||
|
]
|
||||||
|
for (code, key, fallback) in cases {
|
||||||
|
let message = speechModelInstallFailureMessage(for: URLError(code))
|
||||||
|
#expect(message == L(key, fallback))
|
||||||
|
#expect(!message.contains("NSURLErrorDomain"))
|
||||||
|
}
|
||||||
|
#expect(speechModelInstallFailureMessage(for: CancellationError())
|
||||||
|
== speechModelInstallFailureMessage(for: URLError(.cancelled)))
|
||||||
|
let unknown = NSError(domain: "fixture", code: 42,
|
||||||
|
userInfo: [NSLocalizedDescriptionKey: "Подробности отказа"])
|
||||||
|
#expect(speechModelInstallFailureMessage(for: unknown) == "Подробности отказа")
|
||||||
|
}
|
||||||
|
|
||||||
|
private func sandbox() throws -> URL {
|
||||||
|
let root = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("iriz-model-recovery-" + UUID().uuidString, isDirectory: true)
|
||||||
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("пустая или неполная папка не означает установленную модель")
|
||||||
|
func cacheRequiresEveryModelFile() throws {
|
||||||
|
let root = try sandbox()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
#expect(!speechModelCacheIsComplete(for: .multilingualV3, at: root))
|
||||||
|
for file in ModelIntegrity.parakeetV3DownloadFiles {
|
||||||
|
let target = root.appendingPathComponent(file.relativePath)
|
||||||
|
try FileManager.default.createDirectory(at: target.deletingLastPathComponent(),
|
||||||
|
withIntermediateDirectories: true)
|
||||||
|
try Data("fixture".utf8).write(to: target)
|
||||||
|
}
|
||||||
|
// Быстрый UI-probe проверяет состав. SHA-256 проверяется отдельно.
|
||||||
|
#expect(speechModelCacheIsComplete(for: .multilingualV3, at: root))
|
||||||
|
let vocabulary = root.appendingPathComponent("parakeet_vocab.json")
|
||||||
|
try Data().write(to: vocabulary)
|
||||||
|
#expect(!speechModelCacheIsComplete(for: .multilingualV3, at: root))
|
||||||
|
try FileManager.default.removeItem(at: vocabulary)
|
||||||
|
#expect(!speechModelCacheIsComplete(for: .multilingualV3, at: root))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("Whisper требует непустой файл, каталог с именем модели не подходит")
|
||||||
|
func whisperRequiresNonemptyFile() throws {
|
||||||
|
let root = try sandbox()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
let model = root.appendingPathComponent("ggml-large-v3-turbo.bin")
|
||||||
|
try FileManager.default.createDirectory(at: model, withIntermediateDirectories: false)
|
||||||
|
#expect(!speechModelCacheIsComplete(for: .whisperTurbo, at: root))
|
||||||
|
try FileManager.default.removeItem(at: model)
|
||||||
|
try Data().write(to: model)
|
||||||
|
#expect(!speechModelCacheIsComplete(for: .whisperTurbo, at: root))
|
||||||
|
try Data("fixture".utf8).write(to: model)
|
||||||
|
#expect(speechModelCacheIsComplete(for: .whisperTurbo, at: root))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("адреса скачивания ограничены файлами закреплённого манифеста")
|
||||||
|
func downloadsUsePinnedAllowlist() throws {
|
||||||
|
for file in ModelIntegrity.parakeetV3DownloadFiles {
|
||||||
|
let url = try speechModelDownloadURL(for: file)
|
||||||
|
#expect(url.scheme == "https")
|
||||||
|
#expect(url.host == "huggingface.co")
|
||||||
|
#expect(url.path.contains("/resolve/" + ModelIntegrity.parakeetV3RepositoryCommit + "/"))
|
||||||
|
#expect(!url.path.contains("/resolve/main/"))
|
||||||
|
}
|
||||||
|
#expect(throws: URLError.self) {
|
||||||
|
try speechModelDownloadURL(for: ModelFileDigest(relativePath: "../outside.bin",
|
||||||
|
sha256: String(repeating: "0", count: 64)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("публикация новой модели сохраняет предыдущую копию")
|
||||||
|
func publicationKeepsPreviousCache() throws {
|
||||||
|
let root = try sandbox()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
let cache = root.appendingPathComponent("cache", isDirectory: true)
|
||||||
|
let staging = root.appendingPathComponent("staging", isDirectory: true)
|
||||||
|
for url in [cache, staging] {
|
||||||
|
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
|
||||||
|
}
|
||||||
|
try Data("previous".utf8).write(to: cache.appendingPathComponent("model"))
|
||||||
|
try Data("new".utf8).write(to: staging.appendingPathComponent("model"))
|
||||||
|
try publishSpeechModelCache(from: staging, to: cache)
|
||||||
|
#expect(try String(contentsOf: cache.appendingPathComponent("model"), encoding: .utf8) == "new")
|
||||||
|
let backups = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
|
||||||
|
.filter { $0.lastPathComponent.hasPrefix(".iriz-model-backup-") }
|
||||||
|
let backup = try #require(backups.first)
|
||||||
|
#expect(backups.count == 1)
|
||||||
|
#expect(try String(contentsOf: backup.appendingPathComponent("model"), encoding: .utf8) == "previous")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("отказ публикации возвращает предыдущую модель на прежнее место")
|
||||||
|
func failedPublicationRestoresCache() throws {
|
||||||
|
let root = try sandbox()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
let cache = root.appendingPathComponent("cache", isDirectory: true)
|
||||||
|
try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: true)
|
||||||
|
try Data("previous".utf8).write(to: cache.appendingPathComponent("model"))
|
||||||
|
#expect(throws: (any Error).self) {
|
||||||
|
try publishSpeechModelCache(from: root.appendingPathComponent("missing"), to: cache)
|
||||||
|
}
|
||||||
|
#expect(try String(contentsOf: cache.appendingPathComponent("model"), encoding: .utf8) == "previous")
|
||||||
|
let entries = try FileManager.default.contentsOfDirectory(atPath: root.path)
|
||||||
|
#expect(entries == ["cache"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("после установки можно повторить неудачный прогрев без записи и изменения настроек")
|
||||||
|
func failedPreparationCanRetry() async {
|
||||||
|
let name = "iriz-model-preparation-" + UUID().uuidString
|
||||||
|
let defaults = UserDefaults(suiteName: name)!
|
||||||
|
defer { removeSuiteFile(named: name, defaults: defaults) }
|
||||||
|
let settings = DictationSettings(defaults: defaults)
|
||||||
|
settings.speechEngine = .multilingualV3
|
||||||
|
let probe = ModelPreparationProbe()
|
||||||
|
let controller = DictationController(settings: settings,
|
||||||
|
insertionStats: InsertionStats(defaults: defaults),
|
||||||
|
modelLoader: { try await probe.load($0) })
|
||||||
|
#expect(controller.prepareAfterModelInstallation())
|
||||||
|
#expect(controller.state == .warmingUp)
|
||||||
|
#expect(!controller.prepareAfterModelInstallation())
|
||||||
|
await controller.pendingWarmUp?.value
|
||||||
|
guard case .unavailable = controller.state else {
|
||||||
|
Issue.record("Первый отказ загрузчика должен оставаться видимым")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(controller.prepareAfterModelInstallation())
|
||||||
|
#expect(controller.state == .warmingUp)
|
||||||
|
await controller.pendingWarmUp?.value
|
||||||
|
#expect(controller.state == .ready)
|
||||||
|
#expect(!controller.isRecordingActive)
|
||||||
|
#expect(settings.speechEngine == .multilingualV3)
|
||||||
|
#expect(await probe.profiles == [.multilingualV3, .multilingualV3])
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Test("сохранённый выбор установленного движка восстанавливает unavailable без перезапуска")
|
||||||
|
func changingEngineRetriesPreparation() async {
|
||||||
|
let name = "iriz-model-selection-" + UUID().uuidString
|
||||||
|
let defaults = UserDefaults(suiteName: name)!
|
||||||
|
defer { removeSuiteFile(named: name, defaults: defaults) }
|
||||||
|
let settings = DictationSettings(defaults: defaults)
|
||||||
|
settings.speechEngine = .whisperTurbo
|
||||||
|
let probe = ModelPreparationProbe()
|
||||||
|
let controller = DictationController(settings: settings,
|
||||||
|
insertionStats: InsertionStats(defaults: defaults),
|
||||||
|
modelLoader: { try await probe.load($0) })
|
||||||
|
#expect(controller.prepareAfterModelInstallation())
|
||||||
|
await controller.pendingWarmUp?.value
|
||||||
|
guard case .unavailable = controller.state else {
|
||||||
|
Issue.record("Первый отказ должен быть видимым")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
settings.speechEngine = .multilingualV3
|
||||||
|
controller.applySettings()
|
||||||
|
#expect(controller.state == .warmingUp)
|
||||||
|
await controller.pendingWarmUp?.value
|
||||||
|
#expect(controller.state == .ready)
|
||||||
|
#expect(await probe.profiles == [.whisperTurbo, .multilingualV3])
|
||||||
|
#expect(!controller.isRecordingActive)
|
||||||
|
controller.applySettings()
|
||||||
|
#expect(controller.pendingWarmUp == nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private actor ModelPreparationProbe {
|
||||||
|
private(set) var profiles: [SpeechModelProfile] = []
|
||||||
|
|
||||||
|
func load(_ profile: SpeechModelProfile) throws {
|
||||||
|
profiles.append(profile)
|
||||||
|
if profiles.count == 1 { throw URLError(.cannotOpenFile) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import Foundation
|
||||||
|
import IrizDictate
|
||||||
|
import Testing
|
||||||
|
@testable import IrizSettings
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("File transcription UI: safe queue and output")
|
||||||
|
struct SettingsFileTranscriptionTests {
|
||||||
|
@Test func preservesExistingTextAndWritesOnlyCompletePrivateResults() throws {
|
||||||
|
let root = try temporaryDirectory()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
let existing = root.appendingPathComponent("existing.txt")
|
||||||
|
try Data("owner text".utf8).write(to: existing)
|
||||||
|
#expect(throws: AudioBatchPlanError.destinationExists(existing.path)) {
|
||||||
|
try SettingsFileTranscription.saveTranscript("new text", to: existing)
|
||||||
|
}
|
||||||
|
#expect(try String(contentsOf: existing, encoding: .utf8) == "owner text")
|
||||||
|
|
||||||
|
let output = root.appendingPathComponent("result.txt")
|
||||||
|
#expect(throws: (any Error).self) {
|
||||||
|
try SettingsFileTranscription.saveTranscript(" \n ", to: output)
|
||||||
|
}
|
||||||
|
#expect(!FileManager.default.fileExists(atPath: output.path))
|
||||||
|
try SettingsFileTranscription.saveTranscript(" Complete text.\n", to: output)
|
||||||
|
#expect(try String(contentsOf: output, encoding: .utf8) == "Complete text.\n")
|
||||||
|
let attributes = try FileManager.default.attributesOfItem(atPath: output.path)
|
||||||
|
#expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o600)
|
||||||
|
#expect(try !FileManager.default.contentsOfDirectory(atPath: root.path)
|
||||||
|
.contains { $0.hasPrefix(".iriz-transcript-") })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func preventsDoubleSubmitAndRetriesOnlyFailedFiles() async throws {
|
||||||
|
let root = try temporaryDirectory()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
let first = try source("first.wav", in: root)
|
||||||
|
let second = try source("second.wav", in: root)
|
||||||
|
let attempts = Attempts()
|
||||||
|
let model = SettingsFileTranscription { job, _, language, progress in
|
||||||
|
let fail = await attempts.record(job.source, language: language)
|
||||||
|
await progress("test", 0.5)
|
||||||
|
if fail { throw CocoaError(.fileReadCorruptFile) }
|
||||||
|
try SettingsFileTranscription.saveTranscript("test transcript", to: job.destination)
|
||||||
|
}
|
||||||
|
model.queue = [first, second]
|
||||||
|
let task = model.start(engine: .whisperLargeV3, language: .english)
|
||||||
|
#expect(model.busy)
|
||||||
|
#expect(model.start(engine: .multilingualV3, language: .russian) == nil)
|
||||||
|
await task?.value
|
||||||
|
#expect(!model.busy)
|
||||||
|
#expect(model.queue == [second])
|
||||||
|
#expect(model.results.map(\.source) == [first.url])
|
||||||
|
#expect(model.errors[second.id] != nil)
|
||||||
|
#expect(model.progress == nil)
|
||||||
|
#expect(model.fraction == nil)
|
||||||
|
|
||||||
|
await model.start(engine: .whisperLargeV3, language: .english)?.value
|
||||||
|
#expect(model.queue.isEmpty)
|
||||||
|
#expect(model.errors.isEmpty)
|
||||||
|
#expect(model.results.map(\.source) == [first.url, second.url])
|
||||||
|
#expect(await attempts.sources == [first.url, second.url, second.url])
|
||||||
|
#expect(await attempts.languages == [.english, .english, .english])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func stopFinishesCurrentFileAndKeepsRemainingQueue() async throws {
|
||||||
|
let root = try temporaryDirectory()
|
||||||
|
defer { try? FileManager.default.removeItem(at: root) }
|
||||||
|
let first = try source("first.wav", in: root)
|
||||||
|
let second = try source("second.wav", in: root)
|
||||||
|
let started = AsyncStream<Void>.makeStream()
|
||||||
|
let resume = AsyncStream<Void>.makeStream()
|
||||||
|
let model = SettingsFileTranscription { job, _, _, _ in
|
||||||
|
started.continuation.yield(())
|
||||||
|
for await _ in resume.stream { break }
|
||||||
|
try SettingsFileTranscription.saveTranscript("finished", to: job.destination)
|
||||||
|
}
|
||||||
|
model.queue = [first, second]
|
||||||
|
let task = model.start(engine: .multilingualV3, language: .auto)
|
||||||
|
for await _ in started.stream { break }
|
||||||
|
model.stopAfterCurrent()
|
||||||
|
resume.continuation.yield(())
|
||||||
|
await task?.value
|
||||||
|
started.continuation.finish()
|
||||||
|
resume.continuation.finish()
|
||||||
|
#expect(model.queue == [second])
|
||||||
|
#expect(model.results.map(\.source) == [first.url])
|
||||||
|
#expect(model.stopping)
|
||||||
|
#expect(!model.busy)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func rejectsRemoteURLsBeforeAVFoundation() {
|
||||||
|
#expect(!irizDropAccepts(URL(string: "https://example.com/voice.wav")!, extensions: ["wav"]))
|
||||||
|
#expect(irizDropAccepts(URL(fileURLWithPath: "/tmp/voice.WAV"), extensions: ["wav"]))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func temporaryDirectory() throws -> URL {
|
||||||
|
let root = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("iriz-file-ui-tests-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
private func source(_ name: String, in root: URL) throws -> IrizDropItem {
|
||||||
|
let url = root.appendingPathComponent(name)
|
||||||
|
// Только имена и очередь: ASR и декодер тесты не вызывают.
|
||||||
|
try Data("fixture".utf8).write(to: url)
|
||||||
|
return IrizDropItem(url: url, bytes: 7)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private actor Attempts {
|
||||||
|
var sources: [URL] = []
|
||||||
|
var languages: [DictationLanguage] = []
|
||||||
|
func record(_ source: URL, language: DictationLanguage) -> Bool {
|
||||||
|
sources.append(source)
|
||||||
|
languages.append(language)
|
||||||
|
return source.lastPathComponent == "second.wav" && sources.filter { $0 == source }.count == 1
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -305,6 +305,12 @@ struct SettingsModelTests {
|
|||||||
model.addCorrection(source: "a", replacement: "b")
|
model.addCorrection(source: "a", replacement: "b")
|
||||||
model.promptModeEnabled = true
|
model.promptModeEnabled = true
|
||||||
model.promptRecipient = .generic
|
model.promptRecipient = .generic
|
||||||
|
model.retentionDays = 0
|
||||||
|
model.hudShowsHints = true
|
||||||
|
model.hudSize = .large
|
||||||
|
model.promptGuidanceInstructions = "Собирай короткий план"
|
||||||
|
model.promptGuidanceExamples = [PromptUserExample(spoken: "проверь", wanted: "Проверь проект")]
|
||||||
|
model.speechEngine = .whisperTurbo
|
||||||
model.codexPath = "/custom/codex"
|
model.codexPath = "/custom/codex"
|
||||||
model.setHotkey(recordableHotkeyChoice(forKeycode: 97, modifiers: .maskCommand)!, for: .prompt)
|
model.setHotkey(recordableHotkeyChoice(forKeycode: 97, modifiers: .maskCommand)!, for: .prompt)
|
||||||
fixture.dictationSettings.promptOnboardingOffered = true
|
fixture.dictationSettings.promptOnboardingOffered = true
|
||||||
@@ -316,6 +322,17 @@ struct SettingsModelTests {
|
|||||||
#expect(model.layoutMode == .fixing)
|
#expect(model.layoutMode == .fixing)
|
||||||
#expect(model.launchAtLogin)
|
#expect(model.launchAtLogin)
|
||||||
#expect(model.corrections.isEmpty)
|
#expect(model.corrections.isEmpty)
|
||||||
|
#expect(model.retentionDays == DICTATION_RETENTION_DEFAULT_DAYS)
|
||||||
|
#expect(!model.hudShowsHints)
|
||||||
|
#expect(model.hudSize == DICTATION_HUD_DEFAULT_SIZE)
|
||||||
|
#expect(model.promptGuidanceInstructions.isEmpty)
|
||||||
|
#expect(model.promptGuidanceExamples.isEmpty)
|
||||||
|
#expect(model.speechEngine == .multilingualV3)
|
||||||
|
#expect(fixture.dictationSettings.speechEngine == .multilingualV3)
|
||||||
|
#expect(fixture.dictationSettings.dictationRetentionDays == DICTATION_RETENTION_DEFAULT_DAYS)
|
||||||
|
#expect(!fixture.dictationSettings.dictationHUDShowsHints)
|
||||||
|
#expect(fixture.dictationSettings.dictationHUDSize == DICTATION_HUD_DEFAULT_SIZE)
|
||||||
|
#expect(fixture.dictationSettings.promptUserGuidance == .none)
|
||||||
#expect(!model.promptModeEnabled)
|
#expect(!model.promptModeEnabled)
|
||||||
#expect(model.promptRecipient == .codex)
|
#expect(model.promptRecipient == .codex)
|
||||||
#expect(model.codexPath.isEmpty)
|
#expect(model.codexPath.isEmpty)
|
||||||
@@ -439,6 +456,30 @@ struct SettingsModelTests {
|
|||||||
#expect(model.save())
|
#expect(model.save())
|
||||||
#expect(fixture.launchAtLogin)
|
#expect(fixture.launchAtLogin)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func modelReadinessTracksSelectedEngineAndInstallationKeepsOtherDrafts() {
|
||||||
|
let fixture = Fixture()
|
||||||
|
fixture.dictationSettings.speechEngine = .whisperTurbo
|
||||||
|
let model = fixture.makeModel(speechModelProbe: { $0 == .multilingualV3 })
|
||||||
|
#expect(!model.speechModelInstalled)
|
||||||
|
#expect(model.canUseInstalledParakeet)
|
||||||
|
model.speechEngine = .multilingualV3
|
||||||
|
#expect(model.speechModelInstalled)
|
||||||
|
#expect(!model.canUseInstalledParakeet)
|
||||||
|
model.speechEngine = .whisperLargeV3
|
||||||
|
#expect(!model.speechModelInstalled)
|
||||||
|
|
||||||
|
model.enterDelayText = "987"
|
||||||
|
model.promptGuidanceInstructions = "Unsaved user draft"
|
||||||
|
let savedDelay = fixture.dictationSettings.enterDelayMilliseconds
|
||||||
|
model.applyInstalledSpeechModel(.multilingualV3)
|
||||||
|
#expect(model.speechEngine == .multilingualV3)
|
||||||
|
#expect(model.speechModelInstalled)
|
||||||
|
#expect(model.enterDelayText == "987")
|
||||||
|
#expect(model.promptGuidanceInstructions == "Unsaved user draft")
|
||||||
|
#expect(fixture.dictationSettings.enterDelayMilliseconds == savedDelay)
|
||||||
|
#expect(fixture.dictationSettings.speechEngine == .whisperTurbo)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
@@ -462,7 +503,8 @@ private final class Fixture {
|
|||||||
func makeModel(
|
func makeModel(
|
||||||
codexDetector: @escaping (String) -> URL? = {
|
codexDetector: @escaping (String) -> URL? = {
|
||||||
DictationSettings.detectCodexExecutable(storedPath: $0)
|
DictationSettings.detectCodexExecutable(storedPath: $0)
|
||||||
}
|
},
|
||||||
|
speechModelProbe: @escaping (SpeechModelProfile) -> Bool = { _ in false }
|
||||||
) -> SettingsModel {
|
) -> SettingsModel {
|
||||||
SettingsModel(
|
SettingsModel(
|
||||||
dictationSettings: dictationSettings,
|
dictationSettings: dictationSettings,
|
||||||
@@ -473,7 +515,9 @@ private final class Fixture {
|
|||||||
writeLaunchAtLogin: { self.launchAtLogin = $0 }
|
writeLaunchAtLogin: { self.launchAtLogin = $0 }
|
||||||
),
|
),
|
||||||
layoutHotkeys: .settings(layoutHotkeySettings),
|
layoutHotkeys: .settings(layoutHotkeySettings),
|
||||||
codexDetector: codexDetector
|
codexDetector: codexDetector,
|
||||||
|
installedSpeechEngine: { .multilingualV3 },
|
||||||
|
speechModelProbe: speechModelProbe
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,10 +8,10 @@ Hello. I am Fil, a lawyer who vibe-codes, and I wrote iriz.
|
|||||||
|
|
||||||
From here an agent takes over. It will tell you what it is about to do BEFORE it does it, and
|
From here an agent takes over. It will tell you what it is about to do BEFORE it does it, and
|
||||||
name the price of every step: what appears on the disk, where the time goes, where you have a
|
name the price of every step: what appears on the disk, where the time goes, where you have a
|
||||||
choice. If something does not suit you, say so right in the chat — a step can be skipped.
|
choice. If something does not suit you, say so right in the chat. A step can be skipped.
|
||||||
|
|
||||||
One promise this whole thing was built for: the audio of your speech never leaves the machine.
|
One promise this whole thing was built for: the audio of your speech never leaves the machine.
|
||||||
The single trip to the network is the speech model download, and you start it with a button.
|
You download the speech model over the network by pressing a button.
|
||||||
|
|
||||||
<!-- owner-greeting:end -->
|
<!-- owner-greeting:end -->
|
||||||
|
|
||||||
@@ -55,35 +55,49 @@ dependencies (about 300 MB into `.build`) and puts the finished app into `/Appli
|
|||||||
|
|
||||||
**What you get:** an icon in the menu bar at the top right, and the welcome window.
|
**What you get:** an icon in the menu bar at the top right, and the welcome window.
|
||||||
|
|
||||||
**Fork:** if you would rather not hand over `/Applications`, say so — we build into the project
|
**Fork:** if you would rather not hand over `/Applications`, say so. We build into the project
|
||||||
folder and run it from there.
|
folder and run it from there.
|
||||||
|
|
||||||
## Step 4: grant the permissions and download the model
|
## Step 4: download the model and grant permissions
|
||||||
|
|
||||||
**What I do:** walk you through three macOS permissions — microphone, Accessibility, Input
|
**What I do:** take you to the second step of the welcome window, right after the greeting.
|
||||||
Monitoring — and start the speech model download.
|
Click "Download and install Parakeet". iriz downloads about 500 MB, installs the model and
|
||||||
|
selects it for recognition. The window shows progress; download time depends on your connection.
|
||||||
|
While it runs, you can click "Next" and grant the macOS permissions.
|
||||||
|
|
||||||
**Why:** without the microphone there is nothing to hear, without Accessibility there is
|
**Why:** dictation needs a model. The microphone lets iriz hear you, Accessibility lets it
|
||||||
nowhere to paste, without Input Monitoring the key is not heard at all. The model is the half
|
paste text, and Input Monitoring lets it hear the hotkey. After installation, recognition
|
||||||
a gigabyte for which the app goes online exactly once.
|
runs on your Mac without an internet connection.
|
||||||
|
|
||||||
**What changes on disk:** the model lands in `~/Library/Application Support/iriz/Models`. The
|
**What changes on disk:** the model lands in
|
||||||
permissions are written into the macOS database, not into the app.
|
`~/Library/Application Support/FluidAudio/Models/parakeet-tdt-0.6b-v3`.
|
||||||
|
You do not need to move files yourself. macOS stores the permissions in its system database,
|
||||||
|
not in the app.
|
||||||
|
|
||||||
**What you get:** working dictation. Press the key, say a sentence, press again — the text
|
**Fork:** "Download later" skips the download. To return, open Settings → Dictation →
|
||||||
lands where the cursor was blinking.
|
"Download Parakeet model…". The trial step also has a "Set up the model" button when the model
|
||||||
|
is missing. If the download fails, read the reason in the window and click "Try again" after
|
||||||
|
addressing it. We wait for the model before trying dictation.
|
||||||
|
|
||||||
|
**What you get:** once the model is installed and permissions are granted, we test dictation
|
||||||
|
in the welcome window. Press the key, say a sentence, press again. The text appears in the
|
||||||
|
trial field.
|
||||||
|
|
||||||
## Step 5: check that it is all honest
|
## Step 5: check that it is all honest
|
||||||
|
|
||||||
**What I do:** run the project gates and show you their whole output.
|
**What I do:** after the model download, run the tests and project gates, show you the output
|
||||||
|
and point out any skipped checks.
|
||||||
|
|
||||||
**Why:** the promise «the audio never leaves the machine» is checked by an instrument, not by a
|
**Why:** the network gate compares the built binary's networking symbols with a baseline.
|
||||||
paragraph in the README. The gate kicks the set of networking symbols in the built binary and
|
If the app is running from `/Applications`, it also checks its open sockets at that moment.
|
||||||
asks the kernel whether the running app holds a single open socket.
|
Otherwise it skips that check. A snapshot cannot prove the app has never connected to the
|
||||||
|
network; connections are expected during a model download.
|
||||||
|
|
||||||
**What changes on disk:** nothing. The gates only read and count.
|
**What changes on disk:** tests update `.build` and write logs. The gates also clean up their
|
||||||
|
temporary test files.
|
||||||
|
|
||||||
**What you get:** a green report you saw with your own eyes instead of taking on trust.
|
**What you get:** a report of the checks that ran. Failures and skipped checks stay in the
|
||||||
|
report; they do not become a promise that everything works.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash scripts/verify.sh && bash scripts/offline_binary_gate.sh
|
bash scripts/verify.sh && bash scripts/offline_binary_gate.sh
|
||||||
|
|||||||
@@ -6,40 +6,40 @@
|
|||||||
|
|
||||||
Привет. Я Фил, юрист и вайб-кодер, и это я написал iriz.
|
Привет. Я Фил, юрист и вайб-кодер, и это я написал iriz.
|
||||||
|
|
||||||
Дальше вами займется агент. Он будет говорить, что делает, ДО того как сделает, и называть цену
|
Дальше тобой займется агент. Он будет говорить, что делает, ДО того как сделает, и называть цену
|
||||||
каждого шага: что появится на диске, куда уйдет время, где у вас есть выбор. Если что-то из
|
каждого шага: что появится на диске, куда уйдет время, где у тебя есть выбор. Если что-то из
|
||||||
сказанного вам не подходит — скажите об этом прямо в чате, шаг можно пропустить.
|
сказанного тебе не подходит, скажи об этом прямо в чате, шаг можно пропустить.
|
||||||
|
|
||||||
Одно обещание, ради которого все затевалось: звук вашей речи не уходит с машины. Единственный
|
Одно обещание, ради которого все затевалось: звук твоей речи не уходит с машины. Модель
|
||||||
поход в сеть — скачивание модели распознавания, и запускаете его вы кнопкой.
|
распознавания скачивается по сети, и запускаешь загрузку ты кнопкой.
|
||||||
|
|
||||||
<!-- owner-greeting:end -->
|
<!-- owner-greeting:end -->
|
||||||
|
|
||||||
## Шаг 1: смотрим, на чем вы запускаете
|
## Шаг 1: смотрим, на чем ты запускаешь
|
||||||
|
|
||||||
**Что я делаю:** проверяю версию macOS, процессор и наличие Xcode со Swift 6.
|
**Что я делаю:** проверяю версию macOS, процессор и наличие Xcode со Swift 6.
|
||||||
|
|
||||||
**Зачем:** iriz живет на macOS 14 и новее. Стеклянная плашка и настоящий Liquid Glass — это
|
**Зачем:** iriz живет на macOS 14 и новее. Стеклянная плашка и настоящий Liquid Glass требуют
|
||||||
macOS 26; на 14 и 15 приложение работает, но плашка рисуется прежним способом. Знать это лучше
|
macOS 26; на 14 и 15 приложение работает, но плашка рисуется прежним способом. Знать это лучше
|
||||||
сейчас, чем после сборки.
|
сейчас, чем после сборки.
|
||||||
|
|
||||||
**Что меняется на диске:** ничего. Это чтение.
|
**Что меняется на диске:** ничего. Это чтение.
|
||||||
|
|
||||||
**Что вы получите:** ответ, пойдет ли дальше, и на какой ветке визуала вы окажетесь.
|
**Что ты получишь:** ответ, пойдет ли дальше, и на какой ветке визуала ты окажешься.
|
||||||
|
|
||||||
**Развилка:** нет Xcode — не беда. Возьмите готовый образ со страницы Releases, и шаги про
|
**Развилка:** нет Xcode, не беда. Возьми готовый образ со страницы Releases, и шаги про
|
||||||
сборку мы пропустим.
|
сборку мы пропустим.
|
||||||
|
|
||||||
## Шаг 2: приносим исходники
|
## Шаг 2: приносим исходники
|
||||||
|
|
||||||
**Что я делаю:** клонирую репозиторий в папку, которую вы назовете, или распаковываю ZIP.
|
**Что я делаю:** клонирую репозиторий в папку, которую ты назовешь, или распаковываю ZIP.
|
||||||
|
|
||||||
**Зачем:** дальше все делается внутри этой папки, и она должна быть там, где вам удобно ее
|
**Зачем:** дальше все делается внутри этой папки, и она должна быть там, где тебе удобно ее
|
||||||
потом найти.
|
потом найти.
|
||||||
|
|
||||||
**Что меняется на диске:** появляется одна папка, около 40 МБ. Больше ничего никуда не пишется.
|
**Что меняется на диске:** появляется одна папка, около 40 МБ. Больше ничего никуда не пишется.
|
||||||
|
|
||||||
**Что вы получите:** дерево проекта, в котором видно `Sources`, `Tests`, `scripts` и `docs`.
|
**Что ты получишь:** дерево проекта, в котором видно `Sources`, `Tests`, `scripts` и `docs`.
|
||||||
|
|
||||||
## Шаг 3: собираем приложение
|
## Шаг 3: собираем приложение
|
||||||
|
|
||||||
@@ -47,43 +47,56 @@ macOS 26; на 14 и 15 приложение работает, но плашка
|
|||||||
`bash install.sh --build`.
|
`bash install.sh --build`.
|
||||||
|
|
||||||
**Зачем:** без флага установщик ничего не ставит. Он рассказывает, что это за программа,
|
**Зачем:** без флага установщик ничего не ставит. Он рассказывает, что это за программа,
|
||||||
смотрит, чего не хватает на машине, и гоняет самопроверку дерева. Это ваша возможность
|
смотрит, чего не хватает на машине, и гоняет самопроверку дерева. Это твоя возможность
|
||||||
остановиться до того, как что-то произойдет.
|
остановиться до того, как что-то произойдет.
|
||||||
|
|
||||||
**Что меняется на диске:** первая команда не меняет ничего. Вторая тянет зависимости Swift
|
**Что меняется на диске:** первая команда не меняет ничего. Вторая тянет зависимости Swift
|
||||||
(около 300 МБ в `.build`) и кладет готовое приложение в `/Applications`.
|
(около 300 МБ в `.build`) и кладет готовое приложение в `/Applications`.
|
||||||
|
|
||||||
**Что вы получите:** значок в строке меню наверху справа и окно знакомства.
|
**Что ты получишь:** значок в строке меню наверху справа и окно знакомства.
|
||||||
|
|
||||||
**Развилка:** не хотите отдавать `/Applications` — скажите, соберем в папку проекта и запустим
|
**Развилка:** не хочешь отдавать `/Applications`, скажи, соберем в папку проекта и запустим
|
||||||
оттуда.
|
оттуда.
|
||||||
|
|
||||||
## Шаг 4: выдаем разрешения и качаем модель
|
## Шаг 4: скачиваем модель и выдаем разрешения
|
||||||
|
|
||||||
**Что я делаю:** веду вас по трем разрешениям macOS — микрофон, Универсальный доступ,
|
**Что я делаю:** веду тебя ко второму шагу окна знакомства, сразу после приветствия.
|
||||||
Мониторинг ввода — и запускаю скачивание модели распознавания.
|
Здесь ты нажимаешь «Скачать и установить Parakeet». iriz сам скачает около 500 МБ, установит
|
||||||
|
модель и выберет ее для распознавания. Ход загрузки виден в окне; время зависит от соединения.
|
||||||
|
Пока она идет, можно нажать «Дальше» и заняться разрешениями macOS.
|
||||||
|
|
||||||
**Зачем:** без микрофона нечего слушать, без Универсального доступа некуда вставить текст, без
|
**Зачем:** без модели диктовка не работает. Микрофон нужен, чтобы слышать тебя, Универсальный
|
||||||
Мониторинга ввода не слышно клавишу. Модель — это те самые полгигабайта, ради которых
|
доступ нужен для вставки текста, Мониторинг ввода для горячей клавиши. После установки
|
||||||
приложение один раз идет в сеть.
|
распознавание работает на твоем Маке без интернета.
|
||||||
|
|
||||||
**Что меняется на диске:** модель ложится в `~/Library/Application Support/iriz/Models`.
|
**Что меняется на диске:** модель ложится в
|
||||||
Разрешения записываются в системную базу macOS, а не в приложение.
|
`~/Library/Application Support/FluidAudio/Models/parakeet-tdt-0.6b-v3`.
|
||||||
|
Файлы вручную переносить не нужно. Разрешения записываются в системную базу macOS,
|
||||||
|
а не в приложение.
|
||||||
|
|
||||||
**Что вы получите:** рабочую диктовку. Нажали клавишу, сказали фразу, нажали еще раз — текст
|
**Развилка:** «Скачать позже» пропускает загрузку. Вернуться можно из настроек:
|
||||||
встал туда, где мигал курсор.
|
«Диктовка» → «Скачать модель Parakeet…». На шаге пробы без модели тоже есть кнопка
|
||||||
|
«К установке модели». Если загрузка завершилась ошибкой, прочитай причину в окне и нажми
|
||||||
|
«Попробовать снова» после ее устранения. Без модели пробу не начинаем.
|
||||||
|
|
||||||
|
**Что ты получишь:** после установки модели и выдачи разрешений проверим диктовку в окне
|
||||||
|
знакомства. Нажми клавишу, скажи фразу, нажми еще раз. Текст появится в поле пробы.
|
||||||
|
|
||||||
## Шаг 5: проверяем, что все честно
|
## Шаг 5: проверяем, что все честно
|
||||||
|
|
||||||
**Что я делаю:** прогоняю ворота проекта и показываю вам их вывод целиком.
|
**Что я делаю:** после загрузки модели запускаю тесты и ворота проекта, показываю тебе вывод
|
||||||
|
и отмечаю пропущенные проверки.
|
||||||
|
|
||||||
**Зачем:** обещание «звук не уходит с машины» проверяется прибором, а не абзацем в README.
|
**Зачем:** сетевой гейт сравнивает набор сетевых символов в собранном бинарнике с эталоном.
|
||||||
Ворота пинают набор сетевых символов в собранном бинарнике и спрашивают у ядра, есть ли у
|
Если приложение запущено из `/Applications`, он также смотрит его открытые сокеты в момент
|
||||||
работающего приложения хоть один открытый сокет.
|
проверки. Если не запущено, эта часть пропускается. Такой снимок не доказывает, что приложение
|
||||||
|
никогда не выходило в сеть; во время скачивания модели соединения ожидаемы.
|
||||||
|
|
||||||
**Что меняется на диске:** ничего. Ворота только читают и считают.
|
**Что меняется на диске:** тесты обновляют `.build` и пишут служебные логи. Ворота также
|
||||||
|
убирают временные файлы своих тестов.
|
||||||
|
|
||||||
**Что вы получите:** зеленый отчет, который вы видели своими глазами, а не поверили на слово.
|
**Что ты получишь:** отчет о выполненных проверках. Если есть отказ или пропуск, он останется
|
||||||
|
в отчете, а не превратится в обещание, что все работает.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash scripts/verify.sh && bash scripts/offline_binary_gate.sh
|
bash scripts/verify.sh && bash scripts/offline_binary_gate.sh
|
||||||
|
|||||||
@@ -9,8 +9,8 @@
|
|||||||
接下来由代理带你走。它会在动手之前先说明要做什么,并说清每一步的代价:磁盘上会多出什么、时间花
|
接下来由代理带你走。它会在动手之前先说明要做什么,并说清每一步的代价:磁盘上会多出什么、时间花
|
||||||
在哪里、哪里由你选择。如果哪一步不合适,直接在对话里说,可以跳过。
|
在哪里、哪里由你选择。如果哪一步不合适,直接在对话里说,可以跳过。
|
||||||
|
|
||||||
这件事从头到尾只为一个承诺:你说话的声音不会离开这台机器。唯一一次联网是下载识别模型,而且由你
|
这件事从头到尾只为一个承诺:你说话的声音不会离开这台机器。识别模型需要联网下载,由你按下按钮
|
||||||
按下按钮才开始。
|
才开始。
|
||||||
|
|
||||||
<!-- owner-greeting:end -->
|
<!-- owner-greeting:end -->
|
||||||
|
|
||||||
@@ -52,28 +52,37 @@
|
|||||||
|
|
||||||
**岔路:** 如果你不想动 `/Applications`,说一声,我们就构建到项目文件夹里,从那里运行。
|
**岔路:** 如果你不想动 `/Applications`,说一声,我们就构建到项目文件夹里,从那里运行。
|
||||||
|
|
||||||
## 第 4 步:授予权限并下载模型
|
## 第 4 步:下载模型并授予权限
|
||||||
|
|
||||||
**我在做什么:** 带你过三项 macOS 权限——麦克风、辅助功能、输入监控——然后开始下载识别模型。
|
**我在做什么:** 带你进入欢迎窗口的第二步,就在问候之后。点击“下载并安装 Parakeet”,iriz 会下载
|
||||||
|
约 500 MB 的文件,安装模型并将它选为识别引擎。窗口会显示进度,下载时间取决于网络速度。下载期间
|
||||||
|
可以点“下一步”,继续授予 macOS 权限。
|
||||||
|
|
||||||
**为什么:** 没有麦克风就没有可听的;没有辅助功能,文字没地方粘贴;没有输入监控,按键根本听不
|
**为什么:** 没有模型就无法听写。麦克风让 iriz 听到你说话,辅助功能用于粘贴文字,输入监控用于
|
||||||
到。模型就是那半个 GB,应用一生只为它联网一次。
|
响应快捷键。安装完成后,语音识别在你的 Mac 上运行,不需要联网。
|
||||||
|
|
||||||
**磁盘上会改变什么:** 模型放到 `~/Library/Application Support/iriz/Models`。权限写进 macOS
|
**磁盘上会改变什么:** 模型放到
|
||||||
的系统数据库,不写进应用。
|
`~/Library/Application Support/FluidAudio/Models/parakeet-tdt-0.6b-v3`。
|
||||||
|
你不用手动移动文件。权限写进 macOS 的系统数据库,不写进应用。
|
||||||
|
|
||||||
**你会得到:** 可以用的口述。按键,说一句话,再按一下——文字就落在光标闪烁的地方。
|
**岔路:** “稍后下载”会跳过下载。之后可以从设置 → 口述 →“下载 Parakeet 模型…”返回安装页面。
|
||||||
|
如果模型还没装好,试用步骤也有“前往安装模型”按钮。下载失败时,先看窗口里的原因,处理后再点
|
||||||
|
“重试”。模型装好后,我们再尝试听写。
|
||||||
|
|
||||||
|
**你会得到:** 模型装好、权限授予后,我们在欢迎窗口里测试听写。按键,说一句话,再按一下,文字
|
||||||
|
会出现在试用输入框中。
|
||||||
|
|
||||||
## 第 5 步:验证这一切是不是诚实的
|
## 第 5 步:验证这一切是不是诚实的
|
||||||
|
|
||||||
**我在做什么:** 运行项目的闸门,并把它们的完整输出给你看。
|
**我在做什么:** 模型下载完成后,运行测试和项目闸门,给你看输出,并指出跳过了哪些检查。
|
||||||
|
|
||||||
**为什么:** “声音不会离开这台机器”这个承诺,要由工具来验证,而不是 README 里的一段话。闸门会
|
**为什么:** 网络闸门把构建出的二进制中的网络符号与基准比较。如果应用从 `/Applications` 运行,
|
||||||
在构建出的二进制里踢一遍网络相关符号,并向内核询问运行中的应用有没有打开任何一个套接字。
|
还会查看它在检查那一刻打开的套接字;应用没运行时会跳过这项检查。一次快照不能证明应用从未联网,
|
||||||
|
而下载模型时出现网络连接是正常的。
|
||||||
|
|
||||||
**磁盘上会改变什么:** 什么都不改。闸门只读取和统计。
|
**磁盘上会改变什么:** 测试会更新 `.build` 并写入日志,闸门还会清理自己的临时测试文件。
|
||||||
|
|
||||||
**你会得到:** 一份你亲眼看过的绿色报告,而不是听人保证。
|
**你会得到:** 一份实际检查结果的报告。失败和跳过的检查都会写明,不会被改成“一切正常”的保证。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash scripts/verify.sh && bash scripts/offline_binary_gate.sh
|
bash scripts/verify.sh && bash scripts/offline_binary_gate.sh
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 1.7 MiB After Width: | Height: | Size: 1.7 MiB |
|
Before Width: | Height: | Size: 1.5 MiB After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 1.4 MiB |
|
Before Width: | Height: | Size: 1.4 MiB After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.6 MiB |
|
Before Width: | Height: | Size: 1.5 MiB After Width: | Height: | Size: 1.5 MiB |
|
Before Width: | Height: | Size: 1.5 MiB After Width: | Height: | Size: 1.1 MiB |
|
Before Width: | Height: | Size: 970 KiB After Width: | Height: | Size: 816 KiB |
|
Before Width: | Height: | Size: 1.5 MiB After Width: | Height: | Size: 1.5 MiB |
|
Before Width: | Height: | Size: 1.4 MiB After Width: | Height: | Size: 1.4 MiB |
|
Before Width: | Height: | Size: 1.6 MiB After Width: | Height: | Size: 1.7 MiB |
|
Before Width: | Height: | Size: 1.5 MiB After Width: | Height: | Size: 1.5 MiB |
@@ -59,4 +59,4 @@ fi
|
|||||||
printf 'Собираю. Первая сборка тянет зависимости и занимает несколько минут.\n\n'
|
printf 'Собираю. Первая сборка тянет зависимости и занимает несколько минут.\n\n'
|
||||||
bash scripts/build_app.sh || { printf '\nСборка не удалась.\n\n'; exit 1; }
|
bash scripts/build_app.sh || { printf '\nСборка не удалась.\n\n'; exit 1; }
|
||||||
printf '\nГотово. Значок появится в строке меню.\n'
|
printf '\nГотово. Значок появится в строке меню.\n'
|
||||||
printf 'Модель распознавания приложение скачает само на шаге знакомства.\n\n'
|
printf 'Модель распознавания скачивается по кнопке на втором шаге знакомства (около 500 МБ).\n\n'
|
||||||
|
|||||||
@@ -56,21 +56,24 @@ check() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if [ "${1:-}" = "--selftest" ]; then
|
if [ "${1:-}" = "--selftest" ]; then
|
||||||
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
|
TMP=$(mktemp -d) || exit 1
|
||||||
|
trap 'rm -rf "$TMP"' EXIT
|
||||||
|
cp -R Sources "$TMP/Sources" || exit 1
|
||||||
|
cd "$TMP" || exit 1
|
||||||
ok=0
|
ok=0
|
||||||
check > /dev/null || { echo "ПРОВАЛ: живое дерево не проходит ворота"; ok=1; }
|
if check > /dev/null; then
|
||||||
echo " OK живое дерево принято"
|
echo " OK копия дерева принята"
|
||||||
|
else
|
||||||
|
echo "ПРОВАЛ: копия дерева не проходит ворота"; ok=1
|
||||||
|
fi
|
||||||
|
|
||||||
# Подделка: второй путь наружу.
|
# Подделка: второй путь наружу.
|
||||||
cp "$CONTROLLER" "$TMP/backup"
|
|
||||||
printf '\n// let sneak = SpeechCleanupRequest.body(text: "x")\n' >> Sources/IrizDictate/SpeechCleanup.swift
|
printf '\n// let sneak = SpeechCleanupRequest.body(text: "x")\n' >> Sources/IrizDictate/SpeechCleanup.swift
|
||||||
if check > /dev/null; then
|
if check > /dev/null; then
|
||||||
echo "ПРОВАЛ: второй путь наружу не пойман"; ok=1
|
echo "ПРОВАЛ: второй путь наружу не пойман"; ok=1
|
||||||
else
|
else
|
||||||
echo " OK второй путь наружу отвергнут"
|
echo " OK второй путь наружу отвергнут"
|
||||||
fi
|
fi
|
||||||
git checkout -- Sources/IrizDictate/SpeechCleanup.swift 2>/dev/null
|
|
||||||
|
|
||||||
[ $ok -eq 0 ] && echo "SELFTEST OK"
|
[ $ok -eq 0 ] && echo "SELFTEST OK"
|
||||||
exit $ok
|
exit $ok
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -31,7 +31,9 @@ check() {
|
|||||||
|
|
||||||
# M02: у встречи сохраняются ОБА файла. Половина доказательства хуже его
|
# M02: у встречи сохраняются ОБА файла. Половина доказательства хуже его
|
||||||
# отсутствия: она создаёт видимость.
|
# отсутствия: она создаёт видимость.
|
||||||
grep -q "let audioCopy = directory.appendingPathComponent" Sources/IrizDictate/MeetingStore.swift \
|
# Копирование может идти в staging до атомарного переноса пары.
|
||||||
|
# Имя промежуточного каталога не определяет, сохранён ли звук.
|
||||||
|
grep -q 'copyItem(at: audio, to: audioCopy)' Sources/IrizDictate/MeetingStore.swift \
|
||||||
|| { echo "M02: встреча перестала сохранять звук"; rc=1; }
|
|| { echo "M02: встреча перестала сохранять звук"; rc=1; }
|
||||||
grep -q "protocol.md" Sources/IrizDictate/MeetingStore.swift \
|
grep -q "protocol.md" Sources/IrizDictate/MeetingStore.swift \
|
||||||
|| { echo "M02: встреча перестала сохранять расшифровку"; rc=1; }
|
|| { echo "M02: встреча перестала сохранять расшифровку"; rc=1; }
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Положить настоящий кадр продукта на экран мраморного ноутбука.
|
||||||
|
|
||||||
|
Почему прибором, а не рисованием. Модель, которой велено нарисовать интерфейс,
|
||||||
|
рисует ПОХОЖИЙ интерфейс: кнопки не те, слова выдуманы, шрифт чужой. Такая
|
||||||
|
картинка врёт про продукт тем громче, чем красивее сцена. Здесь на экран
|
||||||
|
ложатся настоящие пиксели витрины, снятые тем же прибором, что и всё остальное.
|
||||||
|
|
||||||
|
Четырёхугольник экрана задаётся файлом рядом с кадром: сцена меняется редко, а
|
||||||
|
углы меряются один раз. Прибор проверяет, что по этим углам действительно лежит
|
||||||
|
ровное светлое поле, и отказывается работать, если сцену пересняли и углы
|
||||||
|
разъехались, - иначе кадр продукта уехал бы на мрамор.
|
||||||
|
|
||||||
|
scripts/vstavit_ekran.py <сцена.png> <углы.json> <кадр.png> <выход.png>
|
||||||
|
scripts/vstavit_ekran.py --selftest
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageStat
|
||||||
|
|
||||||
|
|
||||||
|
def koefficienty(iz_uglov, v_ugly):
|
||||||
|
"""Коэффициенты перспективы для PIL: они отображают ВЫХОД в ВХОД."""
|
||||||
|
a = []
|
||||||
|
b = []
|
||||||
|
for (x, y), (u, v) in zip(v_ugly, iz_uglov):
|
||||||
|
a.append([x, y, 1, 0, 0, 0, -u * x, -u * y])
|
||||||
|
b.append(u)
|
||||||
|
a.append([0, 0, 0, x, y, 1, -v * x, -v * y])
|
||||||
|
b.append(v)
|
||||||
|
# Решение системы 8x8 методом Гаусса: numpy сюда тянуть незачем.
|
||||||
|
n = 8
|
||||||
|
for i in range(n):
|
||||||
|
glavnaya = max(range(i, n), key=lambda r: abs(a[r][i]))
|
||||||
|
a[i], a[glavnaya] = a[glavnaya], a[i]
|
||||||
|
b[i], b[glavnaya] = b[glavnaya], b[i]
|
||||||
|
if abs(a[i][i]) < 1e-9:
|
||||||
|
raise ValueError("вырожденный четырёхугольник экрана")
|
||||||
|
for r in range(i + 1, n):
|
||||||
|
k = a[r][i] / a[i][i]
|
||||||
|
for c in range(i, n):
|
||||||
|
a[r][c] -= k * a[i][c]
|
||||||
|
b[r] -= k * b[i]
|
||||||
|
x = [0.0] * n
|
||||||
|
for i in range(n - 1, -1, -1):
|
||||||
|
s = sum(a[i][c] * x[c] for c in range(i + 1, n))
|
||||||
|
x[i] = (b[i] - s) / a[i][i]
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
def proverit_ekran(scena, ugly):
|
||||||
|
"""Экран обязан быть ровным полем, которое СВЕТЛЕЕ мрамора вокруг.
|
||||||
|
|
||||||
|
Абсолютный порог яркости тут не работает: мрамор сцены сам светлый, и
|
||||||
|
четырёхугольник, съехавший на стол, проходил проверку. Судим по разнице с
|
||||||
|
каймой снаружи - она есть у экрана и её нет у мрамора.
|
||||||
|
"""
|
||||||
|
xs = [t[0] for t in ugly]
|
||||||
|
ys = [t[1] for t in ugly]
|
||||||
|
l, r, t, b = int(min(xs)), int(max(xs)), int(min(ys)), int(max(ys))
|
||||||
|
vnutri = scena.crop((l + 12, t + 12, r - 12, b - 12)).convert("L")
|
||||||
|
kajma = 24
|
||||||
|
snaruji = scena.crop((max(0, l - kajma), max(0, t - kajma),
|
||||||
|
min(scena.width, r + kajma), min(scena.height, b + kajma))).convert("L")
|
||||||
|
sv = ImageStat.Stat(vnutri)
|
||||||
|
sn = ImageStat.Stat(snaruji)
|
||||||
|
raznica = sv.mean[0] - sn.mean[0]
|
||||||
|
horosho = raznica > 3 and sv.stddev[0] < 12
|
||||||
|
return horosho, round(sv.mean[0], 1), round(raznica, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def obrezat_polya(kadr, dopusk=10):
|
||||||
|
"""Снять ровные поля вокруг окна.
|
||||||
|
|
||||||
|
Кадры витрины снимаются с полем в 96 точек - ради тени и воздуха на
|
||||||
|
странице. На экране ноутбука это поле лишнее: окно внутри окна читается
|
||||||
|
вложенной картинкой, а не работающей программой.
|
||||||
|
"""
|
||||||
|
seryj = kadr.convert("L")
|
||||||
|
w, h = seryj.size
|
||||||
|
fon = seryj.getpixel((1, 1))
|
||||||
|
|
||||||
|
def dannye(kusok):
|
||||||
|
return kusok.get_flattened_data() if hasattr(kusok, "get_flattened_data") else kusok.getdata()
|
||||||
|
|
||||||
|
def rovnaya(pikseli):
|
||||||
|
return all(abs(p - fon) <= dopusk for p in pikseli)
|
||||||
|
|
||||||
|
l, r, t, b = 0, w - 1, 0, h - 1
|
||||||
|
while l < r and rovnaya(dannye(seryj.crop((l, 0, l + 1, h)))): l += 1
|
||||||
|
while r > l and rovnaya(dannye(seryj.crop((r, 0, r + 1, h)))): r -= 1
|
||||||
|
while t < b and rovnaya(dannye(seryj.crop((0, t, w, t + 1)))): t += 1
|
||||||
|
while b > t and rovnaya(dannye(seryj.crop((0, b, w, b + 1)))): b -= 1
|
||||||
|
if r - l < 40 or b - t < 40:
|
||||||
|
return kadr
|
||||||
|
return kadr.crop((l, t, r + 1, b + 1))
|
||||||
|
|
||||||
|
|
||||||
|
def vstavit(scena_put, ugly_put, kadr_put, vyhod_put):
|
||||||
|
scena = Image.open(scena_put).convert("RGB")
|
||||||
|
ugly = [tuple(t) for t in json.load(open(ugly_put, encoding="utf-8"))["ekran"]]
|
||||||
|
rovno, sredneye, razbros = proverit_ekran(scena, ugly)
|
||||||
|
if not rovno:
|
||||||
|
print(f"УГЛЫ НЕ ПО ЭКРАНУ: яркость {sredneye}, перевес над каймой {razbros}. "
|
||||||
|
f"Сцену пересняли - перемерьте углы.", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
kadr = obrezat_polya(Image.open(kadr_put).convert("RGB"))
|
||||||
|
shirina = int(max(t[0] for t in ugly) - min(t[0] for t in ugly))
|
||||||
|
vysota = int(max(t[1] for t in ugly) - min(t[1] for t in ugly))
|
||||||
|
# Кадр вписывается в экран целиком, поля добираются его же краевым цветом:
|
||||||
|
# обрезать продукт ради формы экрана значит показать половину окна.
|
||||||
|
k = min(shirina / kadr.width, vysota / kadr.height)
|
||||||
|
ujatyj = kadr.resize((max(1, int(kadr.width * k)), max(1, int(kadr.height * k))), Image.LANCZOS)
|
||||||
|
pole = Image.new("RGB", (shirina, vysota), ujatyj.getpixel((0, 0)))
|
||||||
|
pole.paste(ujatyj, ((shirina - ujatyj.width) // 2, (vysota - ujatyj.height) // 2))
|
||||||
|
|
||||||
|
kf = koefficienty([(0, 0), (shirina, 0), (shirina, vysota), (0, vysota)], ugly)
|
||||||
|
lozhe = pole.transform(scena.size, Image.PERSPECTIVE, kf, Image.BICUBIC)
|
||||||
|
maska = Image.new("L", (shirina, vysota), 255).transform(
|
||||||
|
scena.size, Image.PERSPECTIVE, kf, Image.BICUBIC)
|
||||||
|
gotovo = scena.copy()
|
||||||
|
gotovo.paste(lozhe, (0, 0), maska)
|
||||||
|
# Экран остаётся стеклом: лёгкий свет сцены поверх кадра, иначе картинка
|
||||||
|
# выглядит наклейкой, а не свечением панели.
|
||||||
|
blik = Image.new("RGB", scena.size, (255, 255, 255))
|
||||||
|
gotovo = Image.blend(gotovo, Image.composite(blik, gotovo, maska), 0.06)
|
||||||
|
gotovo.save(vyhod_put)
|
||||||
|
print(f"вставлено: {vyhod_put}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def selftest():
|
||||||
|
with tempfile.TemporaryDirectory(prefix="iriz-screen-selftest-") as directory:
|
||||||
|
root = Path(directory)
|
||||||
|
scena = Image.new("RGB", (400, 300), (232, 226, 216))
|
||||||
|
ekran = (100, 60, 300, 200)
|
||||||
|
scena.paste(Image.new("RGB", (200, 140), (242, 236, 228)), ekran[:2])
|
||||||
|
scena.save(root / "scena.png")
|
||||||
|
(root / "ugly.json").write_text(
|
||||||
|
json.dumps({"ekran": [[100, 60], [300, 60], [300, 200], [100, 200]]}), encoding="utf-8")
|
||||||
|
Image.new("RGB", (200, 120), (20, 90, 200)).save(root / "kadr.png")
|
||||||
|
if vstavit(root / "scena.png", root / "ugly.json",
|
||||||
|
root / "kadr.png", root / "vyhod.png") != 0:
|
||||||
|
print("ПРОВАЛ: честная сцена отвергнута", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
gotovo = Image.open(root / "vyhod.png").convert("RGB")
|
||||||
|
r, g, b = gotovo.getpixel((200, 130))
|
||||||
|
if not (b > r + 40):
|
||||||
|
print(f"ПРОВАЛ: кадр не лёг на экран, в середине {r},{g},{b}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(" OK кадр лёг ровно в экран")
|
||||||
|
# Порченый вход: углы показывают на мрамор, а не на экран.
|
||||||
|
(root / "ugly-bad.json").write_text(
|
||||||
|
json.dumps({"ekran": [[10, 10], [90, 10], [90, 50], [10, 50]]}), encoding="utf-8")
|
||||||
|
if vstavit(root / "scena.png", root / "ugly-bad.json",
|
||||||
|
root / "kadr.png", root / "vyhod2.png") == 0:
|
||||||
|
print("ПРОВАЛ: устаревшие углы не пойманы", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(" OK углы мимо экрана отвергнуты")
|
||||||
|
print("SELFTEST OK")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if "--selftest" in sys.argv[1:]:
|
||||||
|
sys.exit(selftest())
|
||||||
|
if len(sys.argv) != 5:
|
||||||
|
print(__doc__, file=sys.stderr)
|
||||||
|
sys.exit(2)
|
||||||
|
sys.exit(vstavit(*sys.argv[1:5]))
|
||||||