Skip to content
Merged
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
9 changes: 9 additions & 0 deletions lib/models/books.dart
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@ abstract class Book {
((externalLibraryId ?? '').isEmpty ||
DatabaseConstants.isBundledLibrarySource(externalLibraryId));

/// האם לספר יש זהות רשמית לשימוש בחיפוש הסמנטי.
bool get hasOfficialSemanticIdentity =>
isOfficialLibraryBook &&
((this is TextBook && id != null && (filePath?.isEmpty ?? true)) ||
(this is PdfBook &&
DatabaseConstants.isTalmudBavliPdfExternalLibraryId(
externalLibraryId,
)));

/// External library ID (e.g., Sefaria ref) for books from external sources
final String? externalLibraryId;

Expand Down
8 changes: 8 additions & 0 deletions lib/search/search_engine_gateway.dart
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,10 @@ class SemanticSearchRequest {
final SemanticGroupingMode? grouping;
final bool matchNikud;
final bool matchTaamim;
final List<SemanticVote> votes;

/// מזהה עימוד מקומי שנשמר בבקשות ההמשך של אותו חיפוש.
final String? paginationSessionId;

const SemanticSearchRequest({
required this.query,
Expand All @@ -190,6 +194,8 @@ class SemanticSearchRequest {
this.grouping,
this.matchNikud = false,
this.matchTaamim = false,
this.votes = const [],
this.paginationSessionId,
});

/// מנוע החיפוש תומך במרחק עריכה עד [kMaxFuzzyDistance].
Expand Down Expand Up @@ -613,6 +619,8 @@ class RustSearchEngineOperations
grouping: request.grouping,
matchNikud: request.matchNikud,
matchTaamim: request.matchTaamim,
votes: request.votes,
paginationSessionId: request.paginationSessionId,
cancellation: token,
)
.whenComplete(token.dispose);
Expand Down
62 changes: 51 additions & 11 deletions lib/semantic_search/bloc/semantic_results_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import 'package:otzaria/semantic_search/models/semantic_feedback_snapshots.dart'
import 'package:otzaria/semantic_search/models/semantic_result_item.dart';
import 'package:otzaria/semantic_search/repository/semantic_results_source.dart';
import 'package:otzaria_search_engine/otzaria_search_engine.dart'
show MergedSibling, SemanticPassageHighlight;
show MergedSibling, SemanticPassageHighlight, SemanticVote;

export 'semantic_results_event.dart';
export 'semantic_results_state.dart';
Expand All @@ -27,9 +27,9 @@ typedef SemanticUserBookResolver = Future<bool> Function(SemanticResultItem);
/// הפסקה המלאה של התוצאה; `null` כשלא נמצאה.
typedef SemanticPassageResolver = Future<String?> Function(SemanticResultItem);

/// ציבורי רק ספר שפוענח ומקורו הספרייה הרשמית; כל השאר (גם מפתח שלא
/// פוענח — לספר אישי יכול להיות מפתח ext:) נחשב פרטי.
bool semanticResultIsPrivate(Book? book) => !(book?.source.isOfficial ?? false);
/// רק תוצאה בעלת זהות ספרייה רשמית נחשבת ציבורית.
bool semanticResultIsPrivate(Book? book) =>
!(book?.hasOfficialSemanticIdentity ?? false);

/// תלויות הטלמטריה; ברירת המחדל [SearchFeedbackService.instance], בגישה הראשונה.
class SemanticFeedbackPorts {
Expand Down Expand Up @@ -99,6 +99,7 @@ class SemanticResultsBloc
SemanticResultsSource? _source;
SemanticSearchContext? _context;
final List<bool> _userBookFlags = [];
final _publicVotes = <({String filePath, BigInt id}), SearchFeedbackVote>{};
int _generation = 0;
SemanticCancelHandle? _highlightCancel;

Expand All @@ -122,14 +123,15 @@ class SemanticResultsBloc
Future<void> _onSubmitted(
SemanticSearchSubmitted event,
Emitter<SemanticResultsState> emit, {
String? message,
bool refresh = false,
}) async {
final generation = ++_generation;
_source?.cancel();
_highlightCancel?.cancel();
_highlightCancel = SemanticCancelHandle();
_context = null;
_userBookFlags.clear();
if (!refresh) _publicVotes.clear();
final options = event.options;
emit(
SemanticResultsState(
Expand Down Expand Up @@ -193,11 +195,14 @@ class SemanticResultsBloc
? SemanticResultsStatus.failed
: SemanticResultsStatus.loaded,
items: page.items,
votes: _votesForPage(page.items, 0),
morePages: page.hasMore,
isDebugPreview: source.isDebugPreview,
message: failedEmpty
? SemanticSearchMessages.semanticPartFailed
: message,
: refresh
? SemanticSearchMessages.resultsRefreshed
: null,
onlyLexical: semanticFailed && !failedEmpty,
),
);
Expand Down Expand Up @@ -230,15 +235,14 @@ class SemanticResultsBloc
emit(state.copyWith(isLoadingMore: false));
return;
}
// אין לצרף עמוד מסדר חדש לרשימה הישנה. חיפוש מחדש מאפס גם הצבעות,
// סימונים והקשר משוב, ומבטל תשובות שעדיין מגיעות מהחיפוש הקודם.
// עמוד מסדר חדש מחליף את הרשימה ומתחיל הקשר משוב חדש.
if (page.sessionRestarted ||
(_context != null &&
page.executedMode != _context!.response.executedMode)) {
await _onSubmitted(
SemanticSearchSubmitted(options),
emit,
message: SemanticSearchMessages.resultsRefreshed,
refresh: true,
);
return;
}
Expand All @@ -250,6 +254,7 @@ class SemanticResultsBloc
isLoadingMore: false,
clearMessage: true,
items: [...state.items, ...page.items],
votes: {...state.votes, ..._votesForPage(page.items, offset)},
// עמוד ריק אומר שאין עוד, גם כשהמקור דיווח אחרת.
morePages: page.items.isNotEmpty && page.hasMore,
),
Expand Down Expand Up @@ -347,12 +352,23 @@ class SemanticResultsBloc
votes[index] = event.vote;
recorded = event.vote;
}
final item = state.items[index];
final isUserBook = isUserBookAt(index);
// גם הציונים בדף הבא עשויים להיכלל במשוב הקיים.
if (!isUserBook) {
final key = (filePath: item.filePath, id: item.id);
if (recorded == SearchFeedbackVote.cleared) {
_publicVotes.remove(key);
} else {
_publicVotes[key] = recorded;
}
}
emit(state.copyWith(votes: votes));
final context = _context;
if (context == null || isUserBookAt(index) || !_isCollecting) return;
if (context == null || isUserBook || !_isCollecting) return;
unawaited(
_fullSnapshot(
state.items[index],
item,
index,
isUserBook: false,
).then(
Expand Down Expand Up @@ -403,6 +419,21 @@ class SemanticResultsBloc
await _feedback.whenQueued();
}

Map<int, SearchFeedbackVote> _votesForPage(
List<SemanticResultItem> items,
int offset,
) {
final votes = <int, SearchFeedbackVote>{};
if (_publicVotes.isEmpty) return votes;
for (var i = 0; i < items.length; i++) {
if (isUserBookAt(offset + i)) continue;
final item = items[i];
final vote = _publicVotes[(filePath: item.filePath, id: item.id)];
if (vote != null) votes[offset + i] = vote;
}
return votes;
}

Future<SemanticResultsPage?> _fetch(
SemanticResultsSource source,
SemanticQueryOptions options,
Expand All @@ -416,6 +447,15 @@ class SemanticResultsBloc
options,
offset: offset,
limit: pageSize,
votes: [
if (!source.isDebugPreview && !state.onlyLexical)
for (final entry in _publicVotes.entries)
SemanticVote(
filePath: entry.key.filePath,
id: entry.key.id,
relevant: entry.value == SearchFeedbackVote.like,
),
],
onSearching: offset == 0
? () {
if (generation == _generation && !emit.isDone) {
Expand Down
2 changes: 2 additions & 0 deletions lib/semantic_search/engine/onnx_semantic_engine_adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ class OnnxSemanticEngineAdapter implements SemanticEngineBackend {
matchNikud: request.matchNikud,
matchTaamim: request.matchTaamim,
ranking: ranking == null ? null : mapRanking(ranking),
votes: request.votes,
paginationSessionId: request.paginationSessionId,
cancellation: token,
);
final fallback = response.fallbackKind;
Expand Down
20 changes: 19 additions & 1 deletion lib/semantic_search/repository/semantic_results_source.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import 'dart:convert';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:otzaria/data/data_providers/tantivy_data_provider.dart';
import 'package:otzaria/search/search_engine_gateway.dart'
Expand All @@ -18,7 +21,8 @@ import 'package:otzaria_search_engine/otzaria_search_engine.dart'
SemanticGroupingMode,
SemanticHighlightTarget,
SemanticPassageHighlight,
SemanticRetrievalMode;
SemanticRetrievalMode,
SemanticVote;

/// מקור עמודי התוצאות של מסך החיפוש הסמנטי.
abstract interface class SemanticResultsSource {
Expand All @@ -29,11 +33,13 @@ abstract interface class SemanticResultsSource {
SemanticRankingConfig? get ranking;

/// `null` כשחיפוש חדש יותר החליף את זה. זורק `SemanticFailure` בכשל.
/// [votes] הם הסימונים הפעילים שמשפיעים על העמודים שטרם הוצגו.
/// [onSearching] נקרא כשההכנה הסתיימה והחיפוש עצמו מתחיל.
Future<SemanticResultsPage?> fetch(
SemanticQueryOptions options, {
required int offset,
required int limit,
List<SemanticVote> votes = const [],
void Function()? onSearching,
});

Expand Down Expand Up @@ -75,12 +81,15 @@ class EngineSemanticResultsSource implements SemanticResultsSource {
}) : _fallbackLog = fallbackLog ?? SemanticFallbackLog.shared,
_slowSearchLog = slowSearchLog ?? SemanticSlowSearchLog.shared;

static final _paginationIdRandom = Random.secure();

final SemanticSearchRepository _repository;
final SemanticFallbackLog _fallbackLog;
final SemanticSlowSearchLog _slowSearchLog;

/// ערוץ משלו: חיפוש בכרטיסייה אחרת אינו מבטל את החיפוש כאן.
final SemanticSearchSession _session = SemanticSearchSession();
String? _paginationSessionId;

@override
bool get isDebugPreview => false;
Expand All @@ -93,8 +102,14 @@ class EngineSemanticResultsSource implements SemanticResultsSource {
SemanticQueryOptions options, {
required int offset,
required int limit,
List<SemanticVote> votes = const [],
void Function()? onSearching,
}) async {
if (offset == 0) {
_paginationSessionId = base64Url.encode(
List.generate(16, (_) => _paginationIdRandom.nextInt(256)),
);
}
final stopwatch = Stopwatch()..start();
Duration? prepare;
final outcome = await _repository.search(
Expand All @@ -103,6 +118,8 @@ class EngineSemanticResultsSource implements SemanticResultsSource {
facets: options.facets,
limit: limit,
offset: offset,
votes: votes,
paginationSessionId: _paginationSessionId,
lexicalMode: kSmartSearchLexicalMode,
fuzzyMaxDistance: kSmartSearchFuzzyMaxDistance,
retrievalMode: options.includeLexical
Expand Down Expand Up @@ -203,6 +220,7 @@ class DebugLexicalPreviewSource implements SemanticResultsSource {
SemanticQueryOptions options, {
required int offset,
required int limit,
List<SemanticVote> votes = const [],
void Function()? onSearching,
}) async {
final generation = ++_generation;
Expand Down
4 changes: 2 additions & 2 deletions pubspec.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ dependencies:
googleapis_auth: ^2.3.7
characters: ^1.4.1
collection: ^1.19.1
otzaria_search_engine: 7.5.1
otzaria_search_engine: 7.5.3
# חוזה הדיווחים מול השרת, משותף עם "עדכוני אוצריא" (Dart טהור).
otzaria_report_contract:
path: packages/otzaria_report_contract
Expand Down
23 changes: 23 additions & 0 deletions test/semantic_search/engine/onnx_semantic_engine_adapter_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ class _FakeEngine implements SearchEngine {
SemanticVectorsInstallInput? installInput;
SemanticArtifactInput? openInput;
SemanticRankingOptions? ranking;
List<SemanticVote>? votes;
String? paginationSessionId;
SemanticCancellationToken? searchToken;
Object? failure;
Completer<void>? searchPause;
Expand Down Expand Up @@ -123,9 +125,12 @@ class _FakeEngine implements SearchEngine {
required bool matchTaamim,
SemanticRankingOptions? ranking,
List<SemanticVote>? votes,
String? paginationSessionId,
required SemanticCancellationToken cancellation,
}) async {
this.ranking = ranking;
this.votes = votes;
this.paginationSessionId = paginationSessionId;
searchToken = cancellation;
await searchPause?.future;
return SemanticSearchResponse(
Expand Down Expand Up @@ -338,6 +343,24 @@ void main() {
expect(tokens.last.isCancelled, isTrue);
});

test('הסימונים ומזהה העימוד מגיעים למנוע', () async {
final votes = [
SemanticVote(filePath: 'id:1', id: BigInt.one, relevant: true),
];
await adapter.search(
SemanticSearchRequest(
query: 'חסד',
facets: ['/'],
offset: 30,
votes: votes,
paginationSessionId: 'local-session',
),
cancel: SemanticCancelHandle(),
);
expect(engine.votes, votes);
expect(engine.paginationSessionId, 'local-session');
});

test('mapRanking ממפה את כל השדות, כולל ספרי היסוד', () {
const config = SemanticRankingConfig(
foundationalBonus: 0.004,
Expand Down
Loading
Loading