feat: 重做阅读找答案题与 AI 情境对话,并归拢本地识别、查词等既有改动

阅读"在对话里找到答案":
- 16 道题全部重写,干扰项真实出现在对话里,靠说话人归属或否定句才能作答
- 选项按题目内容确定性打乱,答案不再固定排第一;听力环节同样处理
- 去掉超纲干扰项、重复题干,收紧自由作答匹配(过去单个字母也能判对)

AI 情境对话:
- 提示词区分"AI 这一句要做什么"与"学习者随后要完成什么",并下发已教词句清单
- JSON 只强制 reply,translation/feedback 可选;不再索要用不上的 slots/evidence
- AI 不可用时页面明确提示当前回复来自内置示范脚本
- 删掉按 stage 下标猜中文翻译的兜底,避免译文与英文对不上
- 整课对话改用逐轮必需表达校验,替换"关键词沾边就算过";修正自由场景正则误伤
- 总结的"完成任务"按实际通过的轮次生成;模型点评只在结束页呈现一次
- 自由场景支持草稿续练(独立存储槽);修正回答轮数文案与永不解锁的场景标注

同时提交此前工作区中累积的改动:SenseVoice 本地识别、查词/句型解析卡、
复习与测评页调整等,并补充对话校验、选项分布和句子解析的测试。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-09-16 16:38:23 +09:00
co-authored by Claude Opus 5
parent 0c16394b5a
commit 61abc69037
24 changed files with 2896 additions and 665 deletions
@@ -1,3 +1,4 @@
// ignore_for_file: avoid_print, unnecessary_overrides
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:kouyu_english/core/ai_service.dart';
@@ -0,0 +1,97 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:kouyu_english/core/seed_courses.dart';
void main() {
group('对话任务校验', () {
test('每个对话都为每一轮声明了任务标签', () {
for (final entry in a0Dialogues.entries) {
final script = entry.value;
expect(
script.taskLabels.length,
script.prompts.length,
reason: '${entry.key} 的任务标签数量要和回合数一致',
);
expect(
script.requiredTerms.length,
script.prompts.length,
reason: '${entry.key} 的校验词组数量要和回合数一致',
);
for (final group in script.requiredTerms) {
expect(group, isNotEmpty);
}
}
for (final entry in a0SegmentDialogues.entries) {
expect(
entry.value.taskLabels.length,
entry.value.prompts.length,
reason: '${entry.key} 的任务标签数量要和回合数一致',
);
}
expect(a0MeetDialogue.taskLabels.length, a0MeetDialogue.prompts.length);
expect(a0MeetDialogue.requiredTerms.length, a0MeetDialogue.prompts.length);
});
test('示范答案能通过对应回合的校验', () {
for (final entry in {...a0Dialogues, 'scene': a0MeetDialogue}.entries) {
final script = entry.value;
for (var stage = 0; stage < script.hints.length; stage++) {
expect(
matchesDialogueStage(script, stage, script.hints[stage]),
isTrue,
reason: '${entry.key}${stage + 1} 轮的示范答案应当通过',
);
}
}
});
test('跑题回答不再因为关键词沾边而通过', () {
// 旧实现用 text.contains('it'),下面这些句子全部会被判为完成任务。
expect(matchesDialogueStage(a0Dialogues['a0-05']!, 0, 'I did it.'), isFalse);
expect(matchesDialogueStage(a0Dialogues['a0-08']!, 0, 'It is good.'), isFalse);
expect(matchesDialogueStage(a0Dialogues['a0-09']!, 2, 'I like tea.'), isFalse);
expect(matchesDialogueStage(a0MeetDialogue, 0, 'Hello.'), isFalse);
expect(matchesDialogueStage(a0MeetDialogue, 1, 'I am good.'), isFalse);
});
test('自由场景接受同样正确的其他说法', () {
// 旧正则只认 good/okay/tired,也不认 my name's。
expect(matchesDialogueStage(a0MeetDialogue, 0, "My name's Shen."), isTrue);
expect(matchesDialogueStage(a0MeetDialogue, 0, 'I am Shen.'), isTrue);
expect(matchesDialogueStage(a0MeetDialogue, 2, "I'm fine, thanks."), isTrue);
expect(matchesDialogueStage(a0MeetDialogue, 2, 'I am great!'), isTrue);
expect(matchesDialogueStage(a0MeetDialogue, 3, 'Where are you from?'), isTrue);
expect(matchesDialogueStage(a0MeetDialogue, 3, 'Do you like tea?'), isTrue);
});
test('只写半句不算完成任务', () {
expect(matchesDialogueStage(a0MeetDialogue, 0, "I'm"), isFalse);
expect(matchesDialogueStage(a0Dialogues['a0-04']!, 0, 'My number is'), isFalse);
expect(
matchesDialogueStage(a0Dialogues['a0-04']!, 0, 'My number is one-three-eight.'),
isTrue,
);
});
test('拼读和数字这类结构化要求可以识别', () {
expect(matchesDialogueStage(a0Dialogues['a0-02']!, 1, 'S-H-E-N'), isTrue);
expect(matchesDialogueStage(a0Dialogues['a0-02']!, 1, 'Shen'), isFalse);
expect(matchesDialogueStage(a0Dialogues['a0-08']!, 2, "It's three o'clock."), isTrue);
expect(matchesDialogueStage(a0Dialogues['a0-08']!, 2, "It's Monday."), isFalse);
});
test('任务标签可用于提示和总结', () {
expect(dialogueTaskLabel(a0MeetDialogue, 0), '介绍姓名');
expect(dialogueTaskLabel(a0MeetDialogue, 9), '完成本轮任务');
});
test('给 AI 的可用词表随课程递增且不越界', () {
final first = taughtLanguageUpTo('a0-01');
final later = taughtLanguageUpTo('a0-09');
expect(first, isNotEmpty);
expect(later.length, greaterThan(first.length));
expect(first.every(later.contains), isTrue);
expect(later.length, lessThanOrEqualTo(allTaughtLanguage.length));
expect(first.any((word) => word.toLowerCase().contains('coffee')), isFalse);
});
});
}
+150
View File
@@ -0,0 +1,150 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:kouyu_english/core/seed_courses.dart';
const _digitWords = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
'5': 'five',
'6': 'six',
'7': 'seven',
'8': 'eight',
'9': 'nine',
};
const _skipWords = {'a', 'an', 'the', 'my', 'is', 'it', 'im', 'to', 'you'};
String _normalize(String text) =>
text.toLowerCase().replaceAll(RegExp(r'[^a-z0-9一-龥]'), '');
/// 选项在对话里是否真的出现过。数字选项按英文读法展开(138 → onethreeeight),
/// 逐字母拼写(S-H-E-N)先去掉连字符。
bool _appearsInReading(String reading, String option) {
final haystack = _normalize(
reading.replaceAllMapped(
RegExp(r'\d'),
(match) => _digitWords[match[0]]!,
),
);
final tokens = option
.replaceAll('-', '')
.replaceAllMapped(RegExp(r'\d'), (match) => _digitWords[match[0]]!)
.toLowerCase()
.split(RegExp(r'[^a-z0-9一-龥]+'))
.where((token) => token.length > 1 && !_skipWords.contains(token));
return tokens.isNotEmpty && tokens.every(haystack.contains);
}
void main() {
final activities = <String, LessonActivity>{
...a0Activities,
...a0SegmentActivities,
};
group('阅读找答案题', () {
test('每题三个选项,第一项是标准答案', () {
for (final entry in activities.entries) {
final activity = entry.value;
expect(activity.answers, hasLength(3), reason: entry.key);
expect(activity.readingOptions, hasLength(3), reason: entry.key);
expect(
activity.readingOptions.first,
activity.readingAnswer,
reason: '${entry.key}readingOptions 第一项应是标准答案',
);
expect(
activity.readingOptions.toSet(),
hasLength(3),
reason: '${entry.key}:选项不能重复',
);
}
});
test('至少两个选项在对话中出现,必须读懂才能选', () {
for (final entry in activities.entries) {
final activity = entry.value;
final present = activity.readingOptions
.where((option) => _appearsInReading(activity.reading, option))
.toList();
expect(
_appearsInReading(activity.reading, activity.readingAnswer),
isTrue,
reason: '${entry.key}:答案必须能在对话里找到',
);
expect(
present.length,
greaterThanOrEqualTo(2),
reason:
'${entry.key}:只有 ${present.length} 个选项出现在对话中,'
'学习者不读对话也能挑出唯一出现过的那个',
);
}
});
test('选项之间不构成子串,避免判分时误判', () {
for (final entry in activities.entries) {
final options = entry.value.readingOptions.map(_normalize).toList();
for (var i = 0; i < options.length; i++) {
for (var j = i + 1; j < options.length; j++) {
expect(
options[i].contains(options[j]) ||
options[j].contains(options[i]),
isFalse,
reason: '${entry.key}:“${entry.value.readingOptions[i]}”与'
'${entry.value.readingOptions[j]}”互为子串,会被判分逻辑当成同一个答案',
);
}
}
}
});
test('打乱后的选项内容不变且顺序稳定', () {
for (final entry in activities.entries) {
final activity = entry.value;
final seed = '${activity.readingQuestion}-reading';
final first = shuffledOptions(activity.readingOptions, seed);
final second = shuffledOptions(activity.readingOptions, seed);
expect(first, second, reason: entry.key);
expect(
first.toSet(),
activity.readingOptions.toSet(),
reason: entry.key,
);
}
});
test('正确答案在三个位置上都出现,不集中在某一位', () {
final readingSlots = <int, int>{};
final listeningSlots = <int, int>{};
for (final activity in activities.values) {
final reading = shuffledOptions(
activity.readingOptions,
'${activity.readingQuestion}-reading',
);
final readingSlot = reading.indexOf(activity.readingAnswer);
readingSlots[readingSlot] = (readingSlots[readingSlot] ?? 0) + 1;
final listening = shuffledOptions(
activity.answers,
'${activity.listening}-listening',
);
final listeningSlot = listening.indexOf(activity.answers.first);
listeningSlots[listeningSlot] = (listeningSlots[listeningSlot] ?? 0) + 1;
}
for (final slots in [readingSlots, listeningSlots]) {
expect(slots.keys.toSet(), {0, 1, 2});
for (final count in slots.values) {
expect(count, lessThan(activities.length ~/ 2));
}
}
});
test('题干不重复,复习时不会撞题', () {
final questions = activities.values
.map((activity) => activity.readingQuestion)
.toList();
expect(questions.toSet(), hasLength(questions.length));
});
});
}
+5 -2
View File
@@ -1,3 +1,4 @@
// ignore_for_file: avoid_print, unnecessary_overrides
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:kouyu_english/core/ai_service.dart';
@@ -44,7 +45,8 @@ void main() {
}
});
test('Live test: /v1/responses dialogueReply', () async {
test('Live test: /v1/responses dialogueReply', timeout: const Timeout(Duration(seconds: 60)), () async {
try {
final reply = await AiService.instance.dialogueReply(
provider: AiProviderType.compatible,
@@ -53,7 +55,8 @@ void main() {
history: [
{'role': 'user', 'content': 'Hello, my name is Alex.'}
],
requiredTask: 'Greet learner and ask what is their name',
aiGoal: 'Greet the learner and ask their name',
learnerTask: 'say their own name',
);
print('Dialogue reply from /v1/responses: reply="${reply?.reply}", slots=${reply?.slots}, suggestsComplete=${reply?.suggestsComplete}');
} catch (e) {
@@ -0,0 +1,231 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:kouyu_english/core/ai_service.dart';
import 'package:kouyu_english/core/app_state.dart';
import 'package:kouyu_english/core/models.dart';
import 'package:kouyu_english/widgets/lexicon_lookup.dart';
void main() {
group('Sentence and Phrase Parsing Logic', () {
test('isSentenceQuery correctly detects sentences vs words', () {
expect(isSentenceQuery('apple'), isFalse);
expect(isSentenceQuery('check in'), isFalse);
expect(isSentenceQuery('Where is the subway?'), isTrue);
expect(isSentenceQuery("I'd like to check in."), isTrue);
expect(isSentenceQuery('This is a longer sentence with more than three words'), isTrue);
});
test('extractCourseLexiconPhrases finds embedded course lexicon items', () {
final matches = extractCourseLexiconPhrases("Hello, nice to meet you, where's the taxi?");
expect(matches, isNotEmpty);
final words = matches.map((m) => m.word.toLowerCase()).toList();
expect(words.any((w) => w.contains('nice to meet you')), isTrue);
});
});
group('Models Serialization', () {
test('PhraseBreakdownItem serialization round-trip', () {
const item = PhraseBreakdownItem(
phrase: 'check in',
meaning: '办理入住/值机',
ipa: '/tʃek ɪn/',
usageNote: '连读发音,酒店或机场常用',
);
final json = item.toJson();
final parsed = PhraseBreakdownItem.fromJson(json);
expect(parsed.phrase, 'check in');
expect(parsed.meaning, '办理入住/值机');
expect(parsed.ipa, '/tʃek ɪn/');
expect(parsed.usageNote, '连读发音,酒店或机场常用');
});
test('SentenceAnalysisResult serialization round-trip', () {
final result = SentenceAnalysisResult(
originalText: "I would like to check in, please.",
translation: '我想办理入住手续,谢谢。',
sentencePattern: "I would like to + 动词原形 (礼貌表达需求)",
grammarNote: 'would like 语气委婉客气,适合服务场景。',
pronunciationTips: 'would like 发音轻柔,check in 发生连读。',
phrases: const [
PhraseBreakdownItem(
phrase: 'would like to',
meaning: '想要做某事(委婉)',
),
PhraseBreakdownItem(
phrase: 'check in',
meaning: '办理入住',
ipa: '/tʃek ɪn/',
),
],
provider: 'mock',
model: 'test-model',
createdAt: DateTime.utc(2026, 9, 16, 10, 0, 0),
);
final json = result.toJson();
final parsed = SentenceAnalysisResult.fromJson(json);
expect(parsed.originalText, result.originalText);
expect(parsed.translation, result.translation);
expect(parsed.sentencePattern, result.sentencePattern);
expect(parsed.grammarNote, result.grammarNote);
expect(parsed.pronunciationTips, result.pronunciationTips);
expect(parsed.phrases.length, 2);
expect(parsed.phrases[0].phrase, 'would like to');
expect(parsed.phrases[1].ipa, '/tʃek ɪn/');
expect(parsed.provider, 'mock');
expect(parsed.model, 'test-model');
});
});
group('AiService Mock Sentence Analysis', () {
test('returns structured breakdown for would like', () async {
final analysis = await AiService.instance.analyzeSentence(
provider: AiProviderType.mock,
endpoint: '',
model: 'mock',
text: 'I would like a cup of tea.',
);
expect(analysis, isNotNull);
expect(analysis!.translation, contains('想要'));
expect(analysis.sentencePattern, contains('would like'));
expect(analysis.pronunciationTips, isNotNull);
expect(analysis.phrases, isNotEmpty);
expect(analysis.phrases.any((p) => p.phrase == 'would like'), isTrue);
});
test('returns structured breakdown for where is', () async {
final analysis = await AiService.instance.analyzeSentence(
provider: AiProviderType.mock,
endpoint: '',
model: 'mock',
text: 'Where is the gate?',
);
expect(analysis, isNotNull);
expect(analysis!.translation, contains('在哪里'));
expect(analysis.sentencePattern, contains('Where is'));
expect(analysis.phrases.any((p) => p.phrase == 'where is'), isTrue);
});
test('returns structured fallback for generic sentence', () async {
final analysis = await AiService.instance.analyzeSentence(
provider: AiProviderType.mock,
endpoint: '',
model: 'mock',
text: 'The weather is very sunny today.',
);
expect(analysis, isNotNull);
expect(analysis!.translation, isNotEmpty);
expect(analysis.sentencePattern, isNotEmpty);
expect(analysis.grammarNote, isNotEmpty);
});
});
group('AppState Sentence Analysis & Review Integration', () {
test('caching and retrieving sentence analyses with query normalization', () {
final state = AppState();
final result = SentenceAnalysisResult(
originalText: ' Where is the bus stop? ',
translation: '请问公交站在哪里?',
sentencePattern: 'Where is + 地点',
createdAt: DateTime.now(),
);
state.cacheSentenceAnalysis(result);
expect(state.sentenceAnalysisFor('where is the bus stop?'), isNotNull);
expect(state.sentenceAnalysisFor('WHERE IS THE BUS STOP? '), isNotNull);
expect(state.sentenceAnalysisFor('where is the bus stop?')?.translation, '请问公交站在哪里?');
state.removeSentenceAnalysis('where is the bus stop?');
expect(state.sentenceAnalysisFor('where is the bus stop?'), isNull);
});
test('addPhraseToReview converts phrase breakdown into vocabulary item in review queue', () {
final state = AppState();
state.addPhraseToReview(
phrase: 'check in',
meaning: '办理登机或入住',
ipa: '/tʃek ɪn/',
usageNote: '酒店机场高频词',
contextSentence: "I'd like to check in please.",
);
expect(state.reviewQueue.any((r) => r.target == 'check in'), isTrue);
final saved = state.reviewQueue.firstWhere((r) => r.target == 'check in');
expect(saved.hint, contains('办理登机或入住'));
expect(saved.hint, contains('酒店机场高频词'));
expect(saved.prompt, "I'd like to check in please.");
});
});
group('UI Lookup Sheet Sentence Analysis View', () {
testWidgets('renders sentence analysis result cards when cached', (tester) async {
final state = AppState();
final analysis = SentenceAnalysisResult(
originalText: 'Where is the departure gate?',
translation: '请问登机口在哪里?',
sentencePattern: 'Where is + 目的地',
grammarNote: 'where 引导的疑问句,注意语调。',
pronunciationTips: 'Where 与 is 自然连读。',
phrases: const [
PhraseBreakdownItem(
phrase: 'departure gate',
ipa: '/dɪˈpɑːrtʃər ɡeɪt/',
meaning: '登机口',
usageNote: '机场核心词汇',
),
],
provider: 'mock',
createdAt: DateTime.now(),
);
state.cacheSentenceAnalysis(analysis);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) => ElevatedButton(
onPressed: () => showLexiconLookup(
context,
state: state,
initialText: 'Where is the departure gate?',
),
child: const Text('查句'),
),
),
),
),
);
await tester.tap(find.text('查句'));
await tester.pumpAndSettle();
expect(find.text('查词与整句深度解析'), findsOneWidget);
expect(find.text('中文整句翻译'), findsOneWidget);
expect(find.text('请问登机口在哪里?'), findsOneWidget);
expect(find.text('核心句型'), findsOneWidget);
expect(find.text('Where is + 目的地'), findsOneWidget);
expect(find.text('口语连读与发音'), findsOneWidget);
expect(find.text('重点短语与搭配 (1)'), findsOneWidget);
expect(find.text('departure gate'), findsOneWidget);
expect(find.text('登机口'), findsOneWidget);
expect(find.text('加复习'), findsOneWidget);
// Scroll to '加复习' and tap
await tester.ensureVisible(find.text('加复习'));
await tester.pumpAndSettle();
await tester.tap(find.text('加复习'));
await tester.pumpAndSettle();
expect(state.reviewQueue.any((r) => r.target == 'departure gate'), isTrue);
expect(find.text('已在复习'), findsOneWidget);
});
});
}
+33 -5
View File
@@ -1,20 +1,32 @@
// ignore_for_file: avoid_print
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:kouyu_english/core/sherpa_stt_service.dart';
import 'package:sherpa_onnx/sherpa_onnx.dart' as sherpa_onnx;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final home = Platform.environment['HOME'] ?? '';
final pubCache = Platform.environment['PUB_CACHE'] ?? '$home/.pub-cache';
final candidateDirs = [
'$pubCache/hosted/pub.dev/sherpa_onnx_macos-1.13.8/macos',
'$home/.pub-cache/hosted/pub.dev/sherpa_onnx_macos-1.13.8/macos',
'/Users/shenlei/.pub-cache/hosted/pub.dev/sherpa_onnx_macos-1.13.8/macos',
];
final macosDir = candidateDirs.firstWhere(
(d) => Directory(d).existsSync(),
orElse: () => candidateDirs.first,
);
test('SenseVoice-Small ONNX transcribes WAV audio file accurately', () async {
const macosDir = '/Users/shen/.pub-cache/hosted/pub.dev/sherpa_onnx_macos-1.13.8/macos';
// Test direct Sherpa ASR initialization and decoding with SenseVoice
sherpa_onnx.initBindings(macosDir);
final modelConfig = sherpa_onnx.OfflineModelConfig(
senseVoice: const sherpa_onnx.OfflineSenseVoiceModelConfig(
model: 'assets/models/sense_voice/model.int8.onnx',
language: 'auto',
language: 'en',
useInverseTextNormalization: true,
),
tokens: 'assets/models/sense_voice/tokens.txt',
@@ -38,10 +50,26 @@ void main() {
stream.acceptWaveform(samples: wave.samples, sampleRate: wave.sampleRate);
recognizer.decode(stream);
final result = recognizer.getResult(stream);
print("SenseVoice transcribed result: ${result.text}");
expect(result.text.toLowerCase().contains("nightfall"), isTrue);
print('SenseVoice transcribed result: ${result.text}');
expect(result.text.toLowerCase().contains('nightfall'), isTrue);
stream.free();
}
recognizer.free();
});
test('SherpaSttService singleton initializes and transcribes cleanly', () async {
final ready = await SherpaSttService.instance.initialize(nativeLibDir: macosDir);
expect(ready, isTrue);
expect(SherpaSttService.instance.isReady, isTrue);
const testWave = '/tmp/sherpa_test/sherpa-onnx-zipformer-small-en-2023-06-26/test_wavs/0.wav';
if (File(testWave).existsSync()) {
final transcribed = await SherpaSttService.instance.transcribeWav(testWave);
expect(transcribed, isNotNull);
print('SherpaSttService transcribed: $transcribed');
expect(transcribed!.toLowerCase().contains('nightfall'), isTrue);
// SenseVoice tags should be stripped
expect(transcribed.contains('<|'), isFalse);
}
});
}