|
|
|
@@ -4,19 +4,32 @@ from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import json
|
|
|
|
|
import re
|
|
|
|
|
from collections import namedtuple
|
|
|
|
|
from collections.abc import Container, Mapping, Sequence
|
|
|
|
|
from collections import deque, namedtuple
|
|
|
|
|
from collections.abc import Callable, Container, Mapping, Sequence
|
|
|
|
|
from contextlib import suppress
|
|
|
|
|
from copy import deepcopy
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
from threading import Event
|
|
|
|
|
from threading import Event, Lock
|
|
|
|
|
from time import monotonic
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
|
from PySide6.QtCore import QObject, QRunnable, QSize, Qt, QThreadPool, QTimer, Signal, Slot
|
|
|
|
|
from PySide6.QtCore import (
|
|
|
|
|
QCoreApplication,
|
|
|
|
|
QEvent,
|
|
|
|
|
QObject,
|
|
|
|
|
QRunnable,
|
|
|
|
|
QSize,
|
|
|
|
|
Qt,
|
|
|
|
|
QThreadPool,
|
|
|
|
|
QTimer,
|
|
|
|
|
Signal,
|
|
|
|
|
Slot,
|
|
|
|
|
)
|
|
|
|
|
from PySide6.QtGui import (
|
|
|
|
|
QIcon,
|
|
|
|
|
QKeyEvent,
|
|
|
|
|
QTextBlock,
|
|
|
|
|
QTextBlockFormat,
|
|
|
|
|
QTextCharFormat,
|
|
|
|
|
QTextCursor,
|
|
|
|
|
QTextDocument,
|
|
|
|
@@ -40,6 +53,7 @@ from PySide6.QtWidgets import (
|
|
|
|
|
QVBoxLayout,
|
|
|
|
|
QWidget,
|
|
|
|
|
)
|
|
|
|
|
from shiboken6 import isValid
|
|
|
|
|
|
|
|
|
|
from .. import icons
|
|
|
|
|
from ..chat_items import parse_chat_item as _parse_chat_item
|
|
|
|
@@ -2045,6 +2059,42 @@ class _FlowRow(QWidget):
|
|
|
|
|
self._layout.addWidget(widget)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _stable_markdown_prefix(text: str) -> int:
|
|
|
|
|
"""Return a paragraph boundary outside fenced code; positions are source offsets."""
|
|
|
|
|
fence = ""
|
|
|
|
|
offset = boundary = 0
|
|
|
|
|
for line in text.splitlines(keepends=True):
|
|
|
|
|
marker = re.match(r"^[ \t]{0,3}(`{3,}|~{3,})(.*)$", line.rstrip("\r\n"))
|
|
|
|
|
if marker:
|
|
|
|
|
run, suffix = marker.groups()
|
|
|
|
|
if not fence:
|
|
|
|
|
fence = run
|
|
|
|
|
elif run[0] == fence[0] and len(run) >= len(fence) and not suffix.strip():
|
|
|
|
|
fence = ""
|
|
|
|
|
elif not fence and not line.strip() and line.endswith("\n"):
|
|
|
|
|
boundary = offset + len(line)
|
|
|
|
|
offset += len(line)
|
|
|
|
|
return boundary
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _insert_stream_markdown(cursor: QTextCursor, text: str) -> QTextBlock | None:
|
|
|
|
|
position = cursor.position()
|
|
|
|
|
cursor.insertMarkdown(text)
|
|
|
|
|
first = cursor.document().findBlock(position)
|
|
|
|
|
# Qt merges the first imported block with the existing empty tail block and
|
|
|
|
|
# drops its heading level. Restore it before applying the normal type scale.
|
|
|
|
|
heading = re.match(r"^[ \t]{0,3}(#{1,6})[ \t]+", text)
|
|
|
|
|
if heading:
|
|
|
|
|
fmt = first.blockFormat()
|
|
|
|
|
fmt.setHeadingLevel(len(heading.group(1)))
|
|
|
|
|
QTextCursor(first).setBlockFormat(fmt)
|
|
|
|
|
# List import can leave the pre-existing empty tail before its first item.
|
|
|
|
|
# Keep the structural block, but don't let it create a large visual gap.
|
|
|
|
|
if not first.text() and first.next().isValid() and re.match(r"^\s*(?:[-+*]|\d+[.)])\s+", text):
|
|
|
|
|
return first
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class _RichMessage(QTextBrowser):
|
|
|
|
|
"""Chat body that auto-detects markdown / HTML / JSON / plain text."""
|
|
|
|
|
|
|
|
|
@@ -2061,15 +2111,87 @@ class _RichMessage(QTextBrowser):
|
|
|
|
|
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
|
|
|
|
self.document().setDocumentMargin(0)
|
|
|
|
|
self._fitting = False
|
|
|
|
|
self._fit_key: tuple[int, int, str] | None = None
|
|
|
|
|
self._streaming = False
|
|
|
|
|
self._stream_tail = ""
|
|
|
|
|
self._stream_tail_position = 0
|
|
|
|
|
self._stream_tail_plain = False
|
|
|
|
|
self.document().contentsChanged.connect(self._fit)
|
|
|
|
|
|
|
|
|
|
def set_payload(self, raw: Any) -> None:
|
|
|
|
|
# Markdown parsing and block formatting both emit contentsChanged. Fit
|
|
|
|
|
# once after the complete update instead of laying out each mutation.
|
|
|
|
|
# Suppress Qt's intermediate layouts as well as our own contentsChanged
|
|
|
|
|
# handler: block formatting would otherwise lay out the long reply over
|
|
|
|
|
# and over while it is still being updated.
|
|
|
|
|
document = self.document()
|
|
|
|
|
self._streaming = False
|
|
|
|
|
layout_enabled = document.isLayoutEnabled()
|
|
|
|
|
self._fitting = True
|
|
|
|
|
self._fit_key = None
|
|
|
|
|
document.setLayoutEnabled(False)
|
|
|
|
|
try:
|
|
|
|
|
render_chat_payload(self, raw, role=self._role)
|
|
|
|
|
finally:
|
|
|
|
|
document.setLayoutEnabled(layout_enabled)
|
|
|
|
|
self._fitting = False
|
|
|
|
|
self._fit()
|
|
|
|
|
|
|
|
|
|
def append_stream_text(self, text: str) -> None:
|
|
|
|
|
"""Keep completed Markdown paragraphs; only parse the unfinished tail.
|
|
|
|
|
|
|
|
|
|
Very long unfinished paragraphs/code use incremental plain text until the
|
|
|
|
|
block closes. The terminal payload still receives one full Markdown pass.
|
|
|
|
|
"""
|
|
|
|
|
document = self.document()
|
|
|
|
|
self._fitting = True
|
|
|
|
|
self._fit_key = None
|
|
|
|
|
cursor = QTextCursor(document)
|
|
|
|
|
cursor.beginEditBlock()
|
|
|
|
|
empty_separators: list[QTextBlock] = []
|
|
|
|
|
try:
|
|
|
|
|
if not self._streaming:
|
|
|
|
|
document.clear()
|
|
|
|
|
document.setDefaultStyleSheet(_AI_DOCUMENT_CSS)
|
|
|
|
|
self._streaming = True
|
|
|
|
|
self._stream_tail = ""
|
|
|
|
|
self._stream_tail_position = 0
|
|
|
|
|
self._stream_tail_plain = False
|
|
|
|
|
self._stream_tail += text
|
|
|
|
|
boundary = _stable_markdown_prefix(self._stream_tail)
|
|
|
|
|
position = self._stream_tail_position
|
|
|
|
|
cursor.movePosition(QTextCursor.MoveOperation.End)
|
|
|
|
|
if self._stream_tail_plain and not boundary:
|
|
|
|
|
cursor.insertText(text)
|
|
|
|
|
else:
|
|
|
|
|
cursor.setPosition(position)
|
|
|
|
|
cursor.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.KeepAnchor)
|
|
|
|
|
cursor.removeSelectedText()
|
|
|
|
|
cursor.setBlockFormat(QTextBlockFormat())
|
|
|
|
|
cursor.setCharFormat(QTextCharFormat())
|
|
|
|
|
if boundary:
|
|
|
|
|
completed = self._stream_tail[:boundary]
|
|
|
|
|
if completed.strip():
|
|
|
|
|
empty = _insert_stream_markdown(cursor, completed)
|
|
|
|
|
if empty is not None:
|
|
|
|
|
empty_separators.append(empty)
|
|
|
|
|
cursor.insertBlock(QTextBlockFormat(), QTextCharFormat())
|
|
|
|
|
self._stream_tail_position = cursor.position()
|
|
|
|
|
self._stream_tail = self._stream_tail[boundary:]
|
|
|
|
|
self._stream_tail_plain = len(self._stream_tail) > 2048
|
|
|
|
|
if self._stream_tail_plain:
|
|
|
|
|
cursor.insertText(self._stream_tail)
|
|
|
|
|
elif self._stream_tail:
|
|
|
|
|
empty = _insert_stream_markdown(cursor, self._stream_tail)
|
|
|
|
|
if empty is not None:
|
|
|
|
|
empty_separators.append(empty)
|
|
|
|
|
apply_reading_rhythm(self, role=self._role, start_position=position)
|
|
|
|
|
for block in empty_separators:
|
|
|
|
|
fmt = block.blockFormat()
|
|
|
|
|
fmt.setTopMargin(0)
|
|
|
|
|
fmt.setBottomMargin(0)
|
|
|
|
|
fmt.setLineHeight(1, QTextBlockFormat.LineHeightTypes.FixedHeight.value)
|
|
|
|
|
QTextCursor(block).setBlockFormat(fmt)
|
|
|
|
|
finally:
|
|
|
|
|
cursor.endEditBlock()
|
|
|
|
|
self._fitting = False
|
|
|
|
|
self._fit()
|
|
|
|
|
|
|
|
|
@@ -2078,15 +2200,20 @@ class _RichMessage(QTextBrowser):
|
|
|
|
|
self._fit()
|
|
|
|
|
|
|
|
|
|
def _fit(self) -> None:
|
|
|
|
|
if self._fitting:
|
|
|
|
|
if self._fitting or not self.document().isLayoutEnabled():
|
|
|
|
|
return
|
|
|
|
|
self._fitting = True
|
|
|
|
|
try:
|
|
|
|
|
width = max(1, self.viewport().width())
|
|
|
|
|
self.document().setTextWidth(width)
|
|
|
|
|
key = (self.document().revision(), width, self.document().defaultFont().toString())
|
|
|
|
|
if key == self._fit_key:
|
|
|
|
|
return
|
|
|
|
|
if self.document().textWidth() != width:
|
|
|
|
|
self.document().setTextWidth(width)
|
|
|
|
|
height = max(24, int(self.document().size().height()) + 8)
|
|
|
|
|
self.setMinimumHeight(height)
|
|
|
|
|
self.setMaximumHeight(height)
|
|
|
|
|
self._fit_key = key
|
|
|
|
|
if self.minimumHeight() != height or self.maximumHeight() != height:
|
|
|
|
|
self.setFixedHeight(height)
|
|
|
|
|
finally:
|
|
|
|
|
self._fitting = False
|
|
|
|
|
|
|
|
|
@@ -2124,9 +2251,47 @@ class _FittedText(QLabel):
|
|
|
|
|
Qt.TextFormat.RichText if rich else Qt.TextFormat.PlainText
|
|
|
|
|
)
|
|
|
|
|
self.setWordWrap(True)
|
|
|
|
|
self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
|
|
|
|
|
# This class owns measurement. Do not let QLabel's size hints reflow
|
|
|
|
|
# long HTML independently of the cached height-for-width path below.
|
|
|
|
|
self.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed))
|
|
|
|
|
self._rich = rich
|
|
|
|
|
self._fitting = False
|
|
|
|
|
self._measure_document = QTextDocument(self)
|
|
|
|
|
self._measure_key: tuple[str, str, bool] | None = None
|
|
|
|
|
self._measured_heights: dict[int, int] = {}
|
|
|
|
|
|
|
|
|
|
def sizeHint(self) -> QSize: # noqa: N802 - Qt API
|
|
|
|
|
return QSize(0, max(1, self.minimumHeight()))
|
|
|
|
|
|
|
|
|
|
def minimumSizeHint(self) -> QSize: # noqa: N802 - Qt API
|
|
|
|
|
return self.sizeHint()
|
|
|
|
|
|
|
|
|
|
def heightForWidth(self, width: int) -> int: # noqa: N802 - Qt API
|
|
|
|
|
# The height is already fixed for the actual widget width. Letting Qt
|
|
|
|
|
# negotiate hypothetical widths here causes thousands of extra reflows
|
|
|
|
|
# in nested report layouts; resizeEvent measures the real width once.
|
|
|
|
|
return max(1, self.minimumHeight())
|
|
|
|
|
|
|
|
|
|
def _height_at_width(self, width: int) -> int:
|
|
|
|
|
key = (self.text(), self.font().toString(), self._rich)
|
|
|
|
|
document = self._measure_document
|
|
|
|
|
if key != self._measure_key:
|
|
|
|
|
document.setDefaultFont(self.font())
|
|
|
|
|
if self._rich:
|
|
|
|
|
document.setHtml(self.text())
|
|
|
|
|
else:
|
|
|
|
|
document.setPlainText(self.text())
|
|
|
|
|
self._measure_key = key
|
|
|
|
|
self._measured_heights.clear()
|
|
|
|
|
width = max(1, width)
|
|
|
|
|
height = self._measured_heights.get(width)
|
|
|
|
|
if height is None:
|
|
|
|
|
document.setTextWidth(width)
|
|
|
|
|
height = max(1, int(document.size().height()) + 1)
|
|
|
|
|
if len(self._measured_heights) >= 8:
|
|
|
|
|
self._measured_heights.clear()
|
|
|
|
|
self._measured_heights[width] = height
|
|
|
|
|
return height
|
|
|
|
|
|
|
|
|
|
def setText(self, text: str) -> None: # noqa: N802 - Qt API
|
|
|
|
|
super().setText(text)
|
|
|
|
@@ -2140,25 +2305,25 @@ class _FittedText(QLabel):
|
|
|
|
|
super().resizeEvent(event)
|
|
|
|
|
self._fit()
|
|
|
|
|
|
|
|
|
|
def changeEvent(self, event: QEvent) -> None: # noqa: N802 - Qt virtual
|
|
|
|
|
super().changeEvent(event)
|
|
|
|
|
if hasattr(self, "_measure_document") and event.type() in (
|
|
|
|
|
QEvent.Type.FontChange, QEvent.Type.StyleChange,
|
|
|
|
|
):
|
|
|
|
|
self._measure_key = None
|
|
|
|
|
self._fit()
|
|
|
|
|
|
|
|
|
|
def _fit(self) -> None:
|
|
|
|
|
if self._fitting:
|
|
|
|
|
return
|
|
|
|
|
width = self.width()
|
|
|
|
|
if width <= 1:
|
|
|
|
|
return
|
|
|
|
|
document = QTextDocument()
|
|
|
|
|
document.setDefaultFont(self.font())
|
|
|
|
|
if self._rich:
|
|
|
|
|
document.setHtml(self.text())
|
|
|
|
|
else:
|
|
|
|
|
document.setPlainText(self.text())
|
|
|
|
|
document.setTextWidth(width)
|
|
|
|
|
height = max(1, int(document.size().height()) + 1)
|
|
|
|
|
if height == self.minimumHeight() and height == self.maximumHeight():
|
|
|
|
|
return
|
|
|
|
|
self._fitting = True
|
|
|
|
|
try:
|
|
|
|
|
self.setFixedHeight(height)
|
|
|
|
|
height = self._height_at_width(width)
|
|
|
|
|
if height != self.minimumHeight() or height != self.maximumHeight():
|
|
|
|
|
self.setFixedHeight(height)
|
|
|
|
|
finally:
|
|
|
|
|
self._fitting = False
|
|
|
|
|
|
|
|
|
@@ -2262,6 +2427,7 @@ class _StructuredReportPanel(QWidget):
|
|
|
|
|
header.addWidget(title)
|
|
|
|
|
self.meta_label = QLabel(time_text)
|
|
|
|
|
self.meta_label.setObjectName("AiConsultClinicalMeta")
|
|
|
|
|
self.meta_label.setWordWrap(True)
|
|
|
|
|
header.addWidget(self.meta_label)
|
|
|
|
|
header.addStretch(1)
|
|
|
|
|
badge = QLabel(f"{len(self.sections)} 个要点")
|
|
|
|
@@ -2384,6 +2550,7 @@ class _ClinicalAnalysisPanel(QWidget):
|
|
|
|
|
header.addWidget(title)
|
|
|
|
|
self.meta_label = QLabel()
|
|
|
|
|
self.meta_label.setObjectName("AiConsultClinicalMeta")
|
|
|
|
|
self.meta_label.setWordWrap(True)
|
|
|
|
|
header.addWidget(self.meta_label)
|
|
|
|
|
header.addStretch(1)
|
|
|
|
|
badge = QLabel("初步判断")
|
|
|
|
@@ -2752,6 +2919,40 @@ def _report_visual_widget(
|
|
|
|
|
return host
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class _ReportRenderQueue(QObject):
|
|
|
|
|
"""Give concurrent completed reports separate turns of the GUI event loop."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, parent: QObject) -> None:
|
|
|
|
|
super().__init__(parent)
|
|
|
|
|
self._jobs: deque[Callable[[], None]] = deque()
|
|
|
|
|
self._timer = QTimer(self)
|
|
|
|
|
self._timer.setSingleShot(True)
|
|
|
|
|
self._timer.setInterval(16)
|
|
|
|
|
self._timer.timeout.connect(self._advance)
|
|
|
|
|
|
|
|
|
|
def submit(self, render: Callable[[], None]) -> None:
|
|
|
|
|
self._jobs.append(render)
|
|
|
|
|
if not self._timer.isActive():
|
|
|
|
|
self._timer.start()
|
|
|
|
|
|
|
|
|
|
def _advance(self) -> None:
|
|
|
|
|
try:
|
|
|
|
|
self._jobs.popleft()()
|
|
|
|
|
finally:
|
|
|
|
|
if self._jobs:
|
|
|
|
|
self._timer.start()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _queue_report_render(render: Callable[[], None]) -> None:
|
|
|
|
|
app = QCoreApplication.instance()
|
|
|
|
|
assert app is not None
|
|
|
|
|
queue = getattr(app, "_ai_report_render_queue", None)
|
|
|
|
|
if queue is None:
|
|
|
|
|
queue = _ReportRenderQueue(app)
|
|
|
|
|
app._ai_report_render_queue = queue
|
|
|
|
|
queue.submit(render)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class _ChatBubble(QWidget):
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
@@ -2765,6 +2966,7 @@ class _ChatBubble(QWidget):
|
|
|
|
|
super().__init__(parent)
|
|
|
|
|
self._role = role
|
|
|
|
|
self._raw_payload = text
|
|
|
|
|
self._report_render_pending = False
|
|
|
|
|
self._provenance: Mapping[str, Any] = {}
|
|
|
|
|
self._clinical_panel: _ClinicalAnalysisPanel | _StructuredReportPanel | None = None
|
|
|
|
|
self._standalone_visuals: list[QWidget] = []
|
|
|
|
@@ -2837,6 +3039,15 @@ class _ChatBubble(QWidget):
|
|
|
|
|
if self.body is not None:
|
|
|
|
|
self.body.set_payload(text)
|
|
|
|
|
|
|
|
|
|
def append_stream_text(self, text: str, full_text: str) -> None:
|
|
|
|
|
self._raw_payload = full_text
|
|
|
|
|
if self.body is not None:
|
|
|
|
|
self.body.append_stream_text(text)
|
|
|
|
|
|
|
|
|
|
def finish_stream_text(self) -> None:
|
|
|
|
|
if self.body is not None and self.body._streaming:
|
|
|
|
|
self.body.set_payload(self._raw_payload)
|
|
|
|
|
|
|
|
|
|
def set_provenance(self, value: Any) -> None:
|
|
|
|
|
self._provenance = dict(value) if isinstance(value, Mapping) else {}
|
|
|
|
|
|
|
|
|
@@ -2995,6 +3206,7 @@ class _ChatEvent(QWidget):
|
|
|
|
|
|
|
|
|
|
class _AiStreamSignals(QObject):
|
|
|
|
|
event = Signal(object)
|
|
|
|
|
ready = Signal()
|
|
|
|
|
error = Signal(object)
|
|
|
|
|
finished = Signal()
|
|
|
|
|
|
|
|
|
@@ -3017,13 +3229,50 @@ class _AiStreamWorker(QRunnable):
|
|
|
|
|
self.task = task
|
|
|
|
|
self.signals = _AiStreamSignals()
|
|
|
|
|
self._cancelled = Event()
|
|
|
|
|
self._pending_lock = Lock()
|
|
|
|
|
self._events: list[Any] = []
|
|
|
|
|
self._chunks: list[str] = []
|
|
|
|
|
self._first_text_queued = False
|
|
|
|
|
|
|
|
|
|
def cancel(self) -> None:
|
|
|
|
|
self._cancelled.set()
|
|
|
|
|
with self._pending_lock:
|
|
|
|
|
self._events.clear()
|
|
|
|
|
self._chunks.clear()
|
|
|
|
|
|
|
|
|
|
def is_cancelled(self) -> bool:
|
|
|
|
|
return self._cancelled.is_set()
|
|
|
|
|
|
|
|
|
|
def _queue_event(self, event: Any) -> None:
|
|
|
|
|
payload = dict(event) if isinstance(event, Mapping) else {}
|
|
|
|
|
delta = payload.get("event") == "delta" and isinstance(payload.get("text"), str)
|
|
|
|
|
wake = not delta
|
|
|
|
|
with self._pending_lock:
|
|
|
|
|
if self.is_cancelled():
|
|
|
|
|
return
|
|
|
|
|
if delta:
|
|
|
|
|
self._chunks.append(payload["text"])
|
|
|
|
|
if payload["text"] and not self._first_text_queued:
|
|
|
|
|
self._first_text_queued = True
|
|
|
|
|
wake = True
|
|
|
|
|
else:
|
|
|
|
|
if self._chunks:
|
|
|
|
|
self._events.append({"event": "delta", "text": "".join(self._chunks)})
|
|
|
|
|
self._chunks.clear()
|
|
|
|
|
self._events.append(event)
|
|
|
|
|
# Only control events and the first text wake the GUI. A GUI timer drains
|
|
|
|
|
# all later text even if the upstream pauses after its last chunk.
|
|
|
|
|
if wake:
|
|
|
|
|
self.signals.ready.emit()
|
|
|
|
|
|
|
|
|
|
def take_events(self) -> list[Any]:
|
|
|
|
|
with self._pending_lock:
|
|
|
|
|
if self._chunks:
|
|
|
|
|
self._events.append({"event": "delta", "text": "".join(self._chunks)})
|
|
|
|
|
self._chunks.clear()
|
|
|
|
|
events, self._events = self._events, []
|
|
|
|
|
return events
|
|
|
|
|
|
|
|
|
|
@Slot()
|
|
|
|
|
def run(self) -> None:
|
|
|
|
|
try:
|
|
|
|
@@ -3057,7 +3306,7 @@ class _AiStreamWorker(QRunnable):
|
|
|
|
|
for event in events:
|
|
|
|
|
if self.is_cancelled():
|
|
|
|
|
return
|
|
|
|
|
self.signals.event.emit(event)
|
|
|
|
|
self._queue_event(event)
|
|
|
|
|
if isinstance(event, Mapping) and event.get("event") == "done":
|
|
|
|
|
return
|
|
|
|
|
except Exception as error: # UI boundary: render transport/domain errors in place.
|
|
|
|
@@ -3436,6 +3685,12 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
self._stream_elapsed_timer = QTimer(self)
|
|
|
|
|
self._stream_elapsed_timer.setInterval(1000)
|
|
|
|
|
self._stream_elapsed_timer.timeout.connect(self._update_stream_elapsed)
|
|
|
|
|
self._delivery_timer = QTimer(self)
|
|
|
|
|
self._delivery_timer.setInterval(40)
|
|
|
|
|
self._delivery_timer.timeout.connect(self._poll_stream_events)
|
|
|
|
|
self._chat_scroll_timer = QTimer(self)
|
|
|
|
|
self._chat_scroll_timer.setSingleShot(True)
|
|
|
|
|
self._chat_scroll_timer.timeout.connect(self._scroll_chat_to_bottom)
|
|
|
|
|
self.setObjectName("AiConsultDialog")
|
|
|
|
|
self.setWindowTitle("问诊详情")
|
|
|
|
|
# QDialog 默认只带关闭按钮,医生无法把这个信息密度很高的窗口放大到整屏。
|
|
|
|
@@ -3977,7 +4232,7 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
self.chat_layout.insertWidget(self.chat_layout.count() - 1, bubble)
|
|
|
|
|
bubble.setVisible(self._chat_item_matches_filter(bubble))
|
|
|
|
|
if self._follow_chat:
|
|
|
|
|
QTimer.singleShot(0, self._scroll_chat_to_bottom)
|
|
|
|
|
self._request_chat_scroll()
|
|
|
|
|
return bubble
|
|
|
|
|
|
|
|
|
|
def _append_event(
|
|
|
|
@@ -3999,7 +4254,7 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
self.chat_layout.insertWidget(self.chat_layout.count() - 1, event)
|
|
|
|
|
event.setVisible(self._chat_item_matches_filter(event))
|
|
|
|
|
if self._follow_chat:
|
|
|
|
|
QTimer.singleShot(0, self._scroll_chat_to_bottom)
|
|
|
|
|
self._request_chat_scroll()
|
|
|
|
|
return event
|
|
|
|
|
|
|
|
|
|
def _chat_scroll_value_changed(self, value: int) -> None:
|
|
|
|
@@ -4008,7 +4263,11 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
|
|
|
|
|
def _chat_scroll_range_changed(self, _minimum: int, _maximum: int) -> None:
|
|
|
|
|
if self._follow_chat:
|
|
|
|
|
QTimer.singleShot(0, self._scroll_chat_to_bottom)
|
|
|
|
|
self._request_chat_scroll()
|
|
|
|
|
|
|
|
|
|
def _request_chat_scroll(self) -> None:
|
|
|
|
|
if not self._session_closed and self._follow_chat and not self._chat_scroll_timer.isActive():
|
|
|
|
|
self._chat_scroll_timer.start(0)
|
|
|
|
|
|
|
|
|
|
def _scroll_chat_to_bottom(self) -> None:
|
|
|
|
|
if self._session_closed or not self._follow_chat:
|
|
|
|
@@ -4609,12 +4868,50 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
bubble.set_provenance(row)
|
|
|
|
|
self._finalize_ai_bubble(bubble)
|
|
|
|
|
|
|
|
|
|
def _finalize_ai_bubble(self, bubble: _ChatBubble, *, prompt: str = "") -> None:
|
|
|
|
|
def _finalize_ai_bubble(
|
|
|
|
|
self, bubble: _ChatBubble, *, prompt: str = "", defer: bool = False,
|
|
|
|
|
) -> None:
|
|
|
|
|
"""Choose useful visual evidence from the current, owned record snapshot."""
|
|
|
|
|
|
|
|
|
|
metadata = _unwrap_analysis(bubble._provenance)
|
|
|
|
|
if not metadata.get("risk_assessment") and isinstance(bubble._raw_payload, Mapping):
|
|
|
|
|
metadata = _unwrap_analysis(bubble._raw_payload)
|
|
|
|
|
if defer and isinstance(bubble._raw_payload, str) and len(bubble._raw_payload) >= 4096:
|
|
|
|
|
# Preserve the exact completed body immediately. Stagger expensive
|
|
|
|
|
# report conversion across windows rather than processing every done
|
|
|
|
|
# signal in a single uninterruptible GUI turn. Freeze chart inputs
|
|
|
|
|
# now so a later workspace refresh cannot change this report.
|
|
|
|
|
generation = self._generation
|
|
|
|
|
diagnosis_id = self.diagnosis_id
|
|
|
|
|
owner = (diagnosis_id, self.patient_id, self._chart_patient_id)
|
|
|
|
|
patient_id = self._chart_patient_id or self.patient_id
|
|
|
|
|
eligible = not self._chart_patient_id or self.patient_id == self._chart_patient_id
|
|
|
|
|
sections = deepcopy(self._workspace_sections) if eligible else {}
|
|
|
|
|
if metadata.get("risk_assessment"):
|
|
|
|
|
sections["analysis"] = {"value": deepcopy(metadata)}
|
|
|
|
|
reply = bubble._raw_payload
|
|
|
|
|
bubble._report_render_pending = True
|
|
|
|
|
|
|
|
|
|
def render() -> None:
|
|
|
|
|
try:
|
|
|
|
|
if (
|
|
|
|
|
not isValid(self) or not isValid(bubble) or self._session_closed
|
|
|
|
|
or self._generation != generation
|
|
|
|
|
or (self.diagnosis_id, self.patient_id, self._chart_patient_id) != owner
|
|
|
|
|
):
|
|
|
|
|
return
|
|
|
|
|
visuals = build_report_visuals(
|
|
|
|
|
prompt, reply, sections=sections, diagnosis_id=diagnosis_id,
|
|
|
|
|
patient_id=patient_id,
|
|
|
|
|
) if eligible else ()
|
|
|
|
|
bubble.finalize_clinical_analysis(visuals=visuals)
|
|
|
|
|
if self._follow_chat:
|
|
|
|
|
self._request_chat_scroll()
|
|
|
|
|
finally:
|
|
|
|
|
bubble._report_render_pending = False
|
|
|
|
|
|
|
|
|
|
_queue_report_render(render)
|
|
|
|
|
return
|
|
|
|
|
visuals = self._record_visuals(prompt, _structured_markdown(bubble._raw_payload), metadata)
|
|
|
|
|
bubble.finalize_clinical_analysis(visuals=visuals)
|
|
|
|
|
|
|
|
|
@@ -5962,15 +6259,35 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
worker.signals.event.connect(
|
|
|
|
|
lambda event: self._stream_event(generation, stream_generation, event)
|
|
|
|
|
)
|
|
|
|
|
worker.signals.ready.connect(
|
|
|
|
|
lambda: self._drain_stream_events(generation, stream_generation, worker)
|
|
|
|
|
)
|
|
|
|
|
worker.signals.error.connect(
|
|
|
|
|
lambda error: self._stream_failed(generation, stream_generation, error)
|
|
|
|
|
lambda error: self._stream_worker_failed(generation, stream_generation, worker, error)
|
|
|
|
|
)
|
|
|
|
|
worker.signals.finished.connect(
|
|
|
|
|
lambda: self._stream_finished(generation, stream_generation, worker)
|
|
|
|
|
)
|
|
|
|
|
self._stream_timeout_timer.start(AI_STREAM_TOTAL_TIMEOUT_MS)
|
|
|
|
|
self._delivery_timer.start()
|
|
|
|
|
QThreadPool.globalInstance().start(worker)
|
|
|
|
|
QTimer.singleShot(0, self._scroll_chat_to_bottom)
|
|
|
|
|
self._request_chat_scroll()
|
|
|
|
|
|
|
|
|
|
def _poll_stream_events(self) -> None:
|
|
|
|
|
worker = self._stream_worker
|
|
|
|
|
if worker is not None:
|
|
|
|
|
self._drain_stream_events(self._generation, self._stream_generation, worker)
|
|
|
|
|
|
|
|
|
|
def _drain_stream_events(self, generation: int, stream_generation: int, worker: _AiStreamWorker) -> None:
|
|
|
|
|
if not self._stream_is_current(generation, stream_generation) or self._stream_ended_at is not None:
|
|
|
|
|
return
|
|
|
|
|
for event in worker.take_events():
|
|
|
|
|
self._stream_event(generation, stream_generation, event)
|
|
|
|
|
self._flush_stream_chunks()
|
|
|
|
|
|
|
|
|
|
def _stream_worker_failed(self, generation: int, stream_generation: int, worker: _AiStreamWorker, error: Exception) -> None:
|
|
|
|
|
self._drain_stream_events(generation, stream_generation, worker)
|
|
|
|
|
self._stream_failed(generation, stream_generation, error)
|
|
|
|
|
|
|
|
|
|
def _stream_is_current(self, generation: int, stream_generation: int) -> bool:
|
|
|
|
|
return generation == self._generation and stream_generation == self._stream_generation
|
|
|
|
@@ -6040,6 +6357,7 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
return
|
|
|
|
|
self._stream_meta.update(payload)
|
|
|
|
|
self._stream_completed = True
|
|
|
|
|
self._delivery_timer.stop()
|
|
|
|
|
self._stream_timeout_timer.stop()
|
|
|
|
|
self._stop_stream_clock()
|
|
|
|
|
if not self._stream_text and not self._pending_chunks:
|
|
|
|
@@ -6048,11 +6366,12 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
self._pending_chunks.append(str(answer))
|
|
|
|
|
self._flush_stream_chunks()
|
|
|
|
|
if self._stream_bubble is not None:
|
|
|
|
|
self._stream_bubble.finish_stream_text()
|
|
|
|
|
if not self._stream_text:
|
|
|
|
|
self._stream_text = "未返回分析内容。"
|
|
|
|
|
self._stream_bubble.set_payload(self._stream_text)
|
|
|
|
|
self._stream_bubble.set_provenance(self._stream_meta)
|
|
|
|
|
self._finalize_ai_bubble(self._stream_bubble, prompt=self._stream_prompt)
|
|
|
|
|
self._finalize_ai_bubble(self._stream_bubble, prompt=self._stream_prompt, defer=True)
|
|
|
|
|
# A terminal event completes the UI request even if transport cleanup
|
|
|
|
|
# has not returned yet. The next click must not depend on finished.
|
|
|
|
|
self._asking = False
|
|
|
|
@@ -6062,11 +6381,12 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
self._flush_timer.stop()
|
|
|
|
|
if not self._pending_chunks or self._stream_bubble is None:
|
|
|
|
|
return
|
|
|
|
|
self._stream_text += "".join(self._pending_chunks)
|
|
|
|
|
added = "".join(self._pending_chunks)
|
|
|
|
|
self._stream_text += added
|
|
|
|
|
self._pending_chunks.clear()
|
|
|
|
|
self._stream_bubble.set_payload(self._stream_text)
|
|
|
|
|
self._stream_bubble.append_stream_text(added, self._stream_text)
|
|
|
|
|
if self._follow_chat:
|
|
|
|
|
QTimer.singleShot(0, self._scroll_chat_to_bottom)
|
|
|
|
|
self._request_chat_scroll()
|
|
|
|
|
|
|
|
|
|
def _stream_failed(
|
|
|
|
|
self,
|
|
|
|
@@ -6077,6 +6397,7 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
if not self._stream_is_current(generation, stream_generation) or self._stream_ended_at is not None:
|
|
|
|
|
return
|
|
|
|
|
self._stream_timeout_timer.stop()
|
|
|
|
|
self._delivery_timer.stop()
|
|
|
|
|
self._stop_stream_clock()
|
|
|
|
|
self._flush_stream_chunks()
|
|
|
|
|
message = friendly_error(error)
|
|
|
|
@@ -6097,8 +6418,12 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
) -> None:
|
|
|
|
|
if not self._stream_is_current(generation, stream_generation):
|
|
|
|
|
return
|
|
|
|
|
self._drain_stream_events(generation, stream_generation, worker)
|
|
|
|
|
self._delivery_timer.stop()
|
|
|
|
|
self._stream_timeout_timer.stop()
|
|
|
|
|
self._flush_stream_chunks()
|
|
|
|
|
if self._stream_bubble is not None:
|
|
|
|
|
self._stream_bubble.finish_stream_text()
|
|
|
|
|
self._stop_stream_clock()
|
|
|
|
|
if self._stream_worker is worker:
|
|
|
|
|
self._stream_worker = None
|
|
|
|
@@ -6115,6 +6440,9 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
self.send_button.setEnabled(True)
|
|
|
|
|
|
|
|
|
|
def _stream_timed_out(self) -> None:
|
|
|
|
|
if not self._asking or self._stream_completed:
|
|
|
|
|
return
|
|
|
|
|
self._poll_stream_events()
|
|
|
|
|
if not self._asking or self._stream_completed:
|
|
|
|
|
return
|
|
|
|
|
self._flush_stream_chunks()
|
|
|
|
@@ -6128,6 +6456,8 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def _cancel_stream(self, *, replaced: bool = False) -> None:
|
|
|
|
|
if replaced and self._asking:
|
|
|
|
|
self._poll_stream_events()
|
|
|
|
|
if replaced and self._asking:
|
|
|
|
|
self._flush_stream_chunks()
|
|
|
|
|
self._stop_stream_clock()
|
|
|
|
@@ -6140,6 +6470,7 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
self._flush_timer.stop()
|
|
|
|
|
self._stream_timeout_timer.stop()
|
|
|
|
|
self._stream_elapsed_timer.stop()
|
|
|
|
|
self._delivery_timer.stop()
|
|
|
|
|
if self._stream_worker is not None:
|
|
|
|
|
self._stream_worker.cancel()
|
|
|
|
|
self._stream_worker = None
|
|
|
|
@@ -6159,6 +6490,7 @@ class AiConsultDialog(QDialog):
|
|
|
|
|
if self._session_closed:
|
|
|
|
|
return
|
|
|
|
|
self._session_closed = True
|
|
|
|
|
self._chat_scroll_timer.stop()
|
|
|
|
|
self._generation += 1
|
|
|
|
|
self._image_generation += 1
|
|
|
|
|
_abort_pending_thumbnails(self)
|
|
|
|
|