Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc347bf9a6 |
@@ -0,0 +1,31 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="referrer" content="no-referrer"><title>集团账号登录 · 互联网医院</title>
|
||||
<style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f3f7f6;color:#183d37;font-family:system-ui,sans-serif}main{width:min(390px,calc(100% - 80px));padding:40px;background:#fff;border:1px solid #dce8e4;border-radius:20px;box-shadow:0 16px 56px #163d3710}.label{font-size:13px;letter-spacing:3px;color:#6e817c}h1{font-size:30px;margin:20px 0}p{line-height:1.8;color:#60736e}button{width:100%;margin-top:20px;padding:13px;border:0;border-radius:9px;background:#176453;color:white;cursor:pointer}a{display:block;margin-top:24px;color:#176453;font-size:14px}</style></head>
|
||||
<body><main><span class="label">甄养堂集团</span><h1>互联网医院</h1><p id="status" role="status">正在连接集团账号…</p><button id="retry" hidden>重新发起登录</button><a href="/admin/login">使用医院账号登录</a></main>
|
||||
<script type="module">
|
||||
import { beginGroupLogin, consumeGroupCallback, exchangeGroupCode, groupLoginDestination } from '/admin/group-sso.mjs'
|
||||
const settings = { identityOrigin: 'http://127.0.0.1:5173', hospitalOrigin: location.origin, storage: sessionStorage }
|
||||
const status = document.querySelector('#status')
|
||||
const retry = document.querySelector('#retry')
|
||||
let running = false
|
||||
async function connect() {
|
||||
if (running) return
|
||||
running = true
|
||||
retry.hidden = true
|
||||
try {
|
||||
if (location.origin !== 'http://127.0.0.1:8090') throw new Error('仅供固定回环预览')
|
||||
if (location.search || location.hash) {
|
||||
const transaction = consumeGroupCallback({ ...settings, url: location.href, history })
|
||||
status.textContent = '正在安全进入互联网医院…'
|
||||
const session = await exchangeGroupCode({ ...settings, transaction })
|
||||
localStorage.setItem('like_admin_token', JSON.stringify({ value: session.token, expire: '' }))
|
||||
location.replace(groupLoginDestination(session))
|
||||
} else location.assign(await beginGroupLogin(settings))
|
||||
} catch {
|
||||
status.textContent = '本次登录未完成或凭据已过期,请重新进入。'
|
||||
retry.hidden = false
|
||||
} finally { running = false }
|
||||
}
|
||||
retry.addEventListener('click', connect)
|
||||
void connect()
|
||||
</script></body></html>
|
||||
@@ -0,0 +1,106 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { webcrypto } from 'node:crypto'
|
||||
import { beginGroupLogin, consumeGroupCallback, exchangeGroupCode, fixedOrigin, groupLoginDestination, GROUP_TRANSACTION_KEY, pkceChallenge } from '../src/utils/groupSso.mjs'
|
||||
|
||||
const identityOrigin = 'http://127.0.0.1:5173'
|
||||
const hospitalOrigin = 'http://127.0.0.1:8090'
|
||||
const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'
|
||||
function store() {
|
||||
const values = new Map()
|
||||
return { getItem: (key) => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: (key) => values.delete(key) }
|
||||
}
|
||||
async function transaction() {
|
||||
const storage = store()
|
||||
const target = new URL(await beginGroupLogin({ identityOrigin, hospitalOrigin, storage, cryptoApi: webcrypto, now: 1000 }))
|
||||
const history = { state: null, calls: [], replaceState(...args) { this.calls.push(args) } }
|
||||
const url = new URL('/admin/group-login', hospitalOrigin)
|
||||
url.search = new URLSearchParams({ code: 'c'.repeat(64), state: target.searchParams.get('state') }).toString()
|
||||
return { storage, target, history, url }
|
||||
}
|
||||
function consume(fixture, overrides = {}) {
|
||||
return consumeGroupCallback({ ...fixture, url: fixture.url.href, identityOrigin, hospitalOrigin, now: 1500, ...overrides })
|
||||
}
|
||||
|
||||
test('S256 对照 RFC 7636 向量', async () => {
|
||||
assert.equal(await pkceChallenge(verifier, webcrypto), 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM')
|
||||
})
|
||||
test('只允许 HTTPS 或回环 HTTP 固定 origin', () => {
|
||||
assert.equal(fixedOrigin(identityOrigin), identityOrigin)
|
||||
for (const value of ['http://example.com', identityOrigin + '/bad', identityOrigin + '?redirect=x', 'https://u:p@example.com', 'javascript:alert(1)']) {
|
||||
assert.throws(() => fixedOrigin(value))
|
||||
}
|
||||
})
|
||||
test('初始化在医院存 verifier,授权 URL 仅有 S256 challenge', async () => {
|
||||
const fixture = await transaction()
|
||||
const saved = JSON.parse(fixture.storage.getItem(GROUP_TRANSACTION_KEY))
|
||||
assert.equal(saved.verifier.length, 43)
|
||||
assert.equal(saved.state.length, 43)
|
||||
assert.equal(fixture.target.pathname, '/sso/authorize')
|
||||
assert.equal(fixture.target.searchParams.get('redirect_uri'), hospitalOrigin + '/admin/group-login')
|
||||
assert.equal(fixture.target.searchParams.get('code_challenge'), await pkceChallenge(saved.verifier, webcrypto))
|
||||
assert.equal(fixture.target.href.includes(saved.verifier), false)
|
||||
})
|
||||
test('回调同步清 URL 和消费本地事务,不能重放', async () => {
|
||||
const fixture = await transaction()
|
||||
const result = consume(fixture)
|
||||
assert.equal(result.code, 'c'.repeat(64))
|
||||
assert.equal(fixture.history.calls[0][2], '/admin/group-login')
|
||||
assert.equal(fixture.storage.getItem(GROUP_TRANSACTION_KEY), null)
|
||||
assert.throws(() => consume(fixture))
|
||||
})
|
||||
test('拒绝错误 state、过期、未来事务、任意 redirect、重复参数和错误医院地址', async () => {
|
||||
for (const mutate of [
|
||||
(f) => f.url.searchParams.set('state', 'x'.repeat(43)),
|
||||
(f) => f.url.searchParams.set('redirect', 'https://example.com'),
|
||||
(f) => f.url.searchParams.append('code', 'x'.repeat(64)),
|
||||
(f) => { f.url.pathname = '/admin/login' },
|
||||
(f) => { f.url.hash = 'unexpected' },
|
||||
(f) => { const saved = JSON.parse(f.storage.getItem(GROUP_TRANSACTION_KEY)); saved.createdAt = -400000; f.storage.setItem(GROUP_TRANSACTION_KEY, JSON.stringify(saved)) },
|
||||
(f) => { const saved = JSON.parse(f.storage.getItem(GROUP_TRANSACTION_KEY)); saved.createdAt = 2000; f.storage.setItem(GROUP_TRANSACTION_KEY, JSON.stringify(saved)) }
|
||||
]) {
|
||||
const fixture = await transaction()
|
||||
mutate(fixture)
|
||||
assert.throws(() => consume(fixture))
|
||||
assert.equal(fixture.history.calls.length, 1)
|
||||
assert.equal(fixture.storage.getItem(GROUP_TRANSACTION_KEY), null)
|
||||
}
|
||||
})
|
||||
test('只执行中央/医院两次 POST,不携带旧 token、拒绝响应指定任意兑换地址', async () => {
|
||||
const fixture = await transaction()
|
||||
const current = consume(fixture)
|
||||
const calls = []
|
||||
const responses = [{ ticket: 't'.repeat(64), exchange_path: '/adminapi/identity.hospitalSso/exchange' }, { token: 'fixture-hospital-session-only', is_paw: 1 }]
|
||||
const result = await exchangeGroupCode({ transaction: current, identityOrigin, hospitalOrigin, fetcher: async (url, options) => {
|
||||
calls.push({ url, options }); return { ok: true, json: async () => ({ code: 1, data: responses.shift() }) }
|
||||
} })
|
||||
assert.equal(result.is_paw, 1)
|
||||
assert.equal(calls.length, 2)
|
||||
assert.equal(calls[0].url, identityOrigin + '/adminapi/group/sso/exchange')
|
||||
assert.equal(calls[1].url, hospitalOrigin + '/adminapi/identity.hospitalSso/exchange')
|
||||
assert.equal(calls[0].options.credentials, 'omit')
|
||||
assert.equal(calls[1].options.credentials, 'same-origin')
|
||||
assert.equal(calls.every(({ options }) => options.method === 'POST' && options.redirect === 'error' && !options.headers.Authorization && !options.headers.token), true)
|
||||
let rejectedCalls = 0
|
||||
await assert.rejects(exchangeGroupCode({ transaction: current, identityOrigin, hospitalOrigin, fetcher: async () => {
|
||||
rejectedCalls++; return { ok: true, json: async () => ({ code: 1, data: { ticket: 't'.repeat(64), exchange_path: 'https://example.com' } }) }
|
||||
} }))
|
||||
assert.equal(rejectedCalls, 1)
|
||||
})
|
||||
test('网络失败不重试,首次改密与企微门禁保留', async () => {
|
||||
const fixture = await transaction()
|
||||
let count = 0
|
||||
await assert.rejects(exchangeGroupCode({ transaction: consume(fixture), identityOrigin, hospitalOrigin, fetcher: async () => { count++; throw new Error('fixture offline') } }))
|
||||
assert.equal(count, 1)
|
||||
const secondFixture = await transaction()
|
||||
count = 0
|
||||
await assert.rejects(exchangeGroupCode({ transaction: consume(secondFixture), identityOrigin, hospitalOrigin, fetcher: async () => {
|
||||
count++
|
||||
if (count === 2) throw new Error('fixture hospital offline')
|
||||
return { ok: true, json: async () => ({ code: 1, data: { ticket: 't'.repeat(64), exchange_path: '/adminapi/identity.hospitalSso/exchange' } }) }
|
||||
} }))
|
||||
assert.equal(count, 2)
|
||||
assert.equal(groupLoginDestination({ is_paw: 0, need_bind_work_wechat: true }), '/admin/change-password')
|
||||
assert.equal(groupLoginDestination({ is_paw: 1, need_bind_work_wechat: true }), '/admin/bind-work-wechat')
|
||||
assert.equal(groupLoginDestination({ is_paw: 1 }), '/admin/')
|
||||
})
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
// 仅供回环预览:静态文件来自隔离副本,PHP 只从固定原入口加载。
|
||||
$project = realpath(__DIR__ . '/../..');
|
||||
$public = $project . '/server/public';
|
||||
$preview = $project . '/.test-runtime/hospital-preview/admin';
|
||||
$path = (string) parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);
|
||||
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
|
||||
header('Referrer-Policy: no-referrer');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('Cache-Control: no-store');
|
||||
|
||||
function missing(): never
|
||||
{
|
||||
http_response_code(404);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo '{"code":0,"msg":"接口不存在","data":{}}';
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true)
|
||||
|| !in_array($_SERVER['HTTP_HOST'] ?? '', ['127.0.0.1:8090', 'localhost:8090'], true)
|
||||
|| array_key_exists('s', $_GET) || preg_match('/[\\\\\x00-\x20\x7f]/', $path)) {
|
||||
missing();
|
||||
}
|
||||
|
||||
if (in_array($method, ['GET', 'HEAD'], true) && ($path === '/admin' || str_starts_with($path, '/admin/'))) {
|
||||
if ($path === '/admin/group-login') {
|
||||
$file = $preview . '/group-login.html';
|
||||
$type = 'text/html; charset=utf-8';
|
||||
} elseif ($path === '/admin/group-sso.mjs') {
|
||||
$file = $preview . '/group-sso.mjs';
|
||||
$type = 'text/javascript; charset=utf-8';
|
||||
} elseif (preg_match('~^/admin/(assets/[A-Za-z0-9_.@/-]+|ai-chat-icon\.png)$~D', $path)) {
|
||||
$file = realpath($preview . substr($path, strlen('/admin')));
|
||||
$base = realpath($preview);
|
||||
$normalizedFile = is_string($file) ? str_replace('\\', '/', $file) : '';
|
||||
$normalizedBase = is_string($base) ? str_replace('\\', '/', $base) . '/' : '';
|
||||
if (!$file || !$base || !str_starts_with($normalizedFile, $normalizedBase) || !is_file($file)) { missing(); }
|
||||
$types = ['js' => 'text/javascript', 'mjs' => 'text/javascript', 'css' => 'text/css', 'png' => 'image/png',
|
||||
'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'webp' => 'image/webp', 'svg' => 'image/svg+xml',
|
||||
'woff' => 'font/woff', 'woff2' => 'font/woff2', 'ttf' => 'font/ttf', 'ico' => 'image/x-icon'];
|
||||
$type = $types[strtolower(pathinfo($file, PATHINFO_EXTENSION))] ?? null;
|
||||
if ($type === null) { missing(); }
|
||||
} elseif (preg_match('~^/admin(?:/[A-Za-z0-9_-]+)*/?$~D', $path)) {
|
||||
$file = $preview . '/index.html';
|
||||
$type = 'text/html; charset=utf-8';
|
||||
} else { missing(); }
|
||||
if (!is_file($file)) { missing(); }
|
||||
header('Content-Type: ' . $type);
|
||||
if ($method !== 'HEAD') { readfile($file); }
|
||||
exit;
|
||||
}
|
||||
|
||||
// 不透传任意磁盘路径、安装器、测试脚本或 PHP 文件。
|
||||
if (!in_array($method, ['GET', 'POST', 'OPTIONS'], true)
|
||||
|| !preg_match('~^/adminapi/[A-Za-z][A-Za-z0-9_.]*/[A-Za-z][A-Za-z0-9_]*$~D', $path)) {
|
||||
missing();
|
||||
}
|
||||
$root = $project . '/server';
|
||||
if (!is_file($root . '/vendor/autoload.php') || !is_file($root . '/config/install.lock')) {
|
||||
http_response_code(503);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo '{"code":0,"msg":"原项目服务尚未配置","data":{}}';
|
||||
exit;
|
||||
}
|
||||
require $root . '/vendor/autoload.php';
|
||||
$_SERVER['SCRIPT_FILENAME'] = $public . '/index.php';
|
||||
$_SERVER['SCRIPT_NAME'] = '/index.php';
|
||||
$_SERVER['PHP_SELF'] = '/index.php';
|
||||
$_SERVER['PATH_INFO'] = $path;
|
||||
foreach (['HTTP_X_FORWARDED_HOST', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP'] as $key) { unset($_SERVER[$key]); }
|
||||
$application = new class($root . DIRECTORY_SEPARATOR) extends think\App {
|
||||
public function loadEnv(string $envName = ''): void
|
||||
{
|
||||
parent::loadEnv($envName);
|
||||
$this->env->set('APP_DEBUG', false);
|
||||
$this->env->set('LOCAL_DEBUG_LOGIN_SKIP_PASSWORD', false);
|
||||
}
|
||||
};
|
||||
$application->initialize();
|
||||
$application->request->setPathinfo(ltrim($path, '/'));
|
||||
$http = $application->http;
|
||||
$response = $http->run();
|
||||
$response->send();
|
||||
$http->end($response);
|
||||
@@ -0,0 +1,29 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const project = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
|
||||
const source = path.join(project, 'server/public/admin')
|
||||
const runtime = path.join(project, '.test-runtime')
|
||||
const output = path.join(runtime, 'hospital-preview')
|
||||
const target = path.join(output, 'admin')
|
||||
const sourceHtml = fs.readFileSync(path.join(source, 'index.html'), 'utf8')
|
||||
const entryPath = sourceHtml.match(/<script\b[^>]*\bsrc="\/admin\/assets\/([^"/]+\.js)"/i)?.[1]
|
||||
if (!entryPath) throw new Error('未找到原医院构建入口')
|
||||
const entry = fs.readFileSync(path.join(source, 'assets', entryPath), 'utf8')
|
||||
const original = 'baseUrl:"https://admin.zhenyangtang.com.cn//"'
|
||||
if (entry.split(original).length !== 2) throw new Error('医院公开 API baseUrl 字面量必须恰好出现一次')
|
||||
fs.mkdirSync(runtime, { recursive: true })
|
||||
// 只忽略生成物,不修改根 .gitignore 或原发布目录。
|
||||
const ignoreFile = path.join(runtime, '.gitignore')
|
||||
if (!fs.existsSync(ignoreFile)) fs.writeFileSync(ignoreFile, '*\n')
|
||||
fs.cpSync(source, target, { recursive: true, force: true })
|
||||
fs.writeFileSync(path.join(target, 'assets', entryPath), entry.replace(original, 'baseUrl:"/"'))
|
||||
// 预览只加载原本地模块;不启动原 HTML 附带的远程客服/音视频脚本及其内联初始化。
|
||||
const previewHtml = sourceHtml.replace(/<script\b([^>]*)>[\s\S]*?<\/script>/gi, (tag, attrs) =>
|
||||
/\bsrc="\/admin\/assets\/[^"/]+\.js"/.test(attrs) ? tag : '')
|
||||
fs.writeFileSync(path.join(target, 'index.html'), previewHtml.replace('<title>后台管理系统</title>', '<title>互联网医院</title>'))
|
||||
fs.copyFileSync(path.join(project, 'admin/src/utils/groupSso.mjs'), path.join(target, 'group-sso.mjs'))
|
||||
fs.copyFileSync(path.join(project, 'admin/public/group-login.html'), path.join(target, 'group-login.html'))
|
||||
if (fs.readFileSync(path.join(target, 'assets', entryPath), 'utf8').includes(original)) throw new Error('本地 API 适配未完成')
|
||||
process.stdout.write(JSON.stringify({ path: output, entry: entryPath }) + '\n')
|
||||
@@ -0,0 +1,18 @@
|
||||
param(
|
||||
[string]$PhpPath = 'C:\Users\isard\.cache\zyt-tools\php\php.exe'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$projectPath = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
if (-not (Test-Path -LiteralPath $PhpPath -PathType Leaf)) { throw 'PHP 可执行文件不存在' }
|
||||
if (Get-NetTCPConnection -LocalPort 8090 -State Listen -ErrorAction SilentlyContinue) { throw '8090 端口已占用,未停止任何进程' }
|
||||
& node (Join-Path $PSScriptRoot 'prepare-hospital-preview.mjs')
|
||||
if ($LASTEXITCODE -ne 0) { throw '医院预览准备失败' }
|
||||
$runtimePath = Join-Path $projectPath '.test-runtime\hospital-preview'
|
||||
$routerPath = Join-Path $PSScriptRoot 'hospital-preview-router.php'
|
||||
$publicPath = Join-Path $projectPath 'server\public'
|
||||
$arguments = @('-S', '127.0.0.1:8090', '-t', ('"' + $publicPath + '"'), ('"' + $routerPath + '"'))
|
||||
# 隐藏控制台,不将 PHP 请求日志重定向到文件,避免保存回调 URL 中的短码。
|
||||
$process = Start-Process -FilePath $PhpPath -ArgumentList $arguments -WorkingDirectory (Join-Path $projectPath 'server') -WindowStyle Hidden -PassThru
|
||||
$state = [ordered]@{ pid = $process.Id; port = 8090; path = $runtimePath }
|
||||
$state | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $runtimePath 'status.json') -Encoding utf8
|
||||
$state | ConvertTo-Json
|
||||
@@ -0,0 +1,32 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const project = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
|
||||
const base = 'http://127.0.0.1:8090'
|
||||
const callback = await fetch(base + '/admin/group-login')
|
||||
const callbackText = await callback.text()
|
||||
if (callback.status !== 200 || !callbackText.includes('集团账号登录') || !callbackText.includes('/admin/group-sso.mjs')) throw new Error('医院回调入口验证失败')
|
||||
const moduleResponse = await fetch(base + '/admin/group-sso.mjs')
|
||||
if (moduleResponse.status !== 200 || !(moduleResponse.headers.get('content-type') || '').includes('javascript')) throw new Error('医院登录模块验证失败')
|
||||
const page = await fetch(base + '/admin/')
|
||||
const html = await page.text()
|
||||
if (!html.includes('<title>互联网医院</title>') || /<script[^>]+src="https?:/i.test(html)) throw new Error('预览标题或远程脚本边界验证失败')
|
||||
const asset = html.match(/<script\b[^>]*\bsrc="(\/admin\/assets\/[^"/]+\.js)"/i)?.[1]
|
||||
if (!asset) throw new Error('未找到预览入口模块')
|
||||
const bundle = await (await fetch(base + asset)).text()
|
||||
if (!bundle.includes('baseUrl:"/"') || bundle.includes('baseUrl:"https://admin.zhenyangtang.com.cn//"')) throw new Error('预览 API 地址验证失败')
|
||||
const paths = ['/test.php', '/admin/assets/anything.php', '/install/install.php', '/admin/group-login?s=auth.admin/mySelf']
|
||||
for (const route of paths) {
|
||||
if ((await fetch(base + route)).status !== 404) throw new Error('静态路径或兼容路由未被拒绝')
|
||||
}
|
||||
const denied = await (await fetch(base + '/adminapi/auth.admin/mySelf')).json()
|
||||
if (denied.code === 1) throw new Error('未认证 API 意外放行')
|
||||
const original = fs.readFileSync(path.join(project, 'server/public' + asset), 'utf8')
|
||||
if (!original.includes('baseUrl:"https://admin.zhenyangtang.com.cn//"')) throw new Error('原发布产物发生修改')
|
||||
const runtime = path.join(project, '.test-runtime/hospital-preview')
|
||||
if (['php.stdout.log', 'php.stderr.log'].some((name) => fs.existsSync(path.join(runtime, name)))) throw new Error('预览不应生成持久化请求日志')
|
||||
const state = JSON.parse(fs.readFileSync(path.join(runtime, 'status.json'), 'utf8').replace(/^\uFEFF/, ''))
|
||||
if (Object.keys(state).sort().join(',') !== 'path,pid,port') throw new Error('启动状态包含额外字段')
|
||||
fs.writeFileSync(path.join(project, 'artifacts/iam-extraction/hospital-preview-status.json'), JSON.stringify(state, null, 2) + '\n')
|
||||
process.stdout.write('医院预览验证通过:回调/模块/首页 200,本地 API,4 条危险路径 404,未认证拒绝,无请求日志,原产物未改。\n')
|
||||
@@ -1,6 +1,6 @@
|
||||
const config = {
|
||||
terminal: 1, //终端
|
||||
title: '后台管理系统', //网站默认标题
|
||||
title: '互联网医院', //网站默认标题
|
||||
version: '1.9.4', //版本号
|
||||
baseUrl: `${import.meta.env.VITE_APP_BASE_URL || ''}/`, //请求接口域名
|
||||
urlPrefix: 'adminapi', //请求默认前缀
|
||||
|
||||
@@ -81,7 +81,7 @@ const defaultPath = PageEnum.INDEX
|
||||
const changePasswordPath = '/change-password'
|
||||
const bindWorkWechatPath = '/bind-work-wechat'
|
||||
// 免登录白名单
|
||||
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403]
|
||||
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403, '/group-login']
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
document.title = to.meta.title ?? config.title
|
||||
const userStore = useUserStore()
|
||||
|
||||
@@ -35,6 +35,11 @@ export const constantRoutes: Array<RouteRecordRaw> = [
|
||||
path: PageEnum.LOGIN,
|
||||
component: () => import('@/views/account/login.vue')
|
||||
},
|
||||
{
|
||||
path: '/group-login',
|
||||
component: () => import('@/views/account/GroupLogin.vue'),
|
||||
meta: { title: '集团账号登录 · 互联网医院', hidden: true, hideTab: true }
|
||||
},
|
||||
{
|
||||
path: '/change-password',
|
||||
component: () => import('@/views/account/change-password.vue')
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface HospitalSession { token: string; is_paw?: number; need_bind_work_wechat?: boolean; [key: string]: unknown }
|
||||
export interface GroupTransaction { code: string; verifier: string; redirectUri: string }
|
||||
export const GROUP_CLIENT_ID: string
|
||||
export const GROUP_TRANSACTION_KEY: string
|
||||
export function fixedOrigin(value: string): string
|
||||
export function callbackUri(origin: string): string
|
||||
export function pkceChallenge(verifier: string, cryptoApi?: Crypto): Promise<string>
|
||||
export function beginGroupLogin(options: { identityOrigin: string; hospitalOrigin: string; storage: Storage; cryptoApi?: Crypto; now?: number }): Promise<string>
|
||||
export function consumeGroupCallback(options: { url: string; history: History; storage: Storage; identityOrigin: string; hospitalOrigin: string; now?: number }): GroupTransaction
|
||||
export function exchangeGroupCode(options: { transaction: GroupTransaction; identityOrigin: string; hospitalOrigin: string; fetcher?: typeof fetch }): Promise<HospitalSession>
|
||||
export function groupLoginDestination(session: HospitalSession): string
|
||||
@@ -0,0 +1,111 @@
|
||||
// 集团登录只交换短时凭据;原业务 token 不进入 URL 或 sessionStorage。
|
||||
export const GROUP_CLIENT_ID = 'internet-hospital'
|
||||
export const GROUP_TRANSACTION_KEY = 'zyt_hospital_group_sso_v1'
|
||||
const TRANSACTION_TTL = 5 * 60 * 1000
|
||||
const CALLBACK_PATH = '/admin/group-login'
|
||||
const HOSPITAL_EXCHANGE = '/adminapi/identity.hospitalSso/exchange'
|
||||
const safeValue = /^[A-Za-z0-9_-]{24,512}$/
|
||||
|
||||
export function fixedOrigin(value) {
|
||||
const url = new URL(value)
|
||||
const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
|
||||
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
|
||||
url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
|
||||
throw new Error('集团登录地址配置无效')
|
||||
}
|
||||
return url.origin
|
||||
}
|
||||
|
||||
export function callbackUri(origin) {
|
||||
return fixedOrigin(origin) + CALLBACK_PATH
|
||||
}
|
||||
|
||||
function base64url(bytes) {
|
||||
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
export async function pkceChallenge(verifier, cryptoApi = globalThis.crypto) {
|
||||
if (!/^[A-Za-z0-9_-]{43,128}$/.test(verifier)) throw new Error('登录事务无效,请重新发起')
|
||||
return base64url(new Uint8Array(await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(verifier))))
|
||||
}
|
||||
|
||||
export async function beginGroupLogin({ identityOrigin, hospitalOrigin, storage, cryptoApi = globalThis.crypto, now = Date.now() }) {
|
||||
const identity = fixedOrigin(identityOrigin)
|
||||
const redirectUri = callbackUri(hospitalOrigin)
|
||||
const verifier = base64url(cryptoApi.getRandomValues(new Uint8Array(32)))
|
||||
const state = base64url(cryptoApi.getRandomValues(new Uint8Array(32)))
|
||||
const challenge = await pkceChallenge(verifier, cryptoApi)
|
||||
storage.setItem(GROUP_TRANSACTION_KEY, JSON.stringify({ verifier, state, redirectUri, identity, createdAt: now }))
|
||||
const target = new URL('/sso/authorize', identity)
|
||||
target.search = new URLSearchParams({ client_id: GROUP_CLIENT_ID, redirect_uri: redirectUri, state,
|
||||
code_challenge: challenge, code_challenge_method: 'S256' }).toString()
|
||||
return target.href
|
||||
}
|
||||
|
||||
// 必须在任何 await/网络请求之前调用,URL 的所有回调参数一并清除。
|
||||
export function consumeGroupCallback({ url, history, storage, identityOrigin, hospitalOrigin, now = Date.now() }) {
|
||||
const current = new URL(url)
|
||||
const expected = callbackUri(hospitalOrigin)
|
||||
history.replaceState(history.state, '', CALLBACK_PATH)
|
||||
const raw = storage.getItem(GROUP_TRANSACTION_KEY)
|
||||
storage.removeItem(GROUP_TRANSACTION_KEY)
|
||||
if (current.origin + current.pathname !== expected || current.hash ||
|
||||
[...current.searchParams.keys()].some((key) => !['code', 'state', 'error'].includes(key)) ||
|
||||
['code', 'state', 'error'].some((key) => current.searchParams.getAll(key).length > 1)) {
|
||||
throw new Error('登录回调地址无效,请重新发起')
|
||||
}
|
||||
if (current.searchParams.has('error')) throw new Error('集团登录未完成,请返回集团后台重试')
|
||||
let transaction
|
||||
try { transaction = JSON.parse(raw || 'null') } catch { /* 统一按无效事务处理。 */ }
|
||||
const code = current.searchParams.get('code') || ''
|
||||
const state = current.searchParams.get('state') || ''
|
||||
if (!transaction || !safeValue.test(code) || !safeValue.test(state) || state !== transaction.state ||
|
||||
!/^[A-Za-z0-9_-]{43,128}$/.test(transaction.verifier || '') ||
|
||||
transaction.identity !== fixedOrigin(identityOrigin) || transaction.redirectUri !== expected ||
|
||||
!Number.isSafeInteger(transaction.createdAt) || now < transaction.createdAt || now - transaction.createdAt > TRANSACTION_TTL) {
|
||||
throw new Error('登录状态已失效或不属于当前浏览器,请重新发起')
|
||||
}
|
||||
return { code, verifier: transaction.verifier, redirectUri: expected }
|
||||
}
|
||||
|
||||
async function postOnce(fetcher, url, body, credentials) {
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), 20000)
|
||||
try {
|
||||
const response = await fetcher(url, { method: 'POST', credentials, redirect: 'error', cache: 'no-store',
|
||||
referrerPolicy: 'no-referrer', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(body), signal: controller.signal })
|
||||
if (!response.ok) throw new Error('登录交接未完成,请重新发起')
|
||||
const envelope = await response.json()
|
||||
if (envelope?.code !== 1 || !envelope.data || typeof envelope.data !== 'object') {
|
||||
throw new Error('登录交接未完成,请重新发起')
|
||||
}
|
||||
return envelope.data
|
||||
} finally { clearTimeout(timeout) }
|
||||
}
|
||||
|
||||
export async function exchangeGroupCode({ transaction, identityOrigin, hospitalOrigin, fetcher = globalThis.fetch }) {
|
||||
const identity = fixedOrigin(identityOrigin)
|
||||
const hospital = fixedOrigin(hospitalOrigin)
|
||||
if (transaction.redirectUri !== callbackUri(hospital) || !safeValue.test(transaction.code || '') ||
|
||||
!/^[A-Za-z0-9_-]{43,128}$/.test(transaction.verifier || '')) throw new Error('登录回调地址无效')
|
||||
const issued = await postOnce(fetcher, identity + '/adminapi/group/sso/exchange', {
|
||||
client_id: GROUP_CLIENT_ID, redirect_uri: transaction.redirectUri,
|
||||
code: transaction.code, code_verifier: transaction.verifier
|
||||
}, 'omit')
|
||||
if (!safeValue.test(issued.ticket || '') || issued.exchange_path !== HOSPITAL_EXCHANGE) {
|
||||
throw new Error('医院登录凭据无效,请重新发起')
|
||||
}
|
||||
const session = await postOnce(fetcher, hospital + HOSPITAL_EXCHANGE,
|
||||
{ ticket: issued.ticket, code_verifier: transaction.verifier }, 'same-origin')
|
||||
if (typeof session.token !== 'string' || session.token.length < 16 || session.token.length > 2048 || /[\x00-\x20\x7f]/.test(session.token)) {
|
||||
throw new Error('医院登录响应无效,请重新发起')
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
export function groupLoginDestination(session) {
|
||||
if (Number(session.is_paw) === 0) return '/admin/change-password'
|
||||
if (session.need_bind_work_wechat) return '/admin/bind-work-wechat'
|
||||
return '/admin/'
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { TOKEN_KEY } from '@/enums/cacheEnums'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import { clearAuthInfo } from '@/utils/auth'
|
||||
import cache from '@/utils/cache'
|
||||
import { beginGroupLogin, consumeGroupCallback, exchangeGroupCode, groupLoginDestination } from '@/utils/groupSso.mjs'
|
||||
|
||||
const localOrigin = ['127.0.0.1', 'localhost', '[::1]'].includes(window.location.hostname)
|
||||
const identityOrigin = String(import.meta.env.VITE_GROUP_IDENTITY_URL || (localOrigin ? 'http://127.0.0.1:5173' : ''))
|
||||
const message = ref('正在连接集团账号…')
|
||||
const failed = ref(false)
|
||||
let running = false
|
||||
|
||||
async function connect() {
|
||||
if (running) return
|
||||
running = true
|
||||
failed.value = false
|
||||
try {
|
||||
const options = { identityOrigin, hospitalOrigin: window.location.origin, storage: sessionStorage }
|
||||
if (window.location.search || window.location.hash) {
|
||||
const transaction = consumeGroupCallback({ ...options, url: window.location.href, history: window.history })
|
||||
message.value = '正在安全进入互联网医院…'
|
||||
const session = await exchangeGroupCode({ ...options, transaction })
|
||||
clearAuthInfo()
|
||||
const user = useUserStore()
|
||||
user.token = session.token
|
||||
user.isPaw = session.is_paw ?? 1
|
||||
cache.set(TOKEN_KEY, session.token)
|
||||
window.location.replace(groupLoginDestination(session))
|
||||
} else {
|
||||
window.location.assign(await beginGroupLogin(options))
|
||||
}
|
||||
} catch {
|
||||
message.value = '本次登录未完成或凭据已过期,请重新进入。'
|
||||
failed.value = true
|
||||
} finally { running = false }
|
||||
}
|
||||
onMounted(connect)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="group-login"><section>
|
||||
<span class="group-label">甄养堂集团</span><h1>互联网医院</h1><p role="status">{{ message }}</p>
|
||||
<button v-if="failed" type="button" @click="connect">重新发起登录</button>
|
||||
<a href="/admin/login">使用医院账号登录</a>
|
||||
</section></main>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.group-login{min-height:100vh;display:grid;place-items:center;background:#f3f7f6;color:#183d37;padding:24px}.group-login section{width:min(440px,100%);padding:44px;background:white;border:1px solid #dce8e4;border-radius:20px;box-shadow:0 16px 56px #163d3710}.group-label{font-size:13px;letter-spacing:3px;color:#6e817c}.group-login h1{font-size:30px;margin:20px 0}.group-login p{line-height:1.8;color:#60736e}.group-login button{display:block;width:100%;margin:24px 0 20px;padding:13px;border:0;border-radius:9px;background:#176453;color:white;cursor:pointer}.group-login a{display:block;margin-top:24px;color:#176453;font-size:14px}
|
||||
</style>
|
||||
@@ -1,6 +1,5 @@
|
||||
.env
|
||||
.local-workstation/
|
||||
resources/local-asr/
|
||||
.venv/
|
||||
.venv-build/
|
||||
.venv-win7-check/
|
||||
|
||||
|
Before Width: | Height: | Size: 118 KiB After Width: | Height: | Size: 124 KiB |
|
Before Width: | Height: | Size: 163 KiB After Width: | Height: | Size: 167 KiB |
|
Before Width: | Height: | Size: 117 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 165 KiB After Width: | Height: | Size: 167 KiB |
|
Before Width: | Height: | Size: 112 KiB After Width: | Height: | Size: 159 KiB |
|
Before Width: | Height: | Size: 147 KiB After Width: | Height: | Size: 188 KiB |
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 92 KiB |
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 77 KiB After Width: | Height: | Size: 73 KiB |
@@ -10,14 +10,11 @@ modules, Qt6Multimedia shared libraries/frameworks, multimedia plugins, and
|
||||
their platform media backends.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PyInstaller.utils.hooks import collect_all
|
||||
|
||||
|
||||
PROJECT_ROOT = Path(SPEC).resolve().parent.parent
|
||||
SOURCE_ROOT = PROJECT_ROOT / "src"
|
||||
@@ -111,24 +108,15 @@ qt_multimedia_hiddenimports = [
|
||||
"PySide6.QtMultimediaWidgets",
|
||||
]
|
||||
|
||||
# Cloud transcription only needs offline character conversion on the client.
|
||||
if importlib.util.find_spec("opencc") is None:
|
||||
raise SystemExit("Install the project dependencies before packaging (missing opencc)")
|
||||
transcript_datas, transcript_binaries, transcript_hiddenimports = collect_all("opencc")
|
||||
client_resources = [
|
||||
(str(entry), f"resources/{entry.name}" if entry.is_dir() else "resources")
|
||||
for entry in RESOURCES.iterdir()
|
||||
if entry.name != "local-asr"
|
||||
]
|
||||
|
||||
analysis = Analysis(
|
||||
[str(ENTRY_POINT)],
|
||||
pathex=[str(SOURCE_ROOT)],
|
||||
binaries=python_runtime_binaries + transcript_binaries,
|
||||
binaries=python_runtime_binaries,
|
||||
datas=[
|
||||
(str(VIDEO_DIST), "video_companion_dist"),
|
||||
] + client_resources + transcript_datas,
|
||||
hiddenimports=qt_webengine_hiddenimports + qt_multimedia_hiddenimports + transcript_hiddenimports,
|
||||
(str(RESOURCES), "resources"),
|
||||
],
|
||||
hiddenimports=qt_webengine_hiddenimports + qt_multimedia_hiddenimports,
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[str(MEDIA_SMOKE_HOOK)],
|
||||
|
||||
@@ -13,16 +13,12 @@ authors = [{ name = "Zhenyangtang" }]
|
||||
dependencies = [
|
||||
"httpx>=0.27.2,<1",
|
||||
"keyring>=25.5,<26",
|
||||
"opencc-python-reimplemented==0.1.7",
|
||||
"platformdirs>=4.3,<5",
|
||||
"PySide6>=6.8.2,<7",
|
||||
"python-dotenv>=1.0.1,<2",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
local-asr = [
|
||||
"faster-whisper==1.2.1",
|
||||
]
|
||||
dev = [
|
||||
"pytest>=8.3,<9",
|
||||
"pytest-cov>=6,<7",
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
# 医生工作站客户端设计规范
|
||||
|
||||
本轮覆盖现有 PySide6 客户端与 Vue 视频伴随窗口。按 `redesign-existing-projects` 审查现有页面,结合 `minimalist-ui` 的扁平化原则实施;医疗工作台保留信息密度,不套用营销页面的大留白、装饰动效或布局模板。
|
||||
|
||||
## 审查结论
|
||||
|
||||
- 主框架与业务页面原先并存科技蓝、紫蓝及多套中性色;登录、AI、诊单的控件也各自定义配色。
|
||||
- 页面内圆角、边框和层级不统一,部分阴影、悬浮位移和过渡使操作显得跳动。
|
||||
- 小窗口的表格、诊单与视频操作需要分别验证,不能依靠整体缩小解决。
|
||||
- 键盘焦点、禁用与选择状态应始终可识别,不通过改变控件几何位置表达状态。
|
||||
|
||||
## 视觉系统
|
||||
|
||||
设计变量以 `src/doctor_workstation/ui/design_system.py` 为准。旧页面通过 `clinical_stylesheet` 迁移已知的浅色主题颜色,新样式使用命名变量。医学数据曲线、模型标识色和深色主题不进行全局替色。
|
||||
|
||||
| 角色 | 值 | 使用场景 |
|
||||
| --- | --- | --- |
|
||||
| 主色 | `#4267B2` | 主操作、选中项、重要链接 |
|
||||
| 主色浅底 | `#EAF0FB` | 选中背景、轻量状态 |
|
||||
| 画布 | `#F5F7FA` | 主窗口背景 |
|
||||
| 表面 | `#FFFFFF` | 内容区、对话框 |
|
||||
| 次级表面 | `#F7F9FC` | 筛选栏、分组、只读区域 |
|
||||
| 侧栏 | `#F0F3F8` | 导航区域 |
|
||||
| 标题 / 正文 | `#223047` / `#344258` | 文字层级 |
|
||||
| 次级文字 | `#647287` | 说明、辅助信息 |
|
||||
| 边框 / 强边框 | `#E6EAF0` / `#D4DCE8` | 低对比结构线、输入边界 |
|
||||
| 成功 / 警示 / 危险 | `#287B65` / `#96601D` / `#B54A59` | 保留明确语义,不只依赖颜色 |
|
||||
|
||||
- 圆角:标签 6 px、输入与按钮 10 px、内容面板 16 px、独立窗口 20 px。
|
||||
- 间距:8 / 12 / 16 / 24 px,根据现有表格密度调整,不整体放大行高。
|
||||
- 字体:继续使用打包的中文字体与现有可读字号;标题层级通过字重、字号和间距体现。
|
||||
- 表面:纯色为主,轻边框划分区域,减少嵌套卡片与装饰阴影。
|
||||
- 按钮:每个操作组主次清晰;次要操作使用浅底或边框;终止、删除等危险操作保留语义色。
|
||||
|
||||
## 交互规范
|
||||
|
||||
- 悬浮、按下和焦点反馈不移动布局、不改变控件尺寸。
|
||||
- 动画短而克制;滚动可被键盘、拖动、程序定位与反向滚动即时打断;尊重减少动画设置。
|
||||
- 切换页面保留原有路由、权限和数据加载机制。
|
||||
- 登录表单保留密码存储、服务器设置与提交保护;组合密码框使用实际 Qt 焦点状态。
|
||||
- 大小窗口都必须能找到主要操作,优先局部滚动而非把全部内容压小。
|
||||
- 视频保留原有截图捕获、确认上传、大预览和小窗关闭返回大窗逻辑;视觉样式不改变媒体内容或尺寸计算。
|
||||
|
||||
## 覆盖范围
|
||||
|
||||
1. 登录与品牌区:扁平品牌面板、简洁功能说明、清晰表单与焦点。
|
||||
2. 主框架:导航、顶部搜索、工具按钮、标签与 AI 入口。
|
||||
3. 列表:挂号、接诊记录、患者、处方库、已开处方、业务订单及患者进度。
|
||||
4. 诊疗:接诊台、预约抽屉、诊单编辑与只读、指标和保存状态。
|
||||
5. 辅助窗口:AI 问诊、处方编辑、处方解读与报告控制台。
|
||||
6. 视频:通话控制、聊天、录制提示与截图确认。
|
||||
|
||||
## 验收方式
|
||||
|
||||
`scripts/render_client_design.py` 使用演示仓库生成 1440 × 900、1024 × 640 的真实页面,以及 1280 × 800、860 × 640 的登录页;输出 `artifacts/client-design/index.html` 与原尺寸 PNG。诊疗和 AI 弹窗使用现有专用渲染脚本验证。
|
||||
|
||||
检查重点:小窗操作可达、中文可读、表格信息密度、长文本换行、键盘焦点、布局稳定、登录与页面路由契约、视频截图与窗口状态回归。生产服务与真实患者资料不用于视觉验收。
|
||||
|
||||
本轮共享组件还覆盖筛选展开按钮、列表加载状态、聊天通知、更新提示、本机录音队列、媒体预览和上传进度。860 × 640 登录表单完整显示,不需要为纯留白滚动。
|
||||
|
||||
## 验证记录与边界
|
||||
|
||||
- 主框架、登录、遮罩与动效首轮 100 项通过;新增组合密码框键盘焦点检查通过。
|
||||
- 小窗登录与焦点补测 2 项、最终登录及主框架复查 68 项通过。
|
||||
- 筛选、无限列表、通知、更新窗口与本机录音队列 37 项通过。
|
||||
- 原生视频截图、截图预览尺寸、小窗关闭与视频契约 199 项通过。
|
||||
- 视频前端 26 项检查通过,生产 dist 已重新构建。
|
||||
- 当前视频 dist 在 1120 × 760、540 × 356、440 × 300 的合成画面中完成 27 项布局检查,截图与关闭事件正常,未访问外部服务。
|
||||
- 临床页面、AI、处方及图表分别完成专项测试和真实控件渲染,详细记录位于 `artifacts/client-design/*-report.md`。
|
||||
- 最终修改文件的 Ruff 与 `git diff --check` 均通过;AI 工作区及快捷操作权限最后复查 24 项通过。
|
||||
|
||||
此记录不表示整仓所有历史测试全部通过。扩展测试中存在已用原始 HEAD 复现的 AI 流式/延迟生命周期失败、共享 QApplication 样式引发的图表测试顺序依赖,以及 Windows Qt 网络模块异常;本轮没有改变相关业务行为。未连接真实面诊服务,也未重新打包或安装 Windows 客户端。
|
||||
@@ -1,21 +0,0 @@
|
||||
# 腾讯云实时转写恢复(2026-10-30)
|
||||
|
||||
用户明确选择“恢复腾讯云实时转写,保留简体中文”。本次仅替换识别通路,保留 IM AI、实时 AI 辅助、复盘、本机录音、视频录制、截图和窗口交互。
|
||||
|
||||
## 当前行为
|
||||
|
||||
- 使用当前固定 SDK 的 `getAITranscriberManager()` 和 `startRealtimeTranscriber({sourceLanguage: 'zh'})`。不再启动本地 PCM 识别或加载 Whisper/Nano 模型,本机语音录音保持独立。
|
||||
- 最终转写片段先经过原生可信页面及会话校验,以宿主的医生/患者用户 ID 确定角色,再用本机 OpenCC 转为简体并保存。仅持久化成功的确认回传简体文字,字幕和本次 AI 引用使用同一保存原文;历史记录查看仍显示简体。
|
||||
- 同一通话的云端重试复用原转写会话,保留已保存字幕和 AI 结果;云端中断不提前封存存储,真正挂断时才排空并归档。出错期间可能漏记的通话最终标记 partial。
|
||||
- 云端启动成功通过 `transcription-ready` 更新原生状态,避免重试成功仍显示失败;旧页面、旧会话、旧监听器及本地 ASR 命令不能混入当前会话。
|
||||
- 启动/打包脚本不再默认启用 `local-asr` 额外依赖;仍打包简体转换字典。`resources/local-asr` 从发布资源中排除。已有开发模型和独立测试模块保留,不默认使用。
|
||||
|
||||
## 验证及生效
|
||||
|
||||
仅用合成身份/文字与 SDK 替身验证启停、重试、尾段排空、成功保存后的六参数 ACK、简体转换、说话人归属、AI 更新和隔离边界。截图、大小窗及录音回归继续通过,前端类型检查和生产资源重建完成。
|
||||
|
||||
详细结果见 `app/artifacts/im-ai/cloud-transcription-restore-frontend.md`、`cloud-transcription-restore-native-tests.md`。没有发起真实患者通话或验证线上腾讯云识别效果,没有生成新的完整安装包。
|
||||
|
||||
最终整合验证:338 项 Python 回归、128 项前端测试通过,Vue 类型检查及生产构建通过。已核对真实 Qt 六参数转写信号,以及 PyInstaller 资源展开结果:图标、字体和简体词典保留,本地识别模型不进入发布资源。
|
||||
|
||||
源码客户端需要在结束当前通话后退出并重新启动整个客户端,原生 Python 代码与新前端资源才能一起生效。已冻结安装包需重新构建,不能只更换网页资源。
|
||||
@@ -1,75 +0,0 @@
|
||||
# IM 问诊 AI 辅助
|
||||
|
||||
用户确认范围:在现有 IM 问诊窗口内增加「总结病情」「建议追问」「起草回复」。结果供医生审阅,医生主动填入输入框后编辑并手动发送。
|
||||
|
||||
## 集成契约
|
||||
|
||||
- 复用 `stream_diagnosis_ai`:总结使用 `summary`,追问和回复使用 `custom`。不新增模型配置、不把凭据传到浏览器、不新增服务端路由。
|
||||
- 每次生成前,通过 `sync_im_chat_messages(scope="current", sync_token=...)` 完成当前账号对话归档;响应 `completed=true` 且没有错误后才能调用 AI。准备失败明确报错,不静默降级为旧聊天。服务器按授权诊单聚合临床资料与归档 IM,提示词限定本次医生账号的近期对话。
|
||||
- 三项提示词保持 500 字以内;不在提示词中挤入、截断完整聊天或未发送草稿。
|
||||
- AI 独立后台 worker,不占用通话、录音和消息发送的队列。
|
||||
|
||||
原生配置 `DoctorCallConfig.imAi`:`{version:1, enabled:boolean, sessionId:string, reason?:string}`。宿主生成 sessionId,每个新窗口独立。上层将 AI 权限布尔值贯穿 launcher;默认拒绝。
|
||||
|
||||
浏览器到原生:
|
||||
|
||||
```json
|
||||
{"source":"doctor-call","event":"im-ai-request","sessionId":"host-uuid","requestId":"uuid","contextKey":"frontend-context","diagnosisId":"501","appointmentId":101,"action":"summary"}
|
||||
```
|
||||
|
||||
取消使用同一组身份字段及 `event="im-ai-cancel"`。只允许 `summary | followup | reply`。宿主核验可信文档、窗口未关闭、AI 权限、会话、诊单、挂号和请求格式;实际 repository 调用始终使用宿主绑定诊单。
|
||||
|
||||
原生通过 `window.doctorConsultation.imAiResult(payload)` 返回相同身份字段与:
|
||||
|
||||
```text
|
||||
status: loading | streaming | success | error | cancelled
|
||||
text?: 累积正文(流式及最终)
|
||||
message?: 简短进度或错误
|
||||
modelLabel?: 服务端模型标签
|
||||
warnings?: string[]
|
||||
```
|
||||
|
||||
所有数据使用 JSON 序列化,桥接正文仍为原始文本。页面通过受限 Markdown 渲染器显示标题、重点、列表和表格;原始 HTML 被转义,链接和图片只保留文字,不执行内容或加载外部资源。客户端截止时间 180 秒,超时发送取消;原生聊天同步有独立有界预算,AI 沿用现有 105 秒传输预算。取消请求由独立线程发送,GUI 不等待网络。停止只是停止本次接收,不冒称上游工作已确认停止。
|
||||
|
||||
## 界面与状态
|
||||
|
||||
- 宽屏右侧约 330 px 辅助区;窄屏可收起抽屉,独立滚动,操作和关闭可达。沿用现有蓝色、圆角和轻边框。
|
||||
- AI loading 不阻塞 IM 输入、发送、加载更多和视频控制。
|
||||
- 只有完整成功结果允许填入;追问与回复可填入,病情总结默认只读。非空草稿明确追加,超过 3000 字拒绝追加而不截断原文。
|
||||
- 切换会话清空 AI 状态和草稿;迟到、重复、身份不匹配结果全部忽略。
|
||||
- 异步手动发送成功仅清空当时提交且没有继续修改的草稿。
|
||||
- 结果注明医生复核,展示服务端临床复核提示;不会自动发送、写病历或开处方。
|
||||
|
||||
## 验证要求
|
||||
|
||||
离线 fake repository 验证同步续拉、失败不生成、取消、终态、身份隔离、权限与关闭;Node 测试验证桥接状态/计时器、草稿追加和发送隔离;使用真实构建产物和合成消息验证宽屏与紧凑窗口。回归截图、录音收尾、通话权限与 IM 流程。验证不得访问真实患者、IM 或 AI 服务。
|
||||
|
||||
## 交付与验证结果(2026-10-29)
|
||||
|
||||
- `app.py` 在实际打开窗口时读取当前账号的 `tcm.diagnosis/aiAssistant` 权限,经 launcher 传入原生窗口;未配置权限时默认关闭,不采用聊天载荷中的权限标记。
|
||||
- 三项功能已接入真实 Qt bridge 和现有流式服务;宽屏常驻侧栏,980 px 及以下窗口使用可收起抽屉。中文输入法选词时按 Enter 不发送,异步发送不会清除医生随后编辑的草稿。
|
||||
- 合并后 Python 回归 **364 项通过**:包括新增 AI 服务/仓库/窗口、权限入口、IM、视频契约、截图、小窗关闭及大预览等。运行使用独立 `artifacts/im-ai/final-integration-tmp`,未访问外部服务。
|
||||
- 前端 **45 项 Node 行为测试通过**,`vue-tsc` 与 Vite 构建通过;实际 dist 在 1120×760、980×640、540×356、440×300 下 **42 项界面检查通过**。离线夹具只使用合成消息和结果,外部请求尝试为 0。
|
||||
- Ruff 与 `git diff --check` 通过。首次交付构建入口:`index-CnqWQu6O.js`、`index-BwArpbVK.css`。
|
||||
- 截图、可复现夹具和详细报告存放在 `app/artifacts/im-ai/`。未验证真实账号的模型响应;未生成 Windows 安装包。源码运行需重启客户端,已安装版本需重新打包后安装。
|
||||
|
||||
停止接收后,原生端会独立请求取消;在旧请求实际退出前重试会提示稍后再试,避免重复模型请求。聊天同步失败时不使用旧归档静默生成,助手显示错误并允许重试。
|
||||
|
||||
## 结果排版与切换改进(2026-10-29)
|
||||
|
||||
- 模型输出的 Markdown 标题、加粗、列表、引用、代码和简单表格转换为安全的结构化展示;重点以加粗和浅蓝底色标记,结构标题使用蓝色引导线。不依据医学关键词自行推断重点。未闭合的流式片段保持可读原文。
|
||||
- 三项操作在当前窗口会话内分别保留状态、正文、模型标签和复核提示。顶部按钮首次点击生成,之后只切换查看;底部“重新生成/重试”才会再发请求。生成中可以阅读其他已完成结果,后台更新不能覆盖当前阅读页。
|
||||
- 每项保留独立滚动位置,换患者、关闭或重开会话时清空。结果仅保存在内存中,不增加本地患者内容持久化。
|
||||
- 填入草稿前去除 Markdown 排版符号,保留原文、数值和列表含义,再执行 3000 字长度检查;仍不覆盖原稿、不自动发送。
|
||||
- 本次前端 **61 项行为测试通过**,包含安全渲染、草稿转换、缓存、显式重生成、后台流式隔离及现有截图/通话守卫;TypeScript 与 Vite 构建通过。
|
||||
- 真实 dist 配合生产 AI controller 源码和离线宿主替身,在四种窗口尺寸完成 **20 项可点击/布局检查**,以及切换不发请求、显式刷新、后台生成、独立阅读位置、原稿追加及注入防护断言。外部请求为 0。
|
||||
- 证据:`artifacts/im-ai/refinements-visual-checks.json`、`render_im_ai_refinements.py` 与 `im-ai-styled-cached-*.png`。未打包安装程序。
|
||||
|
||||
## 可调宽度、首次总结与指标强调(2026-10-29)
|
||||
|
||||
- 聊天与助手之间增加可左右拖动的分隔线,宽屏保留至少 480 px 聊天区域;窄屏抽屉也可调整,最大宽度仍留出可操作的边缘。支持方向键、Home/End、Enter 或双击恢复默认,Escape 取消本次拖动。窗口变更、失焦与关闭释放指针捕获。宽屏和抽屉宽度分别记忆在当前窗口内。
|
||||
- 进入有权限的 IM 会话后,首次总结等待当前登录、聊天、Qt 通道及原生 `imAiReady(sessionId)` 确认;准备等待最多 30 秒。每个会话只自动尝试一次,不因重连、标签切换、展开面板或失败自动重试。医生提前手动操作会取消待启动的自动总结。关闭和换会话清理计时器及旧结果。
|
||||
- 普通文本中的血糖、血压、糖化血红蛋白、体重等指标名称及带单位的数值自动强调,支持范围、小数和血压组合。名称加深,数值加粗并显示浅蓝底色,不依赖模型输出 Markdown。原始数值、单位、否定和不确定表述保持不变;没有新增医学阈值判断或自动风险分级。
|
||||
- **97 项前端测试、318 项客户端回归通过**,TypeScript、Vite 和 Ruff 检查通过,`git diff --check` 无问题。当前构建:`index-C_tMrPfb.js`、`index-CMN1CXTr.css`。
|
||||
- 实际构建页面在 1634×1008、1120×760、980×640、540×356、440×300 下完成真实 Qt 鼠标拖动、键盘调整、取消、跨断点释放及指标样式检查,**15 项布局/点击检查通过**,自动选择与请求次数断言通过,外部请求为 0。
|
||||
- 证据:`artifacts/im-ai/render_im_ai_resizing.py`、`resizing-visual-checks.json`、`im-ai-metrics-resizable-*.png`。本轮未生成安装包;原生就绪握手需重启使用最新源码的客户端。
|
||||
@@ -1,72 +0,0 @@
|
||||
# 实时问诊 AI:响应与建议质量改进
|
||||
|
||||
日期:2026-10-30。最新范围调整:仅视频接通后的实时 AI 使用本次通话文字;IM、病历分析与通话后复盘保持原范围。见末尾“纯对话实时模式”。
|
||||
|
||||
## 问题证据
|
||||
|
||||
从本机服务端当天运行日志中仅提取错误码和耗时,共发现 10 条 `LIVE_RESULT_INVALID` 记录:最短 12,833 ms,中位 15,002 ms,最长 29,465 ms。这说明部分等待最终消耗在无效结果上;原日志没有校验细项,不能断言具体是哪一种格式或引用错误。
|
||||
|
||||
代码另有两处可确认的问题:有结果后的新增对话要等待 8 秒才发起下一轮;“症状要点”允许放入医生的完整问句。模型还会重复询问已有年龄,且只有整份 JSON 通过后才显示结果。
|
||||
|
||||
## 已实现
|
||||
|
||||
- 首次已保存转写后等待约 0.8 秒发起分析,后续更新等待改为 2 秒。等待从第一段新增内容起算,持续说话不会无限推迟。每个窗口仍只有一个在途分析,期间新内容合并,已到期的下一轮不会在上一轮结束后再次等待。
|
||||
- 服务端完整验证一条带合法分隔符的结果后,通过 `live_update` 提前交付累计内容,不再等待整个数组闭合。按实际可展示条目增加发送,实时最多 12 次、复盘最多 15 次,最终仍需 `done`。原始 JSON 片段不展示;客户端同样验证诊单、通话、转写会话、版本及所有引用。失败保留已经可核对的内容,并标明本轮尚未完成。
|
||||
- 优先生成最多三条“下一步追问”,给出简短理由;实时辅助依据完整本次对话减少重复,通话后复盘仍结合授权病历。保留发病年龄、历史年龄和家属信息等必要的追问空间。
|
||||
- 患者摘要由已校验的引用 ID 还原完整原话,不采用模型改写的事实。省略医生、未知说话人和单纯问题选段。合法 JSON 代码块包装可以解析;引用、数据范围和内容校验继续执行。
|
||||
- 侧栏首问突出显示,再展示患者关键信息、待核实及复盘。显示实际已用时间、待处理分段和内容依据时间;区分连接、超时、格式、引用、权限等失败,不再统一提示升级服务端。
|
||||
- 去除模型输入中当前转写和授权历史的重复副本,保留完整来源、资料权限、附件清单和现有超时预算。增加首条有效建议及整轮耗时的安全日志,不记录患者原文或模型正文。
|
||||
- 沟通追问可帮助了解患者诉求、理解困难和执行顾虑,不预设需要新增治疗、检查或购买项目。腾讯云实时转写、简体中文及现有通话流程保持原配置。
|
||||
|
||||
## 验证与构建
|
||||
|
||||
- 客户端 Python 相关回归:277 项通过;Ruff 通过。
|
||||
- 前端组件、通话和布局等测试:136 项通过;Vue 类型检查、生产构建通过。
|
||||
- 服务端质量测试:421 个累计断言;流式集成:851 个累计断言;真实请求构造的响应契约测试:167 个累计检查。它们包含各自复用的基础断言,不能简单相加视为独立用例数。前一轮 SSE 协议、错误回执、心跳、计时、请求生命周期回归通过。
|
||||
- `git diff --check` 通过;未提交或撤销其他开发中的功能。
|
||||
- 构建产物:`app/video_companion/dist/index.html`,脚本 `index-DZWRwUZ-.js`,样式 `index-BbhpEZgS.css`。Vite 仍提示现有视频 SDK 主包体积较大;构建成功。
|
||||
|
||||
测试使用合成资料,未发送真实患者资料,未发起真实通话。第二轮另做了下述一次成功的纯文字在线合成验收。浏览器工具未完成本次视觉验收,组件与布局验证已完成。未重启医生客户端或部署远程服务端。
|
||||
|
||||
## 针对 16 秒反馈的第二轮定位与处理
|
||||
|
||||
11:13 的成功请求在客户端耗时 16,922 ms,首条有效内容 14,952 ms。对应服务端聚合仅 79 ms,未做历史压缩;附件处理 2,800 ms,其中 OCR 2,233 ms;Dify 传输 13,630 ms,其中模型节点开始到首正文约 8,098 ms。这些是相互包含的阶段,不能把嵌套指标重复相加。客户端与服务端按时间及状态关联,不是通过同一 trace ID 直接关联。
|
||||
|
||||
此次新增处理:
|
||||
|
||||
1. 修复公共 Dify 传输给实时任务附加长报告诊疗规则的冲突。仅服务端选定 `response_contract=live_consultation` 的问诊/复盘使用简短的实时结构化契约,普通诊疗报告保持原规则。当前完整资料、附件、否定/日期/角色及“不采脉”边界均保留。
|
||||
2. 逐条交付第一条已校验内容,不等后续问题和整组输出。医生/未知来源不能被理由改写成“患者自述”,明确的无患者依据事实前提会省略。
|
||||
3. 增加 300 秒 OCR 私有缓存,按凭据、应用端点、用户、原图内容、识别配置和运行环境绑定。每次仍重新校验当前来源;失败或识别预算耗尽不缓存。正常无文字图片可按原 unreadable 状态复用,原图仍发送,未减少医学资料。缓存上限 64 个槽位、32 MiB;实际图片内容及模型身份变化即失效。
|
||||
4. 客户端分别显示首条有效结果和整轮完成时间,未知首条时间不显示为零。
|
||||
|
||||
OCR 新增 45 个离线断言通过;原桥接 25、预算 13、上传复用 62 项检查通过。两项外围测试仍失败,已用 Git HEAD 对应实现复现相同失败,未掩盖或计入通过:`DifyImageTextEvidenceTest.php:30` 的既有索引文案断言,以及 `DifyRequiredAttachmentUploadTest.php:519` 的既有“全缺失附件 + 无效配置”断言。后者在沙箱内先受回环测试服务器限制,在正常回环环境下才到达该断言。
|
||||
|
||||
在线合成验收使用现有 Qwen/Dify、无图片、无真实患者资料。一次成功请求的首条有效结果为 **1,306 ms**、整轮 **2,181 ms**,JSON 与引用校验通过。沙箱内两次连接立即失败,随后允许网络的同一合成脚本成功;不把失败连接算作模型速度样本。该结果只证明轻量文字请求可以快速且按契约返回,不能证明原来带图病例的 16.9 秒已降到 2.2 秒,也不是控制变量前后对比。实际带图问诊的缓存收益、首条和整轮耗时仍待部署后的相同场景验证。
|
||||
|
||||
## 生效与验收
|
||||
|
||||
客户端需要加载本次构建并重新启动;使用远程 PHP 服务时需同步服务端改动。旧服务端仍可通过最终 `done` 返回结果,但不能提前交付建议。
|
||||
|
||||
下一次实际使用应比较“已保存转写至首条有效建议”的耗时和校验失败率,同时由医生检查追问相关性、信息遗漏及患者理解情况。0.8 秒、2 秒仅为发起请求前的等待,不是模型响应承诺。本轮不声称已经验证诊断准确率或成单率提升。
|
||||
|
||||
## 纯对话实时模式
|
||||
|
||||
根据用户“仅限视频接通后的 AI 那一块”的明确限定,只有 `live_consultation` 改为 `current_call_only`。视频中的自动更新与重新生成只提交本次会话已保存的全部转写;不读取诊单详情、历史病历,不做病历压缩、OCR 或附件上传。权限、有效诊单、通话归属、会话身份与完整转写快照的校验仍在;原有 1 MiB 容量超限会明确拒绝,不截断早期文字。
|
||||
|
||||
`live_review` 保持 `authorized_case`,继续结合授权病历与图片;IM 总结、追问、起草回复及普通病历 AI 未改。实时提示词不再包含未提供的病历块,明确只依照本次对话、跳过已答问题。代价是没有在对话提及的历史过敏、用药、检查等资料不会纳入实时建议,不能将建议视作完整病历评估。
|
||||
|
||||
服务端在 start、live_update、done 返回可信分析范围。客户端只在结果校验通过后更新“当前内容仅依据本次通话文字,不含历史病历和图片”的说明;复盘等待或失败时不会把旧结果标成另一范围。旧服务端未提供范围时也不会误标为纯对话。同一请求中范围不一致会拒绝更新。
|
||||
|
||||
验证:纯对话服务端专测 328 个累计断言,包括 220 个完整分段、超过旧历史压缩阈值的长文本逐字一致、拒绝任何病历详情/历史读取、零附件,以及普通 summary 和完整复盘隔离。真实 Dify 构包测试 203 个累计检查;进度与质量回归仍为 851、421 个累计断言。客户端 277 项、前端 136 项均通过。服务端完整记录在 `app/artifacts/im-ai/dialogue-only-server.md`;其中两组普通临床策略测试的额外既有失败已隔离复现,没有将它们计入通过或改变其行为。
|
||||
|
||||
在线测速仅使用 6 段完全合成的对话,经真实请求构造器及 `streamPreparedAssistant` 的完整流式校验路径请求现有 Qwen/Dify。没有查询真实诊单、患者转写或图片。三轮结果:
|
||||
|
||||
| 轮次 | 首条已校验结果 | 整轮完成 | 结果 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 859 ms | 2,130 ms | 引用与结构校验通过 |
|
||||
| 2 | 785 ms | 2,001 ms | 引用与结构校验通过 |
|
||||
| 3 | 806 ms | 2,021 ms | 引用与结构校验通过 |
|
||||
|
||||
计时包括纯请求构造与真实流式模型处理,不含语音转写、保存分段、触发等待和客户端渲染。每轮 query 为 5,526 bytes、6 个分段、零附件,首轮与后续轮次均使用独立合成上游用户标识。这不是实际长通话延迟保证,也不是与原带图病例的控制变量对照。数据记录在 `app/artifacts/im-ai/live-dialogue-only-online-timing-20261030.json`。
|
||||
|
||||
尚未部署远程服务端或重启正在运行的医生客户端。需要服务端加载最新代码、客户端加载本次构建后才会生效;腾讯云实时转写与简体中文配置保持原样。
|
||||
@@ -1,92 +0,0 @@
|
||||
# 本地离线语音转写:安装、打包与验证
|
||||
|
||||
> 当前状态(2026-10-30):用户已明确要求恢复腾讯云实时转写、保留简体中文。客户端默认通路已经恢复腾讯云,启动/打包不再自动安装本地 ASR,也不把本地模型加入发布资源。本文后续内容保留为此前本地方案的开发、安装与评估记录,并非当前默认行为。当前通路见 `cloud-transcription-restore.md`。
|
||||
|
||||
运行时使用 faster-whisper 1.2.1,在医生电脑的 CPU 上以 int8 加载本地 Whisper 模型。音频为浏览器桥接传入的单声道、16 kHz、有符号 PCM16 小端字节流;不写临时音频、不发送至 ASR 服务。模型安装和下载只能通过下面的显式命令执行,视频通话不会触发安装、下载或腾讯云语音识别。
|
||||
|
||||
## 开发环境安装
|
||||
|
||||
在已安装医生工作站依赖的 `app` 目录运行:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe scripts/setup_local_transcription.py --install-dependencies --download --model-size small --check
|
||||
```
|
||||
|
||||
此命令明确允许联网安装 `faster-whisper==1.2.1` 及其传递依赖,并从官方 `Systran/faster-whisper-small` 仓库下载模型,然后禁用网络验证 CPU/int8 模型和 Silero VAD 的加载。`tiny`、`base`、`small`、`medium`、`large-v3` 均可选择;中文场景不要使用英文专用 `.en` 模型。开发默认选择 `small`,实际识别准确率和延迟仍需在目标电脑与实际通话音频上验收。
|
||||
|
||||
`--install-dependencies` 仅安装至执行命令的 Python 环境;`--download` 才下载模型。不传操作参数只显示帮助。可用 `--revision <官方仓库提交哈希>` 固定下载版本。
|
||||
|
||||
模型查找顺序为 `DOCTOR_ASR_MODEL_PATH`、开发目录或安装包内的 `resources/local-asr/model`、最后为 `platformdirs.user_data_path("ZhenyangDoctorWorkstation", appauthor="ZhenYangTang") / "local-asr" / "model"`。可以指定独立目录:
|
||||
|
||||
```powershell
|
||||
$env:DOCTOR_ASR_MODEL_PATH = 'D:\DoctorModels\whisper-small'
|
||||
.venv\Scripts\python.exe scripts/setup_local_transcription.py --download --model-size small --check
|
||||
```
|
||||
|
||||
`--model-path` 只覆盖本次安装/检查命令;工作站仍按上述顺序查找。下载后会记录 `doctor-asr-install.json`,包含仓库、请求的版本、运行库版本和时间,不包含音频。运行时要求目录存在,且 `model.bin`、`config.json`、`tokenizer.json`、`vocabulary.txt` 或 `vocabulary.json` 非空。缺失时直接报错。`tokenizer.json` 必须随模型提供,以阻止上游缺失 tokenizer 时的自动获取回退。
|
||||
|
||||
离线电脑可通过离线安装包安装运行库,再复制完整模型目录;不要在通话过程中初始化下载。离线检查:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe scripts/setup_local_transcription.py --check
|
||||
```
|
||||
|
||||
## 桌面安装包
|
||||
|
||||
为应用配置 `local-asr` 可选依赖(`faster-whisper==1.2.1`),并在实际 PyInstaller 构建环境安装该额外依赖。运行库需要 NumPy、CTranslate2、tokenizers、ONNX Runtime、PyAV 等上游依赖。不能仅在开发 `.venv` 安装后假设 `.venv-build` 或已冻结的 exe 自动拥有这些依赖。
|
||||
|
||||
PyInstaller spec 已加入 `faster_whisper` 数据文件(包括 Silero VAD)及 `ctranslate2`、`onnxruntime`、`av`、`tokenizers` 的 `collect_all`,缺少运行库时构建会明确失败。Windows/macOS 运行环境准备与打包脚本已加入 `--extra local-asr`,依赖锁文件同步更新。构建前可把完整模型放在 `app/resources/local-asr/model`,随现有 resources 打入安装包;也可在目标电脑独立安装到应用数据目录或管理员指定目录。模型不纳入 Git。该模块导入依赖是延迟执行的,没有安装本地 ASR 运行库也不会阻止工作站、视频和录音模块启动。
|
||||
|
||||
本轮未生成新 exe 或安装包。发布前仍需验证运行库、模型和 VAD 在成品内真实可用,不能把开发环境通过的单元测试作为成品 ASR 可用性的证明。旧系统兼容性取决于这些原生依赖的官方 wheel 和操作系统支持,不自动沿用工作站其他部分的兼容性声明。
|
||||
|
||||
## 验证
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe -m pytest tests/test_local_transcription.py
|
||||
.venv\Scripts\python.exe -m ruff check src/doctor_workstation/video/local_transcription.py tests/test_local_transcription.py scripts/setup_local_transcription.py
|
||||
.venv\Scripts\python.exe scripts/setup_local_transcription.py --check --smoke-wav D:\ASR-Test\non-sensitive-16k-mono.wav
|
||||
```
|
||||
|
||||
smoke WAV 必须是单声道 16 kHz PCM16,最长 12 秒。该命令阻止网络连接并输出识别结果;请使用无患者信息的人工测试音频。建议覆盖短回答“有”“不”、否定句、药物名称、0.5/5、剂量单位、静音、背景噪声,以及医生和患者同时说话。录音通道的角色来源于浏览器端音轨身份,模型不做声纹识别。
|
||||
|
||||
单元测试使用替代引擎,验证会话隔离、异步回调、队列上限、序号验证、排空停止、错误脱敏、静音和数字/否定词的原样输出。替代引擎测试不证明实际模型准确率。启动和推理只能在后台执行;Qt 接收方通过 signal 转交主线程。`close()` 立即取消回调,正在执行的原生推理可能在守护线程中完成,不能在 UI 线程等待它。
|
||||
|
||||
2026-10-29 已在本仓库 `.venv` 安装运行库,并在 `app/resources/local-asr/model` 安装官方 `Systran/faster-whisper-small`。CPU/int8 模型和 VAD 加载检查通过;使用 [FunASR 官方示例](https://github.com/modelscope/FunASR)提供的[公开中文音频](https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/asr_example_zh.wav)完成真实识别,检查及推理期间阻断网络。输出为“欢迎大家来体验打磨院推出的语音识别模型”,出现“达摩院”的同音误识;这验证了本机推理链路,不能代替医疗词汇、噪声、双向通话及目标电脑负载验收。没有发送真实患者资料,尚未测试真实 AI 服务响应。
|
||||
|
||||
## 视频 AI 接入与验收
|
||||
|
||||
现有腾讯音视频通信、IM 和云端录制继续使用;语音转写改由本地音轨 PCM 和本机模型完成。完成分段保存成功后才触发 AI,约八秒合并更新一次,无新增原文时不重复请求。使用现有 `tcm.diagnosis/aiAssistantStream` 的 `live_consultation`/`live_review` 任务;服务端按医生、诊单、通话及转写会话读取完整原文,再连同授权病历交给已授权的现有 Dify 服务。AI 不发送消息或自动写入病历。
|
||||
|
||||
客户端新增 AI 辅助、对话原文、患者资料标签、可调侧栏宽度和窄屏抽屉。挂断后在 IM 顶部打开“本次通话复盘”;点击复盘按钮请求复盘草稿。每条辅助结果可以查看完整引用原话,转写未完整保存时明确显示状态。模型缺失、AI 服务未更新或没有权限时显示具体状态,视频通话可继续。
|
||||
|
||||
生效需要部署本轮服务端代码,并重启使用新构建资源的客户端。开发验证只使用合成通话数据及公开音频,不连接真实患者。上线验收需在医生测试账号和合成患者下确认双方音轨归属、转写时延、挂断排空、服务端 AI JSON 格式、取消与复盘。
|
||||
|
||||
模型/存储准备阶段先采集到最多 12 个 PCM 分段的内存缓冲;超限明确标记转写不完整。挂断后等待原生识别线程排空才封存文字,15 秒仅提示等待,不提前关闭文字存储。关闭应用时沿用 190 秒异常收尾上限,强制退出会把未完成转写标记为 partial。同会话的存储启动临时失败可以显式重试,正在执行或已成功的启动请求仍复用。
|
||||
|
||||
音轨接入适配当前锁定的 CallEngine 3.5.9 / TRTCCloud 2.10.19:`getTRTCCloudInstance()` 返回包装对象,音轨 API 来自其 `_trtc`。`resolveTrtcAudioSource` 先验证实际能力,并保留方法所属实例;升级 SDK 时需重新运行真实包装对象的隔离验证。前端采集失败优先覆盖旧的 native running 状态,并保留独立错误文字和重试入口。持续声音或非零底噪的 PCM 提交窗口为约 4 秒,之后才排队识别,因此字幕按分段追加,不是逐字流式识别。无需提高音量来触发分段,轻声和短否定词不会因前端音量阈值被丢弃。
|
||||
|
||||
该音轨修复后,118 项前端测试和 63 项转写桥接/通话回归通过,生产资源已重建。公开语音在隔离 Qt 中贯通了实际 SDK 包装适配、生产音频采集、真实 WebChannel、本地 faster-whisper、Qt 信号及实际 App 字幕 DOM,双方共 8 段均显示;首段实测 6.494 秒。SDK 实例的媒体获取替换为公开音频双轨,存储使用内存,因此仍不代表真实 RTC 发布/订阅与在线持久化已验收。详细材料为 `app/artifacts/im-ai/asr-fixed-end-to-end.md`。已打开的通话页面不会自动载入新脚本,结束当前通话后需关闭并重新打开 IM/视频窗口。
|
||||
|
||||
本轮回归:384 项 Python 用例、113 项前端用例通过;PHP 新流式链路 440 项合成断言及 13 组既有回归通过。另有两个既有 PHP 套件在未修改的 HEAD 上同样失败,详见 `app/artifacts/im-ai/live-ai-server-implementation.md`,未将它们计入通过数。Vue 类型检查、前端生产构建、Python Ruff 和 diff 空白检查通过。隔离 QtWebEngine 加载本地合成页面,验证挂断入口、打开不重新生成、完整引用、弹窗 Tab 焦点循环、Escape 返回焦点和 440px 下按钮可见,截图位于 `app/artifacts/im-ai/video-ai-final-*.png`。未执行 macOS 真机构建或冻结安装包验收。
|
||||
|
||||
## 核对的官方来源(2026-10-29)
|
||||
|
||||
- [faster-whisper v1.2.1 模型和转写接口](https://github.com/SYSTRAN/faster-whisper/blob/v1.2.1/faster_whisper/transcribe.py):本地目录、`local_files_only`、CPU/int8 参数、数组音频输入、惰性 segments、tokenizer 回退。
|
||||
- [faster-whisper v1.2.1 本地 VAD](https://github.com/SYSTRAN/faster-whisper/blob/v1.2.1/faster_whisper/vad.py):Silero ONNX 资产和 VAD 参数。保留 `min_speech_duration_ms=0`,避免额外丢弃短否定词。
|
||||
- [faster-whisper 下载实现](https://github.com/SYSTRAN/faster-whisper/blob/master/faster_whisper/utils.py):官方模型映射与模型文件列表。
|
||||
- [Systran/faster-whisper-small 文件清单](https://huggingface.co/Systran/faster-whisper-small/tree/main):本地模型、tokenizer 和词表文件。
|
||||
|
||||
## 简体输出与多方言边界(2026-10-30)
|
||||
|
||||
`opencc-python-reimplemented==0.1.7` 是客户端基础依赖。使用随包配置/词典进行本地 `t2s` 字形转换,在原生转写 controller 发出字幕/保存事件前统一为简体;实时字幕、存储和新通话 AI 引用使用同一份文字。已有通话记录打开“面诊对话文字”时以简体显示,不批量改写历史数据库。数字、剂量、否定词、标点和方言词语保留,不使用大模型改写原话。字形转换不能修复误听,也不把粤语词汇翻译成普通话。
|
||||
|
||||
安装工具已包含该依赖,PyInstaller 收集 `opencc` 配置和词典;模型启动时预加载转换资源,缺失则明确报错。不要同时安装同样提供 `opencc` 导入名的原生 `opencc` 分发。基础依赖与锁文件更新后,源码运行需要结束通话并重启客户端;单独重新打开网页不会重载原生 Python 代码。已冻结的安装包需要重新构建。
|
||||
|
||||
当前通用 Whisper small 不等于多方言专项模型。7 类方言/26 种地域口音的 Fun-ASR-Nano 是本地替代候选,具体能力范围、CPU 成本和离线测试方案见 `app/artifacts/im-ai/dialect-asr-research.md`;未通过目标电脑的双路时延及对应方言准确率验收前,不应声称“所有方言准确识别”。
|
||||
|
||||
本机已在隔离环境完成 Nano CPU float32 公开普通话/粤语测试,固定官方权重通过 SHA-256 校验,加载/推理均禁网。Nano 可以保留这条粤语样本词形,但普通话“开放时间”误成“开饭时间”,没有 VAD 的粤语尾段生成额外“对。”。4 秒双路负载预算也缺乏余量;这些结果不支持默认切换。详细输出、耗时和内存见 `app/artifacts/im-ai/dialect-asr-benchmark.md`。该评估没有修改应用运行环境,没有宣称四川/湖南已验收。
|
||||
|
||||
后续同机 VAD + 动态 int8 有界实测完成 24 个案例,15 次正常生成、9 次无语音输入被 VAD 跳过;短样本平均耗时下降,但量化期间峰值工作集约 5.7 GiB,且输出词形改变。未验证四川/湖南、医疗数字/否定语音和持续视频负载,因此保持默认引擎。完整结果为 `app/artifacts/im-ai/dialect-asr-quantized-benchmark.md`。评估环境、公开样本及权重保存在 `app/artifacts/im-ai/nano-*`,不会随客户端 resources 打包。
|
||||
|
||||
- [转换库发布者文档与固定版本](https://pypi.org/project/opencc-python-reimplemented/0.1.7/):纯 Python、离线词典、t2s 配置。
|
||||
- [Fun-ASR-Nano 官方模型卡](https://huggingface.co/FunAudioLLM/Fun-ASR-Nano-2512):明确列出的多方言/地域口音范围。
|
||||
@@ -1,143 +0,0 @@
|
||||
"""Render the real native client with synthetic data for UI design review."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
os.environ.setdefault("DOCTOR_MOTION", "off")
|
||||
|
||||
from PySide6.QtCore import QSettings, QThreadPool
|
||||
from PySide6.QtGui import QImage
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from doctor_workstation.services import DemoDoctorRepository
|
||||
from doctor_workstation.ui import ShellWindow, apply_theme
|
||||
from doctor_workstation.ui.login import LoginWindow
|
||||
|
||||
ROUTES = {
|
||||
"appointments": "挂号列表",
|
||||
"consultations": "问诊列表",
|
||||
"patients": "我的患者",
|
||||
"prescription_library": "我的处方库",
|
||||
"prescriptions": "已开处方",
|
||||
"reception": "接诊台",
|
||||
}
|
||||
|
||||
|
||||
def settle(app: QApplication) -> None:
|
||||
for _ in range(4):
|
||||
QThreadPool.globalInstance().waitForDone(3000)
|
||||
app.processEvents()
|
||||
QTest.qWait(75)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, default=Path("artifacts/client-design"))
|
||||
args = parser.parse_args()
|
||||
output = args.output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
app = QApplication.instance() or QApplication([])
|
||||
apply_theme(app)
|
||||
repo = DemoDoctorRepository()
|
||||
records = []
|
||||
|
||||
def capture(window, name: str, title: str) -> None:
|
||||
settle(app)
|
||||
filename = f"{name}.png"
|
||||
if not window.grab().save(str(output / filename)):
|
||||
raise RuntimeError(f"Could not save {filename}")
|
||||
records.append({
|
||||
"title": title, "file": filename,
|
||||
"width": window.width(), "height": window.height(),
|
||||
})
|
||||
|
||||
# Isolate preview settings from the user's saved account and credentials.
|
||||
settings = QSettings(str(output / "preview-login.ini"), QSettings.Format.IniFormat)
|
||||
settings.clear()
|
||||
login = LoginWindow(repo, settings=settings)
|
||||
login.show()
|
||||
for width, height in ((1280, 800), (860, 640)):
|
||||
login.resize(width, height)
|
||||
capture(login, f"login-{width}", "登录工作站")
|
||||
login.close()
|
||||
|
||||
session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD)
|
||||
shell = ShellWindow(
|
||||
repo, {"session": session, "demo_mode": True}, permissions=session.permissions,
|
||||
)
|
||||
shell.show()
|
||||
try:
|
||||
for width, height in ((1440, 900), (1024, 640)):
|
||||
shell.resize(width, height)
|
||||
for route, title in ROUTES.items():
|
||||
shell.navigate(route)
|
||||
capture(shell, f"{route}-{width}", title)
|
||||
finally:
|
||||
settle(app)
|
||||
shell.close()
|
||||
|
||||
# Include independently rendered dialog/media fixtures when available.
|
||||
supplementary = [
|
||||
("patient_orders_1366x768.png", "患者业务订单"),
|
||||
("patient_progress_1366x768.png", "患者进度"),
|
||||
("clinical-after/appointment_drawer_1440x900.png", "预约编辑"),
|
||||
("clinical-after/diagnosis_edit_1440x900.png", "诊单编辑"),
|
||||
("clinical-after/diagnosis_edit_1024x640.png", "诊单编辑 · 紧凑窗口"),
|
||||
("clinical-after/diagnosis_index_1440x900.png", "诊单列表"),
|
||||
("assistant-1440.png", "AI 问诊"),
|
||||
("assistant-1080.png", "AI 问诊 · 紧凑窗口"),
|
||||
("../subwindow_exact/prescription_editor_860x900.png", "处方编辑"),
|
||||
("../subwindow_exact/prescription_ai_report_920x760.png", "处方报告"),
|
||||
("video-call-1120x760.png", "视频面诊"),
|
||||
("video-call-440x300.png", "视频面诊 · 小窗"),
|
||||
("video-chat-440x300.png", "视频聊天 · 小窗"),
|
||||
("video-preview-1120x760.png", "视频截图确认"),
|
||||
]
|
||||
for filename, title in supplementary:
|
||||
preview = QImage(str(output / filename))
|
||||
if not preview.isNull():
|
||||
records.append({
|
||||
"title": title, "file": filename,
|
||||
"width": preview.width(), "height": preview.height(),
|
||||
})
|
||||
|
||||
(output / "gallery.json").write_text(
|
||||
json.dumps(records, ensure_ascii=False, indent=2), encoding="utf-8",
|
||||
)
|
||||
cards = []
|
||||
for record in records:
|
||||
filename = html.escape(record["file"])
|
||||
title = html.escape(record["title"])
|
||||
cards.append(
|
||||
f'<section><h2>{title} <small>{record["width"]} × {record["height"]}</small>'
|
||||
f'</h2><a href="{filename}"><img src="{filename}" alt="{title}" loading="lazy">'
|
||||
'</a></section>'
|
||||
)
|
||||
(output / "index.html").write_text(
|
||||
'<!doctype html><html lang="zh-CN"><meta charset="utf-8">'
|
||||
'<meta name="viewport" content="width=device-width, initial-scale=1">'
|
||||
'<title>医生工作站 · 客户端设计验收</title><style>'
|
||||
'body{margin:0;padding:32px;background:#F5F7FA;color:#223047;'
|
||||
'font-family:"Microsoft YaHei",sans-serif}main{max-width:1440px;margin:auto}'
|
||||
'h1{font-size:28px}p,small{color:#647287}small{font-weight:400;font-size:14px}'
|
||||
'section{margin:32px 0 48px}h2{font-size:20px;display:flex;gap:20px;align-items:baseline}'
|
||||
'img{width:100%;display:block;border:1px solid #E6EAF0;border-radius:16px}'
|
||||
'a:focus-visible{outline:3px solid #6D8CCB}footer{padding:24px 0}'
|
||||
'</style><main><h1>医生工作站 · 客户端设计验收</h1>'
|
||||
'<p>使用演示数据渲染的真实客户端。点击图片查看原始尺寸。</p>'
|
||||
+ "".join(cards)
|
||||
+ '<footer>主窗口与紧凑窗口均按实际控件排版生成。</footer></main></html>',
|
||||
encoding="utf-8",
|
||||
)
|
||||
print(output / "index.html")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,193 +0,0 @@
|
||||
"""Explicit installation/download/check CLI; never invoked by a live call.
|
||||
|
||||
Run with --help for examples. With no action flags this only prints help.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import wave
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
APP_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(APP_ROOT / "src"))
|
||||
|
||||
MODEL_REPOS = {
|
||||
size: f"Systran/faster-whisper-{size}"
|
||||
for size in ("tiny", "base", "small", "medium", "large-v3")
|
||||
}
|
||||
RUNTIME_REQUIREMENT = "faster-whisper==1.2.1"
|
||||
TEXT_REQUIREMENT = "opencc-python-reimplemented==0.1.7"
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Install or verify local CPU/int8 speech recognition before making calls.",
|
||||
epilog=(
|
||||
"Example: python scripts/setup_local_transcription.py "
|
||||
"--install-dependencies --download --model-size small --check. "
|
||||
"Offline check: python scripts/setup_local_transcription.py --check. "
|
||||
"A packaged app must ship the runtime; installing into another Python "
|
||||
"does not alter a frozen executable."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--install-dependencies",
|
||||
action="store_true",
|
||||
help="Explicitly run pip in this Python environment.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--download",
|
||||
action="store_true",
|
||||
help="Explicitly download the selected official model from Hugging Face.",
|
||||
)
|
||||
parser.add_argument("--model-size", choices=tuple(MODEL_REPOS), default="small")
|
||||
parser.add_argument(
|
||||
"--model-path",
|
||||
type=Path,
|
||||
help="Override DOCTOR_ASR_MODEL_PATH or the app data model directory.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--revision", default="main", help="Official repository revision/commit for model download."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--check",
|
||||
action="store_true",
|
||||
help="Load the local model and VAD on CPU with networking disabled.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--smoke-wav",
|
||||
type=Path,
|
||||
help="Optional non-sensitive mono 16 kHz PCM16 WAV, at most 12 seconds; recognized text is printed.",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
if not (args.install_dependencies or args.download or args.check or args.smoke_wav):
|
||||
parser.print_help()
|
||||
return args
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_args(argv)
|
||||
if not (args.install_dependencies or args.download or args.check or args.smoke_wav):
|
||||
return 0
|
||||
if args.install_dependencies:
|
||||
installer = [sys.executable, "-m", "pip", "install"]
|
||||
if importlib.util.find_spec("pip") is None:
|
||||
uv = shutil.which("uv")
|
||||
if not uv:
|
||||
print(
|
||||
"This environment has no pip. Install with uv pip install --python <python> "
|
||||
f"{RUNTIME_REQUIREMENT} {TEXT_REQUIREMENT}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
installer = [uv, "pip", "install", "--python", sys.executable]
|
||||
subprocess.run(
|
||||
[*installer, RUNTIME_REQUIREMENT, TEXT_REQUIREMENT, "platformdirs>=4.3,<5"],
|
||||
check=True,
|
||||
)
|
||||
|
||||
from doctor_workstation.core.transcript_text import simplified_transcript
|
||||
from doctor_workstation.video.local_transcription import (
|
||||
MAX_PCM_BYTES,
|
||||
SAMPLE_RATE,
|
||||
FasterWhisperEngine,
|
||||
LocalTranscriptionError,
|
||||
default_model_path,
|
||||
local_transcription_readiness,
|
||||
)
|
||||
|
||||
path = args.model_path.expanduser().resolve() if args.model_path else default_model_path()
|
||||
try:
|
||||
if args.download:
|
||||
from huggingface_hub import snapshot_download
|
||||
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
repo = MODEL_REPOS[args.model_size]
|
||||
print(f"Downloading {repo} into {path}")
|
||||
snapshot_download(
|
||||
repo_id=repo,
|
||||
revision=args.revision,
|
||||
local_dir=str(path),
|
||||
allow_patterns=[
|
||||
"config.json",
|
||||
"preprocessor_config.json",
|
||||
"model.bin",
|
||||
"tokenizer.json",
|
||||
"vocabulary.*",
|
||||
"README.md",
|
||||
"LICENSE*",
|
||||
],
|
||||
token=False,
|
||||
)
|
||||
(path / "doctor-asr-install.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"repository": repo,
|
||||
"requestedRevision": args.revision,
|
||||
"runtimeRequirement": RUNTIME_REQUIREMENT,
|
||||
"textRequirement": TEXT_REQUIREMENT,
|
||||
"installedAt": datetime.now(UTC).isoformat(),
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
if args.check or args.smoke_wav or args.download:
|
||||
# This affects only the explicit setup/check process. The runtime
|
||||
# already requires complete local files and local_files_only=True.
|
||||
os.environ["HF_HUB_OFFLINE"] = "1"
|
||||
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
|
||||
print(json.dumps(local_transcription_readiness(path), ensure_ascii=False, indent=2))
|
||||
# The hub may already have been imported during --download, so its
|
||||
# offline environment flag alone is not a sufficient verification.
|
||||
# Block sockets in this standalone check process as well.
|
||||
blocked = RuntimeError("Network access is disabled during local ASR verification")
|
||||
with (
|
||||
patch("socket.socket.connect", side_effect=blocked),
|
||||
patch("socket.socket.connect_ex", side_effect=blocked),
|
||||
patch("socket.getaddrinfo", side_effect=blocked),
|
||||
):
|
||||
engine = FasterWhisperEngine(path)
|
||||
print("Local model and VAD loaded successfully (CPU/int8; network blocked).")
|
||||
if args.smoke_wav:
|
||||
with wave.open(str(args.smoke_wav), "rb") as audio:
|
||||
if (
|
||||
audio.getnchannels(),
|
||||
audio.getsampwidth(),
|
||||
audio.getframerate(),
|
||||
audio.getcomptype(),
|
||||
) != (1, 2, SAMPLE_RATE, "NONE"):
|
||||
raise ValueError("Smoke WAV must be mono 16 kHz uncompressed PCM16.")
|
||||
if not 0 < audio.getnframes() <= MAX_PCM_BYTES // 2:
|
||||
raise ValueError(
|
||||
"Smoke WAV must contain between one sample and 12 seconds."
|
||||
)
|
||||
pcm = audio.readframes(audio.getnframes())
|
||||
print(f"Recognized text: {simplified_transcript(engine.transcribe(pcm))}")
|
||||
return 0
|
||||
except LocalTranscriptionError as error:
|
||||
print(f"Local ASR setup failed ({error.code}): {error}", file=sys.stderr)
|
||||
except ImportError:
|
||||
print(
|
||||
"Required packages are missing; run with --install-dependencies first.", file=sys.stderr
|
||||
)
|
||||
except (OSError, ValueError, RuntimeError) as error:
|
||||
print(
|
||||
f"Local ASR setup failed: {type(error).__name__}. Check model files, WAV format, and connectivity for explicit downloads.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -3,7 +3,7 @@
|
||||
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
|
||||
|
||||
# Single source of truth for runtime, package, installer, and executable versions.
|
||||
__version__ = "1.5.1"
|
||||
__version__ = "1.5.0"
|
||||
|
||||
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
|
||||
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
|
||||
|
||||
@@ -41,7 +41,6 @@ from doctor_workstation.ui.widgets import (
|
||||
friendly_error,
|
||||
gender_text,
|
||||
get_value,
|
||||
has_permission,
|
||||
run_async,
|
||||
set_authentication_expired_handler,
|
||||
show_toast,
|
||||
@@ -940,11 +939,6 @@ class ApplicationController(QObject):
|
||||
open_im=open_im,
|
||||
patient_name=patient_name,
|
||||
patient_case=patient_case,
|
||||
can_ai_assistant=has_permission(
|
||||
getattr(self.shell_window, "permissions", None),
|
||||
"tcm.diagnosis/aiAssistant",
|
||||
default=False,
|
||||
),
|
||||
on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: (
|
||||
self._open_video_diagnosis(current_id, call_key=current_key)
|
||||
),
|
||||
@@ -1030,14 +1024,11 @@ class ApplicationController(QObject):
|
||||
lambda _result, expected=generation: self._restore_video_preview(expected)
|
||||
)
|
||||
try:
|
||||
set_close_handler = getattr(video_window, "set_compact_close_handler", None)
|
||||
if callable(set_close_handler):
|
||||
set_close_handler(lambda expected=generation: self._restore_video_preview(expected))
|
||||
video_window.raise_()
|
||||
dialog.raise_()
|
||||
dialog.activateWindow()
|
||||
except RuntimeError:
|
||||
self._restore_video_preview(generation, activate=False)
|
||||
self._video_preview_state = None
|
||||
|
||||
def _restore_video_preview(
|
||||
self,
|
||||
@@ -1054,12 +1045,6 @@ class ApplicationController(QObject):
|
||||
self._video_preview_generation += 1
|
||||
window = state.get("window")
|
||||
try:
|
||||
set_close_handler = getattr(window, "set_compact_close_handler", None)
|
||||
if callable(set_close_handler):
|
||||
set_close_handler(None)
|
||||
restore_screenshot = getattr(window, "restore_screenshot_preview", None)
|
||||
if callable(restore_screenshot):
|
||||
restore_screenshot()
|
||||
window.setWindowFlag(
|
||||
Qt.WindowType.WindowStaysOnTopHint,
|
||||
bool(state.get("stays_on_top")),
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
"""Offline script conversion for speech transcripts, without paraphrasing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from threading import local
|
||||
|
||||
_converters = local()
|
||||
|
||||
|
||||
def simplified_transcript(text: str) -> str:
|
||||
"""Convert character forms only; retain dialect words, numbers and negations.
|
||||
|
||||
Each thread owns its converter. Cache dictionaries, never patient text.
|
||||
The t2s configuration deliberately excludes regional vocabulary rewriting.
|
||||
Missing package data is an error, rather than silently mixing scripts.
|
||||
"""
|
||||
converter = getattr(_converters, "simplified", None)
|
||||
if converter is None:
|
||||
from opencc import OpenCC
|
||||
|
||||
converter = OpenCC("t2s")
|
||||
_converters.simplified = converter
|
||||
return converter.convert(text)
|
||||
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import struct
|
||||
import zlib
|
||||
from collections.abc import Callable, Mapping, Sequence
|
||||
@@ -2847,22 +2846,11 @@ class DemoDoctorRepository:
|
||||
}
|
||||
)
|
||||
|
||||
def sync_im_chat_messages(
|
||||
self, diagnosis_id: int, *, scope: str = "", sync_token: str = ""
|
||||
) -> dict[str, Any]:
|
||||
"""Complete synthetic archive sync while retaining the legacy receipt."""
|
||||
def sync_im_chat_messages(self, diagnosis_id: int) -> dict[str, Any]:
|
||||
"""Acknowledge the same asynchronous sync contract in demo mode."""
|
||||
|
||||
self._find_consultation(diagnosis_id)
|
||||
if scope not in {"", "current"}:
|
||||
raise ValueError("IM sync scope must be empty or current")
|
||||
if not isinstance(sync_token, str) or (
|
||||
sync_token and re.fullmatch(r"[a-f0-9]{48}", sync_token) is None
|
||||
):
|
||||
raise ValueError("IM sync token is invalid")
|
||||
return {
|
||||
"queued": True, "diagnosis_id": diagnosis_id,
|
||||
"completed": True, "phase": "completed", "errors": [],
|
||||
}
|
||||
return {"queued": True, "diagnosis_id": diagnosis_id}
|
||||
|
||||
def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]:
|
||||
"""Build demo audit rows from the diagnosis appointments."""
|
||||
|
||||
@@ -214,13 +214,6 @@ class DoctorRepository(Protocol):
|
||||
def cancel_diagnosis_ai(self, diagnosis_id: int, request_id: str) -> dict[str, Any]:
|
||||
"""Request server/upstream cancellation of one correlated stream."""
|
||||
|
||||
def stream_video_ai(
|
||||
self, diagnosis_id: int, *, call_record_id: int,
|
||||
transcription_session_id: str, task: str = "live_consultation",
|
||||
request_id: str, cancelled: Callable[[], bool] | None = None,
|
||||
) -> Iterator[dict[str, Any]]:
|
||||
"""Analyze the server-owned snapshot of this exact video call."""
|
||||
|
||||
def generate_ai_prescription(self, diagnosis_id: int) -> dict[str, Any]:
|
||||
"""Generate a server-validated prescription draft for doctor review."""
|
||||
|
||||
@@ -699,10 +692,8 @@ class DoctorRepository(Protocol):
|
||||
) -> dict[str, Any]:
|
||||
"""Return diagnosis IM messages, defaulting to the fast archive-only path."""
|
||||
|
||||
def sync_im_chat_messages(
|
||||
self, diagnosis_id: int, *, scope: str = "", sync_token: str = ""
|
||||
) -> Any:
|
||||
"""Advance one server-side archive page; inspect completed before using it."""
|
||||
def sync_im_chat_messages(self, diagnosis_id: int) -> Any:
|
||||
"""Queue the server-side IM archive synchronisation job."""
|
||||
|
||||
def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]:
|
||||
"""Return per-diagnosis registration / cancellation audit rows."""
|
||||
@@ -1485,42 +1476,6 @@ class RemoteDoctorRepository:
|
||||
yield {"event": "delta", "text": answer, "fallback": True}
|
||||
yield {**result, "event": "done", "fallback": True}
|
||||
|
||||
def stream_video_ai(
|
||||
self, diagnosis_id: int, *, call_record_id: int,
|
||||
transcription_session_id: str, task: str = "live_consultation",
|
||||
request_id: str, cancelled: Callable[[], bool] | None = None,
|
||||
) -> Iterator[dict[str, Any]]:
|
||||
"""No legacy fallback: an older route cannot bind a live call safely."""
|
||||
|
||||
if (isinstance(diagnosis_id, bool) or not isinstance(diagnosis_id, int)
|
||||
or diagnosis_id <= 0 or isinstance(call_record_id, bool)
|
||||
or not isinstance(call_record_id, int) or call_record_id <= 0):
|
||||
raise ValueError("diagnosis and call_record_id must be positive integers")
|
||||
if (not isinstance(transcription_session_id, str)
|
||||
or re.fullmatch(r"[A-Za-z0-9_-]{1,128}", transcription_session_id) is None):
|
||||
raise ValueError("invalid transcription session")
|
||||
if task not in {"live_consultation", "live_review"}:
|
||||
raise ValueError("unsupported video AI task")
|
||||
body = {
|
||||
"id": diagnosis_id, "task": task,
|
||||
"prompt": "请依据本次通话已保存的原文整理症状、追问和待核实信息,供医生复核。",
|
||||
"call_record_id": call_record_id,
|
||||
"transcription_session_id": transcription_session_id,
|
||||
"request_id": request_id,
|
||||
}
|
||||
for raw in self.client.post_event_stream(
|
||||
"tcm.diagnosis/aiAssistantStream", body, timeout=105.0, cancelled=cancelled,
|
||||
):
|
||||
if cancelled is not None and cancelled():
|
||||
return
|
||||
event = _normalise_diagnosis_ai_event(raw)
|
||||
if event is not None:
|
||||
yield event
|
||||
if event["event"] == "done":
|
||||
return
|
||||
if cancelled is None or not cancelled():
|
||||
raise ApiProtocolError("video AI stream ended before done")
|
||||
|
||||
def cancel_diagnosis_ai(self, diagnosis_id: int, request_id: str) -> dict[str, Any]:
|
||||
"""Use an independent short request, even while the stream is idle."""
|
||||
|
||||
@@ -2647,27 +2602,12 @@ class RemoteDoctorRepository:
|
||||
)
|
||||
return dict(_require_mapping(payload, "tcm.diagnosis/getImChatMessages"))
|
||||
|
||||
def sync_im_chat_messages(
|
||||
self, diagnosis_id: int, *, scope: str = "", sync_token: str = ""
|
||||
) -> Any:
|
||||
"""Advance a bounded archive page, preserving legacy no-option callers."""
|
||||
def sync_im_chat_messages(self, diagnosis_id: int) -> Any:
|
||||
"""Queue the confirmed shutdown-function archive sync endpoint."""
|
||||
|
||||
if diagnosis_id <= 0:
|
||||
raise ValueError("diagnosis_id must be positive")
|
||||
if scope not in {"", "current"}:
|
||||
raise ValueError("IM sync scope must be empty or current")
|
||||
if not isinstance(sync_token, str) or (
|
||||
sync_token and re.fullmatch(r"[a-f0-9]{48}", sync_token) is None
|
||||
):
|
||||
raise ValueError("IM sync token is invalid")
|
||||
payload: dict[str, Any] = {"diagnosis_id": diagnosis_id}
|
||||
if scope:
|
||||
payload["scope"] = scope
|
||||
if sync_token:
|
||||
payload["sync_token"] = sync_token
|
||||
return _client_request(
|
||||
self.client, "post", "tcm.diagnosis/triggerImChatSync", payload, timeout=15.0
|
||||
)
|
||||
return self.client.post("tcm.diagnosis/triggerImChatSync", {"diagnosis_id": diagnosis_id})
|
||||
|
||||
def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]:
|
||||
"""Return registration/cancellation logs from ``guahaoLogList``."""
|
||||
@@ -3103,10 +3043,10 @@ def _normalise_diagnosis_ai_event(raw: Mapping[str, Any]) -> dict[str, Any] | No
|
||||
if not isinstance(text, str):
|
||||
raise ApiProtocolError("AI assistant delta content must be text", data=data)
|
||||
return {"event": "delta", "text": text}
|
||||
if kind in {"live_update", "done"}:
|
||||
if kind == "done":
|
||||
payload.pop("event", None)
|
||||
payload.pop("type", None)
|
||||
return {**payload, "event": kind}
|
||||
return {**payload, "event": "done"}
|
||||
if kind == "error":
|
||||
message = (
|
||||
data
|
||||
|
||||
@@ -23,6 +23,7 @@ from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QFrame,
|
||||
QGraphicsDropShadowEffect,
|
||||
QGraphicsOpacityEffect,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
@@ -42,7 +43,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from ..core.appointment_modes import APPOINTMENT_MODES
|
||||
from .design_system import clinical_stylesheet
|
||||
from .theme import main_window_target_rect
|
||||
from .widgets import (
|
||||
display_text,
|
||||
@@ -84,8 +84,8 @@ QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose {
|
||||
min-height: 32px;
|
||||
max-height: 32px;
|
||||
padding: 0;
|
||||
border: 1px solid transparent;
|
||||
border-radius: $ds_radius_control;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background-color: transparent;
|
||||
color: #606163;
|
||||
font-size: 22px;
|
||||
@@ -95,10 +95,6 @@ QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose {
|
||||
QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose:hover {
|
||||
color: #1A1C1F;
|
||||
background-color: #F0F0F0;
|
||||
}
|
||||
QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose:focus {
|
||||
border-color: $ds_focus;
|
||||
background-color: $ds_accent_soft;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QScrollArea#AppointmentDrawerBody,
|
||||
@@ -114,7 +110,7 @@ QDialog#AppointmentDrawerOverlay QWidget#AppointmentDrawerBodyContent {
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QLabel[appointmentLabel="true"] {
|
||||
color: $ds_muted;
|
||||
color: #1A1C1F;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
@@ -129,7 +125,7 @@ QDialog#AppointmentDrawerOverlay QPlainTextEdit {
|
||||
min-height: 30px;
|
||||
padding: 0 11px;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
border-radius: 9px;
|
||||
background-color: #FFFFFF;
|
||||
color: #1A1C1F;
|
||||
selection-background-color: #EEF1FA;
|
||||
@@ -149,14 +145,7 @@ QDialog#AppointmentDrawerOverlay QPlainTextEdit:hover {
|
||||
QDialog#AppointmentDrawerOverlay QComboBox:focus,
|
||||
QDialog#AppointmentDrawerOverlay QLineEdit:focus,
|
||||
QDialog#AppointmentDrawerOverlay QPlainTextEdit:focus {
|
||||
border: 1px solid #8B9AD9;
|
||||
}
|
||||
QDialog#AppointmentDrawerOverlay QComboBox:disabled,
|
||||
QDialog#AppointmentDrawerOverlay QLineEdit:disabled,
|
||||
QDialog#AppointmentDrawerOverlay QPlainTextEdit:disabled {
|
||||
color: $ds_disabled;
|
||||
background-color: $ds_disabled_surface;
|
||||
border-color: $ds_line;
|
||||
border: 2px solid #8B9AD9;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QComboBox::drop-down {
|
||||
@@ -208,7 +197,7 @@ QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"] {
|
||||
max-height: 38px;
|
||||
padding: 0;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
border-radius: 8px;
|
||||
background-color: #FFFFFF;
|
||||
color: #1A1C1F;
|
||||
font-size: 14px;
|
||||
@@ -232,15 +221,15 @@ QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"]:checked {
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QFrame#AppointmentSlotsPanel {
|
||||
background-color: $ds_surface_alt;
|
||||
background-color: #F7F7F7;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QLabel#AppointmentSlotsTitle {
|
||||
color: #1A1C1F;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots {
|
||||
@@ -258,17 +247,13 @@ QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots {
|
||||
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots:hover {
|
||||
background-color: #EEF1FA;
|
||||
}
|
||||
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots:focus {
|
||||
background-color: $ds_accent_soft;
|
||||
border: 1px solid $ds_focus;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] {
|
||||
min-width: 110px;
|
||||
min-height: 70px;
|
||||
padding: 0 8px;
|
||||
border: 2px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
border-radius: 8px;
|
||||
background-color: #FFFFFF;
|
||||
color: #1A1C1F;
|
||||
}
|
||||
@@ -345,25 +330,25 @@ QDialog#AppointmentDrawerOverlay QLabel#AppointmentEmptyText {
|
||||
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] {
|
||||
background-color: #EEF1FA;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
border-radius: 9px;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="warning"] {
|
||||
background-color: #FFF5E6;
|
||||
border: 1px solid #F6E3C4;
|
||||
border-radius: 10px;
|
||||
border-radius: 9px;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="danger"] {
|
||||
background-color: #FFF1F3;
|
||||
border: 1px solid #F7D7DC;
|
||||
border-radius: 10px;
|
||||
border-radius: 9px;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="success"] {
|
||||
background-color: #EAF9F3;
|
||||
border: 1px solid #D4F0E5;
|
||||
border-radius: 10px;
|
||||
border-radius: 9px;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] QLabel {
|
||||
@@ -393,7 +378,7 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton {
|
||||
max-height: 30px;
|
||||
padding: 0 15px;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
border-radius: 9px;
|
||||
background-color: #FFFFFF;
|
||||
color: #1A1C1F;
|
||||
font-size: 13px;
|
||||
@@ -423,14 +408,9 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[prim
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton:disabled {
|
||||
color: $ds_disabled;
|
||||
border-color: $ds_line;
|
||||
background-color: $ds_disabled_surface;
|
||||
}
|
||||
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[primary="true"]:pressed {
|
||||
color: $ds_surface;
|
||||
background-color: $ds_accent_pressed;
|
||||
border-color: $ds_accent_pressed;
|
||||
color: #FFFFFF;
|
||||
border-color: #EDEDEE;
|
||||
background-color: #8E8F90;
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QFrame#AppointmentLoadingOverlay {
|
||||
@@ -507,7 +487,6 @@ _APPOINTMENT_DARK_REPLACEMENTS = (
|
||||
)
|
||||
# Light is the default application theme. Keep the replacement table available
|
||||
# for a future explicit dark-mode switch, but do not mutate the light source QSS.
|
||||
APPOINTMENT_DRAWER_QSS = clinical_stylesheet(APPOINTMENT_DRAWER_QSS)
|
||||
|
||||
|
||||
def _as_int(value: Any, default: int = 0) -> int:
|
||||
@@ -754,7 +733,35 @@ class _EmptyIllustration(QWidget):
|
||||
painter.end()
|
||||
|
||||
|
||||
class _SlotCard(QPushButton):
|
||||
class _HoverLiftButton(QPushButton):
|
||||
"""Button with a subtle two-pixel lift and blue-tinted shadow on hover."""
|
||||
|
||||
def __init__(self, text: str = "", parent: QWidget | None = None) -> None:
|
||||
super().__init__(text, parent)
|
||||
self._lifted = False
|
||||
self._base_position = QPoint()
|
||||
|
||||
def enterEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API
|
||||
if self.isEnabled() and not self._lifted:
|
||||
self._base_position = self.pos()
|
||||
self.move(self.x(), self.y() - 2)
|
||||
shadow = QGraphicsDropShadowEffect(self)
|
||||
shadow.setBlurRadius(12)
|
||||
shadow.setOffset(0, 4)
|
||||
shadow.setColor(QColor(26, 28, 31, 72))
|
||||
self.setGraphicsEffect(shadow)
|
||||
self._lifted = True
|
||||
super().enterEvent(event)
|
||||
|
||||
def leaveEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API
|
||||
if self._lifted:
|
||||
self.move(self._base_position)
|
||||
self.setGraphicsEffect(None)
|
||||
self._lifted = False
|
||||
super().leaveEvent(event)
|
||||
|
||||
|
||||
class _SlotCard(_HoverLiftButton):
|
||||
"""Two-line time card matching Element's independent time/status typography."""
|
||||
|
||||
def __init__(self, time_text: str, status_text: str) -> None:
|
||||
@@ -812,8 +819,8 @@ class AppointmentDrawer(QDialog):
|
||||
self._today_blocking = False
|
||||
self._channel_names: dict[str, str] = {}
|
||||
self._doctor_buttons: dict[int, QRadioButton] = {}
|
||||
self._date_buttons: dict[str, QPushButton] = {}
|
||||
self._slot_buttons: dict[str, QPushButton] = {}
|
||||
self._date_buttons: dict[str, _HoverLiftButton] = {}
|
||||
self._slot_buttons: dict[str, _HoverLiftButton] = {}
|
||||
self._slot_available: dict[str, bool] = {}
|
||||
self._slot_restore_selection = ""
|
||||
self._active_loading = ""
|
||||
@@ -1419,7 +1426,7 @@ class AppointmentDrawer(QDialog):
|
||||
continue
|
||||
label = f"{parsed.toString('MM月dd日')} ({week_days[parsed.dayOfWeek() % 7]})"
|
||||
self.date_combo.addItem(label, value)
|
||||
button = QPushButton(label)
|
||||
button = _HoverLiftButton(label)
|
||||
button.setProperty("appointmentDate", True)
|
||||
button.setCheckable(True)
|
||||
button.setFixedSize(130, 40)
|
||||
|
||||
@@ -2,155 +2,143 @@
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def appointments_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_QSS).safe_substitute(body=body_family(), heading=heading_family()))
|
||||
return Template(_QSS).substitute(body=body_family(), heading=heading_family())
|
||||
|
||||
|
||||
_QSS = """
|
||||
#AppointmentsPage { background: $ds_canvas; color: $ds_text; }
|
||||
#AppointmentsPage { background: #F3F7FD; color: #273244; }
|
||||
#AppointmentsPage QLabel, #AppointmentsPage QPushButton,
|
||||
#AppointmentsPage QLineEdit, #AppointmentsPage QComboBox,
|
||||
#AppointmentsPage QTabBar, #AppointmentsPage QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#AppointmentsPage QWidget#PageHeader QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
|
||||
}
|
||||
#AppointmentsPage QWidget#PageHeader QLabel[role="muted"],
|
||||
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumb"],
|
||||
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbSeparator"],
|
||||
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbCurrent"] {
|
||||
color: $ds_muted; font-size: 13px; font-weight: 400;
|
||||
color: #5D6B80; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#AppointmentsPage QFrame#AppointmentFilterPanel,
|
||||
#AppointmentsPage QFrame#AppointmentMainCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#AppointmentsPage QPushButton {
|
||||
min-height: 30px; padding: 0 12px; border: 1px solid transparent;
|
||||
border-radius: $ds_radius_control; background: $ds_surface_alt;
|
||||
min-height: 30px; padding: 0 12px; border: 1px solid #DBE5F2;
|
||||
border-radius: 6px; background: #FFFFFF;
|
||||
}
|
||||
#AppointmentsPage QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; }
|
||||
#AppointmentsPage QPushButton:pressed { background: $ds_accent_soft; }
|
||||
#AppointmentsPage QPushButton:focus { border-color: $ds_focus; }
|
||||
#AppointmentsPage QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; }
|
||||
#AppointmentsPage QPushButton:pressed { background: #DCEAFF; }
|
||||
#AppointmentsPage QPushButton:focus { border-color: #75A5F0; }
|
||||
#AppointmentsPage QPushButton[variant="primary"] {
|
||||
background: $ds_accent; color: $ds_surface; border-color: $ds_accent;
|
||||
background: #1769E8; color: #FFFFFF; border-color: #1769E8;
|
||||
}
|
||||
#AppointmentsPage QPushButton[variant="primary"]:hover { background: $ds_accent_hover; }
|
||||
#AppointmentsPage QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
|
||||
#AppointmentsPage QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
|
||||
#AppointmentsPage QPushButton[variant="primary"]:hover { background: #155BCC; }
|
||||
#AppointmentsPage QPushButton[variant="primary"]:pressed { background: #124EA9; }
|
||||
#AppointmentsPage QPushButton[variant="danger"] {
|
||||
color: $ds_danger; background: $ds_danger_soft; border-color: transparent;
|
||||
color: #B84652; background: #FFFFFF; border-color: #EFC8CE;
|
||||
}
|
||||
#AppointmentsPage QPushButton[variant="danger"]:hover { background: $ds_danger_soft; }
|
||||
#AppointmentsPage QPushButton[variant="danger"]:pressed { border-color: $ds_danger; }
|
||||
#AppointmentsPage QPushButton[variant="danger"]:hover { background: #FFF0F2; }
|
||||
#AppointmentsPage QPushButton[variant="ghost"] { background: transparent; border-color: transparent; }
|
||||
#AppointmentsPage QPushButton[variant="ghost"]:hover { background: $ds_accent_soft; }
|
||||
#AppointmentsPage QPushButton[variant="ghost"]:focus { border-color: $ds_focus; }
|
||||
#AppointmentsPage QPushButton:disabled, #AppointmentsPage QPushButton[variant="primary"]:disabled,
|
||||
#AppointmentsPage QPushButton[variant="danger"]:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
#AppointmentsPage QPushButton:disabled {
|
||||
color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#AppointmentsPage QLineEdit, #AppointmentsPage QComboBox {
|
||||
min-height: 32px; padding: 0 10px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft;
|
||||
min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF;
|
||||
}
|
||||
#AppointmentsPage QLineEdit:focus, #AppointmentsPage QComboBox:focus { border-color: $ds_focus; }
|
||||
#AppointmentsPage QLineEdit:focus, #AppointmentsPage QComboBox:focus { border-color: #75A5F0; }
|
||||
#AppointmentsPage QLineEdit QToolButton {
|
||||
min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent;
|
||||
}
|
||||
#AppointmentsPage QLineEdit QToolButton:focus { background: $ds_accent_soft; }
|
||||
#AppointmentsPage QLineEdit QToolButton:focus { background: #EAF2FF; }
|
||||
#AppointmentsPage QPushButton#AppointmentSearchButton {
|
||||
min-height: 39px; max-height: 39px; min-width: 52px;
|
||||
}
|
||||
#AppointmentsPage QLineEdit#AppointmentPatientSearch { min-height: 39px; max-height: 39px; }
|
||||
#AppointmentsPage QPushButton[appointmentStat="true"] {
|
||||
min-height: 34px; max-height: 34px; padding: 0 10px; background: $ds_canvas;
|
||||
border-color: transparent; color: $ds_muted; font-size: 13px;
|
||||
min-height: 34px; max-height: 34px; padding: 0 10px; background: #F4F7FC;
|
||||
border-color: transparent; color: #5D6B80; font-size: 13px;
|
||||
}
|
||||
#AppointmentsPage QPushButton[appointmentStat="true"]:hover { color: $ds_accent; background: $ds_accent_soft; }
|
||||
#AppointmentsPage QPushButton[appointmentStat="true"]:hover { color: #1555B6; background: #EAF2FF; }
|
||||
#AppointmentsPage QPushButton[appointmentStat="true"]:checked {
|
||||
color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600;
|
||||
color: #FFFFFF; background: #1769E8; border-color: #1769E8;
|
||||
}
|
||||
#AppointmentsPage QPushButton[appointmentStatKind="warning"][hasPending="true"]:!checked {
|
||||
color: $ds_warning; background: $ds_warning_soft; border-color: $ds_warning_soft;
|
||||
color: #9C681F; background: #FFF6E7; border-color: #EEDCBF;
|
||||
}
|
||||
#AppointmentsPage QLabel#FilterRowLabel { color: $ds_muted; font-size: 13px; }
|
||||
#AppointmentsPage QLabel#FilterDivider { color: $ds_line; padding: 0 10px; }
|
||||
#AppointmentsPage QLabel#FilterRowLabel { color: #5D6B80; font-size: 13px; }
|
||||
#AppointmentsPage QLabel#FilterDivider { color: #DBE5F2; padding: 0 10px; }
|
||||
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab {
|
||||
min-width: 52px; min-height: 32px; padding: 0 12px; color: $ds_muted;
|
||||
min-width: 52px; min-height: 32px; padding: 0 12px; color: #5D6B80;
|
||||
background: transparent; border: 0; border-bottom: 2px solid transparent; font-size: 13px;
|
||||
}
|
||||
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:hover { color: $ds_accent; background: $ds_surface_alt; }
|
||||
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:hover { color: #1555B6; background: #F7FAFE; }
|
||||
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:selected {
|
||||
color: $ds_accent; background: transparent; border-bottom-color: $ds_accent;
|
||||
color: #1769E8; background: transparent; border-bottom-color: #1769E8;
|
||||
}
|
||||
#AppointmentsPage QPushButton[filterChoice="true"] {
|
||||
min-height: 30px; max-height: 30px; padding: 0 12px; color: $ds_muted;
|
||||
min-height: 30px; max-height: 30px; padding: 0 12px; color: #5D6B80;
|
||||
background: transparent; border-color: transparent; font-size: 13px;
|
||||
}
|
||||
#AppointmentsPage QPushButton[filterChoice="true"]:checked { color: $ds_accent; background: $ds_accent_soft; }
|
||||
#AppointmentsPage QPushButton[filterChoice="true"]:focus,
|
||||
#AppointmentsPage QPushButton[appointmentStat="true"]:focus { border-color: $ds_focus; }
|
||||
#AppointmentsPage QPushButton[filterChoice="true"]:checked { color: #1555B6; background: #EAF2FF; }
|
||||
#AppointmentsPage QFrame#AppointmentToolbar { background: transparent; border: 0; }
|
||||
#AppointmentsPage QPushButton[compactAction="true"] {
|
||||
min-height: 36px; max-height: 36px; padding: 0 17px; font-size: 13px;
|
||||
}
|
||||
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled {
|
||||
color: $ds_text; border-color: transparent;
|
||||
color: #1769E8; border-color: #ADC8F0;
|
||||
}
|
||||
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:hover { color: $ds_accent; background: $ds_accent_soft; }
|
||||
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:focus { border-color: $ds_focus; }
|
||||
#AppointmentsPage QTableWidget#AppointmentTable {
|
||||
background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
|
||||
gridline-color: $ds_line; selection-background-color: $ds_accent_soft; selection-color: $ds_text;
|
||||
background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
|
||||
gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244;
|
||||
}
|
||||
#AppointmentsPage QTableWidget#AppointmentTable::item { padding: 0; border: 0; border-bottom: 1px solid $ds_line; }
|
||||
#AppointmentsPage QTableWidget#AppointmentTable::item:selected { background: $ds_accent_soft; color: $ds_text; }
|
||||
#AppointmentsPage QTableWidget#AppointmentTable::item { padding: 0; border: 0; border-bottom: 1px solid #E6EDF6; }
|
||||
#AppointmentsPage QTableWidget#AppointmentTable::item:selected { background: #EAF2FF; color: #273244; }
|
||||
#AppointmentsPage QTableWidget#AppointmentTable QHeaderView::section {
|
||||
min-height: 40px; padding: 0; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-top: 1px solid $ds_line; border-bottom: 1px solid $ds_line;
|
||||
min-height: 40px; padding: 0; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-top: 1px solid #E1E9F4; border-bottom: 1px solid #E1E9F4;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#AppointmentsPage QWidget[appointmentSelectionHost="true"] {
|
||||
background: transparent; border-left: 3px solid transparent;
|
||||
}
|
||||
#AppointmentsPage QWidget[appointmentSelectionHost="true"][selected="true"] { border-left-color: $ds_accent; }
|
||||
#AppointmentsPage QWidget[appointmentSelectionHost="true"][selected="true"] { border-left-color: #1769E8; }
|
||||
#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator {
|
||||
width: 16px; height: 16px; background: $ds_surface; border: 1px solid $ds_line_strong; border-radius: 3px;
|
||||
width: 16px; height: 16px; background: #FFFFFF; border: 1px solid #C8D5E6; border-radius: 3px;
|
||||
}
|
||||
#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator:checked { background: $ds_accent; border-color: $ds_accent; }
|
||||
#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator:checked { background: #1769E8; border-color: #1769E8; }
|
||||
#AppointmentsPage QWidget[appointmentInfoHost="true"],
|
||||
#AppointmentsPage QWidget[appointmentImHost="true"] { background: transparent; }
|
||||
#AppointmentsPage QLabel[tableAppointmentStatus="true"] {
|
||||
min-height: 20px; max-height: 20px; padding: 0 6px; color: $ds_accent;
|
||||
background: $ds_accent_soft; border-radius: $ds_radius_small; font-size: 13px;
|
||||
min-height: 20px; max-height: 20px; padding: 0 6px; color: #1555B6;
|
||||
background: #EAF2FF; border-radius: 4px; font-size: 13px;
|
||||
}
|
||||
#AppointmentsPage QLabel[tableAppointmentStatusKind="warning"] { color: $ds_warning; background: $ds_warning_soft; }
|
||||
#AppointmentsPage QLabel[tableAppointmentStatusKind="muted"] { color: $ds_muted; background: $ds_disabled_surface; }
|
||||
#AppointmentsPage QLabel[tableAppointmentMeta="true"] { color: $ds_muted; font-size: 13px; }
|
||||
#AppointmentsPage QLabel[tableAppointmentStatusKind="warning"] { color: #9C681F; background: #FFF3DD; }
|
||||
#AppointmentsPage QLabel[tableAppointmentStatusKind="muted"] { color: #66758A; background: #EEF2F7; }
|
||||
#AppointmentsPage QLabel[tableAppointmentMeta="true"] { color: #5D6B80; font-size: 13px; }
|
||||
#AppointmentsPage QPushButton[tableCancelAction="true"] {
|
||||
min-height: 20px; max-height: 20px; padding: 0 5px; color: $ds_danger;
|
||||
background: $ds_danger_soft; border: 0; border-radius: $ds_radius_small; font-size: 13px;
|
||||
min-height: 20px; max-height: 20px; padding: 0 5px; color: #B84652;
|
||||
background: #FFF0F2; border: 0; border-radius: 4px; font-size: 13px;
|
||||
}
|
||||
#AppointmentsPage QPushButton[appointmentImAction="true"] {
|
||||
min-width: 62px; min-height: 32px; max-height: 32px; padding: 0 10px;
|
||||
color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-size: 13px;
|
||||
color: #1555B6; background: #EAF2FF; border-color: #C9DCF7; font-size: 13px;
|
||||
}
|
||||
#AppointmentsPage QPushButton[appointmentImAction="true"]:hover { color: $ds_accent_hover; border-color: $ds_line_strong; }
|
||||
#AppointmentsPage QPushButton[appointmentImAction="true"]:focus { border-color: $ds_focus; }
|
||||
#AppointmentsPage QPushButton[appointmentImAction="true"]:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; }
|
||||
#AppointmentsPage QWidget#Pager { background: $ds_surface; border: 0; border-top: 1px solid $ds_line; }
|
||||
#AppointmentsPage QWidget#Pager QLabel { color: $ds_muted; font-size: 13px; border: 0; }
|
||||
#AppointmentsPage QPushButton[appointmentImAction="true"]:hover { color: #FFFFFF; background: #1769E8; }
|
||||
#AppointmentsPage QPushButton[appointmentImAction="true"]:disabled { color: #8A97A9; background: #F3F6FB; border-color: #DFE7F2; }
|
||||
#AppointmentsPage QWidget#Pager { background: #FFFFFF; border: 0; border-top: 1px solid #E1E9F4; }
|
||||
#AppointmentsPage QWidget#Pager QLabel { color: #5D6B80; font-size: 13px; border: 0; }
|
||||
#AppointmentsPage QWidget#Pager QPushButton {
|
||||
min-width: 30px; max-width: 30px; min-height: 32px; max-height: 32px;
|
||||
padding: 0; border: 1px solid $ds_line; background: $ds_surface; color: $ds_muted; font-size: 13px;
|
||||
padding: 0; border: 1px solid #DBE5F2; background: #FFFFFF; color: #5D6B80; font-size: 13px;
|
||||
}
|
||||
#AppointmentsPage QWidget#Pager QPushButton[active="true"] { color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600; }
|
||||
#AppointmentsPage QWidget#Pager QPushButton:focus { border-color: $ds_focus; }
|
||||
#AppointmentsPage QWidget#Pager QPushButton:disabled { color: $ds_disabled; background: $ds_surface_alt; }
|
||||
#AppointmentsPage QWidget#Pager QPushButton[active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
|
||||
#AppointmentsPage QWidget#Pager QPushButton:disabled { color: #9AA6B7; background: #F7F9FC; }
|
||||
"""
|
||||
|
||||
@@ -24,7 +24,6 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .widgets import display_text, first_value, run_async
|
||||
|
||||
# 后台 ChatNotifyLogic 写入的三种 type。
|
||||
@@ -261,7 +260,7 @@ class ChatNotificationCenter(QWidget):
|
||||
super().__init__(host)
|
||||
self.repository = repository
|
||||
self.setObjectName("ChatNotifyLayer")
|
||||
self.setStyleSheet(clinical_stylesheet(CHAT_NOTIFICATION_QSS))
|
||||
self.setStyleSheet(CHAT_NOTIFICATION_QSS)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, False)
|
||||
self._cards: dict[str, _NotificationCard] = {}
|
||||
self._pending: list[ChatNotification] = []
|
||||
|
||||
@@ -2,67 +2,59 @@
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def consultations_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_QSS).safe_substitute(body=body_family(), heading=heading_family()))
|
||||
return Template(_QSS).substitute(body=body_family(), heading=heading_family())
|
||||
|
||||
|
||||
_QSS = """
|
||||
#DiagnosisIndex, #DiagnosisIndexContent, #DiagnosisPageScroll {
|
||||
background: $ds_canvas; color: $ds_text; border: 0;
|
||||
background: #F3F7FD; color: #273244; border: 0;
|
||||
}
|
||||
#DiagnosisIndex QLabel, #DiagnosisIndex QPushButton, #DiagnosisIndex QToolButton,
|
||||
#DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit,
|
||||
#DiagnosisIndex QSpinBox, #DiagnosisIndex QTableView {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#DiagnosisIndex QWidget#PageHeader QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
|
||||
}
|
||||
#DiagnosisIndex QLabel[role="muted"], #DiagnosisIndex QLabel[role="breadcrumb"],
|
||||
#DiagnosisIndex QLabel[role="breadcrumbCurrent"], #DiagnosisIndex QLabel[role="breadcrumbSeparator"],
|
||||
#DiagnosisIndex QLabel[filterGroup="true"], #DiagnosisIndex QLabel[pagerMuted="true"] {
|
||||
color: $ds_muted; font-size: 13px;
|
||||
color: #5D6B80; font-size: 13px;
|
||||
}
|
||||
#DiagnosisIndex QFrame#DiagnosisFilterCard, #DiagnosisIndex QFrame#DiagnosisListCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#DiagnosisIndex QFrame#DiagnosisStatusCard, #DiagnosisIndex QFrame#DiagnosisQuickFilters,
|
||||
#DiagnosisIndex QFrame#DiagnosisListToolbar { background: transparent; border: 0; }
|
||||
#DiagnosisIndex QFrame#DiagnosisAdvancedFilters {
|
||||
background: transparent; border: 0; border-top: 1px solid $ds_line; border-radius: 0;
|
||||
background: transparent; border: 0; border-top: 1px solid #E6EDF6; border-radius: 0;
|
||||
}
|
||||
#DiagnosisIndex QPushButton {
|
||||
min-height: 34px; padding: 0 13px; border: 1px solid transparent;
|
||||
border-radius: $ds_radius_control; background: $ds_surface_alt;
|
||||
min-height: 34px; padding: 0 13px; border: 1px solid #DBE5F2;
|
||||
border-radius: 6px; background: #FFFFFF;
|
||||
}
|
||||
#DiagnosisIndex QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; }
|
||||
#DiagnosisIndex QPushButton:pressed { background: $ds_accent_soft; }
|
||||
#DiagnosisIndex QPushButton:focus { border-color: $ds_focus; }
|
||||
#DiagnosisIndex QPushButton[variant="primary"] { color: $ds_surface; background: $ds_accent; border-color: $ds_accent; }
|
||||
#DiagnosisIndex QPushButton[variant="primary"]:hover { background: $ds_accent_hover; }
|
||||
#DiagnosisIndex QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
|
||||
#DiagnosisIndex QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
|
||||
#DiagnosisIndex QPushButton[consultationTool="true"] { color: $ds_text; border-color: transparent; }
|
||||
#DiagnosisIndex QPushButton[consultationTool="true"]:hover { color: $ds_accent; background: $ds_accent_soft; }
|
||||
#DiagnosisIndex QPushButton[consultationDanger="true"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
|
||||
#DiagnosisIndex QPushButton[consultationDanger="true"]:hover { border-color: $ds_danger; }
|
||||
#DiagnosisIndex QPushButton[consultationTool="true"]:focus,
|
||||
#DiagnosisIndex QPushButton[consultationDanger="true"]:focus { border-color: $ds_focus; }
|
||||
#DiagnosisIndex QPushButton:disabled, #DiagnosisIndex QPushButton[consultationDanger="true"]:disabled,
|
||||
#DiagnosisIndex QPushButton[variant="primary"]:disabled, #DiagnosisIndex QPushButton[consultationTool="true"]:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
#DiagnosisIndex QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; }
|
||||
#DiagnosisIndex QPushButton:pressed { background: #DCEAFF; }
|
||||
#DiagnosisIndex QPushButton:focus { border-color: #75A5F0; }
|
||||
#DiagnosisIndex QPushButton[variant="primary"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
|
||||
#DiagnosisIndex QPushButton[variant="primary"]:hover { background: #155BCC; }
|
||||
#DiagnosisIndex QPushButton[consultationTool="true"] { color: #1555B6; border-color: #C2D5EF; }
|
||||
#DiagnosisIndex QPushButton[consultationDanger="true"] { color: #BE4B58; border-color: #EBCDD2; }
|
||||
#DiagnosisIndex QPushButton:disabled, #DiagnosisIndex QPushButton[consultationDanger="true"]:disabled {
|
||||
color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit, #DiagnosisIndex QSpinBox {
|
||||
min-height: 32px; padding: 0 10px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft;
|
||||
min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF;
|
||||
font-size: 13px;
|
||||
}
|
||||
#DiagnosisIndex QLineEdit:focus, #DiagnosisIndex QComboBox:focus,
|
||||
#DiagnosisIndex QDateEdit:focus, #DiagnosisIndex QSpinBox:focus { border-color: $ds_focus; }
|
||||
#DiagnosisIndex QDateEdit:focus, #DiagnosisIndex QSpinBox:focus { border-color: #75A5F0; }
|
||||
#DiagnosisIndex QLineEdit QToolButton {
|
||||
min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent;
|
||||
}
|
||||
@@ -70,77 +62,70 @@ _QSS = """
|
||||
width: 22px; border: 0; background: transparent;
|
||||
}
|
||||
#DiagnosisIndex QComboBox QAbstractItemView {
|
||||
color: $ds_text; background: $ds_surface; border: 1px solid $ds_line;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_accent; outline: 0;
|
||||
color: #273244; background: #FFFFFF; border: 1px solid #DBE5F2;
|
||||
selection-background-color: #EAF2FF; selection-color: #1555B6; outline: 0;
|
||||
}
|
||||
#DiagnosisIndex QWidget#DiagnosisStatusSearch QLineEdit,
|
||||
#DiagnosisIndex QWidget#DiagnosisStatusSearch QPushButton { min-height: 39px; max-height: 39px; }
|
||||
#DiagnosisIndex QToolButton { min-width: 0; min-height: 0; border: 0; padding: 0; background: transparent; }
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"] {
|
||||
min-height: 32px; max-height: 32px; padding: 0 14px; border: 1px solid transparent;
|
||||
border-radius: $ds_radius_control; color: $ds_muted; background: transparent; font-size: 13px;
|
||||
border-radius: 5px; color: #5D6B80; background: transparent; font-size: 13px;
|
||||
}
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"]:hover { background: $ds_surface_alt; color: $ds_accent; }
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked { background: $ds_accent_soft; color: $ds_accent; font-weight: 600; }
|
||||
#DiagnosisIndex QToolButton[dateChoice="true"] { padding: 0 17px; background: $ds_surface_alt; border-color: transparent; }
|
||||
#DiagnosisIndex QToolButton[dateChoice="true"]:checked { background: $ds_accent_soft; border-color: transparent; }
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"]:focus { border-color: $ds_focus; }
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"]:hover { background: #F2F7FF; color: #1555B6; }
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked { background: #1769E8; color: #FFFFFF; }
|
||||
#DiagnosisIndex QToolButton[dateChoice="true"] { padding: 0 17px; border-color: #E1E9F4; }
|
||||
#DiagnosisIndex QToolButton[dateChoice="true"]:checked { border-color: #1769E8; }
|
||||
#DiagnosisIndex QToolButton[statusTab="true"] {
|
||||
min-height: 44px; max-height: 44px; padding: 0 20px; border: 0;
|
||||
border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
|
||||
}
|
||||
#DiagnosisIndex QToolButton[statusTab="true"]:checked {
|
||||
color: $ds_accent; background: transparent; border-bottom-color: $ds_accent;
|
||||
color: #1769E8; background: transparent; border-bottom-color: #1769E8;
|
||||
}
|
||||
#DiagnosisIndex QToolButton[statusTab="true"]:focus { background: $ds_accent_soft; }
|
||||
#DiagnosisIndex QToolButton#DiagnosisMoreFilter {
|
||||
min-height: 32px; padding: 0 6px; color: $ds_muted; font-size: 13px;
|
||||
min-height: 32px; padding: 0 6px; color: #5D6B80; font-size: 13px;
|
||||
}
|
||||
#DiagnosisIndex QToolButton#DiagnosisMoreFilter:hover { color: $ds_accent; background: $ds_surface_alt; }
|
||||
#DiagnosisIndex QFrame#DiagnosisFilterDivider { min-width: 1px; max-width: 1px; min-height: 20px; background: $ds_line; border: 0; }
|
||||
#DiagnosisIndex QToolButton#DiagnosisMoreFilter:hover { color: #1769E8; background: #F2F7FF; }
|
||||
#DiagnosisIndex QFrame#DiagnosisFilterDivider { min-width: 1px; max-width: 1px; min-height: 20px; background: #E1E9F4; border: 0; }
|
||||
#DiagnosisIndex QFrame#DiagnosisDateRange {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control;
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 6px;
|
||||
}
|
||||
#DiagnosisIndex QDateEdit[diagnosisRangePart="true"] { min-height: 30px; padding: 0 4px; border: 0; }
|
||||
#DiagnosisIndex QTableView {
|
||||
background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
|
||||
gridline-color: $ds_line; selection-background-color: $ds_accent_soft; selection-color: $ds_text;
|
||||
background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
|
||||
gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244;
|
||||
}
|
||||
#DiagnosisIndex QTableView QHeaderView::section {
|
||||
min-height: 41px; padding: 0; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-bottom: 1px solid $ds_line;
|
||||
min-height: 41px; padding: 0; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-bottom: 1px solid #E1E9F4;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#DiagnosisIndex QToolButton[rowLink], #DiagnosisIndex QToolButton[appointmentCancel="true"] {
|
||||
color: $ds_accent; min-height: 26px; padding: 0 4px; border: 1px solid transparent;
|
||||
border-radius: $ds_radius_small; background: transparent; font-size: 13px;
|
||||
color: #1769E8; min-height: 26px; padding: 0 4px; border: 0; background: transparent; font-size: 13px;
|
||||
}
|
||||
#DiagnosisIndex QToolButton[appointmentCancel="true"] { color: $ds_danger; }
|
||||
#DiagnosisIndex QToolButton[appointmentCancel="true"]:hover { background: $ds_danger_soft; }
|
||||
#DiagnosisIndex QToolButton[rowLink]:hover { color: $ds_accent; background: $ds_accent_soft; border-radius: $ds_radius_small; }
|
||||
#DiagnosisIndex QToolButton[rowLink]:focus,
|
||||
#DiagnosisIndex QToolButton[appointmentCancel="true"]:focus { border-color: $ds_focus; }
|
||||
#DiagnosisIndex QToolButton[appointmentCancel="true"] { color: #BE4B58; }
|
||||
#DiagnosisIndex QToolButton[rowLink]:hover { color: #1555B6; background: #DCEAFF; border-radius: 4px; }
|
||||
#DiagnosisIndex QToolButton[rowLink="muted"], #DiagnosisIndex QLabel[fixedMuted="true"] {
|
||||
color: $ds_muted; font-size: 13px;
|
||||
color: #5D6B80; font-size: 13px;
|
||||
}
|
||||
#DiagnosisIndex QToolButton#DiagnosisRowMore { padding-right: 18px; }
|
||||
#DiagnosisIndex QWidget#DiagnosisFixedCell { background: transparent; }
|
||||
#DiagnosisIndex QLabel#DiagnosisTableEmpty { color: $ds_muted; background: $ds_surface; }
|
||||
#DiagnosisIndex QLabel#DiagnosisTableEmpty[stateKind="error"] { color: $ds_danger; }
|
||||
#DiagnosisIndex QTableView#DiagnosisFixedTable { border-left: 1px solid $ds_line; }
|
||||
#DiagnosisIndex QWidget#DiagnosisPager { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#DiagnosisIndex QLabel#DiagnosisTableEmpty { color: #5D6B80; background: #FFFFFF; }
|
||||
#DiagnosisIndex QLabel#DiagnosisTableEmpty[stateKind="error"] { color: #BE4B58; }
|
||||
#DiagnosisIndex QTableView#DiagnosisFixedTable { border-left: 1px solid #E1E9F4; }
|
||||
#DiagnosisIndex QWidget#DiagnosisPager { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#DiagnosisIndex QToolButton[pagerButton="true"] {
|
||||
min-width: 30px; max-width: 30px; min-height: 30px; max-height: 30px;
|
||||
border: 1px solid $ds_line; border-radius: $ds_radius_control; color: $ds_muted; background: $ds_surface;
|
||||
border: 1px solid #DBE5F2; border-radius: 5px; color: #5D6B80; background: #FFFFFF;
|
||||
}
|
||||
#DiagnosisIndex QToolButton[pagerButton="true"][active="true"] { color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600; }
|
||||
#DiagnosisIndex QToolButton[pagerButton="true"]:focus { border-color: $ds_focus; }
|
||||
#DiagnosisIndex QToolButton[pagerButton="true"]:disabled { color: $ds_disabled; background: $ds_disabled_surface; }
|
||||
#DiagnosisIndex QToolButton[pagerButton="true"][active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
|
||||
#DiagnosisIndex QToolButton[pagerButton="true"]:disabled { color: #A4B0C0; background: #F6F8FC; }
|
||||
#DiagnosisIndex QComboBox#DiagnosisPageSize { min-width: 95px; min-height: 30px; }
|
||||
#DiagnosisIndex QSpinBox#DiagnosisPageJumper { min-height: 30px; padding: 0 8px; }
|
||||
#DiagnosisIndex QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#DiagnosisIndex QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#DiagnosisIndex QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#DiagnosisIndex QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#DiagnosisIndex QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#DiagnosisIndex QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#DiagnosisIndex QScrollBar::add-line, #DiagnosisIndex QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#DiagnosisIndex QScrollBar::add-page, #DiagnosisIndex QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
"""Clinical desktop design tokens, shared by native pages and dialog chrome.
|
||||
|
||||
Keep data-series colours and video pixels outside this palette. Existing scoped
|
||||
QSS can adopt the system without changing selectors, layout or permissions.
|
||||
New rules should use the named ``$ds_*`` tokens rather than legacy colours.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from string import Template
|
||||
|
||||
PALETTE = {
|
||||
"canvas": "#F5F7FA",
|
||||
"surface": "#FFFFFF",
|
||||
"surface_alt": "#F7F9FC",
|
||||
"sidebar": "#F0F3F8",
|
||||
"line": "#E6EAF0",
|
||||
"line_strong": "#D4DCE8",
|
||||
"heading": "#223047",
|
||||
"text": "#344258",
|
||||
"muted": "#647287",
|
||||
"disabled": "#8B96A6",
|
||||
"disabled_surface": "#F0F2F5",
|
||||
"accent": "#4267B2",
|
||||
"accent_hover": "#355995",
|
||||
"accent_pressed": "#2C4C82",
|
||||
"accent_soft": "#EAF0FB",
|
||||
"focus": "#6D8CCB",
|
||||
"success": "#287B65",
|
||||
"success_soft": "#EDF7F2",
|
||||
"warning": "#96601D",
|
||||
"warning_soft": "#FBF4E8",
|
||||
"danger": "#B54A59",
|
||||
"danger_soft": "#FCF0F2",
|
||||
}
|
||||
|
||||
RADII = {"small": 6, "control": 10, "panel": 16, "window": 20}
|
||||
SPACING = {"small": 8, "control": 12, "group": 16, "section": 24}
|
||||
|
||||
TOKENS = {f"ds_{name}": value for name, value in PALETTE.items()}
|
||||
TOKENS.update({f"ds_radius_{name}": f"{value}px" for name, value in RADII.items()})
|
||||
TOKENS.update({f"ds_space_{name}": f"{value}px" for name, value in SPACING.items()})
|
||||
|
||||
# Explicit migration of the two existing native palettes. This adapter only
|
||||
# touches six-digit colour literals; selectors and metrics stay page-owned.
|
||||
_LEGACY_ROLES = {
|
||||
"accent": ("1769E8", "4F63D9", "5761F4", "5267DF"),
|
||||
"accent_hover": ("155BCC", "1555B6", "4156C4", "4356C4", "4055CA"),
|
||||
"accent_pressed": ("124EA9", "354BB4"),
|
||||
"accent_soft": ("EAF2FF", "EEF1FA", "EEF0FF", "F0F2FF", "DCEAFF", "EDF0FC"),
|
||||
"focus": ("75A5F0", "8B9AD9"),
|
||||
"canvas": ("F3F7FD", "F4F6FA", "F6F6F6"),
|
||||
"surface_alt": ("F7F7F7", "F7FAFE", "F5F8FD", "F7F9FE", "F2F7FF"),
|
||||
"sidebar": ("EDF4FF",),
|
||||
"line": ("DBE5F2", "EDEDEE", "E5ECF6", "E6EDF6", "E7EDF7", "EDF0F5", "E7EBF2", "E6EAF5"),
|
||||
"line_strong": ("E4E4E5", "C8D5E6", "C9DCF7", "ADC8F0", "B6CDEE"),
|
||||
"heading": ("1A1C1F", "202C3F", "111F46"),
|
||||
"text": ("273244", "263551", "24334A", "233149", "3F4E75"),
|
||||
"muted": ("606163", "6A6B6D", "5D6B80", "7886AA", "708097"),
|
||||
"disabled": ("8E8F90", "8A97A9", "9AA6B7"),
|
||||
"disabled_surface": ("F2F2F2", "F0F0F0"),
|
||||
"success_soft": ("EEF7F3", "EAF9F3"),
|
||||
"warning": ("A9691D", "9C681F"),
|
||||
"warning_soft": ("FCF5E9", "FFF5E6", "FFF6E7"),
|
||||
"danger": ("BE4B58", "B84652"),
|
||||
"danger_soft": ("FFF0F2", "FFF1F3"),
|
||||
}
|
||||
_LEGACY = {colour.lower(): PALETTE[role] for role, colours in _LEGACY_ROLES.items() for colour in colours}
|
||||
_HEX = re.compile(r"#([0-9a-fA-F]{6})(?![0-9a-fA-F])")
|
||||
|
||||
|
||||
def clinical_stylesheet(source: str) -> str:
|
||||
"""Resolve clinical tokens and migrate known legacy light-theme colours."""
|
||||
resolved = Template(source).safe_substitute(TOKENS)
|
||||
return _HEX.sub(lambda match: _LEGACY.get(match[1].lower(), match[0]), resolved)
|
||||
@@ -64,7 +64,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from .chat_items import ChatItem, parse_chat_item
|
||||
from .design_system import PALETTE, clinical_stylesheet
|
||||
from .diagnosis_editors import FlowLayout
|
||||
from .diagnosis_media import shared_image_manager
|
||||
from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms
|
||||
@@ -81,7 +80,10 @@ QFrame#DiagnosisDrawer {
|
||||
border-left: 1px solid #EDEDEE;
|
||||
}
|
||||
QFrame#DiagnosisDrawerHeader {
|
||||
background-color: #FFFFFF;
|
||||
background-color: qlineargradient(
|
||||
x1:0, y1:0, x2:0, y2:1,
|
||||
stop:0 #FFFFFF, stop:1 #F7F7F7
|
||||
);
|
||||
border-bottom: 1px solid #EDEDEE;
|
||||
}
|
||||
QFrame#DiagnosisDrawerFooter {
|
||||
@@ -103,7 +105,7 @@ QLabel#DiagnosisDrawerModeBadge,
|
||||
QLabel#DiagnosisReadonlyStatus,
|
||||
QLabel[diagnosisTag="true"] {
|
||||
padding: 4px 9px;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 9px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
@@ -157,8 +159,8 @@ QDialog QPushButton:pressed {
|
||||
border-color: #354BB4;
|
||||
}
|
||||
QDialog QPushButton:disabled {
|
||||
color: $ds_disabled;
|
||||
background-color: $ds_disabled_surface;
|
||||
color: #E4E4E5;
|
||||
background-color: #FFFFFF;
|
||||
border-color: #EDEDEE;
|
||||
}
|
||||
QDialog QPushButton[variant="primary"] {
|
||||
@@ -174,9 +176,9 @@ QDialog QPushButton[variant="primary"]:focus {
|
||||
border-color: #4156C4;
|
||||
}
|
||||
QDialog QPushButton[variant="primary"]:disabled {
|
||||
color: $ds_disabled;
|
||||
background-color: $ds_disabled_surface;
|
||||
border-color: $ds_line;
|
||||
color: #FFFFFF;
|
||||
background-color: #F0F0F0;
|
||||
border-color: #F0F0F0;
|
||||
}
|
||||
QDialog QPushButton[variant="secondary"] {
|
||||
color: #4F63D9;
|
||||
@@ -265,9 +267,9 @@ QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:focus {
|
||||
border-color: #4156C4;
|
||||
}
|
||||
QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:disabled {
|
||||
color: $ds_disabled;
|
||||
background-color: $ds_disabled_surface;
|
||||
border-color: $ds_line;
|
||||
color: #FFFFFF;
|
||||
background-color: #F0F0F0;
|
||||
border-color: #F0F0F0;
|
||||
}
|
||||
QDialog#DiagnosisDialogRoot QPushButton#DiagnosisFooterCloseButton {
|
||||
color: #606163;
|
||||
@@ -381,10 +383,10 @@ QFrame#DiagnosisFormHost {
|
||||
QFrame[diagnosisSection="true"] {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 16px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QLabel[diagnosisFieldLabel="true"] {
|
||||
color: $ds_muted;
|
||||
color: #1A1C1F;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
@@ -424,7 +426,7 @@ QDoubleSpinBox[diagnosisField="true"]:focus,
|
||||
QSpinBox[diagnosisField="true"]:focus,
|
||||
QTimeEdit[diagnosisField="true"]:focus {
|
||||
border: 1px solid #8B9AD9;
|
||||
background-color: $ds_surface;
|
||||
background-color: #F7F7F7;
|
||||
}
|
||||
QLineEdit[diagnosisField="true"][invalid="true"],
|
||||
QComboBox[diagnosisField="true"][invalid="true"],
|
||||
@@ -450,8 +452,8 @@ QLabel#DiagnosisSectionTitle {
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
QFrame#DiagnosisSectionAccent {
|
||||
@@ -468,9 +470,9 @@ QFrame#DiagnosisReadonlyPage {
|
||||
background-color: #F6F6F6;
|
||||
}
|
||||
QFrame#DiagnosisReadonlyHero {
|
||||
background-color: $ds_surface;
|
||||
border: 1px solid $ds_line;
|
||||
border-radius: $ds_radius_panel;
|
||||
background-color: #F7F7F7;
|
||||
border: 1px solid #F0F0F0;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QLabel#DiagnosisReadonlyTitle {
|
||||
color: #1A1C1F;
|
||||
@@ -540,7 +542,7 @@ QFrame#DiagnosisReadonlyCaseCard,
|
||||
QFrame[diagnosisReadonlyCard="true"] {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 16px;
|
||||
border-radius: 14px;
|
||||
}
|
||||
QLabel#DiagnosisReadonlyCardTitle {
|
||||
color: #1A1C1F;
|
||||
@@ -769,7 +771,7 @@ QWidget[diagnosisChoiceHost="true"] QPushButton {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
}
|
||||
QWidget[diagnosisChoiceHost="true"] QPushButton:hover,
|
||||
@@ -1066,7 +1068,6 @@ _DIAGNOSIS_BLUE_REPLACEMENTS = (
|
||||
)
|
||||
for _source_color, _theme_color in _DIAGNOSIS_BLUE_REPLACEMENTS:
|
||||
DIAGNOSIS_QSS = DIAGNOSIS_QSS.replace(_source_color, _theme_color)
|
||||
DIAGNOSIS_QSS = clinical_stylesheet(DIAGNOSIS_QSS)
|
||||
|
||||
|
||||
def _text(value: Any, default: str = "—") -> str:
|
||||
@@ -1146,19 +1147,12 @@ class DiagnosisSwitch(QAbstractButton):
|
||||
track = QRectF(1, 3, self.width() - 2, self.height() - 6)
|
||||
checked = self.isChecked()
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"]))
|
||||
if not self.isEnabled():
|
||||
painter.setOpacity(0.6)
|
||||
painter.setBrush(QColor("#4F63D9" if checked else "#E4E4E5"))
|
||||
painter.drawRoundedRect(track, track.height() / 2, track.height() / 2)
|
||||
diameter = track.height() - 4
|
||||
x = track.right() - diameter - 2 if checked else track.left() + 2
|
||||
painter.setBrush(QColor("#FFFFFF"))
|
||||
painter.drawEllipse(QRectF(x, track.top() + 2, diameter, diameter))
|
||||
if self.hasFocus():
|
||||
painter.setOpacity(1)
|
||||
painter.setPen(QPen(QColor(PALETTE["focus"]), 1))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 11, 11)
|
||||
painter.end()
|
||||
|
||||
|
||||
@@ -1196,19 +1190,13 @@ class SaveStateButton(QPushButton):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
enabled = self.isEnabled()
|
||||
idle_color = PALETTE["accent_pressed"] if self.isDown() else PALETTE["accent"]
|
||||
color = {
|
||||
"success": PALETTE["success"],
|
||||
"error": PALETTE["danger"],
|
||||
"loading": PALETTE["accent"],
|
||||
}.get(self._state, idle_color if enabled else PALETTE["disabled_surface"])
|
||||
"success": "#287B65",
|
||||
"error": "#BE4B58",
|
||||
}.get(self._state, "#4F63D9" if enabled else "#8E8F90")
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(color))
|
||||
painter.drawRoundedRect(QRectF(self.rect()).adjusted(1, 1, -1, -1), 10, 10)
|
||||
if self.hasFocus():
|
||||
painter.setPen(QPen(QColor(PALETTE["focus"]), 1))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 10, 10)
|
||||
label = {
|
||||
"loading": "正在保存",
|
||||
"success": "保存成功",
|
||||
@@ -1232,9 +1220,7 @@ class SaveStateButton(QPushButton):
|
||||
else:
|
||||
painter.drawLine(x + 3, center_y - 5, x + 12, center_y + 5)
|
||||
painter.drawLine(x + 12, center_y - 5, x + 3, center_y + 5)
|
||||
painter.setPen(QColor(
|
||||
PALETTE["disabled"] if not enabled and self._state == "idle" else PALETTE["surface"]
|
||||
))
|
||||
painter.setPen(QColor("#FFFFFF"))
|
||||
painter.drawText(
|
||||
QRect(x + icon_width, 0, metrics.horizontalAdvance(label), self.height()),
|
||||
Qt.AlignmentFlag.AlignCenter,
|
||||
@@ -1829,10 +1815,10 @@ class MessageStrip(QFrame):
|
||||
self.glyph = QLabel("i")
|
||||
self.glyph.setFixedWidth(18)
|
||||
self.glyph.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.glyph.setStyleSheet(clinical_stylesheet("font-weight:700; color:$ds_accent;"))
|
||||
self.glyph.setStyleSheet("font-weight:700; color:#4F63D9;")
|
||||
self.label = QLabel()
|
||||
self.label.setWordWrap(True)
|
||||
self.label.setStyleSheet(clinical_stylesheet("color:$ds_text; font-size:13px;"))
|
||||
self.label.setStyleSheet("color:#1A1C1F; font-size:13px;")
|
||||
layout.addWidget(self.glyph)
|
||||
layout.addWidget(self.label, 1)
|
||||
self.action_button = QPushButton()
|
||||
@@ -1908,7 +1894,7 @@ class LoadingOverlay(QFrame):
|
||||
layout.setSpacing(8)
|
||||
self.glyph = _LoadingSpinner(self)
|
||||
label = QLabel(text)
|
||||
label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;"))
|
||||
label.setStyleSheet("color:#606163; font-size:13px;")
|
||||
layout.addWidget(self.glyph)
|
||||
layout.addWidget(label)
|
||||
self.hide()
|
||||
@@ -1999,15 +1985,15 @@ class RecordTable(QTableWidget):
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
)
|
||||
if column_index in danger_columns:
|
||||
item.setForeground(QColor(PALETTE["danger"]))
|
||||
item.setForeground(QColor("#BE4B58"))
|
||||
kind = semantic.get(column_index)
|
||||
if kind:
|
||||
palette = {
|
||||
"success": (PALETTE["success"], PALETTE["success_soft"]),
|
||||
"warning": (PALETTE["warning"], PALETTE["warning_soft"]),
|
||||
"danger": (PALETTE["danger"], PALETTE["danger_soft"]),
|
||||
"info": (PALETTE["accent"], PALETTE["accent_soft"]),
|
||||
"neutral": (PALETTE["muted"], PALETTE["surface_alt"]),
|
||||
"success": ("#287B65", "#EAF9F3"),
|
||||
"warning": ("#A9691D", "#FFF5E6"),
|
||||
"danger": ("#BE4B58", "#FFF1F3"),
|
||||
"info": ("#4F63D9", "#EEF1FA"),
|
||||
"neutral": ("#6A6B6D", "#F7F7F7"),
|
||||
}
|
||||
foreground, background = palette.get(kind, palette["neutral"])
|
||||
item.setForeground(QColor(foreground))
|
||||
@@ -2047,20 +2033,20 @@ class BloodTrendChart(QWidget):
|
||||
plot = self.rect().adjusted(48, 24, -22, -38)
|
||||
values = [value for value in (*self._fasting, *self._postprandial) if value is not None]
|
||||
if not values or plot.width() <= 0 or plot.height() <= 0:
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setPen(QColor("#606163"))
|
||||
painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, "当前时间范围暂无血糖数据")
|
||||
painter.end()
|
||||
return
|
||||
upper = max(12.0, max(values) * 1.15)
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1))
|
||||
for step in range(5):
|
||||
y = plot.bottom() - round(plot.height() * step / 4)
|
||||
painter.drawLine(plot.left(), y, plot.right(), y)
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setPen(QColor("#606163"))
|
||||
painter.drawText(
|
||||
4, y - 8, 40, 16, Qt.AlignmentFlag.AlignRight, f"{upper * step / 4:.0f}"
|
||||
)
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1))
|
||||
count = max(1, len(self._dates) - 1)
|
||||
|
||||
def point(index: int, value: float) -> QPointF:
|
||||
@@ -2090,7 +2076,7 @@ class BloodTrendChart(QWidget):
|
||||
painter.setPen(QColor("#A9691D"))
|
||||
painter.drawText(plot.left() + 100, 4, 110, 18, Qt.AlignmentFlag.AlignLeft, "● 餐后血糖")
|
||||
if self._dates:
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setPen(QColor("#606163"))
|
||||
painter.drawText(
|
||||
plot.left(),
|
||||
plot.bottom() + 8,
|
||||
@@ -2293,7 +2279,7 @@ class DailyRecordPanel(QFrame):
|
||||
self.todo_table.setMinimumHeight(180)
|
||||
todo_layout.addWidget(self.todo_table)
|
||||
self.todo_summary = QLabel("共 0 条")
|
||||
self.todo_summary.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;"))
|
||||
self.todo_summary.setStyleSheet("color:#606163; font-size:13px;")
|
||||
todo_layout.addWidget(self.todo_summary, 0, Qt.AlignmentFlag.AlignRight)
|
||||
root.addWidget(todo_card)
|
||||
self.clear()
|
||||
@@ -2451,8 +2437,8 @@ class DailyRecordPanel(QFrame):
|
||||
for row_index, (metric, label) in enumerate(self.METRICS):
|
||||
label_item = QTableWidgetItem(label)
|
||||
label_item.setFont(label_font)
|
||||
label_item.setForeground(QColor(PALETTE["muted"]))
|
||||
label_item.setBackground(QColor(PALETTE["surface_alt"]))
|
||||
label_item.setForeground(QColor("#606163"))
|
||||
label_item.setBackground(QColor("#F7F7F7"))
|
||||
self.matrix.setItem(row_index, 0, label_item)
|
||||
for date_index, date in enumerate(dates, 1):
|
||||
b = blood.get(date)
|
||||
@@ -2505,11 +2491,11 @@ class DailyRecordPanel(QFrame):
|
||||
item = QTableWidgetItem(value)
|
||||
item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
if high:
|
||||
item.setForeground(QColor(PALETTE["danger"]))
|
||||
item.setBackground(QColor(PALETTE["danger_soft"]))
|
||||
item.setForeground(QColor("#BE4B58"))
|
||||
item.setBackground(QColor("#FFF1F3"))
|
||||
elif value.endswith("· 自录"):
|
||||
item.setForeground(QColor(PALETTE["text"]))
|
||||
item.setBackground(QColor(PALETTE["surface_alt"]))
|
||||
item.setForeground(QColor("#1A1C1F"))
|
||||
item.setBackground(QColor("#F7F7F7"))
|
||||
edit_kind = ""
|
||||
edit_source: Any = None
|
||||
if metric in {"fasting", "postprandial", "other", "bp", "western", "insulin"}:
|
||||
@@ -3036,7 +3022,7 @@ class ChatPanel(QWidget):
|
||||
toolbar_layout.setContentsMargins(0, 0, 0, 0)
|
||||
toolbar_layout.setSpacing(8)
|
||||
archive = QLabel("仅展示服务端已归档消息(only_archived=1)")
|
||||
archive.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;"))
|
||||
archive.setStyleSheet("color:#606163;font-size:12px;")
|
||||
toolbar_layout.addWidget(archive)
|
||||
toolbar_layout.addStretch(1)
|
||||
self.sync_button = QPushButton("同步最新(后台异步)")
|
||||
@@ -3312,7 +3298,7 @@ class CaseGrid(QFrame):
|
||||
if group_index:
|
||||
divider = QFrame()
|
||||
divider.setFrameShape(QFrame.Shape.HLine)
|
||||
divider.setStyleSheet(clinical_stylesheet("border:0; border-top:1px solid $ds_line;"))
|
||||
divider.setStyleSheet("border:0; border-top:1px dashed #E4E4E5;")
|
||||
self.root.addWidget(divider)
|
||||
group_title = QLabel(f"● {group_name}")
|
||||
group_title.setProperty("diagnosisCaseGroup", True)
|
||||
@@ -3470,11 +3456,11 @@ def readonly_card(title: str, object_name: str, body: QWidget) -> QFrame:
|
||||
|
||||
def set_tag_item(item: QTableWidgetItem, kind: str) -> None:
|
||||
palette = {
|
||||
"success": (PALETTE["success"], PALETTE["success_soft"]),
|
||||
"warning": (PALETTE["warning"], PALETTE["warning_soft"]),
|
||||
"danger": (PALETTE["danger"], PALETTE["danger_soft"]),
|
||||
"info": (PALETTE["accent"], PALETTE["accent_soft"]),
|
||||
"neutral": (PALETTE["muted"], PALETTE["surface_alt"]),
|
||||
"success": ("#287B65", "#EAF9F3"),
|
||||
"warning": ("#A9691D", "#FFF5E6"),
|
||||
"danger": ("#BE4B58", "#FFF1F3"),
|
||||
"info": ("#4F63D9", "#EEF1FA"),
|
||||
"neutral": ("#6A6B6D", "#F7F7F7"),
|
||||
}
|
||||
foreground, background = palette.get(kind, palette["neutral"])
|
||||
item.setForeground(QColor(foreground))
|
||||
|
||||
@@ -67,22 +67,21 @@ from ..core.appointment_modes import (
|
||||
can_appointment_video,
|
||||
)
|
||||
from . import icons
|
||||
from .design_system import PALETTE, clinical_stylesheet
|
||||
from .reception_style import TECH_BLUE, body_family, heading_family
|
||||
from .widgets import display_text, first_value, gender_text, get_value
|
||||
|
||||
PRIMARY = QColor(PALETTE["accent"])
|
||||
TEXT = QColor(PALETTE["text"])
|
||||
SECONDARY = QColor(PALETTE["muted"])
|
||||
PLACEHOLDER = QColor(PALETTE["disabled"])
|
||||
PRIMARY = QColor("#4F63D9")
|
||||
TEXT = QColor("#1A1C1F")
|
||||
SECONDARY = QColor("#606163")
|
||||
PLACEHOLDER = QColor("#8E8F90")
|
||||
_INVALID_INDEX = QModelIndex()
|
||||
# The last two columns form the compact frozen pane. Video status and ending
|
||||
# time occupy separate lines; actions keep two inline links plus 更多, with
|
||||
# the remaining actions in its menu so clinical columns retain more space.
|
||||
_TABLE_COLUMN_WIDTHS = (48, 70, 60, 100, 175, 88, 120, 100, 72, 110, 96, 160)
|
||||
_BLUE_COLUMN_WIDTHS = (48, 70, 82, 102, 244, 90, 84, 90, 88, 122, 92, 158)
|
||||
_BLUE_WARNING = QColor(PALETTE["warning"])
|
||||
_BLUE_DANGER = QColor(PALETTE["danger"])
|
||||
_BLUE_WARNING = QColor("#A9691D")
|
||||
_BLUE_DANGER = QColor("#BE4B58")
|
||||
|
||||
|
||||
def _blue_font(pixels: int = 13, *, medium: bool = False) -> QFont:
|
||||
@@ -249,14 +248,14 @@ class _DiagnosisActionMenu(QMenu):
|
||||
return
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||
painter.fillRect(rect, QColor(PALETTE["surface"]))
|
||||
painter.fillRect(rect, QColor("#FFFFFF"))
|
||||
item_rect = rect
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["surface_alt"]) if self.activeAction() is action else QColor(PALETTE["surface"]))
|
||||
painter.setBrush(QColor("#F7F7F7") if self.activeAction() is action else QColor("#FFFFFF"))
|
||||
painter.drawRoundedRect(item_rect, 3, 3)
|
||||
icon_rect = QRect(item_rect.left() + 8, item_rect.center().y() - 9, 18, 18)
|
||||
action.icon().paint(painter, icon_rect)
|
||||
painter.setPen(QColor(PALETTE["danger"] if action.isEnabled() else PALETTE["disabled"]))
|
||||
painter.setPen(QColor("#BE4B58" if action.isEnabled() else "#8E8F90"))
|
||||
painter.drawText(
|
||||
item_rect.adjusted(34, 0, -10, 0),
|
||||
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
||||
@@ -824,8 +823,6 @@ class DiagnosisTableModel(QAbstractTableModel):
|
||||
default="",
|
||||
)
|
||||
return f"最近渠道:{channel}" if channel else ""
|
||||
if column == 6:
|
||||
return DiagnosisTableModel._display(row, column)
|
||||
if column == 7:
|
||||
return display_text(first_value(row, "assistant_name"), "")
|
||||
if column == 9:
|
||||
@@ -852,7 +849,7 @@ class DiagnosisHeader(QHeaderView):
|
||||
def paintSection(self, painter: QPainter, rect: QRect, logical_index: int) -> None: # noqa: N802
|
||||
if self.tech_blue:
|
||||
painter.save()
|
||||
painter.fillRect(rect, QColor(PALETTE["surface_alt"]))
|
||||
painter.fillRect(rect, QColor("#F5F8FD"))
|
||||
painter.setPen(QPen(QColor(TECH_BLUE["line"]), 1))
|
||||
painter.drawLine(rect.bottomLeft(), rect.bottomRight())
|
||||
painter.setFont(_blue_font())
|
||||
@@ -873,7 +870,7 @@ class DiagnosisHeader(QHeaderView):
|
||||
painter.save()
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
primary = QColor(TECH_BLUE["accent"]) if self.tech_blue else PRIMARY
|
||||
secondary = QColor(TECH_BLUE["muted"]) if self.tech_blue else QColor(PALETTE["muted"])
|
||||
secondary = QColor(TECH_BLUE["muted"]) if self.tech_blue else QColor("#606163")
|
||||
painter.setBrush(primary if direction == "asc" else secondary)
|
||||
painter.drawPolygon(
|
||||
QPolygon(
|
||||
@@ -956,7 +953,7 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
|
||||
painter,
|
||||
option.rect,
|
||||
"已确认" if _confirmed(record) else "未确认",
|
||||
QColor(PALETTE["success"]) if _confirmed(record) else QColor(PALETTE["warning"]),
|
||||
QColor("#287B65") if _confirmed(record) else QColor("#A9691D"),
|
||||
)
|
||||
elif index.column() == 6:
|
||||
self._paint_followup(painter, option.rect, record)
|
||||
@@ -1026,16 +1023,16 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
|
||||
) -> None:
|
||||
hovered = model.hover_row == row
|
||||
base = (
|
||||
QColor(PALETTE["accent_soft"])
|
||||
QColor("#EEF1FA")
|
||||
if selected
|
||||
else QColor(PALETTE["surface_alt"] if hovered or row % 2 else PALETTE["surface"])
|
||||
else QColor("#F7F7F7" if hovered else "#F7F7F7" if row % 2 else "#FFFFFF")
|
||||
)
|
||||
special = not _confirmed(record) or not _has_appointment(record)
|
||||
painter.fillRect(rect, base)
|
||||
if special and column == 0:
|
||||
stripe = QColor(PALETTE["warning"]) if not _confirmed(record) else QColor(PALETTE["accent"])
|
||||
stripe = QColor("#A9691D") if not _confirmed(record) else QColor("#4F63D9")
|
||||
painter.fillRect(QRect(rect.left(), rect.top(), 3, rect.height()), stripe)
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1))
|
||||
painter.drawLine(QLine(rect.bottomLeft(), rect.bottomRight()))
|
||||
|
||||
@staticmethod
|
||||
@@ -1073,8 +1070,8 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
|
||||
painter,
|
||||
QRect(left, content.center().y() - 10, 31, 20),
|
||||
"NEW",
|
||||
QColor(PALETTE["danger"]),
|
||||
QColor(PALETTE["surface"]),
|
||||
QColor("#BE4B58"),
|
||||
QColor("#FFFFFF"),
|
||||
10,
|
||||
)
|
||||
|
||||
@@ -1084,17 +1081,17 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
|
||||
self._draw_text(painter, content, "未挂号", PLACEHOLDER, 13)
|
||||
return
|
||||
rows = _appointments(record)
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
|
||||
painter.setBrush(QColor(PALETTE["surface"]))
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1))
|
||||
painter.setBrush(QColor("#FFFFFF"))
|
||||
painter.drawRoundedRect(content, 6, 6)
|
||||
y = content.top() + 4
|
||||
for position, appointment in enumerate(rows or [{}]):
|
||||
status = _as_int(first_value(appointment, "status", "appointment_status"), -1)
|
||||
label, fg, bg = {
|
||||
1: ("已预约", QColor(PALETTE["accent"]), QColor(PALETTE["accent_soft"])),
|
||||
3: ("已完成", QColor(PALETTE["success"]), QColor(PALETTE["success_soft"])),
|
||||
4: ("已过号", QColor(PALETTE["warning"]), QColor(PALETTE["warning_soft"])),
|
||||
}.get(status, ("未知", SECONDARY, QColor(PALETTE["surface_alt"])))
|
||||
1: ("已预约", QColor("#4F63D9"), QColor("#EEF1FA")),
|
||||
3: ("已完成", QColor("#287B65"), QColor("#E8F6F1")),
|
||||
4: ("已过号", QColor("#A9691D"), QColor("#FFF4D8")),
|
||||
}.get(status, ("未知", SECONDARY, QColor("#F7F7F7")))
|
||||
self._draw_tag(painter, QRect(content.left() + 6, y, 46, 20), label, bg, fg, 12)
|
||||
doctor = display_text(first_value(appointment, "doctor_name"), "-")
|
||||
time_text = display_text(first_value(appointment, "time_text", "appointment_time"), "-")
|
||||
@@ -1109,12 +1106,12 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
|
||||
painter,
|
||||
QRect(content.left() + 6, y + 19, max(20, content.width() - 12), 17),
|
||||
time_text,
|
||||
QColor(PALETTE["warning"]) if status == 4 else SECONDARY,
|
||||
QColor("#A9691D") if status == 4 else SECONDARY,
|
||||
13,
|
||||
)
|
||||
y += 42
|
||||
if position < len(rows) - 1:
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1, Qt.PenStyle.DashLine))
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1, Qt.PenStyle.DashLine))
|
||||
painter.drawLine(content.left() + 6, y - 2, content.right() - 6, y - 2)
|
||||
channel = first_value(
|
||||
record,
|
||||
@@ -1156,7 +1153,7 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
|
||||
painter,
|
||||
QRect(content.left(), content.top() + 38, 72, 18),
|
||||
"处方已作废",
|
||||
QColor(PALETTE["surface_alt"]),
|
||||
QColor("#F7F7F7"),
|
||||
SECONDARY,
|
||||
11,
|
||||
outlined=True,
|
||||
@@ -1169,11 +1166,11 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
|
||||
else:
|
||||
days = _as_int(value)
|
||||
color = (
|
||||
QColor(PALETTE["success"])
|
||||
QColor("#287B65")
|
||||
if days <= 2
|
||||
else QColor(PALETTE["warning"])
|
||||
else QColor("#A9691D")
|
||||
if days <= 6
|
||||
else QColor(PALETTE["danger"])
|
||||
else QColor("#BE4B58")
|
||||
)
|
||||
text, bold = str(days), days > 6
|
||||
self._draw_text(
|
||||
@@ -1323,8 +1320,6 @@ class _TechBlueDiagnosisDelegate(DiagnosisItemDelegate):
|
||||
painter, content, "已确认" if _confirmed(record) else "未确认", pixels=13,
|
||||
color="text" if _confirmed(record) else _BLUE_WARNING.name(),
|
||||
)
|
||||
elif column == 6:
|
||||
self._followup(painter, content, display_text(index.data(), "—"))
|
||||
elif column == 8:
|
||||
prescribed = _as_bool(first_value(record, "has_prescription"))
|
||||
self._text(painter, content, "已开方" if prescribed else "未开方",
|
||||
@@ -1353,28 +1348,6 @@ class _TechBlueDiagnosisDelegate(DiagnosisItemDelegate):
|
||||
medium=column == 2)
|
||||
painter.restore()
|
||||
|
||||
@staticmethod
|
||||
def _followup(painter: QPainter, rect: QRect, text: str) -> None:
|
||||
"""Break at the date/time boundary, never in the middle of a number.
|
||||
|
||||
Keep the established row metrics. Long time ranges or doctor names
|
||||
elide within their line; the model tooltip retains the complete text.
|
||||
"""
|
||||
painter.setFont(_blue_font(13))
|
||||
painter.setPen(QColor(TECH_BLUE["muted"]))
|
||||
metrics = painter.fontMetrics()
|
||||
lines = text.splitlines()
|
||||
if lines and metrics.horizontalAdvance(lines[0]) > rect.width():
|
||||
lines[:1] = lines[0].split(maxsplit=1)
|
||||
line_height = metrics.height()
|
||||
top = rect.top() + max(0, (rect.height() - line_height * len(lines)) // 2)
|
||||
for offset, line in enumerate(lines):
|
||||
painter.drawText(
|
||||
QRect(rect.left(), top + offset * line_height, rect.width(), line_height),
|
||||
int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine),
|
||||
metrics.elidedText(line, Qt.TextElideMode.ElideRight, rect.width()),
|
||||
)
|
||||
|
||||
def _appointments(self, painter: QPainter, rect: QRect, record: Any) -> None:
|
||||
content = rect.adjusted(8, 0, -8, 0)
|
||||
if not _has_appointment(record):
|
||||
@@ -1715,9 +1688,7 @@ class DiagnosisTableHost(QFrame):
|
||||
self.main.horizontalHeader().sectionResized.connect(self._columns_resized)
|
||||
self._fixed_render_signature: tuple[Any, ...] | None = None
|
||||
if tech_blue:
|
||||
self.setStyleSheet(clinical_stylesheet(
|
||||
_TECH_BLUE_TABLE_QSS.replace("BODY_FAMILY", body_family())
|
||||
))
|
||||
self.setStyleSheet(_TECH_BLUE_TABLE_QSS.replace("BODY_FAMILY", body_family()))
|
||||
|
||||
def set_rows(self, rows: Iterable[Any]) -> None:
|
||||
previous_id = DiagnosisTableModel.record_id(self.main.current_data())
|
||||
@@ -1933,7 +1904,6 @@ class DiagnosisTableHost(QFrame):
|
||||
.replace("#8E8F90", TECH_BLUE["muted"])
|
||||
+ f'QMenu {{ font-family: "{body_family()}"; font-weight: 400; }}'
|
||||
)
|
||||
menu.setStyleSheet(clinical_stylesheet(menu.styleSheet()))
|
||||
for label, action, _semantic in demoted_actions:
|
||||
_add_menu_action(
|
||||
menu,
|
||||
@@ -2660,19 +2630,19 @@ DIAGNOSIS_INDEX_QSS += """
|
||||
#DiagnosisIndex QFrame#DiagnosisFilterCard,
|
||||
#DiagnosisIndex QFrame#DiagnosisListCard {
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 13px;
|
||||
}
|
||||
#DiagnosisIndex QLineEdit,
|
||||
#DiagnosisIndex QComboBox,
|
||||
#DiagnosisIndex QDateEdit,
|
||||
#DiagnosisIndex QSpinBox,
|
||||
#DiagnosisIndex QPushButton {
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 8px;
|
||||
}
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"] { border-radius: $ds_radius_small; }
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"] { border-radius: 8px; }
|
||||
#DiagnosisIndex QFrame#DiagnosisListToolbar {
|
||||
border-top-left-radius: $ds_radius_panel;
|
||||
border-top-right-radius: $ds_radius_panel;
|
||||
border-top-left-radius: 13px;
|
||||
border-top-right-radius: 13px;
|
||||
}
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked[semantic="primary"],
|
||||
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked[semantic="info"],
|
||||
@@ -2680,27 +2650,7 @@ DIAGNOSIS_INDEX_QSS += """
|
||||
#DiagnosisIndex QPushButton[variant="success"] {
|
||||
color: #FFFFFF;
|
||||
}
|
||||
#DiagnosisIndex QLineEdit:focus,
|
||||
#DiagnosisIndex QComboBox:focus,
|
||||
#DiagnosisIndex QDateEdit:focus,
|
||||
#DiagnosisIndex QSpinBox:focus,
|
||||
#DiagnosisIndex QPushButton:focus {
|
||||
border-color: $ds_focus;
|
||||
}
|
||||
#DiagnosisIndex QPushButton[variant="primary"]:pressed {
|
||||
color: $ds_surface;
|
||||
background-color: $ds_accent_pressed;
|
||||
border-color: $ds_accent_pressed;
|
||||
}
|
||||
#DiagnosisIndex QPushButton:disabled,
|
||||
#DiagnosisIndex QPushButton[variant="primary"]:disabled,
|
||||
#DiagnosisIndex QPushButton[variant="success"]:disabled {
|
||||
color: $ds_disabled;
|
||||
background-color: $ds_disabled_surface;
|
||||
border-color: $ds_line;
|
||||
}
|
||||
"""
|
||||
DIAGNOSIS_INDEX_QSS = clinical_stylesheet(DIAGNOSIS_INDEX_QSS)
|
||||
|
||||
|
||||
__all__ = [
|
||||
|
||||
@@ -32,8 +32,6 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
|
||||
try:
|
||||
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
|
||||
from PySide6.QtMultimediaWidgets import QVideoWidget
|
||||
@@ -225,7 +223,7 @@ class InlineRecordingPlayer(QWidget):
|
||||
self.setMinimumHeight(158)
|
||||
self.setMaximumHeight(180)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
self.setStyleSheet(clinical_stylesheet(_INLINE_PLAYER_QSS))
|
||||
self.setStyleSheet(_INLINE_PLAYER_QSS)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(1, 1, 1, 5)
|
||||
@@ -468,11 +466,11 @@ class RecordingPlaybackCell(QWidget):
|
||||
separator = QFrame()
|
||||
separator.setObjectName("DiagnosisRecordingAlternateSeparator")
|
||||
separator.setFrameShape(QFrame.Shape.HLine)
|
||||
separator.setStyleSheet(clinical_stylesheet("color:$ds_line;"))
|
||||
separator.setStyleSheet("color:#EDEDEE;")
|
||||
layout.addWidget(separator)
|
||||
label = QLabel("备用地址")
|
||||
label.setObjectName("DiagnosisRecordingAlternateLabel")
|
||||
label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:12px;"))
|
||||
label.setStyleSheet("color:#606163; font-size:12px;")
|
||||
layout.addWidget(label)
|
||||
links = QHBoxLayout()
|
||||
links.setContentsMargins(0, 0, 0, 0)
|
||||
@@ -492,7 +490,7 @@ class RecordingPlaybackCell(QWidget):
|
||||
layout.addLayout(links)
|
||||
self.link_status = QLabel("")
|
||||
self.link_status.setObjectName("DiagnosisRecordingLinkStatus")
|
||||
self.link_status.setStyleSheet(clinical_stylesheet("color:$ds_danger; font-size:11px;"))
|
||||
self.link_status.setStyleSheet("color:#BE4B58; font-size:11px;")
|
||||
self.link_status.setWordWrap(True)
|
||||
self.link_status.hide()
|
||||
layout.addWidget(self.link_status)
|
||||
@@ -809,7 +807,7 @@ class ImagePreviewDialog(QDialog):
|
||||
self.setObjectName("DiagnosisImagePreview")
|
||||
self.setWindowTitle(title)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
|
||||
self.setStyleSheet(clinical_stylesheet(_IMAGE_PREVIEW_QSS))
|
||||
self.setStyleSheet(_IMAGE_PREVIEW_QSS)
|
||||
self.resize(880, 660)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
|
||||
@@ -62,7 +62,6 @@ from shiboken6 import isValid
|
||||
|
||||
from .. import icons
|
||||
from ..chat_items import parse_chat_item as _parse_chat_item
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..diagnosis_drawer import CaseGrid, _RemoteImageButton
|
||||
from ..diagnosis_index_widgets import FlowWidget
|
||||
from ..diagnosis_media import (
|
||||
@@ -95,9 +94,6 @@ from ..widgets import (
|
||||
show_toast,
|
||||
)
|
||||
from .ai_consult_charts import GlucoseChartData
|
||||
from .ai_consult_drug_names import TCM as DRUG_TCM
|
||||
from .ai_consult_drug_names import WESTERN as DRUG_WESTERN
|
||||
from .ai_consult_drug_names import summarize_drugs
|
||||
from .ai_consult_metric_state import (
|
||||
ABNORMAL_COLOR,
|
||||
NORMAL_COLOR,
|
||||
@@ -105,6 +101,7 @@ from .ai_consult_metric_state import (
|
||||
combined_metric_state,
|
||||
risk_color,
|
||||
)
|
||||
from .ai_consult_drug_names import TCM as DRUG_TCM, WESTERN as DRUG_WESTERN, summarize_drugs
|
||||
from .ai_consult_metric_text import MetricTextState, metric_text_context, metric_text_html
|
||||
from .ai_consult_report_visuals import (
|
||||
ReportVisual,
|
||||
@@ -117,10 +114,10 @@ from .prescription_ai import (
|
||||
diagnosis_ai_task,
|
||||
)
|
||||
|
||||
AI_CONSULT_QSS = clinical_stylesheet("""
|
||||
AI_CONSULT_QSS = """
|
||||
QDialog#AiConsultDialog {
|
||||
color: $ds_text;
|
||||
background-color: $ds_canvas; font-size: 14px;
|
||||
color: #1A1C1F;
|
||||
background-color: #F7F7F7; font-size: 14px;
|
||||
}
|
||||
QDialog#AiConsultDialog QScrollArea,
|
||||
QDialog#AiConsultDialog QScrollArea > QWidget,
|
||||
@@ -152,7 +149,7 @@ QDialog#AiConsultDialog QScrollBar::sub-page:vertical {
|
||||
background-color: transparent;
|
||||
}
|
||||
QDialog#AiConsultDialog QFrame#AiConsultShell {
|
||||
background-color: $ds_canvas;
|
||||
background-color: #F7F7F7;
|
||||
border: 0;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultCrumb {
|
||||
@@ -174,7 +171,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultBack {
|
||||
color: #1A1C1F;
|
||||
background-color: #F0F0F0;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#AiConsultDialog QPushButton#AiConsultBack:hover { background-color: #EEF1FA; }
|
||||
@@ -186,7 +183,7 @@ QDialog#AiConsultDialog QFrame#AiConsultHero {
|
||||
QDialog#AiConsultDialog QLabel#AiConsultAvatar {
|
||||
color: #FFFFFF;
|
||||
background-color: #4F63D9;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 22px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
@@ -204,7 +201,7 @@ QDialog#AiConsultDialog QLabel#AiConsultMeta {
|
||||
QDialog#AiConsultDialog QLabel#AiConsultChip {
|
||||
color: #6A6B6D;
|
||||
background-color: #F7F7F7;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 8px;
|
||||
padding: 4px 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -243,7 +240,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultChatFilter {
|
||||
color: #4F63D9;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #E1E5F4;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
QDialog#AiConsultDialog QPushButton#AiConsultChatFilter:hover {
|
||||
@@ -278,7 +275,7 @@ QDialog#AiConsultDialog QLabel#AiConsultRole {
|
||||
max-width: 30px;
|
||||
min-height: 30px;
|
||||
max-height: 30px;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 15px;
|
||||
color: #FFFFFF;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -334,7 +331,7 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalMeta {
|
||||
QDialog#AiConsultDialog QLabel#AiConsultClinicalBadge {
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 7px;
|
||||
padding: 4px 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -349,10 +346,10 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalSectionTitle {
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultClinicalSummaryBody {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
@@ -414,7 +411,7 @@ QDialog#AiConsultDialog QLabel#AiConsultHypothesisTag {
|
||||
QDialog#AiConsultDialog QLabel#AiConsultClinicalBody,
|
||||
QDialog#AiConsultDialog QLabel#AiConsultWorkflowBody,
|
||||
QDialog#AiConsultDialog QLabel#AiConsultRiskBody {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
@@ -459,23 +456,23 @@ QDialog#AiConsultDialog QLabel#AiConsultRiskTitle {
|
||||
font-weight: 600;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultRiskBody {
|
||||
color: $ds_text; font-size: 14px;
|
||||
color: #1A1C1F; font-size: 14px;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultRiskTitle {
|
||||
color: #BE4B58;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultRiskBody {
|
||||
color: $ds_text; font-size: 14px;
|
||||
color: #1A1C1F; font-size: 14px;
|
||||
}
|
||||
/* 结构化报告:正文按阅读节奏排版,不再每句话套一个方框。 */
|
||||
QDialog#AiConsultDialog QFrame#AiConsultReportIntro {
|
||||
background-color: $ds_accent_soft;
|
||||
background-color: #F7F7F7;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-left: 3px solid #4F63D9;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultReportIntroBody {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
@@ -500,7 +497,7 @@ QDialog#AiConsultDialog QLabel#AiConsultReportSectionTitle {
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#AiConsultDialog QFrame#AiConsultReportRule {
|
||||
background-color: #EDEDEE;
|
||||
@@ -521,7 +518,7 @@ QDialog#AiConsultDialog QLabel#AiConsultReportBullet {
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultReportBody {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
@@ -544,18 +541,18 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalDisclaimer {
|
||||
font-weight: 400;
|
||||
}
|
||||
QDialog#AiConsultDialog QFrame#AiConsultReportProvenance {
|
||||
background-color: $ds_surface_alt;
|
||||
border: 1px solid $ds_line;
|
||||
border-radius: $ds_radius_control;
|
||||
background-color: #F7F8FC;
|
||||
border: 1px solid #E4E8F2;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultReportProvenanceTitle {
|
||||
color: $ds_heading;
|
||||
color: #27336B;
|
||||
background-color: transparent;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultReportProvenanceLine {
|
||||
color: $ds_muted;
|
||||
color: #555B68;
|
||||
background-color: transparent;
|
||||
font-size: 12px;
|
||||
}
|
||||
@@ -650,7 +647,7 @@ QDialog#AiConsultDialog QLabel#AiConsultSection {
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultBody {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
@@ -684,7 +681,7 @@ QDialog#AiConsultDialog QLabel#AiConsultInsightPlaceholder {
|
||||
QDialog#AiConsultDialog QLabel#AiConsultTag[level="high"] {
|
||||
color: #BE4B58;
|
||||
background-color: #FFF1F3;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 8px;
|
||||
padding: 2px 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
@@ -692,7 +689,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="high"] {
|
||||
QDialog#AiConsultDialog QLabel#AiConsultTag[level="medium"] {
|
||||
color: #A9691D;
|
||||
background-color: #FFF5E6;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 8px;
|
||||
padding: 2px 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -700,7 +697,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="medium"] {
|
||||
QDialog#AiConsultDialog QLabel#AiConsultTag[level="low"] {
|
||||
color: #287B65;
|
||||
background-color: #EAF9F3;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 8px;
|
||||
padding: 2px 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -708,7 +705,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="low"] {
|
||||
QDialog#AiConsultDialog QLabel#AiConsultTag[level="warn"] {
|
||||
color: #BE4B58;
|
||||
background-color: #FFF1F3;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 8px;
|
||||
padding: 2px 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
@@ -716,7 +713,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="warn"] {
|
||||
QDialog#AiConsultDialog QLabel#AiConsultTag[level="unknown"] {
|
||||
color: #6A6B6D;
|
||||
background-color: #F0F0F0;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 8px;
|
||||
padding: 2px 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -742,7 +739,7 @@ QDialog#AiConsultDialog QLineEdit#AiConsultInput {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 12px;
|
||||
font-size: 14px;
|
||||
}
|
||||
QDialog#AiConsultDialog QLineEdit#AiConsultInput:focus {
|
||||
@@ -766,7 +763,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultIconButton {
|
||||
max-height: 36px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 18px;
|
||||
background-color: #F7F7F7;
|
||||
}
|
||||
QDialog#AiConsultDialog QPushButton#AiConsultIconButton:hover { background-color: #EEF1FA; }
|
||||
@@ -777,7 +774,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultSend {
|
||||
max-height: 40px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 20px;
|
||||
background-color: #4F63D9;
|
||||
}
|
||||
QDialog#AiConsultDialog QPushButton#AiConsultSend:hover { background-color: #4156C4; }
|
||||
@@ -786,7 +783,7 @@ QDialog#AiConsultDialog QLabel#AiConsultSideTitle {
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultSideSubtitle {
|
||||
color: #6A6B6D;
|
||||
@@ -874,7 +871,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultSideClose {
|
||||
max-height: 28px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 8px;
|
||||
color: #606163;
|
||||
background-color: transparent;
|
||||
font-size: 16px;
|
||||
@@ -920,10 +917,10 @@ QDialog#AiConsultDialog QLabel#AiConsultRecordTitle {
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultRecordBody {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
}
|
||||
@@ -954,7 +951,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultMediaOpen {
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#AiConsultDialog QPushButton#AiConsultRecordRetry:hover,
|
||||
@@ -1003,11 +1000,10 @@ QDialog#AiConsultDialog QLabel#AiConsultDataLabel {
|
||||
font-size: 13px;
|
||||
}
|
||||
QDialog#AiConsultDialog QLabel#AiConsultDataValue {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
font-size: 13px;
|
||||
}
|
||||
QDialog#AiConsultDialog QPushButton:focus { border-color: $ds_focus; }
|
||||
""")
|
||||
"""
|
||||
|
||||
QUICK_PROMPTS: tuple[tuple[str, str], ...] = (
|
||||
("总结当前病情", "请根据当前病历总结患者病情、证候与风险。"),
|
||||
@@ -1057,8 +1053,8 @@ _DOCTOR_DOCUMENT_CSS = (
|
||||
# 模型回复几乎都是“分节标题 + 两层要点”的长文。早期样式里标题只比正文大 1px、
|
||||
# 段落与列表项的间距也几乎相同,整段读起来就是一堵字墙。这里把层级、行距和分节
|
||||
# 留白拉开:标题明显更大更重,顶层小节之间留出整行空白,嵌套要点单独收紧缩进。
|
||||
_AI_DOCUMENT_CSS = clinical_stylesheet(
|
||||
"body { color:$ds_text; font-size:14px; line-height:200%; } "
|
||||
_AI_DOCUMENT_CSS = (
|
||||
"body { color:#1A1C1F; font-size:14px; line-height:200%; } "
|
||||
"h1,h2 { color:#1A1C1F; font-size:17px; margin:22px 0 10px; line-height:160%; } "
|
||||
"h3,h4 { color:#1A1C1F; font-size:15px; margin:18px 0 8px; line-height:160%; } "
|
||||
"p { margin:10px 0; line-height:200%; } "
|
||||
@@ -2223,12 +2219,15 @@ def _escape_html(value: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
class _FlowRow(FlowWidget):
|
||||
"""Keep patient metadata readable when the details pane is narrow."""
|
||||
|
||||
class _FlowRow(QWidget):
|
||||
def __init__(self, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent, horizontal_spacing=8, vertical_spacing=6)
|
||||
self._layout = self.flow
|
||||
super().__init__(parent)
|
||||
self._layout = QHBoxLayout(self)
|
||||
self._layout.setContentsMargins(0, 0, 0, 0)
|
||||
self._layout.setSpacing(8)
|
||||
self._layout.setAlignment(
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
)
|
||||
|
||||
def add(self, widget: QWidget) -> None:
|
||||
self._layout.addWidget(widget)
|
||||
@@ -2811,7 +2810,7 @@ class _DrugSummaryStrip(QFrame):
|
||||
layout.addLayout(row)
|
||||
|
||||
@staticmethod
|
||||
def for_text(text: str, parent: QWidget | None = None) -> _DrugSummaryStrip | None:
|
||||
def for_text(text: str, parent: QWidget | None = None) -> "_DrugSummaryStrip | None":
|
||||
summary = summarize_drugs(text)
|
||||
return _DrugSummaryStrip(summary, parent) if any(summary.values()) else None
|
||||
|
||||
@@ -3455,11 +3454,11 @@ class _ChatBubble(QWidget):
|
||||
avatar.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
_style_surface(avatar)
|
||||
if role == "doctor":
|
||||
avatar.setStyleSheet(clinical_stylesheet("background-color:#4F63D9; color:#FFFFFF; border-radius:6px;"))
|
||||
avatar.setStyleSheet("background-color:#4F63D9; color:#FFFFFF; border-radius:15px;")
|
||||
elif role == "ai":
|
||||
avatar.setStyleSheet(clinical_stylesheet("background-color:#EEF1FA; color:#4F63D9; border-radius:6px;"))
|
||||
avatar.setStyleSheet("background-color:#EEF1FA; color:#4F63D9; border-radius:15px;")
|
||||
else:
|
||||
avatar.setStyleSheet(clinical_stylesheet("background-color:#6A6B6D; color:#FFFFFF; border-radius:6px;"))
|
||||
avatar.setStyleSheet("background-color:#6A6B6D; color:#FFFFFF; border-radius:15px;")
|
||||
bubble = QFrame()
|
||||
_style_surface(bubble)
|
||||
if role == "doctor":
|
||||
@@ -3630,10 +3629,10 @@ class _ChatBubble(QWidget):
|
||||
toggle.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
toggle.setAccessibleName("展开资料提交回执")
|
||||
toggle.setStyleSheet(
|
||||
clinical_stylesheet("QPushButton {color:$ds_muted;font-size:12px;text-align:left;"
|
||||
"QPushButton {color:#65718A;font-size:12px;text-align:left;"
|
||||
"background:transparent;border:0;padding:4px 0;}"
|
||||
"QPushButton:hover {color:#4F63D9;}"
|
||||
"QPushButton:focus {border-bottom:1px solid #4F63D9;}")
|
||||
"QPushButton:focus {border-bottom:1px solid #4F63D9;}"
|
||||
)
|
||||
layout.addWidget(toggle)
|
||||
label = QLabel(receipt)
|
||||
@@ -3644,7 +3643,7 @@ class _ChatBubble(QWidget):
|
||||
Qt.TextInteractionFlag.TextSelectableByMouse
|
||||
| Qt.TextInteractionFlag.TextSelectableByKeyboard
|
||||
)
|
||||
label.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;"))
|
||||
label.setStyleSheet("color:#65718A;font-size:12px;")
|
||||
label.hide()
|
||||
layout.addWidget(label)
|
||||
self._inner.insertWidget(0, receipt)
|
||||
@@ -3689,7 +3688,7 @@ class _ChatBubble(QWidget):
|
||||
label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
label.setWordWrap(True)
|
||||
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
label.setStyleSheet(clinical_stylesheet("color:#BE4B58;background:#FEF3F2;border-radius:6px;padding:8px;"))
|
||||
label.setStyleSheet("color:#BE4B58;background:#FEF3F2;border-radius:6px;padding:8px;")
|
||||
self._inner.insertWidget(self._inner.indexOf(self.body), label)
|
||||
self._stream_failure_label = label
|
||||
label.setText(f"本次回复未完成\n{text}")
|
||||
@@ -4950,9 +4949,8 @@ class AiConsultDialog(QDialog):
|
||||
button.setObjectName("AiConsultChipButton")
|
||||
button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
task_key = QUICK_PROMPT_TASKS.get(label, "")
|
||||
button.clicked.connect(
|
||||
lambda _checked=False, text=prompt, task=task_key:
|
||||
lambda _checked=False, text=prompt, task=QUICK_PROMPT_TASKS.get(label, ""):
|
||||
self._ask(text, replace_active=True, task=task)
|
||||
)
|
||||
chips.addWidget(button, 1)
|
||||
|
||||
@@ -43,7 +43,6 @@ from doctor_workstation.services.app_update import (
|
||||
validate_installer_download_policy,
|
||||
validate_windows_installer,
|
||||
)
|
||||
from doctor_workstation.ui.design_system import clinical_stylesheet
|
||||
from doctor_workstation.ui.widgets import friendly_error, show_toast
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
@@ -130,11 +129,11 @@ class AppUpdateDialog(QDialog):
|
||||
|
||||
self.badge = QLabel("必须更新后才能继续使用" if offer.force else "发现新版本")
|
||||
self.badge.setObjectName("UpdateBadge")
|
||||
self.badge.setStyleSheet(clinical_stylesheet(
|
||||
self.badge.setStyleSheet(
|
||||
"color:#A9691D;background:#FFF5E6;border-radius:8px;padding:4px 10px;font-weight:600;"
|
||||
if offer.force
|
||||
else "color:#4F63D9;background:#EEF1FA;border-radius:8px;padding:4px 10px;font-weight:600;"
|
||||
))
|
||||
)
|
||||
root.addWidget(self.badge, 0, Qt.AlignmentFlag.AlignLeft)
|
||||
|
||||
self.headline = QLabel(title or "医生工作站有新版本")
|
||||
@@ -147,7 +146,7 @@ class AppUpdateDialog(QDialog):
|
||||
latest = offer.latest_version or "新版本"
|
||||
self.version_label = QLabel(f"当前版本 {current} → 最新版本 {latest}")
|
||||
self.version_label.setObjectName("UpdateVersionLabel")
|
||||
self.version_label.setStyleSheet(clinical_stylesheet("color:$ds_muted;"))
|
||||
self.version_label.setStyleSheet("color:#606163;")
|
||||
root.addWidget(self.version_label)
|
||||
|
||||
self.notes = QTextEdit()
|
||||
@@ -161,7 +160,7 @@ class AppUpdateDialog(QDialog):
|
||||
self.status_label = QLabel("")
|
||||
self.status_label.setObjectName("UpdateStatus")
|
||||
self.status_label.setWordWrap(True)
|
||||
self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;"))
|
||||
self.status_label.setStyleSheet("color:#1A1C1F;")
|
||||
self.status_label.hide()
|
||||
root.addWidget(self.status_label)
|
||||
|
||||
@@ -176,7 +175,7 @@ class AppUpdateDialog(QDialog):
|
||||
|
||||
self.progress_text = QLabel("")
|
||||
self.progress_text.setObjectName("UpdateProgressText")
|
||||
self.progress_text.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;"))
|
||||
self.progress_text.setStyleSheet("color:#606163;font-size:12px;")
|
||||
self.progress_text.hide()
|
||||
root.addWidget(self.progress_text)
|
||||
|
||||
@@ -226,7 +225,7 @@ class AppUpdateDialog(QDialog):
|
||||
def show_download_progress(self, received: int, total: int) -> None:
|
||||
self.progress.show()
|
||||
self.progress_text.show()
|
||||
self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;"))
|
||||
self.status_label.setStyleSheet("color:#1A1C1F;")
|
||||
self.status_label.setText("正在下载安装包…")
|
||||
self.status_label.show()
|
||||
if total > 0:
|
||||
@@ -238,7 +237,7 @@ class AppUpdateDialog(QDialog):
|
||||
self.progress_text.setText(_format_bytes(received))
|
||||
|
||||
def show_status(self, message: str, *, determinate: bool = False) -> None:
|
||||
self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;"))
|
||||
self.status_label.setStyleSheet("color:#1A1C1F;")
|
||||
self.status_label.setText(message)
|
||||
self.status_label.show()
|
||||
self.progress.show()
|
||||
@@ -252,7 +251,7 @@ class AppUpdateDialog(QDialog):
|
||||
def show_error(self, message: str) -> None:
|
||||
self._busy = False
|
||||
self.status_label.setText(message)
|
||||
self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_danger;"))
|
||||
self.status_label.setStyleSheet("color:#BE4B58;")
|
||||
self.status_label.show()
|
||||
self.progress.hide()
|
||||
self.progress_text.hide()
|
||||
|
||||
@@ -48,8 +48,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from ...core.appointment_modes import appointment_type_description, appointment_type_value
|
||||
from ...core.transcript_text import simplified_transcript
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..diagnosis_drawer import (
|
||||
DIAGNOSIS_QSS,
|
||||
CaseGrid,
|
||||
@@ -99,7 +97,6 @@ from .issued_prescription_ai import can_open_issued_ai, present_issued_prescript
|
||||
from .local_audio_queue import LocalAudioQueueDialog
|
||||
from .prescription_ai import can_open_diagnosis_ai_report, present_diagnosis_ai_report
|
||||
|
||||
|
||||
class _UploadProgressRelay(QObject):
|
||||
"""把后台线程中的分片上传进度转回界面线程(信号跨线程自动排队)。"""
|
||||
|
||||
@@ -1544,16 +1541,16 @@ class DiagnosisDialog(QDialog):
|
||||
"""上传本地回放时的进度条:按分片实时更新,医生能看到上传在进行、进行到哪。"""
|
||||
frame = QFrame()
|
||||
frame.setObjectName("DiagnosisVideoUploadProgress")
|
||||
frame.setStyleSheet(clinical_stylesheet(
|
||||
frame.setStyleSheet(
|
||||
"QFrame#DiagnosisVideoUploadProgress { background-color: #EEF1FA;"
|
||||
" border: 1px solid $ds_line_strong; border-radius: $ds_radius_control; }"
|
||||
"QFrame#DiagnosisVideoUploadProgress QLabel { color: $ds_accent_hover; background: transparent;"
|
||||
" border: 1px solid #C9D1F3; border-radius: 8px; }"
|
||||
"QFrame#DiagnosisVideoUploadProgress QLabel { color: #3347B8; background: transparent;"
|
||||
" font-size: 13px; font-weight: 500; }"
|
||||
"QFrame#DiagnosisVideoUploadProgress QProgressBar { background-color: #FFFFFF;"
|
||||
" border: 0; border-radius: 4px; min-height: 8px; max-height: 8px; }"
|
||||
"QFrame#DiagnosisVideoUploadProgress QProgressBar::chunk { background-color: #4F63D9;"
|
||||
" border-radius: 4px; }"
|
||||
))
|
||||
)
|
||||
row = QVBoxLayout(frame)
|
||||
row.setContentsMargins(12, 8, 12, 10)
|
||||
row.setSpacing(6)
|
||||
@@ -4034,8 +4031,7 @@ class DiagnosisDialog(QDialog):
|
||||
content = QPlainTextEdit(dialog)
|
||||
content.setObjectName("DiagnosisCallTranscriptText")
|
||||
content.setReadOnly(True)
|
||||
# Historical records keep their stored source; only the view is converted.
|
||||
content.setPlainText(simplified_transcript(transcript))
|
||||
content.setPlainText(transcript)
|
||||
layout.addWidget(content, 1)
|
||||
close_button = QPushButton("关闭")
|
||||
close_button.setProperty("variant", "primary")
|
||||
|
||||
@@ -21,8 +21,6 @@ from typing import Any
|
||||
|
||||
from PySide6.QtGui import QFont
|
||||
|
||||
from ..design_system import PALETTE
|
||||
|
||||
DARK: dict[str, str] = {
|
||||
# ground and cards
|
||||
"canvas": "#080D18",
|
||||
@@ -64,23 +62,23 @@ DARK: dict[str, str] = {
|
||||
}
|
||||
|
||||
LIGHT: dict[str, str] = {
|
||||
"canvas": PALETTE["canvas"],
|
||||
"canvas_soft": PALETTE["surface_alt"],
|
||||
"surface": PALETTE["surface"],
|
||||
"surface_2": PALETTE["surface_alt"],
|
||||
"raised": PALETTE["sidebar"],
|
||||
"line": PALETTE["line_strong"],
|
||||
"line_soft": PALETTE["line"],
|
||||
"heading": PALETTE["heading"],
|
||||
"text": PALETTE["text"],
|
||||
"muted": PALETTE["muted"],
|
||||
"faint": PALETTE["disabled"],
|
||||
"selected_text": PALETTE["heading"],
|
||||
"accent": PALETTE["accent"],
|
||||
"accent_text": PALETTE["accent_hover"],
|
||||
"accent_pressed": PALETTE["accent_pressed"],
|
||||
"selection": PALETTE["accent_soft"],
|
||||
"selection_line": PALETTE["focus"],
|
||||
"canvas": "#F1F5FC",
|
||||
"canvas_soft": "#E7EEFA",
|
||||
"surface": "#FFFFFF",
|
||||
"surface_2": "#F5F8FE",
|
||||
"raised": "#E8EFFA",
|
||||
"line": "#D5E1F2",
|
||||
"line_soft": "#E3EBF8",
|
||||
"heading": "#0A182E",
|
||||
"text": "#2A3C56",
|
||||
"muted": "#54697F",
|
||||
"faint": "#7A8DA3",
|
||||
"selected_text": "#0A182E",
|
||||
"accent": "#1A5FD0",
|
||||
"accent_text": "#124DAE",
|
||||
"accent_pressed": "#0E3F90",
|
||||
"selection": "#E8EFFA",
|
||||
"selection_line": "#AEC7EE",
|
||||
"qwen": "#0C89AC",
|
||||
"qwen_text": "#086C88",
|
||||
"qwen_dim": "#E2F5FA",
|
||||
|
||||
@@ -29,7 +29,6 @@ from ...services.local_audio_queue import (
|
||||
LocalAudioUploadManager,
|
||||
get_local_audio_upload_manager,
|
||||
)
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..widgets import run_async
|
||||
|
||||
_STATUS_LABELS = {
|
||||
@@ -175,7 +174,7 @@ class LocalAudioQueueDialog(QDialog):
|
||||
self.setModal(True)
|
||||
self.setMinimumSize(760, 480)
|
||||
self.resize(1160, 620)
|
||||
self.setStyleSheet(clinical_stylesheet(_LOCAL_AUDIO_QSS))
|
||||
self.setStyleSheet(_LOCAL_AUDIO_QSS)
|
||||
self._build_ui()
|
||||
|
||||
self.poll_timer = QTimer(self)
|
||||
|
||||
@@ -28,8 +28,8 @@ from PySide6.QtCore import (
|
||||
QDate,
|
||||
QEvent,
|
||||
QIODevice,
|
||||
QMarginsF,
|
||||
QModelIndex,
|
||||
QMarginsF,
|
||||
QObject,
|
||||
QPoint,
|
||||
QRectF,
|
||||
@@ -98,7 +98,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from .. import icons
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..diagnosis_terms import shared_terms
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..theme import main_window_target_rect
|
||||
@@ -117,9 +116,9 @@ from ..widgets import (
|
||||
)
|
||||
from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog
|
||||
|
||||
PRESCRIPTION_DRAWER_QSS = clinical_stylesheet(r"""
|
||||
PRESCRIPTION_DRAWER_QSS = r"""
|
||||
QFrame#PrescriptionDrawerSurface {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border-left: 1px solid #EDEDEE;
|
||||
font-size: 14px;
|
||||
@@ -146,7 +145,7 @@ QLabel#PrescriptionLockTag {
|
||||
color: #BE4B58;
|
||||
background-color: #FEF0F0;
|
||||
border: 1px solid #FDE2E2;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 4px;
|
||||
padding: 2px 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -176,7 +175,7 @@ QLabel#PrescriptionDrawerMode {
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 5px;
|
||||
padding: 4px 9px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -190,7 +189,7 @@ QPushButton#PrescriptionDrawerClose {
|
||||
color: #606163;
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-size: 22px;
|
||||
font-weight: 400;
|
||||
}
|
||||
@@ -209,12 +208,12 @@ QWidget#PrescriptionDrawerContent {
|
||||
QFrame#PrescriptionFormSection {
|
||||
background-color: #F7F7F7;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 10px;
|
||||
}
|
||||
QLabel#PrescriptionSectionTitle {
|
||||
color: #1A1C1F;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
font-weight: 500;
|
||||
}
|
||||
QLabel#PrescriptionSectionHint {
|
||||
color: #6A6B6D;
|
||||
@@ -243,7 +242,7 @@ QLabel#PrescriptionUsageAux {
|
||||
QFrame#PrescriptionRpToolbar {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 10px;
|
||||
}
|
||||
QFrame#PrescriptionRpMarker {
|
||||
background-color: #4F63D9;
|
||||
@@ -263,12 +262,12 @@ QLabel#PrescriptionRpLock {
|
||||
color: #BE4B58;
|
||||
background-color: #FEF3F2;
|
||||
border: 1px solid #FECDCA;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 5px;
|
||||
padding: 5px 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
QLabel#PrescriptionFormulaTag {
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 4px;
|
||||
padding: 3px 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -329,7 +328,7 @@ QFrame#PrescriptionDrawerSurface QDoubleSpinBox {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
padding: 0 11px;
|
||||
selection-background-color: #C9D1F3;
|
||||
selection-color: #1A1C1F; font-size: 14px;
|
||||
@@ -339,7 +338,7 @@ QFrame#PrescriptionDrawerSurface QComboBox {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
padding-left: 11px;
|
||||
padding-right: 28px;
|
||||
selection-background-color: #C9D1F3;
|
||||
@@ -380,7 +379,7 @@ QFrame#PrescriptionDatePicker {
|
||||
min-height: 32px;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
}
|
||||
QFrame#PrescriptionDatePicker:hover {
|
||||
border-color: #8B9AD9;
|
||||
@@ -447,7 +446,7 @@ QFrame#PrescriptionDrawerSurface QPushButton {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton:hover {
|
||||
@@ -469,7 +468,7 @@ QFrame#PrescriptionDrawerSurface QPushButton#PrescriptionDrawerClose {
|
||||
color: #606163;
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-size: 22px;
|
||||
font-weight: 400;
|
||||
}
|
||||
@@ -497,23 +496,23 @@ QFrame#PrescriptionDrawerSurface QPushButton[variant="primary"]:hover {
|
||||
border-color: #4156C4;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="success"] {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_line;
|
||||
color: #FFFFFF;
|
||||
background-color: #287B65;
|
||||
border-color: #287B65;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="success"]:hover {
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
background-color: #287B65;
|
||||
border-color: #287B65;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="warning"] {
|
||||
color: $ds_accent;
|
||||
color: #A9691D;
|
||||
background-color: #FFFFFF;
|
||||
border-color: $ds_accent;
|
||||
border-color: #A9691D;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="warning"]:hover {
|
||||
color: $ds_accent_hover;
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
color: #FFFFFF;
|
||||
background-color: #A9691D;
|
||||
border-color: #A9691D;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="secondary"] {
|
||||
color: #4F63D9;
|
||||
@@ -616,8 +615,7 @@ QFrame#PrescriptionDrawerSurface QFrame#MessageBanner[kind="danger"] {
|
||||
QFrame#PrescriptionDrawerSurface QFrame#MessageBanner[kind="danger"] QLabel {
|
||||
color: #BE4B58;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton:focus { border: 1px solid $ds_focus; }
|
||||
""")
|
||||
"""
|
||||
|
||||
_CHEVRON_PATH: Path | None = None
|
||||
|
||||
@@ -649,7 +647,7 @@ def _prescription_drawer_qss() -> str:
|
||||
|
||||
|
||||
def _prescription_calendar_qss() -> str:
|
||||
return clinical_stylesheet("""
|
||||
return """
|
||||
QCalendarWidget {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
@@ -674,13 +672,13 @@ QCalendarWidget QAbstractItemView:enabled {
|
||||
selection-color: #1A1C1F;
|
||||
outline: 0;
|
||||
}
|
||||
""")
|
||||
"""
|
||||
|
||||
|
||||
PRESCRIPTION_DIALOG_QSS = clinical_stylesheet("""
|
||||
PRESCRIPTION_DIALOG_QSS = """
|
||||
QDialog#PrescriptionDialogSurface {
|
||||
color: #1A1C1F;
|
||||
background-color: $ds_canvas;
|
||||
background-color: #F7F7F7;
|
||||
font-size: 14px;
|
||||
}
|
||||
QDialog#PrescriptionDialogSurface QLabel {
|
||||
@@ -742,7 +740,7 @@ QDialog#PrescriptionDialogSurface QTextBrowser {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
selection-background-color: #EEF1FA;
|
||||
selection-color: #1A1C1F; font-size: 14px;
|
||||
}
|
||||
@@ -770,7 +768,7 @@ QDialog#PrescriptionDialogSurface QPushButton {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#PrescriptionDialogSurface QPushButton:hover {
|
||||
@@ -800,7 +798,7 @@ QDialog#PrescriptionDialogSurface QPushButton:disabled {
|
||||
QDialog#PrescriptionDialogSurface QTabWidget::pane {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 9px;
|
||||
top: -1px;
|
||||
}
|
||||
QDialog#PrescriptionDialogSurface QTabBar::tab {
|
||||
@@ -854,8 +852,7 @@ QDialog#PrescriptionDialogSurface QScrollBar::add-line:vertical,
|
||||
QDialog#PrescriptionDialogSurface QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QDialog#PrescriptionDialogSurface QPushButton:focus { border: 1px solid $ds_focus; }
|
||||
""")
|
||||
"""
|
||||
|
||||
|
||||
def _apply_prescription_dialog_style(dialog: QDialog) -> None:
|
||||
@@ -1534,9 +1531,9 @@ class RemoteMedicineComboBox(QComboBox):
|
||||
popup = self._completer.popup()
|
||||
popup.setItemDelegate(_MedicineSuggestionDelegate(popup))
|
||||
popup.setStyleSheet(
|
||||
clinical_stylesheet("QListView { background-color: #FFFFFF; border: 1px solid #E4E7ED; border-radius: 6px;"
|
||||
"QListView { background-color: #FFFFFF; border: 1px solid #E4E7ED; border-radius: 6px;"
|
||||
" padding: 4px 0; font-size: 14px; outline: 0; }"
|
||||
"QListView::item:selected, QListView::item:hover { background-color: #F5F7FA; }")
|
||||
"QListView::item:selected, QListView::item:hover { background-color: #F5F7FA; }"
|
||||
)
|
||||
self.lineEdit().setCompleter(self._completer)
|
||||
self.lineEdit().installEventFilter(self)
|
||||
@@ -5295,8 +5292,8 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.preview.setObjectName("PrescriptionPaperPreview")
|
||||
self.preview.setOpenExternalLinks(False)
|
||||
self.preview.setStyleSheet(
|
||||
clinical_stylesheet("QTextBrowser#PrescriptionPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}")
|
||||
"QTextBrowser#PrescriptionPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}"
|
||||
)
|
||||
self.preview.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
self.preview.setDocument(self.document)
|
||||
@@ -5304,8 +5301,8 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.user_preview.setObjectName("PrescriptionUserPaperPreview")
|
||||
self.user_preview.setOpenExternalLinks(False)
|
||||
self.user_preview.setStyleSheet(
|
||||
clinical_stylesheet("QTextBrowser#PrescriptionUserPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}")
|
||||
"QTextBrowser#PrescriptionUserPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}"
|
||||
)
|
||||
self.user_preview.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
self.user_preview.setDocument(self.user_document)
|
||||
@@ -5323,8 +5320,8 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.case_preview.setObjectName("CaseRecordPaperPreview")
|
||||
self.case_preview.setOpenExternalLinks(False)
|
||||
self.case_preview.setStyleSheet(
|
||||
clinical_stylesheet("QTextBrowser#CaseRecordPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}")
|
||||
"QTextBrowser#CaseRecordPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}"
|
||||
)
|
||||
self.case_preview.setDocument(self.case_document)
|
||||
case_index = self.tabs.addTab(self.case_preview, "详细病历")
|
||||
|
||||
@@ -26,7 +26,6 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..report_provenance import report_provenance_lines
|
||||
from ..theme import apply_reading_rhythm
|
||||
from ..widgets import (
|
||||
@@ -170,10 +169,10 @@ def diagnosis_ai_task(prompt: str) -> str:
|
||||
return "custom"
|
||||
|
||||
|
||||
PRESCRIPTION_AI_QSS = clinical_stylesheet("""
|
||||
PRESCRIPTION_AI_QSS = """
|
||||
QDialog#PrescriptionAiDialog {
|
||||
color: $ds_text;
|
||||
background-color: $ds_canvas;
|
||||
color: #1A1C1F;
|
||||
background-color: #F7F7F7;
|
||||
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -183,7 +182,7 @@ QDialog#PrescriptionAiDialog QPushButton {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#PrescriptionAiDialog QPushButton:hover {
|
||||
@@ -225,7 +224,7 @@ QLabel#PrescriptionAiSubtitle {
|
||||
QFrame#PrescriptionAiSnapshot {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 10px;
|
||||
}
|
||||
QLabel#PrescriptionAiSnapshotLabel {
|
||||
color: #1A1C1F;
|
||||
@@ -233,20 +232,20 @@ QLabel#PrescriptionAiSnapshotLabel {
|
||||
font-weight: 600;
|
||||
}
|
||||
QLabel#PrescriptionAiSnapshotBody {
|
||||
color: $ds_text;
|
||||
font-size: 14px;
|
||||
color: #1A1C1F;
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
QFrame#PrescriptionAiSummary {
|
||||
background-color: $ds_accent_soft;
|
||||
background-color: #F0F0F0;
|
||||
border: 0;
|
||||
border-left: 3px solid #4F63D9;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 0 9px 9px 0;
|
||||
}
|
||||
QFrame#PrescriptionAiCaution {
|
||||
background-color: #FFF9EE;
|
||||
border: 1px solid #F3DFB5;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QLabel#PrescriptionAiSectionTitle {
|
||||
color: #1A1C1F;
|
||||
@@ -254,17 +253,17 @@ QLabel#PrescriptionAiSectionTitle {
|
||||
font-weight: 600;
|
||||
}
|
||||
QLabel#PrescriptionAiBody {
|
||||
color: $ds_text;
|
||||
font-size: 14px;
|
||||
color: #1A1C1F;
|
||||
font-size: 13px;
|
||||
line-height: 1.75;
|
||||
}
|
||||
QTextBrowser#PrescriptionAiAnswer {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
padding: 16px 18px;
|
||||
selection-color: $ds_text;
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
selection-color: #1A1C1F;
|
||||
selection-background-color: #EEF1FA;
|
||||
}
|
||||
QLabel#PrescriptionAiMuted {
|
||||
@@ -280,7 +279,7 @@ QFrame#PrescriptionAiMeta {
|
||||
QDialog#PrescriptionAiDialog QTabWidget::pane {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 10px;
|
||||
top: -1px;
|
||||
}
|
||||
QDialog#PrescriptionAiDialog QTabBar::tab {
|
||||
@@ -310,7 +309,7 @@ QDialog#PrescriptionAiDialog QTextEdit {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
selection-background-color: #EEF1FA;
|
||||
}
|
||||
@@ -331,12 +330,10 @@ QDialog#PrescriptionAiDialog QScrollBar::add-line:vertical,
|
||||
QDialog#PrescriptionAiDialog QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QDialog#PrescriptionAiDialog QPushButton:focus { border: 1px solid $ds_focus; }
|
||||
QDialog#PrescriptionAiDialog QPushButton:disabled { color: $ds_disabled; background-color: $ds_disabled_surface; border-color: $ds_line; }
|
||||
""")
|
||||
"""
|
||||
|
||||
_AI_ANSWER_DOCUMENT_CSS = clinical_stylesheet(
|
||||
"body { color:$ds_text; font-size:14px; line-height:1.72; } "
|
||||
_AI_ANSWER_DOCUMENT_CSS = (
|
||||
"body { color:#1A1C1F; font-size:14px; line-height:1.72; } "
|
||||
"h1 { color:#1A1C1F; font-size:20px; margin:14px 0 8px; line-height:1.4; } "
|
||||
"h2 { color:#1A1C1F; font-size:17px; margin:14px 0 7px; line-height:1.42; } "
|
||||
"h3,h4 { color:#1A1C1F; font-size:15px; margin:12px 0 6px; line-height:1.45; } "
|
||||
@@ -804,7 +801,7 @@ class PrescriptionAiReportDialog(QDialog):
|
||||
self.report_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
self.host = QWidget()
|
||||
self.host_layout = QVBoxLayout(self.host)
|
||||
self.host_layout.setContentsMargins(18, 14, 20, 16)
|
||||
self.host_layout.setContentsMargins(4, 4, 12, 8)
|
||||
self.host_layout.setSpacing(12)
|
||||
self.report_scroll.setWidget(self.host)
|
||||
self.tabs.widget(0).layout().addWidget(self.report_scroll)
|
||||
@@ -1458,7 +1455,7 @@ class PrescriptionAiReportDialog(QDialog):
|
||||
label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
label.setWordWrap(True)
|
||||
label.setStyleSheet(clinical_stylesheet("color: $ds_muted; font-size: 12px; padding: 10px 14px; background: $ds_surface_alt; border: 1px solid $ds_line; border-radius: $ds_radius_control;"))
|
||||
label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;")
|
||||
self.host_layout.addWidget(label)
|
||||
|
||||
def reject(self) -> None:
|
||||
|
||||
@@ -8,7 +8,6 @@ from PySide6.QtCore import QObject, QSize, Qt, Signal
|
||||
from PySide6.QtWidgets import QApplication, QPushButton, QWidget
|
||||
|
||||
from . import icons
|
||||
from .design_system import PALETTE, clinical_stylesheet
|
||||
|
||||
|
||||
class FilterDisclosure(QObject):
|
||||
@@ -36,17 +35,17 @@ class FilterDisclosure(QObject):
|
||||
self.button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.button.setFixedHeight(32)
|
||||
self.button.setIconSize(QSize(14, 14))
|
||||
self.button.setStyleSheet(clinical_stylesheet("""
|
||||
self.button.setStyleSheet("""
|
||||
QPushButton#FilterDisclosureButton {
|
||||
color: #1769E8; background: #FFFFFF; border: 1px solid #DBE5F2;
|
||||
border-radius: $ds_radius_control; padding: 0 11px; min-height: 30px; max-height: 30px;
|
||||
border-radius: 6px; padding: 0 11px; min-height: 30px; max-height: 30px;
|
||||
min-width: 92px; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
QPushButton#FilterDisclosureButton:hover { background: $ds_canvas; border-color: $ds_line_strong; }
|
||||
QPushButton#FilterDisclosureButton:checked { background: $ds_accent_soft; border-color: $ds_line_strong; }
|
||||
QPushButton#FilterDisclosureButton:focus { border-color: $ds_focus; }
|
||||
QPushButton#FilterDisclosureButton:disabled { color: $ds_disabled; border-color: $ds_line; }
|
||||
"""))
|
||||
QPushButton#FilterDisclosureButton:hover { background: #F3F7FD; border-color: #ADC8F2; }
|
||||
QPushButton#FilterDisclosureButton:checked { background: #EAF2FF; border-color: #ADC8F2; }
|
||||
QPushButton#FilterDisclosureButton:focus { border-color: #1769E8; }
|
||||
QPushButton#FilterDisclosureButton:disabled { color: #8B97A8; border-color: #E3E9F1; }
|
||||
""")
|
||||
self.button.toggled.connect(self.set_expanded)
|
||||
self._apply()
|
||||
|
||||
@@ -79,4 +78,4 @@ class FilterDisclosure(QObject):
|
||||
self.button.setAccessibleName(label)
|
||||
self.button.setAccessibleDescription("显示或收起检索条件和统计信息;收起保留当前筛选条件")
|
||||
self.button.setToolTip("收起保留当前筛选条件" if self._expanded else "展开检索条件和统计信息,当前筛选条件保持不变")
|
||||
self.button.setIcon(icons.icon("chevron_up" if self._expanded else "chevron_down", PALETTE["accent"], 14))
|
||||
self.button.setIcon(icons.icon("chevron_up" if self._expanded else "chevron_down", "#1769E8", 14))
|
||||
|
||||
@@ -16,7 +16,6 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .widgets import first_value, get_value, page_items, page_total, run_async
|
||||
|
||||
|
||||
@@ -55,16 +54,16 @@ class InfiniteList(QWidget):
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(12, 0, 12, 0)
|
||||
self.summary_label = QLabel("", self)
|
||||
self.summary_label.setStyleSheet(clinical_stylesheet(
|
||||
self.summary_label.setStyleSheet(
|
||||
"color: #5D6B80; font-size: 12px; background: transparent;"
|
||||
))
|
||||
)
|
||||
layout.addWidget(self.summary_label)
|
||||
layout.addStretch(1)
|
||||
self.retry_button = QPushButton("加载失败,点击重试", self)
|
||||
self.retry_button.setFlat(True)
|
||||
self.retry_button.setStyleSheet(clinical_stylesheet(
|
||||
self.retry_button.setStyleSheet(
|
||||
"color: #1769E8; font-size: 12px; padding: 0 4px; border: none; background: transparent; min-height: 20px; max-height: 20px; min-width: 0;"
|
||||
))
|
||||
)
|
||||
self.retry_button.hide()
|
||||
self.retry_button.clicked.connect(self.retry)
|
||||
layout.addWidget(self.retry_button)
|
||||
|
||||
@@ -5,21 +5,26 @@ from __future__ import annotations
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QEvent, QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal
|
||||
from PySide6.QtCore import QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal
|
||||
from PySide6.QtGui import (
|
||||
QBrush,
|
||||
QColor,
|
||||
QFont,
|
||||
QIcon,
|
||||
QLinearGradient,
|
||||
QPainter,
|
||||
QPainterPath,
|
||||
QPen,
|
||||
QPixmap,
|
||||
QPolygonF,
|
||||
QRadialGradient,
|
||||
QResizeEvent,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QCheckBox,
|
||||
QFrame,
|
||||
QGraphicsDropShadowEffect,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLayout,
|
||||
@@ -40,7 +45,6 @@ from doctor_workstation import __version__
|
||||
from doctor_workstation.resources import app_icon_path, brand_lockup_path
|
||||
|
||||
from . import icons
|
||||
from .design_system import PALETTE, clinical_stylesheet
|
||||
from .widgets import BusyOverlay, MessageBanner, friendly_error, invoke, run_async
|
||||
|
||||
|
||||
@@ -123,7 +127,7 @@ def _round_pen(color: QColor | str, width: float) -> QPen:
|
||||
|
||||
|
||||
class _BrandPanel(QWidget):
|
||||
"""A flat, readable introduction to the clinician's daily workflow."""
|
||||
"""The quiet medical illustration and copy from the supplied login artwork."""
|
||||
|
||||
def __init__(self, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
@@ -133,76 +137,228 @@ class _BrandPanel(QWidget):
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
|
||||
self._brand_lockup = QPixmap(str(brand_lockup_path()))
|
||||
|
||||
@staticmethod
|
||||
def _draw_cube(painter: QPainter, center: QPointF, size: float, kind: str) -> None:
|
||||
x, y = center.x(), center.y()
|
||||
top = QPolygonF(
|
||||
[
|
||||
QPointF(x, y - size * 0.58),
|
||||
QPointF(x + size * 0.48, y - size * 0.34),
|
||||
QPointF(x, y - size * 0.10),
|
||||
QPointF(x - size * 0.48, y - size * 0.34),
|
||||
]
|
||||
)
|
||||
left = QPolygonF(
|
||||
[
|
||||
QPointF(x - size * 0.48, y - size * 0.34),
|
||||
QPointF(x, y - size * 0.10),
|
||||
QPointF(x, y + size * 0.48),
|
||||
QPointF(x - size * 0.48, y + size * 0.24),
|
||||
]
|
||||
)
|
||||
right = QPolygonF(
|
||||
[
|
||||
QPointF(x, y - size * 0.10),
|
||||
QPointF(x + size * 0.48, y - size * 0.34),
|
||||
QPointF(x + size * 0.48, y + size * 0.24),
|
||||
QPointF(x, y + size * 0.48),
|
||||
]
|
||||
)
|
||||
painter.setPen(QPen(QColor(185, 196, 247, 205), 1.2))
|
||||
painter.setBrush(QColor(235, 239, 255, 218))
|
||||
painter.drawPolygon(top)
|
||||
painter.setBrush(QColor(210, 218, 255, 205))
|
||||
painter.drawPolygon(left)
|
||||
painter.setBrush(QColor(224, 230, 255, 220))
|
||||
painter.drawPolygon(right)
|
||||
painter.setPen(_round_pen(QColor(137, 154, 248, 135), 2.2))
|
||||
if kind == "plus":
|
||||
painter.drawLine(
|
||||
QPointF(x - size * 0.12, y + size * 0.05),
|
||||
QPointF(x + size * 0.15, y - size * 0.02),
|
||||
)
|
||||
painter.drawLine(
|
||||
QPointF(x + size * 0.02, y - size * 0.13),
|
||||
QPointF(x + size * 0.02, y + size * 0.17),
|
||||
)
|
||||
else:
|
||||
shield = QPainterPath(QPointF(x, y - size * 0.16))
|
||||
shield.lineTo(x + size * 0.15, y - size * 0.08)
|
||||
shield.lineTo(x + size * 0.10, y + size * 0.17)
|
||||
shield.lineTo(x, y + size * 0.26)
|
||||
shield.lineTo(x - size * 0.10, y + size * 0.17)
|
||||
shield.lineTo(x - size * 0.15, y - size * 0.08)
|
||||
shield.closeSubpath()
|
||||
painter.drawPath(shield)
|
||||
|
||||
def _draw_illustration(
|
||||
self, painter: QPainter, width: float, height: float
|
||||
) -> None:
|
||||
ox = max(250.0, width - 500.0)
|
||||
oy = max(365.0, height - 500.0)
|
||||
|
||||
glow = QRadialGradient(QPointF(width - 170, oy + 230), 280)
|
||||
glow.setColorAt(0.0, QColor(102, 120, 255, 62))
|
||||
glow.setColorAt(1.0, QColor(102, 120, 255, 0))
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(glow)
|
||||
painter.drawEllipse(QPointF(width - 170, oy + 230), 280, 280)
|
||||
|
||||
painter.setPen(QPen(QColor(166, 180, 241, 78), 1))
|
||||
for offset in (0, 72, 144):
|
||||
painter.drawLine(
|
||||
QPointF(ox - 80, oy + 280 + offset),
|
||||
QPointF(width + 20, oy + 170 + offset),
|
||||
)
|
||||
painter.drawLine(QPointF(ox + 10, oy + 400), QPointF(ox + 10, oy + 80))
|
||||
painter.drawLine(QPointF(ox + 170, oy + 430), QPointF(ox + 170, oy + 35))
|
||||
|
||||
base = QRectF(ox + 80, oy + 365, 430, 88)
|
||||
base_gradient = QLinearGradient(base.topLeft(), base.bottomRight())
|
||||
base_gradient.setColorAt(0.0, QColor(246, 248, 255, 228))
|
||||
base_gradient.setColorAt(1.0, QColor(186, 199, 255, 184))
|
||||
painter.setBrush(base_gradient)
|
||||
painter.setPen(QPen(QColor(166, 181, 248, 158), 1))
|
||||
painter.drawEllipse(base)
|
||||
painter.setBrush(QColor(249, 250, 255, 225))
|
||||
painter.drawEllipse(QRectF(base.x() + 42, base.y() - 12, base.width() - 84, 70))
|
||||
|
||||
painter.save()
|
||||
painter.translate(35, 40)
|
||||
screen = QPolygonF(
|
||||
[
|
||||
QPointF(ox + 130, oy + 60),
|
||||
QPointF(ox + 435, oy + 100),
|
||||
QPointF(ox + 435, oy + 365),
|
||||
QPointF(ox + 130, oy + 310),
|
||||
]
|
||||
)
|
||||
painter.setBrush(QColor(218, 225, 255, 205))
|
||||
painter.setPen(QPen(QColor(145, 163, 242, 170), 1.3))
|
||||
painter.drawPolygon(screen)
|
||||
inner = QPolygonF(
|
||||
[
|
||||
QPointF(ox + 141, oy + 80),
|
||||
QPointF(ox + 425, oy + 117),
|
||||
QPointF(ox + 425, oy + 345),
|
||||
QPointF(ox + 141, oy + 295),
|
||||
]
|
||||
)
|
||||
painter.setBrush(QColor(255, 255, 255, 225))
|
||||
painter.drawPolygon(inner)
|
||||
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(174, 189, 252, 180))
|
||||
painter.drawRoundedRect(QRectF(ox + 148, oy + 89, 270, 15), 7, 7)
|
||||
for dot_x in (156, 173, 190):
|
||||
painter.setBrush(QColor(255, 255, 255, 200))
|
||||
painter.drawEllipse(QPointF(ox + dot_x, oy + 96.5), 3.5, 3.5)
|
||||
|
||||
cards = (
|
||||
QRectF(ox + 150, oy + 135, 82, 80),
|
||||
QRectF(ox + 241, oy + 142, 72, 73),
|
||||
QRectF(ox + 322, oy + 151, 95, 72),
|
||||
QRectF(ox + 151, oy + 232, 264, 50),
|
||||
QRectF(ox + 151, oy + 291, 264, 42),
|
||||
)
|
||||
painter.setPen(QPen(QColor(188, 199, 246, 160), 1))
|
||||
painter.setBrush(QColor(249, 250, 255, 228))
|
||||
for card in cards:
|
||||
painter.drawRoundedRect(card, 7, 7)
|
||||
painter.setPen(_round_pen(QColor(117, 137, 236, 165), 4))
|
||||
for idx, bar_height in enumerate((20, 36, 51)):
|
||||
x = ox + 164 + idx * 17
|
||||
painter.drawLine(QPointF(x, oy + 200), QPointF(x, oy + 200 - bar_height))
|
||||
painter.setBrush(QColor(112, 132, 235, 160))
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.drawEllipse(QPointF(ox + 277, oy + 167), 10, 10)
|
||||
painter.drawRoundedRect(QRectF(ox + 259, oy + 180, 36, 20), 10, 10)
|
||||
painter.setPen(_round_pen(QColor(137, 153, 235, 150), 5))
|
||||
for y, length in ((170, 54), (186, 42), (249, 89), (307, 72)):
|
||||
painter.drawLine(
|
||||
QPointF(ox + 340, oy + y), QPointF(ox + 340 + length, oy + y + 5)
|
||||
)
|
||||
|
||||
self._draw_cube(painter, QPointF(ox + 352, oy - 25), 76, "plus")
|
||||
self._draw_cube(painter, QPointF(ox - 8, oy + 210), 76, "shield")
|
||||
painter.restore()
|
||||
|
||||
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt API
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
bounds = QRectF(self.rect()).adjusted(1, 1, -1, -1)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["sidebar"]))
|
||||
painter.drawRoundedRect(bounds, 20, 20)
|
||||
left = 36.0
|
||||
width = max(240.0, self.width() - 72.0)
|
||||
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing)
|
||||
bounds = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
background = QLinearGradient(bounds.topLeft(), bounds.bottomRight())
|
||||
background.setColorAt(0.0, QColor("#FFFFFF"))
|
||||
background.setColorAt(0.7, QColor("#FFFFFF"))
|
||||
background.setColorAt(1.0, QColor("#F7F7F7"))
|
||||
painter.setBrush(background)
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1))
|
||||
painter.drawRoundedRect(bounds, 24, 24)
|
||||
|
||||
width, height = float(self.width()), float(self.height())
|
||||
self._draw_illustration(painter, width, height)
|
||||
|
||||
left = 64.0 if width >= 620 else 38.0
|
||||
if not self._brand_lockup.isNull():
|
||||
brand = self._brand_lockup.scaled(
|
||||
226, 58, Qt.AspectRatioMode.KeepAspectRatio,
|
||||
Qt.TransformationMode.SmoothTransformation,
|
||||
logo_width = 180.0
|
||||
logo_height = logo_width * (
|
||||
self._brand_lockup.height() / self._brand_lockup.width()
|
||||
)
|
||||
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
|
||||
painter.drawPixmap(
|
||||
QRectF(left, 24, logo_width, logo_height),
|
||||
self._brand_lockup,
|
||||
QRectF(self._brand_lockup.rect()),
|
||||
)
|
||||
painter.drawPixmap(QPointF(left, 36), brand)
|
||||
else:
|
||||
painter.setFont(_font(22, QFont.Weight.DemiBold))
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.drawText(QPointF(left, 70), "甄养堂 · 医生工作站")
|
||||
|
||||
heading_y = max(158.0, min(218.0, self.height() * .27))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setFont(_font(13, QFont.Weight.Medium))
|
||||
painter.drawText(QPointF(left, heading_y - 36), "医 生 工 作 台")
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.setFont(_font(30, QFont.Weight.DemiBold))
|
||||
painter.drawText(QPointF(left, heading_y), "让诊疗有序,")
|
||||
painter.drawText(QPointF(left, heading_y + 44), "让沟通更专注。")
|
||||
painter.setFont(_font(14))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.drawText(QPointF(left, heading_y + 82), "从接诊、病历到处方,在一个工作台完成。")
|
||||
tag_rect = QRectF(left, 238, 119, 40)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor("#EEF1FA"))
|
||||
painter.drawRoundedRect(tag_rect, 11, 11)
|
||||
painter.setFont(_font(17, QFont.Weight.Medium))
|
||||
painter.setPen(QColor("#4F63D9"))
|
||||
painter.drawText(tag_rect, Qt.AlignmentFlag.AlignCenter, "医生工作站")
|
||||
|
||||
row_y = heading_y + 122
|
||||
for index, (title, detail) in enumerate((
|
||||
("今日接诊", "快速找到待接诊患者与预约安排"),
|
||||
("诊疗记录", "病历、随访与面诊资料集中查看"),
|
||||
("处方协作", "开方与审核流程清晰衔接"),
|
||||
), start=1):
|
||||
row = QRectF(left, row_y, width, 66)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["surface"]))
|
||||
painter.drawRoundedRect(row, 12, 12)
|
||||
painter.setFont(_font(13, QFont.Weight.DemiBold))
|
||||
painter.setPen(QColor(PALETTE["accent"]))
|
||||
painter.drawText(QRectF(left + 16, row_y, 28, 66), Qt.AlignmentFlag.AlignCenter, f"0{index}")
|
||||
painter.setFont(_font(15, QFont.Weight.Medium))
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.drawText(QPointF(left + 58, row_y + 27), title)
|
||||
painter.setFont(_font(12))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.drawText(QPointF(left + 58, row_y + 47), detail)
|
||||
row_y += 78
|
||||
if self.height() > row_y + 50:
|
||||
painter.setFont(_font(12))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.drawText(QPointF(left, self.height() - 28), "仅供获授权的医疗人员使用")
|
||||
painter.end()
|
||||
copy_left = left + 4
|
||||
painter.setFont(_font(48, QFont.Weight.Medium))
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
painter.drawText(QPointF(copy_left, 354), "把诊间工作,")
|
||||
painter.drawText(QPointF(copy_left, 424), "留在一个")
|
||||
prefix_width = painter.fontMetrics().horizontalAdvance("留在一个")
|
||||
highlight = QLinearGradient(
|
||||
copy_left + prefix_width,
|
||||
0,
|
||||
copy_left + prefix_width + 264,
|
||||
0,
|
||||
)
|
||||
highlight.setColorAt(0.0, QColor("#4F63D9"))
|
||||
highlight.setColorAt(1.0, QColor("#4F63D9"))
|
||||
painter.setPen(QPen(QBrush(highlight), 1))
|
||||
painter.drawText(QPointF(copy_left + prefix_width, 424), "安静的界面里")
|
||||
suffix_x = (
|
||||
copy_left
|
||||
+ prefix_width
|
||||
+ painter.fontMetrics().horizontalAdvance("安静的界面里")
|
||||
)
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
painter.drawText(QPointF(suffix_x, 424), "。")
|
||||
|
||||
body_left = left + 6
|
||||
painter.setFont(_font(20))
|
||||
painter.setPen(QColor("#606163"))
|
||||
painter.drawText(
|
||||
QPointF(body_left, 492), "接诊、问诊、患者与处方信息统一呈现,"
|
||||
)
|
||||
painter.drawText(QPointF(body_left, 525), "帮助医生专注于每一次沟通。")
|
||||
|
||||
class _PasswordField(QFrame):
|
||||
"""Keep the grouped password control visibly focused for keyboard users."""
|
||||
|
||||
def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
|
||||
if event.type() in (QEvent.Type.FocusIn, QEvent.Type.FocusOut):
|
||||
self.setProperty("focused", event.type() == QEvent.Type.FocusIn)
|
||||
self.style().unpolish(self)
|
||||
self.style().polish(self)
|
||||
self.update()
|
||||
return super().eventFilter(watched, event)
|
||||
painter.setFont(_font(16))
|
||||
painter.setPen(QColor("#6A6B6D"))
|
||||
painter.drawText(
|
||||
QPointF(body_left, height - 85), "本工作站仅供获授权的医疗人员使用"
|
||||
)
|
||||
painter.drawText(QPointF(body_left, height - 59), "请勿在公共设备保存账号信息")
|
||||
|
||||
|
||||
class _RevealButton(QToolButton):
|
||||
@@ -236,8 +392,8 @@ class _ServerButton(QPushButton):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
rect = QRectF(self.rect()).adjusted(0.75, 0.75, -0.75, -0.75)
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"] if self.underMouse() else PALETTE["surface"]))
|
||||
painter.setPen(QPen(QColor(PALETTE["focus"] if self.hasFocus() else PALETTE["line_strong"]), 1))
|
||||
painter.setBrush(QColor("#FFFFFF") if self.underMouse() else QColor("#FFFFFF"))
|
||||
painter.setPen(QPen(QColor("#E4E4E5"), 1.5))
|
||||
painter.drawRoundedRect(rect, 12, 12)
|
||||
color = QColor("#1A1C1F" if self.isEnabled() else "#8E8F90")
|
||||
painter.setPen(_round_pen("#6A6B6D", 1.8))
|
||||
@@ -380,7 +536,7 @@ class LoginWindow(QMainWindow):
|
||||
border: 1px solid #E4E4E5;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QFrame#PasswordField[focused="true"] { border-color: #8B9AD9; }
|
||||
QFrame#PasswordField:focus-within { border-color: #8B9AD9; }
|
||||
QFrame#LoginCard QCheckBox {
|
||||
color: #606163;
|
||||
spacing: 13px;
|
||||
@@ -450,9 +606,6 @@ class LoginWindow(QMainWindow):
|
||||
self.login_root.addWidget(self.brand_panel, 60)
|
||||
self.login_root.addWidget(self._build_login_area(), 40)
|
||||
self._restore_settings()
|
||||
for widget in (canvas, *canvas.findChildren(QWidget)):
|
||||
if widget.styleSheet():
|
||||
widget.setStyleSheet(clinical_stylesheet(widget.styleSheet()))
|
||||
|
||||
def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt API
|
||||
"""Preserve the reference composition while remaining usable on small screens."""
|
||||
@@ -472,15 +625,18 @@ class LoginWindow(QMainWindow):
|
||||
# Keep the form fully visible when the 60/40 desktop split would
|
||||
# otherwise crop its fixed-width card. Small windows focus on login.
|
||||
self.brand_panel.setVisible(width >= 1120)
|
||||
compact_height = event.size().height() < 720
|
||||
self.card.setMinimumHeight(580 if compact_height else 620)
|
||||
self.login_area_layout.setContentsMargins(
|
||||
0, 12 if compact_height else min(104, max(24, (event.size().height() - 694) // 2)), 0, 12
|
||||
0, min(104, max(24, (event.size().height() - 694) // 2)), 0, 12
|
||||
)
|
||||
super().resizeEvent(event)
|
||||
|
||||
def _build_brand_panel(self) -> QWidget:
|
||||
panel = _BrandPanel()
|
||||
shadow = QGraphicsDropShadowEffect(panel)
|
||||
shadow.setBlurRadius(32)
|
||||
shadow.setOffset(0, 10)
|
||||
shadow.setColor(QColor(67, 82, 154, 18))
|
||||
panel.setGraphicsEffect(shadow)
|
||||
return panel
|
||||
|
||||
def _build_login_area(self) -> QWidget:
|
||||
@@ -504,6 +660,11 @@ class LoginWindow(QMainWindow):
|
||||
self.card.setFixedWidth(480)
|
||||
self.card.setMinimumHeight(620)
|
||||
self.card.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum)
|
||||
card_shadow = QGraphicsDropShadowEffect(self.card)
|
||||
card_shadow.setBlurRadius(38)
|
||||
card_shadow.setOffset(0, 16)
|
||||
card_shadow.setColor(QColor(59, 77, 139, 24))
|
||||
self.card.setGraphicsEffect(card_shadow)
|
||||
card_layout = QVBoxLayout(self.card)
|
||||
card_layout.setSizeConstraint(QLayout.SizeConstraint.SetDefaultConstraint)
|
||||
card_layout.setContentsMargins(47, 42, 47, 26)
|
||||
@@ -512,13 +673,13 @@ class LoginWindow(QMainWindow):
|
||||
|
||||
title = QLabel("欢迎回来")
|
||||
title.setObjectName("LoginTitle")
|
||||
title.setStyleSheet("color:#1A1C1F; font-size:26px; font-weight:600;")
|
||||
title.setStyleSheet("color:#1A1C1F; font-size:30px; font-weight:500;")
|
||||
title.setContentsMargins(1, -3, 0, 3)
|
||||
title.setFixedHeight(46)
|
||||
card_layout.addWidget(title)
|
||||
subtitle = QLabel("使用医生账号登录工作站")
|
||||
subtitle.setProperty("role", "muted")
|
||||
subtitle.setStyleSheet("color:#606163; font-size:15px;")
|
||||
subtitle.setStyleSheet("color:#606163; font-size:18px;")
|
||||
subtitle.setContentsMargins(1, 8, 0, 0)
|
||||
subtitle.setFixedHeight(27)
|
||||
card_layout.addWidget(subtitle)
|
||||
@@ -549,7 +710,7 @@ class LoginWindow(QMainWindow):
|
||||
password_label.setFixedHeight(24)
|
||||
card_layout.addWidget(password_label)
|
||||
card_layout.addSpacing(11)
|
||||
password_field = _PasswordField()
|
||||
password_field = QFrame()
|
||||
password_field.setObjectName("PasswordField")
|
||||
password_field.setFixedHeight(54)
|
||||
password_row = QHBoxLayout(password_field)
|
||||
@@ -560,7 +721,6 @@ class LoginWindow(QMainWindow):
|
||||
self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self.password_edit.setPlaceholderText("请输入密码")
|
||||
self.password_edit.setAccessibleName("登录密码")
|
||||
self.password_edit.installEventFilter(password_field)
|
||||
self.password_edit.setTextMargins(0, -2, 0, 2)
|
||||
self.password_edit.returnPressed.connect(self.submit)
|
||||
password_row.addWidget(self.password_edit, 1)
|
||||
@@ -570,7 +730,6 @@ class LoginWindow(QMainWindow):
|
||||
self.reveal_button.setCheckable(True)
|
||||
self.reveal_button.setFixedSize(87, 52)
|
||||
self.reveal_button.setToolTip("显示或隐藏密码")
|
||||
self.reveal_button.installEventFilter(password_field)
|
||||
self.reveal_button.toggled.connect(self._toggle_password)
|
||||
password_row.addWidget(self.reveal_button)
|
||||
card_layout.addWidget(password_field)
|
||||
@@ -599,6 +758,11 @@ class LoginWindow(QMainWindow):
|
||||
self.login_button = QPushButton("登录工作站")
|
||||
self.login_button.setProperty("variant", "primary")
|
||||
self.login_button.setFixedHeight(58)
|
||||
login_shadow = QGraphicsDropShadowEffect(self.login_button)
|
||||
login_shadow.setBlurRadius(20)
|
||||
login_shadow.setOffset(0, 7)
|
||||
login_shadow.setColor(QColor(82, 101, 246, 45))
|
||||
self.login_button.setGraphicsEffect(login_shadow)
|
||||
self.login_button.clicked.connect(self.submit)
|
||||
card_layout.addWidget(self.login_button)
|
||||
self.debug_settings_section = QWidget()
|
||||
|
||||
@@ -37,10 +37,8 @@ from PySide6.QtCore import (
|
||||
QTimer,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractItemView,
|
||||
QAbstractScrollArea,
|
||||
QGraphicsOpacityEffect,
|
||||
QPlainTextEdit,
|
||||
QStackedWidget,
|
||||
QWidget,
|
||||
)
|
||||
@@ -77,35 +75,15 @@ def reduced_motion() -> bool:
|
||||
return os.getenv("QT_QPA_PLATFORM", "").strip().lower() == "offscreen"
|
||||
|
||||
|
||||
def _stop(target: QObject, key: str) -> None:
|
||||
"""Retire a replaced animation without firing its completion callback."""
|
||||
|
||||
running = getattr(target, "_doctor_motion", {})
|
||||
previous = running.pop(key, None)
|
||||
if previous is not None:
|
||||
previous.stop()
|
||||
previous.setParent(None)
|
||||
previous.deleteLater()
|
||||
|
||||
|
||||
def _own(target: QObject, key: str, animation: QPropertyAnimation) -> QPropertyAnimation:
|
||||
def _own(target: QWidget, key: str, animation: QPropertyAnimation) -> QPropertyAnimation:
|
||||
"""Park an animation on its target so Python does not collect it early."""
|
||||
|
||||
_stop(target, key)
|
||||
running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", {})
|
||||
running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", None) or {}
|
||||
previous = running.get(key)
|
||||
if previous is not None:
|
||||
previous.stop()
|
||||
running[key] = animation
|
||||
target._doctor_motion = running
|
||||
|
||||
def release() -> None:
|
||||
if running.get(key) is animation:
|
||||
running.pop(key)
|
||||
# A callback can hold the last Python reference to the owner. Detach
|
||||
# first so releasing that callback during deferred deletion cannot
|
||||
# recursively delete this animation through its former parent.
|
||||
animation.setParent(None)
|
||||
animation.deleteLater()
|
||||
|
||||
animation.finished.connect(release)
|
||||
return animation
|
||||
|
||||
|
||||
@@ -129,10 +107,7 @@ def animate(
|
||||
from inside its own ``finished`` emission.
|
||||
"""
|
||||
|
||||
animation_owner = owner if owner is not None else target
|
||||
animation_key = key or prop.decode()
|
||||
if reduced_motion():
|
||||
_stop(animation_owner, animation_key)
|
||||
target.setProperty(prop.decode() if isinstance(prop, bytes) else prop, end)
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
@@ -142,24 +117,18 @@ def animate(
|
||||
animation.setEasingCurve(easing)
|
||||
animation.setStartValue(start)
|
||||
animation.setEndValue(end)
|
||||
_own(animation_owner, animation_key, animation)
|
||||
if on_finished is not None:
|
||||
animation.finished.connect(on_finished)
|
||||
_own(owner if owner is not None else target, key or prop.decode(), animation)
|
||||
animation.start(QAbstractAnimation.DeletionPolicy.KeepWhenStopped)
|
||||
return animation
|
||||
|
||||
|
||||
def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect | None:
|
||||
def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect:
|
||||
effect = widget.graphicsEffect()
|
||||
# Do not replace a caller's shadow or opacity effect: Qt deletes it when
|
||||
# another effect is attached. Only effects created here belong to a fade.
|
||||
if effect is not None and effect is not getattr(widget, "_doctor_opacity_effect", None):
|
||||
return None
|
||||
if effect is None:
|
||||
if not isinstance(effect, QGraphicsOpacityEffect):
|
||||
effect = QGraphicsOpacityEffect(widget)
|
||||
effect.setOpacity(1.0)
|
||||
widget.setGraphicsEffect(effect)
|
||||
widget._doctor_opacity_effect = effect
|
||||
effect.setEnabled(True)
|
||||
return effect
|
||||
|
||||
@@ -177,17 +146,9 @@ def _drop_effect(widget: QWidget) -> None:
|
||||
signal that is still being delivered.
|
||||
"""
|
||||
|
||||
effect = getattr(widget, "_doctor_opacity_effect", None)
|
||||
revision = getattr(widget, "_doctor_fade_revision", 0)
|
||||
|
||||
def detach() -> None:
|
||||
try:
|
||||
if (
|
||||
effect is not None
|
||||
and widget.graphicsEffect() is effect
|
||||
and getattr(widget, "_doctor_fade_revision", 0) == revision
|
||||
):
|
||||
widget._doctor_opacity_effect = None
|
||||
if isinstance(widget.graphicsEffect(), QGraphicsOpacityEffect):
|
||||
widget.setGraphicsEffect(None)
|
||||
except RuntimeError: # the widget went away while the fade was running
|
||||
pass
|
||||
@@ -195,13 +156,6 @@ def _drop_effect(widget: QWidget) -> None:
|
||||
QTimer.singleShot(0, detach)
|
||||
|
||||
|
||||
def _restart_fade(widget: QWidget) -> None:
|
||||
_stop(widget, "fade")
|
||||
# A completed fade may still have deferred cleanup waiting in the queue.
|
||||
# It must not remove an effect now being used by a subsequent fade.
|
||||
widget._doctor_fade_revision = getattr(widget, "_doctor_fade_revision", 0) + 1
|
||||
|
||||
|
||||
def fade_in(
|
||||
widget: QWidget,
|
||||
*,
|
||||
@@ -211,20 +165,10 @@ def fade_in(
|
||||
) -> None:
|
||||
"""Fade a widget up to full opacity, showing it first if needed."""
|
||||
|
||||
existing = widget.graphicsEffect()
|
||||
if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None):
|
||||
start = float(existing.opacity())
|
||||
_restart_fade(widget)
|
||||
if reduced_motion():
|
||||
if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None):
|
||||
existing.setOpacity(1.0)
|
||||
_drop_effect(widget)
|
||||
widget.show()
|
||||
return
|
||||
effect = _opacity_effect(widget)
|
||||
if effect is None:
|
||||
widget.show()
|
||||
return
|
||||
effect.setOpacity(start)
|
||||
widget.show()
|
||||
animate(
|
||||
@@ -249,11 +193,9 @@ def fade_out(
|
||||
) -> None:
|
||||
"""Fade a widget down, optionally hiding it when the fade completes."""
|
||||
|
||||
_restart_fade(widget)
|
||||
if reduced_motion():
|
||||
if hide:
|
||||
widget.hide()
|
||||
_drop_effect(widget)
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
return
|
||||
@@ -266,9 +208,6 @@ def fade_out(
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
|
||||
if effect is None:
|
||||
done()
|
||||
return
|
||||
animate(
|
||||
effect,
|
||||
b"opacity",
|
||||
@@ -290,17 +229,13 @@ def enter(widget: QWidget, *, duration: int = BASE, rise: int = RISE) -> None:
|
||||
the user has to wait out.
|
||||
"""
|
||||
|
||||
previous = getattr(widget, "_doctor_motion", {}).get("enter")
|
||||
origin = previous.endValue() if previous is not None else widget.pos()
|
||||
if reduced_motion():
|
||||
_stop(widget, "enter")
|
||||
widget.move(origin)
|
||||
fade_in(widget, duration=duration)
|
||||
widget.show()
|
||||
return
|
||||
fade_in(widget, duration=duration)
|
||||
if rise:
|
||||
if previous is None:
|
||||
widget.move(origin + QPoint(0, rise))
|
||||
origin = widget.pos()
|
||||
widget.move(origin + QPoint(0, rise))
|
||||
animate(
|
||||
widget,
|
||||
b"pos",
|
||||
@@ -325,7 +260,7 @@ def switch_stack(stack: QStackedWidget, index: int, *, rise: int = RISE) -> None
|
||||
return
|
||||
stack.setCurrentIndex(index)
|
||||
page = stack.currentWidget()
|
||||
if page is None:
|
||||
if page is None or reduced_motion():
|
||||
return
|
||||
enter(page, rise=rise)
|
||||
|
||||
@@ -339,121 +274,50 @@ SCROLL_STEP = 120
|
||||
SCROLL_MS = 190
|
||||
|
||||
|
||||
class _ScrollAnimation(QPropertyAnimation):
|
||||
"""Identify animation writes so direct scrollbar changes can interrupt us."""
|
||||
|
||||
writing = False
|
||||
|
||||
def updateCurrentValue(self, value: Any) -> None: # noqa: N802 - Qt API
|
||||
self.writing = True
|
||||
try:
|
||||
super().updateCurrentValue(value)
|
||||
finally:
|
||||
self.writing = False
|
||||
|
||||
|
||||
class _SmoothScroller(QObject):
|
||||
"""Animate a scroll area's wheel movement instead of jumping to it."""
|
||||
|
||||
_INTERRUPT_EVENTS = frozenset(
|
||||
{
|
||||
QEvent.Type.KeyPress,
|
||||
QEvent.Type.MouseButtonPress,
|
||||
QEvent.Type.TouchBegin,
|
||||
QEvent.Type.Hide,
|
||||
}
|
||||
)
|
||||
|
||||
def __init__(self, area: QAbstractScrollArea, *, orientation: Qt.Orientation) -> None:
|
||||
super().__init__(area)
|
||||
self._area = area
|
||||
self._orientation = orientation
|
||||
self._bar = (
|
||||
area.verticalScrollBar()
|
||||
if orientation is Qt.Orientation.Vertical
|
||||
else area.horizontalScrollBar()
|
||||
)
|
||||
self._target = self._bar.value()
|
||||
self._animation = _ScrollAnimation(self._bar, b"value", self)
|
||||
self._animation = QPropertyAnimation(self._bar, b"value", self)
|
||||
self._animation.setEasingCurve(EASE_ENTER)
|
||||
self._animation.setDuration(SCROLL_MS)
|
||||
# Keyboard, programmatic and drag movements must not be fought over: when
|
||||
# nothing is animating, the wheel target follows wherever the bar went.
|
||||
self._bar.valueChanged.connect(self._sync_target)
|
||||
self._bar.sliderPressed.connect(self._cancel)
|
||||
self._bar.actionTriggered.connect(self._cancel)
|
||||
self._bar.rangeChanged.connect(self._cancel)
|
||||
self._bar.installEventFilter(self)
|
||||
area.installEventFilter(self)
|
||||
area.viewport().installEventFilter(self)
|
||||
|
||||
def _cancel(self, *_: Any) -> None:
|
||||
self._animation.stop()
|
||||
self._target = self._bar.value()
|
||||
|
||||
def _sync_target(self, value: int) -> None:
|
||||
if not self._animation.writing:
|
||||
self._animation.stop()
|
||||
if self._animation.state() != QAbstractAnimation.State.Running:
|
||||
self._target = value
|
||||
|
||||
def _uses_pixels(self) -> bool:
|
||||
if isinstance(self._area, QAbstractItemView):
|
||||
mode = (
|
||||
self._area.verticalScrollMode()
|
||||
if self._orientation == Qt.Orientation.Vertical
|
||||
else self._area.horizontalScrollMode()
|
||||
)
|
||||
return mode == QAbstractItemView.ScrollMode.ScrollPerPixel
|
||||
# QPlainTextEdit's vertical scrollbar counts text blocks, not pixels.
|
||||
return not (
|
||||
isinstance(self._area, QPlainTextEdit) and self._orientation == Qt.Orientation.Vertical
|
||||
)
|
||||
|
||||
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt API
|
||||
event_type = event.type()
|
||||
if event_type in self._INTERRUPT_EVENTS:
|
||||
self._cancel()
|
||||
del watched
|
||||
if event.type() is not QEvent.Type.Wheel or reduced_motion():
|
||||
return False
|
||||
if event_type != QEvent.Type.Wheel:
|
||||
delta = event.angleDelta().y() or event.angleDelta().x()
|
||||
if not delta or event.modifiers() & Qt.KeyboardModifier.ControlModifier:
|
||||
return False
|
||||
horizontal = self._orientation == Qt.Orientation.Horizontal
|
||||
shifted = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)
|
||||
delta = event.angleDelta().x() if horizontal else event.angleDelta().y()
|
||||
if horizontal and shifted and not delta:
|
||||
delta = event.angleDelta().y()
|
||||
if (
|
||||
watched is not self._area.viewport()
|
||||
or reduced_motion()
|
||||
or not self._uses_pixels()
|
||||
or not event.pixelDelta().isNull()
|
||||
or event.phase() != Qt.ScrollPhase.NoScrollPhase
|
||||
or event.modifiers()
|
||||
& (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier)
|
||||
or (shifted and not horizontal)
|
||||
or not delta
|
||||
):
|
||||
# Trackpads already provide continuous motion and native momentum.
|
||||
# Mixing another easing curve into it adds lag and fights gestures.
|
||||
self._cancel()
|
||||
return False
|
||||
|
||||
lower, upper = self._bar.minimum(), self._bar.maximum()
|
||||
# Re-clamp first: the range can shrink underneath a running animation
|
||||
# when the content behind it reloads, which would otherwise leave the
|
||||
# pending target past the end of the new content.
|
||||
self._target = max(lower, min(upper, self._target))
|
||||
current = self._bar.value()
|
||||
step = -round(delta / 120.0 * SCROLL_STEP)
|
||||
# Reverse immediately from the visible position, not the end of a
|
||||
# backlog of wheel notches still travelling in the opposite direction.
|
||||
origin = current if (self._target - current) * step < 0 else self._target
|
||||
target = origin + step
|
||||
target = self._target - round(delta / 120.0 * SCROLL_STEP)
|
||||
target = max(lower, min(upper, target))
|
||||
# At either end, hand the wheel back so an enclosing scroll area still
|
||||
# gets it - swallowing it there is what makes nested panes feel stuck.
|
||||
if target == self._target:
|
||||
return target != current
|
||||
return False
|
||||
self._target = target
|
||||
self._animation.stop()
|
||||
self._animation.setStartValue(current)
|
||||
self._animation.setStartValue(self._bar.value())
|
||||
self._animation.setEndValue(target)
|
||||
self._animation.start()
|
||||
return True
|
||||
@@ -464,7 +328,7 @@ def install_smooth_scroll(
|
||||
*,
|
||||
orientation: Qt.Orientation = Qt.Orientation.Vertical,
|
||||
) -> None:
|
||||
"""Ease discrete wheels on pixel-based areas; preserve native gestures."""
|
||||
"""Give a scroll area eased wheel scrolling."""
|
||||
|
||||
if getattr(area, "_doctor_smooth_scroll", None) is not None:
|
||||
return
|
||||
|
||||
@@ -50,7 +50,6 @@ from ...core.appointment_modes import (
|
||||
)
|
||||
from .. import icons
|
||||
from ..appointment_drawer import AppointmentDrawer
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail
|
||||
from ..dialogs.ai_consult import can_open_ai_consult
|
||||
from ..dialogs.prescription import PrescriptionOrderListDialog
|
||||
@@ -111,97 +110,97 @@ FULFILLMENT_TEXT = {
|
||||
}
|
||||
|
||||
_SEMANTIC_COLORS = {
|
||||
"primary": PALETTE["accent"],
|
||||
"success": PALETTE["success"],
|
||||
"warning": PALETTE["warning"],
|
||||
"danger": PALETTE["danger"],
|
||||
"info": PALETTE["accent"],
|
||||
"muted": PALETTE["muted"],
|
||||
"primary": "#4F63D9",
|
||||
"success": "#287B65",
|
||||
"warning": "#A9691D",
|
||||
"danger": "#BE4B58",
|
||||
"info": "#4F63D9",
|
||||
"muted": "#606163",
|
||||
}
|
||||
|
||||
PATIENTS_LIGHT_QSS = clinical_stylesheet("""
|
||||
PATIENTS_LIGHT_QSS = """
|
||||
#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
|
||||
color: $ds_heading;
|
||||
color: #1A1C1F;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
#PatientsPage QWidget#PageHeader QLabel[role="muted"] {
|
||||
color: $ds_muted;
|
||||
color: #606163;
|
||||
font-size: 13px;
|
||||
}
|
||||
#PatientsPage QPushButton[patientSearchAction="true"] {
|
||||
min-height: 32px;
|
||||
max-height: 32px;
|
||||
color: $ds_surface;
|
||||
background-color: $ds_accent;
|
||||
border: 1px solid $ds_accent;
|
||||
color: #FFFFFF;
|
||||
background-color: #4F63D9;
|
||||
border: 1px solid #4F63D9;
|
||||
border-radius: 7px;
|
||||
font-weight: 500;
|
||||
}
|
||||
#PatientsPage QPushButton[patientSearchAction="true"]:hover {
|
||||
background-color: $ds_accent_hover;
|
||||
border-color: $ds_accent_hover;
|
||||
background-color: #4156C4;
|
||||
border-color: #4156C4;
|
||||
}
|
||||
#PatientsPage QFrame[patientListFilter="true"] {
|
||||
min-height: 88px;
|
||||
max-height: 88px;
|
||||
background-color: $ds_surface;
|
||||
border: 1px solid $ds_line;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 12px;
|
||||
}
|
||||
#PatientsPage QFrame[patientListFilter="true"] QLineEdit,
|
||||
#PatientsPage QFrame[patientListFilter="true"] QDateEdit {
|
||||
min-height: 32px;
|
||||
max-height: 32px;
|
||||
background-color: $ds_surface;
|
||||
border: 1px solid $ds_line;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 7px; font-size: 14px;
|
||||
}
|
||||
#PatientsPage QFrame[patientListFilter="true"] QPushButton {
|
||||
min-height: 32px; max-height: 32px;
|
||||
}
|
||||
#PatientsPage QFrame[patientListFilter="true"] QDateEdit:disabled {
|
||||
color: $ds_disabled; background-color: $ds_surface_alt;
|
||||
color: #8E8F90; background-color: #F7F7F7;
|
||||
}
|
||||
#PatientsPage QPushButton[patientStatusChip="true"] {
|
||||
min-height: 32px;
|
||||
max-height: 32px;
|
||||
padding: 0 10px;
|
||||
color: $ds_muted;
|
||||
background-color: $ds_surface_alt;
|
||||
color: #606163;
|
||||
background-color: #F7F7F7;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 5px;
|
||||
}
|
||||
#PatientsPage QPushButton[patientStatusChip="true"]:hover {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
}
|
||||
#PatientsPage QPushButton[patientStatusChip="true"]:checked {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border: 1px solid $ds_focus;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border: 1px solid #8B9AD9;
|
||||
}
|
||||
#PatientsPage QPushButton[patientQuickDate="true"] {
|
||||
min-height: 32px;
|
||||
max-height: 32px;
|
||||
padding: 0 9px;
|
||||
color: $ds_heading;
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 7px;
|
||||
}
|
||||
#PatientsPage QPushButton[patientQuickDate="true"]:hover {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
}
|
||||
#PatientsPage QPushButton[patientQuickDate="true"]:checked {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border-color: #8B9AD9;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane {
|
||||
border: 0;
|
||||
border-top: 1px solid $ds_line;
|
||||
border-top: 1px solid #EDEDEE;
|
||||
background-color: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab {
|
||||
@@ -209,124 +208,124 @@ PATIENTS_LIGHT_QSS = clinical_stylesheet("""
|
||||
min-height: 34px;
|
||||
padding: 0 6px;
|
||||
margin-right: 8px;
|
||||
color: $ds_muted;
|
||||
color: #606163;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
font-weight: 400;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected {
|
||||
color: $ds_accent;
|
||||
border-bottom-color: $ds_accent;
|
||||
color: #4F63D9;
|
||||
border-bottom-color: #4F63D9;
|
||||
font-weight: 500;
|
||||
}
|
||||
#PatientsPage QPushButton[summaryCard="true"] {
|
||||
min-height: 42px;
|
||||
max-height: 42px;
|
||||
padding: 0 11px;
|
||||
color: $ds_heading;
|
||||
background-color: $ds_surface_alt;
|
||||
border: 1px solid $ds_line;
|
||||
color: #1A1C1F;
|
||||
background-color: #F7F7F7;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 9px;
|
||||
text-align: left;
|
||||
font-weight: 500;
|
||||
}
|
||||
#PatientsPage QPushButton[summaryCard="true"]:hover {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border-color: #8B9AD9;
|
||||
}
|
||||
#PatientsPage QPushButton[rowAction="true"] {
|
||||
min-height: 26px;
|
||||
max-height: 26px;
|
||||
padding: 0 7px;
|
||||
color: $ds_accent;
|
||||
background-color: $ds_surface;
|
||||
border: 1px solid $ds_line;
|
||||
color: #4F63D9;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
}
|
||||
#PatientsPage QPushButton[rowAction="true"]:hover {
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
background-color: #EEF1FA;
|
||||
border-color: #8B9AD9;
|
||||
}
|
||||
#PatientsPage QPushButton[rowAction="true"][variant="danger"] {
|
||||
color: $ds_danger;
|
||||
background-color: $ds_danger_soft;
|
||||
border-color: $ds_danger_soft;
|
||||
color: #BE4B58;
|
||||
background-color: #FFF7F8;
|
||||
border-color: #F4C4CC;
|
||||
}
|
||||
#PatientsPage QTableWidget#PatientTable QHeaderView::section {
|
||||
min-height: 34px;
|
||||
background-color: $ds_surface_alt; font-size: 13px;
|
||||
background-color: #F7F7F7; font-size: 13px;
|
||||
}
|
||||
#PatientsPage QTableWidget#PatientTable::item { padding: 5px 7px; }
|
||||
#PatientsPage QTableWidget#PatientTable {
|
||||
gridline-color: $ds_line;
|
||||
selection-background-color: $ds_accent_soft;
|
||||
selection-color: $ds_heading; font-size: 14px;
|
||||
gridline-color: #EDEDEE;
|
||||
selection-background-color: #EEF1FA;
|
||||
selection-color: #1A1C1F; font-size: 14px;
|
||||
}
|
||||
#PatientsPage QCheckBox[patientSelector="true"]::indicator {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
background-color: $ds_surface;
|
||||
border: 1px solid $ds_line;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 2px;
|
||||
}
|
||||
#PatientsPage QCheckBox[patientSelector="true"]::indicator:checked {
|
||||
background-color: $ds_accent;
|
||||
border-color: $ds_accent;
|
||||
background-color: #4F63D9;
|
||||
border-color: #4F63D9;
|
||||
}
|
||||
#PatientsPage QPushButton[variant="ghost"]:checked {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border: 1px solid $ds_accent;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border: 1px solid #4F63D9;
|
||||
}
|
||||
#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: $ds_accent_soft; }
|
||||
#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: #EEF1FA; }
|
||||
#PatientsPage QPushButton[statusKind="info"]:checked {
|
||||
color: $ds_accent;
|
||||
border-color: $ds_accent;
|
||||
color: #4F63D9;
|
||||
border-color: #4F63D9;
|
||||
}
|
||||
#PatientsPage QPushButton[statusKind="warning"]:checked {
|
||||
color: $ds_warning;
|
||||
border-color: $ds_warning;
|
||||
color: #A9691D;
|
||||
border-color: #A9691D;
|
||||
}
|
||||
#PatientsPage QPushButton[statusKind="success"]:checked {
|
||||
color: $ds_success;
|
||||
border-color: $ds_success;
|
||||
color: #287B65;
|
||||
border-color: #287B65;
|
||||
}
|
||||
#PatientsPage QPushButton[statusKind="danger"]:checked {
|
||||
color: $ds_danger;
|
||||
border-color: $ds_danger;
|
||||
color: #BE4B58;
|
||||
border-color: #BE4B58;
|
||||
}
|
||||
#PatientsPage QLabel[metricKind="primary"] { color: $ds_accent; }
|
||||
#PatientsPage QLabel[metricKind="info"] { color: $ds_accent; }
|
||||
#PatientsPage QLabel[metricKind="success"] { color: $ds_success; }
|
||||
#PatientsPage QLabel[metricKind="warning"] { color: $ds_warning; }
|
||||
#PatientsPage QLabel[metricKind="danger"] { color: $ds_danger; }
|
||||
#PatientsPage QLabel[metricKind="primary"] { color: #4F63D9; }
|
||||
#PatientsPage QLabel[metricKind="info"] { color: #4F63D9; }
|
||||
#PatientsPage QLabel[metricKind="success"] { color: #287B65; }
|
||||
#PatientsPage QLabel[metricKind="warning"] { color: #A9691D; }
|
||||
#PatientsPage QLabel[metricKind="danger"] { color: #BE4B58; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane {
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
top: -1px;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab {
|
||||
color: $ds_muted;
|
||||
color: #606163;
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
font-weight: 400;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:hover {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected {
|
||||
color: $ds_accent;
|
||||
color: #4F63D9;
|
||||
background-color: transparent;
|
||||
border-bottom-color: $ds_accent;
|
||||
border-bottom-color: #4F63D9;
|
||||
font-weight: 500;
|
||||
}
|
||||
""")
|
||||
"""
|
||||
|
||||
|
||||
def _style_table_cell(table: SortableTable, row: int, column: int, kind: str) -> None:
|
||||
@@ -1283,7 +1282,7 @@ class _PatientDateEdit(QDateEdit):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 15)
|
||||
glyph = icons.pixmap("calendar", "#5D6B80" if self.isEnabled() else "#8A97A9", 15)
|
||||
painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 15) / 2, 15, 15), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -1301,18 +1300,18 @@ class _PatientSummaryButton(QPushButton):
|
||||
label, _, count = self.text().partition("\n")
|
||||
left = max(18, (self.width() - 204) // 2)
|
||||
icon_rect = QRectF(left, (self.height() - 36) / 2, 36, 36)
|
||||
glyph = icons.pixmap("calendar", PALETTE["accent"], 36)
|
||||
glyph = icons.pixmap("calendar", "#1769E8", 36)
|
||||
painter.drawPixmap(icon_rect, glyph, QRectF(glyph.rect()))
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setPen(QColor("#5D6B80"))
|
||||
text_rect = self.rect().adjusted(left + 46, 10, -12, -32)
|
||||
painter.drawText(text_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||
painter.fontMetrics().elidedText(label, Qt.TextElideMode.ElideRight, text_rect.width()))
|
||||
font.setPixelSize(16)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
painter.setPen(QColor("#273244"))
|
||||
painter.drawText(self.rect().adjusted(left + 46, 31, -12, -9),
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, count)
|
||||
painter.end()
|
||||
@@ -1325,11 +1324,11 @@ class _PatientInfoDelegate(QStyledItemDelegate):
|
||||
painter.save()
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.fillRect(option.rect, QColor("#EAF2FF" if selected else "#F6F9FE" if hovered else "#FFFFFF"))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
|
||||
if index.column() in (0, 9):
|
||||
painter.restore()
|
||||
return
|
||||
@@ -1338,9 +1337,9 @@ class _PatientInfoDelegate(QStyledItemDelegate):
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(14)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
painter.setPen(QColor("#273244"))
|
||||
|
||||
def draw(text: str, target: Any, color: str = PALETTE["text"], centered: bool = False) -> None:
|
||||
def draw(text: str, target: Any, color: str = "#273244", centered: bool = False) -> None:
|
||||
painter.setPen(QColor(color))
|
||||
text = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, target.width())
|
||||
alignment = Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignHCenter if centered else Qt.AlignmentFlag.AlignLeft)
|
||||
@@ -1360,17 +1359,17 @@ class _PatientInfoDelegate(QStyledItemDelegate):
|
||||
doctor = display_text(first_value(row, "appointment_doctor_name"), "")
|
||||
status, _kind = _patient_status(row)
|
||||
if not doctor:
|
||||
draw(status, rect, PALETTE["muted"])
|
||||
draw(status, rect, "#5D6B80")
|
||||
else:
|
||||
draw(doctor, top)
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
color, fill = (PALETTE["warning"], PALETTE["warning_soft"]) if status == "已过号" else (PALETTE["accent"], PALETTE["accent_soft"])
|
||||
color, fill = ("#A9691D", "#FFF7EA") if status == "已过号" else ("#1769E8", "#F0F6FF")
|
||||
if status == "已取消":
|
||||
color, fill = PALETTE["muted"], PALETTE["canvas"]
|
||||
color, fill = "#5D6B80", "#F5F7FA"
|
||||
badge = QRectF(bottom.x(), bottom.y() + 1, min(bottom.width(), painter.fontMetrics().horizontalAdvance(status) + 10), 20)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(QColor(PALETTE["warning_soft"] if status == "已过号" else PALETTE["line_strong"]))
|
||||
painter.setPen(QColor("#E7CDA8" if status == "已过号" else "#C7DAF7"))
|
||||
painter.setBrush(QColor(fill))
|
||||
painter.drawRoundedRect(badge, 3, 3)
|
||||
draw(status, badge.toRect(), color, True)
|
||||
@@ -1386,7 +1385,7 @@ class _PatientInfoDelegate(QStyledItemDelegate):
|
||||
draw(value, rect)
|
||||
else:
|
||||
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "")
|
||||
draw(text, rect, PALETTE["warning"] if index.column() == 6 and text == "待确认" else PALETTE["text"], index.column() == 5)
|
||||
draw(text, rect, "#A9691D" if index.column() == 6 and text == "待确认" else "#273244", index.column() == 5)
|
||||
painter.restore()
|
||||
|
||||
|
||||
@@ -1494,7 +1493,7 @@ class PatientListWorkspace(QWidget):
|
||||
self.keyword_edit.setMaximumWidth(360)
|
||||
self.keyword_edit.setPlaceholderText("患者姓名 / 手机号 / 助理 / 医生")
|
||||
self.keyword_edit.setClearButtonEnabled(True)
|
||||
self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
|
||||
self.keyword_edit.addAction(icons.icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition)
|
||||
self.keyword_edit.returnPressed.connect(self.search)
|
||||
search_row.addWidget(self.keyword_edit, 1)
|
||||
self.status_label = QLabel("患者状态:")
|
||||
@@ -1847,7 +1846,7 @@ class PatientListWorkspace(QWidget):
|
||||
)
|
||||
host = RowActions(row_actions, self.table)
|
||||
if host.more_button is not None:
|
||||
host.more_button.setIcon(icons.icon("chevron_down", PALETTE["muted"], 12))
|
||||
host.more_button.setIcon(icons.icon("chevron_down", "#5D6B80", 12))
|
||||
host.more_button.setIconSize(QSize(12, 12))
|
||||
host.more_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
|
||||
host.more_button.setLayoutDirection(Qt.LayoutDirection.RightToLeft)
|
||||
@@ -2080,7 +2079,7 @@ class _OrderComboBox(QComboBox):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
|
||||
glyph = icons.pixmap("chevron_down", "#5D6B80", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -2089,7 +2088,7 @@ class _OrderActionButton(QToolButton):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("chevron_down", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14)
|
||||
glyph = icons.pixmap("chevron_down", "#5D6B80" if self.isEnabled() else "#97A4B6", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 23, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -2108,18 +2107,18 @@ class _OrderInfoDelegate(QStyledItemDelegate):
|
||||
painter.setClipRect(option.rect)
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.fillRect(option.rect, QColor("#F5F8FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
|
||||
rect = option.rect.adjusted(16, 0, -12, -1)
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(14)
|
||||
painter.setFont(font)
|
||||
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "—")
|
||||
|
||||
def draw(value: str, target: Any, color: str = PALETTE["text"], right: bool = False) -> None:
|
||||
def draw(value: str, target: Any, color: str = "#273244", right: bool = False) -> None:
|
||||
painter.setPen(QColor(color))
|
||||
value = painter.fontMetrics().elidedText(value, Qt.TextElideMode.ElideRight, target.width())
|
||||
painter.drawText(target, Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignRight if right else Qt.AlignmentFlag.AlignLeft), value)
|
||||
@@ -2139,7 +2138,7 @@ class _OrderInfoDelegate(QStyledItemDelegate):
|
||||
font.setWeight(QFont.Weight.Normal)
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
draw(secondary, bottom, PALETTE["muted"])
|
||||
draw(secondary, bottom, "#5D6B80")
|
||||
else:
|
||||
draw(text, rect)
|
||||
elif column in (9, 11):
|
||||
@@ -2148,7 +2147,7 @@ class _OrderInfoDelegate(QStyledItemDelegate):
|
||||
draw(primary, top)
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
draw(("(" if column == 9 else "") + secondary, bottom, PALETTE["muted"])
|
||||
draw(("(" if column == 9 else "") + secondary, bottom, "#5D6B80")
|
||||
else:
|
||||
draw(text, rect)
|
||||
elif column in (4, 5, 6):
|
||||
@@ -2159,10 +2158,10 @@ class _OrderInfoDelegate(QStyledItemDelegate):
|
||||
else:
|
||||
kind = "blue" if raw in {3, 5, 6, 7, 8, 11} else "danger" if raw in {4, 9, 10} else "warning" if raw in {1, 2, 12} else "neutral"
|
||||
foreground, background, border = {
|
||||
"blue": (PALETTE["accent"], PALETTE["accent_soft"], PALETTE["line_strong"]),
|
||||
"warning": (PALETTE["warning"], PALETTE["warning_soft"], PALETTE["warning_soft"]),
|
||||
"danger": (PALETTE["danger"], PALETTE["danger_soft"], PALETTE["danger_soft"]),
|
||||
"neutral": (PALETTE["muted"], PALETTE["disabled_surface"], PALETTE["line"]),
|
||||
"blue": ("#1769E8", "#F2F7FF", "#CEE0FA"),
|
||||
"warning": ("#AD640C", "#FFFAF2", "#F2DABD"),
|
||||
"danger": ("#BE4657", "#FFF5F6", "#F0D0D7"),
|
||||
"neutral": ("#5D6B80", "#F6F8FC", "#E2E9F2"),
|
||||
}[kind]
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
@@ -2276,7 +2275,7 @@ class PatientOrdersWorkspace(QWidget):
|
||||
self.keyword_edit.setMinimumWidth(240)
|
||||
self.keyword_edit.setPlaceholderText("订单号 / 患者 / 手机号 / 处方ID / 诊单ID")
|
||||
self.keyword_edit.setClearButtonEnabled(True)
|
||||
self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
|
||||
self.keyword_edit.addAction(icons.icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition)
|
||||
self.keyword_edit.returnPressed.connect(self.search)
|
||||
self.filter_top_row.addWidget(self.keyword_edit, 1)
|
||||
self.audit_host = QWidget()
|
||||
@@ -2748,11 +2747,11 @@ class _ProgressInfoDelegate(QStyledItemDelegate):
|
||||
painter.setClipRect(option.rect)
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.fillRect(option.rect, QColor("#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
|
||||
rect = option.rect.adjusted(16, 0, -16, -1)
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(14)
|
||||
@@ -2763,20 +2762,20 @@ class _ProgressInfoDelegate(QStyledItemDelegate):
|
||||
painter.setFont(font)
|
||||
raw_text = index.data(Qt.ItemDataRole.DisplayRole)
|
||||
text = "" if raw_text is None else str(raw_text)
|
||||
color = PALETTE["text"]
|
||||
color = "#273244"
|
||||
if not self.schedule and index.column() == 5 and text and text != "—":
|
||||
row = index.data(Qt.ItemDataRole.UserRole)
|
||||
status = str(first_value(row, "queue_status", default="") or "").lower()
|
||||
color = {
|
||||
"consulting": PALETTE["accent"], "next": PALETTE["accent_hover"],
|
||||
"waiting": PALETTE["warning"], "missed": PALETTE["danger"],
|
||||
}.get(status, PALETTE["muted"])
|
||||
"consulting": "#1769E8", "next": "#1555B6",
|
||||
"waiting": "#AD640C", "missed": "#BE4657",
|
||||
}.get(status, "#5D6B80")
|
||||
painter.setPen(QColor(color))
|
||||
alignment = Qt.AlignmentFlag.AlignVCenter
|
||||
alignment |= Qt.AlignmentFlag.AlignHCenter if self.schedule and 1 <= index.column() <= 5 else Qt.AlignmentFlag.AlignLeft
|
||||
painter.drawText(rect, alignment, painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, rect.width()))
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setPen(QColor(PALETTE["focus"]))
|
||||
painter.setPen(QColor("#75A5F0"))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
|
||||
painter.restore()
|
||||
@@ -2876,7 +2875,7 @@ class PatientProgressWorkspace(QWidget):
|
||||
row = QHBoxLayout(frame)
|
||||
row.setContentsMargins(0, 0, 0, 0)
|
||||
row.setSpacing(0)
|
||||
divider = QFrame(frame)
|
||||
divider = QFrame()
|
||||
divider.setObjectName("ProgressMetricDivider")
|
||||
divider.setFixedSize(1, 60)
|
||||
divider.setVisible(key != "total")
|
||||
|
||||
@@ -24,7 +24,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from .. import motion
|
||||
from ..design_system import PALETTE
|
||||
from ..dialogs.prescription import PrescriptionTemplateDialog
|
||||
from ..dialogs.prescription_ai import PrescriptionAiReportDialog, can_open_ai_explain
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
@@ -120,7 +119,7 @@ def _metric_card(title: str, kind: str = "accent", glyph: str = "layers") -> Met
|
||||
icon.setProperty("metricIcon", True)
|
||||
icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
icon.setFixedSize(32, 32)
|
||||
color = PALETTE["accent"] if kind == "accent" else PALETTE["muted"]
|
||||
color = "#1769E8" if kind == "accent" else "#60789F"
|
||||
icon.setPixmap(_painted_icon(glyph, color, 25).pixmap(25, 25))
|
||||
card.layout().addWidget(icon)
|
||||
return card
|
||||
@@ -544,7 +543,7 @@ class PrescriptionLibraryPage(QWidget):
|
||||
|
||||
name_item = self.table.item(row_index, 1)
|
||||
if name_item is not None:
|
||||
name_item.setForeground(QColor(PALETTE["heading"]))
|
||||
name_item.setForeground(QColor("#1A1C1F"))
|
||||
font = name_item.font()
|
||||
font.setWeight(QFont.Weight.Medium)
|
||||
name_item.setFont(font)
|
||||
|
||||
@@ -50,7 +50,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from .. import icons, motion
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..dialogs.issued_prescription_ai import (
|
||||
PrescriptionAiStatisticsDialog,
|
||||
agreement_safe_batch,
|
||||
@@ -230,11 +229,11 @@ _ROLE_AVATAR = Qt.ItemDataRole.UserRole + 11
|
||||
_ROLE_LEAD_ICON = Qt.ItemDataRole.UserRole + 12
|
||||
|
||||
_TAG_PALETTE = {
|
||||
"accent": (PALETTE["accent"], PALETTE["accent_soft"]),
|
||||
"success": (PALETTE["success"], PALETTE["success_soft"]),
|
||||
"warning": (PALETTE["warning"], PALETTE["warning_soft"]),
|
||||
"danger": (PALETTE["danger"], PALETTE["danger_soft"]),
|
||||
"neutral": (PALETTE["muted"], PALETTE["surface_alt"]),
|
||||
"accent": ("#4F63D9", "#EEF1FA"),
|
||||
"success": ("#287B65", "#E7F8F1"),
|
||||
"warning": ("#A9691D", "#FFF5DF"),
|
||||
"danger": ("#BE4B58", "#FFF0F2"),
|
||||
"neutral": ("#606163", "#F7F7F7"),
|
||||
}
|
||||
|
||||
|
||||
@@ -294,7 +293,7 @@ class _RowDecorationDelegate(QStyledItemDelegate):
|
||||
glyph,
|
||||
QRectF(glyph.rect()),
|
||||
)
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
painter.setFont(style_option.font)
|
||||
text_rect = rect.adjusted(28, 0, -8, 0)
|
||||
painter.drawText(
|
||||
@@ -307,17 +306,17 @@ class _RowDecorationDelegate(QStyledItemDelegate):
|
||||
else:
|
||||
initial = str(avatar)[:1] or "医"
|
||||
circle = QRectF(rect.left() + 8, rect.center().y() - 10, 20, 20)
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1.0))
|
||||
painter.setBrush(QColor(PALETTE["surface_alt"]))
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1.0))
|
||||
painter.setBrush(QColor("#F7F7F7"))
|
||||
painter.drawEllipse(circle.adjusted(0.5, 0.5, -0.5, -0.5))
|
||||
initial_font = QFont(style_option.font)
|
||||
initial_font.setPixelSize(10)
|
||||
initial_font.setWeight(QFont.Weight.Medium)
|
||||
painter.setFont(initial_font)
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setPen(QColor("#6A6B6D"))
|
||||
painter.drawText(circle, Qt.AlignmentFlag.AlignCenter, initial)
|
||||
painter.setFont(style_option.font)
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
name_rect = rect.adjusted(35, 0, -8, 0)
|
||||
painter.drawText(
|
||||
name_rect,
|
||||
@@ -510,11 +509,11 @@ class _PrescriptionNumberDelegate(QStyledItemDelegate):
|
||||
text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)
|
||||
document.setDefaultTextOption(text_option)
|
||||
paragraphs = [
|
||||
f'<p style="margin:0;color:{PALETTE["heading"]};font-size:14px;font-weight:500">{escape(number)}</p>',
|
||||
f'<p style="margin:2px 0 0;color:{PALETTE["muted"]};font-size:12px;font-weight:400">ID: {escape(record_id)}</p>',
|
||||
f'<p style="margin:0;color:#1A1C1F;font-size:14px;font-weight:500">{escape(number)}</p>',
|
||||
f'<p style="margin:2px 0 0;color:#606163;font-size:12px;font-weight:400">ID: {escape(record_id)}</p>',
|
||||
]
|
||||
paragraphs.extend(
|
||||
f'<p style="margin:2px 0 0;color:{PALETTE["danger"]};font-size:13px;font-weight:400">'
|
||||
'<p style="margin:2px 0 0;color:#BE4B58;font-size:13px;font-weight:400">'
|
||||
+ escape(warning)
|
||||
+ "</p>"
|
||||
for warning in _order_warnings(row)
|
||||
@@ -604,14 +603,14 @@ class _DoctorOptionDelegate(QStyledItemDelegate):
|
||||
rect = option.rect.adjusted(2, 1, -2, -1)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"] if checked else PALETTE["canvas"] if hovered else PALETTE["surface"]))
|
||||
painter.setBrush(QColor("#EAF2FF" if checked else "#F3F7FD" if hovered else "#FFFFFF"))
|
||||
painter.drawRoundedRect(rect, 5, 5)
|
||||
box = QRectF(rect.left() + 10, rect.center().y() - 8, 16, 16)
|
||||
painter.setPen(QPen(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"]), 1))
|
||||
painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["surface"]))
|
||||
painter.setPen(QPen(QColor("#1769E8" if checked else "#B8C7DA"), 1))
|
||||
painter.setBrush(QColor("#1769E8" if checked else "#FFFFFF"))
|
||||
painter.drawRoundedRect(box, 3, 3)
|
||||
if checked:
|
||||
pen = QPen(QColor(PALETTE["surface"]), 2)
|
||||
pen = QPen(QColor("#FFFFFF"), 2)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
painter.setPen(pen)
|
||||
x, y = int(box.x()), int(box.y())
|
||||
@@ -620,16 +619,16 @@ class _DoctorOptionDelegate(QStyledItemDelegate):
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
painter.setPen(QColor("#273244"))
|
||||
text_rect = rect.adjusted(38, 0, -54, 0)
|
||||
label = painter.fontMetrics().elidedText(str(index.data() or ""), Qt.TextElideMode.ElideRight, text_rect.width())
|
||||
painter.drawText(text_rect, Qt.AlignmentFlag.AlignVCenter, label)
|
||||
if checked:
|
||||
painter.setPen(QColor(PALETTE["accent"]))
|
||||
painter.setPen(QColor("#1769E8"))
|
||||
painter.drawText(rect.adjusted(0, 0, -12, 0), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, "已选")
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.setPen(QPen(QColor(PALETTE["line_strong"]), 1))
|
||||
painter.setPen(QPen(QColor("#ADC8F2"), 1))
|
||||
painter.drawRoundedRect(rect, 5, 5)
|
||||
painter.restore()
|
||||
|
||||
@@ -675,18 +674,18 @@ class _DoctorSelectionDialog(QDialog):
|
||||
self.setObjectName("DoctorSelectionDialog")
|
||||
self.setWindowTitle("选择医生")
|
||||
self.resize(420, 500)
|
||||
self.setStyleSheet(clinical_stylesheet("""
|
||||
QDialog#DoctorSelectionDialog { background: $ds_surface; color: $ds_text; }
|
||||
QListWidget#DoctorOptionsList { background: $ds_surface; border: 1px solid $ds_line; border-radius: 6px; padding: 3px; }
|
||||
QLabel#DoctorSelectionCount { color: $ds_accent; font-size: 13px; }
|
||||
QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid $ds_line; border-radius: 6px; }
|
||||
QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: $ds_accent; }
|
||||
QDialog#DoctorSelectionDialog QPushButton { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; border-radius: 6px; }
|
||||
QDialog#DoctorSelectionDialog QPushButton:hover { background: $ds_canvas; border-color: $ds_line_strong; }
|
||||
QDialog#DoctorSelectionDialog QPushButton:disabled { color: $ds_disabled; }
|
||||
QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: $ds_accent; color: $ds_surface; border-color: $ds_accent; }
|
||||
QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; }
|
||||
"""))
|
||||
self.setStyleSheet("""
|
||||
QDialog#DoctorSelectionDialog { background: #FFFFFF; color: #273244; }
|
||||
QListWidget#DoctorOptionsList { background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 6px; padding: 3px; }
|
||||
QLabel#DoctorSelectionCount { color: #1769E8; font-size: 13px; }
|
||||
QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid #DBE5F2; border-radius: 6px; }
|
||||
QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: #1769E8; }
|
||||
QDialog#DoctorSelectionDialog QPushButton { background: #FFFFFF; color: #273244; border: 1px solid #DBE5F2; border-radius: 6px; }
|
||||
QDialog#DoctorSelectionDialog QPushButton:hover { background: #F3F7FD; border-color: #ADC8F2; }
|
||||
QDialog#DoctorSelectionDialog QPushButton:disabled { color: #8A97A9; }
|
||||
QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: #1769E8; color: #FFFFFF; border-color: #1769E8; }
|
||||
QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: #125DCE; border-color: #125DCE; }
|
||||
""")
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(16, 16, 16, 16)
|
||||
layout.setSpacing(10)
|
||||
@@ -794,9 +793,9 @@ class DoctorMultiSelect(QWidget):
|
||||
self.button.setText("、".join(names[:2]) + (f" 等{len(names)}人" if len(names) > 2 else ""))
|
||||
|
||||
|
||||
def _blue_prescription_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon:
|
||||
def _blue_prescription_icon(kind: str, color: str = "#1769E8", size: int = 15) -> QIcon:
|
||||
result = QIcon(icons.icon(kind, color, size))
|
||||
result.addPixmap(icons.pixmap(kind, PALETTE["disabled"], size), QIcon.Mode.Disabled)
|
||||
result.addPixmap(icons.pixmap(kind, "#A4ADBA", size), QIcon.Mode.Disabled)
|
||||
return result
|
||||
|
||||
|
||||
@@ -804,7 +803,7 @@ class _PrescriptionCombo(QComboBox):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
|
||||
glyph = icons.pixmap("chevron_down", "#5D6B80", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -813,7 +812,7 @@ class _PrescriptionDateTime(QDateTimeEdit):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14)
|
||||
glyph = icons.pixmap("calendar", "#5D6B80" if self.isEnabled() else "#8A97A9", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -826,7 +825,7 @@ class _PrescriptionDoctorButton(QPushButton):
|
||||
option.text = self.fontMetrics().elidedText(self.text(), Qt.TextElideMode.ElideRight, max(1, self.width() - 48))
|
||||
painter = QPainter(self)
|
||||
self.style().drawControl(QStyle.ControlElement.CE_PushButton, option, painter, self)
|
||||
glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
|
||||
glyph = icons.pixmap("chevron_down", "#5D6B80", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -838,13 +837,13 @@ class _PrescriptionDoctorButton(QPushButton):
|
||||
def _prescription_cell_background(painter: QPainter, option: Any, index: QModelIndex) -> None:
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.fillRect(option.rect, QColor("#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setPen(QColor(PALETTE["focus"]))
|
||||
painter.setPen(QColor("#75A5F0"))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
|
||||
|
||||
@@ -876,7 +875,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate):
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(14)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
painter.setPen(QColor("#273244"))
|
||||
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "")
|
||||
column = index.column()
|
||||
if column == 0:
|
||||
@@ -889,9 +888,9 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate):
|
||||
elif column in (3, 6):
|
||||
kind = index.data(_ROLE_TAG_KIND)
|
||||
foreground, background = {
|
||||
"accent": (PALETTE["accent"], PALETTE["accent_soft"]), "success": (PALETTE["accent"], PALETTE["accent_soft"]),
|
||||
"warning": (PALETTE["warning"], PALETTE["warning_soft"]), "danger": (PALETTE["danger"], PALETTE["danger_soft"]),
|
||||
}.get(kind, (PALETTE["muted"], PALETTE["surface_alt"]))
|
||||
"accent": ("#1769E8", "#EDF4FF"), "success": ("#1769E8", "#EDF4FF"),
|
||||
"warning": ("#AD640C", "#FFF5E5"), "danger": ("#BE4657", "#FFF0F2"),
|
||||
}.get(kind, ("#5D6B80", "#F5F8FD"))
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
label = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, max(1, rect.width() - 12))
|
||||
@@ -919,7 +918,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate):
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setPen(QColor("#5D6B80"))
|
||||
second_rect = first_rect.translated(0, 26)
|
||||
painter.drawText(second_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, painter.fontMetrics().elidedText(secondary, Qt.TextElideMode.ElideRight, rect.width()))
|
||||
else:
|
||||
@@ -943,11 +942,11 @@ class _PrescriptionNumberBlueDelegate(_PrescriptionNumberDelegate):
|
||||
text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)
|
||||
document.setDefaultTextOption(text_option)
|
||||
paragraphs = [
|
||||
f'<p style="margin:0;color:{PALETTE["text"]};font-size:14px;font-weight:400">{escape(number)}</p>',
|
||||
f'<p style="margin:6px 0 0;color:{PALETTE["muted"]};font-size:13px;font-weight:400">ID: {escape(record_id)}</p>',
|
||||
f'<p style="margin:0;color:#273244;font-size:14px;font-weight:400">{escape(number)}</p>',
|
||||
f'<p style="margin:6px 0 0;color:#5D6B80;font-size:13px;font-weight:400">ID: {escape(record_id)}</p>',
|
||||
]
|
||||
paragraphs.extend(
|
||||
f'<p style="margin:6px 0 0;color:{PALETTE["danger"]};font-size:13px;font-weight:400">' + escape(warning) + "</p>"
|
||||
'<p style="margin:6px 0 0;color:#BE4657;font-size:13px;font-weight:400">' + escape(warning) + "</p>"
|
||||
for warning in _order_warnings(row)
|
||||
)
|
||||
document.setHtml("".join(paragraphs))
|
||||
@@ -977,7 +976,7 @@ class _PrescriptionBlueTable(SortableTable):
|
||||
for button in widget.findChildren(QPushButton):
|
||||
kind = {"查看处方": "eye", "编辑处方": "pencil", "删除处方": "trash"}.get(button.accessibleName())
|
||||
if kind:
|
||||
button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"]))
|
||||
button.setIcon(_blue_prescription_icon(kind, "#BE4657" if kind == "trash" else "#1769E8"))
|
||||
|
||||
|
||||
class PrescriptionsPage(QWidget):
|
||||
@@ -1061,7 +1060,7 @@ class PrescriptionsPage(QWidget):
|
||||
self.add_button.setObjectName("PrescriptionAddButton")
|
||||
self.add_button.setMinimumWidth(122)
|
||||
self.add_button.setProperty("variant", "primary")
|
||||
self.add_button.setIcon(_blue_prescription_icon("plus", PALETTE["surface"]))
|
||||
self.add_button.setIcon(_blue_prescription_icon("plus", "#FFFFFF"))
|
||||
self.add_button.setIconSize(QSize(15, 15))
|
||||
self.add_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.add_button.setVisible(has_permission(permissions, "cf.prescription/add"))
|
||||
@@ -1080,7 +1079,7 @@ class PrescriptionsPage(QWidget):
|
||||
self.table_card = table_card
|
||||
root.addWidget(table_card, 1)
|
||||
for button, kind in ((self.view_button, "eye"), (self.edit_button, "pencil"), (self.delete_button, "trash")):
|
||||
button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"]))
|
||||
button.setIcon(_blue_prescription_icon(kind, "#BE4657" if kind == "trash" else "#1769E8"))
|
||||
self._load_doctor_options()
|
||||
|
||||
def _build_filters(self) -> QWidget:
|
||||
@@ -1227,7 +1226,7 @@ class PrescriptionsPage(QWidget):
|
||||
refresh = QPushButton("刷新")
|
||||
refresh.setProperty("variant", "ghost")
|
||||
refresh.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
refresh.setIcon(_blue_prescription_icon("refresh", PALETTE["muted"]))
|
||||
refresh.setIcon(_blue_prescription_icon("refresh", "#5D6B80"))
|
||||
refresh.setIconSize(QSize(15, 15))
|
||||
refresh.clicked.connect(self.refresh)
|
||||
toolbar.addWidget(refresh)
|
||||
@@ -1288,7 +1287,7 @@ class PrescriptionsPage(QWidget):
|
||||
self.table.setItemDelegate(_PrescriptionInfoDelegate(self.table))
|
||||
self.table.setItemDelegateForColumn(1, _PrescriptionNumberBlueDelegate(self.table))
|
||||
self.table.horizontalHeader().sectionResized.connect(self._number_column_resized)
|
||||
self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", PALETTE["disabled"], 14))
|
||||
self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", "#8A97A9", 14))
|
||||
self.table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.table.itemSelectionChanged.connect(self._selection_changed)
|
||||
self.table.itemDoubleClicked.connect(lambda _item: self._view_selected())
|
||||
@@ -1538,7 +1537,7 @@ class PrescriptionsPage(QWidget):
|
||||
|
||||
sn_item = self.table.item(row_index, 1)
|
||||
if sn_item is not None:
|
||||
sn_item.setForeground(QColor(PALETTE["heading"]))
|
||||
sn_item.setForeground(QColor("#1A1C1F"))
|
||||
font = sn_item.font()
|
||||
font.setWeight(QFont.Weight.Normal)
|
||||
sn_item.setFont(font)
|
||||
|
||||
@@ -75,7 +75,6 @@ from PySide6.QtWidgets import (
|
||||
|
||||
from ...core.appointment_modes import appointment_type_description, appointment_type_value
|
||||
from .. import icons
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..diagnosis_drawer import DailyRecordPanel
|
||||
from ..diagnosis_editors import FlowLayout
|
||||
from ..dialogs import DiagnosisDialog
|
||||
@@ -2021,7 +2020,7 @@ def _painted_reception_tab_icon(kind: str, size: int = 16) -> QIcon:
|
||||
outline (bubble / chart page / capsule / clipboard / calendar-clock).
|
||||
"""
|
||||
|
||||
return icons.icon(kind, PALETTE["muted"], size)
|
||||
return icons.icon(kind, "#5D6B80", size)
|
||||
|
||||
|
||||
def _painted_reception_action_icon(kind: str, color: str, size: int = 14) -> QIcon:
|
||||
@@ -2883,7 +2882,7 @@ class _ReceptionSparkIcon(QWidget):
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
glyph = icons.pixmap("ai", PALETTE["accent"], 18)
|
||||
glyph = icons.pixmap("ai", "#1769E8", 18)
|
||||
painter.drawPixmap(QRectF(0, 0, 18, 18), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -2897,9 +2896,9 @@ class _ReceptionAiSectionIcon(QWidget):
|
||||
|
||||
#: Section tone -> (plate, glyph tint, shared glyph name).
|
||||
_TONES = {
|
||||
"diagnosis": (PALETTE["accent_soft"], PALETTE["accent"], "report"),
|
||||
"risk": (PALETTE["accent_soft"], PALETTE["accent"], "alert"),
|
||||
"treatment": (PALETTE["accent_soft"], PALETTE["accent"], "meds"),
|
||||
"diagnosis": ("#EAF2FF", "#1769E8", "report"),
|
||||
"risk": ("#EAF2FF", "#1769E8", "alert"),
|
||||
"treatment": ("#EAF2FF", "#1769E8", "meds"),
|
||||
}
|
||||
|
||||
def __init__(self, tone: str, parent: QWidget | None = None) -> None:
|
||||
@@ -2950,9 +2949,9 @@ class _ReceptionAssistantIcon(QWidget):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent"]))
|
||||
painter.setBrush(QColor("#1769E8"))
|
||||
painter.drawRoundedRect(QRectF(1, 1, 22, 22), 4, 4)
|
||||
painter.setPen(QColor(PALETTE["surface"]))
|
||||
painter.setPen(QColor("#FFFFFF"))
|
||||
font = painter.font()
|
||||
font.setPixelSize(11)
|
||||
font.setBold(True)
|
||||
@@ -2976,7 +2975,7 @@ class _ReceptionSendButton(QPushButton):
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(
|
||||
QPen(
|
||||
QColor(PALETTE["surface"]),
|
||||
QColor("#FFFFFF"),
|
||||
1.8,
|
||||
Qt.PenStyle.SolidLine,
|
||||
Qt.PenCapStyle.RoundCap,
|
||||
@@ -3054,7 +3053,7 @@ class _ReceptionDateButton(QPushButton):
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
color = QColor(PALETTE["muted"])
|
||||
color = QColor("#5D6B80")
|
||||
painter.setPen(
|
||||
QPen(
|
||||
color,
|
||||
@@ -3088,7 +3087,7 @@ class _ReceptionAiExpandButton(QPushButton):
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
color = QColor(PALETTE["accent"] if self.isEnabled() else PALETTE["disabled"])
|
||||
color = QColor("#1769E8" if self.isEnabled() else "#8E8F90")
|
||||
painter.setPen(
|
||||
QPen(
|
||||
color,
|
||||
@@ -3121,7 +3120,7 @@ class _ReceptionAiModelCombo(QComboBox):
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
color = QColor(PALETTE["text"] if self.isEnabled() else PALETTE["disabled"])
|
||||
color = QColor("#273244" if self.isEnabled() else "#8E8F90")
|
||||
painter.setPen(
|
||||
QPen(
|
||||
color,
|
||||
@@ -3163,7 +3162,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
|
||||
self.resize(920, 760)
|
||||
self.setMinimumSize(720, 560)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
|
||||
self.setStyleSheet(clinical_stylesheet(RECEPTION_AI_DIALOG_QSS))
|
||||
self.setStyleSheet(RECEPTION_AI_DIALOG_QSS)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(18, 18, 18, 18)
|
||||
@@ -3366,11 +3365,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
|
||||
source_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
source_label.setWordWrap(True)
|
||||
source_label.setStyleSheet(clinical_stylesheet(
|
||||
"color: $ds_muted; font-size: 12px; padding: 10px 14px; "
|
||||
"background: $ds_surface_alt; border: 1px solid $ds_line; "
|
||||
"border-radius: $ds_radius_control;"
|
||||
))
|
||||
source_label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;")
|
||||
body_layout.addWidget(source_label)
|
||||
self.source_label = source_label
|
||||
body_layout.addStretch(1)
|
||||
@@ -3619,9 +3614,9 @@ class _VitalMetricIcon(QWidget):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"]))
|
||||
painter.setBrush(QColor("#EAF2FF"))
|
||||
painter.drawRoundedRect(QRectF(0, 0, 22, 22), 6, 6)
|
||||
glyph = icons.pixmap(self._GLYPHS.get(self._kind, "pulse"), PALETTE["accent"], 15)
|
||||
glyph = icons.pixmap(self._GLYPHS.get(self._kind, "pulse"), "#1769E8", 15)
|
||||
painter.drawPixmap(QRectF(3.5, 3.5, 15, 15), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -3641,7 +3636,7 @@ class _LifestyleIcon(QWidget):
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
glyph = icons.pixmap(self._GLYPHS.get(self._kind, "exercise"), PALETTE["muted"], 16)
|
||||
glyph = icons.pixmap(self._GLYPHS.get(self._kind, "exercise"), "#5D6B80", 16)
|
||||
painter.drawPixmap(QRectF(0, 0, 16, 16), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -3677,7 +3672,7 @@ class _GenderMark(QWidget):
|
||||
return
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
pen = QPen(QColor(PALETTE["muted"]), 1.35)
|
||||
pen = QPen(QColor("#5D6B80"), 1.35)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
|
||||
painter.setPen(pen)
|
||||
@@ -3742,7 +3737,7 @@ class _ReceptionQueueSpinner(QWidget):
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
pen = QPen(QColor(PALETTE["accent"]), 2.2)
|
||||
pen = QPen(QColor("#1769E8"), 2.2)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
painter.setPen(pen)
|
||||
painter.drawArc(QRectF(2, 2, 14, 14), self._angle * 16, 250 * 16)
|
||||
@@ -3878,15 +3873,15 @@ class QueueRow(QWidget):
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
if self._selected:
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"]))
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
|
||||
painter.setBrush(QColor("#EAF2FF"))
|
||||
painter.setPen(QPen(QColor("#E5ECF6"), 1))
|
||||
else:
|
||||
painter.setBrush(QColor(PALETTE["surface"]))
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
|
||||
painter.drawRoundedRect(rect, 10, 10)
|
||||
painter.setBrush(QColor("#FFFFFF"))
|
||||
painter.setPen(QPen(QColor("#E5ECF6"), 1))
|
||||
painter.drawRoundedRect(rect, 6, 6)
|
||||
if self._selected:
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent"]))
|
||||
painter.setBrush(QColor("#1769E8"))
|
||||
painter.drawRoundedRect(QRectF(1.2, 1, 3.2, self.height() - 2), 1.6, 1.6)
|
||||
|
||||
|
||||
@@ -4079,7 +4074,7 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel):
|
||||
font = item.font()
|
||||
font.setWeight(QFont.Weight.DemiBold if high else QFont.Weight.Normal)
|
||||
item.setFont(font)
|
||||
item.setForeground(QBrush(QColor(PALETTE["danger"] if high else PALETTE["text"])))
|
||||
item.setForeground(QBrush(QColor("#BE4B58" if high else "#273244")))
|
||||
item.setBackground(
|
||||
QBrush(
|
||||
QColor(
|
||||
@@ -4108,11 +4103,9 @@ class ReceptionPage(QWidget):
|
||||
super().__init__(parent)
|
||||
self.setObjectName("ReceptionPage")
|
||||
self.setStyleSheet(
|
||||
clinical_stylesheet(
|
||||
(RECEPTION_QSS + RECEPTION_WORKSPACE_QSS).replace("$body_family", body_family())
|
||||
.replace("$heading_family", heading_family())
|
||||
.replace("$number_family", number_family())
|
||||
)
|
||||
(RECEPTION_QSS + RECEPTION_WORKSPACE_QSS).replace("$body_family", body_family())
|
||||
.replace("$heading_family", heading_family())
|
||||
.replace("$number_family", number_family())
|
||||
)
|
||||
self.repository = repository
|
||||
self.permissions = permissions
|
||||
@@ -4269,7 +4262,7 @@ class ReceptionPage(QWidget):
|
||||
header_layout.addWidget(title)
|
||||
header_layout.addStretch(1)
|
||||
self.refresh_button = QPushButton("", header)
|
||||
self.refresh_button.setIcon(icons.icon("refresh", PALETTE["muted"], 18))
|
||||
self.refresh_button.setIcon(icons.icon("refresh", "#5D6B80", 18))
|
||||
self.refresh_button.setObjectName("ReceptionRefreshButton")
|
||||
self.refresh_button.setFixedSize(34, 32)
|
||||
self.refresh_button.setAccessibleName("刷新接诊台")
|
||||
@@ -4461,7 +4454,7 @@ class ReceptionPage(QWidget):
|
||||
self.video_button.clicked.connect(self._request_video)
|
||||
actions.addWidget(self.video_button)
|
||||
self.more_button = QPushButton(hero)
|
||||
self.more_button.setIcon(icons.icon("more", PALETTE["muted"], 16))
|
||||
self.more_button.setIcon(icons.icon("more", "#5D6B80", 16))
|
||||
self.more_button.setIconSize(QSize(16, 16))
|
||||
self.more_button.setToolTip("更多操作")
|
||||
self.more_button.setAccessibleName("更多操作")
|
||||
@@ -5293,9 +5286,7 @@ class ReceptionPage(QWidget):
|
||||
self.ai_source_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self.ai_source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
self.ai_source_label.setWordWrap(True)
|
||||
self.ai_source_label.setStyleSheet(clinical_stylesheet(
|
||||
"color: $ds_muted; font-size: 12px;"
|
||||
))
|
||||
self.ai_source_label.setStyleSheet("color: #5B6474; font-size: 11px;")
|
||||
analysis_layout.addWidget(self.ai_source_label)
|
||||
|
||||
self.ai_detail_actions_host = QWidget(analysis_card)
|
||||
|
||||
@@ -1,126 +1,119 @@
|
||||
"""Scoped surfaces for the approved patient order-management workspace."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family
|
||||
|
||||
|
||||
def patient_orders_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_ORDERS).safe_substitute(body=body_family()))
|
||||
|
||||
|
||||
_ORDERS = """
|
||||
#PatientOrdersWorkspace { background: transparent; color: $ds_text; }
|
||||
#OrderWorkspaceContent, #OrderWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QLabel, #PatientOrdersWorkspace QPushButton,
|
||||
#PatientOrdersWorkspace QToolButton, #PatientOrdersWorkspace QLineEdit,
|
||||
#PatientOrdersWorkspace QComboBox, #PatientOrdersWorkspace QDateEdit,
|
||||
#PatientOrdersWorkspace QCheckBox, #PatientOrdersWorkspace QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QLabel[role="muted"] { font-size: 13px; color: $ds_muted; }
|
||||
#PatientOrdersWorkspace QFrame#OrderFilterCard,
|
||||
#PatientOrdersWorkspace QFrame#OrderTableCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PatientOrdersWorkspace QFrame#OrderSummaryStrip { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid transparent;
|
||||
border-radius: $ds_radius_control; background: $ds_surface_alt; color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover {
|
||||
background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: $ds_accent_soft; }
|
||||
#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: $ds_focus; }
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton {
|
||||
color: $ds_surface; background: $ds_accent; border-color: $ds_accent;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; }
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:pressed,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:pressed { background: $ds_accent_pressed; border-color: $ds_accent_pressed; }
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:focus,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:focus { border-color: $ds_focus; }
|
||||
#PatientOrdersWorkspace QPushButton:disabled, #PatientOrdersWorkspace QToolButton:disabled,
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:disabled,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
}
|
||||
#PatientOrdersWorkspace QLineEdit, #PatientOrdersWorkspace QComboBox,
|
||||
#PatientOrdersWorkspace QDateEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 10px; font-size: 13px;
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QLineEdit:focus, #PatientOrdersWorkspace QComboBox:focus,
|
||||
#PatientOrdersWorkspace QDateEdit:focus { border-color: $ds_focus; }
|
||||
#PatientOrdersWorkspace QLineEdit QToolButton {
|
||||
min-height: 0; max-height: 24px; min-width: 0; border: 0; padding: 0; background: transparent;
|
||||
}
|
||||
#PatientOrdersWorkspace QComboBox { padding-right: 30px; }
|
||||
#PatientOrdersWorkspace QComboBox::drop-down { border: 0; width: 28px; background: transparent; }
|
||||
#PatientOrdersWorkspace QComboBox::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent;
|
||||
}
|
||||
#PatientOrdersWorkspace QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PatientOrdersWorkspace QDateEdit { padding-right: 26px; }
|
||||
#PatientOrdersWorkspace QDateEdit::drop-down { border: 0; width: 24px; background: transparent; }
|
||||
#PatientOrdersWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QDateEdit:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; }
|
||||
#PatientOrdersWorkspace QCalendarWidget {
|
||||
font-family: "$body"; font-size: 13px; background: $ds_surface; color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QCalendarWidget QWidget#qt_calendar_navigationbar { background: $ds_surface_alt; }
|
||||
#PatientOrdersWorkspace QCalendarWidget QToolButton {
|
||||
min-height: 28px; max-height: 28px; padding: 0 8px; border: 0; background: transparent;
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QCalendarWidget QToolButton:hover { background: $ds_accent_soft; }
|
||||
#PatientOrdersWorkspace QCalendarWidget QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
color: $ds_text; selection-background-color: $ds_accent; selection-color: $ds_surface; outline: 0;
|
||||
}
|
||||
#PatientOrdersWorkspace QCheckBox { spacing: 9px; font-size: 13px; }
|
||||
#PatientOrdersWorkspace QCheckBox::indicator {
|
||||
width: 15px; height: 15px; border: 1px solid $ds_line_strong; border-radius: 3px; background: $ds_surface;
|
||||
}
|
||||
#PatientOrdersWorkspace QCheckBox::indicator:checked { background: $ds_accent; border-color: $ds_accent; }
|
||||
#PatientOrdersWorkspace QCheckBox::indicator:hover { border-color: $ds_focus; }
|
||||
#PatientOrdersWorkspace QCheckBox:focus { color: $ds_accent; }
|
||||
#PatientOrdersWorkspace QFrame#OrderMetricCell { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QFrame#OrderMetricDivider { border: 0; background: $ds_line; }
|
||||
#PatientOrdersWorkspace QLabel[orderMetricCaption="true"] { color: $ds_muted; font-size: 13px; }
|
||||
#PatientOrdersWorkspace QLabel[orderMetricValue="true"] { color: $ds_text; font-size: 18px; font-weight: 500; }
|
||||
#PatientOrdersWorkspace QLabel#OrderAmountMetric { color: $ds_accent; }
|
||||
#PatientOrdersWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable {
|
||||
border: 0; border-radius: 0; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable::item { padding: 0; border: 0; }
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable QHeaderView::section {
|
||||
min-height: 44px; padding: 0 16px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientOrdersWorkspace QWidget#OrderActionBar { background: $ds_surface; }
|
||||
#PatientOrdersWorkspace QToolButton#OrderActionButton { padding-right: 28px; }
|
||||
#PatientOrdersWorkspace QToolButton#OrderActionButton::menu-indicator { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PatientOrdersWorkspace QMenu, QMenu#OrderActionMenu {
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; padding: 5px;
|
||||
}
|
||||
#PatientOrdersWorkspace QMenu::item, QMenu#OrderActionMenu::item { padding: 8px 24px; }
|
||||
#PatientOrdersWorkspace QMenu::item:selected, QMenu#OrderActionMenu::item:selected { color: $ds_accent; background: $ds_accent_soft; }
|
||||
#PatientOrdersWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientOrdersWorkspace QScrollBar::add-line, #PatientOrdersWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar::add-page, #PatientOrdersWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
"""Scoped surfaces for the approved patient order-management workspace."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .reception_style import body_family
|
||||
|
||||
|
||||
def patient_orders_stylesheet() -> str:
|
||||
return Template(_ORDERS).substitute(body=body_family())
|
||||
|
||||
|
||||
_ORDERS = """
|
||||
#PatientOrdersWorkspace { background: transparent; color: #273244; }
|
||||
#OrderWorkspaceContent, #OrderWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QLabel, #PatientOrdersWorkspace QPushButton,
|
||||
#PatientOrdersWorkspace QToolButton, #PatientOrdersWorkspace QLineEdit,
|
||||
#PatientOrdersWorkspace QComboBox, #PatientOrdersWorkspace QDateEdit,
|
||||
#PatientOrdersWorkspace QCheckBox, #PatientOrdersWorkspace QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QLabel[role="muted"] { font-size: 13px; color: #5D6B80; }
|
||||
#PatientOrdersWorkspace QFrame#OrderFilterCard,
|
||||
#PatientOrdersWorkspace QFrame#OrderSummaryStrip,
|
||||
#PatientOrdersWorkspace QFrame#OrderTableCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid #DBE5F2;
|
||||
border-radius: 5px; background: #FFFFFF; color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover {
|
||||
background: #F2F7FF; border-color: #B6CDEE; color: #1555B6;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: #DCEAFF; }
|
||||
#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: #75A5F0; }
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton {
|
||||
color: #FFFFFF; background: #1769E8; border-color: #1769E8;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: #155BCC; border-color: #155BCC; }
|
||||
#PatientOrdersWorkspace QPushButton:disabled, #PatientOrdersWorkspace QToolButton:disabled {
|
||||
color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#PatientOrdersWorkspace QLineEdit, #PatientOrdersWorkspace QComboBox,
|
||||
#PatientOrdersWorkspace QDateEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 10px; font-size: 13px;
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 5px;
|
||||
selection-background-color: #DCEAFF; selection-color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QLineEdit:focus, #PatientOrdersWorkspace QComboBox:focus,
|
||||
#PatientOrdersWorkspace QDateEdit:focus { border-color: #75A5F0; }
|
||||
#PatientOrdersWorkspace QLineEdit QToolButton {
|
||||
min-height: 0; max-height: 24px; min-width: 0; border: 0; padding: 0; background: transparent;
|
||||
}
|
||||
#PatientOrdersWorkspace QComboBox { padding-right: 30px; }
|
||||
#PatientOrdersWorkspace QComboBox::drop-down { border: 0; width: 28px; background: transparent; }
|
||||
#PatientOrdersWorkspace QComboBox::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6;
|
||||
}
|
||||
#PatientOrdersWorkspace QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PatientOrdersWorkspace QDateEdit { padding-right: 26px; }
|
||||
#PatientOrdersWorkspace QDateEdit::drop-down { border: 0; width: 24px; background: transparent; }
|
||||
#PatientOrdersWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QDateEdit:disabled { color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; }
|
||||
#PatientOrdersWorkspace QCalendarWidget {
|
||||
font-family: "$body"; font-size: 13px; background: #FFFFFF; color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QCalendarWidget QWidget#qt_calendar_navigationbar { background: #F5F8FD; }
|
||||
#PatientOrdersWorkspace QCalendarWidget QToolButton {
|
||||
min-height: 28px; max-height: 28px; padding: 0 8px; border: 0; background: transparent;
|
||||
font-family: "$body"; font-size: 13px; color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QCalendarWidget QToolButton:hover { background: #EAF2FF; }
|
||||
#PatientOrdersWorkspace QCalendarWidget QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
color: #273244; selection-background-color: #1769E8; selection-color: #FFFFFF; outline: 0;
|
||||
}
|
||||
#PatientOrdersWorkspace QCheckBox { spacing: 9px; font-size: 13px; }
|
||||
#PatientOrdersWorkspace QCheckBox::indicator {
|
||||
width: 15px; height: 15px; border: 1px solid #C5D5EB; border-radius: 3px; background: #FFFFFF;
|
||||
}
|
||||
#PatientOrdersWorkspace QCheckBox::indicator:checked { background: #1769E8; border-color: #1769E8; }
|
||||
#PatientOrdersWorkspace QCheckBox::indicator:hover { border-color: #75A5F0; }
|
||||
#PatientOrdersWorkspace QCheckBox:focus { color: #1555B6; }
|
||||
#PatientOrdersWorkspace QFrame#OrderMetricCell { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QFrame#OrderMetricDivider { border: 0; background: #DBE5F2; }
|
||||
#PatientOrdersWorkspace QLabel[orderMetricCaption="true"] { color: #5D6B80; font-size: 13px; }
|
||||
#PatientOrdersWorkspace QLabel[orderMetricValue="true"] { color: #273244; font-size: 18px; font-weight: 500; }
|
||||
#PatientOrdersWorkspace QLabel#OrderAmountMetric { color: #1769E8; }
|
||||
#PatientOrdersWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable {
|
||||
border: 1px solid #E6EDF6; border-radius: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
selection-background-color: #F5F8FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable::item { padding: 0; border: 0; }
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable QHeaderView::section {
|
||||
min-height: 44px; padding: 0 16px; background: #F8FAFD; color: #5D6B80;
|
||||
border: 0; border-bottom: 1px solid #E1E9F4;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientOrdersWorkspace QWidget#OrderActionBar { background: #FFFFFF; }
|
||||
#PatientOrdersWorkspace QToolButton#OrderActionButton { padding-right: 28px; }
|
||||
#PatientOrdersWorkspace QToolButton#OrderActionButton::menu-indicator { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PatientOrdersWorkspace QMenu, QMenu#OrderActionMenu {
|
||||
font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; padding: 5px;
|
||||
}
|
||||
#PatientOrdersWorkspace QMenu::item, QMenu#OrderActionMenu::item { padding: 8px 24px; }
|
||||
#PatientOrdersWorkspace QMenu::item:selected, QMenu#OrderActionMenu::item:selected { color: #1555B6; background: #EAF2FF; }
|
||||
#PatientOrdersWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientOrdersWorkspace QScrollBar::add-line, #PatientOrdersWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar::add-page, #PatientOrdersWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
@@ -1,55 +1,54 @@
|
||||
"""Local typography and surfaces for the approved consultation-progress page."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family
|
||||
|
||||
|
||||
def patient_progress_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_PROGRESS).safe_substitute(body=body_family()))
|
||||
|
||||
|
||||
_PROGRESS = """
|
||||
#PatientProgressWorkspace { background: transparent; color: $ds_text; }
|
||||
#ProgressWorkspaceContent, #ProgressWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QLabel, #PatientProgressWorkspace QPushButton,
|
||||
#PatientProgressWorkspace QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PatientProgressWorkspace QLabel[role="muted"] { font-size: 13px; color: $ds_muted; }
|
||||
#PatientProgressWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
|
||||
#PatientProgressWorkspace QLabel#EmptyStateGlyph {
|
||||
font-size: 24px; color: $ds_accent; background: $ds_surface_alt;
|
||||
border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PatientProgressWorkspace QFrame#ProgressScheduleCard,
|
||||
#PatientProgressWorkspace QFrame#ProgressQueueCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PatientProgressWorkspace QFrame#ProgressOverviewCard { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QFrame#ProgressMetricCell { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QFrame#ProgressMetricDivider { background: $ds_line; border: 0; }
|
||||
#PatientProgressWorkspace QLabel[progressMetricValue="true"] { font-size: 18px; font-weight: 500; color: $ds_text; }
|
||||
#PatientProgressWorkspace QLabel#ProgressTotalMetric { color: $ds_accent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter { background: transparent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter::handle { background: transparent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter::handle:hover { background: $ds_accent_soft; }
|
||||
#PatientProgressWorkspace QTableWidget#ProgressScheduleTable,
|
||||
#PatientProgressWorkspace QTableWidget#ProgressQueueTable {
|
||||
border: 0; border-radius: 0; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PatientProgressWorkspace QTableWidget::item { border: 0; padding: 0; }
|
||||
#PatientProgressWorkspace QHeaderView::section {
|
||||
min-height: 0; padding: 0 16px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientProgressWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PatientProgressWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PatientProgressWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PatientProgressWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientProgressWorkspace QScrollBar::add-line, #PatientProgressWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientProgressWorkspace QScrollBar::add-page, #PatientProgressWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
"""Local typography and surfaces for the approved consultation-progress page."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .reception_style import body_family
|
||||
|
||||
|
||||
def patient_progress_stylesheet() -> str:
|
||||
return Template(_PROGRESS).substitute(body=body_family())
|
||||
|
||||
|
||||
_PROGRESS = """
|
||||
#PatientProgressWorkspace { background: transparent; color: #273244; }
|
||||
#ProgressWorkspaceContent, #ProgressWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QLabel, #PatientProgressWorkspace QPushButton,
|
||||
#PatientProgressWorkspace QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PatientProgressWorkspace QLabel[role="muted"] { font-size: 13px; color: #5D6B80; }
|
||||
#PatientProgressWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
|
||||
#PatientProgressWorkspace QLabel#EmptyStateGlyph {
|
||||
font-size: 24px; color: #1769E8; background: #F2F7FF;
|
||||
border: 1px solid #DBE5F2; border-radius: 22px;
|
||||
}
|
||||
#PatientProgressWorkspace QFrame#ProgressOverviewCard,
|
||||
#PatientProgressWorkspace QFrame#ProgressScheduleCard,
|
||||
#PatientProgressWorkspace QFrame#ProgressQueueCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PatientProgressWorkspace QFrame#ProgressMetricCell { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QFrame#ProgressMetricDivider { background: #DBE5F2; border: 0; }
|
||||
#PatientProgressWorkspace QLabel[progressMetricValue="true"] { font-size: 18px; font-weight: 500; color: #273244; }
|
||||
#PatientProgressWorkspace QLabel#ProgressTotalMetric { color: #1769E8; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter { background: transparent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter::handle { background: transparent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter::handle:hover { background: #EAF2FF; }
|
||||
#PatientProgressWorkspace QTableWidget#ProgressScheduleTable,
|
||||
#PatientProgressWorkspace QTableWidget#ProgressQueueTable {
|
||||
border: 0; border-radius: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PatientProgressWorkspace QTableWidget::item { border: 0; padding: 0; }
|
||||
#PatientProgressWorkspace QHeaderView::section {
|
||||
min-height: 0; padding: 0 16px; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-bottom: 1px solid #E1E9F4;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientProgressWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PatientProgressWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PatientProgressWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PatientProgressWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientProgressWorkspace QScrollBar::add-line, #PatientProgressWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientProgressWorkspace QScrollBar::add-page, #PatientProgressWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
@@ -1,154 +1,141 @@
|
||||
"""Quiet clinical surfaces for the patient-list workspace."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def patients_chrome_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_CHROME).safe_substitute(body=body_family(), heading=heading_family()))
|
||||
|
||||
|
||||
def patient_list_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_LIST).safe_substitute(body=body_family()))
|
||||
|
||||
|
||||
_CHROME = """
|
||||
#PatientsPage { background: $ds_canvas; }
|
||||
#PatientsPage QWidget#PageHeader QLabel {
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400; color: $ds_muted;
|
||||
}
|
||||
#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
|
||||
}
|
||||
#PatientsPage QPushButton#PatientRefreshButton {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
min-height: 38px; max-height: 38px; padding: 0 20px;
|
||||
border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt;
|
||||
}
|
||||
#PatientsPage QPushButton#PatientRefreshButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; }
|
||||
#PatientsPage QPushButton#PatientRefreshButton:pressed { background: $ds_accent_soft; }
|
||||
#PatientsPage QPushButton#PatientRefreshButton:focus { border-color: $ds_focus; }
|
||||
#PatientsPage QPushButton#PatientRefreshButton:disabled { color: $ds_disabled; background: $ds_disabled_surface; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane { border: 0; background: transparent; top: 0; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
min-width: 84px; min-height: 42px; padding: 0 10px; margin-right: 22px;
|
||||
border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:selected {
|
||||
color: $ds_accent; border-bottom-color: $ds_accent; background: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:hover { color: $ds_accent; background: $ds_accent_soft; }
|
||||
"""
|
||||
|
||||
_LIST = """
|
||||
#PatientListWorkspace { background: transparent; color: $ds_text; }
|
||||
#PatientWorkspaceContent, #PatientWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientListWorkspace QLabel, #PatientListWorkspace QPushButton,
|
||||
#PatientListWorkspace QToolButton, #PatientListWorkspace QDateEdit,
|
||||
#PatientListWorkspace QTableWidget, #PatientSearchToolbar QLineEdit,
|
||||
#PatientSearchToolbar QPushButton {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PatientListWorkspace QLabel[role="muted"], #PatientListWorkspace QLabel[filterLabel="true"] {
|
||||
color: $ds_muted; font-size: 13px;
|
||||
}
|
||||
#PatientListWorkspace QFrame#PatientFilterCard,
|
||||
#PatientListWorkspace QFrame#PatientListCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PatientListWorkspace QFrame#PatientSummaryStrip { background: transparent; border: 0; }
|
||||
#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px;
|
||||
border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt;
|
||||
}
|
||||
#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover {
|
||||
color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong;
|
||||
}
|
||||
#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: $ds_accent_soft; }
|
||||
#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: $ds_focus; }
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton {
|
||||
min-height: 38px; max-height: 38px; color: $ds_surface; background: $ds_accent; border-color: $ds_accent;
|
||||
}
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: $ds_accent_hover; }
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton:pressed { background: $ds_accent_pressed; }
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton:focus { border-color: $ds_focus; }
|
||||
#PatientSearchToolbar QLineEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 8px; background: $ds_surface;
|
||||
border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft;
|
||||
}
|
||||
#PatientSearchToolbar QLineEdit:focus { border-color: $ds_focus; }
|
||||
#PatientSearchToolbar QLineEdit QToolButton { border: 0; padding: 0; background: transparent; }
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"] {
|
||||
min-height: 44px; max-height: 44px; padding: 0 16px; font-size: 13px;
|
||||
color: $ds_text; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:checked {
|
||||
color: $ds_accent; border-bottom-color: $ds_accent; background: transparent;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:hover { color: $ds_accent; background: $ds_surface_alt; }
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:focus { background: $ds_accent_soft; }
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"] { padding: 0 12px; font-size: 13px; }
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"]:checked,
|
||||
#PatientListWorkspace QPushButton#PatientCustomDateButton:checked {
|
||||
color: $ds_accent; background: $ds_accent_soft; border: 1px solid transparent; font-weight: 600;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"]:focus,
|
||||
#PatientListWorkspace QPushButton#PatientCustomDateButton:focus { border-color: $ds_focus; }
|
||||
#PatientListWorkspace QDateEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 8px; font-size: 13px;
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control;
|
||||
selection-background-color: $ds_accent_soft;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit:focus { border-color: $ds_focus; }
|
||||
#PatientListWorkspace QDateEdit:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit::drop-down { border: 0; width: 20px; background: transparent; }
|
||||
#PatientListWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"] {
|
||||
min-height: 64px; max-height: 64px; padding: 0; background: transparent;
|
||||
border: 1px solid transparent; border-radius: $ds_radius_control;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"]:hover { background: $ds_surface_alt; }
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"]:focus { border-color: $ds_focus; }
|
||||
#PatientListWorkspace QFrame#PatientSummaryDivider { border: 0; background: $ds_line; }
|
||||
#PatientListWorkspace QWidget#PatientListHeading { background: transparent; }
|
||||
#PatientListWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; color: $ds_text; }
|
||||
#PatientListWorkspace QTableWidget#PatientTable {
|
||||
background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PatientListWorkspace QTableWidget#PatientTable::item { padding: 0; border: 0; }
|
||||
#PatientListWorkspace QTableWidget#PatientTable QHeaderView::section {
|
||||
min-height: 41px; padding: 0 10px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-top: 1px solid $ds_line; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientListWorkspace QWidget#RowActions, #PatientListWorkspace QWidget#PatientSelectorHost { background: transparent; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"],
|
||||
#PatientListWorkspace QToolButton#RowActionsMore {
|
||||
min-height: 28px; max-height: 28px; padding: 0 5px; border: 1px solid transparent;
|
||||
border-radius: $ds_radius_small; background: transparent; color: $ds_accent; font-size: 13px;
|
||||
}
|
||||
#PatientListWorkspace QToolButton#RowActionsMore { color: $ds_text; padding-right: 16px; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"]:hover,
|
||||
#PatientListWorkspace QToolButton#RowActionsMore:hover { background: $ds_accent_soft; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"]:focus,
|
||||
#PatientListWorkspace QToolButton#RowActionsMore:focus { border-color: $ds_focus; }
|
||||
#PatientListWorkspace QMenu { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; padding: 4px; }
|
||||
#PatientListWorkspace QMenu::item { padding: 7px 22px; font-size: 13px; }
|
||||
#PatientListWorkspace QMenu::item:selected { background: $ds_accent_soft; color: $ds_accent; }
|
||||
#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator {
|
||||
width: 13px; height: 13px; background: $ds_surface; border: 1px solid $ds_line_strong; border-radius: 3px;
|
||||
}
|
||||
#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator:checked { background: $ds_accent; border-color: $ds_accent; }
|
||||
#PatientListWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PatientListWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PatientListWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PatientListWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientListWorkspace QScrollBar::add-line, #PatientListWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientListWorkspace QScrollBar::add-page, #PatientListWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
"""Scoped technology-blue surfaces for the approved patient-list workspace."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def patients_chrome_stylesheet() -> str:
|
||||
return Template(_CHROME).substitute(body=body_family(), heading=heading_family())
|
||||
|
||||
|
||||
def patient_list_stylesheet() -> str:
|
||||
return Template(_LIST).substitute(body=body_family())
|
||||
|
||||
|
||||
_CHROME = """
|
||||
#PatientsPage { background: #F3F7FD; }
|
||||
#PatientsPage QWidget#PageHeader QLabel {
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400; color: #5D6B80;
|
||||
}
|
||||
#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
|
||||
}
|
||||
#PatientsPage QPushButton#PatientRefreshButton {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
min-height: 38px; max-height: 38px; padding: 0 20px;
|
||||
border: 1px solid #DBE5F2; border-radius: 5px; background: #FFFFFF;
|
||||
}
|
||||
#PatientsPage QPushButton#PatientRefreshButton:hover { background: #F2F7FF; border-color: #B6CDEE; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane { border: 0; background: transparent; top: 0; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
min-width: 84px; min-height: 42px; padding: 0 10px; margin-right: 22px;
|
||||
border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:selected {
|
||||
color: #1769E8; border-bottom-color: #1769E8; background: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:hover { color: #1769E8; background: #EAF2FF; }
|
||||
"""
|
||||
|
||||
_LIST = """
|
||||
#PatientListWorkspace { background: transparent; color: #273244; }
|
||||
#PatientWorkspaceContent, #PatientWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientListWorkspace QLabel, #PatientListWorkspace QPushButton,
|
||||
#PatientListWorkspace QToolButton, #PatientListWorkspace QDateEdit,
|
||||
#PatientListWorkspace QTableWidget, #PatientSearchToolbar QLineEdit,
|
||||
#PatientSearchToolbar QPushButton {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PatientListWorkspace QLabel[role="muted"], #PatientListWorkspace QLabel[filterLabel="true"] {
|
||||
color: #5D6B80; font-size: 13px;
|
||||
}
|
||||
#PatientListWorkspace QFrame#PatientFilterCard,
|
||||
#PatientListWorkspace QFrame#PatientSummaryStrip,
|
||||
#PatientListWorkspace QFrame#PatientListCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px;
|
||||
border: 1px solid #DBE5F2; border-radius: 5px; background: #FFFFFF;
|
||||
}
|
||||
#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover {
|
||||
color: #1555B6; background: #F2F7FF; border-color: #B6CDEE;
|
||||
}
|
||||
#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: #DCEAFF; }
|
||||
#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: #75A5F0; }
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton {
|
||||
min-height: 38px; max-height: 38px; color: #FFFFFF; background: #1769E8; border-color: #1769E8;
|
||||
}
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: #155BCC; }
|
||||
#PatientSearchToolbar QLineEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 8px; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; border-radius: 5px; selection-background-color: #DCEAFF;
|
||||
}
|
||||
#PatientSearchToolbar QLineEdit:focus { border-color: #75A5F0; }
|
||||
#PatientSearchToolbar QLineEdit QToolButton { border: 0; padding: 0; background: transparent; }
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"] {
|
||||
min-height: 44px; max-height: 44px; padding: 0 16px; font-size: 13px;
|
||||
color: #273244; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:checked {
|
||||
color: #1769E8; border-bottom-color: #1769E8; background: transparent;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:hover { color: #1769E8; background: #F2F7FF; }
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"] { padding: 0 12px; font-size: 13px; }
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"]:checked,
|
||||
#PatientListWorkspace QPushButton#PatientCustomDateButton:checked {
|
||||
color: #FFFFFF; background: #1769E8; border: 1px solid #1769E8;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 8px; font-size: 13px;
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 5px;
|
||||
selection-background-color: #DCEAFF;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit:focus { border-color: #75A5F0; }
|
||||
#PatientListWorkspace QDateEdit:disabled {
|
||||
color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit::drop-down { border: 0; width: 20px; background: transparent; }
|
||||
#PatientListWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"] {
|
||||
min-height: 64px; max-height: 64px; padding: 0; background: transparent; border: 0; border-radius: 5px;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"]:hover { background: #F2F7FF; }
|
||||
#PatientListWorkspace QFrame#PatientSummaryDivider { border: 0; background: #E1E9F4; }
|
||||
#PatientListWorkspace QWidget#PatientListHeading { background: transparent; }
|
||||
#PatientListWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; color: #273244; }
|
||||
#PatientListWorkspace QTableWidget#PatientTable {
|
||||
background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
|
||||
selection-background-color: #EAF2FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PatientListWorkspace QTableWidget#PatientTable::item { padding: 0; border: 0; }
|
||||
#PatientListWorkspace QTableWidget#PatientTable QHeaderView::section {
|
||||
min-height: 41px; padding: 0 10px; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-top: 1px solid #E6EDF6; border-bottom: 1px solid #E1E9F4;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientListWorkspace QWidget#RowActions, #PatientListWorkspace QWidget#PatientSelectorHost { background: transparent; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"],
|
||||
#PatientListWorkspace QToolButton#RowActionsMore {
|
||||
min-height: 28px; max-height: 28px; padding: 0 5px; border: 0;
|
||||
border-radius: 4px; background: transparent; color: #1769E8; font-size: 13px;
|
||||
}
|
||||
#PatientListWorkspace QToolButton#RowActionsMore { color: #273244; padding-right: 16px; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"]:hover,
|
||||
#PatientListWorkspace QToolButton#RowActionsMore:hover { background: #DCEAFF; }
|
||||
#PatientListWorkspace QMenu { background: #FFFFFF; color: #273244; border: 1px solid #DBE5F2; padding: 4px; }
|
||||
#PatientListWorkspace QMenu::item { padding: 7px 22px; font-size: 13px; }
|
||||
#PatientListWorkspace QMenu::item:selected { background: #EAF2FF; color: #1555B6; }
|
||||
#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator {
|
||||
width: 13px; height: 13px; background: #FFFFFF; border: 1px solid #CBDAED; border-radius: 3px;
|
||||
}
|
||||
#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator:checked { background: #1769E8; border-color: #1769E8; }
|
||||
#PatientListWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PatientListWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PatientListWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PatientListWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientListWorkspace QScrollBar::add-line, #PatientListWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientListWorkspace QScrollBar::add-page, #PatientListWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
@@ -1,419 +1,410 @@
|
||||
"""Shared clinical tokens for the prescription library and its native delegates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Sequence
|
||||
from string import Template
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QEvent, QModelIndex, QRectF, QSize, Qt, QTimer
|
||||
from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QPushButton,
|
||||
QStyle,
|
||||
QStyledItemDelegate,
|
||||
QToolTip,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .design_system import PALETTE, RADII, clinical_stylesheet
|
||||
from .reception_style import body_family, heading_family
|
||||
from .widgets import SortableTable, TableColumn, first_value
|
||||
|
||||
|
||||
def library_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_LIBRARY).safe_substitute(body=body_family(), heading=heading_family()))
|
||||
|
||||
|
||||
def _library_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon:
|
||||
# Defer the page helper lookup so importing this module alone does not
|
||||
# recurse through pages.__init__ and the library page's own style import.
|
||||
from .pages.prescriptions import _painted_icon
|
||||
|
||||
result = QIcon()
|
||||
for mode, tint in (
|
||||
(QIcon.Mode.Normal, color),
|
||||
(QIcon.Mode.Active, color),
|
||||
(QIcon.Mode.Selected, color),
|
||||
(QIcon.Mode.Disabled, PALETTE["disabled"]),
|
||||
):
|
||||
pixmap = _painted_icon(kind, tint, size).pixmap(QSize(size, size))
|
||||
for state in (QIcon.State.Off, QIcon.State.On):
|
||||
result.addPixmap(pixmap, mode, state)
|
||||
return result
|
||||
|
||||
|
||||
class LibraryComboBox(QComboBox):
|
||||
"""Keep native combo interaction while painting the local caret."""
|
||||
|
||||
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
try:
|
||||
rect = QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14)
|
||||
mode = QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled
|
||||
_library_icon("chevron_down", PALETTE["muted"], 14).paint(painter, rect.toRect(), mode=mode)
|
||||
finally:
|
||||
painter.end()
|
||||
|
||||
|
||||
class LibraryTable(SortableTable):
|
||||
"""Fit readable columns while preserving actions and selected template IDs."""
|
||||
|
||||
_FLEX_COLUMNS = ((1, 2), (4, 5), (5, 2))
|
||||
|
||||
def __init__(self, columns: Sequence[TableColumn], parent: QWidget | None = None) -> None:
|
||||
super().__init__(columns, parent)
|
||||
self.horizontalHeader().setStretchLastSection(False)
|
||||
self._minimum_widths = tuple(column.width for column in self.columns)
|
||||
self._manual_widths: dict[int, int] = {}
|
||||
self._fitting_columns = False
|
||||
self._fit_timer = QTimer(self)
|
||||
self._fit_timer.setSingleShot(True)
|
||||
self._fit_timer.timeout.connect(self._fit_columns)
|
||||
self.horizontalHeader().sectionResized.connect(self._column_resized)
|
||||
self.viewport().installEventFilter(self)
|
||||
|
||||
def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
|
||||
if watched is self.viewport() and event.type() in {QEvent.Type.Resize, QEvent.Type.Show}:
|
||||
self._schedule_column_fit()
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def _schedule_column_fit(self) -> None:
|
||||
if not self._fit_timer.isActive():
|
||||
self._fit_timer.start(0)
|
||||
|
||||
def _column_resized(self, column: int, _old_size: int, size: int) -> None:
|
||||
if self._fitting_columns:
|
||||
return
|
||||
self._manual_widths[column] = max(self._minimum_widths[column], size)
|
||||
self._schedule_column_fit()
|
||||
|
||||
def _fit_columns(self) -> None:
|
||||
widths = [self._manual_widths.get(column, minimum)
|
||||
for column, minimum in enumerate(self._minimum_widths)]
|
||||
extra = max(0, self.viewport().width() - sum(widths))
|
||||
flexible = [(column, weight) for column, weight in self._FLEX_COLUMNS
|
||||
if column not in self._manual_widths]
|
||||
# If every text column was manually sized, keep those preferences as
|
||||
# minimums and let the herb preview absorb any remaining wide-screen space.
|
||||
flexible = flexible or [(4, 1)]
|
||||
total_weight = sum(weight for _column, weight in flexible)
|
||||
for column, weight in flexible:
|
||||
widths[column] += extra * weight // total_weight
|
||||
widths[flexible[0][0]] += max(0, self.viewport().width() - sum(widths))
|
||||
if widths == [self.columnWidth(column) for column in range(self.columnCount())]:
|
||||
return
|
||||
self._fitting_columns = True
|
||||
try:
|
||||
for column, width in enumerate(widths):
|
||||
self.setColumnWidth(column, width)
|
||||
finally:
|
||||
self._fitting_columns = False
|
||||
|
||||
def set_rows(self, rows: Iterable[Any]) -> None:
|
||||
selected_id = first_value(self.current_data(), "id", "template_id", default=None)
|
||||
super().set_rows(rows)
|
||||
# The shared table restores an unsorted row index after enabling sort.
|
||||
# Locate the same source object in the finished visual order instead.
|
||||
if selected_id is not None:
|
||||
for row_index in range(self.rowCount()):
|
||||
item = self.item(row_index, 0)
|
||||
row = item.data(Qt.ItemDataRole.UserRole) if item is not None else None
|
||||
row_id = first_value(row, "id", "template_id", default=None)
|
||||
if row_id is not None and str(row_id) == str(selected_id):
|
||||
self.selectRow(row_index)
|
||||
return
|
||||
self.clearSelection()
|
||||
self.setCurrentCell(-1, -1)
|
||||
|
||||
def setCellWidget(self, row: int, column: int, widget: QWidget | None) -> None: # noqa: N802
|
||||
super().setCellWidget(row, column, widget)
|
||||
if widget is None or column != 9:
|
||||
return
|
||||
widget.setObjectName("PrescriptionLibraryTableCellHost")
|
||||
widget.setAutoFillBackground(False)
|
||||
glyphs = {
|
||||
"查看处方模板": "eye",
|
||||
"AI 解释": "spark",
|
||||
"编辑处方模板": "pencil",
|
||||
"删除处方模板": "trash",
|
||||
}
|
||||
for button in widget.findChildren(QPushButton):
|
||||
if not button.property("rowAction"):
|
||||
continue
|
||||
glyph = glyphs.get(button.accessibleName()) or glyphs.get(button.toolTip())
|
||||
if glyph is not None:
|
||||
color = PALETTE["danger"] if button.property("danger") else PALETTE["accent"]
|
||||
button.setIcon(_library_icon(glyph, color, button.iconSize().width()))
|
||||
|
||||
|
||||
def _library_font(size: int = 14, *, medium: bool = False) -> QFont:
|
||||
font = QFont(heading_family() if medium else body_family())
|
||||
font.setPixelSize(size)
|
||||
font.setWeight(QFont.Weight.Medium if medium else QFont.Weight.Normal)
|
||||
return font
|
||||
|
||||
|
||||
def _elide(text: str, metrics: QFontMetrics, width: int) -> str:
|
||||
return metrics.elidedText(text, Qt.TextElideMode.ElideRight, max(1, width))
|
||||
|
||||
|
||||
def _herb_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
|
||||
"""Wrap between complete herb entries; elide only the displayed lines."""
|
||||
entries = text.split("、")
|
||||
first = entries[0]
|
||||
next_index = 1
|
||||
while next_index < min(2, len(entries)):
|
||||
candidate = first + "、" + entries[next_index]
|
||||
if metrics.horizontalAdvance(candidate) > width:
|
||||
break
|
||||
first = candidate
|
||||
next_index += 1
|
||||
lines = [_elide(first, metrics, width)]
|
||||
if next_index < len(entries):
|
||||
lines.append(_elide("、".join(entries[next_index:]), metrics, width))
|
||||
return lines
|
||||
|
||||
|
||||
def _name_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
|
||||
if metrics.horizontalAdvance(text) <= width:
|
||||
return [text]
|
||||
split = 1
|
||||
while split < len(text) and metrics.horizontalAdvance(text[: split + 1]) <= width:
|
||||
split += 1
|
||||
return [_elide(text[:split], metrics, width), _elide(text[split:], metrics, width)]
|
||||
|
||||
|
||||
class LibraryItemDelegate(QStyledItemDelegate):
|
||||
"""Paint the ten existing columns without changing display or source roles."""
|
||||
|
||||
def sizeHint(self, option: Any, index: QModelIndex) -> QSize: # noqa: N802
|
||||
size = super().sizeHint(option, index)
|
||||
size.setHeight(78)
|
||||
return size
|
||||
|
||||
def helpEvent(self, event: Any, view: Any, option: Any, index: QModelIndex) -> bool: # noqa: N802
|
||||
if event is not None and index.isValid() and index.column() != 9:
|
||||
text = index.data(Qt.ItemDataRole.ToolTipRole) or index.data(Qt.ItemDataRole.DisplayRole)
|
||||
if text:
|
||||
QToolTip.showText(event.globalPos(), str(text), view)
|
||||
return True
|
||||
return super().helpEvent(event, view, option, index)
|
||||
|
||||
@staticmethod
|
||||
def _paint_lines(
|
||||
painter: QPainter,
|
||||
rect: QRectF,
|
||||
lines: list[str],
|
||||
*,
|
||||
secondary_muted: bool = False,
|
||||
) -> None:
|
||||
line_height = 26
|
||||
top = rect.center().y() - len(lines) * line_height / 2
|
||||
for line_index, line in enumerate(lines):
|
||||
if secondary_muted and line_index:
|
||||
painter.setFont(_library_font(13))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
line_rect = QRectF(rect.left(), top + line_index * line_height, rect.width(), line_height)
|
||||
painter.drawText(line_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, line)
|
||||
|
||||
def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None:
|
||||
painter.save()
|
||||
try:
|
||||
painter.setClipRect(option.rect)
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
background = PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]
|
||||
painter.fillRect(option.rect, QColor(background))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
stripe = QRectF(option.rect.left(), option.rect.top(), 3, option.rect.height() - 1)
|
||||
painter.fillRect(stripe, QColor(PALETTE["accent"]))
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setPen(QColor(PALETTE["focus"]))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
|
||||
|
||||
column = index.column()
|
||||
if column == 9:
|
||||
return
|
||||
rect = QRectF(option.rect.adjusted(12, 0, -12, -1))
|
||||
if rect.width() <= 0:
|
||||
return
|
||||
value = index.data(Qt.ItemDataRole.DisplayRole)
|
||||
text = "" if value is None else str(value)
|
||||
font = _library_font(medium=column == 1)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
metrics = QFontMetrics(font)
|
||||
width = int(rect.width())
|
||||
|
||||
if column == 2:
|
||||
painter.setFont(_library_font(13))
|
||||
metrics = painter.fontMetrics()
|
||||
label = _elide(text, metrics, width - 12)
|
||||
pill_width = min(rect.width(), metrics.horizontalAdvance(label) + 14)
|
||||
pill = QRectF(rect.center().x() - pill_width / 2, rect.center().y() - 12, pill_width, 24)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"]))
|
||||
painter.drawRoundedRect(pill, RADII["small"], RADII["small"])
|
||||
painter.setPen(QColor(PALETTE["accent"]))
|
||||
painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label)
|
||||
elif column == 6:
|
||||
glyph = "users" if text == "所有人可见" else "lock"
|
||||
icon_rect = QRectF(rect.left(), rect.center().y() - 7, 14, 14)
|
||||
_library_icon(glyph, PALETTE["muted"], 14).paint(painter, icon_rect.toRect())
|
||||
label_rect = rect.adjusted(22, 0, 0, 0)
|
||||
painter.drawText(
|
||||
label_rect,
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||
_elide(text, metrics, int(label_rect.width())),
|
||||
)
|
||||
elif column == 4:
|
||||
self._paint_lines(painter, rect, _herb_lines(text, metrics, width))
|
||||
elif column == 8:
|
||||
parts = text.splitlines() if "\n" in text else text.rsplit(" ", 1)
|
||||
lines = [_elide(parts[0], metrics, width)]
|
||||
if len(parts) > 1:
|
||||
lines.append(_elide(" ".join(parts[1:]), QFontMetrics(_library_font(13)), width))
|
||||
self._paint_lines(painter, rect, lines, secondary_muted=True)
|
||||
elif column == 1:
|
||||
self._paint_lines(painter, rect, _name_lines(text, metrics, width))
|
||||
else:
|
||||
alignment = Qt.AlignmentFlag.AlignCenter if column in (0, 3, 5) else (
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
)
|
||||
painter.drawText(rect, alignment, _elide(text, metrics, width))
|
||||
finally:
|
||||
painter.restore()
|
||||
|
||||
|
||||
_LIBRARY = """
|
||||
#PrescriptionLibraryPage { background: $ds_canvas; color: $ds_text; }
|
||||
#PrescriptionLibraryPage QWidget#PrescriptionLibraryContent,
|
||||
#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryScroll,
|
||||
#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryToolbarScroll {
|
||||
background: transparent; border: 0;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel, #PrescriptionLibraryPage QPushButton,
|
||||
#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox,
|
||||
#PrescriptionLibraryPage QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[role="muted"] { color: $ds_muted; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar,
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryTableCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard { background: $ds_surface; border: 0; border-radius: $ds_radius_panel; }
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricTitle"] {
|
||||
font-family: "$body"; color: $ds_muted; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricValue"] {
|
||||
font-family: "$heading"; color: $ds_text; font-size: 18px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[metricIcon="true"] {
|
||||
border: 0; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control;
|
||||
border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; }
|
||||
#PrescriptionLibraryPage QPushButton:pressed { background: $ds_accent_soft; }
|
||||
#PrescriptionLibraryPage QPushButton:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton {
|
||||
background: $ds_accent; border-color: $ds_accent; color: $ds_surface;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover {
|
||||
background: $ds_accent_hover; border-color: $ds_accent_hover;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed {
|
||||
background: $ds_accent_pressed; border-color: $ds_accent_pressed;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:focus,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton:disabled,
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:disabled,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:disabled,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
}
|
||||
#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox {
|
||||
min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid $ds_line;
|
||||
border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text;
|
||||
}
|
||||
#PrescriptionLibraryPage QLineEdit:focus, #PrescriptionLibraryPage QComboBox:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QLineEdit QToolButton { border: 0; background: transparent; padding: 0; }
|
||||
#PrescriptionLibraryPage QComboBox { padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QComboBox::drop-down { width: 28px; border: 0; background: transparent; }
|
||||
#PrescriptionLibraryPage QComboBox::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PrescriptionLibraryPage QComboBox:disabled { color: $ds_disabled; background: $ds_disabled_surface; }
|
||||
#PrescriptionLibraryPage QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent;
|
||||
}
|
||||
#PrescriptionLibraryPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar { background: transparent; border: 0; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton { padding: 0 12px; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"] {
|
||||
min-width: 80px; min-height: 40px; max-height: 40px; padding: 0 10px; margin-right: 8px;
|
||||
background: transparent; border: 0; border-bottom: 2px solid transparent;
|
||||
border-radius: 0; color: $ds_text; font-size: 14px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:checked {
|
||||
color: $ds_accent; border-bottom-color: $ds_accent;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:hover {
|
||||
color: $ds_accent; background: $ds_surface_alt;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:focus { background: $ds_accent_soft; }
|
||||
#PrescriptionLibraryPage QTableWidget {
|
||||
border: 0; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PrescriptionLibraryPage QTableWidget::item { padding: 0; border: 0; }
|
||||
#PrescriptionLibraryPage QHeaderView::section {
|
||||
min-height: 0; padding: 0 12px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#PrescriptionLibraryTableCellHost { background: transparent; border: 0; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"] {
|
||||
min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
|
||||
padding: 0; border: 1px solid transparent; border-radius: $ds_radius_small; background: transparent;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:hover { background: $ds_accent_soft; border-color: $ds_line_strong; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:hover { background: $ds_danger_soft; border-color: $ds_danger_soft; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:disabled { background: transparent; border-color: transparent; color: $ds_disabled; }
|
||||
#PrescriptionLibraryPage QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PrescriptionLibraryPage QLabel#EmptyStateGlyph {
|
||||
font-size: 24px; color: $ds_accent; background: $ds_surface_alt;
|
||||
border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
|
||||
#PrescriptionLibraryPage QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PrescriptionLibraryPage QScrollBar::add-line, #PrescriptionLibraryPage QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar::add-page, #PrescriptionLibraryPage QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
|
||||
__all__ = ["library_stylesheet", "LibraryComboBox", "LibraryTable", "LibraryItemDelegate"]
|
||||
"""Local technology-blue rendering for the approved prescription library."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Sequence
|
||||
from string import Template
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QEvent, QModelIndex, QRectF, QSize, Qt, QTimer
|
||||
from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QPushButton,
|
||||
QStyle,
|
||||
QStyledItemDelegate,
|
||||
QToolTip,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .reception_style import body_family, heading_family
|
||||
from .widgets import SortableTable, TableColumn, first_value
|
||||
|
||||
|
||||
def library_stylesheet() -> str:
|
||||
return Template(_LIBRARY).substitute(body=body_family(), heading=heading_family())
|
||||
|
||||
|
||||
def _library_icon(kind: str, color: str = "#1769E8", size: int = 15) -> QIcon:
|
||||
# Defer the page helper lookup so importing this module alone does not
|
||||
# recurse through pages.__init__ and the library page's own style import.
|
||||
from .pages.prescriptions import _painted_icon
|
||||
|
||||
result = QIcon()
|
||||
for mode, tint in (
|
||||
(QIcon.Mode.Normal, color),
|
||||
(QIcon.Mode.Active, color),
|
||||
(QIcon.Mode.Selected, color),
|
||||
(QIcon.Mode.Disabled, "#A4ADBA"),
|
||||
):
|
||||
pixmap = _painted_icon(kind, tint, size).pixmap(QSize(size, size))
|
||||
for state in (QIcon.State.Off, QIcon.State.On):
|
||||
result.addPixmap(pixmap, mode, state)
|
||||
return result
|
||||
|
||||
|
||||
class LibraryComboBox(QComboBox):
|
||||
"""Keep native combo interaction while painting the local caret."""
|
||||
|
||||
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
try:
|
||||
rect = QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14)
|
||||
mode = QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled
|
||||
_library_icon("chevron_down", "#5D6B80", 14).paint(painter, rect.toRect(), mode=mode)
|
||||
finally:
|
||||
painter.end()
|
||||
|
||||
|
||||
class LibraryTable(SortableTable):
|
||||
"""Fit readable columns while preserving actions and selected template IDs."""
|
||||
|
||||
_FLEX_COLUMNS = ((1, 2), (4, 5), (5, 2))
|
||||
|
||||
def __init__(self, columns: Sequence[TableColumn], parent: QWidget | None = None) -> None:
|
||||
super().__init__(columns, parent)
|
||||
self.horizontalHeader().setStretchLastSection(False)
|
||||
self._minimum_widths = tuple(column.width for column in self.columns)
|
||||
self._manual_widths: dict[int, int] = {}
|
||||
self._fitting_columns = False
|
||||
self._fit_timer = QTimer(self)
|
||||
self._fit_timer.setSingleShot(True)
|
||||
self._fit_timer.timeout.connect(self._fit_columns)
|
||||
self.horizontalHeader().sectionResized.connect(self._column_resized)
|
||||
self.viewport().installEventFilter(self)
|
||||
|
||||
def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
|
||||
if watched is self.viewport() and event.type() in {QEvent.Type.Resize, QEvent.Type.Show}:
|
||||
self._schedule_column_fit()
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def _schedule_column_fit(self) -> None:
|
||||
if not self._fit_timer.isActive():
|
||||
self._fit_timer.start(0)
|
||||
|
||||
def _column_resized(self, column: int, _old_size: int, size: int) -> None:
|
||||
if self._fitting_columns:
|
||||
return
|
||||
self._manual_widths[column] = max(self._minimum_widths[column], size)
|
||||
self._schedule_column_fit()
|
||||
|
||||
def _fit_columns(self) -> None:
|
||||
widths = [self._manual_widths.get(column, minimum)
|
||||
for column, minimum in enumerate(self._minimum_widths)]
|
||||
extra = max(0, self.viewport().width() - sum(widths))
|
||||
flexible = [(column, weight) for column, weight in self._FLEX_COLUMNS
|
||||
if column not in self._manual_widths]
|
||||
# If every text column was manually sized, keep those preferences as
|
||||
# minimums and let the herb preview absorb any remaining wide-screen space.
|
||||
flexible = flexible or [(4, 1)]
|
||||
total_weight = sum(weight for _column, weight in flexible)
|
||||
for column, weight in flexible:
|
||||
widths[column] += extra * weight // total_weight
|
||||
widths[flexible[0][0]] += max(0, self.viewport().width() - sum(widths))
|
||||
if widths == [self.columnWidth(column) for column in range(self.columnCount())]:
|
||||
return
|
||||
self._fitting_columns = True
|
||||
try:
|
||||
for column, width in enumerate(widths):
|
||||
self.setColumnWidth(column, width)
|
||||
finally:
|
||||
self._fitting_columns = False
|
||||
|
||||
def set_rows(self, rows: Iterable[Any]) -> None:
|
||||
selected_id = first_value(self.current_data(), "id", "template_id", default=None)
|
||||
super().set_rows(rows)
|
||||
# The shared table restores an unsorted row index after enabling sort.
|
||||
# Locate the same source object in the finished visual order instead.
|
||||
if selected_id is not None:
|
||||
for row_index in range(self.rowCount()):
|
||||
item = self.item(row_index, 0)
|
||||
row = item.data(Qt.ItemDataRole.UserRole) if item is not None else None
|
||||
row_id = first_value(row, "id", "template_id", default=None)
|
||||
if row_id is not None and str(row_id) == str(selected_id):
|
||||
self.selectRow(row_index)
|
||||
return
|
||||
self.clearSelection()
|
||||
self.setCurrentCell(-1, -1)
|
||||
|
||||
def setCellWidget(self, row: int, column: int, widget: QWidget | None) -> None: # noqa: N802
|
||||
super().setCellWidget(row, column, widget)
|
||||
if widget is None or column != 9:
|
||||
return
|
||||
widget.setObjectName("PrescriptionLibraryTableCellHost")
|
||||
widget.setAutoFillBackground(False)
|
||||
glyphs = {
|
||||
"查看处方模板": "eye",
|
||||
"AI 解释": "spark",
|
||||
"编辑处方模板": "pencil",
|
||||
"删除处方模板": "trash",
|
||||
}
|
||||
for button in widget.findChildren(QPushButton):
|
||||
if not button.property("rowAction"):
|
||||
continue
|
||||
glyph = glyphs.get(button.accessibleName()) or glyphs.get(button.toolTip())
|
||||
if glyph is not None:
|
||||
color = "#BE4657" if button.property("danger") else "#1769E8"
|
||||
button.setIcon(_library_icon(glyph, color, button.iconSize().width()))
|
||||
|
||||
|
||||
def _library_font(size: int = 14, *, medium: bool = False) -> QFont:
|
||||
font = QFont(heading_family() if medium else body_family())
|
||||
font.setPixelSize(size)
|
||||
font.setWeight(QFont.Weight.Medium if medium else QFont.Weight.Normal)
|
||||
return font
|
||||
|
||||
|
||||
def _elide(text: str, metrics: QFontMetrics, width: int) -> str:
|
||||
return metrics.elidedText(text, Qt.TextElideMode.ElideRight, max(1, width))
|
||||
|
||||
|
||||
def _herb_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
|
||||
"""Wrap between complete herb entries; elide only the displayed lines."""
|
||||
entries = text.split("、")
|
||||
first = entries[0]
|
||||
next_index = 1
|
||||
while next_index < min(2, len(entries)):
|
||||
candidate = first + "、" + entries[next_index]
|
||||
if metrics.horizontalAdvance(candidate) > width:
|
||||
break
|
||||
first = candidate
|
||||
next_index += 1
|
||||
lines = [_elide(first, metrics, width)]
|
||||
if next_index < len(entries):
|
||||
lines.append(_elide("、".join(entries[next_index:]), metrics, width))
|
||||
return lines
|
||||
|
||||
|
||||
def _name_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
|
||||
if metrics.horizontalAdvance(text) <= width:
|
||||
return [text]
|
||||
split = 1
|
||||
while split < len(text) and metrics.horizontalAdvance(text[: split + 1]) <= width:
|
||||
split += 1
|
||||
return [_elide(text[:split], metrics, width), _elide(text[split:], metrics, width)]
|
||||
|
||||
|
||||
class LibraryItemDelegate(QStyledItemDelegate):
|
||||
"""Paint the ten existing columns without changing display or source roles."""
|
||||
|
||||
def sizeHint(self, option: Any, index: QModelIndex) -> QSize: # noqa: N802
|
||||
size = super().sizeHint(option, index)
|
||||
size.setHeight(78)
|
||||
return size
|
||||
|
||||
def helpEvent(self, event: Any, view: Any, option: Any, index: QModelIndex) -> bool: # noqa: N802
|
||||
if event is not None and index.isValid() and index.column() != 9:
|
||||
text = index.data(Qt.ItemDataRole.ToolTipRole) or index.data(Qt.ItemDataRole.DisplayRole)
|
||||
if text:
|
||||
QToolTip.showText(event.globalPos(), str(text), view)
|
||||
return True
|
||||
return super().helpEvent(event, view, option, index)
|
||||
|
||||
@staticmethod
|
||||
def _paint_lines(
|
||||
painter: QPainter,
|
||||
rect: QRectF,
|
||||
lines: list[str],
|
||||
*,
|
||||
secondary_muted: bool = False,
|
||||
) -> None:
|
||||
line_height = 26
|
||||
top = rect.center().y() - len(lines) * line_height / 2
|
||||
for line_index, line in enumerate(lines):
|
||||
if secondary_muted and line_index:
|
||||
painter.setFont(_library_font(13))
|
||||
painter.setPen(QColor("#5D6B80"))
|
||||
line_rect = QRectF(rect.left(), top + line_index * line_height, rect.width(), line_height)
|
||||
painter.drawText(line_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, line)
|
||||
|
||||
def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None:
|
||||
painter.save()
|
||||
try:
|
||||
painter.setClipRect(option.rect)
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
background = "#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"
|
||||
painter.fillRect(option.rect, QColor(background))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
stripe = QRectF(option.rect.left(), option.rect.top(), 3, option.rect.height() - 1)
|
||||
painter.fillRect(stripe, QColor("#1769E8"))
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setPen(QColor("#75A5F0"))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
|
||||
|
||||
column = index.column()
|
||||
if column == 9:
|
||||
return
|
||||
rect = QRectF(option.rect.adjusted(12, 0, -12, -1))
|
||||
if rect.width() <= 0:
|
||||
return
|
||||
value = index.data(Qt.ItemDataRole.DisplayRole)
|
||||
text = "" if value is None else str(value)
|
||||
font = _library_font(medium=column == 1)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor("#273244"))
|
||||
metrics = QFontMetrics(font)
|
||||
width = int(rect.width())
|
||||
|
||||
if column == 2:
|
||||
painter.setFont(_library_font(13))
|
||||
metrics = painter.fontMetrics()
|
||||
label = _elide(text, metrics, width - 12)
|
||||
pill_width = min(rect.width(), metrics.horizontalAdvance(label) + 14)
|
||||
pill = QRectF(rect.center().x() - pill_width / 2, rect.center().y() - 12, pill_width, 24)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor("#EAF2FF"))
|
||||
painter.drawRoundedRect(pill, 4, 4)
|
||||
painter.setPen(QColor("#1769E8"))
|
||||
painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label)
|
||||
elif column == 6:
|
||||
glyph = "users" if text == "所有人可见" else "lock"
|
||||
icon_rect = QRectF(rect.left(), rect.center().y() - 7, 14, 14)
|
||||
_library_icon(glyph, "#5D6B80", 14).paint(painter, icon_rect.toRect())
|
||||
label_rect = rect.adjusted(22, 0, 0, 0)
|
||||
painter.drawText(
|
||||
label_rect,
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||
_elide(text, metrics, int(label_rect.width())),
|
||||
)
|
||||
elif column == 4:
|
||||
self._paint_lines(painter, rect, _herb_lines(text, metrics, width))
|
||||
elif column == 8:
|
||||
parts = text.splitlines() if "\n" in text else text.rsplit(" ", 1)
|
||||
lines = [_elide(parts[0], metrics, width)]
|
||||
if len(parts) > 1:
|
||||
lines.append(_elide(" ".join(parts[1:]), QFontMetrics(_library_font(13)), width))
|
||||
self._paint_lines(painter, rect, lines, secondary_muted=True)
|
||||
elif column == 1:
|
||||
self._paint_lines(painter, rect, _name_lines(text, metrics, width))
|
||||
else:
|
||||
alignment = Qt.AlignmentFlag.AlignCenter if column in (0, 3, 5) else (
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
)
|
||||
painter.drawText(rect, alignment, _elide(text, metrics, width))
|
||||
finally:
|
||||
painter.restore()
|
||||
|
||||
|
||||
_LIBRARY = """
|
||||
#PrescriptionLibraryPage { background: #F3F7FD; color: #273244; }
|
||||
#PrescriptionLibraryPage QWidget#PrescriptionLibraryContent,
|
||||
#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryScroll,
|
||||
#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryToolbarScroll {
|
||||
background: transparent; border: 0;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel, #PrescriptionLibraryPage QPushButton,
|
||||
#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox,
|
||||
#PrescriptionLibraryPage QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[role="muted"] { color: #5D6B80; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QFrame#MetricCard,
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar,
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryTableCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricTitle"] {
|
||||
font-family: "$body"; color: #5D6B80; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricValue"] {
|
||||
font-family: "$heading"; color: #273244; font-size: 18px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[metricIcon="true"] {
|
||||
border: 0; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: 5px;
|
||||
border: 1px solid #DBE5F2; background: #FFFFFF; color: #273244;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton:hover { background: #F2F7FF; border-color: #B6CDEE; color: #1555B6; }
|
||||
#PrescriptionLibraryPage QPushButton:pressed { background: #DCEAFF; }
|
||||
#PrescriptionLibraryPage QPushButton:focus { border-color: #75A5F0; }
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton {
|
||||
background: #1769E8; border-color: #1769E8; color: #FFFFFF;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover {
|
||||
background: #155BCC; border-color: #155BCC;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed {
|
||||
background: #124EA9; border-color: #124EA9;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"] { color: #BE4657; border-color: #E9D8DE; }
|
||||
#PrescriptionLibraryPage QPushButton:disabled,
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:disabled {
|
||||
color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox {
|
||||
min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid #DBE5F2;
|
||||
border-radius: 5px; background: #FFFFFF; color: #273244;
|
||||
selection-background-color: #DCEAFF; selection-color: #273244;
|
||||
}
|
||||
#PrescriptionLibraryPage QLineEdit:focus, #PrescriptionLibraryPage QComboBox:focus { border-color: #75A5F0; }
|
||||
#PrescriptionLibraryPage QLineEdit QToolButton { border: 0; background: transparent; padding: 0; }
|
||||
#PrescriptionLibraryPage QComboBox { padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QComboBox::drop-down { width: 28px; border: 0; background: transparent; }
|
||||
#PrescriptionLibraryPage QComboBox::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PrescriptionLibraryPage QComboBox:disabled { color: #97A4B6; background: #F6F8FC; }
|
||||
#PrescriptionLibraryPage QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6;
|
||||
}
|
||||
#PrescriptionLibraryPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar { background: transparent; border: 0; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton { padding: 0 12px; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"] {
|
||||
min-width: 80px; min-height: 40px; max-height: 40px; padding: 0 10px; margin-right: 8px;
|
||||
background: transparent; border: 0; border-bottom: 2px solid transparent;
|
||||
border-radius: 0; color: #273244; font-size: 14px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:checked {
|
||||
color: #1769E8; border-bottom-color: #1769E8;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:hover {
|
||||
color: #1555B6; background: #F2F7FF;
|
||||
}
|
||||
#PrescriptionLibraryPage QTableWidget {
|
||||
border: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PrescriptionLibraryPage QTableWidget::item { padding: 0; border: 0; }
|
||||
#PrescriptionLibraryPage QHeaderView::section {
|
||||
min-height: 0; padding: 0 12px; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-bottom: 1px solid #DBE5F2;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#PrescriptionLibraryTableCellHost { background: transparent; border: 0; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"] {
|
||||
min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
|
||||
padding: 0; border: 1px solid transparent; border-radius: 4px; background: transparent;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:hover { background: #EAF2FF; border-color: #B6CDEE; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:focus { border-color: #75A5F0; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:hover { background: #FFF0F2; border-color: #EAC8D0; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:disabled { background: transparent; border-color: transparent; color: #A4ADBA; }
|
||||
#PrescriptionLibraryPage QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PrescriptionLibraryPage QLabel#EmptyStateGlyph {
|
||||
font-size: 24px; color: #1769E8; background: #F2F7FF;
|
||||
border: 1px solid #DBE5F2; border-radius: 22px;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
|
||||
#PrescriptionLibraryPage QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PrescriptionLibraryPage QScrollBar::add-line, #PrescriptionLibraryPage QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar::add-page, #PrescriptionLibraryPage QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
|
||||
__all__ = ["library_stylesheet", "LibraryComboBox", "LibraryTable", "LibraryItemDelegate"]
|
||||
|
||||
@@ -1,115 +1,107 @@
|
||||
"""Scoped surfaces and real fonts for the approved issued-prescription page."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def prescriptions_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_PRESCRIPTIONS).safe_substitute(body=body_family(), heading=heading_family()))
|
||||
|
||||
|
||||
_PRESCRIPTIONS = """
|
||||
#PrescriptionsPage { background: $ds_canvas; color: $ds_text; }
|
||||
#PrescriptionWorkspaceContent, #PrescriptionWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PrescriptionsPage QLabel, #PrescriptionsPage QPushButton, #PrescriptionsPage QLineEdit,
|
||||
#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit, #PrescriptionsPage QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="sectionTitle"] {
|
||||
font-family: "$heading"; font-size: 14px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="muted"], #PrescriptionsPage QLabel#PrescriptionCountBadge {
|
||||
color: $ds_muted; font-size: 13px; background: transparent; border: 0; padding: 0;
|
||||
}
|
||||
#PrescriptionsPage QFrame#PrescriptionFilterBar, #PrescriptionsPage QFrame#PrescriptionTableCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; }
|
||||
#PrescriptionsPage QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control;
|
||||
border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text;
|
||||
}
|
||||
#PrescriptionsPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; }
|
||||
#PrescriptionsPage QPushButton:pressed { background: $ds_accent_soft; }
|
||||
#PrescriptionsPage QPushButton:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton {
|
||||
background: $ds_accent; color: $ds_surface; border-color: $ds_accent;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover {
|
||||
background: $ds_accent_hover; border-color: $ds_accent_hover;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed {
|
||||
background: $ds_accent_pressed; border-color: $ds_accent_pressed;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:focus,
|
||||
#PrescriptionsPage QPushButton#PrescriptionQueryButton:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
|
||||
#PrescriptionsPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
|
||||
#PrescriptionsPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled,
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:disabled,
|
||||
#PrescriptionsPage QPushButton#PrescriptionQueryButton:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
}
|
||||
#PrescriptionsPage QLineEdit, #PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid $ds_line;
|
||||
border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text;
|
||||
}
|
||||
#PrescriptionsPage QLineEdit:focus, #PrescriptionsPage QComboBox:focus, #PrescriptionsPage QDateTimeEdit:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QLineEdit QToolButton { min-width: 0; min-height: 0; border: 0; background: transparent; padding: 0; }
|
||||
#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionsPage QComboBox::drop-down, #PrescriptionsPage QDateTimeEdit::drop-down { width: 28px; border: 0; background: transparent; }
|
||||
#PrescriptionsPage QComboBox::down-arrow, #PrescriptionsPage QDateTimeEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PrescriptionsPage QDateTimeEdit:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; }
|
||||
#PrescriptionsPage QPushButton#PrescriptionDoctorButton { text-align: left; padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionsPage QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent;
|
||||
}
|
||||
#PrescriptionsPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PrescriptionsPage QCalendarWidget { font-family: "$body"; font-size: 13px; background: $ds_surface; color: $ds_text; }
|
||||
#PrescriptionsPage QCalendarWidget QWidget#qt_calendar_navigationbar { background: $ds_surface_alt; }
|
||||
#PrescriptionsPage QCalendarWidget QToolButton { min-height: 28px; border: 0; padding: 0 8px; color: $ds_text; background: transparent; }
|
||||
#PrescriptionsPage QCalendarWidget QAbstractItemView { color: $ds_text; background: $ds_surface; selection-background-color: $ds_accent; selection-color: $ds_surface; outline: 0; }
|
||||
#PrescriptionsPage QFrame#PrescriptionToolbar QPushButton { padding: 0 12px; font-size: 13px; }
|
||||
#PrescriptionsPage QTableWidget#PrescriptionTable {
|
||||
border: 0; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PrescriptionsPage QTableWidget#PrescriptionTable::item { border: 0; padding: 0; }
|
||||
#PrescriptionsPage QHeaderView::section {
|
||||
min-height: 0; padding: 0 12px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionsPage QWidget#PrescriptionTableCellHost { border: 0; background: transparent; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"] {
|
||||
min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
|
||||
padding: 0; border: 1px solid transparent; border-radius: $ds_radius_small; background: transparent;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"] {
|
||||
min-width: 64px; max-width: 64px; color: $ds_accent; font-size: 13px; padding: 0;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:hover { background: $ds_accent_soft; border-color: $ds_line_strong; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:hover { background: $ds_danger_soft; border-color: $ds_danger_soft; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:disabled,
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"]:disabled {
|
||||
background: transparent; border-color: transparent; color: $ds_disabled;
|
||||
}
|
||||
#PrescriptionsPage QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PrescriptionsPage QLabel#EmptyStateGlyph { font-size: 24px; color: $ds_accent; background: $ds_surface_alt; border: 1px solid $ds_line; border-radius: $ds_radius_panel; }
|
||||
#PrescriptionsPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
|
||||
#PrescriptionsPage QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PrescriptionsPage QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PrescriptionsPage QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PrescriptionsPage QScrollBar::add-line, #PrescriptionsPage QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PrescriptionsPage QScrollBar::add-page, #PrescriptionsPage QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
"""Scoped surfaces and real fonts for the approved issued-prescription page."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def prescriptions_stylesheet() -> str:
|
||||
return Template(_PRESCRIPTIONS).substitute(body=body_family(), heading=heading_family())
|
||||
|
||||
|
||||
_PRESCRIPTIONS = """
|
||||
#PrescriptionsPage { background: #F3F7FD; color: #273244; }
|
||||
#PrescriptionWorkspaceContent, #PrescriptionWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PrescriptionsPage QLabel, #PrescriptionsPage QPushButton, #PrescriptionsPage QLineEdit,
|
||||
#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit, #PrescriptionsPage QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="sectionTitle"] {
|
||||
font-family: "$heading"; font-size: 14px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="muted"], #PrescriptionsPage QLabel#PrescriptionCountBadge {
|
||||
color: #5D6B80; font-size: 13px; background: transparent; border: 0; padding: 0;
|
||||
}
|
||||
#PrescriptionsPage QFrame#PrescriptionFilterBar, #PrescriptionsPage QFrame#PrescriptionTableCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; }
|
||||
#PrescriptionsPage QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: 5px;
|
||||
border: 1px solid #DBE5F2; background: #FFFFFF; color: #273244;
|
||||
}
|
||||
#PrescriptionsPage QPushButton:hover { background: #F2F7FF; border-color: #B6CDEE; color: #1555B6; }
|
||||
#PrescriptionsPage QPushButton:pressed { background: #DCEAFF; }
|
||||
#PrescriptionsPage QPushButton:focus { border-color: #75A5F0; }
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton {
|
||||
background: #1769E8; color: #FFFFFF; border-color: #1769E8;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover {
|
||||
background: #155BCC; border-color: #155BCC;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed {
|
||||
background: #124EA9; border-color: #124EA9;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[variant="danger"] { color: #BE4657; background: #FFFFFF; border-color: #E9D8DE; }
|
||||
#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled {
|
||||
color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#PrescriptionsPage QLineEdit, #PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid #DBE5F2;
|
||||
border-radius: 5px; background: #FFFFFF; color: #273244;
|
||||
selection-background-color: #DCEAFF; selection-color: #273244;
|
||||
}
|
||||
#PrescriptionsPage QLineEdit:focus, #PrescriptionsPage QComboBox:focus, #PrescriptionsPage QDateTimeEdit:focus { border-color: #75A5F0; }
|
||||
#PrescriptionsPage QLineEdit QToolButton { min-width: 0; min-height: 0; border: 0; background: transparent; padding: 0; }
|
||||
#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionsPage QComboBox::drop-down, #PrescriptionsPage QDateTimeEdit::drop-down { width: 28px; border: 0; background: transparent; }
|
||||
#PrescriptionsPage QComboBox::down-arrow, #PrescriptionsPage QDateTimeEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PrescriptionsPage QDateTimeEdit:disabled { color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; }
|
||||
#PrescriptionsPage QPushButton#PrescriptionDoctorButton { text-align: left; padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionsPage QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6;
|
||||
}
|
||||
#PrescriptionsPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PrescriptionsPage QCalendarWidget { font-family: "$body"; font-size: 13px; background: #FFFFFF; color: #273244; }
|
||||
#PrescriptionsPage QCalendarWidget QWidget#qt_calendar_navigationbar { background: #F5F8FD; }
|
||||
#PrescriptionsPage QCalendarWidget QToolButton { min-height: 28px; border: 0; padding: 0 8px; color: #273244; background: transparent; }
|
||||
#PrescriptionsPage QCalendarWidget QAbstractItemView { color: #273244; background: #FFFFFF; selection-background-color: #1769E8; selection-color: #FFFFFF; outline: 0; }
|
||||
#PrescriptionsPage QFrame#PrescriptionToolbar QPushButton { padding: 0 12px; font-size: 13px; }
|
||||
#PrescriptionsPage QTableWidget#PrescriptionTable {
|
||||
border: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PrescriptionsPage QTableWidget#PrescriptionTable::item { border: 0; padding: 0; }
|
||||
#PrescriptionsPage QHeaderView::section {
|
||||
min-height: 0; padding: 0 12px; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-bottom: 1px solid #DBE5F2;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionsPage QWidget#PrescriptionTableCellHost { border: 0; background: transparent; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"] {
|
||||
min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
|
||||
padding: 0; border: 1px solid transparent; border-radius: 4px; background: transparent;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"] {
|
||||
min-width: 64px; max-width: 64px; color: #1769E8; font-size: 13px; padding: 0;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:hover { background: #EAF2FF; border-color: #B6CDEE; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:focus { border-color: #75A5F0; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:hover { background: #FFF0F2; border-color: #EAC8D0; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:disabled,
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"]:disabled {
|
||||
background: transparent; border-color: transparent; color: #A4ADBA;
|
||||
}
|
||||
#PrescriptionsPage QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PrescriptionsPage QLabel#EmptyStateGlyph { font-size: 24px; color: #1769E8; background: #F2F7FF; border: 1px solid #DBE5F2; border-radius: 22px; }
|
||||
#PrescriptionsPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
|
||||
#PrescriptionsPage QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PrescriptionsPage QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PrescriptionsPage QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PrescriptionsPage QScrollBar::add-line, #PrescriptionsPage QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PrescriptionsPage QScrollBar::add-page, #PrescriptionsPage QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
@@ -4,24 +4,23 @@ from __future__ import annotations
|
||||
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from .design_system import PALETTE
|
||||
from .theme import _register_preferred_cjk_fonts
|
||||
|
||||
TECH_BLUE = {
|
||||
"accent": PALETTE["accent"],
|
||||
"accent_hover": PALETTE["accent_hover"],
|
||||
"accent_pressed": PALETTE["accent_pressed"],
|
||||
"selection": PALETTE["accent_soft"],
|
||||
"selected_text": PALETTE["accent_hover"],
|
||||
"canvas": PALETTE["canvas"],
|
||||
"sidebar": PALETTE["sidebar"],
|
||||
"surface": PALETTE["surface"],
|
||||
"raised": PALETTE["surface_alt"],
|
||||
"line": PALETTE["line"],
|
||||
"text": PALETTE["text"],
|
||||
"heading": PALETTE["heading"],
|
||||
"muted": PALETTE["muted"],
|
||||
"focus": PALETTE["focus"],
|
||||
"accent": "#1769E8",
|
||||
"accent_hover": "#155BCC",
|
||||
"accent_pressed": "#124EA9",
|
||||
"selection": "#EAF2FF",
|
||||
"selected_text": "#1555B6",
|
||||
"canvas": "#F3F7FD",
|
||||
"sidebar": "#EDF4FF",
|
||||
"surface": "#FFFFFF",
|
||||
"raised": "#F7FAFE",
|
||||
"line": "#DBE5F2",
|
||||
"text": "#273244",
|
||||
"heading": "#202C3F",
|
||||
"muted": "#5D6B80",
|
||||
"focus": "#75A5F0",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -170,8 +170,8 @@ QWidget#ReceptionPage QStackedWidget#ReceptionNarrowWorkspace {
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionQueuePanel {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDF0F5;
|
||||
border-radius: 16px;
|
||||
border: 1px solid #E5ECF6;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionQueueTitle {
|
||||
font-size: 18px;
|
||||
@@ -200,8 +200,8 @@ QWidget#ReceptionPage QFrame#ReceptionHero,
|
||||
QWidget#ReceptionPage QFrame#ReceptionClinicalCard {
|
||||
min-height: 0;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDF0F5;
|
||||
border-radius: 16px;
|
||||
border: 1px solid #E5ECF6;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionPatientName {
|
||||
font-size: 20px;
|
||||
@@ -223,8 +223,8 @@ QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs {
|
||||
background-color: #FFFFFF;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #E5ECF6;
|
||||
border-top-left-radius: 16px;
|
||||
border-top-right-radius: 16px;
|
||||
border-top-left-radius: 8px;
|
||||
border-top-right-radius: 8px;
|
||||
}
|
||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab,
|
||||
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab {
|
||||
@@ -295,8 +295,8 @@ QWidget#ReceptionPage QFrame#ReceptionPatientSummaryCard,
|
||||
QWidget#ReceptionPage QFrame#ReceptionVitalsCard,
|
||||
QWidget#ReceptionPage QFrame#ReceptionLabsCard {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDF0F5;
|
||||
border-radius: 16px;
|
||||
border: 1px solid #E5ECF6;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue {
|
||||
color: #24334A;
|
||||
@@ -367,8 +367,8 @@ QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"][warning=
|
||||
QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard,
|
||||
QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid $ds_line;
|
||||
border-radius: $ds_radius_panel;
|
||||
border: 1px solid #DCE5F0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionAiTitle,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionAiTitle {
|
||||
@@ -405,37 +405,4 @@ QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::add-line:v
|
||||
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QWidget#ReceptionPage QLineEdit#ReceptionQueueSearch,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionDateButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionQueueFilterToggle,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionVideoButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionNotifyButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionHistoryButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionImButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionMoreButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton,
|
||||
QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"] {
|
||||
border-radius: $ds_radius_control;
|
||||
}
|
||||
QWidget#ReceptionPage QPushButton:focus,
|
||||
QWidget#ReceptionPage QLineEdit:focus,
|
||||
QWidget#ReceptionPage QComboBox:focus,
|
||||
QWidget#ReceptionPage QTextEdit:focus {
|
||||
border-color: $ds_focus;
|
||||
}
|
||||
QWidget#ReceptionPage QPushButton#ReceptionVideoButton:pressed {
|
||||
color: $ds_surface;
|
||||
background-color: $ds_accent_pressed;
|
||||
border-color: $ds_accent_pressed;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionMetricState="true"] {
|
||||
border-radius: $ds_radius_small;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionLabCell,
|
||||
QWidget#ReceptionPage QWidget#ReceptionCaseField {
|
||||
border-bottom-color: $ds_line;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue[missing="true"] {
|
||||
color: $ds_muted;
|
||||
}
|
||||
"""
|
||||
|
||||
@@ -59,7 +59,6 @@ from .chat_notifications import (
|
||||
ChatNotification,
|
||||
ChatNotificationCenter,
|
||||
)
|
||||
from .design_system import PALETTE, clinical_stylesheet
|
||||
from .dialogs.ai_consult import can_open_ai_consult
|
||||
from .dialogs.ai_consult_picker import select_and_present_ai_consult
|
||||
from .dialogs.diagnosis import DiagnosisDialog
|
||||
@@ -73,7 +72,7 @@ from .pages import (
|
||||
ReceptionPage,
|
||||
)
|
||||
from .reception_style import TECH_BLUE, body_family, heading_family, number_family
|
||||
from .theme import COLORS, METRICS, TYPE, crisp_pixmap
|
||||
from .theme import COLORS, TYPE, crisp_pixmap
|
||||
from .widgets import (
|
||||
EmptyState,
|
||||
StatusBadge,
|
||||
@@ -94,8 +93,8 @@ _SHELL_DESIGN_SIZE = QSize(1710, 920)
|
||||
_SHELL_MINIMUM_SIZE = QSize(1024, 640)
|
||||
_RECEPTION_SIDEBAR_WIDTH = 208
|
||||
_RECEPTION_TOPBAR_HEIGHT = 76
|
||||
_RECEPTION_SIDEBAR_COLOR = PALETTE["sidebar"]
|
||||
_RECEPTION_CHROME_LINE = PALETTE["line"]
|
||||
_RECEPTION_SIDEBAR_COLOR = "#F3F7FD"
|
||||
_RECEPTION_CHROME_LINE = "#E7EDF7"
|
||||
# Approved pages share one chrome state, so navigation among them keeps it intact.
|
||||
_TECH_BLUE_PAGES = frozenset({"appointments", "consultations", "patients", "prescriptions", "prescription_library", "reception"})
|
||||
|
||||
@@ -1006,7 +1005,7 @@ class ShellWindow(QMainWindow):
|
||||
chrome_widgets.extend(self.topbar.findChildren(_PaintedIconButton))
|
||||
chrome_widgets.append(self.tabs_menu_button)
|
||||
self._legacy_chrome_styles = {
|
||||
widget: clinical_stylesheet(widget.styleSheet()) for widget in chrome_widgets
|
||||
widget: widget.styleSheet() for widget in chrome_widgets
|
||||
}
|
||||
self._register_pages()
|
||||
self.search_shortcut = QShortcut(QKeySequence("Ctrl+K"), self)
|
||||
@@ -1269,7 +1268,7 @@ class ShellWindow(QMainWindow):
|
||||
color: #606163;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
border-radius: 999px;
|
||||
padding: 4px 10px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -1694,7 +1693,7 @@ class ShellWindow(QMainWindow):
|
||||
font-family: "{body_family()}"; font-weight: 400;
|
||||
min-height: 44px; max-height: 44px;
|
||||
border: 0; border-left: 5px solid transparent;
|
||||
border-radius: {METRICS["r_md"]};
|
||||
border-radius: 6px;
|
||||
padding: 0 16px; font-size: {TYPE['fs_body']};
|
||||
color: {TECH_BLUE['text']};
|
||||
}}
|
||||
@@ -1712,7 +1711,7 @@ class ShellWindow(QMainWindow):
|
||||
}}
|
||||
QPushButton#ShellNavButton[collapsed="true"] {{ padding: 0; }}
|
||||
QFrame#ShellAssistantCard {{
|
||||
background-color: {TECH_BLUE['surface']}; border-radius: {METRICS["r_lg"]};
|
||||
background-color: {TECH_BLUE['surface']}; border-radius: 8px;
|
||||
border: 1px solid {_RECEPTION_CHROME_LINE};
|
||||
}}
|
||||
QLabel#ShellAssistantName {{
|
||||
@@ -1724,7 +1723,7 @@ class ShellWindow(QMainWindow):
|
||||
QPushButton#ShellAssistantButton, QPushButton#ShellSettingsButton {{
|
||||
font-family: "{body_family()}"; font-weight: 400; font-size: {TYPE['fs_body']};
|
||||
}}
|
||||
QPushButton#ShellAssistantButton {{ border-radius: {METRICS["r_md"]}; }}
|
||||
QPushButton#ShellAssistantButton {{ border-radius: 6px; }}
|
||||
QPushButton#ShellSettingsButton {{
|
||||
min-height: 50px; max-height: 50px;
|
||||
text-align: left; padding: 0 32px;
|
||||
@@ -1739,7 +1738,7 @@ class ShellWindow(QMainWindow):
|
||||
border-radius: 0;
|
||||
border-bottom: 1px solid {_RECEPTION_CHROME_LINE};
|
||||
}}
|
||||
QFrame#ShellGlobalSearch {{ background-color: {PALETTE["surface_alt"]}; border: 1px solid transparent; border-radius: {METRICS["r_md"]}; }}
|
||||
QFrame#ShellGlobalSearch {{ border: 1px solid {_RECEPTION_CHROME_LINE}; border-radius: 5px; }}
|
||||
QFrame#ShellUserSeparator {{ background: {_RECEPTION_CHROME_LINE}; border: 0; }}
|
||||
QLabel#ShellShortcutHint {{
|
||||
font-family: "{number_family()}"; font-size: {TYPE['fs_small']};
|
||||
@@ -1768,7 +1767,7 @@ class ShellWindow(QMainWindow):
|
||||
if isinstance(widget, _PaintedIconButton):
|
||||
side = 50 if widget in (self.refresh_button, self.notification_button, self.settings_button) else 34
|
||||
stylesheet += f"QToolButton#ShellPaintedIconButton {{ min-width: {side - 2}px; max-width: {side - 2}px; min-height: {side - 2}px; max-height: {side - 2}px; }}"
|
||||
widget.setStyleSheet(clinical_stylesheet(stylesheet))
|
||||
widget.setStyleSheet(stylesheet)
|
||||
|
||||
self._set_reception_geometry(active)
|
||||
for widget in (
|
||||
|
||||
@@ -41,46 +41,46 @@ from doctor_workstation.resources import resource_path
|
||||
# ``motion`` deliberately imports nothing from this module, so this stays a
|
||||
# one-way dependency: tokens here, animation there.
|
||||
from . import motion
|
||||
from .design_system import PALETTE, RADII, SPACING, clinical_stylesheet
|
||||
|
||||
# Shared reading colors keep native pages and dialog chrome consistent.
|
||||
# Neutral reading colors follow the installed Codex light chrome defaults.
|
||||
# Brand accents are independent of reading ink; use opaque text for stable contrast.
|
||||
# The legacy teal/ink aliases remain for existing callers.
|
||||
COLORS = {
|
||||
"canvas": PALETTE["canvas"],
|
||||
"canvas_mid": PALETTE["surface"],
|
||||
"canvas_glow": PALETTE["accent_soft"],
|
||||
"surface": PALETTE["surface"],
|
||||
"surface_alt": PALETTE["surface_alt"],
|
||||
"raised": PALETTE["surface_alt"],
|
||||
"glass": PALETTE["surface"],
|
||||
"glass_alt": PALETTE["surface_alt"],
|
||||
"line": PALETTE["line"],
|
||||
"line_soft": PALETTE["line_strong"],
|
||||
"text": PALETTE["heading"],
|
||||
"text_soft": PALETTE["text"],
|
||||
"muted": PALETTE["muted"],
|
||||
"disabled_surface": PALETTE["disabled_surface"],
|
||||
"disabled_text": PALETTE["disabled"],
|
||||
"indigo": PALETTE["accent"],
|
||||
"indigo_hover": PALETTE["accent_hover"],
|
||||
"indigo_pressed": PALETTE["accent_pressed"],
|
||||
"indigo_pale": PALETTE["accent_soft"],
|
||||
"focus": PALETTE["focus"],
|
||||
"selection": PALETTE["accent_soft"],
|
||||
"success": PALETTE["success"],
|
||||
"success_pale": PALETTE["success_soft"],
|
||||
"warning": PALETTE["warning"],
|
||||
"warning_pale": PALETTE["warning_soft"],
|
||||
"danger": PALETTE["danger"],
|
||||
"danger_pale": PALETTE["danger_soft"],
|
||||
"info": PALETTE["accent"],
|
||||
"info_pale": PALETTE["accent_soft"],
|
||||
"ink": PALETTE["heading"],
|
||||
"ink_soft": PALETTE["text"],
|
||||
"teal": PALETTE["accent"],
|
||||
"teal_dark": PALETTE["accent_pressed"],
|
||||
"teal_pale": PALETTE["accent_soft"],
|
||||
"canvas": "#F4F6FA",
|
||||
"canvas_mid": "#FFFFFF",
|
||||
"canvas_glow": "#EEF1FA",
|
||||
"surface": "#FFFFFF",
|
||||
"surface_alt": "#F7F7F7",
|
||||
"raised": "#F7F7F7",
|
||||
"glass": "#FFFFFF",
|
||||
"glass_alt": "#F7F7F7",
|
||||
"line": "#EDEDEE",
|
||||
"line_soft": "#E4E4E5",
|
||||
"text": "#1A1C1F",
|
||||
"text_soft": "#606163",
|
||||
"muted": "#6A6B6D",
|
||||
"disabled_surface": "#F2F2F2",
|
||||
"disabled_text": "#8E8F90",
|
||||
"indigo": "#4F63D9",
|
||||
"indigo_hover": "#4156C4",
|
||||
"indigo_pressed": "#354BB4",
|
||||
"indigo_pale": "#EEF1FA",
|
||||
"focus": "#8B9AD9",
|
||||
"selection": "#EEF1FA",
|
||||
"success": "#287B65",
|
||||
"success_pale": "#EEF7F3",
|
||||
"warning": "#A9691D",
|
||||
"warning_pale": "#FCF5E9",
|
||||
"danger": "#BE4B58",
|
||||
"danger_pale": "#FCF0F2",
|
||||
"info": "#4F63D9",
|
||||
"info_pale": "#EEF1FA",
|
||||
# Backward-compatible names used by older UI code and integrations.
|
||||
"ink": "#1A1C1F",
|
||||
"ink_soft": "#606163",
|
||||
"teal": "#4F63D9",
|
||||
"teal_dark": "#354BB4",
|
||||
"teal_pale": "#EEF1FA",
|
||||
}
|
||||
|
||||
|
||||
@@ -122,11 +122,11 @@ METRICS = {
|
||||
# ``outer - gap``. Where the gap is bigger than the outer radius the inner
|
||||
# element is far enough from the corner that its own radius is free.
|
||||
"r_xs": "4px", # chips, badges, tiny status pills
|
||||
"r_sm": f"{RADII['small']}px", # inline row actions, tags
|
||||
"r_md": f"{RADII['control']}px", # buttons, inputs, combo boxes
|
||||
"r_lg": f"{RADII['panel']}px", # cards, filter bars, panels
|
||||
"r_xl": f"{RADII['window']}px", # the shell surfaces the cards sit on
|
||||
"pad_control": f"{SPACING['control']}px", # horizontal padding inside default controls
|
||||
"r_sm": "6px", # inline row actions, tags
|
||||
"r_md": "8px", # buttons, inputs, combo boxes
|
||||
"r_lg": "12px", # cards, filter bars, panels
|
||||
"r_xl": "16px", # the shell surfaces the cards sit on
|
||||
"pad_control": "12px", # horizontal padding inside default controls
|
||||
"pad_compact": "9px",
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ QDialog[businessDialog="true"] QFrame#DialogSurface,
|
||||
QDialog[businessDialog="true"] QFrame[dialogSurface="true"] {
|
||||
background-color: $surface;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 14px;
|
||||
}
|
||||
QDialog[businessDialog="true"] QFrame#DialogHeader,
|
||||
QDialog[businessDialog="true"] QFrame[dialogRole="header"] {
|
||||
@@ -275,18 +275,18 @@ QFrame#Card, QFrame#Panel, QFrame#FilterBar, QFrame#DetailPanel,
|
||||
QFrame[glass="true"] {
|
||||
background-color: $glass;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QFrame#FilterBar { background-color: $surface; }
|
||||
QFrame#SubtleCard {
|
||||
background-color: $glass_alt;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QFrame#MetricCard {
|
||||
background-color: $surface;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 11px;
|
||||
}
|
||||
QFrame#MetricCard:hover { border-color: $line_soft; background-color: $surface_alt; }
|
||||
QFrame#MetricCard QLabel[role="metricTitle"] { color: $muted; font-size: $fs_caption; }
|
||||
@@ -297,7 +297,7 @@ QFrame#ReceptionAiCard {
|
||||
min-height: 132px;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 13px;
|
||||
}
|
||||
QLabel#ReceptionAiTitle {
|
||||
color: $indigo_pressed;
|
||||
@@ -313,7 +313,7 @@ QLabel#MetricGlyph {
|
||||
color: $indigo;
|
||||
background-color: $indigo_pale;
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_md;
|
||||
border-radius: 11px;
|
||||
font-size: $fs_section;
|
||||
font-weight: $fw_heading;
|
||||
}
|
||||
@@ -329,7 +329,7 @@ QGroupBox {
|
||||
margin-top: 12px;
|
||||
padding-top: 12px;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
background-color: $glass;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
@@ -351,7 +351,7 @@ QPushButton {
|
||||
}
|
||||
QPushButton:hover {
|
||||
background-color: $raised;
|
||||
border-color: $line_soft;
|
||||
border-color: $indigo_hover;
|
||||
}
|
||||
QPushButton:pressed {
|
||||
background-color: $indigo_pale;
|
||||
@@ -401,7 +401,7 @@ QPushButton[variant="primary"]:disabled {
|
||||
QPushButton[variant="secondary"] {
|
||||
color: $indigo_hover;
|
||||
background-color: $indigo_pale;
|
||||
border-color: $indigo_pale;
|
||||
border-color: $line_soft;
|
||||
}
|
||||
QPushButton[variant="secondary"]:hover {
|
||||
color: $indigo_pressed;
|
||||
@@ -462,7 +462,7 @@ QToolButton#RowActionsMore::menu-indicator { width: 0; height: 0; image: none; }
|
||||
QFrame#NoteAttachmentTile {
|
||||
background-color: $surface;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 10px;
|
||||
}
|
||||
QPushButton#NoteAttachmentPreview {
|
||||
min-height: 132px;
|
||||
@@ -470,7 +470,7 @@ QPushButton#NoteAttachmentPreview {
|
||||
color: $muted;
|
||||
background-color: $surface_alt;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
QPushButton#NoteAttachmentPreview:hover {
|
||||
@@ -558,7 +558,7 @@ QPushButton[variant="chip"] {
|
||||
color: $text_soft;
|
||||
background-color: $surface_alt;
|
||||
border-color: $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QPushButton[variant="chip"]:hover {
|
||||
color: $text;
|
||||
@@ -653,7 +653,7 @@ QComboBox QAbstractItemView {
|
||||
background-color: $raised;
|
||||
alternate-background-color: $surface_alt;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 10px;
|
||||
padding: 5px;
|
||||
outline: 0;
|
||||
selection-background-color: $indigo_pressed;
|
||||
@@ -692,7 +692,7 @@ QAbstractItemView, QTableWidget, QTableView, QListWidget, QListView, QTreeWidget
|
||||
background-color: $surface;
|
||||
alternate-background-color: $surface_alt;
|
||||
border: 0;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
gridline-color: $line;
|
||||
selection-background-color: $selection;
|
||||
selection-color: $text;
|
||||
@@ -729,17 +729,17 @@ QListWidget::item:selected, QListView::item:selected,
|
||||
QTreeWidget::item:selected, QTreeView::item:selected {
|
||||
background-color: $indigo_pale;
|
||||
color: $indigo_pressed;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QListWidget::item:hover, QListView::item:hover,
|
||||
QTreeWidget::item:hover, QTreeView::item:hover {
|
||||
background-color: $surface_alt;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
QTabWidget::pane {
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
background-color: $glass;
|
||||
}
|
||||
QTabBar::tab {
|
||||
@@ -749,7 +749,7 @@ QTabBar::tab {
|
||||
color: $muted;
|
||||
background-color: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: $r_md;
|
||||
border-radius: 9px;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
QTabBar::tab:hover { color: $text; background-color: $surface_alt; }
|
||||
@@ -792,7 +792,7 @@ QMenu {
|
||||
color: $text;
|
||||
background-color: $raised;
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_md;
|
||||
border-radius: 10px;
|
||||
padding: 6px;
|
||||
}
|
||||
QMenu::item {
|
||||
@@ -815,7 +815,7 @@ QCalendarWidget {
|
||||
color: $text;
|
||||
background-color: $surface;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QCalendarWidget QWidget#qt_calendar_navigationbar {
|
||||
background-color: $raised;
|
||||
@@ -914,7 +914,7 @@ QWidget#Pager QLabel#PagerActive {
|
||||
color: #FFFFFF;
|
||||
background-color: $indigo;
|
||||
border: 1px solid $indigo;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
font-size: $fs_caption;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
@@ -937,7 +937,7 @@ QLabel#EmptyStateGlyph {
|
||||
|
||||
QFrame#MessageBanner {
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 10px;
|
||||
color: $text_soft;
|
||||
}
|
||||
QFrame#MessageBanner QLabel { background-color: transparent; }
|
||||
@@ -955,7 +955,7 @@ QLabel#Toast {
|
||||
color: $text;
|
||||
background-color: $raised;
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_md;
|
||||
border-radius: 11px;
|
||||
padding: 11px 16px;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
@@ -995,9 +995,13 @@ QLabel#UserAvatar {
|
||||
font-weight: $fw_heading;
|
||||
}
|
||||
QWidget#LoginBrandPanel {
|
||||
background-color: $surface_alt;
|
||||
background-color: qlineargradient(
|
||||
x1: 0, y1: 0, x2: 1, y2: 1,
|
||||
stop: 0 $surface,
|
||||
stop: 1 $canvas_glow
|
||||
);
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 22px;
|
||||
}
|
||||
QFrame#LoginCard {
|
||||
background-color: $glass;
|
||||
@@ -1039,7 +1043,6 @@ QToolTip {
|
||||
}
|
||||
"""
|
||||
).substitute(_QSS_TOKENS)
|
||||
GLOBAL_QSS = clinical_stylesheet(GLOBAL_QSS)
|
||||
|
||||
|
||||
#: Per-block reading rhythm, in device pixels. ``(top, bottom, line%)``.
|
||||
|
||||
@@ -44,7 +44,6 @@ from doctor_workstation.core.errors import (
|
||||
)
|
||||
|
||||
from . import icons, motion
|
||||
from .design_system import PALETTE
|
||||
|
||||
AuthenticationExpiredHandler = Callable[[AuthenticationExpiredError], bool]
|
||||
_AUTHENTICATION_EXPIRED_HANDLER: AuthenticationExpiredHandler | None = None
|
||||
@@ -799,7 +798,7 @@ class _BusyTrack(QWidget):
|
||||
chunk_width = max(36, int(rect.width() * 0.32))
|
||||
span = rect.width() + chunk_width
|
||||
x = int(self._phase * span) - chunk_width
|
||||
painter.setBrush(QColor(PALETTE["accent"]))
|
||||
painter.setBrush(QColor("#4F63D9"))
|
||||
painter.drawRoundedRect(x, 0, chunk_width, rect.height(), 3, 3)
|
||||
|
||||
|
||||
|
||||
@@ -1,387 +0,0 @@
|
||||
"""Bounded, Qt-independent AI requests for one authenticated IM window.
|
||||
|
||||
Only server-archived clinical context is submitted. This module never sends IM
|
||||
messages and never shares the ordered call/recording lifecycle worker.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from threading import BoundedSemaphore, Event, RLock, Thread
|
||||
from time import monotonic
|
||||
from typing import Any
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
MAX_RESULT_CHARS = 65_536
|
||||
MAX_SYNC_STEPS = 24
|
||||
SYNC_TIMEOUT_SECONDS = 45.0
|
||||
_WORKER_SLOTS = BoundedSemaphore(4)
|
||||
_CANCEL_SLOTS = BoundedSemaphore(4)
|
||||
_ACTIONS = frozenset({"summary", "followup", "reply"})
|
||||
|
||||
|
||||
def _integer(value: Any, *, minimum: int) -> int | None:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, str)):
|
||||
return None
|
||||
if isinstance(value, str) and re.fullmatch(r"0|[1-9][0-9]{0,18}", value) is None:
|
||||
return None
|
||||
number = int(value)
|
||||
return number if minimum <= number < 2**63 else None
|
||||
|
||||
|
||||
def _request_uuid(value: Any) -> bool:
|
||||
if not isinstance(value, str) or len(value) != 36:
|
||||
return False
|
||||
try:
|
||||
return str(UUID(value)) == value.lower()
|
||||
except (ValueError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
def task_prompt(action: str, doctor_account: str) -> tuple[str, str]:
|
||||
"""Keep instructions separate from clinical source text and under API limits."""
|
||||
|
||||
if action not in _ACTIONS or not re.fullmatch(r"doctor_[1-9][0-9]{0,18}", doctor_account):
|
||||
raise ValueError("AI 操作或当前医生账号无效")
|
||||
shared = (
|
||||
f"这是 IM 问诊辅助,本次医生 IM 账号为 {doctor_account}。"
|
||||
"优先依据该医生与本患者最近已归档对话,结合服务端授权病历;"
|
||||
"其他医生及历史记录仅作背景,不能当成本次已确认事实。"
|
||||
"若未找到本次对话请明确说明,不猜测最新诉求。"
|
||||
"区分已知、明确否认与未知,保留日期及不确定性;"
|
||||
"不补问脉象,不编造事实、不自动确诊、不新增或更改药物剂量。"
|
||||
)
|
||||
instructions = {
|
||||
"summary": "请用简短条目总结本次病情、病程、现用治疗与待核实事项,供医生交接复核。",
|
||||
"followup": (
|
||||
"请建议最多5条优先追问,直接给出可向患者询问的自然短句,"
|
||||
"每条可附简短目的;避免重复已回答的问题,不做通用问卷。"
|
||||
),
|
||||
"reply": (
|
||||
"请起草一段医生可审阅后发给患者的简短自然回复,围绕该对话最近的患者问题。"
|
||||
"不冒称已检查、已预约或已开处方,不承诺疗效,不让患者自行停换药。"
|
||||
"只给回复草稿,不写分析过程;任何缺失资料通过必要的问题核实。"
|
||||
),
|
||||
}
|
||||
prompt = shared + instructions[action] + "此内容须由医生复核,不能自动发送。"
|
||||
if len(prompt) > 500:
|
||||
raise ValueError("AI 提示词超过接口长度限制")
|
||||
return ("summary" if action == "summary" else "custom"), prompt
|
||||
|
||||
|
||||
def _warnings(value: Any) -> list[str]:
|
||||
if not isinstance(value, (list, tuple)):
|
||||
return []
|
||||
warnings = []
|
||||
for row in value[:20]:
|
||||
if isinstance(row, str):
|
||||
text = row
|
||||
elif isinstance(row, Mapping):
|
||||
text = row.get("message") or row.get("label")
|
||||
if not text and row.get("code"):
|
||||
text = (
|
||||
"请复核回答中的脉象判断;本流程不采集脉象。"
|
||||
if row["code"] == "PULSE_EXCLUDED_FROM_ASSESSMENT"
|
||||
else "请对照原始记录复核,回答中的事实、否认或未知状态可能不一致。"
|
||||
)
|
||||
else:
|
||||
continue
|
||||
if isinstance(text, str) and text.strip():
|
||||
rendered = text.strip()[:400]
|
||||
if rendered not in warnings:
|
||||
warnings.append(rendered)
|
||||
return warnings
|
||||
|
||||
|
||||
class _RequestError(Exception):
|
||||
"""A deliberately safe, user-facing failure message."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Job:
|
||||
identity: dict[str, Any]
|
||||
action: str
|
||||
cancelled: Event = field(default_factory=Event)
|
||||
completed: bool = False
|
||||
succeeded: bool = False
|
||||
stream_started: bool = False
|
||||
cancel_sent: bool = False
|
||||
|
||||
|
||||
class ImAiController:
|
||||
"""One live request, a coalesced mailbox, and bounded daemon workers.
|
||||
|
||||
Qt polls ``take_result`` every 60 ms. Worker threads only mutate plain data;
|
||||
they never touch a QObject. A cancelled worker must retire before a retry
|
||||
starts, so rapid clicks cannot create an unbounded collection of requests.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
repository: Any,
|
||||
*,
|
||||
diagnosis_id: Any,
|
||||
appointment_id: Any,
|
||||
doctor_account: str,
|
||||
enabled: bool = False,
|
||||
clock: Callable[[], float] = monotonic,
|
||||
max_sync_steps: int = MAX_SYNC_STEPS,
|
||||
sync_timeout: float = SYNC_TIMEOUT_SECONDS,
|
||||
) -> None:
|
||||
self.repository = repository
|
||||
self.diagnosis_id = _integer(diagnosis_id, minimum=1)
|
||||
self.appointment_id = _integer(appointment_id, minimum=0)
|
||||
self.doctor_account = str(doctor_account)
|
||||
self.enabled = (
|
||||
enabled is True
|
||||
and repository is not None
|
||||
and self.diagnosis_id is not None
|
||||
and self.appointment_id is not None
|
||||
and re.fullmatch(r"doctor_[1-9][0-9]{0,18}", self.doctor_account) is not None
|
||||
)
|
||||
self.session_id = str(uuid4())
|
||||
self._clock = clock
|
||||
self._max_sync_steps = max(1, min(MAX_SYNC_STEPS, max_sync_steps))
|
||||
self._sync_timeout = max(0.01, min(SYNC_TIMEOUT_SECONDS, sync_timeout))
|
||||
self._lock = RLock()
|
||||
self._closed = False
|
||||
self._current: _Job | None = None
|
||||
self._running: _Job | None = None
|
||||
self._worker: Thread | None = None
|
||||
self._mailbox: dict[str, Any] | None = None
|
||||
self._seen: deque[str] = deque(maxlen=256)
|
||||
|
||||
@property
|
||||
def config(self) -> dict[str, Any]:
|
||||
return {
|
||||
"version": 1,
|
||||
"enabled": self.enabled and not self._closed,
|
||||
"sessionId": self.session_id,
|
||||
**({} if self.enabled else {"reason": "当前账号或问诊暂不能使用 AI 辅助。"}),
|
||||
}
|
||||
|
||||
def _valid_identity(self, message: Mapping[str, Any]) -> bool:
|
||||
return (
|
||||
self.enabled
|
||||
and not self._closed
|
||||
and message.get("source") == "doctor-call"
|
||||
and message.get("sessionId") == self.session_id
|
||||
and _request_uuid(message.get("requestId"))
|
||||
and isinstance(message.get("contextKey"), str)
|
||||
and 0 < len(message["contextKey"]) <= 128
|
||||
and _integer(message.get("diagnosisId"), minimum=1) == self.diagnosis_id
|
||||
and _integer(message.get("appointmentId"), minimum=0) == self.appointment_id
|
||||
and isinstance(message.get("action"), str)
|
||||
and message["action"] in _ACTIONS
|
||||
)
|
||||
|
||||
def handle(self, message: Mapping[str, Any]) -> bool:
|
||||
with self._lock:
|
||||
if not self._valid_identity(message):
|
||||
return False
|
||||
event = message.get("event")
|
||||
identity = {key: message[key] for key in (
|
||||
"sessionId", "requestId", "contextKey", "diagnosisId", "appointmentId", "action"
|
||||
)}
|
||||
if event == "im-ai-cancel":
|
||||
if self._current is None or self._current.identity != identity:
|
||||
return False
|
||||
self._cancel(self._current)
|
||||
return True
|
||||
if event != "im-ai-request" or message["requestId"] in self._seen:
|
||||
return False
|
||||
self._seen.append(message["requestId"])
|
||||
job = _Job(identity, message["action"])
|
||||
if self._running is not None:
|
||||
self._cancel(self._running)
|
||||
self._current = job
|
||||
self._publish(job, "error", message="上次请求正在结束,请稍后重试。", terminal=True)
|
||||
return True
|
||||
self._current = job
|
||||
if not _WORKER_SLOTS.acquire(blocking=False):
|
||||
self._publish(job, "error", message="AI 正在处理其他请求,请稍后重试。", terminal=True)
|
||||
return True
|
||||
self._running = job
|
||||
self._publish(job, "loading", message="正在同步当前聊天记录…")
|
||||
self._worker = Thread(target=self._run, args=(job,), name="im-ai", daemon=True)
|
||||
try:
|
||||
self._worker.start()
|
||||
except RuntimeError:
|
||||
self._running = None
|
||||
_WORKER_SLOTS.release()
|
||||
self._publish(job, "error", message="AI 请求暂时无法启动,请稍后重试。", terminal=True)
|
||||
return True
|
||||
|
||||
def _publish(self, job: _Job, status: str, *, terminal: bool = False, **fields: Any) -> None:
|
||||
with self._lock:
|
||||
if self._closed or self._current is not job or job.cancelled.is_set() or job.completed:
|
||||
return
|
||||
if terminal:
|
||||
job.completed = True
|
||||
job.succeeded = status == "success"
|
||||
self._mailbox = {**job.identity, "status": status, **fields}
|
||||
|
||||
def take_result(self) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
result, self._mailbox = self._mailbox, None
|
||||
return None if self._closed else result
|
||||
|
||||
def _sync(self, job: _Job) -> bool:
|
||||
deadline = self._clock() + self._sync_timeout
|
||||
token = ""
|
||||
for _ in range(self._max_sync_steps):
|
||||
if job.cancelled.is_set():
|
||||
return False
|
||||
if self._clock() >= deadline:
|
||||
raise _RequestError("聊天同步超时,尚未生成,请稍后重试。")
|
||||
result = self.repository.sync_im_chat_messages(
|
||||
self.diagnosis_id, scope="current", sync_token=token
|
||||
)
|
||||
if job.cancelled.is_set():
|
||||
return False
|
||||
if self._clock() >= deadline:
|
||||
raise _RequestError("聊天同步超时,尚未生成,请稍后重试。")
|
||||
if not isinstance(result, Mapping) or result.get("errors"):
|
||||
raise _RequestError("当前聊天记录未能完整同步,尚未生成,请稍后重试。")
|
||||
if result.get("completed") is True:
|
||||
return True
|
||||
token = result.get("sync_token", "")
|
||||
if not isinstance(token, str) or re.fullmatch(r"[a-f0-9]{48}", token) is None:
|
||||
raise _RequestError("聊天同步进度无效,请更新客户端或稍后重试。")
|
||||
raise _RequestError("聊天记录仍在同步,尚未生成,请稍后重试。")
|
||||
|
||||
def _run(self, job: _Job) -> None:
|
||||
try:
|
||||
if not self._sync(job):
|
||||
return
|
||||
task, prompt = task_prompt(job.action, self.doctor_account)
|
||||
with self._lock:
|
||||
if job.cancelled.is_set() or self._closed:
|
||||
return
|
||||
job.stream_started = True
|
||||
self._publish(job, "loading", message="聊天已同步,正在整理病历资料…")
|
||||
if job.cancelled.is_set():
|
||||
return
|
||||
text = ""
|
||||
events = self.repository.stream_diagnosis_ai(
|
||||
self.diagnosis_id, prompt, task=task,
|
||||
request_id=job.identity["requestId"], cancelled=job.cancelled.is_set,
|
||||
)
|
||||
try:
|
||||
for event in events:
|
||||
if job.cancelled.is_set():
|
||||
return
|
||||
if not isinstance(event, Mapping):
|
||||
continue
|
||||
kind = event.get("event")
|
||||
if kind == "delta":
|
||||
delta = event.get("text", "")
|
||||
if not isinstance(delta, str) or len(text) + len(delta) > MAX_RESULT_CHARS:
|
||||
raise _RequestError("AI 内容超过显示上限,已停止接收,请缩小问题后重试。")
|
||||
text += delta
|
||||
self._publish(job, "streaming", text=text, message="正在生成,内容尚未完成。")
|
||||
elif kind in {"start", "progress"}:
|
||||
message = str(event.get("message") or "正在整理资料并生成…")[:240]
|
||||
self._publish(job, "streaming" if text else "loading", text=text, message=message)
|
||||
elif kind == "done":
|
||||
result_id = event.get("diagnosis_id")
|
||||
if result_id is not None and _integer(result_id, minimum=1) != self.diagnosis_id:
|
||||
raise _RequestError("AI 返回的问诊上下文不匹配,结果未采用。")
|
||||
answer = event.get("answer", event.get("content", text))
|
||||
if not isinstance(answer, str) or not answer.strip():
|
||||
raise _RequestError("AI 未返回完整内容,请重试。")
|
||||
if len(answer) > MAX_RESULT_CHARS:
|
||||
raise _RequestError("AI 内容超过显示上限,结果未采用,请缩小问题后重试。")
|
||||
self._publish(
|
||||
job, "success", terminal=True, text=answer,
|
||||
message="已生成,请由医生复核后使用。",
|
||||
modelLabel=str(event.get("model_label") or "")[:100],
|
||||
warnings=_warnings(event.get("clinical_review_warnings")),
|
||||
)
|
||||
return
|
||||
elif kind == "error":
|
||||
raise _RequestError("AI 请求未完成,请检查权限或稍后重试。")
|
||||
if not job.cancelled.is_set():
|
||||
raise _RequestError("AI 连接提前结束,内容未完成,请重试。")
|
||||
finally:
|
||||
close = getattr(events, "close", None)
|
||||
if callable(close):
|
||||
close()
|
||||
except Exception as error:
|
||||
message = str(error) if isinstance(error, _RequestError) else (
|
||||
"AI 请求失败,请检查权限或稍后重试。" if job.stream_started
|
||||
else "当前聊天同步失败,尚未生成,请检查权限或稍后重试。"
|
||||
)
|
||||
self._publish(job, "error", message=message, terminal=True)
|
||||
if job.stream_started and not job.cancelled.is_set() and not job.succeeded:
|
||||
self._request_cancel(job)
|
||||
finally:
|
||||
with self._lock:
|
||||
if self._running is job:
|
||||
self._running = None
|
||||
_WORKER_SLOTS.release()
|
||||
|
||||
def _cancel(self, job: _Job) -> None:
|
||||
if job.completed or job.cancelled.is_set():
|
||||
return
|
||||
job.cancelled.set()
|
||||
if self._current is job and not self._closed:
|
||||
self._mailbox = {
|
||||
**job.identity, "status": "cancelled",
|
||||
"message": ("已停止本次接收,上游是否结束尚未确认。" if job.stream_started
|
||||
else "已取消,尚未向 AI 提交请求。"),
|
||||
}
|
||||
if job.stream_started:
|
||||
self._request_cancel(job)
|
||||
|
||||
def _request_cancel(self, job: _Job) -> None:
|
||||
with self._lock:
|
||||
if job.cancel_sent:
|
||||
return
|
||||
job.cancel_sent = True
|
||||
if not _CANCEL_SLOTS.acquire(blocking=False):
|
||||
return
|
||||
|
||||
def send() -> None:
|
||||
try:
|
||||
result = self.repository.cancel_diagnosis_ai(self.diagnosis_id, job.identity["requestId"])
|
||||
if not isinstance(result, Mapping):
|
||||
return
|
||||
message = "已发送取消请求,上游是否结束尚未确认。"
|
||||
terminal = result.get("upstream_terminal_status")
|
||||
if result.get("upstream_terminal_confirmed") is True and terminal in {"stopped", "succeeded", "failed"}:
|
||||
message = "本次接收已停止,上游工作流已结束。"
|
||||
elif result.get("upstream_stop_confirmed") is True:
|
||||
message = "上游已接受停止请求,是否结束尚未确认。"
|
||||
with self._lock:
|
||||
if not self._closed and self._current is job and job.cancelled.is_set():
|
||||
self._mailbox = {**job.identity, "status": "cancelled", "message": message}
|
||||
except Exception:
|
||||
pass # Keep the visible unconfirmed cancellation; never expose transport details.
|
||||
finally:
|
||||
_CANCEL_SLOTS.release()
|
||||
|
||||
try:
|
||||
Thread(target=send, name="im-ai-cancel", daemon=True).start()
|
||||
except RuntimeError:
|
||||
_CANCEL_SLOTS.release()
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
self._mailbox = None
|
||||
if self._running is not None:
|
||||
self._cancel(self._running)
|
||||
|
||||
def wait(self, timeout: float = 1.0) -> bool:
|
||||
"""Bounded diagnostic/test helper; never called by the Qt GUI."""
|
||||
|
||||
worker = self._worker
|
||||
if worker is not None:
|
||||
worker.join(max(0.0, min(timeout, 5.0)))
|
||||
return worker is None or not worker.is_alive()
|
||||
@@ -413,7 +413,6 @@ class VideoCallLauncher:
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
) -> Any:
|
||||
request = self.prepare(
|
||||
ticket,
|
||||
@@ -433,7 +432,6 @@ class VideoCallLauncher:
|
||||
patient_name=patient_name,
|
||||
patient_case=patient_case,
|
||||
on_open_diagnosis=on_open_diagnosis,
|
||||
can_ai_assistant=can_ai_assistant is True,
|
||||
)
|
||||
|
||||
|
||||
@@ -452,7 +450,6 @@ def launch_video_call(
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
) -> Any:
|
||||
"""Normalize a ticket and open a call with the requested backend."""
|
||||
|
||||
@@ -471,5 +468,4 @@ def launch_video_call(
|
||||
patient_name=patient_name,
|
||||
patient_case=patient_case,
|
||||
on_open_diagnosis=on_open_diagnosis,
|
||||
can_ai_assistant=can_ai_assistant is True,
|
||||
)
|
||||
|
||||
@@ -18,7 +18,6 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from ..core.transcript_text import simplified_transcript
|
||||
from .launcher import VideoCallRequest, normalize_backend_ticket
|
||||
|
||||
ResultT = TypeVar("ResultT")
|
||||
@@ -135,7 +134,7 @@ def _extract_cloud_recording_outcome(result: Any) -> tuple[bool, str] | None:
|
||||
return None
|
||||
|
||||
|
||||
def normalize_transcript_segment(segment: Mapping[str, Any], session_id: str) -> dict[str, Any]:
|
||||
def _clean_transcript_segment(segment: Mapping[str, Any], session_id: str) -> dict[str, Any]:
|
||||
segment_id = str(segment.get("segment_id", segment.get("segmentId", ""))).strip()
|
||||
text = str(segment.get("text", segment.get("sourceText", ""))).strip()
|
||||
speaker_user_id = str(
|
||||
@@ -146,14 +145,13 @@ def normalize_transcript_segment(segment: Mapping[str, Any], session_id: str) ->
|
||||
raise ValueError("transcript segment_id must contain 1 to 160 characters")
|
||||
if not text or len(text) > 4_000:
|
||||
raise ValueError("transcript text must contain 1 to 4000 characters")
|
||||
text = simplified_transcript(text)
|
||||
if len(speaker_user_id) > 160:
|
||||
raise ValueError("transcript speaker_user_id is too long")
|
||||
if speaker_role not in {"doctor", "patient", "unknown"}:
|
||||
speaker_role = "unknown"
|
||||
try:
|
||||
timestamp = int(segment.get("timestamp") or 0)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
except (TypeError, ValueError):
|
||||
timestamp = 0
|
||||
return {
|
||||
"segment_id": segment_id,
|
||||
@@ -545,25 +543,10 @@ class OrderedCallLifecycle:
|
||||
with self._lock:
|
||||
if self._end_future is not None:
|
||||
raise RuntimeError("video call has already ended")
|
||||
if self._transcription_finish_future is not None:
|
||||
raise RuntimeError("call transcription has already stopped")
|
||||
if (
|
||||
self._transcription_session_id is not None
|
||||
and self._transcription_session_id != clean_session
|
||||
):
|
||||
raise RuntimeError("another transcription session already exists")
|
||||
previous = self._transcription_start_future
|
||||
if previous is not None:
|
||||
if not previous.done() or (
|
||||
not previous.cancelled()
|
||||
and previous.exception() is None
|
||||
and previous.result() is True
|
||||
):
|
||||
return previous
|
||||
# A completed failure must not poison this call's retry button.
|
||||
# Keep the exact session identity: the server may have accepted
|
||||
# an earlier request whose response never reached this client.
|
||||
self._transcription_active = False
|
||||
if self._transcription_start_future is not None:
|
||||
if self._transcription_session_id != clean_session:
|
||||
raise RuntimeError("another transcription session already exists")
|
||||
return self._transcription_start_future
|
||||
if self._start_future is None:
|
||||
self.start()
|
||||
method = getattr(self.repository, "start_call_transcription", None)
|
||||
@@ -610,7 +593,7 @@ class OrderedCallLifecycle:
|
||||
raise RuntimeError("call transcription has not started")
|
||||
if self._transcription_finish_future is not None:
|
||||
raise RuntimeError("call transcription has already stopped")
|
||||
cleaned = normalize_transcript_segment(segment, session_id)
|
||||
cleaned = _clean_transcript_segment(segment, session_id)
|
||||
segment_id = cleaned["segment_id"]
|
||||
existing = self._segment_futures.get(segment_id)
|
||||
if existing is not None:
|
||||
@@ -755,4 +738,4 @@ class OrderedCallLifecycle:
|
||||
return self._worker.wait(timeout)
|
||||
|
||||
|
||||
__all__ = ["OrderedCallLifecycle", "normalize_transcript_segment"]
|
||||
__all__ = ["OrderedCallLifecycle"]
|
||||
|
||||
@@ -1,414 +0,0 @@
|
||||
"""Incremental video assistance; never runs on the call persistence FIFO or Qt.
|
||||
|
||||
Only persisted segment notifications trigger work. One in-flight request and
|
||||
one coalesced latest revision are retained, with explicit patient/call/session
|
||||
correlation. Clinical content is never written or sent to the patient here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
from collections.abc import Callable, Mapping
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, field
|
||||
from threading import BoundedSemaphore, Event, RLock, Thread
|
||||
from time import monotonic
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from ..core.errors import (
|
||||
ApiBusinessError,
|
||||
ApiHttpError,
|
||||
ApiProtocolError,
|
||||
ApiTimeoutError,
|
||||
ApiTransportError,
|
||||
AuthenticationExpiredError,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_SLOTS = BoundedSemaphore(2)
|
||||
_CANCEL_SLOTS = BoundedSemaphore(4)
|
||||
|
||||
|
||||
def _failure_details(error: Exception) -> tuple[str, str]:
|
||||
"""Translate stable error codes, never echo an upstream exception/response."""
|
||||
if isinstance(error, ApiTimeoutError):
|
||||
code = "UPSTREAM_TIMEOUT"
|
||||
elif isinstance(error, AuthenticationExpiredError):
|
||||
code = "AUTH_REQUIRED"
|
||||
elif isinstance(error, ApiHttpError):
|
||||
code = ({401: "AUTH_REQUIRED", 403: "PERMISSION_DENIED", 404: "SERVICE_UPDATE_REQUIRED",
|
||||
405: "SERVICE_UPDATE_REQUIRED", 429: "RATE_LIMITED"}.get(error.status_code)
|
||||
or "UPSTREAM_UNAVAILABLE")
|
||||
elif isinstance(error, ApiBusinessError) and isinstance(error.data, Mapping):
|
||||
code = error.data.get("error_code") or error.data.get("code")
|
||||
elif isinstance(error, ApiProtocolError):
|
||||
code = "STREAM_INCOMPLETE"
|
||||
elif isinstance(error, ApiTransportError):
|
||||
code = "NETWORK_ERROR"
|
||||
elif isinstance(error, ValueError):
|
||||
code = "LIVE_RESULT_INVALID"
|
||||
else:
|
||||
code = "UPSTREAM_UNAVAILABLE"
|
||||
messages = {
|
||||
"UPSTREAM_TIMEOUT": "分析服务响应超时,可点击重新生成。",
|
||||
"AUTH_REQUIRED": "登录状态已失效,请重新登录后使用 AI 辅助。",
|
||||
"PERMISSION_DENIED": "当前账号没有 AI 辅助权限,请联系管理员开通。",
|
||||
"SERVICE_UPDATE_REQUIRED": "服务端尚不支持实时 AI,请更新服务端后重试。",
|
||||
"RATE_LIMITED": "分析请求较多,请稍后重新生成。",
|
||||
"LIVE_RESULT_INVALID": "本次建议未通过格式或引用校验,可点击重新生成。",
|
||||
"LIVE_CONTEXT_UNAVAILABLE": "本次通话的分析资料尚未就绪,请等待转写保存后重试。",
|
||||
"STREAM_INCOMPLETE": "分析连接提前结束,可点击重新生成。",
|
||||
"NETWORK_ERROR": "分析服务连接中断,请检查网络后重试。",
|
||||
"UPSTREAM_UNAVAILABLE": "分析服务暂时不可用,请稍后重新生成。",
|
||||
}
|
||||
if not isinstance(code, str) or code not in messages:
|
||||
code = "UPSTREAM_UNAVAILABLE"
|
||||
if code == "LIVE_RESULT_INVALID" and isinstance(getattr(error, "data", None), Mapping):
|
||||
reason = error.data.get("live_validation_reason")
|
||||
details = {
|
||||
"JSON_INVALID": "分析服务返回的格式不完整,可点击重新生成。",
|
||||
"SCHEMA_INVALID": "分析服务返回的格式不符合要求,可点击重新生成。",
|
||||
"CITATION_INVALID": "部分建议的原文引用无法核对,可点击重新生成。",
|
||||
"SOURCE_QUOTE_MISMATCH": "部分建议与引用原文不一致,可点击重新生成。",
|
||||
"SAFETY_REJECTED": "本次建议包含超出辅助范围的内容,未通过校验,可重新生成。",
|
||||
}
|
||||
if isinstance(reason, str) and reason in details:
|
||||
return code, details[reason]
|
||||
return code, messages[code]
|
||||
|
||||
|
||||
def empty_video_ai_state(available: bool) -> dict[str, Any]:
|
||||
return {
|
||||
"enabled": available, "available": available, "busy": False,
|
||||
"phase": "waiting", "message": ("接通并产生转写文字后,自动整理本次对话。" if available
|
||||
else "当前账号或服务暂不能使用 AI 辅助;语音转写可独立运行。"),
|
||||
"error": "", "revision": "", "throughTimestampMs": 0, "segmentCount": 0,
|
||||
"transcriptionStatus": "idle", "summary": [], "questions": [],
|
||||
"checks": [], "review": [], "sources": [],
|
||||
"elapsedMs": 0, "lastDurationMs": 0, "firstResultMs": None,
|
||||
"pendingSegments": 0, "errorCode": "", "analysisScope": "",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Job:
|
||||
generation: int
|
||||
call_id: int
|
||||
session_id: str
|
||||
dirty: int
|
||||
task: str
|
||||
started_at: float = 0.0
|
||||
first_result_ms: int | None = None
|
||||
revision: str = ""
|
||||
analysis_scope: str | None = None
|
||||
request_id: str = field(default_factory=lambda: str(uuid4()))
|
||||
cancelled: Event = field(default_factory=Event)
|
||||
cancel_sent: bool = False
|
||||
|
||||
|
||||
class LiveAiController:
|
||||
def __init__(self, repository: Any, *, diagnosis_id: int, enabled: bool,
|
||||
clock: Callable[[], float] = monotonic, interval: float = 2.0) -> None:
|
||||
self.repository = repository
|
||||
self.diagnosis_id = diagnosis_id
|
||||
self.available = enabled is True and callable(getattr(repository, "stream_video_ai", None))
|
||||
self._clock = clock
|
||||
self._interval = max(0, interval)
|
||||
self._lock = RLock()
|
||||
self._state = empty_video_ai_state(self.available)
|
||||
self._mailbox: dict[str, Any] | None = copy.deepcopy(self._state)
|
||||
self._closed = False
|
||||
self._generation = 0
|
||||
self._call_id = 0
|
||||
self._session_id = ""
|
||||
self._dirty = 0
|
||||
self._attempted = 0
|
||||
self._displayed_dirty = 0
|
||||
self._due = 0.0
|
||||
self._forced_task = ""
|
||||
self._running: _Job | None = None
|
||||
self._worker: Thread | None = None
|
||||
|
||||
def _publish(self, **changes: Any) -> None:
|
||||
self._state.update(changes)
|
||||
self._state["pendingSegments"] = max(0, self._dirty - self._displayed_dirty)
|
||||
self._mailbox = copy.deepcopy(self._state)
|
||||
|
||||
def take_state(self) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
result, self._mailbox = self._mailbox, None
|
||||
return None if self._closed else result
|
||||
|
||||
def bind(self, call_id: int, session_id: str) -> None:
|
||||
with self._lock:
|
||||
if self._closed or (self._call_id == call_id and self._session_id == session_id):
|
||||
return
|
||||
self._cancel()
|
||||
enabled = self._state["enabled"]
|
||||
self._generation += 1
|
||||
self._call_id, self._session_id = call_id, session_id
|
||||
self._dirty = self._attempted = 0
|
||||
self._displayed_dirty = 0
|
||||
self._forced_task = ""
|
||||
self._state = empty_video_ai_state(self.available)
|
||||
self._publish(enabled=enabled, transcriptionStatus="running" if session_id else "idle")
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Clear the previous call before a new call's model/storage is ready."""
|
||||
self.bind(0, "")
|
||||
|
||||
def changed(self, session_id: str) -> None:
|
||||
with self._lock:
|
||||
if self._closed or session_id != self._session_id:
|
||||
return
|
||||
was_clean = self._dirty == self._attempted
|
||||
self._dirty += 1
|
||||
if was_clean:
|
||||
# Coalesce a short speech burst without repeatedly moving the deadline.
|
||||
self._due = self._clock() + (0.8 if not self._state["revision"] else self._interval)
|
||||
self._publish()
|
||||
|
||||
def transcription_error(self, message: str, *, status: str = "partial") -> None:
|
||||
with self._lock:
|
||||
if not self._closed:
|
||||
self._publish(transcriptionStatus=status, error=message[:240])
|
||||
|
||||
def transcription_starting(self) -> None:
|
||||
with self._lock:
|
||||
if not self._closed:
|
||||
self._publish(transcriptionStatus="starting", error="")
|
||||
|
||||
def transcription_running(self, session_id: str) -> None:
|
||||
"""A retried cloud recognizer is ready without resetting saved evidence."""
|
||||
with self._lock:
|
||||
if not self._closed and session_id == self._session_id:
|
||||
self._publish(transcriptionStatus="running", error="")
|
||||
|
||||
def finish(self, session_id: str, status: str) -> None:
|
||||
with self._lock:
|
||||
if not self._closed and session_id == self._session_id:
|
||||
self._publish(transcriptionStatus=status)
|
||||
|
||||
def handle(self, action: str, enabled: Any = None) -> None:
|
||||
with self._lock:
|
||||
if self._closed or not self.available:
|
||||
return
|
||||
if action == "toggle" and isinstance(enabled, bool):
|
||||
if not enabled:
|
||||
self._cancel()
|
||||
self._publish(enabled=enabled, busy=False if not enabled else self._state["busy"],
|
||||
message="已暂停自动分析。" if not enabled else "有新增对话后自动更新。")
|
||||
return
|
||||
if action not in {"refresh", "review"} or not self._dirty or self._running is not None:
|
||||
return
|
||||
if action == "review" and self._state["transcriptionStatus"] not in {"completed", "partial"}:
|
||||
return
|
||||
self._forced_task = "live_review" if action == "review" else "live_consultation"
|
||||
self._due = self._clock()
|
||||
|
||||
def tick(self) -> None:
|
||||
with self._lock:
|
||||
if self._running is not None and self._current(self._running):
|
||||
elapsed = self._elapsed(self._running)
|
||||
if elapsed // 1000 != self._state["elapsedMs"] // 1000:
|
||||
self._publish(elapsedMs=elapsed)
|
||||
if (self._closed or not self.available or not self._call_id or not self._session_id
|
||||
or self._running is not None or not self._dirty
|
||||
or (not self._forced_task and (not self._state["enabled"] or self._dirty <= self._attempted))
|
||||
or self._clock() < self._due):
|
||||
return
|
||||
if not _SLOTS.acquire(blocking=False):
|
||||
return
|
||||
job = _Job(self._generation, self._call_id, self._session_id, self._dirty,
|
||||
self._forced_task or "live_consultation", started_at=self._clock())
|
||||
self._forced_task = ""
|
||||
self._attempted = self._dirty
|
||||
self._running = job
|
||||
self._publish(busy=True, phase="analyzing", error="", errorCode="", elapsedMs=0, firstResultMs=None,
|
||||
message="正在分析最新对话,优先整理下一步追问…")
|
||||
self._worker = Thread(target=self._run, args=(job,), name="video-ai", daemon=True)
|
||||
try:
|
||||
self._worker.start()
|
||||
except RuntimeError:
|
||||
self._running = None
|
||||
_SLOTS.release()
|
||||
self._publish(busy=False, phase="error", error="分析任务无法启动,请重试。")
|
||||
|
||||
def _elapsed(self, job: _Job) -> int:
|
||||
return max(0, int((self._clock() - job.started_at) * 1000))
|
||||
|
||||
def _current(self, job: _Job) -> bool:
|
||||
return not self._closed and job.generation == self._generation and not job.cancelled.is_set()
|
||||
|
||||
def _validated_result(self, job: _Job, event: Mapping[str, Any]) -> dict[str, Any]:
|
||||
context = event.get("live_context")
|
||||
result = event.get("live_assistance")
|
||||
# Only label the scope of validated displayed content. Older servers do
|
||||
# not report it; never infer dialogue-only behavior from the task name.
|
||||
scope = event.get("analysis_scope", "")
|
||||
if not isinstance(scope, str) or scope not in {"", "current_call_only", "authorized_case"}:
|
||||
raise ValueError("invalid analysis scope")
|
||||
if (not isinstance(context, Mapping) or not isinstance(result, Mapping)
|
||||
or event.get("diagnosis_id") != self.diagnosis_id
|
||||
or context.get("call_record_id") != job.call_id
|
||||
or context.get("transcription_session_id") != job.session_id
|
||||
or not isinstance(context.get("revision"), str)
|
||||
or not re.fullmatch(r"[a-f0-9]{64}", context["revision"])):
|
||||
raise ValueError("context mismatch")
|
||||
sources = context.get("sources")
|
||||
if not isinstance(sources, list) or len(sources) > 1000:
|
||||
raise ValueError("invalid evidence")
|
||||
known: set[str] = set()
|
||||
clean_sources = []
|
||||
for source in sources:
|
||||
if (not isinstance(source, Mapping) or not isinstance(source.get("id"), str)
|
||||
or not source["id"] or source["id"] in known
|
||||
or not isinstance(source.get("text"), str) or not source["text"].strip()
|
||||
or len(source["text"]) > 4000
|
||||
or source.get("role") not in {"doctor", "patient", "unknown"}
|
||||
or isinstance(source.get("timestamp_ms"), bool)
|
||||
or not isinstance(source.get("timestamp_ms"), int) or source["timestamp_ms"] < 0):
|
||||
raise ValueError("invalid source")
|
||||
known.add(source["id"])
|
||||
clean_sources.append({key: source.get(key) for key in ("id", "text", "role", "timestamp_ms")})
|
||||
cleaned: dict[str, Any] = {}
|
||||
for key in ("summary", "questions", "checks", "review"):
|
||||
items = result.get(key, [])
|
||||
if not isinstance(items, list) or len(items) > 6:
|
||||
raise ValueError("invalid items")
|
||||
cleaned[key] = []
|
||||
for item in items:
|
||||
if (not isinstance(item, Mapping) or not isinstance(item.get("text"), str)
|
||||
or not item["text"].strip() or len(item["text"]) > (4020 if key == "summary" else 600)
|
||||
or not isinstance(item.get("evidence_ids"), list)
|
||||
or not 1 <= len(item["evidence_ids"]) <= 8
|
||||
or any(not isinstance(s, str) or s not in known for s in item["evidence_ids"])
|
||||
or len(set(item["evidence_ids"])) != len(item["evidence_ids"])):
|
||||
raise ValueError("invalid cited item")
|
||||
reason = item.get("reason", "")
|
||||
if not isinstance(reason, str) or len(reason) > 600:
|
||||
raise ValueError("invalid reason")
|
||||
cleaned[key].append({"text": item["text"], "reason": reason,
|
||||
"evidence_ids": list(item["evidence_ids"])})
|
||||
count = context.get("segment_count")
|
||||
through = context.get("through_timestamp_ms")
|
||||
if (isinstance(count, bool) or not isinstance(count, int) or count < 1
|
||||
or isinstance(through, bool) or not isinstance(through, (int, float))
|
||||
or not math.isfinite(through) or through < 0
|
||||
or context.get("transcription_status") not in {"running", "completed", "partial"}):
|
||||
raise ValueError("invalid revision metadata")
|
||||
return {**cleaned, "sources": clean_sources, "revision": context["revision"], "analysisScope": scope,
|
||||
"segmentCount": count, "throughTimestampMs": through,
|
||||
"transcriptionStatus": context.get("transcription_status", "partial")}
|
||||
|
||||
def _run(self, job: _Job) -> None:
|
||||
events = None
|
||||
success = False
|
||||
try:
|
||||
if job.cancelled.is_set():
|
||||
return
|
||||
events = self.repository.stream_video_ai(
|
||||
self.diagnosis_id, call_record_id=job.call_id, transcription_session_id=job.session_id,
|
||||
task=job.task, request_id=job.request_id, cancelled=job.cancelled.is_set,
|
||||
)
|
||||
for event in events:
|
||||
with self._lock:
|
||||
if not self._current(job):
|
||||
return
|
||||
if event.get("event") in {"start", "progress"}:
|
||||
self._publish(message=str(event.get("message") or "正在分析本次对话…")[:200])
|
||||
elif event.get("event") in {"live_update", "done"}:
|
||||
result = self._validated_result(job, event)
|
||||
if job.revision and job.revision != result["revision"]:
|
||||
raise ValueError("revision changed inside a single snapshot")
|
||||
if job.analysis_scope is not None and job.analysis_scope != result["analysisScope"]:
|
||||
raise ValueError("analysis scope changed inside a single snapshot")
|
||||
job.revision = result["revision"]
|
||||
job.analysis_scope = result["analysisScope"]
|
||||
# Preserve a newer native completion status while an older
|
||||
# in-flight snapshot still reports running.
|
||||
if self._state["transcriptionStatus"] in {"completed", "partial", "failed"}:
|
||||
result["transcriptionStatus"] = self._state["transcriptionStatus"]
|
||||
complete = event.get("event") == "done"
|
||||
duration = self._elapsed(job)
|
||||
if job.first_result_ms is None and any(
|
||||
result[key] for key in ("summary", "questions", "checks", "review")
|
||||
):
|
||||
job.first_result_ms = duration
|
||||
self._displayed_dirty = job.dirty
|
||||
self._publish(**result, busy=not complete,
|
||||
phase="ready" if complete else "analyzing", error="", errorCode="",
|
||||
elapsedMs=duration,
|
||||
firstResultMs=job.first_result_ms,
|
||||
lastDurationMs=duration if complete else self._state["lastDurationMs"],
|
||||
message="已更新,请对照原话复核。" if complete
|
||||
else "已显示可核对的建议,其余内容仍在整理。")
|
||||
if complete:
|
||||
success = True
|
||||
return
|
||||
if not job.cancelled.is_set():
|
||||
raise ApiProtocolError("incomplete stream")
|
||||
except Exception as error:
|
||||
with self._lock:
|
||||
if self._current(job):
|
||||
code, message = _failure_details(error)
|
||||
self._publish(busy=False, phase="error", error=message, errorCode=code,
|
||||
elapsedMs=self._elapsed(job), lastDurationMs=self._elapsed(job),
|
||||
message=("已显示的建议仍可核对,本次分析尚未全部完成。"
|
||||
if job.first_result_ms is not None else
|
||||
"保留上次结果;新内容尚未分析完成。" if any(
|
||||
self._state[key] for key in ("summary", "questions", "checks", "review")
|
||||
) else
|
||||
"本次暂未生成可用建议,可点击重新生成。"))
|
||||
# Log categories/timing only, never response text or patient details.
|
||||
_LOGGER.warning("video_ai_failed code=%s type=%s duration_ms=%d",
|
||||
code, type(error).__name__, self._elapsed(job))
|
||||
finally:
|
||||
if events is not None and callable(getattr(events, "close", None)):
|
||||
with suppress(Exception):
|
||||
events.close()
|
||||
with self._lock:
|
||||
if not success:
|
||||
self._send_cancel(job)
|
||||
if self._running is job:
|
||||
self._running = None
|
||||
_SLOTS.release()
|
||||
if success:
|
||||
_LOGGER.info("video_ai_completed duration_ms=%d first_result_ms=%s",
|
||||
self._elapsed(job), job.first_result_ms)
|
||||
|
||||
def _cancel(self) -> None:
|
||||
if self._running is not None:
|
||||
self._running.cancelled.set()
|
||||
self._send_cancel(self._running)
|
||||
|
||||
def _send_cancel(self, job: _Job) -> None:
|
||||
if job.cancel_sent or not _CANCEL_SLOTS.acquire(blocking=False):
|
||||
return
|
||||
job.cancel_sent = True
|
||||
|
||||
def cancel() -> None:
|
||||
try:
|
||||
self.repository.cancel_diagnosis_ai(self.diagnosis_id, job.request_id)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
_CANCEL_SLOTS.release()
|
||||
try:
|
||||
Thread(target=cancel, name="video-ai-cancel", daemon=True).start()
|
||||
except RuntimeError:
|
||||
_CANCEL_SLOTS.release()
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
self._closed = True
|
||||
self._cancel()
|
||||
self._mailbox = None
|
||||
|
||||
def wait(self, timeout: float = 1.0) -> bool:
|
||||
if self._worker is not None:
|
||||
self._worker.join(max(0, min(timeout, 5)))
|
||||
return self._worker is None or not self._worker.is_alive()
|
||||
@@ -1,446 +0,0 @@
|
||||
"""Bounded, in-memory speech recognition using an explicitly installed local model.
|
||||
|
||||
This module has no dependency on Qt, the recording queue, or the call lifecycle.
|
||||
Callbacks run on one daemon worker and must only enqueue work (for example, emit
|
||||
a Qt signal). Runtime code never downloads a model or sends audio to a service.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
from collections import deque
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from platformdirs import user_data_path
|
||||
|
||||
from ..core.transcript_text import simplified_transcript
|
||||
|
||||
SAMPLE_RATE = 16_000
|
||||
MAX_CHUNK_SECONDS = 12
|
||||
MAX_PCM_BYTES = SAMPLE_RATE * 2 * MAX_CHUNK_SECONDS
|
||||
MAX_BASE64_CHARS = ((MAX_PCM_BYTES + 2) // 3) * 4
|
||||
MAX_SEQUENCE = 2_147_483_647
|
||||
MAX_TIMESTAMP_MS = 253_402_300_799_999
|
||||
MAX_TRANSCRIPT_CHARS = 4_000
|
||||
_SESSION_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}\Z")
|
||||
_REQUIRED_FILES = ("model.bin", "config.json", "tokenizer.json")
|
||||
_DEPENDENCIES = ("faster_whisper", "numpy", "ctranslate2", "onnxruntime", "opencc")
|
||||
_MESSAGES = {
|
||||
"model_missing": "本地语音模型未安装或文件不完整,请先运行本地转写安装工具。",
|
||||
"dependency_missing": "本地转写运行库未安装,请先安装本地转写依赖。",
|
||||
"dependency_unavailable": "本地转写运行库无法加载,请检查安装包及系统运行库。",
|
||||
"model_load_failed": "本地语音模型加载失败,请检查模型文件和本机运行环境。",
|
||||
"conversion_unavailable": "简体转换字典无法加载,请修复本地转写安装。",
|
||||
"invalid_audio": "本地转写音频格式无效,需要最长 12 秒的单声道 16 kHz PCM16 音频。",
|
||||
"invalid_metadata": "本地转写音频的角色、序号或时间戳无效。",
|
||||
"sequence_out_of_order": "本地转写音频序号重复或倒序,该片段未被接受。",
|
||||
"sequence_gap": "本地转写检测到音频片段缺失,转写结果可能不完整。",
|
||||
"overloaded": "本地转写处理速度不足,部分音频片段未转写;通话和录音继续。",
|
||||
"transcription_failed": "本地音频片段转写失败,结果可能不完整;通话和录音继续。",
|
||||
}
|
||||
|
||||
|
||||
def default_model_path() -> Path:
|
||||
"""Return the model directory without creating it or accessing the network."""
|
||||
override = os.getenv("DOCTOR_ASR_MODEL_PATH", "").strip()
|
||||
if override:
|
||||
return Path(override).expanduser().resolve()
|
||||
bundle = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parents[3]))
|
||||
bundled_model = bundle / "resources" / "local-asr" / "model"
|
||||
if bundled_model.is_dir():
|
||||
return bundled_model
|
||||
return (
|
||||
user_data_path("ZhenyangDoctorWorkstation", appauthor="ZhenYangTang")
|
||||
/ "local-asr"
|
||||
/ "model"
|
||||
)
|
||||
|
||||
|
||||
def _missing_model_files(path: Path) -> list[str]:
|
||||
def exists(name: str) -> bool:
|
||||
try:
|
||||
file = path / name
|
||||
return file.is_file() and file.stat().st_size > 0
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
missing = [name for name in _REQUIRED_FILES if not exists(name)]
|
||||
if not any(exists(name) for name in ("vocabulary.txt", "vocabulary.json")):
|
||||
missing.append("vocabulary.txt or vocabulary.json")
|
||||
return missing
|
||||
|
||||
|
||||
def local_transcription_readiness(model_path: Path | str | None = None) -> dict[str, Any]:
|
||||
"""Cheap installation preflight; ``available`` does not claim a model has loaded."""
|
||||
path = Path(model_path).expanduser().resolve() if model_path else default_model_path()
|
||||
missing_dependencies = []
|
||||
for name in _DEPENDENCIES:
|
||||
try:
|
||||
available = importlib.util.find_spec(name) is not None
|
||||
except (ImportError, ValueError):
|
||||
available = False
|
||||
if not available:
|
||||
missing_dependencies.append(name)
|
||||
missing_files = _missing_model_files(path)
|
||||
code = (
|
||||
"model_missing" if missing_files else "dependency_missing" if missing_dependencies else ""
|
||||
)
|
||||
return {
|
||||
"available": not (missing_files or missing_dependencies),
|
||||
"modelPath": str(path),
|
||||
"missingDependencies": missing_dependencies,
|
||||
"missingFiles": missing_files,
|
||||
"code": code,
|
||||
"message": _MESSAGES.get(code, "本地转写文件检查通过,启动后将加载模型。"),
|
||||
}
|
||||
|
||||
|
||||
class LocalTranscriptionError(RuntimeError):
|
||||
"""A fixed, patient-data-free error suitable for displaying in the UI."""
|
||||
|
||||
def __init__(self, code: str) -> None:
|
||||
self.code = code if code in _MESSAGES else "transcription_failed"
|
||||
super().__init__(_MESSAGES[self.code])
|
||||
|
||||
|
||||
class SpeechEngine(Protocol):
|
||||
def transcribe(self, pcm: bytes) -> str:
|
||||
"""Return verbatim recognized text for mono, little-endian PCM16 at 16 kHz."""
|
||||
|
||||
|
||||
class FasterWhisperEngine:
|
||||
"""CPU/int8 recognition. Construct only on a background worker or setup CLI."""
|
||||
|
||||
def __init__(self, model_path: Path | str | None = None) -> None:
|
||||
path = Path(model_path).expanduser().resolve() if model_path else default_model_path()
|
||||
# In particular, require tokenizer.json: upstream may otherwise fetch a
|
||||
# tokenizer even when WhisperModel(local_files_only=True) is requested.
|
||||
if _missing_model_files(path):
|
||||
raise LocalTranscriptionError("model_missing")
|
||||
try:
|
||||
import numpy as np
|
||||
from faster_whisper import WhisperModel
|
||||
from faster_whisper.vad import get_vad_model
|
||||
except ModuleNotFoundError:
|
||||
raise LocalTranscriptionError("dependency_missing") from None
|
||||
except (ImportError, OSError):
|
||||
raise LocalTranscriptionError("dependency_unavailable") from None
|
||||
self._np = np
|
||||
try:
|
||||
# Load local dictionaries before ready, so a broken/frozen install
|
||||
# cannot claim successful ASR and then fail on its first sentence.
|
||||
simplified_transcript("")
|
||||
except ImportError:
|
||||
raise LocalTranscriptionError("dependency_missing") from None
|
||||
except Exception:
|
||||
raise LocalTranscriptionError("conversion_unavailable") from None
|
||||
try:
|
||||
self._model = WhisperModel(
|
||||
str(path),
|
||||
device="cpu",
|
||||
compute_type="int8",
|
||||
cpu_threads=min(4, max(1, (os.cpu_count() or 2) // 2)),
|
||||
num_workers=1,
|
||||
local_files_only=True,
|
||||
)
|
||||
# Silero's ONNX asset ships inside faster-whisper; preflight it so
|
||||
# a packaged application cannot report ready with a missing VAD.
|
||||
get_vad_model()
|
||||
except Exception:
|
||||
raise LocalTranscriptionError("model_load_failed") from None
|
||||
|
||||
def transcribe(self, pcm: bytes) -> str:
|
||||
if not pcm or len(pcm) % 2 or len(pcm) > MAX_PCM_BYTES:
|
||||
raise LocalTranscriptionError("invalid_audio")
|
||||
if not any(pcm):
|
||||
return ""
|
||||
audio = self._np.frombuffer(pcm, dtype="<i2").astype(self._np.float32) / 32768.0
|
||||
segments, _ = self._model.transcribe(
|
||||
audio,
|
||||
language="zh",
|
||||
task="transcribe",
|
||||
beam_size=5,
|
||||
temperature=0.0,
|
||||
condition_on_previous_text=False,
|
||||
vad_filter=True,
|
||||
vad_parameters={
|
||||
"min_speech_duration_ms": 0,
|
||||
"min_silence_duration_ms": 500,
|
||||
"speech_pad_ms": 400,
|
||||
},
|
||||
)
|
||||
# Iterating is essential: faster-whisper returns a lazy generator. Do
|
||||
# not rewrite numbers, units, negations, repetitions, or short answers.
|
||||
return "".join(segment.text for segment in segments).strip()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Chunk:
|
||||
role: str
|
||||
sequence: int
|
||||
timestamp_ms: int
|
||||
pcm: bytes
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Session:
|
||||
id: str
|
||||
initialized: bool = False
|
||||
stopping: bool = False
|
||||
stopped: bool = False
|
||||
partial: bool = False
|
||||
last_sequence: dict[str, int] = field(default_factory=dict)
|
||||
chunks: deque[_Chunk] = field(default_factory=deque)
|
||||
errors: deque[str] = field(default_factory=deque)
|
||||
reported_errors: set[str] = field(default_factory=set)
|
||||
|
||||
|
||||
class LocalTranscriptionController:
|
||||
"""One bounded daemon worker, isolated by session object identity.
|
||||
|
||||
``start`` accepts a new session, replacing queued old work. ``submit`` only
|
||||
acknowledges enqueueing, while ``ready`` confirms successful model loading.
|
||||
``stop`` rejects further submissions and drains accepted chunks in order.
|
||||
``close`` cancels immediately without waiting for native inference. No
|
||||
callbacks from an old generation occur after start/close returns.
|
||||
|
||||
The callback must be quick, thread-safe, and must not join/wait for another
|
||||
thread that is calling this controller. It is invoked under a reentrant
|
||||
lock, which makes close/session replacement atomic with callback delivery.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
on_event: Callable[[dict[str, Any]], None],
|
||||
engine_factory: Callable[[], SpeechEngine] | None = None,
|
||||
*,
|
||||
max_pending_chunks: int = 12,
|
||||
) -> None:
|
||||
if type(max_pending_chunks) is not int or not 1 <= max_pending_chunks <= 64:
|
||||
raise ValueError("max_pending_chunks must be an integer between 1 and 64")
|
||||
self._on_event = on_event
|
||||
self._engine_factory = engine_factory or FasterWhisperEngine
|
||||
self._max_pending_chunks = max_pending_chunks
|
||||
self._condition = threading.Condition(threading.RLock())
|
||||
self._session: _Session | None = None
|
||||
self._engine: SpeechEngine | None = None
|
||||
self._closed = False
|
||||
self._worker: threading.Thread | None = None
|
||||
|
||||
def start(self, session_id: str) -> bool:
|
||||
if not isinstance(session_id, str) or not _SESSION_ID.fullmatch(session_id):
|
||||
return False
|
||||
with self._condition:
|
||||
if self._closed:
|
||||
return False
|
||||
if self._session and self._session.id == session_id:
|
||||
return not (self._session.stopping or self._session.stopped)
|
||||
if self._session:
|
||||
self._session.chunks.clear()
|
||||
self._session.errors.clear()
|
||||
self._session = _Session(session_id)
|
||||
if self._worker is None:
|
||||
self._worker = threading.Thread(
|
||||
target=self._run, name="doctor-local-asr", daemon=True
|
||||
)
|
||||
self._worker.start()
|
||||
self._condition.notify_all()
|
||||
return True
|
||||
|
||||
def submit(
|
||||
self,
|
||||
session_id: str,
|
||||
role: str,
|
||||
sequence: int,
|
||||
timestamp_ms: int,
|
||||
pcm_base64: str,
|
||||
) -> bool:
|
||||
with self._condition:
|
||||
session = self._session
|
||||
if (
|
||||
self._closed
|
||||
or session is None
|
||||
or session.id != session_id
|
||||
or session.stopping
|
||||
or session.stopped
|
||||
):
|
||||
return False
|
||||
if (
|
||||
role not in ("doctor", "patient")
|
||||
or type(sequence) is not int
|
||||
or not 0 <= sequence <= MAX_SEQUENCE
|
||||
or type(timestamp_ms) is not int
|
||||
or not 0 < timestamp_ms <= MAX_TIMESTAMP_MS
|
||||
):
|
||||
self._error_locked(session, "invalid_metadata")
|
||||
return False
|
||||
if (
|
||||
not isinstance(pcm_base64, str)
|
||||
or not pcm_base64
|
||||
or len(pcm_base64) > MAX_BASE64_CHARS
|
||||
):
|
||||
self._error_locked(session, "invalid_audio")
|
||||
return False
|
||||
try:
|
||||
pcm = base64.b64decode(pcm_base64, validate=True)
|
||||
except (ValueError, binascii.Error):
|
||||
self._error_locked(session, "invalid_audio")
|
||||
return False
|
||||
if not pcm or len(pcm) % 2 or len(pcm) > MAX_PCM_BYTES:
|
||||
self._error_locked(session, "invalid_audio")
|
||||
return False
|
||||
previous = session.last_sequence.get(role)
|
||||
if previous is not None and sequence <= previous:
|
||||
self._error_locked(session, "sequence_out_of_order")
|
||||
return False
|
||||
if previous is not None and sequence != previous + 1:
|
||||
self._error_locked(session, "sequence_gap")
|
||||
session.last_sequence[role] = sequence
|
||||
if len(session.chunks) >= self._max_pending_chunks:
|
||||
self._error_locked(session, "overloaded")
|
||||
return False
|
||||
session.chunks.append(_Chunk(role, sequence, timestamp_ms, pcm))
|
||||
self._condition.notify_all()
|
||||
return True
|
||||
|
||||
def stop(self, session_id: str) -> bool:
|
||||
with self._condition:
|
||||
session = self._session
|
||||
if self._closed or session is None or session.id != session_id:
|
||||
return False
|
||||
session.stopping = True
|
||||
self._condition.notify_all()
|
||||
return True
|
||||
|
||||
def close(self) -> None:
|
||||
with self._condition:
|
||||
self._closed = True
|
||||
if self._session:
|
||||
self._session.chunks.clear()
|
||||
self._session.errors.clear()
|
||||
self._session = None
|
||||
self._condition.notify_all()
|
||||
|
||||
def _error_locked(self, session: _Session, code: str) -> None:
|
||||
session.partial = True
|
||||
# At most one pending/report per fixed error code, even when the browser
|
||||
# continues submitting into an overloaded queue. No unbounded UI queue.
|
||||
if code not in session.reported_errors:
|
||||
session.reported_errors.add(code)
|
||||
session.errors.append(code)
|
||||
self._condition.notify_all()
|
||||
|
||||
def _emit(self, session: _Session, event: dict[str, Any]) -> None:
|
||||
with self._condition:
|
||||
if self._closed or self._session is not session:
|
||||
return
|
||||
# A detached UI must not kill the worker or expose transcript
|
||||
# contents through exception logging.
|
||||
with suppress(Exception):
|
||||
self._on_event({"sessionId": session.id, **event})
|
||||
|
||||
def _initialize(self, session: _Session) -> None:
|
||||
try:
|
||||
if self._engine is None:
|
||||
self._engine = self._engine_factory()
|
||||
except Exception as error:
|
||||
code = error.code if isinstance(error, LocalTranscriptionError) else "model_load_failed"
|
||||
with self._condition:
|
||||
if self._closed or self._session is not session:
|
||||
return
|
||||
session.initialized = True
|
||||
session.stopping = True
|
||||
session.chunks.clear()
|
||||
self._error_locked(session, code)
|
||||
return
|
||||
with self._condition:
|
||||
if self._closed or self._session is not session:
|
||||
return
|
||||
session.initialized = True
|
||||
if not session.stopping:
|
||||
self._emit(session, {"type": "ready"})
|
||||
|
||||
def _transcribe(self, session: _Session, chunk: _Chunk) -> None:
|
||||
try:
|
||||
# Reject only exact digital silence here. VAD in the real engine
|
||||
# handles room noise without an amplitude cutoff that loses quiet
|
||||
# numerals or one-word negations.
|
||||
if not any(chunk.pcm):
|
||||
return
|
||||
assert self._engine is not None
|
||||
text = self._engine.transcribe(chunk.pcm)
|
||||
if not isinstance(text, str) or len(text) > MAX_TRANSCRIPT_CHARS:
|
||||
raise LocalTranscriptionError("transcription_failed")
|
||||
# Normalize before persistence and captions, so AI evidence and the
|
||||
# doctor's visible transcript refer to the exact same text.
|
||||
text = simplified_transcript(text.strip())
|
||||
if text:
|
||||
self._emit(
|
||||
session,
|
||||
{
|
||||
"type": "segment",
|
||||
"segmentId": f"{session.id}:{chunk.role}:{chunk.sequence}",
|
||||
"role": chunk.role,
|
||||
"text": text,
|
||||
"timestamp": chunk.timestamp_ms,
|
||||
"isCompleted": True,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
with self._condition:
|
||||
if not self._closed and self._session is session:
|
||||
self._error_locked(session, "transcription_failed")
|
||||
|
||||
def _run(self) -> None:
|
||||
try:
|
||||
while True:
|
||||
with self._condition:
|
||||
while True:
|
||||
if self._closed:
|
||||
return
|
||||
session = self._session
|
||||
if session is not None and not session.stopped:
|
||||
if session.errors:
|
||||
action, payload = "error", session.errors.popleft()
|
||||
break
|
||||
if not session.initialized:
|
||||
action, payload = "initialize", None
|
||||
break
|
||||
if session.chunks:
|
||||
action, payload = "chunk", session.chunks.popleft()
|
||||
break
|
||||
if session.stopping:
|
||||
session.stopped = True
|
||||
action, payload = "stopped", None
|
||||
break
|
||||
self._condition.wait()
|
||||
if action == "initialize":
|
||||
self._initialize(session)
|
||||
elif action == "chunk":
|
||||
self._transcribe(session, payload)
|
||||
payload = None # Release raw PCM before waiting for work.
|
||||
elif action == "error":
|
||||
self._emit(
|
||||
session,
|
||||
{"type": "error", "code": payload, "message": _MESSAGES[payload]},
|
||||
)
|
||||
else:
|
||||
self._emit(
|
||||
session,
|
||||
{
|
||||
"type": "stopped",
|
||||
"status": "partial" if session.partial else "completed",
|
||||
},
|
||||
)
|
||||
finally:
|
||||
self._engine = None
|
||||
@@ -1,124 +0,0 @@
|
||||
"""Capture the rendered call region without accessing the rest of the desktop."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ScreenshotPreviewSize:
|
||||
"""Temporarily give a compact call the same space as a normal preview."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._state: tuple[Any, Any, Any] | None = None
|
||||
|
||||
def open(self, window: Any, target: Any = None) -> None:
|
||||
from PySide6.QtCore import QRect
|
||||
|
||||
if self._state is not None or window.isMaximized() or window.isFullScreen():
|
||||
return
|
||||
screen = window.screen()
|
||||
if screen is None:
|
||||
return
|
||||
available = screen.availableGeometry().adjusted(24, 24, -24, -24)
|
||||
if available.isEmpty():
|
||||
return
|
||||
original = window.geometry()
|
||||
width = min(available.width(), max(original.width(), target.width() if target else 1120))
|
||||
height = min(available.height(), max(original.height(), target.height() if target else 760))
|
||||
if original.width() >= width and original.height() >= height:
|
||||
return
|
||||
expanded = QRect(
|
||||
available.x() + (available.width() - width) // 2,
|
||||
available.y() + (available.height() - height) // 2,
|
||||
width,
|
||||
height,
|
||||
)
|
||||
window.setGeometry(expanded)
|
||||
self._state = (original, window.geometry(), window.property("doctorSkipOpenGeometry"))
|
||||
|
||||
def restore(self, window: Any) -> None:
|
||||
state, self._state = self._state, None
|
||||
if state is None:
|
||||
return
|
||||
original, expanded, compact_flag = state
|
||||
# A diagnosis closing or a manual resize takes priority over this temporary size.
|
||||
if (
|
||||
window.isMaximized()
|
||||
or window.isFullScreen()
|
||||
or window.geometry() != expanded
|
||||
or window.property("doctorSkipOpenGeometry") != compact_flag
|
||||
):
|
||||
return
|
||||
window.setGeometry(original)
|
||||
|
||||
|
||||
def capture_view_region(web_view: Any, region: Mapping[str, Any]) -> str:
|
||||
"""Map CSS viewport coordinates to Qt logical pixels; retain composited video."""
|
||||
|
||||
from PySide6.QtCore import QBuffer, QByteArray, QIODevice, QRect, Qt
|
||||
|
||||
values: dict[str, float] = {}
|
||||
for key in ("x", "y", "width", "height", "viewportWidth", "viewportHeight"):
|
||||
value = region.get(key)
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ValueError("截屏区域无效,请重试。")
|
||||
try:
|
||||
value = float(value)
|
||||
except OverflowError as error:
|
||||
raise ValueError("截屏区域无效,请重试。") from error
|
||||
if not math.isfinite(value):
|
||||
raise ValueError("截屏区域无效,请重试。")
|
||||
values[key] = value
|
||||
|
||||
viewport_width = values["viewportWidth"]
|
||||
viewport_height = values["viewportHeight"]
|
||||
if min(viewport_width, viewport_height, values["width"], values["height"]) <= 0:
|
||||
raise ValueError("视频区域尚未显示,请稍后重试。")
|
||||
left = max(0.0, values["x"])
|
||||
top = max(0.0, values["y"])
|
||||
right = min(viewport_width, values["x"] + values["width"])
|
||||
bottom = min(viewport_height, values["y"] + values["height"])
|
||||
if right <= left or bottom <= top:
|
||||
raise ValueError("视频区域尚未显示,请稍后重试。")
|
||||
|
||||
zoom = web_view.zoomFactor()
|
||||
tolerance = max(2.0, 2 * zoom)
|
||||
if (
|
||||
abs(viewport_width * zoom - web_view.width()) > tolerance
|
||||
or abs(viewport_height * zoom - web_view.height()) > tolerance
|
||||
):
|
||||
raise ValueError("视频窗口尺寸已变化,请重新截屏。")
|
||||
|
||||
# QWebEngine's zoom and Windows display scaling are independent. grab() takes
|
||||
# widget logical coordinates and returns an image at the widget's pixel ratio.
|
||||
scale_x = web_view.width() / viewport_width
|
||||
scale_y = web_view.height() / viewport_height
|
||||
x = math.ceil(left * scale_x)
|
||||
y = math.ceil(top * scale_y)
|
||||
width = math.floor(right * scale_x) - x
|
||||
height = math.floor(bottom * scale_y) - y
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError("视频区域尚未显示,请稍后重试。")
|
||||
rect = QRect(x, y, width, height).intersected(web_view.rect())
|
||||
if rect.isEmpty():
|
||||
raise ValueError("视频区域尚未显示,请稍后重试。")
|
||||
|
||||
image = web_view.grab(rect).toImage()
|
||||
if image.isNull():
|
||||
raise ValueError("截屏失败,请稍后重试。")
|
||||
if max(image.width(), image.height()) > 1920:
|
||||
image = image.scaled(
|
||||
1920, 1920,
|
||||
Qt.AspectRatioMode.KeepAspectRatio,
|
||||
Qt.TransformationMode.SmoothTransformation,
|
||||
)
|
||||
data = QByteArray()
|
||||
buffer = QBuffer(data)
|
||||
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
if not image.save(buffer, "JPEG", 90):
|
||||
raise ValueError("截屏图片生成失败,请重试。")
|
||||
buffer.close()
|
||||
return "data:image/jpeg;base64," + base64.b64encode(bytes(data)).decode("ascii")
|
||||
@@ -11,7 +11,6 @@ import base64
|
||||
import binascii
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
@@ -29,15 +28,12 @@ from ..services.local_audio_queue import (
|
||||
LocalAudioUploadManager,
|
||||
get_local_audio_upload_manager,
|
||||
)
|
||||
from .im_ai import ImAiController
|
||||
from .launcher import (
|
||||
VideoCallRequest,
|
||||
VideoTicketError,
|
||||
require_supported_backend,
|
||||
)
|
||||
from .lifecycle import OrderedCallLifecycle, normalize_transcript_segment
|
||||
from .live_ai import LiveAiController
|
||||
from .screenshot import ScreenshotPreviewSize, capture_view_region
|
||||
from .lifecycle import OrderedCallLifecycle
|
||||
from .security import TrustedDocumentError, TrustedDocumentPolicy
|
||||
|
||||
try: # Optional by design: core-only builds must still import this module.
|
||||
@@ -192,29 +188,9 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
return None
|
||||
|
||||
class _QtVideoBridge(QObject): # type: ignore[misc, valid-type]
|
||||
def __init__(
|
||||
self,
|
||||
callback: Callable[[Mapping[str, Any]], None],
|
||||
capture_screenshot: Callable[[Mapping[str, Any]], str],
|
||||
) -> None:
|
||||
def __init__(self, callback: Callable[[Mapping[str, Any]], None]) -> None:
|
||||
super().__init__()
|
||||
self._callback = callback
|
||||
self._capture_screenshot = capture_screenshot
|
||||
|
||||
@Slot(str, result=str) # type: ignore[misc]
|
||||
def captureScreenshot(self, payload: str) -> str: # noqa: N802 - Qt bridge API
|
||||
"""Return a local preview only; persistence still needs saveScreenshot."""
|
||||
|
||||
try:
|
||||
if not isinstance(payload, str) or len(payload) > 2048:
|
||||
raise ValueError("截屏区域无效,请重试。")
|
||||
region = json.loads(payload)
|
||||
if not isinstance(region, Mapping):
|
||||
raise ValueError("截屏区域无效,请重试。")
|
||||
result = {"dataUrl": self._capture_screenshot(region)}
|
||||
except (ValueError, TypeError, RuntimeError):
|
||||
result = {"error": "无法截取当前视频画面,请稍后重试。"}
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
|
||||
@Slot(str) # type: ignore[misc]
|
||||
def notify(self, payload: str) -> None:
|
||||
@@ -298,16 +274,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
}
|
||||
)
|
||||
|
||||
@Slot(str, str, int, float, str) # type: ignore[misc]
|
||||
def appendLocalTranscriptionChunk( # noqa: N802
|
||||
self, session_id: str, role: str, sequence: int, timestamp: float, encoded: str
|
||||
) -> None:
|
||||
if len(encoded) > 512_000:
|
||||
return
|
||||
self._callback({"source": "doctor-call", "event": "local-transcription-chunk",
|
||||
"sessionId": session_id, "role": role, "sequence": sequence,
|
||||
"timestamp": timestamp, "data": encoded})
|
||||
|
||||
class _EmbeddedVideoWindow(QMainWindow): # type: ignore[misc, valid-type]
|
||||
status_changed = Signal(str) # type: ignore[misc]
|
||||
call_ended = Signal(str) # type: ignore[misc]
|
||||
@@ -316,8 +282,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
_policy_completed = Signal(str, object) # type: ignore[misc]
|
||||
_room_completed = Signal(str, bool, str) # type: ignore[misc]
|
||||
_screenshot_completed = Signal(bool, str) # type: ignore[misc]
|
||||
_transcription_completed = Signal(str, str, str, bool, str, str) # type: ignore[misc]
|
||||
_local_transcription_event = Signal(object) # type: ignore[misc]
|
||||
_transcription_completed = Signal(str, str, str, bool, str) # type: ignore[misc]
|
||||
_local_recording_completed = Signal( # type: ignore[misc]
|
||||
str, str, int, bool, str
|
||||
)
|
||||
@@ -334,8 +299,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
repository: Any = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.request = request
|
||||
@@ -348,7 +311,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self.patient_name = str(patient_name or "患者").strip() or "患者"
|
||||
self.patient_case = dict(patient_case or {})
|
||||
self._on_open_diagnosis = on_open_diagnosis
|
||||
self._on_compact_close: Callable[[], None] | None = None
|
||||
try:
|
||||
self._policy = TrustedDocumentPolicy.from_url(
|
||||
location.url,
|
||||
@@ -365,33 +327,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self._call_cycle_closed = False
|
||||
self._start_requested = False
|
||||
self._shutdown_requested = False
|
||||
self._im_ai = ImAiController(
|
||||
repository,
|
||||
diagnosis_id=request.diagnosis_id,
|
||||
appointment_id=request.appointment_id,
|
||||
doctor_account=request.user_id,
|
||||
enabled=can_ai_assistant is True and self.open_im,
|
||||
)
|
||||
self._im_ai_timer = QTimer(self)
|
||||
self._im_ai_timer.setInterval(60)
|
||||
self._im_ai_timer.timeout.connect(self._flush_im_ai)
|
||||
if self._im_ai.enabled:
|
||||
self._im_ai_timer.start()
|
||||
self._live_ai = LiveAiController(
|
||||
repository, diagnosis_id=request.diagnosis_id, enabled=can_ai_assistant is True,
|
||||
)
|
||||
# The default recognizer is Tencent's existing call transcriber.
|
||||
# Keep local audio recording independent; no local model is loaded.
|
||||
self._local_transcription = None
|
||||
self._asr_session_id = ""
|
||||
self._asr_ready = False
|
||||
self._asr_partial = False
|
||||
self._transcription_final_status = "idle"
|
||||
self._video_ai_timer = QTimer(self)
|
||||
self._video_ai_timer.setInterval(100)
|
||||
self._video_ai_timer.timeout.connect(self._flush_video_ai)
|
||||
self._video_ai_timer.start()
|
||||
self._screenshot_preview_size = ScreenshotPreviewSize()
|
||||
self._local_audio_capture: _LocalAudioCapture | None = None
|
||||
self._local_audio_store: LocalAudioQueueStore | None = None
|
||||
self._local_audio_uploads: LocalAudioUploadManager | None = None
|
||||
@@ -428,9 +363,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self.setCentralWidget(self.web_view)
|
||||
|
||||
self._configure_settings(self._page.settings())
|
||||
self._bridge = _QtVideoBridge(
|
||||
self._handle_bridge_message, self._capture_screenshot_preview
|
||||
)
|
||||
self._bridge = _QtVideoBridge(self._handle_bridge_message)
|
||||
self._channel = QWebChannel(self._page)
|
||||
self._channel.registerObject("qtVideoBridge", self._bridge)
|
||||
self._page.setWebChannel(self._channel)
|
||||
@@ -441,7 +374,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self._room_completed.connect(self._on_room_completed)
|
||||
self._screenshot_completed.connect(self._on_screenshot_completed)
|
||||
self._transcription_completed.connect(self._on_transcription_completed)
|
||||
self._local_transcription_event.connect(self._on_local_transcription)
|
||||
self._local_recording_completed.connect(self._on_local_recording_completed)
|
||||
self.web_view.loadFinished.connect(self._on_load_finished)
|
||||
self.web_view.setUrl(QUrl(self.location.url))
|
||||
@@ -517,7 +449,8 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
"embedded video companion failed to load",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
self._request_companion_shutdown("page-load-failed")
|
||||
self._close_reason = "page-load-failed"
|
||||
self.close()
|
||||
return
|
||||
|
||||
self._media_active = True
|
||||
@@ -526,7 +459,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
"patientName": self.patient_name,
|
||||
"patientCase": self.patient_case,
|
||||
"mode": "chat" if self.open_im else "video",
|
||||
"imAi": self._im_ai.config,
|
||||
}
|
||||
config_json = json.dumps(config, ensure_ascii=True, separators=(",", ":"))
|
||||
script = f"""
|
||||
@@ -567,37 +499,13 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
def _after_injection(self, result: Any) -> None:
|
||||
self._injected = result is not False
|
||||
if not self._injected:
|
||||
self._request_companion_shutdown("bridge-api-missing")
|
||||
return
|
||||
if not self._im_ai_context_is_trusted():
|
||||
return
|
||||
# open() may finish IM login before runJavaScript returns. Only
|
||||
# acknowledge readiness after the native request gate is open.
|
||||
session_id = json.dumps(self._im_ai.session_id, ensure_ascii=True)
|
||||
self._page.runJavaScript(
|
||||
f"window.doctorConsultation?.imAiReady?.({session_id});"
|
||||
)
|
||||
self._close_reason = "bridge-api-missing"
|
||||
self.close()
|
||||
|
||||
def _handle_bridge_message(self, message: Mapping[str, Any]) -> None:
|
||||
if self._closing:
|
||||
return
|
||||
event = str(message.get("event", ""))
|
||||
if event.startswith("local-transcription-"):
|
||||
# An old companion must not start a second recognizer.
|
||||
return
|
||||
if event == "video-ai-action":
|
||||
self._handle_video_assistance_message(message)
|
||||
return
|
||||
if event.startswith("transcription-") and not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
if event in {"im-ai-request", "im-ai-cancel"}:
|
||||
self._handle_im_ai_message(message)
|
||||
return
|
||||
if event == "screenshot-preview":
|
||||
visible = message.get("visible")
|
||||
if isinstance(visible, bool):
|
||||
self._set_screenshot_preview_visible(visible)
|
||||
return
|
||||
if event == "open-diagnosis-request":
|
||||
if self._on_open_diagnosis is not None:
|
||||
QTimer.singleShot(0, self._open_diagnosis_safely)
|
||||
@@ -640,9 +548,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self._abort_local_audio_recording(str(message.get("sessionId") or ""))
|
||||
return
|
||||
if event == "transcription-start-request":
|
||||
if (self._shutdown_requested or not self._start_requested
|
||||
or self._call_cycle_closed or not self.lifecycle.call_record_id):
|
||||
return
|
||||
self._start_transcription(
|
||||
str(message.get("sessionId") or ""),
|
||||
str(message.get("language") or "zh-CN"),
|
||||
@@ -651,22 +556,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
if event == "transcription-segment":
|
||||
self._save_transcript_segment(message)
|
||||
return
|
||||
if event == "transcription-ready":
|
||||
session_id = str(message.get("sessionId") or "")
|
||||
if (not self._shutdown_requested and session_id
|
||||
and session_id == str(self.lifecycle.transcription_session_id or "")):
|
||||
self._live_ai.transcription_running(session_id)
|
||||
return
|
||||
if event == "transcription-error":
|
||||
if (str(message.get("sessionId") or "")
|
||||
== str(self.lifecycle.transcription_session_id or "")
|
||||
and self.lifecycle.transcription_session_id):
|
||||
self._asr_partial = True
|
||||
self._live_ai.transcription_error(
|
||||
str(message.get("message") or "腾讯云实时转写未完成,请重试。")[:240],
|
||||
status="failed",
|
||||
)
|
||||
return
|
||||
if event == "transcription-stop":
|
||||
self._finish_transcription(
|
||||
str(message.get("sessionId") or ""),
|
||||
@@ -705,139 +594,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
if not self.open_im or self._shutdown_requested:
|
||||
self._close_from_companion("companion-error")
|
||||
|
||||
def _im_ai_context_is_trusted(self) -> bool:
|
||||
return (
|
||||
not self._closing
|
||||
and not self._released
|
||||
and not self._shutdown_requested
|
||||
and self._injected
|
||||
and self._policy.allows_main_document(self._page.url().toString())
|
||||
)
|
||||
|
||||
def _handle_im_ai_message(self, message: Mapping[str, Any]) -> None:
|
||||
if self._im_ai_context_is_trusted():
|
||||
self._im_ai.handle(message)
|
||||
|
||||
def _flush_im_ai(self) -> None:
|
||||
if not self._im_ai_context_is_trusted():
|
||||
return
|
||||
result = self._im_ai.take_result()
|
||||
if result is not None:
|
||||
payload = json.dumps(result, ensure_ascii=True, separators=(",", ":"))
|
||||
self._page.runJavaScript(f"window.doctorConsultation?.imAiResult?.({payload});")
|
||||
|
||||
def _close_im_ai(self) -> None:
|
||||
controller = getattr(self, "_im_ai", None)
|
||||
if controller is not None:
|
||||
controller.close()
|
||||
timer = getattr(self, "_im_ai_timer", None)
|
||||
if timer is not None:
|
||||
timer.stop()
|
||||
|
||||
def _local_transcription_context_is_trusted(self) -> bool:
|
||||
return (not self._closing and not self._released and self._injected
|
||||
and self._policy.allows_main_document(self._page.url().toString()))
|
||||
|
||||
def _handle_video_assistance_message(self, message: Mapping[str, Any]) -> None:
|
||||
if not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
event = message.get("event")
|
||||
if event == "video-ai-action":
|
||||
if not self._shutdown_requested:
|
||||
self._live_ai.handle(str(message.get("action") or ""), message.get("enabled"))
|
||||
return
|
||||
session_id = str(message.get("sessionId") or "")
|
||||
if event == "local-transcription-start":
|
||||
if (self._shutdown_requested or not self._start_requested or self._call_cycle_closed
|
||||
or not self.lifecycle.call_record_id
|
||||
or re.fullmatch(r"[A-Za-z0-9_-]{1,128}", session_id) is None):
|
||||
return
|
||||
existing = str(self.lifecycle.transcription_session_id or "")
|
||||
if existing and existing != session_id:
|
||||
return
|
||||
was_ready = self._asr_session_id == session_id and self._asr_ready
|
||||
if self._asr_session_id != session_id:
|
||||
self._asr_partial = False
|
||||
self._asr_ready = False
|
||||
self._asr_session_id = session_id
|
||||
self._live_ai.transcription_starting()
|
||||
accepted = self._local_transcription.start(session_id)
|
||||
if accepted and was_ready:
|
||||
self._on_local_transcription({"type": "ready", "sessionId": session_id})
|
||||
elif not accepted:
|
||||
self._on_local_transcription({"type": "error", "sessionId": session_id,
|
||||
"message": "本次转写已结束,请重新发起通话。"})
|
||||
elif session_id and session_id == self._asr_session_id:
|
||||
if event == "local-transcription-chunk":
|
||||
if session_id != str(self.lifecycle.transcription_session_id or ""):
|
||||
return
|
||||
timestamp = message.get("timestamp")
|
||||
if (isinstance(timestamp, bool) or not isinstance(timestamp, (int, float))
|
||||
or not math.isfinite(timestamp) or not 0 < timestamp < 2**53):
|
||||
return
|
||||
self._local_transcription.submit(
|
||||
session_id, str(message.get("role") or ""), message.get("sequence"),
|
||||
int(timestamp), str(message.get("data") or ""),
|
||||
)
|
||||
elif event == "local-transcription-stop":
|
||||
self._local_transcription.stop(session_id)
|
||||
|
||||
def _emit_local_transcription(self, event: dict[str, Any]) -> None:
|
||||
with suppress(RuntimeError):
|
||||
self._local_transcription_event.emit(event)
|
||||
|
||||
def _on_local_transcription(self, event: Mapping[str, Any]) -> None:
|
||||
if (not self._local_transcription_context_is_trusted()
|
||||
or event.get("sessionId") != self._asr_session_id):
|
||||
return
|
||||
kind = event.get("type")
|
||||
if kind == "ready":
|
||||
self._asr_ready = True
|
||||
elif kind == "stopped":
|
||||
self._asr_ready = False
|
||||
elif kind == "segment":
|
||||
role = event.get("role")
|
||||
if role not in {"doctor", "patient"}:
|
||||
return
|
||||
self._save_transcript_segment({
|
||||
"sessionId": self._asr_session_id,
|
||||
"segment": {
|
||||
"segment_id": event.get("segmentId"),
|
||||
"speaker_role": role,
|
||||
"speaker_user_id": (self.request.user_id if role == "doctor"
|
||||
else self.request.target_user_id),
|
||||
"timestamp": event.get("timestamp"), "text": event.get("text"),
|
||||
},
|
||||
})
|
||||
elif kind == "error":
|
||||
self._asr_partial = True
|
||||
self._live_ai.transcription_error(
|
||||
str(event.get("message") or "本地转写未完成"),
|
||||
status="partial" if self._asr_ready else "failed",
|
||||
)
|
||||
payload = json.dumps(dict(event), ensure_ascii=True, separators=(",", ":"))
|
||||
self._page.runJavaScript(f"window.doctorConsultation?.localTranscriptionEvent?.({payload});")
|
||||
|
||||
def _flush_video_ai(self) -> None:
|
||||
if not self._local_transcription_context_is_trusted() or self._shutdown_requested:
|
||||
return
|
||||
self._live_ai.tick()
|
||||
state = self._live_ai.take_state()
|
||||
if state is not None:
|
||||
payload = json.dumps(state, ensure_ascii=True, separators=(",", ":"))
|
||||
self._page.runJavaScript(f"window.doctorConsultation?.videoAiState?.({payload});")
|
||||
|
||||
def _close_video_assistance(self, *, close_asr: bool = True) -> None:
|
||||
controller = getattr(self, "_live_ai", None)
|
||||
if controller is not None:
|
||||
controller.close()
|
||||
timer = getattr(self, "_video_ai_timer", None)
|
||||
if timer is not None:
|
||||
timer.stop()
|
||||
controller = getattr(self, "_local_transcription", None)
|
||||
if close_asr and controller is not None:
|
||||
controller.close()
|
||||
|
||||
def _open_diagnosis_safely(self) -> None:
|
||||
if self._closing or self._on_open_diagnosis is None:
|
||||
return
|
||||
@@ -1222,12 +978,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
if self._closing or self._shutdown_requested or self._start_requested:
|
||||
return
|
||||
self._prepare_call_cycle()
|
||||
live_ai = getattr(self, "_live_ai", None)
|
||||
if live_ai is not None:
|
||||
live_ai.reset()
|
||||
self._asr_session_id = ""
|
||||
self._asr_ready = False
|
||||
self._asr_partial = False
|
||||
self._start_requested = True
|
||||
try:
|
||||
future = self.lifecycle.start(call_type=call_type)
|
||||
@@ -1237,30 +987,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
return
|
||||
future.add_done_callback(self._notify_start_completed)
|
||||
|
||||
def _set_screenshot_preview_visible(self, visible: bool) -> None:
|
||||
if self._closing or self._released:
|
||||
return
|
||||
if not self._policy.allows_main_document(self._page.url().toString()):
|
||||
return
|
||||
if not visible:
|
||||
self.restore_screenshot_preview()
|
||||
return
|
||||
if self._shutdown_requested or not self._media_active:
|
||||
return
|
||||
from ..ui.theme import main_window_target_rect
|
||||
|
||||
self._screenshot_preview_size.open(self, main_window_target_rect(self))
|
||||
|
||||
def restore_screenshot_preview(self) -> None:
|
||||
self._screenshot_preview_size.restore(self)
|
||||
|
||||
def _capture_screenshot_preview(self, region: Mapping[str, Any]) -> str:
|
||||
if self._closing or self._released or self._shutdown_requested or not self._media_active:
|
||||
raise ValueError("视频窗口已关闭。")
|
||||
if not self._policy.allows_main_document(self._page.url().toString()):
|
||||
raise ValueError("视频页面不可用。")
|
||||
return capture_view_region(self.web_view, region)
|
||||
|
||||
def _save_screenshot(self, data_url: str) -> None:
|
||||
prefix = "data:image/jpeg;base64,"
|
||||
if not data_url.startswith(prefix):
|
||||
@@ -1306,7 +1032,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
session_id: str,
|
||||
segment_id: str,
|
||||
future: Future[bool],
|
||||
normalized_segment: Mapping[str, Any] | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
succeeded = bool(future.result())
|
||||
@@ -1321,8 +1046,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
}.get(operation, "")
|
||||
with suppress(RuntimeError):
|
||||
self._transcription_completed.emit(
|
||||
operation, session_id, segment_id, succeeded, message,
|
||||
json.dumps(normalized_segment if succeeded else None, ensure_ascii=True),
|
||||
operation, session_id, segment_id, succeeded, message
|
||||
)
|
||||
|
||||
def _on_transcription_completed(
|
||||
@@ -1332,47 +1056,16 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
segment_id: str,
|
||||
succeeded: bool,
|
||||
message: str,
|
||||
normalized_segment: str | Mapping[str, Any] | None = None,
|
||||
) -> None:
|
||||
if not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
live_ai = getattr(self, "_live_ai", None)
|
||||
if (live_ai is not None
|
||||
and session_id == str(self.lifecycle.transcription_session_id or "")):
|
||||
if operation == "start" and succeeded:
|
||||
live_ai.bind(int(self.lifecycle.call_record_id), session_id)
|
||||
elif operation == "start":
|
||||
live_ai.transcription_error(message or "转写文字存储未就绪,请重试。", status="failed")
|
||||
elif operation == "segment":
|
||||
if succeeded:
|
||||
live_ai.changed(session_id)
|
||||
else:
|
||||
self._asr_partial = True
|
||||
live_ai.transcription_error("部分对话文字保存失败,分析资料可能不完整。")
|
||||
elif operation == "stop":
|
||||
live_ai.finish(session_id, self._transcription_final_status if succeeded else "partial")
|
||||
payload = json.dumps(str(message)[:200], ensure_ascii=True)
|
||||
state = "true" if succeeded else "false"
|
||||
if isinstance(normalized_segment, str):
|
||||
try:
|
||||
normalized_segment = json.loads(normalized_segment)
|
||||
except (ValueError, TypeError):
|
||||
normalized_segment = None
|
||||
caption = json.dumps(
|
||||
dict(normalized_segment)
|
||||
if succeeded and operation == "segment" and isinstance(normalized_segment, Mapping)
|
||||
else None,
|
||||
ensure_ascii=True,
|
||||
)
|
||||
self._page.runJavaScript(
|
||||
"window.doctorConsultation?.transcriptionResult?.("
|
||||
f"{json.dumps(operation)}, {json.dumps(session_id)}, "
|
||||
f"{json.dumps(segment_id)}, {state}, {payload}, {caption});"
|
||||
f"{json.dumps(segment_id)}, {state}, {payload});"
|
||||
)
|
||||
|
||||
def _start_transcription(self, session_id: str, language: str) -> None:
|
||||
if not self._local_transcription_context_is_trusted() or self._shutdown_requested:
|
||||
return
|
||||
try:
|
||||
future = self.lifecycle.start_transcription(session_id, language=language)
|
||||
except Exception as error:
|
||||
@@ -1380,7 +1073,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
"start", session_id, "", False, str(error)[:200]
|
||||
)
|
||||
return
|
||||
self._live_ai.transcription_starting()
|
||||
future.add_done_callback(
|
||||
lambda completed: self._notify_transcription_completed(
|
||||
"start", session_id, "", completed
|
||||
@@ -1388,8 +1080,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
)
|
||||
|
||||
def _save_transcript_segment(self, message: Mapping[str, Any]) -> None:
|
||||
if not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
session_id = str(message.get("sessionId") or "").strip()
|
||||
segment = message.get("segment")
|
||||
segment_id = (
|
||||
@@ -1408,44 +1098,25 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
)
|
||||
return
|
||||
try:
|
||||
normalized = normalize_transcript_segment(segment, session_id)
|
||||
speaker = normalized["speaker_user_id"]
|
||||
normalized["speaker_role"] = (
|
||||
"doctor" if speaker == self.request.user_id
|
||||
else "patient" if speaker == self.request.target_user_id
|
||||
else "unknown"
|
||||
)
|
||||
future = self.lifecycle.save_transcript_segment(normalized)
|
||||
future = self.lifecycle.save_transcript_segment(segment)
|
||||
except Exception as error:
|
||||
self._on_transcription_completed(
|
||||
"segment", session_id, segment_id, False, str(error)[:200]
|
||||
)
|
||||
return
|
||||
caption = {
|
||||
"segmentId": normalized["segment_id"],
|
||||
"speakerUserId": normalized["speaker_user_id"],
|
||||
"sourceText": normalized["text"],
|
||||
"timestamp": normalized["timestamp"],
|
||||
"isCompleted": True,
|
||||
}
|
||||
future.add_done_callback(
|
||||
lambda completed: self._notify_transcription_completed(
|
||||
"segment", session_id, segment_id, completed, caption
|
||||
"segment", session_id, segment_id, completed
|
||||
)
|
||||
)
|
||||
|
||||
def _finish_transcription(self, session_id: str, status: str) -> None:
|
||||
if not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
if session_id.strip() != str(self.lifecycle.transcription_session_id or ""):
|
||||
self._on_transcription_completed(
|
||||
"stop", session_id, "", False, "录音会话标识不匹配。"
|
||||
)
|
||||
return
|
||||
try:
|
||||
if getattr(self, "_asr_partial", False):
|
||||
status = "partial"
|
||||
self._transcription_final_status = status
|
||||
future = self.lifecycle.finish_transcription(status=status)
|
||||
except Exception as error:
|
||||
self._on_transcription_completed(
|
||||
@@ -1466,16 +1137,9 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
def hangup(self) -> None:
|
||||
self._request_companion_shutdown("desktop-hangup")
|
||||
|
||||
def set_compact_close_handler(self, callback: Callable[[], None] | None) -> None:
|
||||
"""Let the compact title-bar close return to the same full call window."""
|
||||
|
||||
self._on_compact_close = callback
|
||||
|
||||
def _request_companion_shutdown(self, reason: str) -> None:
|
||||
"""Let MediaRecorder finish and upload before WebEngine is destroyed."""
|
||||
|
||||
_EmbeddedVideoWindow._close_im_ai(self)
|
||||
_EmbeddedVideoWindow._close_video_assistance(self, close_asr=False)
|
||||
self._close_reason = reason
|
||||
if self._closing or self._released:
|
||||
return
|
||||
@@ -1486,7 +1150,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
and not self._companion_ended
|
||||
)
|
||||
if not should_wait_for_companion:
|
||||
self._shutdown_requested = True
|
||||
self.close()
|
||||
return
|
||||
if self._shutdown_requested:
|
||||
@@ -1520,9 +1183,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
def _begin_shutdown(self) -> None:
|
||||
if self._closing:
|
||||
return
|
||||
_EmbeddedVideoWindow._close_im_ai(self)
|
||||
_EmbeddedVideoWindow._close_video_assistance(self)
|
||||
self._on_compact_close = None
|
||||
self._closing = True
|
||||
self._media_active = False
|
||||
self._shutdown_timer.stop()
|
||||
@@ -1580,16 +1240,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self._profile.deleteLater()
|
||||
|
||||
def closeEvent(self, event: Any) -> None:
|
||||
if (
|
||||
self._on_compact_close is not None
|
||||
and not self._shutdown_requested
|
||||
and not self._companion_ended
|
||||
and not self._closing
|
||||
and not self._released
|
||||
):
|
||||
event.ignore()
|
||||
self._on_compact_close()
|
||||
return
|
||||
if (
|
||||
self._injected
|
||||
and self._start_requested
|
||||
@@ -1623,7 +1273,6 @@ class VideoCallWindow:
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
) -> None:
|
||||
del browser_opener # Reserved for a future authenticated handoff implementation.
|
||||
try:
|
||||
@@ -1642,7 +1291,6 @@ class VideoCallWindow:
|
||||
self.open_im = bool(open_im)
|
||||
self.patient_name = str(patient_name or "患者").strip() or "患者"
|
||||
self.patient_case = dict(patient_case or {})
|
||||
self.can_ai_assistant = can_ai_assistant is True
|
||||
self.on_open_diagnosis = on_open_diagnosis
|
||||
self.logger = logger or _LOGGER
|
||||
self.location = resolve_companion_location(
|
||||
@@ -1674,8 +1322,6 @@ class VideoCallWindow:
|
||||
patient_name=self.patient_name,
|
||||
patient_case=self.patient_case,
|
||||
on_open_diagnosis=self.on_open_diagnosis,
|
||||
can_ai_assistant=self.can_ai_assistant,
|
||||
repository=self.repository,
|
||||
)
|
||||
except Exception:
|
||||
self.lifecycle.end("window-open-failed")
|
||||
@@ -1695,7 +1341,7 @@ class VideoCallWindow:
|
||||
|
||||
def close(self) -> None:
|
||||
if self._session is not None:
|
||||
self._session._request_companion_shutdown("window-closed")
|
||||
self._session.close()
|
||||
else:
|
||||
self.lifecycle.end("unopened-session")
|
||||
|
||||
@@ -1721,7 +1367,6 @@ def open_video_call(
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
) -> VideoCallWindow:
|
||||
"""Create and immediately open a trusted embedded video window."""
|
||||
|
||||
@@ -1738,7 +1383,6 @@ def open_video_call(
|
||||
patient_name=patient_name,
|
||||
patient_case=patient_case,
|
||||
on_open_diagnosis=on_open_diagnosis,
|
||||
can_ai_assistant=can_ai_assistant,
|
||||
).open()
|
||||
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@ from PySide6.QtWidgets import (
|
||||
|
||||
from doctor_workstation.core import PermissionSet
|
||||
from doctor_workstation.services import ApiClient, DemoDoctorRepository, RemoteDoctorRepository
|
||||
from doctor_workstation.ui.design_system import PALETTE
|
||||
from doctor_workstation.ui.dialogs import ai_consult as ai_consult_module
|
||||
from doctor_workstation.ui.dialogs.ai_consult import (
|
||||
AiConsultDialog,
|
||||
@@ -2307,14 +2306,14 @@ def test_risk_block_uses_the_red_alert_palette() -> None:
|
||||
assert "#FEF3F2" in risk_card
|
||||
assert "#F1B35C" not in risk_card # 旧的橙色描边
|
||||
marker = qss.split("QLabel#AiConsultRiskMarker {", 1)[1].split("}", 1)[0]
|
||||
assert PALETTE["danger"] in marker
|
||||
assert "#BE4B58" in marker
|
||||
|
||||
|
||||
def test_clinical_bodies_are_no_longer_rendered_at_eleven_pixels() -> None:
|
||||
qss = ai_consult_module.AI_CONSULT_QSS
|
||||
|
||||
body = qss.rsplit("QLabel#AiConsultRiskBody {", 1)[1].split("}", 1)[0]
|
||||
assert f'color: {PALETTE["text"]}' in body
|
||||
assert "color: #1a1c1f" in body.lower()
|
||||
assert "font-size: 14px" in body
|
||||
block = qss.split("QLabel#AiConsultClinicalBody,", 1)[1].split("}", 1)[0]
|
||||
assert "font-size: 14px" in block
|
||||
|
||||
@@ -10,7 +10,6 @@ from PySide6.QtCore import QDate, QSize, Qt
|
||||
from PySide6.QtWidgets import QApplication, QStyle, QStyleOptionButton, QWidget
|
||||
|
||||
from doctor_workstation.ui.appointment_drawer import APPOINTMENT_DRAWER_QSS, AppointmentDrawer
|
||||
from doctor_workstation.ui.design_system import PALETTE
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -566,39 +565,8 @@ def test_keyboard_focus_has_a_visible_state(
|
||||
assert focus_target.hasFocus()
|
||||
assert application.focusWidget() is focus_target
|
||||
assert 'QPushButton[appointmentDate="true"]:focus' in APPOINTMENT_DRAWER_QSS
|
||||
assert f"border-color: {PALETTE['focus']};" in APPOINTMENT_DRAWER_QSS
|
||||
assert "border-color: #8B9AD9;" in APPOINTMENT_DRAWER_QSS
|
||||
|
||||
drawer.close()
|
||||
host.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("button_kind", ["date", "slot"])
|
||||
def test_appointment_hover_keeps_hit_target_stable_after_relayout(
|
||||
application: QApplication, button_kind: str,
|
||||
) -> None:
|
||||
"""Hovering must not move a time choice or restore a stale layout position."""
|
||||
from PySide6.QtCore import QEvent, QPoint, QPointF
|
||||
from PySide6.QtGui import QEnterEvent
|
||||
|
||||
host, drawer = _show_drawer(
|
||||
application, (1440, 900), repository=_VisualRepository(), autoload=True,
|
||||
)
|
||||
tomorrow = QDate.currentDate().addDays(1).toString("yyyy-MM-dd")
|
||||
button = drawer.date_buttons[tomorrow] if button_kind == "date" else drawer.slot_buttons["09:30-10:00"]
|
||||
original = button.geometry()
|
||||
try:
|
||||
for _ in range(3):
|
||||
application.sendEvent(button, QEnterEvent(QPointF(10, 10), QPointF(30, 34), QPointF(30, 34)))
|
||||
assert button.geometry() == original
|
||||
assert button.graphicsEffect() is None
|
||||
relocated = original.topLeft() + QPoint(12, 16)
|
||||
button.move(relocated) # A resize/reflow while the pointer stays inside.
|
||||
application.sendEvent(button, QEvent(QEvent.Type.Leave))
|
||||
assert button.pos() == relocated
|
||||
button.setGeometry(original)
|
||||
button.click()
|
||||
assert button.isChecked()
|
||||
finally:
|
||||
drawer.close()
|
||||
host.close()
|
||||
|
||||
@@ -1,362 +0,0 @@
|
||||
"""Cloud ASR reaches UI and live AI only after trusted, normalized persistence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from concurrent.futures import Future
|
||||
from types import MethodType, SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.video import window
|
||||
from doctor_workstation.video.security import TrustedDocumentPolicy
|
||||
|
||||
pytestmark = pytest.mark.skipif(not window.WEBENGINE_AVAILABLE, reason="optional QtWebEngine")
|
||||
TRUSTED = "https://video.example.test/call/index.html"
|
||||
SESSION = "tr-cloud-test"
|
||||
SOURCE = "沒有過敏,沒有吃藥。0.5 mg,不是 5 mg。血壓 120/80 mmHg。\n唔係,冇食藥。"
|
||||
SIMPLIFIED = "没有过敏,没有吃药。0.5 mg,不是 5 mg。血压 120/80 mmHg。\n唔系,冇食药。"
|
||||
TIMESTAMP = 1793332800000
|
||||
|
||||
|
||||
def host(**changes):
|
||||
item = SimpleNamespace(
|
||||
_closing=False, _released=False, _shutdown_requested=False, _injected=True,
|
||||
_start_requested=True, _call_cycle_closed=False,
|
||||
_policy=TrustedDocumentPolicy.from_url(TRUSTED, is_local=False),
|
||||
_page=Mock(), _local_transcription=Mock(), _live_ai=Mock(),
|
||||
_asr_session_id=SESSION, _asr_ready=False, _asr_partial=False,
|
||||
_transcription_final_status="completed", _transcription_completed=Mock(),
|
||||
request=SimpleNamespace(user_id="doctor_test", target_user_id="patient_test"),
|
||||
lifecycle=SimpleNamespace(
|
||||
call_record_id=71, transcription_session_id=SESSION,
|
||||
start_transcription=Mock(return_value=Future()),
|
||||
save_transcript_segment=Mock(return_value=Future()),
|
||||
finish_transcription=Mock(return_value=Future()),
|
||||
),
|
||||
_start_local_audio_recording=Mock(), _append_local_audio_chunk=Mock(),
|
||||
_finish_local_audio_recording=Mock(), _abort_local_audio_recording=Mock(),
|
||||
)
|
||||
item._page.url.return_value.toString.return_value = TRUSTED
|
||||
for name in (
|
||||
"_handle_bridge_message", "_handle_video_assistance_message",
|
||||
"_local_transcription_context_is_trusted", "_start_transcription",
|
||||
"_save_transcript_segment", "_finish_transcription",
|
||||
"_notify_transcription_completed", "_on_transcription_completed",
|
||||
):
|
||||
setattr(item, name, MethodType(getattr(window._EmbeddedVideoWindow, name), item))
|
||||
item._transcription_completed.emit.side_effect = item._on_transcription_completed
|
||||
for name, value in changes.items():
|
||||
setattr(item, name, value)
|
||||
return item
|
||||
|
||||
|
||||
def segment_message(**changes):
|
||||
return {
|
||||
"source": "doctor-call", "event": "transcription-segment", "sessionId": SESSION,
|
||||
"segment": {
|
||||
"segment_id": "cloud-segment-1", "speaker_user_id": "patient_test",
|
||||
"speaker_role": "doctor", "timestamp": TIMESTAMP, "text": SOURCE,
|
||||
},
|
||||
**changes,
|
||||
}
|
||||
|
||||
|
||||
def transcription_result(item):
|
||||
script = item._page.runJavaScript.call_args.args[0]
|
||||
assert script.startswith("window.doctorConsultation?.transcriptionResult?.(")
|
||||
assert script.endswith(");")
|
||||
return json.loads("[" + script.split("?.(", 1)[1][:-2] + "]")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("speaker_id", "expected_role"),
|
||||
[("doctor_test", "doctor"), ("patient_test", "patient"), ("other_test", "unknown")],
|
||||
)
|
||||
def test_trusted_cloud_segment_is_normalized_and_role_is_host_derived(speaker_id, expected_role):
|
||||
item = host()
|
||||
message = segment_message()
|
||||
message["segment"]["speaker_user_id"] = speaker_id
|
||||
item._handle_bridge_message(message)
|
||||
|
||||
item.lifecycle.save_transcript_segment.assert_called_once()
|
||||
saved = item.lifecycle.save_transcript_segment.call_args.args[0]
|
||||
assert saved["text"] == SIMPLIFIED
|
||||
assert saved["speaker_role"] == expected_role
|
||||
assert saved["speaker_user_id"] == speaker_id
|
||||
assert saved["segment_id"] == "cloud-segment-1"
|
||||
assert saved["timestamp"] == TIMESTAMP
|
||||
assert message["segment"]["text"] == SOURCE
|
||||
item._live_ai.changed.assert_not_called()
|
||||
item._page.runJavaScript.assert_not_called()
|
||||
|
||||
item.lifecycle.save_transcript_segment.return_value.set_result(True)
|
||||
|
||||
result = transcription_result(item)
|
||||
assert result == [
|
||||
"segment", SESSION, "cloud-segment-1", True, "",
|
||||
{"segmentId": "cloud-segment-1", "speakerUserId": speaker_id,
|
||||
"sourceText": SIMPLIFIED, "timestamp": TIMESTAMP, "isCompleted": True},
|
||||
]
|
||||
assert len(item._transcription_completed.emit.call_args.args) == 6
|
||||
item._live_ai.changed.assert_called_once_with(SESSION)
|
||||
item._local_transcription.start.assert_not_called()
|
||||
item._local_transcription.submit.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", [False, RuntimeError("storage unavailable")])
|
||||
def test_failed_storage_never_returns_normalized_text_or_dirties_ai(failure):
|
||||
item = host()
|
||||
item._handle_bridge_message(segment_message())
|
||||
future = item.lifecycle.save_transcript_segment.return_value
|
||||
if isinstance(failure, Exception):
|
||||
future.set_exception(failure)
|
||||
else:
|
||||
future.set_result(failure)
|
||||
|
||||
result = transcription_result(item)
|
||||
assert result[:4] == ["segment", SESSION, "cloud-segment-1", False]
|
||||
assert len(result) == 6 and result[5] is None
|
||||
assert item._asr_partial
|
||||
item._live_ai.changed.assert_not_called()
|
||||
item._live_ai.transcription_error.assert_called_once()
|
||||
|
||||
|
||||
def test_synchronous_storage_failure_has_no_normalized_ack():
|
||||
item = host()
|
||||
item.lifecycle.save_transcript_segment.side_effect = RuntimeError("storage unavailable")
|
||||
item._handle_bridge_message(segment_message())
|
||||
result = transcription_result(item)
|
||||
assert result[:4] == ["segment", SESSION, "cloud-segment-1", False]
|
||||
assert result[5] is None
|
||||
item._live_ai.changed.assert_not_called()
|
||||
|
||||
|
||||
def test_camel_case_cloud_segment_uses_the_same_normalized_contract():
|
||||
item = host()
|
||||
item._handle_bridge_message(segment_message(segment={
|
||||
"segmentId": "cloud-segment-2", "speakerUserId": " doctor_test ",
|
||||
"speakerRole": "patient", "sourceText": SOURCE, "timestamp": TIMESTAMP,
|
||||
}))
|
||||
saved = item.lifecycle.save_transcript_segment.call_args.args[0]
|
||||
assert saved["speaker_role"] == "doctor"
|
||||
assert saved["speaker_user_id"] == "doctor_test"
|
||||
assert saved["text"] == SIMPLIFIED
|
||||
item.lifecycle.save_transcript_segment.return_value.set_result(True)
|
||||
assert transcription_result(item)[5] == {
|
||||
"segmentId": "cloud-segment-2", "speakerUserId": "doctor_test",
|
||||
"sourceText": SIMPLIFIED, "timestamp": TIMESTAMP, "isCompleted": True,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("segment", [
|
||||
None, {}, {"segment_id": "s1", "text": " "},
|
||||
{"segment_id": "s1", "text": "字" * 4001},
|
||||
])
|
||||
def test_malformed_segment_is_rejected_before_storage(segment):
|
||||
item = host()
|
||||
item._handle_bridge_message(segment_message(segment=segment))
|
||||
item.lifecycle.save_transcript_segment.assert_not_called()
|
||||
result = transcription_result(item)
|
||||
assert result[0] == "segment" and result[3] is False and result[5] is None
|
||||
item._live_ai.changed.assert_not_called()
|
||||
|
||||
|
||||
def test_conversion_failure_does_not_store_or_ack_unnormalized_text(monkeypatch):
|
||||
def unavailable_dictionary(_text):
|
||||
raise RuntimeError("conversion dictionary unavailable")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"doctor_workstation.video.lifecycle.simplified_transcript", unavailable_dictionary,
|
||||
)
|
||||
item = host()
|
||||
item._handle_bridge_message(segment_message())
|
||||
item.lifecycle.save_transcript_segment.assert_not_called()
|
||||
result = transcription_result(item)
|
||||
assert result[:4] == ["segment", SESSION, "cloud-segment-1", False]
|
||||
assert result[5] is None
|
||||
item._live_ai.changed.assert_not_called()
|
||||
|
||||
|
||||
def test_json_ack_preserves_text_without_inserting_executable_source():
|
||||
item = host()
|
||||
message = segment_message()
|
||||
message["segment"]["text"] = '沒有;0.5 mg,不是 5 mg。</script>"\\\u2028\u2029結尾'
|
||||
item._handle_bridge_message(message)
|
||||
item.lifecycle.save_transcript_segment.return_value.set_result(True)
|
||||
result = transcription_result(item)
|
||||
assert result[5]["sourceText"] == '没有;0.5 mg,不是 5 mg。</script>"\\\u2028\u2029结尾'
|
||||
script = item._page.runJavaScript.call_args.args[0]
|
||||
assert "\u2028" not in script and "\u2029" not in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize("session_id", ["tr-old-call", ""])
|
||||
def test_segment_for_another_or_empty_session_is_not_saved(session_id):
|
||||
item = host()
|
||||
item._handle_bridge_message(segment_message(sessionId=session_id))
|
||||
item.lifecycle.save_transcript_segment.assert_not_called()
|
||||
item._live_ai.changed.assert_not_called()
|
||||
|
||||
|
||||
def test_late_persistence_completion_does_not_dirty_new_call():
|
||||
item = host()
|
||||
item._handle_bridge_message(segment_message())
|
||||
original_future = item.lifecycle.save_transcript_segment.return_value
|
||||
item.lifecycle = SimpleNamespace(call_record_id=72, transcription_session_id="tr-new-call")
|
||||
item._asr_session_id = "tr-new-call"
|
||||
original_future.set_result(True)
|
||||
item._live_ai.changed.assert_not_called()
|
||||
item._live_ai.bind.assert_not_called()
|
||||
item._live_ai.finish.assert_not_called()
|
||||
|
||||
|
||||
def test_navigation_before_persistence_ack_blocks_page_delivery_and_ai_change():
|
||||
item = host()
|
||||
item._handle_bridge_message(segment_message())
|
||||
item._page.url.return_value.toString.return_value = "https://another.example.test/"
|
||||
item.lifecycle.save_transcript_segment.return_value.set_result(True)
|
||||
item._page.runJavaScript.assert_not_called()
|
||||
item._live_ai.changed.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("succeeded", [True, False])
|
||||
def test_start_marks_starting_and_binds_only_after_successful_storage_ack(succeeded):
|
||||
item = host()
|
||||
item._handle_bridge_message({
|
||||
"event": "transcription-start-request", "sessionId": SESSION, "language": "zh-CN",
|
||||
})
|
||||
item._live_ai.transcription_starting.assert_called_once()
|
||||
item.lifecycle.start_transcription.assert_called_once_with(SESSION, language="zh-CN")
|
||||
item._live_ai.bind.assert_not_called()
|
||||
item._local_transcription.start.assert_not_called()
|
||||
|
||||
item.lifecycle.start_transcription.return_value.set_result(succeeded)
|
||||
if succeeded:
|
||||
item._live_ai.bind.assert_called_once_with(71, SESSION)
|
||||
else:
|
||||
item._live_ai.bind.assert_not_called()
|
||||
assert transcription_result(item)[:4] == ["start", SESSION, "", succeeded]
|
||||
item._live_ai.changed.assert_not_called()
|
||||
|
||||
|
||||
def test_cloud_error_marks_failed_and_stop_keeps_partial_storage_status():
|
||||
item = host()
|
||||
item._handle_bridge_message({
|
||||
"event": "transcription-error", "sessionId": SESSION, "message": "云转写连接中断",
|
||||
})
|
||||
item._live_ai.transcription_error.assert_called_once_with("云转写连接中断", status="failed")
|
||||
assert item._asr_partial
|
||||
|
||||
item._handle_bridge_message({
|
||||
"event": "transcription-stop", "sessionId": SESSION, "status": "completed",
|
||||
})
|
||||
item.lifecycle.finish_transcription.assert_called_once_with(status="partial")
|
||||
item._live_ai.finish.assert_not_called()
|
||||
item.lifecycle.finish_transcription.return_value.set_result(True)
|
||||
item._live_ai.finish.assert_called_once_with(SESSION, "partial")
|
||||
item._live_ai.changed.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("session,shutdown,ready", [(SESSION, False, True), ("old", False, False), (SESSION, True, False), ("", False, False)])
|
||||
def test_cloud_ready_after_retry_is_scoped_to_active_call(session, shutdown, ready):
|
||||
item = host(_shutdown_requested=shutdown)
|
||||
item._handle_bridge_message({"event": "transcription-ready", "sessionId": session})
|
||||
assert item._live_ai.transcription_running.called is ready
|
||||
if ready:
|
||||
item._live_ai.transcription_running.assert_called_once_with(SESSION)
|
||||
|
||||
|
||||
def test_error_or_stop_from_old_session_does_not_change_current_call():
|
||||
item = host()
|
||||
item._handle_bridge_message({
|
||||
"event": "transcription-error", "sessionId": "tr-old-call", "message": "old failure",
|
||||
})
|
||||
item._handle_bridge_message({
|
||||
"event": "transcription-stop", "sessionId": "tr-old-call", "status": "partial",
|
||||
})
|
||||
assert not item._asr_partial
|
||||
item.lifecycle.finish_transcription.assert_not_called()
|
||||
item._live_ai.transcription_error.assert_not_called()
|
||||
item._live_ai.finish.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event", [
|
||||
"transcription-start-request", "transcription-segment", "transcription-stop", "transcription-error", "transcription-ready",
|
||||
])
|
||||
@pytest.mark.parametrize("untrusted", ["closing", "released", "uninjected", "navigated"])
|
||||
def test_cloud_commands_require_injected_trusted_live_document(event, untrusted):
|
||||
item = host()
|
||||
if untrusted == "navigated":
|
||||
item._page.url.return_value.toString.return_value = "https://another.example.test/"
|
||||
else:
|
||||
setattr(item, {"closing": "_closing", "released": "_released", "uninjected": "_injected"}[untrusted],
|
||||
untrusted != "uninjected")
|
||||
message = segment_message(event=event, message="cloud failure", language="zh-CN", status="completed")
|
||||
item._handle_bridge_message(message)
|
||||
item.lifecycle.start_transcription.assert_not_called()
|
||||
item.lifecycle.save_transcript_segment.assert_not_called()
|
||||
item.lifecycle.finish_transcription.assert_not_called()
|
||||
item._live_ai.transcription_starting.assert_not_called()
|
||||
item._live_ai.transcription_error.assert_not_called()
|
||||
item._live_ai.transcription_running.assert_not_called()
|
||||
item._live_ai.changed.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["start", "segment", "stop"])
|
||||
def test_direct_transcription_methods_also_require_a_trusted_document(operation):
|
||||
item = host(_injected=False)
|
||||
if operation == "start":
|
||||
item._start_transcription(SESSION, "zh-CN")
|
||||
elif operation == "segment":
|
||||
item._save_transcript_segment(segment_message())
|
||||
else:
|
||||
item._finish_transcription(SESSION, "completed")
|
||||
item.lifecycle.start_transcription.assert_not_called()
|
||||
item.lifecycle.save_transcript_segment.assert_not_called()
|
||||
item.lifecycle.finish_transcription.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event", [
|
||||
"local-transcription-start", "local-transcription-chunk", "local-transcription-stop",
|
||||
])
|
||||
def test_old_local_asr_dispatch_cannot_run_recognition(event):
|
||||
item = host()
|
||||
item._handle_bridge_message({
|
||||
"event": event, "sessionId": SESSION, "role": "patient", "sequence": 0,
|
||||
"timestamp": TIMESTAMP, "data": "AQACAA==",
|
||||
})
|
||||
item._local_transcription.start.assert_not_called()
|
||||
item._local_transcription.submit.assert_not_called()
|
||||
item._local_transcription.stop.assert_not_called()
|
||||
item.lifecycle.start_transcription.assert_not_called()
|
||||
item.lifecycle.save_transcript_segment.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("event", "handler", "arguments"),
|
||||
[
|
||||
("local-audio-start", "_start_local_audio_recording", (SESSION, "audio/webm")),
|
||||
("local-audio-chunk", "_append_local_audio_chunk", (SESSION, 0, "AQACAA==")),
|
||||
("local-audio-finish", "_finish_local_audio_recording", (SESSION, 4)),
|
||||
("local-audio-abort", "_abort_local_audio_recording", (SESSION,)),
|
||||
],
|
||||
)
|
||||
def test_local_audio_recording_dispatch_remains_available(event, handler, arguments):
|
||||
item = host()
|
||||
item._handle_bridge_message({
|
||||
"event": event, "sessionId": SESSION, "mimeType": "audio/webm",
|
||||
"sequence": 0, "data": "AQACAA==", "totalBytes": 4,
|
||||
})
|
||||
getattr(item, handler).assert_called_once_with(*arguments)
|
||||
|
||||
|
||||
def test_pending_shutdown_drains_cloud_segments_and_stop_without_new_start():
|
||||
item = host(_shutdown_requested=True)
|
||||
item._handle_bridge_message({"event": "transcription-start-request", "sessionId": "tr-next"})
|
||||
item._handle_bridge_message(segment_message())
|
||||
item._handle_bridge_message({"event": "transcription-stop", "sessionId": SESSION})
|
||||
item.lifecycle.start_transcription.assert_not_called()
|
||||
item.lifecycle.save_transcript_segment.assert_called_once()
|
||||
item.lifecycle.finish_transcription.assert_called_once_with(status="completed")
|
||||
item._local_transcription.start.assert_not_called()
|
||||
@@ -1,343 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Callable, Iterator
|
||||
from types import MethodType, SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from PySide6.QtCore import QRect, QSize, Qt
|
||||
from PySide6.QtGui import QCloseEvent
|
||||
from PySide6.QtWidgets import QApplication, QDialog, QMainWindow
|
||||
|
||||
from doctor_workstation.app import ApplicationController
|
||||
from doctor_workstation.video import window as video_window
|
||||
|
||||
|
||||
class _CallWindow(QMainWindow):
|
||||
"""Exercise production Qt close handling without starting WebEngine or media."""
|
||||
|
||||
closeEvent = video_window._EmbeddedVideoWindow.closeEvent
|
||||
set_compact_close_handler = video_window._EmbeddedVideoWindow.set_compact_close_handler
|
||||
hangup = video_window._EmbeddedVideoWindow.hangup
|
||||
_request_companion_shutdown = video_window._EmbeddedVideoWindow._request_companion_shutdown
|
||||
_close_from_companion = video_window._EmbeddedVideoWindow._close_from_companion
|
||||
_force_requested_shutdown = video_window._EmbeddedVideoWindow._force_requested_shutdown
|
||||
_begin_shutdown = video_window._EmbeddedVideoWindow._begin_shutdown
|
||||
_handle_bridge_message = video_window._EmbeddedVideoWindow._handle_bridge_message
|
||||
_on_load_finished = video_window._EmbeddedVideoWindow._on_load_finished
|
||||
_after_injection = video_window._EmbeddedVideoWindow._after_injection
|
||||
|
||||
def __init__(self, **changes: Any) -> None:
|
||||
super().__init__()
|
||||
self._on_compact_close: Callable[[], None] | None = None
|
||||
self._closing = False
|
||||
self._released = False
|
||||
self._shutdown_requested = False
|
||||
self._companion_ended = False
|
||||
self._injected = True
|
||||
self._start_requested = True
|
||||
self._call_cycle_closed = False
|
||||
self._media_active = True
|
||||
self._close_reason = "window-closed"
|
||||
self.open_im = False
|
||||
self.lifecycle = SimpleNamespace(end=Mock())
|
||||
self._page = SimpleNamespace(runJavaScript=Mock())
|
||||
self._shutdown_timer = SimpleNamespace(start=Mock(), stop=Mock())
|
||||
self._abort_local_audio_recording = Mock()
|
||||
self._append_local_audio_chunk = Mock()
|
||||
self._release_webengine = Mock(side_effect=self._mark_released)
|
||||
self.restore_screenshot_preview = Mock()
|
||||
self.call_ended = SimpleNamespace(emit=Mock())
|
||||
self.call_error = SimpleNamespace(emit=Mock())
|
||||
self.logger = Mock()
|
||||
self.request = SimpleNamespace(safe_log_context=lambda: {})
|
||||
for key, value in changes.items():
|
||||
setattr(self, key, value)
|
||||
self.setProperty("doctorSkipOpenGeometry", True)
|
||||
self.setMinimumSize(620, 420)
|
||||
self.setGeometry(40, 50, 680, 480)
|
||||
|
||||
def _mark_released(self) -> None:
|
||||
self._released = True
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def qapp() -> QApplication:
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_window(qapp: QApplication) -> Iterator[Callable[..., _CallWindow]]:
|
||||
windows: list[_CallWindow] = []
|
||||
|
||||
def create(**changes: Any) -> _CallWindow:
|
||||
window = _CallWindow(**changes)
|
||||
windows.append(window)
|
||||
return window
|
||||
|
||||
yield create
|
||||
for window in windows:
|
||||
window.set_compact_close_handler(None)
|
||||
window._companion_ended = True
|
||||
window.close()
|
||||
window.deleteLater()
|
||||
qapp.processEvents()
|
||||
|
||||
|
||||
def _controller() -> SimpleNamespace:
|
||||
controller = SimpleNamespace(_video_preview_state=None, _video_preview_generation=0)
|
||||
controller._show_video_preview = MethodType(
|
||||
ApplicationController._show_video_preview, controller
|
||||
)
|
||||
controller._restore_video_preview = MethodType(
|
||||
ApplicationController._restore_video_preview, controller
|
||||
)
|
||||
return controller
|
||||
|
||||
|
||||
def test_native_compact_close_restores_visible_window_and_next_close_ends_call(
|
||||
qapp: QApplication, make_window: Callable[..., _CallWindow]
|
||||
) -> None:
|
||||
window = make_window()
|
||||
window.show()
|
||||
qapp.processEvents()
|
||||
original_geometry = QRect(window.geometry())
|
||||
original_minimum = QSize(window.minimumSize())
|
||||
controller = _controller()
|
||||
dialog = QDialog()
|
||||
|
||||
controller._show_video_preview(window, dialog)
|
||||
qapp.processEvents()
|
||||
|
||||
assert window.isVisible()
|
||||
assert window.minimumSize() == QSize(440, 300)
|
||||
assert window.geometry() != original_geometry
|
||||
assert window.windowFlags() & Qt.WindowType.WindowStaysOnTopHint
|
||||
assert window._on_compact_close is not None
|
||||
|
||||
assert window.close() is False
|
||||
qapp.processEvents()
|
||||
|
||||
assert window.isVisible()
|
||||
assert window.geometry() == original_geometry
|
||||
assert window.minimumSize() == original_minimum
|
||||
assert not window.windowFlags() & Qt.WindowType.WindowStaysOnTopHint
|
||||
assert window.property("doctorSkipOpenGeometry") is False
|
||||
assert controller._video_preview_state is None
|
||||
assert window._on_compact_close is None
|
||||
assert window._shutdown_requested is False
|
||||
window._page.runJavaScript.assert_not_called()
|
||||
window.lifecycle.end.assert_not_called()
|
||||
window._abort_local_audio_recording.assert_not_called()
|
||||
window._release_webengine.assert_not_called()
|
||||
window.restore_screenshot_preview.assert_called_once_with()
|
||||
|
||||
assert window.close() is False
|
||||
|
||||
assert window._shutdown_requested is True
|
||||
assert window.isVisible()
|
||||
assert window._closing is False
|
||||
window._page.runJavaScript.assert_called_once()
|
||||
window._release_webengine.assert_not_called()
|
||||
|
||||
window._handle_bridge_message({"event": "hangup", "status": "local-hangup"})
|
||||
qapp.processEvents()
|
||||
|
||||
assert not window.isVisible()
|
||||
assert window._closing is True
|
||||
window._release_webengine.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["hangup", "facade-close"])
|
||||
@pytest.mark.parametrize("wait_for_recording", [False, True], ids=["idle", "recording"])
|
||||
def test_explicit_shutdown_bypasses_compact_restore_and_drains_recording(
|
||||
make_window: Callable[..., _CallWindow], action: str, wait_for_recording: bool
|
||||
) -> None:
|
||||
window = make_window(_start_requested=wait_for_recording)
|
||||
restore = Mock()
|
||||
window.set_compact_close_handler(restore)
|
||||
window.show()
|
||||
|
||||
def end_call() -> None:
|
||||
if action == "hangup":
|
||||
window.hangup()
|
||||
else:
|
||||
video_window.VideoCallWindow.close(SimpleNamespace(_session=window))
|
||||
|
||||
end_call()
|
||||
|
||||
restore.assert_not_called()
|
||||
assert window._shutdown_requested is True
|
||||
if wait_for_recording:
|
||||
assert window.isVisible()
|
||||
assert window._closing is False
|
||||
window.lifecycle.end.assert_not_called()
|
||||
window._release_webengine.assert_not_called()
|
||||
window._abort_local_audio_recording.assert_not_called()
|
||||
window._shutdown_timer.start.assert_called_once_with(190_000)
|
||||
window._page.runJavaScript.assert_called_once()
|
||||
assert "doctorConsultation?.close?.()" in window._page.runJavaScript.call_args.args[0]
|
||||
|
||||
end_call()
|
||||
window.close()
|
||||
window._page.runJavaScript.assert_called_once()
|
||||
window._handle_bridge_message(
|
||||
{"event": "local-audio-chunk", "sessionId": "recording", "sequence": 7, "data": "YQ=="}
|
||||
)
|
||||
window._append_local_audio_chunk.assert_called_once_with("recording", 7, "YQ==")
|
||||
window._release_webengine.assert_not_called()
|
||||
window._handle_bridge_message({"event": "hangup", "status": "local-hangup"})
|
||||
else:
|
||||
window._page.runJavaScript.assert_not_called()
|
||||
window._shutdown_timer.start.assert_not_called()
|
||||
reason = "desktop-hangup" if action == "hangup" else "window-closed"
|
||||
window.lifecycle.end.assert_called_once_with(reason)
|
||||
|
||||
restore.assert_not_called()
|
||||
assert not window.isVisible()
|
||||
assert window._on_compact_close is None
|
||||
assert window._closing is True
|
||||
assert window._released is True
|
||||
assert window._media_active is False
|
||||
window._shutdown_timer.stop.assert_called_once_with()
|
||||
window._abort_local_audio_recording.assert_called_once_with("")
|
||||
window._release_webengine.assert_called_once_with()
|
||||
window._begin_shutdown()
|
||||
window._release_webengine.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"trigger",
|
||||
["remote-hangup", "remote-error", "timeout", "load-failed", "load-failed-active", "bridge-missing"],
|
||||
)
|
||||
def test_terminal_paths_close_compact_window_without_restoring(
|
||||
make_window: Callable[..., _CallWindow], trigger: str
|
||||
) -> None:
|
||||
window = make_window()
|
||||
restore = Mock()
|
||||
window.set_compact_close_handler(restore)
|
||||
window.show()
|
||||
|
||||
if trigger == "remote-hangup":
|
||||
window._handle_bridge_message({"event": "hangup", "status": "remote-hangup"})
|
||||
window.call_ended.emit.assert_called_once_with("remote-hangup")
|
||||
elif trigger == "remote-error":
|
||||
window._handle_bridge_message({"event": "error", "message": "connection lost"})
|
||||
window.call_error.emit.assert_called_once_with("connection lost")
|
||||
elif trigger == "timeout":
|
||||
window.hangup()
|
||||
window._force_requested_shutdown()
|
||||
window.lifecycle.end.assert_any_call("desktop-hangup-timeout")
|
||||
elif trigger.startswith("load-failed"):
|
||||
if trigger == "load-failed":
|
||||
window._injected = False
|
||||
window._start_requested = False
|
||||
window._on_load_finished(False)
|
||||
assert window._close_reason == "page-load-failed"
|
||||
if trigger == "load-failed-active":
|
||||
assert window._closing is False
|
||||
window._release_webengine.assert_not_called()
|
||||
restore.assert_not_called()
|
||||
window._force_requested_shutdown()
|
||||
window.lifecycle.end.assert_any_call("page-load-failed-timeout")
|
||||
else:
|
||||
window._after_injection(False)
|
||||
assert window._close_reason == "bridge-api-missing"
|
||||
|
||||
restore.assert_not_called()
|
||||
assert not window.isVisible()
|
||||
assert window._closing is True
|
||||
assert window._released is True
|
||||
assert window._on_compact_close is None
|
||||
window._release_webengine.assert_called_once_with()
|
||||
window._shutdown_timer.stop.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"state", ["_shutdown_requested", "_companion_ended", "_closing", "_released"]
|
||||
)
|
||||
def test_close_event_never_restores_a_stopping_or_released_call(
|
||||
make_window: Callable[..., _CallWindow], state: str
|
||||
) -> None:
|
||||
window = make_window(_start_requested=False, **{state: True})
|
||||
restore = Mock()
|
||||
window.set_compact_close_handler(restore)
|
||||
event = QCloseEvent()
|
||||
|
||||
window.closeEvent(event)
|
||||
|
||||
restore.assert_not_called()
|
||||
assert event.isAccepted()
|
||||
|
||||
|
||||
def test_repeated_preview_refreshes_handler_and_ignores_old_dialog_generation(
|
||||
make_window: Callable[..., _CallWindow],
|
||||
) -> None:
|
||||
window = make_window()
|
||||
controller = _controller()
|
||||
first_dialog, second_dialog, third_dialog = QDialog(), QDialog(), QDialog()
|
||||
controller._show_video_preview(window, first_dialog)
|
||||
first_handler = window._on_compact_close
|
||||
original_state = controller._video_preview_state
|
||||
|
||||
controller._show_video_preview(window, second_dialog)
|
||||
second_handler = window._on_compact_close
|
||||
assert first_handler is not None
|
||||
assert second_handler is not None
|
||||
assert first_handler is not second_handler
|
||||
assert controller._video_preview_state is original_state
|
||||
first_dialog.finished.emit(0)
|
||||
first_handler()
|
||||
assert controller._video_preview_state is original_state
|
||||
assert window._on_compact_close is second_handler
|
||||
|
||||
second_handler()
|
||||
assert controller._video_preview_state is None
|
||||
assert window._on_compact_close is None
|
||||
|
||||
controller._show_video_preview(window, third_dialog)
|
||||
current_handler = window._on_compact_close
|
||||
second_dialog.finished.emit(0)
|
||||
second_handler()
|
||||
assert controller._video_preview_state is not None
|
||||
assert window._on_compact_close is current_handler
|
||||
|
||||
third_dialog.finished.emit(0)
|
||||
assert controller._video_preview_state is None
|
||||
assert window._on_compact_close is None
|
||||
window.lifecycle.end.assert_not_called()
|
||||
window._page.runJavaScript.assert_not_called()
|
||||
|
||||
|
||||
def test_switching_preview_restores_old_window_and_isolates_old_callbacks(
|
||||
make_window: Callable[..., _CallWindow],
|
||||
) -> None:
|
||||
first, second = make_window(), make_window()
|
||||
controller = _controller()
|
||||
first_dialog, second_dialog = QDialog(), QDialog()
|
||||
first_geometry = QRect(first.geometry())
|
||||
controller._show_video_preview(first, first_dialog)
|
||||
old_handler = first._on_compact_close
|
||||
|
||||
controller._show_video_preview(second, second_dialog)
|
||||
current_handler = second._on_compact_close
|
||||
|
||||
assert first._on_compact_close is None
|
||||
assert first.geometry() == first_geometry
|
||||
assert controller._video_preview_state["window"] is second
|
||||
assert old_handler is not None
|
||||
old_handler()
|
||||
first_dialog.finished.emit(0)
|
||||
assert controller._video_preview_state["window"] is second
|
||||
assert second._on_compact_close is current_handler
|
||||
|
||||
second_dialog.finished.emit(0)
|
||||
assert controller._video_preview_state is None
|
||||
assert second._on_compact_close is None
|
||||
first.lifecycle.end.assert_not_called()
|
||||
second.lifecycle.end.assert_not_called()
|
||||
@@ -22,7 +22,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from doctor_workstation.core import PermissionSet
|
||||
from doctor_workstation.ui.design_system import PALETTE
|
||||
from doctor_workstation.ui.diagnosis_drawer import (
|
||||
DiagnosisChoiceButtons,
|
||||
DiagnosisComboBox,
|
||||
@@ -1013,14 +1012,14 @@ def test_choice_chips_keep_visible_checked_style_when_readonly(
|
||||
application.processEvents()
|
||||
# Sample the pad (not glyph center) so white text does not hide the fill.
|
||||
enabled_color = selected.grab().toImage().pixelColor(6, selected.height() // 2)
|
||||
assert enabled_color.name().lower() == PALETTE["accent_soft"].lower()
|
||||
assert enabled_color.name().lower() == "#eef1fa"
|
||||
diet.setReadOnly(True)
|
||||
application.processEvents()
|
||||
disabled_color = selected.grab().toImage().pixelColor(6, selected.height() // 2)
|
||||
assert selected.isChecked()
|
||||
assert selected.isEnabled()
|
||||
assert diet.isReadOnly()
|
||||
assert disabled_color.name().lower() == PALETTE["accent_soft"].lower()
|
||||
assert disabled_color.name().lower() == "#eef1fa"
|
||||
dialog.close()
|
||||
application.processEvents()
|
||||
|
||||
@@ -1040,7 +1039,7 @@ def test_view_only_drawer_shows_selected_choice_chips(
|
||||
selected = next(button for button in diet._buttons if button.isChecked())
|
||||
application.processEvents()
|
||||
color = selected.grab().toImage().pixelColor(6, selected.height() // 2)
|
||||
assert color.name().lower() == PALETTE["accent_soft"].lower()
|
||||
assert color.name().lower() == "#eef1fa"
|
||||
assert diet.isReadOnly()
|
||||
assert not dialog.save_button.isVisibleTo(dialog)
|
||||
dialog.close()
|
||||
|
||||
@@ -23,7 +23,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from doctor_workstation.core import PermissionSet
|
||||
from doctor_workstation.ui.design_system import PALETTE
|
||||
from doctor_workstation.ui.diagnosis_index_widgets import (
|
||||
DIAGNOSIS_INDEX_QSS,
|
||||
DiagnosisItemDelegate,
|
||||
@@ -425,8 +424,8 @@ def test_empty_loading_and_compact_footer_keep_the_table_shell(
|
||||
@pytest.mark.parametrize(
|
||||
("record", "stripe", "channel"),
|
||||
[
|
||||
(_row(701, DiagnosisViewRecord=[{"is_confirmed": 0}]), PALETTE["warning"].lower(), "warning"),
|
||||
(_row(702, has_appointment=0, appointments=[]), PALETTE["accent"].lower(), "info"),
|
||||
(_row(701, DiagnosisViewRecord=[{"is_confirmed": 0}]), "#a9691d", "warning"),
|
||||
(_row(702, has_appointment=0, appointments=[]), "#4f63d9", "info"),
|
||||
],
|
||||
)
|
||||
def test_semantic_hover_preserves_three_pixel_stripe_on_neutral_background(
|
||||
@@ -453,9 +452,9 @@ def test_semantic_hover_preserves_three_pixel_stripe_on_neutral_background(
|
||||
assert image.pixelColor(0, 20).name() == stripe
|
||||
assert image.pixelColor(1, 20).name() == stripe
|
||||
assert image.pixelColor(2, 20).name() == stripe
|
||||
assert image.pixelColor(3, 20).name() == PALETTE["surface_alt"].lower(), f"{channel} stripe widened"
|
||||
assert image.pixelColor(6, 20).name() == PALETTE["surface_alt"].lower()
|
||||
assert image.pixelColor(40, 20).name() == PALETTE["surface_alt"].lower()
|
||||
assert image.pixelColor(3, 20).name() == "#f7f7f7", f"{channel} stripe widened"
|
||||
assert image.pixelColor(6, 20).name() == "#f7f7f7"
|
||||
assert image.pixelColor(40, 20).name() == "#f7f7f7"
|
||||
|
||||
|
||||
def test_page_hides_fixed_shadow_and_preserves_admin_token_contract(
|
||||
|
||||
@@ -9,17 +9,10 @@ from pathlib import Path
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QPoint, QRect, Qt
|
||||
from PySide6.QtGui import QFont, QImage, QPainter
|
||||
from PySide6.QtCore import QPoint, Qt
|
||||
from PySide6.QtGui import QFont
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QLabel,
|
||||
QStyleOptionViewItem,
|
||||
QToolButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
from PySide6.QtWidgets import QApplication, QLabel, QToolButton, QVBoxLayout, QWidget
|
||||
|
||||
from doctor_workstation.ui.diagnosis_index_widgets import (
|
||||
DiagnosisTableHost,
|
||||
@@ -122,79 +115,6 @@ def test_blue_metrics_are_opt_in_and_expand_for_complete_content(application: QA
|
||||
legacy.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size,column_width,row_height",
|
||||
[((1024, 640), 84, 75), ((1440, 900), 126, 72)],
|
||||
)
|
||||
def test_followup_paint_keeps_time_whole_and_preserves_density(
|
||||
application: QApplication, size: tuple[int, int], column_width: int, row_height: int,
|
||||
) -> None:
|
||||
class RecordingPainter(QPainter):
|
||||
def __init__(self, image: QImage) -> None:
|
||||
super().__init__(image)
|
||||
self.lines: list[tuple[QRect, int, str]] = []
|
||||
|
||||
def drawText(self, rect: QRect, flags: int, text: str) -> None: # noqa: N802
|
||||
self.lines.append((QRect(rect), flags, text))
|
||||
super().drawText(rect, flags, text)
|
||||
|
||||
row = {
|
||||
"id": 501, "has_prescription": 1,
|
||||
"followup_time_text": "2026-08-17 09:00", "followup_doctor_name": "陈医生",
|
||||
}
|
||||
original = copy.deepcopy(row)
|
||||
host = DiagnosisTableHost(tech_blue=True)
|
||||
host.resize(*size)
|
||||
host.set_rows([row])
|
||||
host.show()
|
||||
_settle(application)
|
||||
try:
|
||||
assert host.main.columnWidth(6) == column_width
|
||||
assert host.main.rowHeight(0) == row_height
|
||||
assert host.fixed.rowHeight(0) == row_height
|
||||
index = host.model.index(0, 6)
|
||||
full_text = "2026-08-17 09:00\n陈医生"
|
||||
assert index.data() == full_text
|
||||
assert index.data(Qt.ItemDataRole.ToolTipRole) == full_text
|
||||
option = QStyleOptionViewItem()
|
||||
option.rect = QRect(0, 0, column_width, row_height)
|
||||
image = QImage(column_width, row_height, QImage.Format.Format_ARGB32)
|
||||
painter = RecordingPainter(image)
|
||||
host.main.itemDelegate().paint(painter, option, index)
|
||||
painter.end()
|
||||
expected = ["2026-08-17", "09:00", "陈医生"] if size[0] == 1024 else [
|
||||
"2026-08-17 09:00", "陈医生",
|
||||
]
|
||||
assert [line[2] for line in painter.lines] == expected
|
||||
content = option.rect.adjusted(8, 8, -8, -8)
|
||||
for rect, flags, _text in painter.lines:
|
||||
assert content.contains(rect)
|
||||
assert flags & Qt.TextFlag.TextSingleLine
|
||||
assert not flags & Qt.TextFlag.TextWrapAnywhere
|
||||
assert row == original
|
||||
finally:
|
||||
host.close()
|
||||
_settle(application)
|
||||
|
||||
|
||||
def test_followup_long_metadata_has_complete_tooltip(application: QApplication) -> None:
|
||||
host = DiagnosisTableHost(tech_blue=True)
|
||||
row = {
|
||||
"id": 502, "has_prescription": 1,
|
||||
"followup_time_text": "2026-08-17 09:00-09:30",
|
||||
"followup_doctor_name": "陈医生(内分泌科专家门诊)", "followup_rx_voided": True,
|
||||
}
|
||||
original = copy.deepcopy(row)
|
||||
host.set_rows([row])
|
||||
index = host.model.index(0, 6)
|
||||
assert index.data(Qt.ItemDataRole.ToolTipRole) == (
|
||||
"2026-08-17 09:00-09:30\n陈医生(内分泌科专家门诊)\n处方已作废"
|
||||
)
|
||||
assert index.data() == index.data(Qt.ItemDataRole.ToolTipRole)
|
||||
assert row == original
|
||||
host.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tech_blue", [False, True])
|
||||
def test_geometry_has_no_minimum_height_feedback_and_tracks_both_scroll_axes(
|
||||
application: QApplication, tech_blue: bool,
|
||||
|
||||
@@ -8,7 +8,6 @@ from PySide6.QtCore import QPoint, Qt, QTimer
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from doctor_workstation.ui.design_system import PALETTE
|
||||
from doctor_workstation.ui.pages.prescriptions import DoctorMultiSelect, _DoctorSelectionDialog
|
||||
from doctor_workstation.ui.theme import apply_theme
|
||||
|
||||
@@ -75,7 +74,7 @@ def test_checked_row_blue_and_unchecked_white(dialog, application):
|
||||
rect = dialog.listing.visualItemRect(item_for(dialog, doctor_id))
|
||||
colors.append(image.pixelColor(int((rect.right() - 70) * scale),
|
||||
int(rect.center().y() * scale)).name())
|
||||
assert colors == [PALETTE["accent_soft"].lower(), PALETTE["surface"].lower()]
|
||||
assert colors == ["#eaf2ff", "#ffffff"]
|
||||
|
||||
|
||||
def test_accept_commits_cancel_preserves_and_reopen_restores(application):
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
"""Current-peer archive paging preserves old callers and request identities."""
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.services.mock_repository import DemoDoctorRepository
|
||||
from doctor_workstation.services.repository import RemoteDoctorRepository
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def post(self, endpoint, payload, *, timeout=None):
|
||||
self.calls.append((endpoint, payload, timeout))
|
||||
return {"completed": False, "sync_token": "a" * 48, "errors": []}
|
||||
|
||||
|
||||
def test_sync_optional_parameters_and_timeout_preserve_exact_legacy_payload():
|
||||
client = Client()
|
||||
repository = RemoteDoctorRepository(client)
|
||||
repository.sync_im_chat_messages(501)
|
||||
result = repository.sync_im_chat_messages(501, scope="current", sync_token="a" * 48)
|
||||
assert client.calls == [
|
||||
("tcm.diagnosis/triggerImChatSync", {"diagnosis_id": 501}, 15.0),
|
||||
("tcm.diagnosis/triggerImChatSync",
|
||||
{"diagnosis_id": 501, "scope": "current", "sync_token": "a" * 48}, 15.0),
|
||||
]
|
||||
assert result["completed"] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kwargs", [{"scope": "other"}, {"sync_token": "bad"}, {"sync_token": None}])
|
||||
def test_sync_rejects_invalid_options_without_network(kwargs):
|
||||
client = Client()
|
||||
with pytest.raises(ValueError):
|
||||
RemoteDoctorRepository(client).sync_im_chat_messages(501, **kwargs)
|
||||
assert not client.calls
|
||||
|
||||
|
||||
def test_mock_sync_supports_paging_contract_and_legacy_receipt():
|
||||
repository = DemoDoctorRepository()
|
||||
assert repository.sync_im_chat_messages(501)["queued"] is True
|
||||
assert repository.sync_im_chat_messages(501, scope="current")["completed"] is True
|
||||
@@ -1,270 +0,0 @@
|
||||
"""Offline tests for native IM AI authorization, synchronization and races."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from threading import BoundedSemaphore, Event
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.video import im_ai
|
||||
|
||||
|
||||
class Repository:
|
||||
def __init__(self, pages=None, events=None):
|
||||
self.pages = deque(pages or [{"completed": True, "errors": []}])
|
||||
self.events = events or [{"event": "done", "diagnosis_id": 501, "answer": "合成回复"}]
|
||||
self.sync_calls = []
|
||||
self.stream_calls = []
|
||||
self.cancel_calls = []
|
||||
self.cancel_called = Event()
|
||||
|
||||
def sync_im_chat_messages(self, diagnosis_id, **kwargs):
|
||||
self.sync_calls.append((diagnosis_id, kwargs))
|
||||
return self.pages.popleft()
|
||||
|
||||
def stream_diagnosis_ai(self, diagnosis_id, prompt, **kwargs):
|
||||
self.stream_calls.append((diagnosis_id, prompt, kwargs))
|
||||
yield from self.events
|
||||
|
||||
def cancel_diagnosis_ai(self, diagnosis_id, request_id):
|
||||
self.cancel_calls.append((diagnosis_id, request_id))
|
||||
self.cancel_called.set()
|
||||
return {"cancel_requested": True}
|
||||
|
||||
|
||||
def controller(repository=None, **kwargs):
|
||||
return im_ai.ImAiController(
|
||||
repository or Repository(), diagnosis_id=501, appointment_id=101,
|
||||
doctor_account="doctor_7", enabled=True, **kwargs,
|
||||
)
|
||||
|
||||
|
||||
def request(service, **changes):
|
||||
return {
|
||||
"source": "doctor-call", "event": "im-ai-request", "sessionId": service.session_id,
|
||||
"requestId": str(uuid4()), "contextKey": "view-1", "diagnosisId": "501",
|
||||
"appointmentId": 101, "action": "summary", **changes,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action,task", [("summary", "summary"), ("followup", "custom"), ("reply", "custom")])
|
||||
def test_current_peer_sync_completes_before_ai_and_keeps_identity(action, task):
|
||||
token = "a" * 48
|
||||
repository = Repository(pages=[
|
||||
{"completed": False, "phase": "checking_accounts", "sync_token": token, "errors": []},
|
||||
{"completed": False, "phase": "syncing", "sync_token": token, "errors": []},
|
||||
{"completed": True, "errors": []},
|
||||
], events=[
|
||||
{"event": "start"}, {"event": "delta", "text": "合成"},
|
||||
{"event": "done", "diagnosis_id": 501, "answer": "合成完整回复", "model_label": "模型",
|
||||
"clinical_review_warnings": [{"code": "PULSE_EXCLUDED_FROM_ASSESSMENT", "source_id": "report"}]},
|
||||
])
|
||||
service = controller(repository)
|
||||
message = request(service, action=action)
|
||||
assert service.handle(message)
|
||||
assert service.wait()
|
||||
result = service.take_result()
|
||||
assert result["status"] == "success"
|
||||
assert result["text"] == "合成完整回复"
|
||||
assert result["requestId"] == message["requestId"]
|
||||
assert result["modelLabel"] == "模型"
|
||||
assert "不采集脉象" in result["warnings"][0]
|
||||
assert len(repository.sync_calls) == 3
|
||||
assert repository.sync_calls[0] == (501, {"scope": "current", "sync_token": ""})
|
||||
assert repository.sync_calls[1][1]["sync_token"] == token
|
||||
assert len(repository.stream_calls) == 1
|
||||
diagnosis_id, prompt, options = repository.stream_calls[0]
|
||||
assert diagnosis_id == 501 and options["task"] == task
|
||||
assert options["request_id"] == message["requestId"]
|
||||
assert "doctor_7" in prompt and len(prompt) <= 500
|
||||
assert "不补问脉象" in prompt and "不自动确诊" in prompt
|
||||
assert not repository.cancel_calls
|
||||
assert service.take_result() is None
|
||||
assert not service.handle(message) # A replay cannot submit another billable request.
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [
|
||||
{"sessionId": "other"}, {"diagnosisId": "502"}, {"diagnosisId": True},
|
||||
{"diagnosisId": "0501"}, {"appointmentId": 102}, {"requestId": "invalid"},
|
||||
{"contextKey": ""}, {"contextKey": "x" * 129}, {"action": "prescription"},
|
||||
{"action": {}}, {"source": "another-page"}, {"event": "send-message"},
|
||||
])
|
||||
def test_invalid_identity_or_action_cannot_read_patient_context(changes):
|
||||
repository = Repository()
|
||||
service = controller(repository)
|
||||
assert not service.handle(request(service, **changes))
|
||||
assert not repository.sync_calls and not repository.stream_calls
|
||||
|
||||
|
||||
def test_permission_default_denied_and_each_host_has_unique_session():
|
||||
repository = Repository()
|
||||
disabled = im_ai.ImAiController(
|
||||
repository, diagnosis_id=501, appointment_id=101, doctor_account="doctor_7"
|
||||
)
|
||||
assert disabled.config["enabled"] is False
|
||||
assert not disabled.handle(request(disabled))
|
||||
assert controller().session_id != controller().session_id
|
||||
|
||||
|
||||
@pytest.mark.parametrize("page", [
|
||||
{"queued": True}, {"completed": "true"}, {"completed": True, "errors": ["private detail"]},
|
||||
{"completed": False, "sync_token": "bad"}, None,
|
||||
])
|
||||
def test_incomplete_or_failed_sync_never_generates(page):
|
||||
repository = Repository(pages=[page])
|
||||
service = controller(repository)
|
||||
assert service.handle(request(service))
|
||||
assert service.wait()
|
||||
result = service.take_result()
|
||||
assert result["status"] == "error"
|
||||
assert "private detail" not in str(result)
|
||||
assert not repository.stream_calls and not repository.cancel_calls
|
||||
|
||||
|
||||
def test_sync_step_and_time_budget_are_bounded():
|
||||
page = {"completed": False, "sync_token": "b" * 48, "errors": []}
|
||||
repository = Repository(pages=[page] * 10)
|
||||
service = controller(repository, max_sync_steps=2)
|
||||
service.handle(request(service))
|
||||
assert service.wait()
|
||||
assert len(repository.sync_calls) == 2
|
||||
assert service.take_result()["status"] == "error"
|
||||
assert not repository.stream_calls
|
||||
|
||||
times = iter([0, 0, 46])
|
||||
repository = Repository()
|
||||
service = controller(repository, clock=lambda: next(times))
|
||||
service.handle(request(service))
|
||||
assert service.wait()
|
||||
assert "超时" in service.take_result()["message"]
|
||||
assert not repository.stream_calls
|
||||
|
||||
|
||||
def test_cancel_during_sync_stops_before_model_submission():
|
||||
entered, release = Event(), Event()
|
||||
|
||||
class SlowSync(Repository):
|
||||
def sync_im_chat_messages(self, diagnosis_id, **kwargs):
|
||||
entered.set()
|
||||
assert release.wait(2)
|
||||
return super().sync_im_chat_messages(diagnosis_id, **kwargs)
|
||||
|
||||
repository = SlowSync()
|
||||
service = controller(repository)
|
||||
message = request(service)
|
||||
service.handle(message)
|
||||
try:
|
||||
assert entered.wait(1)
|
||||
assert service.handle({**message, "event": "im-ai-cancel"})
|
||||
assert "尚未向 AI" in service.take_result()["message"]
|
||||
finally:
|
||||
release.set()
|
||||
assert service.wait()
|
||||
assert not repository.stream_calls and not repository.cancel_calls
|
||||
assert service.take_result() is None
|
||||
|
||||
|
||||
def test_cancel_is_independent_and_late_response_cannot_overwrite_next_request():
|
||||
entered, release, cancel_release = Event(), Event(), Event()
|
||||
|
||||
class SlowStream(Repository):
|
||||
def stream_diagnosis_ai(self, *args, **kwargs):
|
||||
self.stream_calls.append((args, kwargs))
|
||||
yield {"event": "delta", "text": "尚未完成"}
|
||||
entered.set()
|
||||
assert release.wait(2)
|
||||
yield {"event": "done", "answer": "迟到的旧结果"}
|
||||
|
||||
def cancel_diagnosis_ai(self, *args):
|
||||
result = super().cancel_diagnosis_ai(*args)
|
||||
assert cancel_release.wait(2)
|
||||
return result
|
||||
|
||||
repository = SlowStream()
|
||||
service = controller(repository)
|
||||
first = request(service)
|
||||
service.handle(first)
|
||||
try:
|
||||
assert entered.wait(1)
|
||||
assert service.take_result()["text"] == "尚未完成"
|
||||
service.handle({**first, "event": "im-ai-cancel"})
|
||||
assert repository.cancel_called.wait(1) # Independent HTTP starts while stream is blocked.
|
||||
assert service.take_result()["status"] == "cancelled"
|
||||
second = request(service, contextKey="view-2")
|
||||
assert service.handle(second)
|
||||
result = service.take_result()
|
||||
assert result["requestId"] == second["requestId"] and result["status"] == "error"
|
||||
assert len(repository.stream_calls) == 1
|
||||
finally:
|
||||
release.set()
|
||||
cancel_release.set()
|
||||
assert service.wait()
|
||||
assert service.take_result() is None
|
||||
|
||||
|
||||
def test_close_invalidates_mailbox_and_cancels_without_waiting():
|
||||
entered, release = Event(), Event()
|
||||
|
||||
class SlowStream(Repository):
|
||||
def stream_diagnosis_ai(self, *args, **kwargs):
|
||||
entered.set()
|
||||
assert release.wait(2)
|
||||
yield {"event": "done", "answer": "旧患者回复"}
|
||||
|
||||
repository = SlowStream()
|
||||
service = controller(repository)
|
||||
message = request(service)
|
||||
service.handle(message)
|
||||
try:
|
||||
assert entered.wait(1)
|
||||
service.close()
|
||||
assert repository.cancel_called.wait(1)
|
||||
assert service.take_result() is None
|
||||
assert not service.handle(request(service))
|
||||
finally:
|
||||
release.set()
|
||||
assert service.wait()
|
||||
assert service.take_result() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("events", [
|
||||
[{"event": "delta", "text": "不完整"}],
|
||||
[{"event": "done", "answer": ""}],
|
||||
[{"event": "done", "diagnosis_id": 502, "answer": "其他患者"}],
|
||||
[{"event": "delta", "text": "x" * (im_ai.MAX_RESULT_CHARS + 1)}],
|
||||
[{"event": "done", "answer": "x" * (im_ai.MAX_RESULT_CHARS + 1)}],
|
||||
])
|
||||
def test_incomplete_mismatched_and_oversized_results_are_not_usable(events):
|
||||
repository = Repository(events=events)
|
||||
service = controller(repository)
|
||||
service.handle(request(service))
|
||||
assert service.wait()
|
||||
assert service.take_result()["status"] == "error"
|
||||
assert repository.cancel_called.wait(1)
|
||||
assert len(repository.stream_calls) == 1 # No transport/validation retry.
|
||||
|
||||
|
||||
def test_thousands_of_deltas_are_coalesced_into_one_mailbox_result():
|
||||
events = [{"event": "delta", "text": "字"}] * 4000 + [{"event": "done"}]
|
||||
service = controller(Repository(events=events))
|
||||
service.handle(request(service))
|
||||
assert service.wait()
|
||||
result = service.take_result()
|
||||
assert result["status"] == "success" and result["text"] == "字" * 4000
|
||||
assert service.take_result() is None
|
||||
|
||||
|
||||
def test_capacity_rejection_does_not_spawn_or_sync(monkeypatch):
|
||||
slots = BoundedSemaphore(1)
|
||||
slots.acquire()
|
||||
monkeypatch.setattr(im_ai, "_WORKER_SLOTS", slots)
|
||||
repository = Repository()
|
||||
service = controller(repository)
|
||||
try:
|
||||
service.handle(request(service))
|
||||
assert service.take_result()["status"] == "error"
|
||||
assert not repository.sync_calls
|
||||
finally:
|
||||
slots.release()
|
||||
@@ -1,157 +0,0 @@
|
||||
"""Exercise bridge trust and JSON delivery without starting WebEngine or HTTP."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.video import window
|
||||
from doctor_workstation.video.security import TrustedDocumentPolicy
|
||||
|
||||
pytestmark = pytest.mark.skipif(not window.WEBENGINE_AVAILABLE, reason="optional QtWebEngine")
|
||||
TRUSTED = "https://video.example.test/im/index.html"
|
||||
|
||||
|
||||
def host(**changes):
|
||||
item = SimpleNamespace(
|
||||
_closing=False, _released=False, _shutdown_requested=False, _injected=True,
|
||||
_policy=TrustedDocumentPolicy.from_url(TRUSTED, is_local=False),
|
||||
_page=Mock(), _im_ai=Mock(), _im_ai_timer=Mock(),
|
||||
)
|
||||
item._page.url.return_value.toString.return_value = TRUSTED
|
||||
item._im_ai_context_is_trusted = lambda: window._EmbeddedVideoWindow._im_ai_context_is_trusted(item)
|
||||
for key, value in changes.items():
|
||||
setattr(item, key, value)
|
||||
return item
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [
|
||||
{"_closing": True}, {"_released": True}, {"_shutdown_requested": True}, {"_injected": False},
|
||||
])
|
||||
def test_inactive_or_closing_page_cannot_submit_or_receive_ai(changes):
|
||||
item = host(**changes)
|
||||
window._EmbeddedVideoWindow._handle_im_ai_message(item, {"event": "im-ai-request"})
|
||||
window._EmbeddedVideoWindow._flush_im_ai(item)
|
||||
item._im_ai.handle.assert_not_called()
|
||||
item._im_ai.take_result.assert_not_called()
|
||||
item._page.runJavaScript.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", ["about:blank", "https://evil.example.test/im/index.html", TRUSTED + "?other=1"])
|
||||
def test_document_navigation_cannot_reuse_authenticated_ai_bridge(url):
|
||||
item = host()
|
||||
item._page.url.return_value.toString.return_value = url
|
||||
window._EmbeddedVideoWindow._handle_im_ai_message(item, {"event": "im-ai-request"})
|
||||
window._EmbeddedVideoWindow._flush_im_ai(item)
|
||||
item._im_ai.handle.assert_not_called()
|
||||
item._page.runJavaScript.assert_not_called()
|
||||
|
||||
|
||||
def test_trusted_bridge_routes_only_to_identity_checked_controller():
|
||||
item = host()
|
||||
message = {"source": "doctor-call", "event": "im-ai-request", "diagnosisId": 501}
|
||||
window._EmbeddedVideoWindow._handle_im_ai_message(item, message)
|
||||
item._im_ai.handle.assert_called_once_with(message)
|
||||
|
||||
|
||||
def test_result_content_is_json_encoded_and_no_javascript_is_executed():
|
||||
item = host()
|
||||
payload = {"status": "success", "text": '\");window.bad=true;//\n</script>\u2028', "warnings": ["合成提示"]}
|
||||
item._im_ai.take_result.return_value = payload
|
||||
window._EmbeddedVideoWindow._flush_im_ai(item)
|
||||
script = item._page.runJavaScript.call_args.args[0]
|
||||
prefix, suffix = "window.doctorConsultation?.imAiResult?.(", ");"
|
||||
assert script.startswith(prefix) and script.endswith(suffix)
|
||||
assert json.loads(script[len(prefix):-len(suffix)]) == payload
|
||||
assert "\\u2028" in script
|
||||
|
||||
|
||||
def test_host_acknowledges_initial_summary_only_after_request_gate_opens():
|
||||
item = host(_injected=False)
|
||||
item._im_ai.session_id = 'synthetic-session-\\"\u2028'
|
||||
|
||||
def verify_gate(script):
|
||||
assert item._im_ai_context_is_trusted() is True
|
||||
prefix, suffix = "window.doctorConsultation?.imAiReady?.(", ");"
|
||||
assert script.startswith(prefix) and script.endswith(suffix)
|
||||
assert json.loads(script[len(prefix):-len(suffix)]) == item._im_ai.session_id
|
||||
|
||||
item._page.runJavaScript.side_effect = verify_gate
|
||||
window._EmbeddedVideoWindow._after_injection(item, True)
|
||||
item._page.runJavaScript.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [
|
||||
{"_closing": True}, {"_released": True}, {"_shutdown_requested": True},
|
||||
])
|
||||
def test_late_injection_cannot_acknowledge_a_closed_ai_context(changes):
|
||||
item = host(_injected=False, **changes)
|
||||
window._EmbeddedVideoWindow._after_injection(item, True)
|
||||
item._page.runJavaScript.assert_not_called()
|
||||
|
||||
|
||||
def test_navigation_cannot_receive_ai_readiness_acknowledgement():
|
||||
item = host(_injected=False)
|
||||
item._page.url.return_value.toString.return_value = "https://evil.example.test/im/index.html"
|
||||
window._EmbeddedVideoWindow._after_injection(item, True)
|
||||
item._page.runJavaScript.assert_not_called()
|
||||
|
||||
|
||||
def test_failed_injection_closes_without_ai_readiness_acknowledgement():
|
||||
item = host(_injected=False, _request_companion_shutdown=Mock())
|
||||
window._EmbeddedVideoWindow._after_injection(item, False)
|
||||
item._request_companion_shutdown.assert_called_once_with("bridge-api-missing")
|
||||
item._page.runJavaScript.assert_not_called()
|
||||
|
||||
|
||||
def test_shutdown_cancels_ai_before_waiting_for_media_or_destroying_page():
|
||||
item = host(
|
||||
_start_requested=True, _call_cycle_closed=False, _companion_ended=False,
|
||||
_shutdown_timer=Mock(), close=Mock(),
|
||||
)
|
||||
window._EmbeddedVideoWindow._request_companion_shutdown(item, "window-closed")
|
||||
item._im_ai.close.assert_called_once()
|
||||
item._im_ai_timer.stop.assert_called_once()
|
||||
assert item._shutdown_requested is True
|
||||
item.close.assert_not_called() # Recording shutdown still gets its existing grace period.
|
||||
item._shutdown_timer.start.assert_called_once_with(190_000)
|
||||
|
||||
|
||||
def test_qt_notify_rejects_oversized_or_wrong_source_payloads():
|
||||
callback = Mock()
|
||||
bridge = window._QtVideoBridge(callback, Mock())
|
||||
bridge.notify("x" * 16_385)
|
||||
bridge.notify(json.dumps({"source": "evil", "event": "im-ai-request"}))
|
||||
bridge.notify("[]")
|
||||
callback.assert_not_called()
|
||||
message = {"source": "doctor-call", "event": "im-ai-cancel"}
|
||||
bridge.notify(json.dumps(message))
|
||||
callback.assert_called_once_with(message)
|
||||
|
||||
|
||||
def test_video_module_remains_importable_without_optional_qt():
|
||||
source = Path(__file__).resolve().parents[1] / "src"
|
||||
script = """
|
||||
import builtins
|
||||
original_import = builtins.__import__
|
||||
def without_qt(name, *args, **kwargs):
|
||||
if name == 'PySide6' or name.startswith('PySide6.'):
|
||||
raise ImportError('synthetic core-only installation')
|
||||
return original_import(name, *args, **kwargs)
|
||||
builtins.__import__ = without_qt
|
||||
from doctor_workstation.video.window import WEBENGINE_AVAILABLE, VideoCallWindow
|
||||
from doctor_workstation.video.im_ai import ImAiController
|
||||
assert WEBENGINE_AVAILABLE is False
|
||||
"""
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", script], env={**os.environ, "PYTHONPATH": str(source)},
|
||||
capture_output=True, text=True, timeout=10, check=False,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
@@ -1,512 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.core.errors import ApiBusinessError, ApiHttpError, ApiTimeoutError
|
||||
from doctor_workstation.video.live_ai import LiveAiController
|
||||
|
||||
|
||||
def result(call=71, session="tr-local", **changes):
|
||||
value = {
|
||||
"event": "done", "diagnosis_id": 9,
|
||||
"live_context": {
|
||||
"call_record_id": call, "transcription_session_id": session,
|
||||
"revision": "a" * 64, "segment_count": 151,
|
||||
"through_timestamp_ms": 1793332800000, "transcription_status": "running",
|
||||
"sources": [{"id": "patient-1", "role": "patient", "timestamp_ms": 1793332800000,
|
||||
"text": "这是用于软件测试的合成对话。"}],
|
||||
},
|
||||
"live_assistance": {
|
||||
"summary": [{"text": "合成测试要点", "evidence_ids": ["patient-1"]}],
|
||||
"questions": [], "checks": [], "review": [],
|
||||
},
|
||||
}
|
||||
value.update(changes)
|
||||
return value
|
||||
|
||||
|
||||
class Repo:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
self.cancels = []
|
||||
self.response = result()
|
||||
self.started = Event()
|
||||
self.release = None
|
||||
self.fail = False
|
||||
|
||||
def stream_video_ai(self, diagnosis_id, **kwargs):
|
||||
self.calls.append((diagnosis_id, kwargs))
|
||||
self.started.set()
|
||||
if self.release is not None:
|
||||
assert self.release.wait(3)
|
||||
if self.fail:
|
||||
raise RuntimeError("private connection details must not leak")
|
||||
yield deepcopy(self.response)
|
||||
|
||||
def cancel_diagnosis_ai(self, diagnosis_id, request_id):
|
||||
self.cancels.append((diagnosis_id, request_id))
|
||||
return {"accepted": True}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def configured():
|
||||
repo = Repo()
|
||||
clock = [100.0]
|
||||
controller = LiveAiController(repo, diagnosis_id=9, enabled=True, clock=lambda: clock[0])
|
||||
controller.bind(71, "tr-local")
|
||||
yield controller, repo, clock
|
||||
if repo.release is not None:
|
||||
repo.release.set()
|
||||
controller.close()
|
||||
assert controller.wait(3)
|
||||
|
||||
|
||||
def run(controller, clock):
|
||||
clock[0] += 10
|
||||
controller.tick()
|
||||
assert controller.wait(3)
|
||||
return controller.take_state()
|
||||
|
||||
|
||||
def test_only_persisted_current_call_changes_trigger(configured):
|
||||
controller, repo, clock = configured
|
||||
controller.changed("another-call")
|
||||
run(controller, clock)
|
||||
assert not repo.calls
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["summary"][0]["evidence_ids"] == ["patient-1"]
|
||||
assert state["segmentCount"] == 151
|
||||
assert "transcript" not in repo.calls[0][1]
|
||||
assert repo.calls[0][1]["call_record_id"] == 71
|
||||
run(controller, clock)
|
||||
assert len(repo.calls) == 1
|
||||
|
||||
|
||||
def test_cloud_retry_clears_failure_without_losing_saved_evidence(configured):
|
||||
controller, repo, clock = configured
|
||||
controller.changed("tr-local")
|
||||
before = run(controller, clock)
|
||||
controller.transcription_error("云转写中断", status="failed")
|
||||
controller.transcription_running("stale-session")
|
||||
assert controller.take_state()["transcriptionStatus"] == "failed"
|
||||
controller.transcription_running("tr-local")
|
||||
after = controller.take_state()
|
||||
assert after["transcriptionStatus"] == "running"
|
||||
assert after["error"] == ""
|
||||
assert after["summary"] == before["summary"]
|
||||
assert after["revision"] == before["revision"]
|
||||
run(controller, clock)
|
||||
assert len(repo.calls) == 1
|
||||
|
||||
|
||||
def test_one_inflight_and_many_changes_coalesce(configured):
|
||||
controller, repo, clock = configured
|
||||
repo.release = Event()
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 2
|
||||
controller.tick()
|
||||
assert repo.started.wait(2)
|
||||
for _ in range(50):
|
||||
controller.changed("tr-local")
|
||||
controller.tick()
|
||||
assert len(repo.calls) == 1
|
||||
repo.release.set()
|
||||
assert controller.wait(3)
|
||||
run(controller, clock)
|
||||
assert len(repo.calls) == 2
|
||||
run(controller, clock)
|
||||
assert len(repo.calls) == 2
|
||||
|
||||
|
||||
def test_pause_stops_auto_but_explicit_refresh_works(configured):
|
||||
controller, repo, clock = configured
|
||||
controller.handle("toggle", False)
|
||||
controller.changed("tr-local")
|
||||
run(controller, clock)
|
||||
assert not repo.calls
|
||||
controller.handle("refresh")
|
||||
state = run(controller, clock)
|
||||
assert len(repo.calls) == 1
|
||||
assert state["enabled"] is False
|
||||
|
||||
|
||||
def test_no_retry_loop_on_failure(configured):
|
||||
controller, repo, clock = configured
|
||||
repo.fail = True
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["phase"] == "error"
|
||||
assert "private" not in str(state)
|
||||
for _ in range(5):
|
||||
run(controller, clock)
|
||||
assert len(repo.calls) == 1
|
||||
repo.fail = False
|
||||
controller.handle("refresh")
|
||||
assert run(controller, clock)["phase"] == "ready"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", [
|
||||
lambda r: r.update(diagnosis_id=10),
|
||||
lambda r: r["live_context"].update(call_record_id=72),
|
||||
lambda r: r["live_context"].update(transcription_session_id="other"),
|
||||
lambda r: r["live_context"].update(revision="invalid"),
|
||||
lambda r: r["live_context"].update(segment_count=-1),
|
||||
lambda r: r["live_context"].update(through_timestamp_ms=float("nan")),
|
||||
lambda r: r["live_context"]["sources"][0].update(role="guessed"),
|
||||
lambda r: r["live_context"]["sources"][0].update(timestamp_ms=True),
|
||||
lambda r: r["live_assistance"]["summary"][0].update(evidence_ids=["made-up"]),
|
||||
lambda r: r["live_assistance"]["summary"][0].update(evidence_ids=[]),
|
||||
])
|
||||
def test_invalid_identity_or_citations_never_published(configured, mutation):
|
||||
controller, repo, clock = configured
|
||||
mutation(repo.response)
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["phase"] == "error"
|
||||
assert state["summary"] == []
|
||||
|
||||
|
||||
def test_new_call_discards_late_result(configured):
|
||||
controller, repo, clock = configured
|
||||
repo.release = Event()
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 2
|
||||
controller.tick()
|
||||
assert repo.started.wait(2)
|
||||
controller.bind(72, "tr-next")
|
||||
repo.release.set()
|
||||
assert controller.wait(3)
|
||||
state = controller.take_state()
|
||||
assert state["summary"] == []
|
||||
assert state["revision"] == ""
|
||||
|
||||
|
||||
def test_dialing_clears_previous_call_before_new_transcription_exists(configured):
|
||||
controller, repo, clock = configured
|
||||
controller.changed("tr-local")
|
||||
assert run(controller, clock)["summary"]
|
||||
controller.reset()
|
||||
state = controller.take_state()
|
||||
assert state["summary"] == [] and state["sources"] == []
|
||||
assert state["transcriptionStatus"] == "idle"
|
||||
controller.changed("tr-local")
|
||||
controller.handle("review")
|
||||
run(controller, clock)
|
||||
assert len(repo.calls) == 1
|
||||
|
||||
|
||||
def test_complete_long_source_quote_is_not_truncated(configured):
|
||||
controller, repo, clock = configured
|
||||
source = "合成测试原文。" * 400
|
||||
repo.response["live_context"]["sources"][0]["text"] = source
|
||||
repo.response["live_assistance"]["summary"][0]["text"] = "患者原话:" + source
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["summary"][0]["text"] == "患者原话:" + source
|
||||
|
||||
|
||||
def test_previous_good_result_retained_during_update_and_failure(configured):
|
||||
controller, repo, clock = configured
|
||||
controller.changed("tr-local")
|
||||
assert run(controller, clock)["summary"]
|
||||
repo.release = Event()
|
||||
repo.fail = True
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 10
|
||||
controller.tick()
|
||||
state = controller.take_state()
|
||||
assert state["busy"] and state["summary"]
|
||||
repo.release.set()
|
||||
assert controller.wait(3)
|
||||
assert controller.take_state()["summary"]
|
||||
|
||||
|
||||
def test_review_only_after_transcript_finish(configured):
|
||||
controller, repo, clock = configured
|
||||
controller.changed("tr-local")
|
||||
run(controller, clock)
|
||||
controller.handle("review")
|
||||
run(controller, clock)
|
||||
assert len(repo.calls) == 1
|
||||
controller.finish("tr-local", "partial")
|
||||
controller.handle("review")
|
||||
state = run(controller, clock)
|
||||
assert repo.calls[-1][1]["task"] == "live_review"
|
||||
assert state["transcriptionStatus"] == "partial"
|
||||
|
||||
|
||||
def test_no_permission_no_work(configured):
|
||||
_, repo, clock = configured
|
||||
disabled = LiveAiController(repo, diagnosis_id=9, enabled=False)
|
||||
disabled.bind(71, "tr-local")
|
||||
disabled.changed("tr-local")
|
||||
disabled.handle("refresh")
|
||||
disabled.tick()
|
||||
assert not repo.calls
|
||||
assert disabled.take_state()["available"] is False
|
||||
disabled.close()
|
||||
|
||||
|
||||
def test_first_and_subsequent_updates_have_short_bounded_coalescing(configured):
|
||||
controller, repo, clock = configured
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 0.79
|
||||
controller.tick()
|
||||
assert not repo.calls
|
||||
# More speech does not indefinitely postpone the first request.
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 0.02
|
||||
controller.tick()
|
||||
assert controller.wait(3)
|
||||
assert len(repo.calls) == 1
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 1.99
|
||||
controller.tick()
|
||||
assert len(repo.calls) == 1
|
||||
clock[0] += 0.02
|
||||
controller.tick()
|
||||
assert controller.wait(3)
|
||||
assert len(repo.calls) == 2
|
||||
|
||||
|
||||
def test_validated_suggestions_are_visible_before_stream_finishes(configured):
|
||||
controller, repo, clock = configured
|
||||
delivered = Event()
|
||||
repo.release = Event()
|
||||
|
||||
def stream(*args, **kwargs):
|
||||
yield result(event="live_update")
|
||||
delivered.set()
|
||||
assert repo.release.wait(3)
|
||||
yield result()
|
||||
|
||||
repo.stream_video_ai = stream
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 1
|
||||
controller.tick()
|
||||
assert delivered.wait(2)
|
||||
state = controller.take_state()
|
||||
assert state["busy"] is True and state["phase"] == "analyzing"
|
||||
assert state["firstResultMs"] == 0
|
||||
assert state["summary"] and state["revision"] == "a" * 64
|
||||
assert state["pendingSegments"] == 0
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 3
|
||||
controller.tick()
|
||||
state = controller.take_state()
|
||||
assert state["elapsedMs"] == 3000 and state["pendingSegments"] == 1
|
||||
repo.release.set()
|
||||
assert controller.wait(3)
|
||||
state = controller.take_state()
|
||||
assert state["busy"] is False and state["lastDurationMs"] == 3000
|
||||
assert state["firstResultMs"] == 0
|
||||
assert state["pendingSegments"] == 1
|
||||
|
||||
|
||||
def test_slow_request_does_not_add_another_wait_for_queued_speech(configured):
|
||||
controller, repo, clock = configured
|
||||
repo.release = Event()
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 1
|
||||
controller.tick()
|
||||
assert repo.started.wait(2)
|
||||
controller.changed("tr-local")
|
||||
clock[0] += 20
|
||||
controller.tick()
|
||||
assert len(repo.calls) == 1
|
||||
repo.release.set()
|
||||
assert controller.wait(3)
|
||||
# The queued snapshot is already due; no new sleep after the slow request ends.
|
||||
controller.tick()
|
||||
assert controller.wait(3)
|
||||
assert len(repo.calls) == 2
|
||||
assert controller.take_state()["pendingSegments"] == 0
|
||||
|
||||
|
||||
def test_failed_stream_keeps_only_validated_progress(configured):
|
||||
controller, repo, clock = configured
|
||||
|
||||
def stream(*args, **kwargs):
|
||||
yield result(event="live_update")
|
||||
raise ApiTimeoutError("secret raw upstream content")
|
||||
|
||||
repo.stream_video_ai = stream
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["phase"] == "error" and state["summary"]
|
||||
assert state["errorCode"] == "UPSTREAM_TIMEOUT"
|
||||
assert "尚未全部完成" in state["message"]
|
||||
assert "secret" not in str(state)
|
||||
|
||||
|
||||
def test_progress_cannot_change_snapshot_mid_request(configured):
|
||||
controller, repo, clock = configured
|
||||
|
||||
def stream(*args, **kwargs):
|
||||
yield result(event="live_update")
|
||||
different = result()
|
||||
different["live_context"]["revision"] = "b" * 64
|
||||
yield different
|
||||
|
||||
repo.stream_video_ai = stream
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["phase"] == "error"
|
||||
assert state["revision"] == "a" * 64
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scope", ["current_call_only", "authorized_case"])
|
||||
def test_displayed_scope_comes_from_validated_server_result(configured, scope):
|
||||
controller, repo, clock = configured
|
||||
repo.response["analysis_scope"] = scope
|
||||
controller.changed("tr-local")
|
||||
assert run(controller, clock)["analysisScope"] == scope
|
||||
controller.bind(72, "new-session")
|
||||
assert controller.take_state()["analysisScope"] == ""
|
||||
|
||||
|
||||
def test_legacy_server_does_not_claim_dialogue_only(configured):
|
||||
controller, repo, clock = configured
|
||||
controller.changed("tr-local")
|
||||
assert run(controller, clock)["analysisScope"] == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scope", [None, [], "invented"])
|
||||
def test_unrecognized_result_scope_is_rejected(configured, scope):
|
||||
controller, repo, clock = configured
|
||||
repo.response["analysis_scope"] = scope
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["phase"] == "error" and not state["summary"]
|
||||
assert state["analysisScope"] == ""
|
||||
|
||||
|
||||
def test_scope_cannot_change_within_one_stream(configured):
|
||||
controller, repo, clock = configured
|
||||
|
||||
def stream(*args, **kwargs):
|
||||
yield result(event="live_update", analysis_scope="current_call_only")
|
||||
yield result(analysis_scope="authorized_case")
|
||||
|
||||
repo.stream_video_ai = stream
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["phase"] == "error" and state["summary"]
|
||||
assert state["analysisScope"] == "current_call_only"
|
||||
|
||||
|
||||
def test_scope_of_previous_results_survives_review_start_or_failure(configured):
|
||||
controller, repo, clock = configured
|
||||
repo.response["analysis_scope"] = "current_call_only"
|
||||
controller.changed("tr-local")
|
||||
assert run(controller, clock)["analysisScope"] == "current_call_only"
|
||||
controller.finish("tr-local", "completed")
|
||||
observed = []
|
||||
|
||||
def stream(*args, **kwargs):
|
||||
assert kwargs["task"] == "live_review"
|
||||
yield {"event": "start", "analysis_scope": "authorized_case"}
|
||||
observed.append(controller.take_state())
|
||||
raise ApiTimeoutError("synthetic timeout")
|
||||
|
||||
repo.stream_video_ai = stream
|
||||
controller.handle("review")
|
||||
state = run(controller, clock)
|
||||
assert observed[0]["busy"] and observed[0]["analysisScope"] == "current_call_only"
|
||||
assert state["phase"] == "error" and state["analysisScope"] == "current_call_only"
|
||||
|
||||
|
||||
def test_successful_review_and_refresh_replace_displayed_scope(configured):
|
||||
controller, repo, clock = configured
|
||||
repo.response["analysis_scope"] = "current_call_only"
|
||||
controller.changed("tr-local")
|
||||
assert run(controller, clock)["analysisScope"] == "current_call_only"
|
||||
controller.finish("tr-local", "completed")
|
||||
repo.response["analysis_scope"] = "authorized_case"
|
||||
controller.handle("review")
|
||||
assert run(controller, clock)["analysisScope"] == "authorized_case"
|
||||
assert repo.calls[-1][1]["task"] == "live_review"
|
||||
repo.response["analysis_scope"] = "current_call_only"
|
||||
controller.handle("refresh")
|
||||
assert run(controller, clock)["analysisScope"] == "current_call_only"
|
||||
assert repo.calls[-1][1]["task"] == "live_consultation"
|
||||
|
||||
|
||||
def test_items_in_the_same_group_are_published_cumulatively(configured):
|
||||
controller, repo, clock = configured
|
||||
observed = []
|
||||
|
||||
def stream(*args, **kwargs):
|
||||
response = result(event="live_update")
|
||||
for index in range(3):
|
||||
response["live_assistance"]["questions"].append({
|
||||
"text": f"合成测试追问 {index + 1}?", "evidence_ids": ["patient-1"],
|
||||
})
|
||||
yield deepcopy(response)
|
||||
observed.append(controller.take_state())
|
||||
yield {**response, "event": "done"}
|
||||
|
||||
repo.stream_video_ai = stream
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert [len(item["questions"]) for item in observed] == [1, 2, 3]
|
||||
assert all(item["busy"] and item["revision"] == "a" * 64 for item in observed)
|
||||
assert len(state["questions"]) == 3 and not state["busy"]
|
||||
|
||||
|
||||
def test_invalid_progress_never_publishes_or_accepts_a_later_done(configured):
|
||||
controller, repo, clock = configured
|
||||
|
||||
def stream(*args, **kwargs):
|
||||
bad = result(event="live_update")
|
||||
bad["live_assistance"]["summary"][0]["evidence_ids"] = ["invented"]
|
||||
yield bad
|
||||
yield result()
|
||||
|
||||
repo.stream_video_ai = stream
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["phase"] == "error" and not state["summary"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error, expected", [
|
||||
(ApiTimeoutError("private payload"), "UPSTREAM_TIMEOUT"),
|
||||
(ApiHttpError("private payload", status_code=403), "PERMISSION_DENIED"),
|
||||
(ApiHttpError("private payload", status_code=404), "SERVICE_UPDATE_REQUIRED"),
|
||||
(ApiBusinessError("private payload", data={"error_code": "LIVE_RESULT_INVALID"}), "LIVE_RESULT_INVALID"),
|
||||
(ApiBusinessError("private payload", data={"error_code": "UPSTREAM_TIMEOUT"}), "UPSTREAM_TIMEOUT"),
|
||||
(ApiBusinessError("private payload", data={"error_code": {"secret": "payload"}}), "UPSTREAM_UNAVAILABLE"),
|
||||
])
|
||||
def test_failure_categories_do_not_leak_payloads(configured, error, expected, caplog):
|
||||
controller, repo, clock = configured
|
||||
|
||||
def stream(*args, **kwargs):
|
||||
raise error
|
||||
yield
|
||||
|
||||
repo.stream_video_ai = stream
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert state["errorCode"] == expected
|
||||
assert "private payload" not in str(state) + caplog.text
|
||||
assert expected in caplog.text
|
||||
|
||||
|
||||
def test_validated_error_reason_distinguishes_citations_from_format(configured):
|
||||
controller, repo, clock = configured
|
||||
|
||||
def stream(*args, **kwargs):
|
||||
raise ApiBusinessError("private source text", data={
|
||||
"error_code": "LIVE_RESULT_INVALID", "live_validation_reason": "CITATION_INVALID",
|
||||
})
|
||||
yield
|
||||
|
||||
repo.stream_video_ai = stream
|
||||
controller.changed("tr-local")
|
||||
state = run(controller, clock)
|
||||
assert "引用无法核对" in state["error"]
|
||||
assert "private" not in str(state)
|
||||
@@ -1,82 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.core.errors import ApiProtocolError
|
||||
from doctor_workstation.services.repository import RemoteDoctorRepository
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, events=None):
|
||||
self.calls = []
|
||||
self.events = events if events is not None else [{"event": "done", "data": {"diagnosis_id": 9, "live_context": {"revision": "a" * 64}}}]
|
||||
|
||||
def post_event_stream(self, endpoint, body, **kwargs):
|
||||
self.calls.append((endpoint, body, kwargs))
|
||||
yield from self.events
|
||||
|
||||
|
||||
def invoke(client, **changes):
|
||||
args = {"call_record_id": 71, "transcription_session_id": "tr-local", "request_id": "a" * 36}
|
||||
args.update(changes)
|
||||
return list(RemoteDoctorRepository(client).stream_video_ai(9, **args))
|
||||
|
||||
|
||||
def test_scope_is_server_bound_and_structured_done_is_preserved():
|
||||
client = Client()
|
||||
result = invoke(client)
|
||||
assert result[0]["live_context"]["revision"] == "a" * 64
|
||||
endpoint, body, options = client.calls[0]
|
||||
assert endpoint == "tcm.diagnosis/aiAssistantStream"
|
||||
assert body["call_record_id"] == 71 and body["transcription_session_id"] == "tr-local"
|
||||
assert body["task"] == "live_consultation"
|
||||
assert "audio" not in body and "transcript" not in body
|
||||
assert options["timeout"] == 105
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [{"call_record_id": True}, {"call_record_id": 0},
|
||||
{"transcription_session_id": ""}, {"transcription_session_id": "../other"},
|
||||
{"task": "prescription_generate"}])
|
||||
def test_bad_identity_or_task_never_sends(changes):
|
||||
client = Client()
|
||||
with pytest.raises(ValueError):
|
||||
invoke(client, **changes)
|
||||
assert client.calls == []
|
||||
|
||||
|
||||
def test_early_disconnect_does_not_fallback_to_unbound_general_assistant():
|
||||
client = Client([])
|
||||
with pytest.raises(ApiProtocolError):
|
||||
invoke(client)
|
||||
assert len(client.calls) == 1
|
||||
|
||||
|
||||
def test_cancelled_stream_does_not_publish_late_done():
|
||||
client = Client()
|
||||
assert invoke(client, cancelled=lambda: True) == []
|
||||
|
||||
|
||||
def test_validated_progress_is_forwarded_before_done_without_ending_stream():
|
||||
client = Client([
|
||||
{"event": "live_update", "data": {"diagnosis_id": 9, "live_assistance": {"questions": []}}},
|
||||
{"event": "done", "data": {"diagnosis_id": 9, "live_context": {"revision": "a" * 64}}},
|
||||
])
|
||||
events = invoke(client)
|
||||
assert [event["event"] for event in events] == ["live_update", "done"]
|
||||
assert events[0]["live_assistance"] == {"questions": []}
|
||||
|
||||
|
||||
def test_progress_does_not_substitute_for_final_done():
|
||||
client = Client([{"event": "live_update", "data": {"diagnosis_id": 9}}])
|
||||
with pytest.raises(ApiProtocolError):
|
||||
invoke(client)
|
||||
|
||||
|
||||
def test_server_analysis_scope_is_preserved_in_stream_metadata():
|
||||
client = Client([
|
||||
{"event": kind, "data": {"analysis_scope": "current_call_only"}}
|
||||
for kind in ("start", "live_update", "done")
|
||||
])
|
||||
events = invoke(client)
|
||||
assert [event["analysis_scope"] for event in events] == ["current_call_only"] * 3
|
||||
assert "analysis_scope" not in client.calls[0][1]
|
||||
@@ -1,571 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import builtins
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.video.local_transcription import (
|
||||
MAX_BASE64_CHARS,
|
||||
MAX_PCM_BYTES,
|
||||
MAX_SEQUENCE,
|
||||
FasterWhisperEngine,
|
||||
LocalTranscriptionController,
|
||||
LocalTranscriptionError,
|
||||
default_model_path,
|
||||
local_transcription_readiness,
|
||||
)
|
||||
|
||||
TIMESTAMP = 1_795_000_000_000
|
||||
PCM = struct.pack("<hhhh", 0, 100, -100, 200)
|
||||
AUDIO = base64.b64encode(PCM).decode("ascii")
|
||||
|
||||
|
||||
class Events:
|
||||
def __init__(self) -> None:
|
||||
self.items: list[dict[str, Any]] = []
|
||||
self.thread_ids: list[int] = []
|
||||
self.condition = threading.Condition()
|
||||
|
||||
def __call__(self, event: dict[str, Any]) -> None:
|
||||
with self.condition:
|
||||
self.items.append(event)
|
||||
self.thread_ids.append(threading.get_ident())
|
||||
self.condition.notify_all()
|
||||
|
||||
def wait(self, kind: str, session: str = "call-1") -> dict[str, Any]:
|
||||
with self.condition:
|
||||
|
||||
def match() -> dict[str, Any] | None:
|
||||
return next(
|
||||
(e for e in self.items if e["type"] == kind and e["sessionId"] == session),
|
||||
None,
|
||||
)
|
||||
|
||||
assert self.condition.wait_for(lambda: match() is not None, timeout=3)
|
||||
event = match()
|
||||
assert event is not None
|
||||
return event
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, text: str = "无过敏史,服用 0.5 mg,不是 5 mg。") -> None:
|
||||
self.text = text
|
||||
self.inputs: list[bytes] = []
|
||||
|
||||
def transcribe(self, pcm: bytes) -> str:
|
||||
self.inputs.append(pcm)
|
||||
return self.text
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_controller():
|
||||
controllers = []
|
||||
|
||||
def make(events: Events, factory: Callable | None = None, **kwargs):
|
||||
controller = LocalTranscriptionController(events, factory or Engine, **kwargs)
|
||||
controllers.append(controller)
|
||||
return controller
|
||||
|
||||
yield make
|
||||
for controller in controllers:
|
||||
controller.close()
|
||||
if controller._worker:
|
||||
controller._worker.join(3)
|
||||
assert not controller._worker.is_alive()
|
||||
|
||||
|
||||
def test_lazy_daemon_load_async_events_and_exact_numeric_negation_text(make_controller) -> None:
|
||||
events = Events()
|
||||
engine = Engine()
|
||||
factory_threads = []
|
||||
|
||||
def factory():
|
||||
factory_threads.append(threading.get_ident())
|
||||
return engine
|
||||
|
||||
controller = make_controller(events, factory)
|
||||
assert not factory_threads
|
||||
assert controller.start("call-1")
|
||||
assert events.wait("ready") == {"sessionId": "call-1", "type": "ready"}
|
||||
assert controller.submit("call-1", "patient", 0, TIMESTAMP, AUDIO)
|
||||
assert controller.stop("call-1")
|
||||
assert events.wait("stopped")["status"] == "completed"
|
||||
assert events.wait("segment") == {
|
||||
"sessionId": "call-1",
|
||||
"type": "segment",
|
||||
"segmentId": "call-1:patient:0",
|
||||
"role": "patient",
|
||||
"text": engine.text,
|
||||
"timestamp": TIMESTAMP,
|
||||
"isCompleted": True,
|
||||
}
|
||||
assert engine.inputs == [PCM]
|
||||
assert controller._worker.daemon
|
||||
assert factory_threads == [events.thread_ids[0]]
|
||||
assert all(i != threading.get_ident() for i in events.thread_ids)
|
||||
|
||||
|
||||
def test_controller_converts_before_caption_and_persistence_events(make_controller) -> None:
|
||||
events = Events()
|
||||
controller = make_controller(events, lambda: Engine("沒有吃藥,0.5 mg,不是 5 mg。"))
|
||||
controller.start("call-1")
|
||||
controller.submit("call-1", "patient", 0, TIMESTAMP, AUDIO)
|
||||
controller.stop("call-1")
|
||||
assert events.wait("segment")["text"] == "没有吃药,0.5 mg,不是 5 mg。"
|
||||
assert events.wait("stopped")["status"] == "completed"
|
||||
|
||||
|
||||
def test_conversion_failure_does_not_emit_unconverted_text(make_controller, monkeypatch) -> None:
|
||||
def broken(text):
|
||||
raise OSError("private dictionary path")
|
||||
|
||||
monkeypatch.setattr("doctor_workstation.video.local_transcription.simplified_transcript", broken)
|
||||
events = Events()
|
||||
controller = make_controller(events, lambda: Engine("沒有吃藥"))
|
||||
controller.start("call-1")
|
||||
controller.submit("call-1", "patient", 0, TIMESTAMP, AUDIO)
|
||||
controller.stop("call-1")
|
||||
assert events.wait("error")["code"] == "transcription_failed"
|
||||
assert events.wait("stopped")["status"] == "partial"
|
||||
assert not any(e["type"] == "segment" for e in events.items)
|
||||
|
||||
|
||||
def test_roles_have_independent_monotonic_sequences_and_drain_is_ordered(make_controller) -> None:
|
||||
events = Events()
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
engine = Engine()
|
||||
|
||||
def transcribe(pcm):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return engine.text
|
||||
|
||||
engine.transcribe = transcribe
|
||||
controller = make_controller(events, lambda: engine)
|
||||
assert controller.start("call-1")
|
||||
events.wait("ready")
|
||||
try:
|
||||
assert controller.submit("call-1", "doctor", 0, TIMESTAMP, AUDIO)
|
||||
assert entered.wait(3)
|
||||
assert controller.submit("call-1", "patient", 0, TIMESTAMP + 100, AUDIO)
|
||||
assert controller.submit("call-1", "doctor", 1, TIMESTAMP + 200, AUDIO)
|
||||
assert controller.stop("call-1")
|
||||
assert not controller.submit("call-1", "doctor", 2, TIMESTAMP + 300, AUDIO)
|
||||
assert not any(e["type"] == "stopped" for e in events.items)
|
||||
finally:
|
||||
release.set()
|
||||
assert events.wait("stopped")["status"] == "completed"
|
||||
assert [e["type"] for e in events.items] == [
|
||||
"ready",
|
||||
"segment",
|
||||
"segment",
|
||||
"segment",
|
||||
"stopped",
|
||||
]
|
||||
assert [e["segmentId"] for e in events.items if e["type"] == "segment"] == [
|
||||
"call-1:doctor:0",
|
||||
"call-1:patient:0",
|
||||
"call-1:doctor:1",
|
||||
]
|
||||
assert controller.stop("call-1")
|
||||
assert not controller.start("call-1")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sequence", [0, -1, True, 1.5, MAX_SEQUENCE + 1, "2"])
|
||||
def test_rejects_duplicate_invalid_or_unbounded_sequence(make_controller, sequence) -> None:
|
||||
events = Events()
|
||||
controller = make_controller(events)
|
||||
assert controller.start("call-1")
|
||||
assert controller.submit("call-1", "patient", 0, TIMESTAMP, AUDIO)
|
||||
assert not controller.submit("call-1", "patient", sequence, TIMESTAMP, AUDIO)
|
||||
assert controller.stop("call-1")
|
||||
assert events.wait("stopped")["status"] == "partial"
|
||||
assert len([e for e in events.items if e["type"] == "segment"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("role", "timestamp", "audio"),
|
||||
[
|
||||
("unknown", TIMESTAMP, AUDIO),
|
||||
("patient", 0, AUDIO),
|
||||
("patient", True, AUDIO),
|
||||
("patient", float("nan"), AUDIO),
|
||||
("patient", 253_402_300_800_000, AUDIO),
|
||||
("patient", TIMESTAMP, "!!!"),
|
||||
("patient", TIMESTAMP, ""),
|
||||
("patient", TIMESTAMP, "é"),
|
||||
("patient", TIMESTAMP, "AA=="),
|
||||
("patient", TIMESTAMP, "A" * (MAX_BASE64_CHARS + 1)),
|
||||
],
|
||||
ids=[
|
||||
"role",
|
||||
"zero-time",
|
||||
"bool-time",
|
||||
"nan-time",
|
||||
"large-time",
|
||||
"base64",
|
||||
"empty",
|
||||
"non-ascii",
|
||||
"odd-pcm",
|
||||
"oversized",
|
||||
],
|
||||
)
|
||||
def test_input_validation_rejects_bad_metadata_and_audio(
|
||||
make_controller, role, timestamp, audio
|
||||
) -> None:
|
||||
events = Events()
|
||||
engine = Engine()
|
||||
controller = make_controller(events, lambda: engine)
|
||||
controller.start("call-1")
|
||||
assert not controller.submit("call-1", role, 0, timestamp, audio)
|
||||
controller.stop("call-1")
|
||||
assert events.wait("stopped")["status"] == "partial"
|
||||
assert events.wait("error")["code"] in {"invalid_audio", "invalid_metadata"}
|
||||
assert not engine.inputs
|
||||
|
||||
|
||||
def test_accepts_twelve_seconds_rejects_extra_sample_and_reports_sequence_gap(
|
||||
make_controller,
|
||||
) -> None:
|
||||
events = Events()
|
||||
controller = make_controller(events)
|
||||
controller.start("call-1")
|
||||
assert controller.submit(
|
||||
"call-1", "doctor", 0, TIMESTAMP, base64.b64encode(bytes(MAX_PCM_BYTES)).decode()
|
||||
)
|
||||
assert not controller.submit(
|
||||
"call-1", "doctor", 1, TIMESTAMP, base64.b64encode(bytes(MAX_PCM_BYTES + 2)).decode()
|
||||
)
|
||||
assert controller.submit("call-1", "doctor", 2, TIMESTAMP, AUDIO)
|
||||
controller.stop("call-1")
|
||||
assert events.wait("stopped")["status"] == "partial"
|
||||
assert {e["code"] for e in events.items if e["type"] == "error"} == {
|
||||
"invalid_audio",
|
||||
"sequence_gap",
|
||||
}
|
||||
|
||||
|
||||
def test_silence_and_vad_empty_result_produce_no_fabricated_segment(make_controller) -> None:
|
||||
events = Events()
|
||||
engine = Engine("")
|
||||
controller = make_controller(events, lambda: engine)
|
||||
controller.start("call-1")
|
||||
assert controller.submit(
|
||||
"call-1", "patient", 0, TIMESTAMP, base64.b64encode(bytes(3200)).decode()
|
||||
)
|
||||
assert controller.submit("call-1", "patient", 1, TIMESTAMP, AUDIO)
|
||||
controller.stop("call-1")
|
||||
assert events.wait("stopped")["status"] == "completed"
|
||||
assert engine.inputs == [PCM]
|
||||
assert not any(e["type"] == "segment" for e in events.items)
|
||||
|
||||
|
||||
def test_queue_overload_is_bounded_coalesced_and_stop_still_drains(make_controller) -> None:
|
||||
events = Events()
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
class SlowEngine(Engine):
|
||||
def transcribe(self, pcm):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return super().transcribe(pcm)
|
||||
|
||||
engine = SlowEngine()
|
||||
controller = make_controller(events, lambda: engine, max_pending_chunks=2)
|
||||
controller.start("call-1")
|
||||
events.wait("ready")
|
||||
try:
|
||||
assert controller.submit("call-1", "patient", 0, TIMESTAMP, AUDIO)
|
||||
assert entered.wait(3)
|
||||
assert controller.submit("call-1", "patient", 1, TIMESTAMP, AUDIO)
|
||||
assert controller.submit("call-1", "patient", 2, TIMESTAMP, AUDIO)
|
||||
for sequence in range(3, 100):
|
||||
assert not controller.submit("call-1", "patient", sequence, TIMESTAMP, AUDIO)
|
||||
assert controller.stop("call-1")
|
||||
finally:
|
||||
release.set()
|
||||
assert events.wait("stopped")["status"] == "partial"
|
||||
assert len(engine.inputs) == 3
|
||||
assert len([e for e in events.items if e.get("code") == "overloaded"]) == 1
|
||||
assert events.items[-1]["type"] == "stopped"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("during_load", [False, True])
|
||||
def test_new_session_cancels_old_inflight_result_and_queued_audio(
|
||||
make_controller, during_load
|
||||
) -> None:
|
||||
events = Events()
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
engine = Engine()
|
||||
loads = []
|
||||
|
||||
def block():
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
|
||||
def factory():
|
||||
loads.append(1)
|
||||
if during_load:
|
||||
block()
|
||||
return engine
|
||||
|
||||
if not during_load:
|
||||
original = engine.transcribe
|
||||
|
||||
def transcribe(pcm):
|
||||
block()
|
||||
return original(pcm)
|
||||
|
||||
engine.transcribe = transcribe
|
||||
controller = make_controller(events, factory)
|
||||
controller.start("call-1")
|
||||
try:
|
||||
if not during_load:
|
||||
events.wait("ready")
|
||||
controller.submit("call-1", "patient", 0, TIMESTAMP, AUDIO)
|
||||
assert entered.wait(3)
|
||||
controller.submit("call-1", "patient", 1, TIMESTAMP, AUDIO)
|
||||
controller.stop("call-1")
|
||||
assert controller.start("call-2")
|
||||
cutoff = len(events.items)
|
||||
assert not controller.submit("call-1", "patient", 2, TIMESTAMP, AUDIO)
|
||||
assert not controller.stop("call-1")
|
||||
finally:
|
||||
release.set()
|
||||
events.wait("ready", "call-2")
|
||||
assert controller.submit("call-2", "doctor", 0, TIMESTAMP, AUDIO)
|
||||
controller.stop("call-2")
|
||||
events.wait("stopped", "call-2")
|
||||
assert all(e["sessionId"] == "call-2" for e in events.items[cutoff:])
|
||||
assert len(loads) == 1
|
||||
assert len(engine.inputs) == (1 if during_load else 2)
|
||||
|
||||
|
||||
def test_close_suppresses_callbacks_without_waiting_for_native_inference(make_controller) -> None:
|
||||
events = Events()
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
class SlowEngine(Engine):
|
||||
def transcribe(self, pcm):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return "不"
|
||||
|
||||
controller = make_controller(events, SlowEngine)
|
||||
controller.start("call-1")
|
||||
events.wait("ready")
|
||||
try:
|
||||
controller.submit("call-1", "patient", 0, TIMESTAMP, AUDIO)
|
||||
assert entered.wait(3)
|
||||
controller.close()
|
||||
count = len(events.items)
|
||||
assert not controller.start("call-2")
|
||||
assert not controller.stop("call-1")
|
||||
finally:
|
||||
release.set()
|
||||
controller._worker.join(3)
|
||||
assert not controller._worker.is_alive()
|
||||
assert len(events.items) == count
|
||||
|
||||
|
||||
def test_missing_model_failure_is_explicit_and_stops_partial(make_controller) -> None:
|
||||
events = Events()
|
||||
|
||||
def missing_model():
|
||||
raise LocalTranscriptionError("model_missing")
|
||||
|
||||
controller = make_controller(events, missing_model)
|
||||
controller.start("call-1")
|
||||
assert events.wait("error")["code"] == "model_missing"
|
||||
assert events.wait("stopped")["status"] == "partial"
|
||||
assert not any(e["type"] == "ready" for e in events.items)
|
||||
assert not controller.submit("call-1", "doctor", 0, TIMESTAMP, AUDIO)
|
||||
|
||||
|
||||
def test_inference_failure_does_not_leak_data_or_abort_later_chunks(make_controller) -> None:
|
||||
events = Events()
|
||||
|
||||
class FailingEngine(Engine):
|
||||
def transcribe(self, pcm):
|
||||
if not self.inputs:
|
||||
self.inputs.append(pcm)
|
||||
raise RuntimeError("SECRET_PATIENT_DETAILS")
|
||||
return "不"
|
||||
|
||||
controller = make_controller(events, FailingEngine)
|
||||
controller.start("call-1")
|
||||
controller.submit("call-1", "patient", 0, TIMESTAMP, AUDIO)
|
||||
controller.submit("call-1", "patient", 1, TIMESTAMP, AUDIO)
|
||||
controller.stop("call-1")
|
||||
assert events.wait("stopped")["status"] == "partial"
|
||||
assert events.wait("error")["code"] == "transcription_failed"
|
||||
assert events.wait("segment")["text"] == "不"
|
||||
assert "SECRET_PATIENT_DETAILS" not in repr(events.items)
|
||||
|
||||
|
||||
def test_callback_failure_does_not_kill_worker(make_controller) -> None:
|
||||
events = Events()
|
||||
|
||||
def callback(event):
|
||||
if event["type"] == "ready":
|
||||
raise RuntimeError("detached UI")
|
||||
events(event)
|
||||
|
||||
controller = make_controller(callback)
|
||||
controller.start("call-1")
|
||||
controller.submit("call-1", "doctor", 0, TIMESTAMP, AUDIO)
|
||||
controller.stop("call-1")
|
||||
assert events.wait("stopped")["status"] == "completed"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("session", ["", " ", "a" * 129, "x\n", "患者", None, 123])
|
||||
def test_invalid_session_cannot_create_worker(make_controller, session) -> None:
|
||||
events = Events()
|
||||
controller = make_controller(events)
|
||||
assert not controller.start(session)
|
||||
assert controller._worker is None
|
||||
assert not events.items
|
||||
|
||||
|
||||
def write_model_files(path: Path) -> None:
|
||||
for name in ("model.bin", "config.json", "tokenizer.json", "vocabulary.txt"):
|
||||
(path / name).write_text("test", encoding="utf-8")
|
||||
|
||||
|
||||
def test_missing_tokenizer_never_imports_model_or_accesses_network(tmp_path, monkeypatch) -> None:
|
||||
write_model_files(tmp_path)
|
||||
(tmp_path / "tokenizer.json").unlink()
|
||||
original_import = builtins.__import__
|
||||
|
||||
def guarded_import(name, *args, **kwargs):
|
||||
assert name != "faster_whisper"
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
def no_network(*args, **kwargs):
|
||||
pytest.fail("Runtime ASR must not access the network")
|
||||
|
||||
monkeypatch.setattr(builtins, "__import__", guarded_import)
|
||||
monkeypatch.setattr(socket.socket, "connect", no_network)
|
||||
with pytest.raises(LocalTranscriptionError) as raised:
|
||||
FasterWhisperEngine(tmp_path)
|
||||
assert raised.value.code == "model_missing"
|
||||
|
||||
|
||||
def test_missing_dependency_is_explicit_without_exposing_exception(tmp_path, monkeypatch) -> None:
|
||||
write_model_files(tmp_path)
|
||||
original_import = builtins.__import__
|
||||
|
||||
def guarded_import(name, *args, **kwargs):
|
||||
if name == "numpy":
|
||||
raise ModuleNotFoundError("internal path / private details")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(builtins, "__import__", guarded_import)
|
||||
with pytest.raises(LocalTranscriptionError) as raised:
|
||||
FasterWhisperEngine(tmp_path)
|
||||
assert raised.value.code == "dependency_missing"
|
||||
assert "private" not in str(raised.value)
|
||||
|
||||
|
||||
def test_missing_conversion_dictionary_fails_before_model_ready(tmp_path, monkeypatch) -> None:
|
||||
write_model_files(tmp_path)
|
||||
|
||||
def broken_dictionary(text):
|
||||
raise FileNotFoundError("private path to missing t2s.json")
|
||||
|
||||
def model_must_not_load(*args, **kwargs):
|
||||
pytest.fail("Missing conversion resources must fail before expensive model loading")
|
||||
|
||||
monkeypatch.setitem(sys.modules, "numpy", SimpleNamespace())
|
||||
monkeypatch.setitem(sys.modules, "faster_whisper", SimpleNamespace(WhisperModel=model_must_not_load))
|
||||
monkeypatch.setitem(sys.modules, "faster_whisper.vad", SimpleNamespace(get_vad_model=lambda: None))
|
||||
monkeypatch.setattr(
|
||||
"doctor_workstation.video.local_transcription.simplified_transcript", broken_dictionary
|
||||
)
|
||||
with pytest.raises(LocalTranscriptionError) as raised:
|
||||
FasterWhisperEngine(tmp_path)
|
||||
assert raised.value.code == "conversion_unavailable"
|
||||
assert "private" not in str(raised.value)
|
||||
|
||||
|
||||
def test_engine_uses_local_cpu_int8_vad_and_iterates_without_rewriting(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
write_model_files(tmp_path)
|
||||
calls = {}
|
||||
|
||||
class Array:
|
||||
def astype(self, dtype):
|
||||
calls["float_dtype"] = dtype
|
||||
return self
|
||||
|
||||
def __truediv__(self, divisor):
|
||||
calls["divisor"] = divisor
|
||||
return self
|
||||
|
||||
def frombuffer(pcm, dtype):
|
||||
calls["pcm"] = pcm
|
||||
calls["pcm_dtype"] = dtype
|
||||
return Array()
|
||||
|
||||
class Model:
|
||||
def __init__(self, path, **kwargs):
|
||||
calls["path"] = path
|
||||
calls["load"] = kwargs
|
||||
|
||||
def transcribe(self, audio, **kwargs):
|
||||
calls["transcribe"] = kwargs
|
||||
|
||||
def segments():
|
||||
calls["iterated"] = True
|
||||
yield SimpleNamespace(text=" 没有。")
|
||||
yield SimpleNamespace(text=" 0.5 mg,不是 5 mg。 ")
|
||||
|
||||
return segments(), None
|
||||
|
||||
def vad():
|
||||
calls["vad_loaded"] = True
|
||||
|
||||
def no_network(*args, **kwargs):
|
||||
pytest.fail("Runtime ASR must not access the network")
|
||||
|
||||
monkeypatch.setattr(socket.socket, "connect", no_network)
|
||||
monkeypatch.setitem(
|
||||
sys.modules, "numpy", SimpleNamespace(frombuffer=frombuffer, float32="float32")
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, "faster_whisper", SimpleNamespace(WhisperModel=Model))
|
||||
monkeypatch.setitem(sys.modules, "faster_whisper.vad", SimpleNamespace(get_vad_model=vad))
|
||||
engine = FasterWhisperEngine(tmp_path)
|
||||
assert engine.transcribe(PCM) == "没有。 0.5 mg,不是 5 mg。"
|
||||
assert calls["path"] == str(tmp_path.resolve())
|
||||
assert calls["load"]["local_files_only"] is True
|
||||
assert calls["load"]["device"] == "cpu"
|
||||
assert calls["load"]["compute_type"] == "int8"
|
||||
assert calls["load"]["num_workers"] == 1
|
||||
assert calls["vad_loaded"] and calls["iterated"]
|
||||
assert calls["pcm"] == PCM and calls["pcm_dtype"] == "<i2"
|
||||
assert calls["float_dtype"] == "float32" and calls["divisor"] == 32768.0
|
||||
assert calls["transcribe"]["vad_filter"] is True
|
||||
assert calls["transcribe"]["vad_parameters"]["min_speech_duration_ms"] == 0
|
||||
assert calls["transcribe"]["condition_on_previous_text"] is False
|
||||
assert calls["transcribe"]["task"] == "transcribe"
|
||||
assert engine.transcribe(bytes(3200)) == ""
|
||||
|
||||
|
||||
def test_preflight_reports_model_path_override_without_downloading(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setenv("DOCTOR_ASR_MODEL_PATH", str(tmp_path))
|
||||
assert default_model_path() == tmp_path.resolve()
|
||||
info = local_transcription_readiness()
|
||||
assert not info["available"]
|
||||
assert info["modelPath"] == str(tmp_path.resolve())
|
||||
assert "tokenizer.json" in info["missingFiles"]
|
||||
assert not list(tmp_path.iterdir())
|
||||
@@ -1,135 +0,0 @@
|
||||
"""Trusted native PCM ingestion and exact transcript/AI identity handoff."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.video import window
|
||||
from doctor_workstation.video.security import TrustedDocumentPolicy
|
||||
|
||||
pytestmark = pytest.mark.skipif(not window.WEBENGINE_AVAILABLE, reason="optional QtWebEngine")
|
||||
TRUSTED = "https://video.example.test/call/index.html"
|
||||
|
||||
|
||||
def host(**changes):
|
||||
item = SimpleNamespace(
|
||||
_closing=False, _released=False, _shutdown_requested=False, _injected=True,
|
||||
_start_requested=True, _call_cycle_closed=False,
|
||||
_policy=TrustedDocumentPolicy.from_url(TRUSTED, is_local=False),
|
||||
_page=Mock(), _local_transcription=Mock(), _live_ai=Mock(),
|
||||
_video_ai_timer=Mock(), _asr_session_id="tr-local", _asr_ready=True,
|
||||
_asr_partial=False, _transcription_final_status="completed",
|
||||
lifecycle=SimpleNamespace(call_record_id=71, transcription_session_id="tr-local"),
|
||||
request=SimpleNamespace(user_id="doctor_1", target_user_id="patient_9"),
|
||||
_save_transcript_segment=Mock(),
|
||||
)
|
||||
item._page.url.return_value.toString.return_value = TRUSTED
|
||||
for key, value in changes.items():
|
||||
setattr(item, key, value)
|
||||
item._local_transcription_context_is_trusted = lambda: window._EmbeddedVideoWindow._local_transcription_context_is_trusted(item)
|
||||
item._on_local_transcription = lambda event: window._EmbeddedVideoWindow._on_local_transcription(item, event)
|
||||
return item
|
||||
|
||||
|
||||
def chunk(**changes):
|
||||
return {"event": "local-transcription-chunk", "sessionId": "tr-local", "role": "patient",
|
||||
"sequence": 3, "timestamp": 1793332800000.0, "data": "AQACAA==", **changes}
|
||||
|
||||
|
||||
def test_pcm_uses_bound_session_and_double_timestamp_is_converted_safely():
|
||||
item = host()
|
||||
window._EmbeddedVideoWindow._handle_video_assistance_message(item, chunk())
|
||||
item._local_transcription.submit.assert_called_once_with("tr-local", "patient", 3, 1793332800000, "AQACAA==")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [{"sessionId": "other"}, {"timestamp": float("nan")},
|
||||
{"timestamp": float("inf")}, {"timestamp": -1}, {"timestamp": True}])
|
||||
def test_wrong_session_or_unbounded_pcm_metadata_rejected(changes):
|
||||
item = host()
|
||||
window._EmbeddedVideoWindow._handle_video_assistance_message(item, chunk(**changes))
|
||||
item._local_transcription.submit.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [{"_closing": True}, {"_released": True}, {"_injected": False}])
|
||||
def test_untrusted_lifecycle_cannot_ingest_audio(changes):
|
||||
item = host(**changes)
|
||||
window._EmbeddedVideoWindow._handle_video_assistance_message(item, chunk())
|
||||
item._local_transcription.submit.assert_not_called()
|
||||
|
||||
|
||||
def test_navigation_blocks_pcm_and_analysis_commands():
|
||||
item = host()
|
||||
item._page.url.return_value.toString.return_value = "https://another.example.test/"
|
||||
window._EmbeddedVideoWindow._handle_video_assistance_message(item, chunk())
|
||||
window._EmbeddedVideoWindow._handle_video_assistance_message(item, {"event": "video-ai-action", "action": "refresh"})
|
||||
item._local_transcription.submit.assert_not_called()
|
||||
item._live_ai.handle.assert_not_called()
|
||||
|
||||
|
||||
def test_pending_shutdown_drains_pcm_but_cannot_start_new_inference_session():
|
||||
item = host(_shutdown_requested=True)
|
||||
window._EmbeddedVideoWindow._handle_video_assistance_message(item, chunk())
|
||||
window._EmbeddedVideoWindow._handle_video_assistance_message(item, {"event": "local-transcription-start", "sessionId": "tr-next"})
|
||||
window._EmbeddedVideoWindow._handle_video_assistance_message(item, {"event": "video-ai-action", "action": "refresh"})
|
||||
item._local_transcription.submit.assert_called_once()
|
||||
item._local_transcription.start.assert_not_called()
|
||||
item._live_ai.handle.assert_not_called()
|
||||
|
||||
|
||||
def test_asr_segment_is_persisted_with_host_speaker_before_json_display():
|
||||
item = host()
|
||||
event = {"type": "segment", "sessionId": "tr-local", "role": "patient", "segmentId": "tr-local:patient:3",
|
||||
"text": '没有;0.5 mg,不是 5 mg。</script>\u2028', "timestamp": 1793332800000, "isCompleted": True}
|
||||
item._on_local_transcription(event)
|
||||
item._save_transcript_segment.assert_called_once()
|
||||
saved = item._save_transcript_segment.call_args.args[0]
|
||||
assert saved["segment"]["text"] == event["text"]
|
||||
assert saved["segment"]["speaker_user_id"] == "patient_9"
|
||||
script = item._page.runJavaScript.call_args.args[0]
|
||||
assert json.loads(script.split("?.(", 1)[1][:-2]) == event
|
||||
item._live_ai.changed.assert_not_called() # waits for persistence ACK
|
||||
|
||||
|
||||
def test_late_asr_segment_cannot_enter_new_call():
|
||||
item = host(_asr_session_id="tr-next")
|
||||
item._on_local_transcription({"type": "segment", "sessionId": "tr-local", "role": "patient"})
|
||||
item._save_transcript_segment.assert_not_called()
|
||||
item._page.runJavaScript.assert_not_called()
|
||||
|
||||
|
||||
def test_persistence_ack_is_the_only_ai_dirty_trigger():
|
||||
item = host()
|
||||
window._EmbeddedVideoWindow._on_transcription_completed(item, "segment", "other", "s1", True, "")
|
||||
item._live_ai.changed.assert_not_called()
|
||||
window._EmbeddedVideoWindow._on_transcription_completed(item, "segment", "tr-local", "s1", True, "")
|
||||
item._live_ai.changed.assert_called_once_with("tr-local")
|
||||
window._EmbeddedVideoWindow._on_transcription_completed(item, "segment", "tr-local", "s2", False, "")
|
||||
assert item._asr_partial
|
||||
assert item._live_ai.changed.call_count == 1
|
||||
|
||||
|
||||
def test_model_missing_is_failed_and_partial_chunk_is_not_false_ready():
|
||||
item = host(_asr_ready=False)
|
||||
item._on_local_transcription({"type": "error", "sessionId": "tr-local", "message": "本地模型未安装"})
|
||||
item._live_ai.transcription_error.assert_called_once_with("本地模型未安装", status="failed")
|
||||
|
||||
|
||||
def test_shutdown_keeps_asr_for_drain_then_closes_it():
|
||||
item = host()
|
||||
window._EmbeddedVideoWindow._close_video_assistance(item, close_asr=False)
|
||||
item._live_ai.close.assert_called_once()
|
||||
item._local_transcription.close.assert_not_called()
|
||||
window._EmbeddedVideoWindow._close_video_assistance(item)
|
||||
item._local_transcription.close.assert_called_once()
|
||||
|
||||
|
||||
def test_special_pcm_bridge_bounds_data_and_preserves_epoch():
|
||||
callback = Mock()
|
||||
bridge = window._QtVideoBridge(callback, Mock())
|
||||
bridge.appendLocalTranscriptionChunk("tr-local", "doctor", 0, 1793332800000.0, "x" * 512001)
|
||||
callback.assert_not_called()
|
||||
bridge.appendLocalTranscriptionChunk("tr-local", "doctor", 0, 1793332800000.0, "AQACAA==")
|
||||
assert callback.call_args.args[0]["timestamp"] == 1793332800000.0
|
||||
@@ -12,16 +12,17 @@ from __future__ import annotations
|
||||
import os
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
# The module disables itself under the offscreen platform so widget grabs in the
|
||||
# other suites capture settled frames; these tests are about the animation, so
|
||||
# they opt back in.
|
||||
os.environ["DOCTOR_MOTION"] = "on"
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QAbstractAnimation, QEvent, QPoint, QPointF, QPropertyAnimation, Qt
|
||||
from PySide6.QtGui import QKeyEvent, QWheelEvent
|
||||
from PySide6.QtCore import QEvent, QPoint, QPointF, Qt
|
||||
from PySide6.QtGui import QWheelEvent
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractItemView,
|
||||
QApplication,
|
||||
QGraphicsDropShadowEffect,
|
||||
QLabel,
|
||||
QListWidget,
|
||||
QPlainTextEdit,
|
||||
QScrollArea,
|
||||
QStackedWidget,
|
||||
QVBoxLayout,
|
||||
@@ -31,13 +32,6 @@ from PySide6.QtWidgets import (
|
||||
from doctor_workstation.ui import motion
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def enable_motion(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
# Opt in per test so collecting this module does not animate other suites'
|
||||
# screenshots or leak motion settings across the shared QApplication.
|
||||
monkeypatch.setenv("DOCTOR_MOTION", "on")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def application() -> QApplication:
|
||||
return QApplication.instance() or QApplication([])
|
||||
@@ -128,22 +122,15 @@ def _scroll_area(application: QApplication) -> QScrollArea:
|
||||
return area
|
||||
|
||||
|
||||
def _wheel(
|
||||
delta: int,
|
||||
*,
|
||||
horizontal: int = 0,
|
||||
pixels: int = 0,
|
||||
modifiers: Qt.KeyboardModifier = Qt.KeyboardModifier.NoModifier,
|
||||
phase: Qt.ScrollPhase = Qt.ScrollPhase.NoScrollPhase,
|
||||
) -> QWheelEvent:
|
||||
def _wheel(delta: int) -> QWheelEvent:
|
||||
return QWheelEvent(
|
||||
QPointF(50, 50),
|
||||
QPointF(50, 50),
|
||||
QPoint(0, pixels),
|
||||
QPoint(horizontal, delta),
|
||||
QPoint(0, 0),
|
||||
QPoint(0, delta),
|
||||
Qt.MouseButton.NoButton,
|
||||
modifiers,
|
||||
phase,
|
||||
Qt.KeyboardModifier.NoModifier,
|
||||
Qt.ScrollPhase.NoScrollPhase,
|
||||
False,
|
||||
)
|
||||
|
||||
@@ -239,273 +226,3 @@ def test_reading_surfaces_get_smooth_scrolling_from_the_theme(
|
||||
|
||||
assert getattr(area, "_doctor_smooth_scroll", None) is not None
|
||||
area.close()
|
||||
|
||||
|
||||
def test_repeated_fade_continues_from_current_opacity(application: QApplication) -> None:
|
||||
widget = QWidget()
|
||||
motion.fade_in(widget)
|
||||
first = widget._doctor_motion["fade"]
|
||||
first.setCurrentTime(motion.BASE // 2)
|
||||
opacity = widget.graphicsEffect().opacity()
|
||||
|
||||
motion.fade_in(widget)
|
||||
|
||||
assert widget.graphicsEffect().opacity() == pytest.approx(opacity)
|
||||
assert widget._doctor_motion["fade"].startValue() == pytest.approx(opacity)
|
||||
assert first.state() == QAbstractAnimation.State.Stopped
|
||||
widget.close()
|
||||
|
||||
|
||||
def test_fade_out_starts_at_full_opacity(application: QApplication) -> None:
|
||||
widget = QWidget()
|
||||
widget.show()
|
||||
|
||||
motion.fade_out(widget)
|
||||
|
||||
assert widget.graphicsEffect().opacity() == pytest.approx(1.0)
|
||||
widget.close()
|
||||
|
||||
|
||||
def test_reversing_fade_does_not_run_cancelled_hide_callback(application: QApplication) -> None:
|
||||
widget = QWidget()
|
||||
widget.show()
|
||||
completed = []
|
||||
motion.fade_out(widget, on_finished=lambda: completed.append(True))
|
||||
outgoing = widget._doctor_motion["fade"]
|
||||
outgoing.setCurrentTime(motion.FAST // 2)
|
||||
opacity = widget.graphicsEffect().opacity()
|
||||
|
||||
motion.fade_in(widget)
|
||||
incoming = widget._doctor_motion["fade"]
|
||||
|
||||
assert incoming.startValue() == pytest.approx(opacity)
|
||||
incoming.setCurrentTime(incoming.duration())
|
||||
application.processEvents()
|
||||
assert widget.isVisible()
|
||||
assert not completed
|
||||
assert widget.graphicsEffect() is None
|
||||
widget.close()
|
||||
|
||||
|
||||
def test_previous_fade_cleanup_does_not_delete_reentrant_fade(application: QApplication) -> None:
|
||||
widget = QWidget()
|
||||
widget.show()
|
||||
motion.fade_out(widget, on_finished=lambda: motion.fade_in(widget))
|
||||
outgoing = widget._doctor_motion["fade"]
|
||||
|
||||
outgoing.setCurrentTime(outgoing.duration())
|
||||
incoming = widget._doctor_motion["fade"]
|
||||
effect = widget.graphicsEffect()
|
||||
application.processEvents()
|
||||
|
||||
assert widget.graphicsEffect() is effect
|
||||
assert incoming.state() == QAbstractAnimation.State.Running
|
||||
incoming.setCurrentTime(incoming.duration())
|
||||
application.processEvents()
|
||||
assert widget.graphicsEffect() is None
|
||||
assert widget.isVisible()
|
||||
widget.close()
|
||||
|
||||
|
||||
def test_replaced_and_completed_animations_are_released(application: QApplication) -> None:
|
||||
widget = QWidget()
|
||||
destroyed = []
|
||||
for _ in range(10):
|
||||
motion.fade_in(widget)
|
||||
widget._doctor_motion["fade"].destroyed.connect(lambda: destroyed.append(True))
|
||||
fade = widget._doctor_motion["fade"]
|
||||
fade.setCurrentTime(fade.duration())
|
||||
application.processEvents()
|
||||
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
|
||||
|
||||
assert not widget._doctor_motion
|
||||
assert not widget.findChildren(QPropertyAnimation)
|
||||
assert len(destroyed) == 10
|
||||
widget.close()
|
||||
|
||||
|
||||
def test_fades_preserve_existing_graphics_effects(application: QApplication) -> None:
|
||||
widget = QWidget()
|
||||
shadow = QGraphicsDropShadowEffect(widget)
|
||||
widget.setGraphicsEffect(shadow)
|
||||
|
||||
motion.fade_in(widget)
|
||||
assert widget.graphicsEffect() is shadow
|
||||
motion.fade_out(widget)
|
||||
application.processEvents()
|
||||
|
||||
assert widget.graphicsEffect() is shadow
|
||||
assert widget.isHidden()
|
||||
widget.close()
|
||||
|
||||
|
||||
def test_repeated_enter_does_not_accumulate_position_offset(application: QApplication) -> None:
|
||||
host = QWidget()
|
||||
widget = QWidget(host)
|
||||
origin = QPoint(10, 20)
|
||||
widget.move(origin)
|
||||
motion.enter(widget)
|
||||
widget._doctor_motion["enter"].setCurrentTime(motion.BASE // 3)
|
||||
position = widget.pos()
|
||||
|
||||
motion.enter(widget)
|
||||
|
||||
assert widget.pos() == position
|
||||
arrival = widget._doctor_motion["enter"]
|
||||
assert arrival.endValue() == origin
|
||||
arrival.setCurrentTime(arrival.duration())
|
||||
assert widget.pos() == origin
|
||||
host.close()
|
||||
|
||||
|
||||
def test_disabling_motion_settles_an_active_entry(
|
||||
application: QApplication, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
host = QWidget()
|
||||
widget = QWidget(host)
|
||||
origin = QPoint(10, 20)
|
||||
widget.move(origin)
|
||||
motion.enter(widget)
|
||||
monkeypatch.setenv("DOCTOR_MOTION", "off")
|
||||
|
||||
motion.enter(widget)
|
||||
application.processEvents()
|
||||
|
||||
assert widget.pos() == origin
|
||||
assert widget.graphicsEffect() is None
|
||||
assert not widget._doctor_motion
|
||||
host.close()
|
||||
|
||||
|
||||
def test_wheel_reversal_discards_pending_travel(application: QApplication) -> None:
|
||||
area = _scroll_area(application)
|
||||
motion.install_smooth_scroll(area)
|
||||
scroller = area._doctor_smooth_scroll
|
||||
bar = area.verticalScrollBar()
|
||||
bar.setValue(500)
|
||||
for _ in range(4):
|
||||
scroller.eventFilter(area.viewport(), _wheel(-120))
|
||||
scroller._animation.setCurrentTime(30)
|
||||
position = bar.value()
|
||||
|
||||
scroller.eventFilter(area.viewport(), _wheel(120))
|
||||
|
||||
assert scroller._animation.startValue() == position
|
||||
assert scroller._animation.endValue() == position - motion.SCROLL_STEP
|
||||
scroller._animation.setCurrentTime(60)
|
||||
assert bar.value() < position
|
||||
area.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("interaction", ["set_value", "keyboard", "slider_press", "range_change"])
|
||||
def test_direct_scroll_interaction_cancels_pending_wheel(
|
||||
application: QApplication, interaction: str
|
||||
) -> None:
|
||||
area = _scroll_area(application)
|
||||
motion.install_smooth_scroll(area)
|
||||
scroller = area._doctor_smooth_scroll
|
||||
bar = area.verticalScrollBar()
|
||||
scroller.eventFilter(area.viewport(), _wheel(-120))
|
||||
scroller._animation.setCurrentTime(30)
|
||||
|
||||
if interaction == "set_value":
|
||||
bar.setValue(500)
|
||||
elif interaction == "keyboard":
|
||||
application.sendEvent(
|
||||
area,
|
||||
QKeyEvent(QEvent.Type.KeyPress, Qt.Key.Key_Down, Qt.KeyboardModifier.NoModifier),
|
||||
)
|
||||
elif interaction == "slider_press":
|
||||
bar.setSliderDown(True)
|
||||
else:
|
||||
bar.setRange(0, 50)
|
||||
|
||||
assert scroller._animation.state() == QAbstractAnimation.State.Stopped
|
||||
assert scroller._target == bar.value()
|
||||
if interaction == "set_value":
|
||||
scroller.eventFilter(area.viewport(), _wheel(-120))
|
||||
assert scroller._animation.endValue() == 500 + motion.SCROLL_STEP
|
||||
area.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"wheel_options",
|
||||
[
|
||||
{"pixels": -8},
|
||||
{"phase": Qt.ScrollPhase.ScrollUpdate},
|
||||
{"phase": Qt.ScrollPhase.ScrollMomentum},
|
||||
{"modifiers": Qt.KeyboardModifier.ControlModifier},
|
||||
{"modifiers": Qt.KeyboardModifier.ShiftModifier},
|
||||
{"horizontal": -120},
|
||||
],
|
||||
)
|
||||
def test_native_gestures_cancel_pending_wheel(
|
||||
application: QApplication, wheel_options: dict
|
||||
) -> None:
|
||||
area = _scroll_area(application)
|
||||
motion.install_smooth_scroll(area)
|
||||
scroller = area._doctor_smooth_scroll
|
||||
scroller.eventFilter(area.viewport(), _wheel(-120))
|
||||
scroller._animation.setCurrentTime(30)
|
||||
delta = 0 if "horizontal" in wheel_options else -120
|
||||
|
||||
assert not scroller.eventFilter(area.viewport(), _wheel(delta, **wheel_options))
|
||||
assert scroller._animation.state() == QAbstractAnimation.State.Stopped
|
||||
assert scroller._target == area.verticalScrollBar().value()
|
||||
area.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["items", "text_blocks"])
|
||||
def test_non_pixel_scrollbars_keep_native_wheel_steps(application: QApplication, kind: str) -> None:
|
||||
if kind == "items":
|
||||
area = QListWidget()
|
||||
area.addItems([f"row {index}" for index in range(300)])
|
||||
area.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerItem)
|
||||
else:
|
||||
area = QPlainTextEdit("\n".join(f"line {index}" for index in range(300)))
|
||||
area.resize(300, 200)
|
||||
area.show()
|
||||
application.processEvents()
|
||||
motion.install_smooth_scroll(area)
|
||||
|
||||
assert not area._doctor_smooth_scroll.eventFilter(area.viewport(), _wheel(-120))
|
||||
application.sendEvent(area.viewport(), _wheel(-120))
|
||||
assert 0 < area.verticalScrollBar().value() < motion.SCROLL_STEP
|
||||
area.close()
|
||||
|
||||
|
||||
def test_pending_scroll_reaches_edge_before_handing_wheel_back(application: QApplication) -> None:
|
||||
area = _scroll_area(application)
|
||||
motion.install_smooth_scroll(area)
|
||||
scroller = area._doctor_smooth_scroll
|
||||
bar = area.verticalScrollBar()
|
||||
bar.setValue(bar.maximum() - 20)
|
||||
|
||||
assert scroller.eventFilter(area.viewport(), _wheel(-120))
|
||||
assert scroller.eventFilter(area.viewport(), _wheel(-120))
|
||||
scroller._animation.setCurrentTime(scroller._animation.duration())
|
||||
assert not scroller.eventFilter(area.viewport(), _wheel(-120))
|
||||
area.close()
|
||||
|
||||
|
||||
def test_horizontal_scroller_honors_horizontal_and_shift_wheel(application: QApplication) -> None:
|
||||
area = QScrollArea()
|
||||
content = QWidget()
|
||||
content.resize(2000, 1000)
|
||||
area.setWidget(content)
|
||||
area.resize(300, 200)
|
||||
motion.install_smooth_scroll(area, orientation=Qt.Orientation.Horizontal)
|
||||
area.show()
|
||||
application.processEvents()
|
||||
scroller = area._doctor_smooth_scroll
|
||||
|
||||
assert not scroller.eventFilter(area.viewport(), _wheel(-120))
|
||||
assert scroller.eventFilter(area.viewport(), _wheel(0, horizontal=-120))
|
||||
scroller._animation.setCurrentTime(scroller._animation.duration())
|
||||
assert area.horizontalScrollBar().value() == motion.SCROLL_STEP
|
||||
assert area.verticalScrollBar().value() == 0
|
||||
assert scroller.eventFilter(
|
||||
area.viewport(), _wheel(-120, modifiers=Qt.KeyboardModifier.ShiftModifier)
|
||||
)
|
||||
assert scroller._animation.endValue() == motion.SCROLL_STEP * 2
|
||||
area.close()
|
||||
|
||||
@@ -16,7 +16,6 @@ from PySide6.QtWidgets import QAbstractItemView, QApplication, QPushButton
|
||||
from doctor_workstation.core import PermissionSet
|
||||
from doctor_workstation.services import DemoDoctorRepository
|
||||
from doctor_workstation.ui import icons
|
||||
from doctor_workstation.ui.design_system import PALETTE
|
||||
from doctor_workstation.ui.pages import prescriptions as prescriptions_module
|
||||
from doctor_workstation.ui.shell import ShellWindow
|
||||
from doctor_workstation.ui.theme import apply_theme
|
||||
@@ -223,7 +222,7 @@ def test_sorted_native_row_view_button_targets_visible_record(
|
||||
|
||||
|
||||
def test_blue_icon_disabled_variant_does_not_modify_shared_icon_cache(application) -> None:
|
||||
kind, color, size = "pencil", PALETTE["accent"], 19
|
||||
kind, color, size = "pencil", "#1769E8", 19
|
||||
shared = icons.icon(kind, color, size)
|
||||
original_key = shared.cacheKey()
|
||||
original_normal = shared.pixmap(size, size, QIcon.Mode.Normal).toImage()
|
||||
@@ -231,19 +230,13 @@ def test_blue_icon_disabled_variant_does_not_modify_shared_icon_cache(applicatio
|
||||
|
||||
blue = prescriptions_module._blue_prescription_icon(kind, color, size)
|
||||
|
||||
assert blue is not shared
|
||||
assert icons.icon(kind, color, size) is shared
|
||||
assert shared.cacheKey() == original_key
|
||||
assert shared.pixmap(size, size, QIcon.Mode.Normal).toImage() == original_normal
|
||||
assert shared.pixmap(size, size, QIcon.Mode.Disabled).toImage() == original_disabled
|
||||
assert blue.pixmap(size, size, QIcon.Mode.Normal).toImage() == original_normal
|
||||
assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() == icons.pixmap(kind, PALETTE["disabled"], size).toImage()
|
||||
assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() == original_disabled
|
||||
# Both surfaces share the disabled colour; changing the returned icon still
|
||||
# must not mutate the cached icon used by another page.
|
||||
blue.addPixmap(icons.pixmap(kind, PALETTE["danger"], size), QIcon.Mode.Disabled)
|
||||
assert shared.cacheKey() == original_key
|
||||
assert shared.pixmap(size, size, QIcon.Mode.Disabled).toImage() == original_disabled
|
||||
assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() == icons.pixmap(kind, "#A4ADBA", size).toImage()
|
||||
assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() != original_disabled
|
||||
|
||||
|
||||
def test_long_doctor_button_paints_compactly_without_truncating_real_value(shell_factory, application) -> None:
|
||||
|
||||
@@ -6,7 +6,6 @@ from PySide6.QtGui import QPalette
|
||||
from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton
|
||||
|
||||
from doctor_workstation.core import PermissionSet
|
||||
from doctor_workstation.ui.design_system import PALETTE
|
||||
from doctor_workstation.ui.pages import reception as reception_module
|
||||
from doctor_workstation.ui.pages.reception import ReceptionPage
|
||||
from doctor_workstation.ui.theme import apply_theme
|
||||
@@ -44,12 +43,12 @@ def page(application, monkeypatch):
|
||||
def test_primary_action_and_reading_ink_use_separate_colors(page, application):
|
||||
page.video_button.setEnabled(True)
|
||||
settle(application)
|
||||
assert page.video_button.palette().color(QPalette.ColorRole.Button).name() == PALETTE["accent"].lower()
|
||||
assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == PALETTE["surface"].lower()
|
||||
assert page.case_labels["present"].palette().color(QPalette.ColorRole.WindowText).name() == PALETTE["text"].lower()
|
||||
assert page.video_button.palette().color(QPalette.ColorRole.Button).name() == "#1769e8"
|
||||
assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == "#ffffff"
|
||||
assert page.case_labels["present"].palette().color(QPalette.ColorRole.WindowText).name() == "#273244"
|
||||
page.video_button.setEnabled(False)
|
||||
settle(application)
|
||||
assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == PALETTE["disabled"].lower()
|
||||
assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == "#8e8f90"
|
||||
|
||||
|
||||
def test_typography_preserves_regular_body_and_distinct_values(page):
|
||||
|
||||
@@ -1,322 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from PySide6.QtCore import QRect, QSize, Qt, QUrl
|
||||
from PySide6.QtWidgets import QApplication, QMainWindow
|
||||
|
||||
from doctor_workstation.app import ApplicationController
|
||||
from doctor_workstation.ui import theme
|
||||
from doctor_workstation.video import window as video_window
|
||||
from doctor_workstation.video.screenshot import ScreenshotPreviewSize
|
||||
from doctor_workstation.video.security import TrustedDocumentPolicy
|
||||
|
||||
TRUSTED_URL = "https://video.example.test/companion/index.html?mode=call"
|
||||
|
||||
|
||||
class _Window:
|
||||
"""Supply geometry and state only, so preview sizing cannot alter other settings."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
available: QRect | None = None,
|
||||
geometry: QRect | None = None,
|
||||
) -> None:
|
||||
self.current_geometry = QRect(geometry) if geometry is not None else QRect(1362, 18, 540, 356)
|
||||
self.available = QRect(available) if available is not None else QRect(0, 0, 1920, 1040)
|
||||
self.compact_flag: bool | None = True
|
||||
self.maximized = False
|
||||
self.full_screen = False
|
||||
self.geometry_changes: list[QRect] = []
|
||||
|
||||
def screen(self) -> SimpleNamespace:
|
||||
return SimpleNamespace(availableGeometry=lambda: QRect(self.available))
|
||||
|
||||
def geometry(self) -> QRect:
|
||||
return QRect(self.current_geometry)
|
||||
|
||||
def setGeometry(self, geometry: QRect) -> None: # noqa: N802 - Qt-compatible double
|
||||
self.current_geometry = QRect(geometry)
|
||||
self.geometry_changes.append(QRect(geometry))
|
||||
|
||||
def property(self, name: str) -> bool | None:
|
||||
assert name == "doctorSkipOpenGeometry"
|
||||
return self.compact_flag
|
||||
|
||||
def isMaximized(self) -> bool: # noqa: N802 - Qt-compatible double
|
||||
return self.maximized
|
||||
|
||||
def isFullScreen(self) -> bool: # noqa: N802 - Qt-compatible double
|
||||
return self.full_screen
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def qapp() -> QApplication:
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("available", "target", "expected_size"),
|
||||
[
|
||||
(QRect(0, 0, 1920, 1040), None, QSize(1120, 760)),
|
||||
(QRect(-1920, -120, 1920, 1040), None, QSize(1120, 760)),
|
||||
(QRect(-1280, 180, 1280, 720), QRect(0, 0, 1400, 950), QSize(1232, 672)),
|
||||
(QRect(100, 50, 800, 600), None, QSize(752, 552)),
|
||||
(QRect(0, 0, 1920, 1040), QRect(40, 60, 1360, 850), QSize(1360, 850)),
|
||||
],
|
||||
ids=["default", "negative-monitor", "bounded-target", "small-screen", "normal-target"],
|
||||
)
|
||||
def test_preview_expands_within_current_screen_and_restores(
|
||||
available: QRect, target: QRect | None, expected_size: QSize
|
||||
) -> None:
|
||||
window = _Window(available, QRect(available.x() + 30, available.y() + 30, 440, 300))
|
||||
original = window.geometry()
|
||||
preview = ScreenshotPreviewSize()
|
||||
|
||||
preview.open(window, target)
|
||||
|
||||
expanded = window.geometry()
|
||||
assert expanded.size() == expected_size
|
||||
assert available.adjusted(24, 24, -24, -24).contains(expanded)
|
||||
assert abs(expanded.center().x() - available.center().x()) <= 1
|
||||
assert abs(expanded.center().y() - available.center().y()) <= 1
|
||||
assert window.compact_flag is True
|
||||
|
||||
preview.restore(window)
|
||||
|
||||
assert window.geometry() == original
|
||||
assert window.compact_flag is True
|
||||
|
||||
|
||||
def test_repeated_open_preserves_first_geometry_and_restore_is_idempotent() -> None:
|
||||
window = _Window()
|
||||
original = window.geometry()
|
||||
preview = ScreenshotPreviewSize()
|
||||
|
||||
preview.open(window)
|
||||
expanded = window.geometry()
|
||||
preview.open(window, QRect(0, 0, 1500, 900))
|
||||
|
||||
assert window.geometry() == expanded
|
||||
assert len(window.geometry_changes) == 1
|
||||
|
||||
preview.restore(window)
|
||||
preview.restore(window)
|
||||
|
||||
assert window.geometry() == original
|
||||
assert window.geometry_changes == [expanded, original]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state", ["maximized", "full_screen", "large", "no-screen", "tiny-screen"])
|
||||
def test_preview_does_not_modify_windows_that_do_not_need_expansion(state: str) -> None:
|
||||
window = _Window()
|
||||
if state == "large":
|
||||
window.current_geometry = QRect(25, 30, 1300, 850)
|
||||
elif state == "no-screen":
|
||||
window.screen = lambda: None # type: ignore[method-assign, return-value]
|
||||
elif state == "tiny-screen":
|
||||
window.available = QRect(0, 0, 40, 40)
|
||||
else:
|
||||
setattr(window, state, True)
|
||||
original = window.geometry()
|
||||
preview = ScreenshotPreviewSize()
|
||||
|
||||
preview.open(window)
|
||||
preview.restore(window)
|
||||
|
||||
assert window.geometry() == original
|
||||
assert window.geometry_changes == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["move", "resize", "compact-flag", "maximize", "fullscreen"])
|
||||
def test_restore_preserves_external_window_changes_and_forgets_old_snapshot(change: str) -> None:
|
||||
window = _Window()
|
||||
preview = ScreenshotPreviewSize()
|
||||
preview.open(window)
|
||||
expanded = window.geometry()
|
||||
if change == "move":
|
||||
window.current_geometry.translate(40, 15)
|
||||
elif change == "resize":
|
||||
window.current_geometry.setWidth(window.current_geometry.width() + 50)
|
||||
elif change == "compact-flag":
|
||||
window.compact_flag = False
|
||||
elif change == "maximize":
|
||||
window.maximized = True
|
||||
else:
|
||||
window.full_screen = True
|
||||
external_geometry = window.geometry()
|
||||
writes_before_restore = len(window.geometry_changes)
|
||||
|
||||
preview.restore(window)
|
||||
|
||||
assert window.geometry() == external_geometry
|
||||
assert len(window.geometry_changes) == writes_before_restore
|
||||
|
||||
# Even when those external changes later disappear, a late close is harmless.
|
||||
window.current_geometry = expanded
|
||||
window.compact_flag = True
|
||||
window.maximized = False
|
||||
window.full_screen = False
|
||||
preview.restore(window)
|
||||
|
||||
assert window.geometry() == expanded
|
||||
assert len(window.geometry_changes) == writes_before_restore
|
||||
|
||||
|
||||
def test_real_window_preserves_theme_opt_out_minimum_and_flags(qapp: QApplication) -> None:
|
||||
theme._install_business_dialog_styling(qapp)
|
||||
main = QMainWindow()
|
||||
main.setProperty("doctorMainWindow", True)
|
||||
main.setGeometry(30, 30, 980, 720)
|
||||
main.show()
|
||||
window = QMainWindow()
|
||||
window.setProperty("doctorSkipOpenGeometry", True)
|
||||
window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)
|
||||
window.setMinimumSize(440, 300)
|
||||
window.setGeometry(30, 30, 440, 300)
|
||||
window.show()
|
||||
qapp.processEvents()
|
||||
original = window.geometry()
|
||||
flags = window.windowFlags()
|
||||
minimum = window.minimumSize()
|
||||
preview = ScreenshotPreviewSize()
|
||||
try:
|
||||
preview.open(window, theme.main_window_target_rect(window))
|
||||
qapp.processEvents()
|
||||
|
||||
assert window.width() > original.width()
|
||||
assert window.height() > original.height()
|
||||
assert window.minimumSize() == minimum
|
||||
assert window.windowFlags() == flags
|
||||
assert window.property("doctorSkipOpenGeometry") is True
|
||||
|
||||
preview.restore(window)
|
||||
qapp.processEvents()
|
||||
|
||||
assert window.geometry() == original
|
||||
assert window.minimumSize() == minimum
|
||||
assert window.windowFlags() == flags
|
||||
assert window.property("doctorSkipOpenGeometry") is True
|
||||
finally:
|
||||
window.close()
|
||||
main.close()
|
||||
|
||||
|
||||
def test_diagnosis_restore_clears_screenshot_layer_before_restoring_large_window(
|
||||
qapp: QApplication,
|
||||
) -> None:
|
||||
theme._install_business_dialog_styling(qapp)
|
||||
window = QMainWindow()
|
||||
window.setProperty("doctorSkipOpenGeometry", True)
|
||||
window.setMinimumSize(440, 300)
|
||||
window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)
|
||||
window.setGeometry(30, 30, 440, 300)
|
||||
window.show()
|
||||
qapp.processEvents()
|
||||
compact = window.geometry()
|
||||
normal = QRect(40, 50, 670, 500)
|
||||
preview = ScreenshotPreviewSize()
|
||||
restored_layers: list[QRect] = []
|
||||
|
||||
def restore_screenshot_preview() -> None:
|
||||
preview.restore(window)
|
||||
restored_layers.append(window.geometry())
|
||||
|
||||
window.restore_screenshot_preview = restore_screenshot_preview
|
||||
controller = SimpleNamespace(
|
||||
_video_preview_generation=4,
|
||||
_video_preview_state={
|
||||
"window": window,
|
||||
"geometry": normal,
|
||||
"minimum_size": QSize(500, 360),
|
||||
"maximized": False,
|
||||
"full_screen": False,
|
||||
"stays_on_top": False,
|
||||
},
|
||||
)
|
||||
try:
|
||||
preview.open(window, QRect(0, 0, 600, 450))
|
||||
|
||||
ApplicationController._restore_video_preview(controller, 4, activate=False)
|
||||
qapp.processEvents()
|
||||
|
||||
assert restored_layers == [compact]
|
||||
assert window.geometry() == normal
|
||||
assert window.minimumSize() == QSize(500, 360)
|
||||
assert not window.windowFlags() & Qt.WindowType.WindowStaysOnTopHint
|
||||
assert window.property("doctorSkipOpenGeometry") is False
|
||||
assert controller._video_preview_state is None
|
||||
assert controller._video_preview_generation == 5
|
||||
|
||||
restore_screenshot_preview()
|
||||
|
||||
assert window.geometry() == normal
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
|
||||
def _host(**changes: Any) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
**{
|
||||
"_closing": False,
|
||||
"_released": False,
|
||||
"_shutdown_requested": False,
|
||||
"_media_active": True,
|
||||
"_policy": TrustedDocumentPolicy.from_url(TRUSTED_URL, is_local=False),
|
||||
"_page": SimpleNamespace(url=lambda: QUrl(TRUSTED_URL)),
|
||||
"_screenshot_preview_size": SimpleNamespace(open=Mock()),
|
||||
"restore_screenshot_preview": Mock(),
|
||||
**changes,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"changes",
|
||||
[
|
||||
{"_closing": True},
|
||||
{"_released": True},
|
||||
{"_shutdown_requested": True},
|
||||
{"_media_active": False},
|
||||
{"_page": SimpleNamespace(url=lambda: QUrl("about:blank"))},
|
||||
{"_page": SimpleNamespace(url=lambda: QUrl("https://untrusted.example.test/"))},
|
||||
],
|
||||
ids=["closing", "released", "shutdown", "inactive", "blank-document", "untrusted-document"],
|
||||
)
|
||||
def test_host_does_not_open_preview_when_inactive_or_untrusted(changes: dict[str, Any]) -> None:
|
||||
host = _host(**changes)
|
||||
|
||||
video_window._EmbeddedVideoWindow._set_screenshot_preview_visible(host, True)
|
||||
|
||||
host._screenshot_preview_size.open.assert_not_called()
|
||||
host.restore_screenshot_preview.assert_not_called()
|
||||
|
||||
|
||||
def test_host_uses_normal_window_target_for_trusted_preview(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
host = _host()
|
||||
target = QRect(30, 40, 1360, 850)
|
||||
target_for_window = Mock(return_value=target)
|
||||
monkeypatch.setattr(theme, "main_window_target_rect", target_for_window)
|
||||
|
||||
video_window._EmbeddedVideoWindow._set_screenshot_preview_visible(host, True)
|
||||
|
||||
target_for_window.assert_called_once_with(host)
|
||||
host._screenshot_preview_size.open.assert_called_once_with(host, target)
|
||||
host.restore_screenshot_preview.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [{}, {"_shutdown_requested": True}, {"_media_active": False}])
|
||||
def test_host_allows_preview_cleanup_after_shutdown_request(changes: dict[str, Any]) -> None:
|
||||
host = _host(**changes)
|
||||
|
||||
video_window._EmbeddedVideoWindow._set_screenshot_preview_visible(host, False)
|
||||
|
||||
host.restore_screenshot_preview.assert_called_once_with()
|
||||
host._screenshot_preview_size.open.assert_not_called()
|
||||
@@ -164,59 +164,6 @@ def test_diagnosis_callback_previews_exact_appointment_session(chat_controller):
|
||||
assert len(case.previews) == 1 # A closed session cannot borrow another appointment's video.
|
||||
|
||||
|
||||
@pytest.mark.parametrize("permissions, expected", [
|
||||
(None, False),
|
||||
([], False),
|
||||
(["tcm.diagnosis/read"], False),
|
||||
(["tcm.diagnosis.aiAssistant"], False),
|
||||
(["tcm.diagnosis/aiAssistant"], True),
|
||||
(["tcm.diagnosis/*"], True),
|
||||
(["*"], True),
|
||||
])
|
||||
def test_im_ai_capability_comes_from_current_shell_permissions(chat_controller, permissions, expected):
|
||||
case = chat_controller
|
||||
case.controller.shell_window.permissions = permissions
|
||||
case.controller._request_video({
|
||||
"patient_id": 8, "diagnosis_id": 123, "appointment_id": 456,
|
||||
"mode": "im", "can_ai_assistant": True,
|
||||
})
|
||||
case.complete(0)
|
||||
assert case.launched[0][1]["can_ai_assistant"] is expected
|
||||
|
||||
|
||||
def test_im_ai_permission_is_evaluated_after_ticket_load(chat_controller):
|
||||
case = chat_controller
|
||||
case.controller.shell_window.permissions = ["tcm.diagnosis/aiAssistant"]
|
||||
case.request(456)
|
||||
case.controller.shell_window.permissions = []
|
||||
case.complete(0)
|
||||
assert case.launched[0][1]["can_ai_assistant"] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("capability, expected", [(True, True), (False, False), (None, False), (1, False), ("true", False)])
|
||||
def test_video_launcher_forwards_only_explicit_ai_capability(monkeypatch, capability, expected):
|
||||
from doctor_workstation.video import window as window_module
|
||||
from doctor_workstation.video.launcher import launch_video_call
|
||||
|
||||
launches = []
|
||||
sentinel = object()
|
||||
|
||||
def capture(request, **kwargs):
|
||||
launches.append((request, kwargs))
|
||||
return sentinel
|
||||
|
||||
monkeypatch.setattr(window_module, "open_video_call", capture)
|
||||
result = launch_video_call(
|
||||
ticket(), repository=object(), open_im=True, can_ai_assistant=capability,
|
||||
)
|
||||
assert result is sentinel
|
||||
request, options = launches[0]
|
||||
assert request.diagnosis_id == 123
|
||||
assert request.patient_id == 8
|
||||
assert request.appointment_id == 456
|
||||
assert options["can_ai_assistant"] is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("second_diagnosis", [123, 124])
|
||||
@pytest.mark.parametrize("completion_order", [(0, 1), (1, 0)])
|
||||
def test_latest_im_selection_retires_pending_callbacks(chat_controller, second_diagnosis, completion_order):
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import pytest
|
||||
from PySide6.QtWidgets import QApplication, QDialog, QPlainTextEdit, QWidget
|
||||
|
||||
from doctor_workstation.core.transcript_text import simplified_transcript
|
||||
from doctor_workstation.ui.dialogs.diagnosis import DiagnosisDialog
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("source", "expected"),
|
||||
[
|
||||
("你會說老家話嗎?很會,很會。", "你会说老家话吗?很会,很会。"),
|
||||
("沒有過敏,沒有吃藥。0.5 mg,不是 5 mg。", "没有过敏,没有吃药。0.5 mg,不是 5 mg。"),
|
||||
("血壓 120/80 mmHg,血糖 2.00–30.00 mmol/L,HbA1c 6.5%。",
|
||||
"血压 120/80 mmHg,血糖 2.00–30.00 mmol/L,HbA1c 6.5%。"),
|
||||
("唔係,冇食藥,咩事?", "唔系,冇食药,咩事?"),
|
||||
("患者:口乾。\n醫生:不?\n患者:不。", "患者:口干。\n医生:不?\n患者:不。"),
|
||||
("简体,不! \n0.5 mg\tB12", "简体,不! \n0.5 mg\tB12"),
|
||||
("", ""),
|
||||
],
|
||||
)
|
||||
def test_script_conversion_is_offline_and_preserves_clinical_tokens(monkeypatch, source, expected):
|
||||
def no_network(*args, **kwargs):
|
||||
pytest.fail("Script conversion must use bundled dictionaries only")
|
||||
|
||||
monkeypatch.setattr(socket.socket, "connect", no_network)
|
||||
# A fresh thread loads its own dictionaries, even when a prior test ran.
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
assert pool.submit(simplified_transcript, source).result() == expected
|
||||
assert simplified_transcript(expected) == expected
|
||||
|
||||
|
||||
def test_historical_transcript_dialog_displays_simplified_without_changing_record(monkeypatch):
|
||||
application = QApplication.instance() or QApplication([])
|
||||
parent = QWidget()
|
||||
record = {"transcript_text": "患者:你會說老家話嗎?\n患者:沒有吃藥,0.5 mg。"}
|
||||
source = DiagnosisDialog._call_transcript_text(record)
|
||||
displayed = []
|
||||
|
||||
def inspect(dialog):
|
||||
displayed.append(dialog.findChild(QPlainTextEdit, "DiagnosisCallTranscriptText").toPlainText())
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(QDialog, "exec", inspect)
|
||||
try:
|
||||
DiagnosisDialog._view_call_transcript(parent, 12, source)
|
||||
assert displayed == ["患者:你会说老家话吗?\n患者:没有吃药,0.5 mg。"]
|
||||
assert record["transcript_text"] == source
|
||||
finally:
|
||||
parent.close()
|
||||
application.processEvents()
|
||||
@@ -1,234 +0,0 @@
|
||||
"""Retry a failed storage start without duplicate requests or reopening a call."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
|
||||
import pytest
|
||||
|
||||
from doctor_workstation.video.launcher import VideoCallRequest
|
||||
from doctor_workstation.video.lifecycle import OrderedCallLifecycle
|
||||
|
||||
|
||||
class Repository:
|
||||
def __init__(self, *, fail_first: bool = False, block_attempt: int = 0) -> None:
|
||||
self.fail_first = fail_first
|
||||
self.block_attempt = block_attempt
|
||||
self.attempts: list[dict] = []
|
||||
self.entered = threading.Event()
|
||||
self.release = threading.Event()
|
||||
|
||||
def start_call(self, **_payload):
|
||||
return {"call_record_id": 71}
|
||||
|
||||
def start_call_transcription(self, **payload):
|
||||
self.attempts.append(payload)
|
||||
attempt = len(self.attempts)
|
||||
if attempt == self.block_attempt:
|
||||
self.entered.set()
|
||||
assert self.release.wait(3), "test did not release storage request"
|
||||
if self.fail_first and attempt == 1:
|
||||
raise RuntimeError("temporary storage failure")
|
||||
|
||||
def finish_call_transcription(self, **_payload):
|
||||
return True
|
||||
|
||||
def end_call(self, **_payload):
|
||||
return True
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_lifecycle():
|
||||
lifecycles = []
|
||||
|
||||
def make(**options):
|
||||
repository = Repository(**options)
|
||||
request = VideoCallRequest(
|
||||
sdk_app_id=1400123456,
|
||||
user_id="doctor-test",
|
||||
user_sig="test-ticket",
|
||||
target_user_id="patient-test",
|
||||
diagnosis_id=12,
|
||||
)
|
||||
lifecycle = OrderedCallLifecycle(request, repository, logging.getLogger(__name__))
|
||||
lifecycles.append((lifecycle, repository))
|
||||
assert lifecycle.start().result(timeout=2) is True
|
||||
return lifecycle, repository
|
||||
|
||||
yield make
|
||||
for lifecycle, repository in lifecycles:
|
||||
repository.release.set()
|
||||
lifecycle.end("test-cleanup").result(timeout=3)
|
||||
assert lifecycle.wait(3)
|
||||
|
||||
|
||||
def test_failed_storage_start_retries_same_session_then_reuses_success(make_lifecycle):
|
||||
lifecycle, repository = make_lifecycle(fail_first=True)
|
||||
failed = lifecycle.start_transcription("tr-retry", language="zh")
|
||||
with pytest.raises(RuntimeError, match="temporary storage failure"):
|
||||
failed.result(timeout=2)
|
||||
|
||||
retry = lifecycle.start_transcription("tr-retry", language="zh")
|
||||
assert retry is not failed
|
||||
assert retry.result(timeout=2) is True
|
||||
assert lifecycle.start_transcription("tr-retry") is retry
|
||||
assert lifecycle.transcription_session_id == "tr-retry"
|
||||
assert len(repository.attempts) == 2
|
||||
assert (
|
||||
repository.attempts[0]
|
||||
== repository.attempts[1]
|
||||
== {
|
||||
"diagnosis_id": 12,
|
||||
"call_record_id": 71,
|
||||
"transcription_session_id": "tr-retry",
|
||||
"language": "zh",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_inflight_start_is_reused_without_blocking_caller(make_lifecycle):
|
||||
lifecycle, repository = make_lifecycle(block_attempt=1)
|
||||
first = lifecycle.start_transcription("tr-running")
|
||||
try:
|
||||
assert repository.entered.wait(2)
|
||||
assert not first.done()
|
||||
assert lifecycle.start_transcription("tr-running") is first
|
||||
assert len(repository.attempts) == 1
|
||||
finally:
|
||||
repository.release.set()
|
||||
assert first.result(timeout=2) is True
|
||||
|
||||
|
||||
def test_concurrent_retry_callers_share_one_new_request(make_lifecycle):
|
||||
lifecycle, repository = make_lifecycle(fail_first=True, block_attempt=2)
|
||||
with pytest.raises(RuntimeError, match="temporary storage failure"):
|
||||
lifecycle.start_transcription("tr-concurrent").result(timeout=2)
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=4) as callers:
|
||||
futures = list(
|
||||
callers.map(lambda _: lifecycle.start_transcription("tr-concurrent"), range(4))
|
||||
)
|
||||
assert repository.entered.wait(2)
|
||||
assert all(future is futures[0] for future in futures)
|
||||
assert not futures[0].done()
|
||||
assert len(repository.attempts) == 2
|
||||
finally:
|
||||
repository.release.set()
|
||||
assert futures[0].result(timeout=2) is True
|
||||
|
||||
|
||||
def test_false_completion_can_retry_without_changing_identity(make_lifecycle):
|
||||
lifecycle, repository = make_lifecycle()
|
||||
# Seed the documented False completion (e.g. call-start dependency had not
|
||||
# succeeded), then exercise retry against a now-available actual lifecycle.
|
||||
previous: Future[bool] = Future()
|
||||
previous.set_result(False)
|
||||
lifecycle._transcription_session_id = "tr-false"
|
||||
lifecycle._transcription_start_future = previous
|
||||
|
||||
retry = lifecycle.start_transcription("tr-false")
|
||||
assert retry is not previous
|
||||
assert retry.result(timeout=2) is True
|
||||
assert lifecycle.start_transcription("tr-false") is retry
|
||||
assert len(repository.attempts) == 1
|
||||
assert repository.attempts[0]["transcription_session_id"] == "tr-false"
|
||||
|
||||
|
||||
def test_cancelled_queued_start_can_retry_same_session(make_lifecycle):
|
||||
lifecycle, repository = make_lifecycle()
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
def occupy_worker():
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
|
||||
lifecycle._worker.submit("test-block", occupy_worker)
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
cancelled = lifecycle.start_transcription("tr-cancelled")
|
||||
assert cancelled.cancel()
|
||||
retry = lifecycle.start_transcription("tr-cancelled")
|
||||
assert retry is not cancelled
|
||||
finally:
|
||||
release.set()
|
||||
assert retry.result(timeout=2) is True
|
||||
assert len(repository.attempts) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state", ["running", "succeeded", "failed", "false"])
|
||||
def test_session_identity_cannot_change_even_after_failure(make_lifecycle, state):
|
||||
lifecycle, repository = make_lifecycle(
|
||||
fail_first=state == "failed", block_attempt=1 if state == "running" else 0
|
||||
)
|
||||
if state == "false":
|
||||
first: Future[bool] = Future()
|
||||
first.set_result(False)
|
||||
lifecycle._transcription_session_id = "tr-original"
|
||||
lifecycle._transcription_start_future = first
|
||||
else:
|
||||
first = lifecycle.start_transcription("tr-original")
|
||||
if state == "running":
|
||||
assert repository.entered.wait(2)
|
||||
elif state == "failed":
|
||||
with pytest.raises(RuntimeError, match="temporary storage failure"):
|
||||
first.result(timeout=2)
|
||||
else:
|
||||
assert first.result(timeout=2)
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match="another transcription session"):
|
||||
lifecycle.start_transcription("tr-different")
|
||||
assert lifecycle.transcription_session_id == "tr-original"
|
||||
finally:
|
||||
repository.release.set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminal", ["finish", "end"])
|
||||
@pytest.mark.parametrize("failed", [False, True])
|
||||
def test_finish_or_end_blocks_restart_before_and_after_completion(make_lifecycle, terminal, failed):
|
||||
lifecycle, repository = make_lifecycle(fail_first=failed)
|
||||
first = lifecycle.start_transcription("tr-terminal")
|
||||
if failed:
|
||||
with pytest.raises(RuntimeError, match="temporary storage failure"):
|
||||
first.result(timeout=2)
|
||||
else:
|
||||
assert first.result(timeout=2)
|
||||
|
||||
ending = (
|
||||
lifecycle.finish_transcription(status="partial")
|
||||
if terminal == "finish"
|
||||
else lifecycle.end("test-terminal")
|
||||
)
|
||||
error = "already stopped" if terminal == "finish" else "already ended"
|
||||
with pytest.raises(RuntimeError, match=error):
|
||||
lifecycle.start_transcription("tr-terminal")
|
||||
ending.result(timeout=2)
|
||||
with pytest.raises(RuntimeError, match=error):
|
||||
lifecycle.start_transcription("tr-terminal")
|
||||
assert len(repository.attempts) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminal", ["finish", "end"])
|
||||
def test_terminal_request_blocks_start_even_while_original_start_is_running(
|
||||
make_lifecycle, terminal
|
||||
):
|
||||
lifecycle, repository = make_lifecycle(block_attempt=1)
|
||||
first = lifecycle.start_transcription("tr-draining")
|
||||
try:
|
||||
assert repository.entered.wait(2)
|
||||
ending = (
|
||||
lifecycle.finish_transcription()
|
||||
if terminal == "finish"
|
||||
else lifecycle.end("test-draining")
|
||||
)
|
||||
assert not first.done()
|
||||
assert not ending.done()
|
||||
error = "already stopped" if terminal == "finish" else "already ended"
|
||||
with pytest.raises(RuntimeError, match=error):
|
||||
lifecycle.start_transcription("tr-draining")
|
||||
finally:
|
||||
repository.release.set()
|
||||
assert first.result(timeout=2) is True
|
||||
assert ending.result(timeout=2) is True
|
||||
assert len(repository.attempts) == 1
|
||||
@@ -295,48 +295,6 @@ def test_real_demo_login_reaches_success_without_widget_adapter(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_login_password_group_keeps_focus_when_reveal_is_keyboard_focused(tmp_path: Any) -> None:
|
||||
application = QApplication.instance() or QApplication([])
|
||||
apply_theme(application)
|
||||
window = LoginWindow(
|
||||
object(), settings=QSettings(str(tmp_path / "focus.ini"), QSettings.Format.IniFormat),
|
||||
)
|
||||
window.show()
|
||||
application.processEvents()
|
||||
group = window.password_edit.parentWidget()
|
||||
geometry = group.geometry()
|
||||
try:
|
||||
for control in (window.password_edit, window.reveal_button):
|
||||
control.setFocus()
|
||||
application.processEvents()
|
||||
assert group.property("focused") is True
|
||||
assert group.geometry() == geometry
|
||||
window.login_button.setFocus()
|
||||
application.processEvents()
|
||||
assert group.property("focused") is False
|
||||
assert group.geometry() == geometry
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
|
||||
def test_compact_login_keeps_the_whole_form_visible(tmp_path: Any) -> None:
|
||||
application = QApplication.instance() or QApplication([])
|
||||
apply_theme(application)
|
||||
window = LoginWindow(
|
||||
object(), settings=QSettings(str(tmp_path / "compact.ini"), QSettings.Format.IniFormat),
|
||||
)
|
||||
window.resize(860, 640)
|
||||
window.show()
|
||||
application.processEvents()
|
||||
try:
|
||||
assert not window.brand_panel.isVisible()
|
||||
assert window.login_scroll.verticalScrollBar().maximum() == 0
|
||||
assert window.card.height() >= window.card.minimumSizeHint().height()
|
||||
assert window.login_button.isVisibleTo(window)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
|
||||
def test_remembered_password_survives_a_new_login_window(tmp_path: Any) -> None:
|
||||
application = QApplication.instance() or QApplication([])
|
||||
settings_path = tmp_path / "remember-password.ini"
|
||||
|
||||
@@ -38,8 +38,6 @@ def page(application, monkeypatch):
|
||||
|
||||
|
||||
def test_reception_prompts_remain_readable_in_a_narrow_workspace(page, application):
|
||||
# The responsive workspace exposes insights in its second tab.
|
||||
page.workbench.mode_tabs.setCurrentIndex(1)
|
||||
settle(application)
|
||||
for button in page.ai_prompt_buttons:
|
||||
assert button.width() >= button.minimumSizeHint().width()
|
||||
@@ -50,8 +48,6 @@ def test_reception_prompts_remain_readable_in_a_narrow_workspace(page, applicati
|
||||
|
||||
|
||||
def test_hidden_tall_consultation_does_not_expand_daily_records(page, application):
|
||||
# Force real overflow: a short case is allowed to fill the viewport.
|
||||
page.case_labels["present"].setText("Long clinical history\n" * 80)
|
||||
page.detail_tabs.setCurrentIndex(0)
|
||||
settle(application)
|
||||
consultation_height = page.clinical_pages.height()
|
||||
|
||||