feat: 修订了调试功能

这个提交包含在:
2026-05-25 17:14:14 +08:00
父节点 8790fcb5a9
当前提交 61b20ca200
共有 17 个文件被更改,包括 838 次插入 和 61 次删除

查看文件

@ -1,7 +1,10 @@
from __future__ import annotations
from fastapi import APIRouter, HTTPException, Query
from typing import Optional
from fastapi import APIRouter, Header, HTTPException, Query
from app.core.dependencies import find_field, list_fields, reading_guard_manager, resolve_session_id
from app.core.experiment_debug import VoiceSpeedDebugProvider, debug_registry
from app.schemas.validation import DebugMenuItem, DebugMenuResponse
@ -121,3 +124,38 @@ async def debug_oscilloscope(action: str = Query(default="status")):
return provider.capture_frequency()
else:
raise HTTPException(status_code=400, detail=f"unknown action '{action}', use: status, peak, frequency")
@router.get("/guarded-fields")
async def debug_guarded_fields(
experiment: str = Query(default="cn.edu.muc.lxy.phyexp.voicespeed"),
):
fields = list_fields(experiment)
guarded = [
{
"field_id": f.fieldId,
"source": f.readingGuard.source.value if f.readingGuard else None,
"tolerance": f.readingGuard.tolerance if f.readingGuard else None,
"placeholder": f.placeholder,
"unit": f.unit,
}
for f in fields
if f.readingGuard and f.readingGuard.enabled
]
return {"experiment": experiment, "fields": guarded, "count": len(guarded)}
@router.get("/answer")
async def debug_answer(
field_id: str = Query(...),
experiment: str = Query(default="cn.edu.muc.lxy.phyexp.voicespeed"),
x_session_id: str | None = Header(default=None),
):
session_id = resolve_session_id(x_session_id)
all_fields = list_fields(experiment)
result = reading_guard_manager.get_reference_answer(session_id, field_id, all_fields)
if result is None:
raise HTTPException(status_code=400, detail="no reading guard active for this experiment")
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return {"experiment": experiment, "session_id": session_id, **result}

查看文件

@ -22,6 +22,44 @@ _active_monitors: dict[str, "_PeakMonitor"] = {}
_lock = threading.Lock()
def _auto_start_default() -> None:
with _lock:
session_id = "default"
existing = _active_monitors.pop(session_id, None)
if existing is not None:
existing.stop()
detector = PeakDetector()
caliper_ocr_service.reset()
monitor = _PeakMonitor(session_id, detector)
_active_monitors[session_id] = monitor
monitor.start()
_logger.info("峰值监控自动启动 (f5 已完成)")
reading_guard_manager.set_peak_ocr_start_callback(_auto_start_default)
def _peak_ocr_done() -> None:
with _lock:
monitor = _active_monitors.get("default")
if monitor is not None:
monitor.detector.acknowledge_peak()
_logger.info("峰值已确认,进入冷却等待下一次上升")
def _peak_ocr_failed() -> None:
with _lock:
monitor = _active_monitors.get("default")
if monitor is not None:
monitor.detector.acknowledge_peak()
caliper_ocr_service._index = max(0, caliper_ocr_service._index - 1)
_logger.info("峰值验证失败,回退 OCR 索引至 %d,请重新寻找峰值", caliper_ocr_service._index)
reading_guard_manager.set_peak_ocr_done_callback(_peak_ocr_done)
reading_guard_manager.set_peak_ocr_failed_callback(_peak_ocr_failed)
class _PeakMonitor:
def __init__(
self,
@ -57,6 +95,11 @@ class _PeakMonitor:
self.detector.set_ocr_reading(ocr_result.reading_mm)
_logger.info("峰值 %d 已检测 OCR读数=%.2f mm session=%s",
result.peak_index, ocr_result.reading_mm, self.session_id)
pending = reading_guard_manager.get_pending_field(self.session_id)
if pending and ocr_result.reading_mm is not None:
reading_guard_manager.submit_peak_ocr_answer(
self.session_id, pending[0], ocr_result.reading_mm)
_logger.info("OCR读数已提交到 reading_guard field=%s", pending[0])
except Exception as exc:
_logger.warning("峰值轮询异常: %s", exc)
time.sleep(POLL_INTERVAL)
@ -166,3 +209,23 @@ async def peak_monitor_acknowledge(
"peak_index": result.peak_index,
"state": result.state,
}
@router.post("/undo")
async def peak_monitor_undo(
x_session_id: str | None = Header(default=None),
):
session_id = resolve_session_id(x_session_id)
monitor = _get_monitor(session_id)
if monitor is None:
raise HTTPException(status_code=400, detail="峰值监控未启动")
detector = monitor.detector
if detector.state == PeakState.IDLE:
return {"success": False, "message": "无峰值可回退", "state": detector.state}
detector._state = PeakState.PEAK_TRIGGERED
caliper_ocr_service._index = max(0, caliper_ocr_service._index - 1)
_logger.info("峰值回退 session=%s index=%d", session_id, caliper_ocr_service._index)
return {"success": True, "message": "已回退到上一个峰值", "state": detector.state}

查看文件

@ -2,14 +2,33 @@ from __future__ import annotations
from fastapi import APIRouter, Header, HTTPException, Query
from app.api.peak_monitor import _active_monitors, _get_monitor
from app.core.dependencies import find_field, list_fields, reading_guard_manager, resolve_session_id, session_store
from app.core.validation import FieldValidator
from app.schemas.experiment import ReadingGuardSource
from app.schemas.validation import FieldValidationRequest, FieldValidationResponse
router = APIRouter(prefix="/value", tags=["value"])
def _peak_monitor_status_text(session_id: str) -> str | None:
monitor = _get_monitor(session_id) or _get_monitor("default")
if monitor is None:
return None
detector = monitor.detector
state = detector.state.value
if state == "idle":
return "空闲 — 等待数值上升"
if state == "rising":
return f"上升中 — 当前峰值 {detector._peak_max:.1f}"
if state == "peak_triggered":
return f"峰值已检测 (#{detector._peak_index}) — 请读取游标卡尺"
if state == "cooldown":
return "冷却中 — 等待下一次上升"
return None
@router.post("")
async def validate_field_value(
request: FieldValidationRequest,
@ -30,21 +49,71 @@ async def validate_field_value(
all_fields=list_fields(experiment),
)
if guard_result is not None:
guard_accept, guard_message = guard_result
if not guard_accept:
return FieldValidationResponse(accept=False, message=guard_message)
pending = reading_guard_manager.get_pending_field(session_id)
ctrl = _peak_monitor_status_text(session_id)
if not guard_result["accept"]:
return FieldValidationResponse(
accept=False, message=guard_result["message"],
severity=guard_result.get("severity", "error"),
reference=guard_result.get("reference"),
pending_field=pending[0] if pending else None,
control_status=ctrl,
)
session_store.set_value(session_id, request.field_id, request.value)
return FieldValidationResponse(accept=True, message=guard_message)
return FieldValidationResponse(
accept=True, message=guard_result["message"],
severity=guard_result.get("severity", "ok"),
reference=guard_result.get("reference"),
pending_field=pending[0] if pending else None,
control_status=ctrl,
)
session_store.set_value(session_id, request.field_id, request.value)
return base_result
@router.post("/undo")
async def undo_last_reading(
field_id: str,
experiment: str = Query(default="cn.edu.muc.lxy.phyexp.voicespeed"),
x_session_id: str | None = Header(default=None),
):
session_id = resolve_session_id(x_session_id)
field = find_field(experiment, field_id)
result = reading_guard_manager.undo(session_id, field, list_fields(experiment))
if result is None:
raise HTTPException(status_code=400, detail="no reading guard active for this session")
ok, msg = result
if ok:
session_store.delete_value(session_id, field_id)
pending = reading_guard_manager.get_pending_field(session_id)
cursor_now, cursor_total = reading_guard_manager.get_cursor(session_id)
return {
"success": ok,
"message": msg,
"pending_field": pending[0] if pending else None,
"cursor": cursor_now,
"total": cursor_total,
"session_id": session_id,
}
@router.get("")
async def get_all_field_values(x_session_id: str | None = Header(default=None)):
session_id = resolve_session_id(x_session_id)
fields = session_store.get_all(session_id)
return {"fields": fields, "count": len(fields), "session_id": session_id}
pending = reading_guard_manager.get_pending_field(session_id)
cursor_now, cursor_total = reading_guard_manager.get_cursor(session_id)
return {
"fields": fields,
"count": len(fields),
"session_id": session_id,
"pending_field": pending[0] if pending else None,
"cursor": cursor_now,
"total": cursor_total,
}
@router.get("/{field_id}")

查看文件

@ -34,6 +34,7 @@ class VoiceSpeedDebugProvider(ExperimentDebugProvider):
"oscilloscope_peak",
"oscilloscope_frequency",
"peak_monitor",
"debug_answer",
]
def status(self) -> Dict[str, Any]:

查看文件

@ -66,6 +66,9 @@ class PeakDetector:
if self._state == PeakState.IDLE:
if len(self._value_buffer) >= self.window_size:
buf = list(self._value_buffer)
if buf[-1] < buf[0] * (1.0 - self.drop_ratio):
return self._snapshot(peak_value)
self._state = PeakState.RISING
self._peak_max = max(self._value_buffer)
return self._snapshot(peak_value)
@ -85,8 +88,7 @@ class PeakDetector:
if self._state == PeakState.COOLDOWN:
valley = self._peak_max * (1.0 - self.cooldown_ratio)
if peak_value > valley * (1.0 + self.drop_ratio * 2):
self._state = PeakState.RISING
self._peak_max = max(self._value_buffer)
self._state = PeakState.IDLE
return self._snapshot(peak_value)
return self._snapshot(peak_value)
@ -97,7 +99,8 @@ class PeakDetector:
self._state = PeakState.COOLDOWN
self._ocr_reading = None
self._pending_field = None
return self._snapshot(self._peak_max if self._value_buffer else None)
self._value_buffer.clear()
return self._snapshot(self._peak_max if self._peak_max > 0 else None)
@property
def state(self) -> PeakState:

查看文件

@ -1,12 +1,15 @@
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from threading import Lock
from typing import Any, Dict, List, Optional
from typing import Any, Callable, Dict, List, Optional
from app.hardware.service import oscilloscope_service
from app.schemas.experiment import GridInputCell, ReadingGuardSource
_logger = logging.getLogger("reading_guard")
@dataclass
class GuardSessionState:
@ -18,12 +21,33 @@ class GuardSessionState:
source: ReadingGuardSource = ReadingGuardSource.MANUAL
manual_answers: Dict[str, Any] = field(default_factory=dict)
peak_ocr_answers: Dict[str, float] = field(default_factory=dict)
peak_monitor_triggered: bool = False
class ReadingGuardManager:
def __init__(self) -> None:
self._lock = Lock()
self._sessions: Dict[str, GuardSessionState] = {}
self._on_peak_ocr_start: Optional[Callable[[], None]] = None
self._on_peak_ocr_done: Optional[Callable[[], None]] = None
self._on_peak_ocr_failed: Optional[Callable[[], None]] = None
def set_peak_ocr_start_callback(self, callback: Callable[[], None]) -> None:
self._on_peak_ocr_start = callback
def set_peak_ocr_done_callback(self, callback: Callable[[], None]) -> None:
self._on_peak_ocr_done = callback
def set_peak_ocr_failed_callback(self, callback: Callable[[], None]) -> None:
self._on_peak_ocr_failed = callback
def _call_callback(self, cb: Optional[Callable[[], None]], label: str) -> None:
if cb is None:
return
try:
cb()
except Exception as exc:
_logger.warning("%s callback failed: %s", label, exc)
def set_manual_answer(self, session_id: str, field_id: str, value: Any) -> None:
with self._lock:
@ -35,6 +59,91 @@ class ReadingGuardManager:
state = self._sessions.setdefault(session_id, GuardSessionState())
state.peak_ocr_answers[field_id] = value
def get_pending_field(self, session_id: str) -> Optional[tuple[str, str, float]]:
with self._lock:
state = self._sessions.get(session_id)
if state is None or state.pending_field is None:
return None
src = state.source.value if isinstance(state.source, ReadingGuardSource) else str(state.source)
return (state.pending_field, src, state.tolerance)
def get_cursor(self, session_id: str) -> tuple[int, int]:
with self._lock:
state = self._sessions.get(session_id)
if state is None:
return (0, 0)
return (state.cursor, len(state.strict_fields))
def get_reference_answer(
self,
session_id: str,
field_id: str,
all_fields: List[GridInputCell],
) -> Optional[dict]:
state = self._ensure_initialized(session_id, all_fields)
if not state.strict_fields:
return None
if field_id not in state.strict_fields:
return {"error": f"field '{field_id}' is not in the strict reading order"}
idx = state.strict_fields.index(field_id)
fields_map = {f.fieldId: f for f in all_fields}
config = fields_map[field_id].readingGuard
if idx > state.cursor:
return {
"field_id": field_id,
"status": "not_started",
"message": f"field '{field_id}' 测量尚未开始,请按顺序先完成前面的步骤",
"cursor": state.cursor,
"total": len(state.strict_fields),
}
source = config.source if config else ReadingGuardSource.MANUAL
answer = state.peak_ocr_answers.get(field_id) if source == ReadingGuardSource.PEAK_OCR else (
state.manual_answers.get(field_id) if source == ReadingGuardSource.MANUAL else None
)
if answer is None and source in (ReadingGuardSource.DEVICE_PEAK, ReadingGuardSource.DEVICE_FREQUENCY):
answer = self._capture_answer(source, field_id, state)
if answer is not None:
return {
"field_id": field_id,
"status": "available",
"reference": answer,
"tolerance": config.tolerance if config else 0.0,
"source": source.value,
}
return {
"field_id": field_id,
"status": "pending",
"message": f"field '{field_id}' 的参考值尚未捕获",
"source": source.value,
}
def undo(
self,
session_id: str,
current_field: GridInputCell,
all_fields: List[GridInputCell],
) -> Optional[tuple[bool, str]]:
state = self._sessions.get(session_id)
if state is None or state.cursor == 0:
return False, "no reading to undo"
expected = state.strict_fields[state.cursor - 1]
if current_field.fieldId != expected:
return False, f"cannot undo: last completed field was {expected}"
state.cursor -= 1
fields_map = {f.fieldId: f for f in all_fields}
if state.source == ReadingGuardSource.PEAK_OCR:
state.peak_ocr_answers.pop(expected, None)
self._arm_next(state, fields_map)
return True, f"undid {expected}, now awaiting: {state.pending_field}"
def _capture_answer(self, source: ReadingGuardSource, field_id: str, state: GuardSessionState) -> Optional[float]:
if source == ReadingGuardSource.DEVICE_PEAK:
snapshot = oscilloscope_service.capture_peak()
@ -93,6 +202,12 @@ class ReadingGuardManager:
state.source = config.source if config else ReadingGuardSource.MANUAL
if state.source != ReadingGuardSource.PEAK_OCR:
state.pending_answer = self._capture_answer(state.source, next_field, state)
elif not state.peak_monitor_triggered and self._on_peak_ocr_start:
state.peak_monitor_triggered = True
try:
self._on_peak_ocr_start()
except Exception as exc:
_logger.warning("auto-start peak monitor failed: %s", exc)
def validate(
self,
@ -100,7 +215,7 @@ class ReadingGuardManager:
current_field: GridInputCell,
current_value: Any,
all_fields: List[GridInputCell],
) -> Optional[tuple[bool, str]]:
) -> Optional[dict]:
state = self._ensure_initialized(session_id, all_fields)
if not state.strict_fields:
return None
@ -109,37 +224,67 @@ class ReadingGuardManager:
return None
if state.pending_field is None:
return True, "reading process completed"
return {"accept": True, "message": "reading process completed", "severity": "ok", "reference": None}
if current_field.fieldId != state.pending_field:
return False, f"should submit field {state.pending_field}, please follow experiment reading order"
return {"accept": False, "message": f"should submit field {state.pending_field}, please follow experiment reading order", "severity": "error", "reference": None}
if state.source == ReadingGuardSource.PEAK_OCR:
state.pending_answer = self._capture_answer(state.source, current_field.fieldId, state)
if state.pending_answer is None:
source_label = "OCR" if state.source == ReadingGuardSource.PEAK_OCR else "standard reading"
return False, f"{source_label} not yet captured, please wait for peak detection or retry"
return {"accept": False, "message": f"{source_label} not yet captured, please wait for peak detection or retry", "severity": "error", "reference": None}
try:
student_value = float(current_value)
except Exception:
return False, "reading fields must be numeric"
return {"accept": False, "message": "reading fields must be numeric", "severity": "error", "reference": None}
error = abs(student_value - state.pending_answer)
if error > state.tolerance:
return (
False,
f"reading mismatch, reference {state.pending_answer:.2f}, tolerance ±{state.tolerance:.2f}, please re-enter",
)
config = current_field.readingGuard
tol1 = config.tolerance if config else 0.0
tol2 = config.tolerance2 if config else None
if error > (tol2 if tol2 is not None else tol1):
if state.source == ReadingGuardSource.PEAK_OCR:
self._call_callback(self._on_peak_ocr_failed, "peak_ocr_failed")
state.pending_answer = None
return {
"accept": False,
"message": f"reading mismatch, reference {state.pending_answer:.2f}, tolerance ±{tol1:.2f}, please re-enter",
"severity": "error",
"reference": state.pending_answer,
}
if tol2 is not None and error > tol1:
state.cursor += 1
fields_map = {f.fieldId: f for f in all_fields}
was_peak_ocr = state.source == ReadingGuardSource.PEAK_OCR
self._arm_next(state, fields_map)
if was_peak_ocr:
self._call_callback(self._on_peak_ocr_done, "peak_ocr_done")
msg = "reading correct, awaiting next: " + (state.pending_field or "done")
return {
"accept": True,
"message": f"读数精度略低 (偏差 {error:.2f} ≤ 二级容差 {tol2:.2f}),但仍接受。{msg}",
"severity": "warning",
"reference": state.pending_answer,
}
state.cursor += 1
fields_map = {f.fieldId: f for f in all_fields}
was_peak_ocr = state.source == ReadingGuardSource.PEAK_OCR
self._arm_next(state, fields_map)
if state.pending_field is None:
return True, "reading correct, all reading steps completed"
return True, f"reading correct, awaiting next: {state.pending_field}"
if was_peak_ocr:
self._call_callback(self._on_peak_ocr_done, "peak_ocr_done")
msg = "reading correct, awaiting next: " + (state.pending_field or "done")
return {
"accept": True,
"message": msg,
"severity": "ok",
"reference": state.pending_answer,
}
reading_guard_manager = ReadingGuardManager()

查看文件

@ -85,30 +85,27 @@ class Oscilloscope:
self._attached_drivers.clear()
def send_command_raw(self, cmd: bytes, timeout: int = DEFAULT_TIMEOUT_MS) -> Optional[bytes]:
"""
发送SCPI命令并返回响应数据。
:param cmd: SCPI命令字符串(会自动添加换行符)
:param timeout: 超时时间(毫秒)
:return: 响应字节数据,若失败则返回None
"""
if self.device is None or self.ep_out is None or self.ep_in is None:
raise RuntimeError("设备未连接,请先调用connect()")
# 发送命令
max_packet = self.ep_in.wMaxPacketSize
# 冲洗输入缓冲区,避免读到上一次命令的残留数据
try:
while True:
self.device.read(self.ep_in, max_packet, timeout=50)
except usb.core.USBError:
pass
try:
# self.device.write(self.ep_out.bEndpointAddress, cmd_bytes, timeout=timeout)
self.device.write(self.ep_out, cmd, timeout=timeout)
# self.ep_out.write(cmd_bytes, timeout)
except usb.core.USBError as e:
print(f"发送命令失败: {e}")
return None
# 读取响应(直到超时或收到短包)
response = b''
max_packet = self.ep_in.wMaxPacketSize # type: ignore
while True:
try:
# data = self.device.read(self.ep_in.bEndpointAddress, max_packet, timeout=timeout)
data = self.device.read(self.ep_in, max_packet, timeout=timeout)
if not data:
break
@ -116,7 +113,7 @@ class Oscilloscope:
if len(data) < max_packet:
break
except usb.core.USBError as e:
if e.errno == 110: # 超时,表示没有更多数据
if e.errno == 110:
break
else:
print(f"读取响应失败: {e}")

查看文件

@ -1,4 +1,6 @@
from app.schemas.experiment import (
ControlBar,
ControlBarItem,
ExperimentGridConfig,
GridCell,
GridComputedCell,

查看文件

@ -31,6 +31,7 @@ class ReadingGuardConfig(BaseModel):
enabled: bool = False
source: ReadingGuardSource = ReadingGuardSource.MANUAL
tolerance: float = 0.0
tolerance2: Optional[float] = None
class GridLabelCell(BaseModel):
@ -66,6 +67,19 @@ class GridComputedCell(BaseModel):
GridCell = Union[GridLabelCell, GridInputCell, GridComputedCell]
class ControlBarItem(BaseModel):
type: Literal["action", "status"]
id: str
label: str
method: Optional[str] = None
endpoint: Optional[str] = None
refreshMs: Optional[int] = None
class ControlBar(BaseModel):
items: List[ControlBarItem] = Field(default_factory=list)
class GridSheet(BaseModel):
id: str
title: Optional[str] = None
@ -73,6 +87,7 @@ class GridSheet(BaseModel):
columnHeaders: Optional[List[str]] = None
columnWidths: Optional[List[str]] = None
rowHeaders: Optional[List[str]] = None
controlBar: Optional[ControlBar] = None
cells: List[List[Optional[GridCell]]]

查看文件

@ -14,6 +14,10 @@ class FieldValidationRequest(BaseModel):
class FieldValidationResponse(BaseModel):
accept: bool
message: str
pending_field: Optional[str] = None
severity: str = "ok"
reference: Optional[float] = None
control_status: Optional[str] = None
class ManualAnswerRequest(BaseModel):

查看文件

@ -80,6 +80,12 @@
"min": 30,
"max": 45,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "device_frequency",
"tolerance": 0.5,
"tolerance2": 1.0
}
},
{
@ -92,6 +98,12 @@
"min": 30,
"max": 45,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "device_frequency",
"tolerance": 0.5,
"tolerance2": 1.0
}
},
{
@ -104,6 +116,12 @@
"min": 30,
"max": 45,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "device_frequency",
"tolerance": 0.5,
"tolerance2": 1.0
}
},
{
@ -116,6 +134,12 @@
"min": 30,
"max": 45,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "device_frequency",
"tolerance": 0.5,
"tolerance2": 1.0
}
},
{
@ -128,6 +152,12 @@
"min": 30,
"max": 45,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "device_frequency",
"tolerance": 0.5,
"tolerance2": 1.0
}
}
],
@ -219,7 +249,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -236,7 +267,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -253,7 +285,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -270,7 +303,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -287,7 +321,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
}
],
@ -310,7 +345,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -327,7 +363,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -344,7 +381,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -361,7 +399,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -378,7 +417,8 @@
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05
"tolerance": 0.05,
"tolerance2": 0.1
}
}
],
@ -508,7 +548,25 @@
"colSpan": 5
}
]
]
],
"controlBar": {
"items": [
{
"type": "action",
"id": "start_monitor",
"label": "启动峰值监控",
"method": "POST",
"endpoint": "/peak-monitor/start"
},
{
"type": "action",
"id": "stop_monitor",
"label": "停止峰值监控",
"method": "POST",
"endpoint": "/peak-monitor/stop"
}
]
}
},
{
"id": "table3_phase",
@ -537,6 +595,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -549,6 +613,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -561,6 +631,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -573,6 +649,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -585,6 +667,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
}
],
@ -603,6 +691,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -615,6 +709,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -627,6 +727,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -639,6 +745,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
},
{
@ -651,6 +763,12 @@
"min": 0,
"max": 400,
"required": true
},
"readingGuard": {
"enabled": true,
"source": "peak_ocr",
"tolerance": 0.05,
"tolerance2": 0.1
}
}
],
@ -780,7 +898,25 @@
"colSpan": 5
}
]
]
],
"controlBar": {
"items": [
{
"type": "action",
"id": "start_monitor",
"label": "启动峰值监控",
"method": "POST",
"endpoint": "/peak-monitor/start"
},
{
"type": "action",
"id": "stop_monitor",
"label": "停止峰值监控",
"method": "POST",
"endpoint": "/peak-monitor/stop"
}
]
}
},
{
"id": "table4_timediff",

查看文件

@ -56,6 +56,18 @@ const debugMenuItems = ref<DebugMenuItem[]>([])
const debugMenuLoading = ref(false)
const debugMenuError = ref('')
const debugActionLoading = ref<string | null>(null)
const debugFieldId = ref('')
const queryAnswerLoading = ref(false)
const undoLoading = ref(false)
type GuardedFieldInfo = {
field_id: string
source: string | null
tolerance: number | null
placeholder: string | null
unit: string | null
}
const guardedFields = ref<GuardedFieldInfo[]>([])
const currentExperiment = computed((): string => {
const hash = window.location.hash
@ -125,6 +137,20 @@ const loadDebugMenu = async () => {
}
}
const loadGuardedFields = async () => {
try {
const url = `${backendUrl.value}/debug/guarded-fields?experiment=${encodeURIComponent(currentExperiment.value)}`
const resp = await fetch(url)
if (resp.ok) {
const data = await resp.json()
guardedFields.value = (data?.fields || []) as GuardedFieldInfo[]
if (guardedFields.value.length > 0 && !debugFieldId.value) {
debugFieldId.value = guardedFields.value[0]!.field_id
}
}
} catch { /* ignore */ }
}
const executeDebugAction = async (item: DebugMenuItem) => {
debugActionLoading.value = item.action
const resultId = ++resultIdCounter
@ -163,6 +189,58 @@ const executeDebugAction = async (item: DebugMenuItem) => {
debugActionLoading.value = null
}
const queryAnswer = async () => {
const fid = debugFieldId.value.trim()
if (!fid) return
queryAnswerLoading.value = true
const resultId = ++resultIdCounter
const entry: DebugResult = {
id: resultId, timestamp: Date.now(),
label: `答案查询: ${fid}`,
endpoint: `GET ${backendUrl.value}/debug/answer?field_id=${fid}`,
method: 'GET', success: false, body: null, error: '',
}
try {
const url = `${backendUrl.value}/debug/answer?field_id=${encodeURIComponent(fid)}&experiment=${encodeURIComponent(currentExperiment.value)}`
const resp = await fetch(url)
const body = (await resp.json().catch(() => resp.text())) as unknown
entry.success = resp.ok
entry.body = body
} catch (e: any) {
entry.error = e.message || String(e)
}
debugResults.value.unshift(entry)
if (debugResults.value.length > 50) debugResults.value.length = 50
expandedResult.value = resultId
queryAnswerLoading.value = false
}
const undoLastReading = async () => {
const fid = debugFieldId.value.trim()
if (!fid) return
undoLoading.value = true
const resultId = ++resultIdCounter
const entry: DebugResult = {
id: resultId, timestamp: Date.now(),
label: `回退: ${fid}`,
endpoint: `POST ${backendUrl.value}/value/undo?field_id=${fid}`,
method: 'POST', success: false, body: null, error: '',
}
try {
const url = `${backendUrl.value}/value/undo?field_id=${encodeURIComponent(fid)}&experiment=${encodeURIComponent(currentExperiment.value)}`
const resp = await fetch(url, { method: 'POST' })
const body = (await resp.json().catch(() => resp.text())) as unknown
entry.success = resp.ok
entry.body = body
} catch (e: any) {
entry.error = e.message || String(e)
}
debugResults.value.unshift(entry)
if (debugResults.value.length > 50) debugResults.value.length = 50
expandedResult.value = resultId
undoLoading.value = false
}
const togglePanel = () => {
if (!isVisible.value) {
loadExperiences()
@ -211,6 +289,7 @@ onMounted(() => {
if (debugEnabled.value) {
loadExperiences()
loadDebugMenu()
loadGuardedFields()
}
})
@ -336,6 +415,39 @@ const navToExperience = (id: string) => {
</button>
</div>
<div class="debug-field" style="margin-top:0.5rem">
<label>fieldId 选择器</label>
<div class="debug-input-row">
<select
v-model="debugFieldId"
class="debug-input debug-select"
>
<option v-if="guardedFields.length === 0" value="">加载中...</option>
<option
v-for="gf in guardedFields"
:key="gf.field_id"
:value="gf.field_id"
>
{{ gf.field_id }} ({{ gf.source || 'manual' }} ±{{ gf.tolerance }})
</option>
</select>
<button
class="debug-btn debug-btn-sm"
:disabled="queryAnswerLoading || !debugFieldId"
@click="queryAnswer"
>
{{ queryAnswerLoading ? '...' : '查答案' }}
</button>
<button
class="debug-btn debug-btn-sm debug-btn-danger"
:disabled="undoLoading || !debugFieldId"
@click="undoLastReading"
>
{{ undoLoading ? '...' : '回退' }}
</button>
</div>
</div>
<div v-if="debugResults.length > 0" class="debug-results">
<div class="debug-logs-header">
<span>操作结果({{ debugResults.length }})</span>
@ -531,6 +643,11 @@ const navToExperience = (id: string) => {
border-color: #007bff;
}
.debug-select {
flex: 1;
cursor: pointer;
}
.debug-btn {
background: #007bff;
color: white;
@ -550,6 +667,14 @@ const navToExperience = (id: string) => {
cursor: not-allowed;
}
.debug-btn-danger {
background: #dc3545;
}
.debug-btn-danger:hover {
background: #c82333;
}
.debug-btn-sm {
padding: 0.35rem 0.6rem;
font-size: 0.8rem;

查看文件

@ -31,6 +31,12 @@ const fieldData = computed(() => experimentStore.data)
const areaResults = computed(() => experimentStore.areaResults)
const allFieldsValidated = computed(() => experimentStore.allFieldsValidated)
const dataVersion = computed(() => experimentStore.dataVersion)
const pendingField = computed(() => experimentStore.pendingField)
const controlStatus = computed(() => experimentStore.controlStatus)
const backendBaseUrl = computed(() => {
if (!props.validationUrl) return ''
return props.validationUrl.replace(/\/value\/?$/, '')
})
const configSummary = computed<ConfigSummary>(() => {
const fields: ConfigSummary['fields'] = []
@ -185,6 +191,9 @@ watch(allFieldsValidated, (newValue) => {
:area-results="areaResults"
:on-field-update="handleFieldUpdate"
:on-field-validate="handleFieldValidate"
:pending-field="pendingField"
:backend-base-url="backendBaseUrl"
:control-status="controlStatus"
:cell-inspect-mode="cellInspectMode"
:on-cell-inspect="(info: any) => emit('cell-inspect', info)"
/>

查看文件

@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, inject } from 'vue'
import { computed, inject, ref } from 'vue'
import type { GridSheet, GridCell, GridInputCell } from '@/types/experiment'
import ExperimentGridCell from './ExperimentGridCell.vue'
import { AIEvalContextKey } from '@/utils/aiEvalContext'
@ -7,10 +7,13 @@ import { renderTextWithLatex } from '@/utils/latex'
const props = defineProps<{
sheet: GridSheet
fieldData: Record<string, { value: any; validated: boolean; validationResult?: { accept: boolean; message: string } }>
fieldData: Record<string, { value: any; validated: boolean; validationResult?: { accept: boolean; message: string; severity?: string } }>
areaResults: Record<string, { value: any; formatted: string; error?: string }>
onFieldUpdate: (fieldId: string, value: any) => void
onFieldValidate: (fieldId: string) => void
pendingField?: string | null
backendBaseUrl?: string
controlStatus?: string | null
cellInspectMode?: boolean
onCellInspect?: (info: { sheetTitle?: string; cellType: string; label: string; value: any; unit?: string; validation?: any }) => void
}>()
@ -40,6 +43,31 @@ function getCellValidationResult(cell: GridCell) {
return props.fieldData[cell.fieldId]?.validationResult
}
function isCellPending(cell: GridCell): boolean {
if (!props.pendingField || !cell || cell.type !== 'input') return false
return (cell as GridInputCell).fieldId === props.pendingField
}
function isCellLocked(cell: GridCell): boolean {
if (!cell || cell.type !== 'input') return false
const inp = cell as GridInputCell
if (!inp.readingGuard?.enabled) return false
if (!props.pendingField) return inp.fieldId !== findFirstGuardedField()
return inp.fieldId !== props.pendingField
}
function findFirstGuardedField(): string {
if (!props.sheet.cells) return ''
for (const row of props.sheet.cells) {
for (const cell of row) {
if (cell && cell.type === 'input' && (cell as GridInputCell).readingGuard?.enabled) {
return (cell as GridInputCell).fieldId
}
}
}
return ''
}
function getCellAreaResult(cell: GridCell) {
if (!cell || cell.type !== 'computed') return undefined
return props.areaResults[cell.areaId]
@ -50,6 +78,8 @@ function onCellInput(fieldId: string, value: any) {
}
function onCellBlur(fieldId: string) {
const val = props.fieldData[fieldId]?.value
if (val === null || val === undefined || val === '') return
props.onFieldValidate(fieldId)
}
@ -87,6 +117,25 @@ function handleCellInspect(cell: GridCell) {
const isFirstRowHeader = computed(() => {
return props.sheet.columnHeaders && props.sheet.columnHeaders.length > 0
})
const controlBar = computed(() => props.sheet.controlBar?.items || [])
const displayStatus = computed(() => {
if (!props.controlStatus) return ''
if (localStorage.getItem('DEBUG') === 'true') return props.controlStatus
const s = props.controlStatus
if (s.startsWith('空闲')) return '就绪'
if (s.startsWith('上升中')) return '监控中'
if (s.startsWith('峰值已检测')) return '峰值就绪,请读数'
if (s.startsWith('冷却中')) return '监控中'
return props.controlStatus
})
function handleControlAction(item: { id: string; method?: string; endpoint?: string }) {
if (!item.endpoint || !props.backendBaseUrl) return
const url = props.backendBaseUrl + item.endpoint
fetch(url, { method: item.method || 'GET' }).catch(() => {})
}
</script>
<template>
@ -107,6 +156,24 @@ const isFirstRowHeader = computed(() => {
</th>
</tr>
</thead>
<thead v-if="controlBar.length > 0" class="grid-control-bar">
<tr>
<td :colspan="sheet.columns" class="control-bar-cell">
<div class="control-bar-row">
<template v-for="item in controlBar" :key="item.id">
<button
v-if="item.type === 'action'"
class="control-btn"
@click="handleControlAction(item)"
>
{{ item.label }}
</button>
</template>
<span v-if="controlStatus" class="control-status">{{ displayStatus }}</span>
</div>
</td>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in effectiveRows.rows" :key="ri" class="grid-row">
<td
@ -126,6 +193,8 @@ const isFirstRowHeader = computed(() => {
:validated="getCellValidated(cell)"
:validation-result="getCellValidationResult(cell)"
:area-result="getCellAreaResult(cell)"
:is-pending="isCellPending(cell)"
:is-locked="isCellLocked(cell)"
:inspect-mode="cellInspectMode"
@input="(val: any) => onCellInput((cell as GridInputCell).fieldId, val)"
@blur="() => onCellBlur((cell as GridInputCell).fieldId)"
@ -196,4 +265,42 @@ const isFirstRowHeader = computed(() => {
.grid-cell-wrapper:first-child {
min-width: 70px;
}
.grid-control-bar {
border: none;
}
.control-bar-cell {
padding: 6px 10px;
background: #f0f4f8;
border-bottom: 2px solid #d0d4da;
}
.control-bar-row {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.control-status {
font-size: 0.85rem;
color: #333;
font-weight: 600;
}
.control-btn {
background: #007bff;
color: white;
border: none;
border-radius: 6px;
padding: 0.35rem 0.6rem;
font-size: 0.8rem;
font-weight: 600;
cursor: pointer;
}
.control-btn:hover {
background: #0056b3;
}
</style>

查看文件

@ -9,9 +9,11 @@ const props = defineProps<{
cell: GridCell
value?: any
validated?: boolean
validationResult?: { accept: boolean; message: string }
validationResult?: { accept: boolean; message: string; severity?: string }
areaResult?: { value: any; formatted: string; error?: string }
inspectMode?: boolean
isPending?: boolean
isLocked?: boolean
}>()
const emit = defineEmits<{
@ -53,14 +55,15 @@ const bgColor = computed(() => {
if (isFocused.value) return '#e8f0fe'
if (props.validated && props.validationResult?.accept) {
return '#d4edda'
}
if (props.validated && props.validationResult && !props.validationResult.accept) {
if (props.validationResult && !props.validationResult.accept) {
return '#f8d7da'
}
if (props.value !== null && props.value !== undefined && props.value !== '') {
return '#fff3cd'
if (props.validated && props.validationResult?.accept) {
if (props.validationResult.severity === 'warning') return '#fff3cd'
return '#d4edda'
}
if (hasValue.value) {
return '#e8f0fe'
}
return '#ffffff'
})
@ -174,6 +177,8 @@ onBeforeUnmount(() => {
'cell-focused': isFocused,
'cell-inspect-mode': inspectMode,
'cell-inspect-hover': inspectMode && isHovering,
'cell-pending': isInput && isPending && !isFocused,
'cell-locked': isInput && isLocked,
}"
:style="{
backgroundColor: isLabel ? labelBgColor : isInput ? bgColor : isComputed ? (areaResult?.error ? '#f8d7da' : '#f0fff4') : 'transparent',
@ -191,6 +196,7 @@ onBeforeUnmount(() => {
class="cell-input-field"
:value="internalValue"
:placeholder="inputCell?.placeholder || ''"
:disabled="isLocked"
@input="handleInput"
@blur="handleBlur"
@focus="handleFocus"
@ -254,6 +260,23 @@ onBeforeUnmount(() => {
outline-offset: -1px;
}
.cell-pending {
outline: 3px solid #ff6b35;
outline-offset: -2px;
animation: pending-pulse 1.5s ease-in-out infinite;
box-shadow: 0 0 6px rgba(255, 107, 53, 0.35);
}
.cell-locked {
cursor: not-allowed;
pointer-events: none;
}
@keyframes pending-pulse {
0%, 100% { box-shadow: 0 0 4px rgba(255, 107, 53, 0.3); }
50% { box-shadow: 0 0 12px rgba(255, 107, 53, 0.6); }
}
.cell-inspect-mode {
cursor: pointer;
}

查看文件

@ -21,6 +21,8 @@ export const useExperimentStore = defineStore('experiment', () => {
const currentField: Ref<string | null> = ref(null)
const validationUrl: Ref<string | null> = ref(null)
const dataVersion = ref(0)
const pendingField: Ref<string | null> = ref(null)
const controlStatus: Ref<string | null> = ref(null)
const allFieldsValidated = computed(() => {
return Object.values(data.value).every((field) => field.validated)
@ -209,7 +211,14 @@ export const useExperimentStore = defineStore('experiment', () => {
const result: FieldValidationResponse = await response.json()
if (data.value[fieldId]) {
data.value[fieldId].validationResult = result
data.value[fieldId].validated = result.accept
data.value[fieldId].validated = true
data.value[fieldId].severity = result.severity
}
if (result.pending_field !== undefined) {
pendingField.value = result.pending_field
}
if (result.control_status !== undefined) {
controlStatus.value = result.control_status
}
dataVersion.value += 1
@ -227,7 +236,7 @@ export const useExperimentStore = defineStore('experiment', () => {
}
if (data.value[fieldId]) {
data.value[fieldId].validationResult = response
data.value[fieldId].validated = false
data.value[fieldId].validated = true
}
dataVersion.value += 1
return response
@ -331,6 +340,16 @@ export const useExperimentStore = defineStore('experiment', () => {
if (!response.ok) throw new Error(`加载配置失败: ${response.status}`)
const configData: ExperimentGridConfig = await response.json()
setConfig(configData, validationEndpoint)
if (validationEndpoint) {
try {
const resp = await fetch(validationEndpoint)
if (resp.ok) {
const vdata = await resp.json()
pendingField.value = vdata.pending_field || null
controlStatus.value = vdata.control_status || null
}
} catch { /* ignore */ }
}
} catch (err) {
error.value = err instanceof Error ? err.message : '加载配置失败'
console.error('加载实验配置失败:', err)
@ -347,6 +366,8 @@ export const useExperimentStore = defineStore('experiment', () => {
error,
currentField,
dataVersion,
pendingField,
controlStatus,
allFieldsValidated,
fieldValues,
allInputFields,

查看文件

@ -1,7 +1,8 @@
export interface ReadingGuardConfig {
enabled?: boolean
source?: 'device_peak' | 'device_frequency' | 'manual'
source?: 'device_peak' | 'device_frequency' | 'manual' | 'peak_ocr'
tolerance?: number
tolerance2?: number
}
export interface ValidationConfig {
@ -44,6 +45,18 @@ export interface GridComputedCell {
export type GridCell = GridLabelCell | GridInputCell | GridComputedCell | null
export interface ControlBarItem {
type: 'action'
id: string
label: string
method?: string
endpoint?: string
}
export interface ControlBar {
items: ControlBarItem[]
}
export interface GridSheet {
id: string
title?: string
@ -51,6 +64,7 @@ export interface GridSheet {
columnHeaders?: string[]
columnWidths?: string[]
rowHeaders?: string[]
controlBar?: ControlBar
cells: GridCell[][]
}
@ -63,12 +77,17 @@ export interface ExperimentGridConfig {
export interface FieldValidationResponse {
accept: boolean
message: string
pending_field?: string
severity?: string
reference?: number
control_status?: string
}
export interface ExperimentFieldData {
value: any
validated: boolean
validationResult?: FieldValidationResponse
severity?: string
lastUpdated?: Date
}