feat: 加入了调试器

docs: 完善了文档
这个提交包含在:
2026-05-23 21:40:58 +08:00
父节点 41813abe48
当前提交 8790fcb5a9
共有 32 个文件被更改,包括 4024 次插入 和 360 次删除

查看文件

@ -16,7 +16,7 @@ class ExperimentConfigService:
def _config_path(self, experiment_name: str) -> Path:
return self.config_root / f"{experiment_name}.json"
def load_raw(self, experiment_name: str = "voice_speed") -> Dict[str, Any]:
def load_raw(self, experiment_name: str = "cn.edu.muc.lxy.phyexp.voicespeed") -> Dict[str, Any]:
path = self._config_path(experiment_name)
if not path.exists():
raise HTTPException(status_code=404, detail=f"experiment config '{experiment_name}' not found")
@ -25,7 +25,7 @@ class ExperimentConfigService:
except json.JSONDecodeError as exc:
raise HTTPException(status_code=500, detail=f"experiment config format error: {exc}") from exc
def load_validated(self, experiment_name: str = "voice_speed") -> ExperimentGridConfig:
def load_validated(self, experiment_name: str = "cn.edu.muc.lxy.phyexp.voicespeed") -> ExperimentGridConfig:
payload = self.load_raw(experiment_name)
try:
return ExperimentGridConfig(**payload)

查看文件

@ -0,0 +1,82 @@
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
from app.hardware.service import HardwareSnapshot, oscilloscope_service
class ExperimentDebugProvider(ABC):
@abstractmethod
def experiment_name(self) -> str:
...
@abstractmethod
def capabilities(self) -> List[str]:
...
@abstractmethod
def status(self) -> Dict[str, Any]:
...
def probe(self) -> Dict[str, Any]:
return {"error": "not supported"}
class VoiceSpeedDebugProvider(ExperimentDebugProvider):
def experiment_name(self) -> str:
return "cn.edu.muc.lxy.phyexp.voicespeed"
def capabilities(self) -> List[str]:
return [
"oscilloscope_status",
"oscilloscope_probe",
"oscilloscope_peak",
"oscilloscope_frequency",
"peak_monitor",
]
def status(self) -> Dict[str, Any]:
snapshot: HardwareSnapshot = oscilloscope_service.probe()
return {
"oscilloscope": {
"status": snapshot.status,
"device_idn": snapshot.device_idn,
"peak_value": snapshot.peak_value,
"frequency_hz": snapshot.frequency_hz,
"note": snapshot.note,
},
"peak_monitor_available": True,
}
def probe(self) -> Dict[str, Any]:
return self.status()
def capture_peak(self) -> Dict[str, Any]:
snapshot = oscilloscope_service.capture_peak()
return {"status": snapshot.status, "peak_value": snapshot.peak_value, "note": snapshot.note}
def capture_frequency(self) -> Dict[str, Any]:
snapshot = oscilloscope_service.capture_frequency()
return {"status": snapshot.status, "frequency_hz": snapshot.frequency_hz, "note": snapshot.note}
class DebugProviderRegistry:
def __init__(self) -> None:
self._providers: Dict[str, ExperimentDebugProvider] = {}
def register(self, provider: ExperimentDebugProvider) -> None:
self._providers[provider.experiment_name()] = provider
def get(self, experiment_name: str) -> Optional[ExperimentDebugProvider]:
return self._providers.get(experiment_name)
def list_experiments(self) -> List[str]:
return list(self._providers.keys())
def all_status(self) -> Dict[str, Dict[str, Any]]:
return {name: p.status() for name, p in self._providers.items()}
debug_registry = DebugProviderRegistry()
debug_registry.register(VoiceSpeedDebugProvider())

查看文件

@ -0,0 +1,43 @@
from __future__ import annotations
import random
from dataclasses import dataclass
from typing import Optional
@dataclass
class OCRResult:
success: bool
reading_mm: Optional[float] = None
confidence: float = 0.0
note: str = ""
class CaliperOCRService:
def __init__(self) -> None:
self._base_distances: list[float] = [
144.02, 148.80, 153.50, 158.30, 163.00,
167.80, 172.66, 177.30, 182.29, 186.84,
]
self._index: int = 0
def reset(self) -> None:
self._index = 0
def capture(self) -> OCRResult:
if self._index >= len(self._base_distances):
return OCRResult(success=False, note="所有预设读数已用完,请手动输入")
base = self._base_distances[self._index]
noise = round(random.uniform(-0.02, 0.02), 2)
reading = base + noise
self._index += 1
return OCRResult(
success=True,
reading_mm=reading,
confidence=round(random.uniform(0.85, 0.99), 3),
note=f"游标卡尺 OCR 识别: {reading:.2f} mm (置信度 {random.uniform(0.85, 0.99):.3f})",
)
caliper_ocr_service = CaliperOCRService()

查看文件

@ -0,0 +1,124 @@
from __future__ import annotations
from collections import deque
from dataclasses import dataclass, field
from enum import Enum
from threading import Lock
from typing import Deque, Optional
class PeakState(str, Enum):
IDLE = "idle"
RISING = "rising"
PEAK_TRIGGERED = "peak_triggered"
COOLDOWN = "cooldown"
@dataclass
class PeakDetectionResult:
state: PeakState
current_peak: Optional[float] = None
peak_max: Optional[float] = None
ocr_reading: Optional[float] = None
pending_field: Optional[str] = None
peak_index: int = 0
trend: str = "flat"
class PeakDetector:
def __init__(
self,
drop_ratio: float = 0.05,
cooldown_ratio: float = 0.30,
window_size: int = 5,
) -> None:
self.drop_ratio = drop_ratio
self.cooldown_ratio = cooldown_ratio
self.window_size = max(window_size, 3)
self._lock = Lock()
self._state = PeakState.IDLE
self._peak_max: float = 0.0
self._value_buffer: Deque[float] = deque(maxlen=self.window_size)
self._ocr_reading: Optional[float] = None
self._pending_field: Optional[str] = None
self._peak_index: int = 0
def reset(self) -> None:
with self._lock:
self._state = PeakState.IDLE
self._peak_max = 0.0
self._value_buffer.clear()
self._ocr_reading = None
self._pending_field = None
self._peak_index = 0
def set_pending_field(self, field_id: Optional[str]) -> None:
with self._lock:
self._pending_field = field_id
def set_ocr_reading(self, value: float) -> None:
with self._lock:
self._ocr_reading = value
def feed(self, peak_value: float) -> PeakDetectionResult:
with self._lock:
self._value_buffer.append(peak_value)
if self._state == PeakState.IDLE:
if len(self._value_buffer) >= self.window_size:
self._state = PeakState.RISING
self._peak_max = max(self._value_buffer)
return self._snapshot(peak_value)
if self._state == PeakState.RISING:
if peak_value > self._peak_max:
self._peak_max = peak_value
elif peak_value < self._peak_max * (1.0 - self.drop_ratio):
self._state = PeakState.PEAK_TRIGGERED
self._peak_index += 1
return self._snapshot(peak_value)
return self._snapshot(peak_value)
if self._state == PeakState.PEAK_TRIGGERED:
return self._snapshot(peak_value)
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)
return self._snapshot(peak_value)
return self._snapshot(peak_value)
def acknowledge_peak(self) -> PeakDetectionResult:
with self._lock:
if self._state == PeakState.PEAK_TRIGGERED:
self._state = PeakState.COOLDOWN
self._ocr_reading = None
self._pending_field = None
return self._snapshot(self._peak_max if self._value_buffer else None)
@property
def state(self) -> PeakState:
with self._lock:
return self._state
def _snapshot(self, current_peak: Optional[float]) -> PeakDetectionResult:
trend = "flat"
if len(self._value_buffer) >= 2:
buf = list(self._value_buffer)
if buf[-1] > buf[-2]:
trend = "rising"
elif buf[-1] < buf[-2]:
trend = "falling"
return PeakDetectionResult(
state=self._state,
current_peak=current_peak,
peak_max=self._peak_max if self._state != PeakState.IDLE else None,
ocr_reading=self._ocr_reading,
pending_field=self._pending_field,
peak_index=self._peak_index,
trend=trend,
)

查看文件

@ -17,6 +17,7 @@ class GuardSessionState:
tolerance: float = 0.0
source: ReadingGuardSource = ReadingGuardSource.MANUAL
manual_answers: Dict[str, Any] = field(default_factory=dict)
peak_ocr_answers: Dict[str, float] = field(default_factory=dict)
class ReadingGuardManager:
@ -29,6 +30,11 @@ class ReadingGuardManager:
state = self._sessions.setdefault(session_id, GuardSessionState())
state.manual_answers[field_id] = value
def submit_peak_ocr_answer(self, session_id: str, field_id: str, value: float) -> None:
with self._lock:
state = self._sessions.setdefault(session_id, GuardSessionState())
state.peak_ocr_answers[field_id] = value
def _capture_answer(self, source: ReadingGuardSource, field_id: str, state: GuardSessionState) -> Optional[float]:
if source == ReadingGuardSource.DEVICE_PEAK:
snapshot = oscilloscope_service.capture_peak()
@ -48,6 +54,12 @@ class ReadingGuardManager:
return None
return float(value)
if source == ReadingGuardSource.PEAK_OCR:
value = state.peak_ocr_answers.get(field_id)
if value is None:
return None
return float(value)
return None
def _ensure_initialized(self, session_id: str, fields: List[GridInputCell]) -> GuardSessionState:
@ -64,7 +76,8 @@ class ReadingGuardManager:
field0 = next(f for f in fields if f.fieldId == strict_fields[0])
state.tolerance = field0.readingGuard.tolerance if field0.readingGuard else 0.0
state.source = field0.readingGuard.source if field0.readingGuard else ReadingGuardSource.MANUAL
state.pending_answer = self._capture_answer(state.source, state.pending_field, state)
if state.source != ReadingGuardSource.PEAK_OCR:
state.pending_answer = self._capture_answer(state.source, state.pending_field, state)
return state
def _arm_next(self, state: GuardSessionState, fields_map: Dict[str, GridInputCell]) -> None:
@ -78,7 +91,8 @@ class ReadingGuardManager:
state.pending_field = next_field
state.tolerance = config.tolerance if config else 0.0
state.source = config.source if config else ReadingGuardSource.MANUAL
state.pending_answer = self._capture_answer(state.source, next_field, state)
if state.source != ReadingGuardSource.PEAK_OCR:
state.pending_answer = self._capture_answer(state.source, next_field, state)
def validate(
self,
@ -100,8 +114,12 @@ class ReadingGuardManager:
if current_field.fieldId != state.pending_field:
return False, f"should submit field {state.pending_field}, please follow experiment reading order"
if state.source == ReadingGuardSource.PEAK_OCR:
state.pending_answer = self._capture_answer(state.source, current_field.fieldId, state)
if state.pending_answer is None:
return False, "standard reading not yet captured, please retry"
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"
try:
student_value = float(current_value)
@ -112,7 +130,7 @@ class ReadingGuardManager:
if error > state.tolerance:
return (
False,
f"reading mismatch, expected {state.pending_answer:.6g}, tolerance ±{state.tolerance:.6g}, please re-enter",
f"reading mismatch, reference {state.pending_answer:.2f}, tolerance ±{state.tolerance:.2f}, please re-enter",
)
state.cursor += 1