A cross platform Audiobookshelf client for Android and iOS
Dart
Use the ebook's exact words for a transcribed bookmark when they can be matched
Barnabas3d1fe9c6e12f
diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex 9b4ada13..4f6ddc48 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -218,6 +218,17 @@ class PlayerSettings {await prefs.setInt('transcriptionWindowSeconds', value);}+ /// Replace a bookmark transcript with the ebook's exact text when a+ /// confident match is found (only offered when the book has an EPUB).+ static Future<bool> getTranscriptionUseEbookText() async {+ final prefs = await SharedPreferences.getInstance();+ return prefs.getBool('transcriptionUseEbookText') ?? true;+ }+ static Future<void> setTranscriptionUseEbookText(bool value) async {+ final prefs = await SharedPreferences.getInstance();+ await prefs.setBool('transcriptionUseEbookText', value);+ }+/// Where Find in audiobook lands on success: true = switch to the player,/// false = stay in the reader while the audio plays.static Future<bool> getFindInAudiobookGoToPlayer() async {diff --git a/lib/utils/passage_match.dart b/lib/utils/passage_match.dartnew file mode 100644index 00000000..1a1ad487--- /dev/null+++ b/lib/utils/passage_match.dart@@ -0,0 +1,223 @@+import 'dart:convert';+import 'dart:io';++import 'package:archive/archive.dart';+import 'package:flutter/foundation.dart';++/// Pure-Dart port of the reader's fuzzy passage matcher (ebook_reader_view's+/// in-WebView JS), for places with no epub.js available - correcting a+/// bookmark transcript against the ebook's real text. Same scoring, same+/// device-tuned thresholds: token bag-of-words narrows candidate windows,+/// character-level Levenshtein on the normalized window ranks them, and a+/// clear winner is required before anything is trusted.++// Accept a match at this similarity, with this margin over the runner-up+// (unless both point at the same spot). Slightly stricter than the reader's+// jump gate: a wrong jump is undoable, a wrong note replacement is silent.+const double _acceptFine = 0.68;+const double _margin = 0.05;++final RegExp _tokenRe = RegExp(r"[\p{L}\p{N}']+", unicode: true);++/// Locate [args.transcript] in the EPUB at [args.epubPath] and return the+/// book's own text for that passage, snapped to sentence boundaries - or null+/// when no confident match exists. Runs standalone so it can go through+/// compute(); a whole-book scan takes well under a second in an isolate.+String? correctFromEpub(({String epubPath, String transcript}) args) {+ // Whisper sometimes emits bracketed non-speech tags; they'd poison matching.+ final query = args.transcript+ .replaceAll(RegExp(r'\[[^\]]*\]|\([^)]*\)'), ' ')+ .replaceAll(RegExp(r'\s+'), ' ')+ .trim();+ final qTokens =+ _tokenRe.allMatches(query.toLowerCase()).map((m) => m.group(0)!).toList();+ if (qTokens.length < 3) return null;++ final List<String> sections;+ try {+ sections = _epubSectionTexts(args.epubPath);+ } catch (e) {+ debugPrint('[PassageMatch] epub read failed: $e');+ return null;+ }+ if (sections.isEmpty) return null;++ final need = <String, int>{};+ for (final t in qTokens) {+ need[t] = (need[t] ?? 0) + 1;+ }+ final qNorm = qTokens.join(' ');+ final w = qTokens.length;++ _Candidate? best;+ _Candidate? second;+ void offer(_Candidate c) {+ if (best == null || c.fine > best!.fine) {+ second = best;+ best = c;+ } else if (second == null || c.fine > second!.fine) {+ second = c;+ }+ }++ for (var si = 0; si < sections.length; si++) {+ final text = sections[si];+ final toks = _tokenRe+ .allMatches(text.toLowerCase())+ .map((m) => (t: m.group(0)!, s: m.start, e: m.end))+ .toList();+ if (toks.length < 3) continue;++ // Rolling multiset intersection over a query-sized token window.+ final have = <String, int>{};+ var matched = 0;+ final cands = <({int i, int m})>[];+ for (var p = 0; p < toks.length; p++) {+ final tk = toks[p].t;+ have[tk] = (have[tk] ?? 0) + 1;+ if (have[tk]! <= (need[tk] ?? 0)) matched++;+ if (p >= w) {+ final old = toks[p - w].t;+ if (have[old]! <= (need[old] ?? 0)) matched--;+ have[old] = have[old]! - 1;+ }+ if (matched >= (w * 0.4).floor().clamp(2, w)) {+ cands.add((i: (p - w + 1).clamp(0, toks.length - 1), m: matched));+ }+ }+ cands.sort((a, b) => b.m.compareTo(a.m));+ final used = <int>[];+ for (final c in cands) {+ if (used.length >= 4) break;+ if (used.any((u) => (u - c.i).abs() < w)) continue;+ used.add(c.i);+ final s1 = c.i;+ final e1 = (s1 + w - 1).clamp(0, toks.length - 1);+ final winNorm =+ toks.sublist(s1, e1 + 1).map((x) => x.t).join(' ');+ final dl = _levenshtein(qNorm, winNorm);+ final fine = 1 -+ dl / (qNorm.length > winNorm.length ? qNorm.length : winNorm.length);+ offer(_Candidate(si, toks[s1].s, toks[e1].e, fine));+ }+ }++ final b = best;+ if (b == null) return null;+ final s = second;+ final sameSpot =+ s != null && s.section == b.section && (s.start - b.start).abs() < 200;+ final confident = b.fine >= _acceptFine &&+ (s == null || sameSpot || b.fine - s.fine >= _margin);+ debugPrint('[PassageMatch] best fine=${b.fine.toStringAsFixed(3)} '+ 'second=${s?.fine.toStringAsFixed(3)} sameSpot=$sameSpot '+ 'confident=$confident');+ if (!confident) return null;+ return _snapToSentences(sections[b.section], b.start, b.end);+}++class _Candidate {+ final int section;+ final int start;+ final int end;+ final double fine;+ const _Candidate(this.section, this.start, this.end, this.fine);+}++/// Text content of every content document in the EPUB. Spine order doesn't+/// matter for matching, so this just takes the (x)html entries as stored.+List<String> _epubSectionTexts(String epubPath) {+ final archive = ZipDecoder().decodeBytes(File(epubPath).readAsBytesSync());+ final out = <String>[];+ for (final f in archive.files) {+ if (!f.isFile) continue;+ final name = f.name.toLowerCase();+ if (!name.endsWith('.xhtml') && !name.endsWith('.html') && !name.endsWith('.htm')) {+ continue;+ }+ final raw = utf8.decode(f.content as List<int>, allowMalformed: true);+ final text = _stripHtml(raw);+ if (text.length > 200) out.add(text);+ }+ return out;+}++String _stripHtml(String html) {+ var s = html+ .replaceAll(RegExp(r'<head[\s\S]*?</head>', caseSensitive: false), ' ')+ .replaceAll(RegExp(r'<(script|style)[\s\S]*?</\1>', caseSensitive: false), ' ')+ .replaceAll(RegExp(r'</(p|div|h[1-6]|li|blockquote)>', caseSensitive: false), '\n')+ .replaceAll(RegExp(r'<br\s*/?>', caseSensitive: false), '\n')+ .replaceAll(RegExp(r'<[^>]+>'), ' ');+ s = s+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"')+ .replaceAll(''', "'")+ .replaceAll(''', "'")+ .replaceAll(' ', ' ')+ .replaceAllMapped(RegExp(r'&#(\d+);'),+ (m) => String.fromCharCode(int.parse(m.group(1)!)))+ .replaceAllMapped(RegExp(r'&#x([0-9a-fA-F]+);'),+ (m) => String.fromCharCode(int.parse(m.group(1)!, radix: 16)));+ // Collapse runs of spaces but keep the newlines - they mark paragraph+ // boundaries for sentence snapping.+ return s.replaceAll(RegExp(r'[ \t]+'), ' ').replaceAll(RegExp(r'\n\s*'), '\n').trim();+}++int _levenshtein(String a, String b) {+ if (a.isEmpty) return b.length;+ if (b.isEmpty) return a.length;+ var prev = List<int>.generate(b.length + 1, (j) => j);+ var cur = List<int>.filled(b.length + 1, 0);+ for (var i = 1; i <= a.length; i++) {+ cur[0] = i;+ final ca = a.codeUnitAt(i - 1);+ for (var j = 1; j <= b.length; j++) {+ final cost = ca == b.codeUnitAt(j - 1) ? 0 : 1;+ cur[j] = [prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost]+ .reduce((x, y) => x < y ? x : y);+ }+ final tmp = prev;+ prev = cur;+ cur = tmp;+ }+ return prev[b.length];+}++/// Grow a matched span outward to clean sentence boundaries so the note reads+/// like the book, not like a window that starts and ends mid-sentence.+String _snapToSentences(String text, int start, int end) {+ var s = start;+ var e = end;+ final minS = (start - 220).clamp(0, text.length);+ for (var i = start - 1; i >= minS; i--) {+ final c = text[i];+ if (c == '\n') {+ s = i + 1;+ break;+ }+ if (c == '.' || c == '!' || c == '?') {+ s = i + 1;+ break;+ }+ }+ final maxE = (end + 260).clamp(0, text.length);+ for (var i = end; i < maxE; i++) {+ final c = text[i];+ if (c == '.' || c == '!' || c == '?') {+ var j = i + 1;+ while (j < text.length && const ['"', "'", '”', '’'].contains(text[j])) {+ j++;+ }+ e = j;+ break;+ }+ if (c == '\n') {+ e = i;+ break;+ }+ }+ return text.substring(s, e).trim().replaceAll(RegExp(r'\s+'), ' ');+}diff --git a/lib/widgets/bookmark_detail_dialog.dart b/lib/widgets/bookmark_detail_dialog.dartindex e90c0b3a..789d9cae 100644--- a/lib/widgets/bookmark_detail_dialog.dart+++ b/lib/widgets/bookmark_detail_dialog.dart@@ -1,6 +1,7 @@import 'dart:convert';import 'dart:io';+import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';import 'package:provider/provider.dart';@@ -12,7 +13,9 @@ import '../services/bookmark_service.dart';import '../services/bookmark_preview_player.dart';import '../services/chapter_lookup.dart';import '../services/download_service.dart';+import '../services/ebook_cache.dart';import '../services/transcription_service.dart';+import '../utils/passage_match.dart';import 'clip_editor_sheet.dart';import 'overlay_toast.dart';import 'progress_dialog.dart';@@ -50,6 +53,8 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {late final BookmarkPreviewPlayer _preview;bool _saving = false;bool _transcriptionOn = false;+ // Non-null when the book has an EPUB to cross-reference transcripts against.+ Map<String, dynamic>? _epubForCrossRef;// Display-only speed division (speed-adjusted-time setting). _seconds stays// raw book time throughout - preview, clip export, jump and save all use it.double _displaySpeed = 1.0;@@ -74,6 +79,22 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {PlayerSettings.getTranscriptionEnabled().then((on) {if (mounted && on) setState(() => _transcriptionOn = true);});+ _resolveEpubForCrossRef();+ }++ /// Whether this book has an EPUB the transcript can be corrected against -+ /// the cached copy first, then the item's metadata (fetched lazily at+ /// transcribe time when it isn't cached yet).+ Future<void> _resolveEpubForCrossRef() async {+ var ef = await cachedEbookFileFor(widget.itemId);+ if (ef == null && widget.api != null) {+ try {+ final item = await widget.api!.getLibraryItem(widget.itemId);+ ef = resolveEbookFile(item);+ } catch (_) {}+ }+ if (ef == null || ebookExtFromFile(ef) != '.epub') return;+ if (mounted) setState(() => _epubForCrossRef = ef);}Future<void> _loadDisplaySpeed() async {@@ -203,6 +224,26 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {);}+ /// The book's own words for [transcript], when the EPUB can be fetched and+ /// the passage confidently matched. Null keeps the raw transcript - a+ /// failed fetch or an unconfident match must never block the transcription.+ Future<String?> _ebookExactText(String transcript) async {+ final ebookFile = _epubForCrossRef;+ if (ebookFile == null) return null;+ try {+ var f = await ebookCacheFileFor(widget.itemId, ebookFile);+ if (!f.existsSync() || await f.length() <= 0) {+ final api = widget.api;+ if (api == null) return null;+ f = await fetchEbookToCache(api, widget.itemId, ebookFile, '');+ }+ return await compute(correctFromEpub, (epubPath: f.path, transcript: transcript));+ } catch (e) {+ debugPrint('[Transcribe] ebook cross-reference failed: $e');+ return null;+ }+ }+String _mapTranscriptionError(AppLocalizations l, TranscriptionError kind) {switch (kind) {case TranscriptionError.disabled:@@ -238,8 +279,9 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {// Set expectations before burning CPU (it takes a while, the text needs a// once-over, the result lands in the note) and let the user pick how much- // audio to transcribe. The choice is remembered for next time.+ // audio to transcribe. The choices are remembered for next time.var window = await PlayerSettings.getTranscriptionWindowSeconds();+ var useEbookText = await PlayerSettings.getTranscriptionUseEbookText();if (!mounted) return;final go = await showDialog<bool>(context: context,@@ -265,6 +307,21 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {onSelectionChanged: (sel) =>setDialogState(() => window = sel.first),),+ if (_epubForCrossRef != null)+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Row(children: [+ Expanded(+ child: Text(l.transcriptionUseEbookText,+ style: Theme.of(ctx).textTheme.bodySmall),+ ),+ Switch(+ value: useEbookText,+ onChanged: (v) =>+ setDialogState(() => useEbookText = v),+ ),+ ]),+ ),],),actions: [@@ -282,17 +339,32 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {);if (go != true || !mounted) return;await PlayerSettings.setTranscriptionWindowSeconds(window);+ await PlayerSettings.setTranscriptionUseEbookText(useEbookText);+ if (!mounted) return;showProgressDialog(context, l.transcribing);- ({String text, String audioPath})? result;+ String? text;String? error;try {- result = await TranscriptionService.instance.transcribeAt(+ final result = await TranscriptionService.instance.transcribeAt(itemId: widget.itemId,positionSeconds: _seconds,windowSeconds: window.toDouble(),);+ // No review playback anymore, so the extracted clip is done with.+ try {+ final f = File(result.audioPath);+ if (f.existsSync()) await f.delete();+ } catch (_) {}+ text = result.text.trim();+ // Cross-reference the ebook: a confident match swaps Whisper's+ // approximation for the book's actual words. Still under the progress+ // dialog - fetching an uncached epub plus matching can take a moment.+ if (useEbookText && text.isNotEmpty) {+ final exact = await _ebookExactText(text);+ if (exact != null && exact.isNotEmpty) text = exact;+ }} on TranscriptionException catch (e) {error = _mapTranscriptionError(l, e.kind);} catch (_) {@@ -307,15 +379,9 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {return;}- // No review playback anymore, so the extracted clip is done with.- try {- final f = File(result!.audioPath);- if (f.existsSync()) await f.delete();- } catch (_) {}-// Save straight into the note - a Share-then-back must never lose the// text. Fixing mistakes and sharing both happen right here in the sheet.- final trimmed = result!.text.trim();+ final trimmed = (text ?? '').trim();if (trimmed.isEmpty) return;setState(() {_noteC.text =diff --git a/pubspec.lock b/pubspec.lockindex f9f5dedd..0c166e95 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -58,7 +58,7 @@ packages:source: hostedversion: "1.0.4"archive:- dependency: transitive+ dependency: "direct main"description:name: archivesha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ffdiff --git a/pubspec.yaml b/pubspec.yamlindex 8d2d3ee7..0d4acfee 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -37,6 +37,9 @@ dependencies:# we feed it 16kHz mono WAV produced by native decoders (MediaCodec / AVAssetReader).whisper_ggml_plus: ^1.5.2+ # Reading EPUB text without a WebView (transcript ebook cross-reference).+ archive: ^4.0.9+# CarPlay - vendored copy of 1.2.11 with a patched image loader (downsampled +# cached list thumbnails) so large browse lists don't run CarPlay out of memory.flutter_carplay: