Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions lib/search/utils/scope_tree.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:otzaria/data/book_identity.dart';
import 'package:otzaria/library/models/library.dart';
import 'package:otzaria/models/books.dart';
import 'package:otzaria/search/utils/facet_helper.dart';
Expand Down Expand Up @@ -144,9 +145,15 @@ class ScopeTree {
'withoutUserBooksScopeTree',
);

/// העץ בלי ספרים אישיים ומצורפים, ובלי קטגוריות שנותרו ריקות.
ScopeTree officialOnly() =>
_officialOnlyCache[this] ??= _pruned((book) => book.source.isOfficial);
/// העץ בלי ספרים אישיים ומצורפים, מלבד אלה שמפתחם ב-[alsoKeep],
/// ובלי קטגוריות שנותרו ריקות.
ScopeTree officialOnly({Set<String> alsoKeep = const {}}) => alsoKeep.isEmpty
? _officialOnlyCache[this] ??= _pruned((book) => book.source.isOfficial)
: _pruned(
(book) =>
book.source.isOfficial ||
alsoKeep.contains(BookIdentity.keyOf(book)),
);

/// העץ בלי ספרים אישיים, ובלי קטגוריות שנותרו ריקות.
ScopeTree withoutUserBooks() =>
Expand Down
9 changes: 8 additions & 1 deletion lib/search/view/search_dialog.dart
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,7 @@ class _SearchDialogState extends State<SearchDialog> {
_semanticBloc = SemanticSearchBloc(
repository:
widget.semanticRepository ?? SemanticSearchRepository.instance,
loadCoveredBooks: true,
)..add(const SemanticSearchStarted());
// מצב מבוקש במפורש (קיצור חיפוש מתקדם, איתור) וכרטיסייה בעריכה
// גוברים על זיכרון הסשן.
Expand Down Expand Up @@ -1152,7 +1153,11 @@ class _SearchDialogState extends State<SearchDialog> {
UiSnack.show(LibraryMessages.emptySearchQuery);
return;
}
final isOfficialCategory = officialCategoryFilter(library);
final coveredBooks = _semanticBloc?.state.coveredBooks ?? const <String>{};
final isOfficialCategory = officialCategoryFilter(
library,
coveredBooks: coveredBooks,
);
final selection = parsedCategory.categoryFound
? [
...parsedCategory.facets!,
Expand All @@ -1164,6 +1169,7 @@ class _SearchDialogState extends State<SearchDialog> {
facet,
includeLexical: _semanticIncludeLexical,
isOfficialCategory: isOfficialCategory,
coveredBooks: coveredBooks,
),
)) {
UiSnack.showError(SemanticSearchMessages.unsupportedScope);
Expand Down Expand Up @@ -1222,6 +1228,7 @@ class _SearchDialogState extends State<SearchDialog> {
Widget _buildSemanticPanel(SemanticAvailability availability) {
return SemanticModePanel(
availability: availability,
coveredBooks: _semanticBloc?.state.coveredBooks ?? const <String>{},
debug: widget.semanticDebugPreview,
queryController: _searchTab.queryController,
queryFocusNode: _searchTab.searchFieldFocusNode,
Expand Down
29 changes: 22 additions & 7 deletions lib/search/view/search_scope_menu.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,13 @@ class SearchScopeMenuButton extends StatefulWidget {
final Set<String> selected;
final ValueChanged<Set<String>> onChanged;

/// מציג רק ספרים מהספרייה הרשמית (בחיפוש החכם — רק להם יש וקטורים).
/// מציג רק ספרים מהספרייה הרשמית ואת [coveredBooks] — בחיפוש החכם,
/// הספרים שיש להם וקטורים.
final bool officialBooksOnly;

/// מפתחות ספרים לא רשמיים שמוצגים גם עם [officialBooksOnly].
final Set<String> coveredBooks;

/// מסתיר ספרים אישיים כשאינם באינדקס ("בלי ספרים אישיים").
final bool excludeUserBooks;

Expand All @@ -55,6 +59,7 @@ class SearchScopeMenuButton extends StatefulWidget {
required this.selected,
required this.onChanged,
this.officialBooksOnly = false,
this.coveredBooks = const {},
this.excludeUserBooks = false,
});

Expand Down Expand Up @@ -82,7 +87,7 @@ class _SearchScopeMenuButtonState extends State<SearchScopeMenuButton> {
int _baseBookGeneration = 0;

ScopeTree _visibleTree(ScopeTree tree) => widget.officialBooksOnly
? tree.officialOnly()
? tree.officialOnly(alsoKeep: widget.coveredBooks)
: widget.excludeUserBooks
? tree.withoutUserBooks()
: tree;
Expand Down Expand Up @@ -166,6 +171,20 @@ class _SearchScopeMenuButtonState extends State<SearchScopeMenuButton> {
_searchController.addListener(_onTextChanged);
}

@override
void didUpdateWidget(covariant SearchScopeMenuButton oldWidget) {
super.didUpdateWidget(oldWidget);
if (!setEquals(oldWidget.coveredBooks, widget.coveredBooks)) _resetTree();
}

void _resetTree() {
_treeCache = null;
_treeFuture = null;
_baseBookGeneration++;
_baseBookNodesCache = null;
_baseBookNodesFuture = null;
}

@override
void dispose() {
_fieldFocus.removeListener(_onFocusChanged);
Expand Down Expand Up @@ -324,11 +343,7 @@ class _SearchScopeMenuButtonState extends State<SearchScopeMenuButton> {
final enabled = library != null;
if (!identical(library, _library)) {
_library = library;
_treeCache = null;
_treeFuture = null;
_baseBookGeneration++;
_baseBookNodesCache = null;
_baseBookNodesFuture = null;
_resetTree();
}

return OverlayPortal(
Expand Down
20 changes: 15 additions & 5 deletions lib/semantic_search/bloc/semantic_search_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ export 'semantic_search_state.dart';
class SemanticSearchBloc
extends Bloc<SemanticSearchEvent, SemanticSearchState> {
final SemanticSearchRepository repository;

/// טוען את [SemanticSearchState.coveredBooks]; החישוב קורא את כל הסט.
final bool loadCoveredBooks;
StreamSubscription<Object?>? _subscription;

SemanticSearchBloc({required this.repository})
SemanticSearchBloc({required this.repository, this.loadCoveredBooks = false})
: super(
SemanticSearchState(
availability: repository.availability,
Expand Down Expand Up @@ -49,15 +52,16 @@ class SemanticSearchBloc
);
});
on<SemanticDataRemovalRequested>(_onRemovalRequested);
on<SemanticAvailabilityUpdated>(
(event, emit) => emit(
on<SemanticAvailabilityUpdated>((event, emit) async {
emit(
state.copyWith(
availability: event.availability,
modelChoice: repository.modelChoice,
activeModelChoice: repository.activeModelChoice,
),
),
);
);
await _loadCoveredBooks(emit);
});
}

Future<void> _onStarted(
Expand All @@ -69,6 +73,12 @@ class SemanticSearchBloc
);
final availability = await repository.refresh();
emit(state.copyWith(availability: availability));
await _loadCoveredBooks(emit);
}

Future<void> _loadCoveredBooks(Emitter<SemanticSearchState> emit) async {
if (!loadCoveredBooks || !state.availability.isUsable) return;
emit(state.copyWith(coveredBooks: await repository.coveredBooks()));
}

Future<void> _onQuantizationChanged(
Expand Down
7 changes: 7 additions & 0 deletions lib/semantic_search/bloc/semantic_search_state.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ class SemanticSearchState extends Equatable {
final SemanticModelChoice activeModelChoice;
final bool isRemoving;

/// מפתחות האינדקס של הספרים שיש להם וקטורים, מכל המקורות.
final Set<String> coveredBooks;

const SemanticSearchState({
this.availability = SemanticAvailability.initial,
this.quantization = SemanticQuantization.int8,
this.modelChoice = SemanticModelChoice.meivin,
this.activeModelChoice = SemanticModelChoice.meivin,
this.isRemoving = false,
this.coveredBooks = const {},
});

SemanticSearchState copyWith({
Expand All @@ -24,12 +28,14 @@ class SemanticSearchState extends Equatable {
SemanticModelChoice? modelChoice,
SemanticModelChoice? activeModelChoice,
bool? isRemoving,
Set<String>? coveredBooks,
}) => SemanticSearchState(
availability: availability ?? this.availability,
quantization: quantization ?? this.quantization,
modelChoice: modelChoice ?? this.modelChoice,
activeModelChoice: activeModelChoice ?? this.activeModelChoice,
isRemoving: isRemoving ?? this.isRemoving,
coveredBooks: coveredBooks ?? this.coveredBooks,
);

@override
Expand All @@ -39,5 +45,6 @@ class SemanticSearchState extends Equatable {
modelChoice,
activeModelChoice,
isRemoving,
coveredBooks,
];
}
12 changes: 12 additions & 0 deletions lib/semantic_search/engine/onnx_semantic_engine_adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,18 @@ class OnnxSemanticEngineAdapter implements SemanticEngineBackend {
);
});

@override
Future<Set<String>> coveredBooks(
String vectorsDir, {
required SemanticCancelHandle cancel,
}) => _withToken(cancel, (token) async {
final covered = await (await _engine()).semanticCoveredBooks(
vectorsDir: vectorsDir,
cancellation: token,
);
return covered.filePaths.toSet();
});

@override
Future<SemanticBackendStatus> open(SemanticOpenRequest request) => _guard(
() async => mapStatus(
Expand Down
12 changes: 12 additions & 0 deletions lib/semantic_search/engine/semantic_engine_backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ abstract interface class SemanticEngineBackend {
required SemanticCancelHandle cancel,
});

/// מפתחות האינדקס (`id:`/`uid:`/`db:`...) של הספרים שהסט מכסה, מכל המקורות.
Future<Set<String>> coveredBooks(
String vectorsDir, {
required SemanticCancelHandle cancel,
});

/// פותח את הסט והמודל לקריאה ומחזיר את המצב שאחרי הפתיחה.
Future<SemanticBackendStatus> open(SemanticOpenRequest request);

Expand Down Expand Up @@ -108,6 +114,12 @@ class UnavailableSemanticEngineBackend implements SemanticEngineBackend {
required SemanticCancelHandle cancel,
}) => Future.error(_unavailable);

@override
Future<Set<String>> coveredBooks(
String vectorsDir, {
required SemanticCancelHandle cancel,
}) => Future.error(_unavailable);

@override
Future<SemanticBackendStatus> open(SemanticOpenRequest request) =>
Future.error(_unavailable);
Expand Down
44 changes: 30 additions & 14 deletions lib/semantic_search/models/semantic_mode_gate.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:otzaria/data/book_identity.dart';
import 'package:otzaria/data/data_providers/book_database_resolver.dart';
import 'package:otzaria/library/models/library.dart';
import 'package:otzaria/models/book_source.dart';
Expand Down Expand Up @@ -36,7 +37,7 @@ bool isWholeLibraryScope(Iterable<String> selection) {
return categories.isEmpty || categories.contains('/');
}

/// מפתחות של ספרים אישיים ושל מסדים מצורפים — אין להם וקטורים.
/// מפתחות של ספרים אישיים ושל מסדים מצורפים — וקטורים רק כשהסט מכסה אותם.
final RegExp _nonOfficialBookKey = RegExp(r'^(uid|db):');
final RegExp _bookKeySegment = RegExp(r'^(id|uid|ext|db):|\|');

Expand All @@ -52,29 +53,38 @@ List<String> semanticScopeFacets(Iterable<String> selection) {
}

/// האם facet של ספר או קטגוריה נתמך, לפני נרמול של בחירת כל הספרייה.
/// [coveredBooks] — מפתחות הספרים שהסט מכסה (ראו [officialCategoryFilter]).
bool isSemanticScopeFacetSupported(
String facet, {
bool includeLexical = false,
bool Function(String facet)? isOfficialCategory,
Set<String> coveredBooks = const {},
}) {
if (includeLexical || facet == '/' || FacetHelper.isDimensionFacet(facet)) {
return true;
}
if (BookDatabaseResolver.likelySource(categoryPath: facet) !=
BookSource.official) {
return false;
}
final segments = facet.split('/');
final isBook = _bookKeySegment.hasMatch(segments.last);
if (isBook && coveredBooks.contains(segments.last)) return true;
if (segments.any(_nonOfficialBookKey.hasMatch)) return false;
final categoryPath = _bookKeySegment.hasMatch(segments.last)
final categoryPath = isBook
? segments.sublist(0, segments.length - 1).join('/')
: facet;
return categoryPath.isEmpty ||
(isOfficialCategory?.call(categoryPath) ?? true);
final searchableCategory = isOfficialCategory?.call(categoryPath);
if (searchableCategory != true &&
BookDatabaseResolver.likelySource(categoryPath: facet) !=
BookSource.official) {
return false;
}
return categoryPath.isEmpty || (searchableCategory ?? true);
}

/// האם בקטגוריה של [facet] יש ספר מהספרייה הרשמית; `null` כשהספרייה לא נטענה.
bool Function(String facet)? officialCategoryFilter(Library? library) {
/// האם בקטגוריה של [facet] יש ספר רשמי או ספר שמפתחו ב-[coveredBooks];
/// `null` כשהספרייה לא נטענה.
bool Function(String facet)? officialCategoryFilter(
Library? library, {
Set<String> coveredBooks = const {},
}) {
if (library == null) return null;
return (facet) {
// פסיק בשם תיקייה הוא מפריד ב-facet, ולכן משווים לנתיב ה-facet של התיקייה.
Expand All @@ -85,10 +95,16 @@ bool Function(String facet)? officialCategoryFilter(Library? library) {
return facet == path || facet.startsWith('$path/');
}).firstOrNull;
}
return category != null && _hasOfficialBook(category);
return category != null && _hasSearchableBook(category, coveredBooks);
};
}

bool _hasOfficialBook(Category category) =>
category.books.any((book) => book.source.isOfficial) ||
category.subCategories.any(_hasOfficialBook);
bool _hasSearchableBook(Category category, Set<String> coveredBooks) =>
category.books.any(
(book) =>
book.source.isOfficial ||
coveredBooks.contains(BookIdentity.keyOf(book)),
) ||
category.subCategories.any(
(child) => _hasSearchableBook(child, coveredBooks),
);
31 changes: 31 additions & 0 deletions lib/semantic_search/repository/semantic_search_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,37 @@ class SemanticSearchRepository {
cancel: cancel ?? SemanticCancelHandle(),
);

({SemanticVectorsSummary vectors, Future<Set<String>> books})? _covered;

/// מפתחות האינדקס של הספרים שהסט המותקן מכסה — גם אישיים ומצורפים.
/// החישוב קורא את כל הסט, ולכן נשמר עד שהסט משתנה; בכשל — קבוצה ריקה.
Future<Set<String>> coveredBooks() async {
try {
final directory = (await _paths()).vectorsDirectory;
final vectors = await vectorsInfo();
if (!vectors.present) return const <String>{};
var cached = _covered;
if (cached == null || cached.vectors != vectors) {
cached = _covered = (
vectors: vectors,
books: _backend.coveredBooks(
directory,
cancel: SemanticCancelHandle(),
),
);
}
return _lastCoveredBooks = await cached.books;
} catch (error, stackTrace) {
_covered = null;
_log('coveredBooks', error, stackTrace);
return const <String>{};
}
}

/// התשובה האחרונה של [coveredBooks] שכבר הושלמה, בלי לחשב.
Set<String> get lastCoveredBooks => _lastCoveredBooks;
Set<String> _lastCoveredBooks = const {};

/// תמונת המנוע לטלמטריה: מצב, זהות המודל, החבילה והוקטורים המותקנים.
Future<SemanticEngineSnapshot> engineSnapshot() async {
final status = await _safeStatus();
Expand Down
Loading
Loading