Skip to content

Commit 1809a0e

Browse files
committed
הוסף ממשק חיפוש חכם מורשה לתוספים
מימוש C1 של #5595, בעקבות ההצעה והמימוש הראשוני ב־#5937.
1 parent b723218 commit 1809a0e

26 files changed

Lines changed: 2608 additions & 25 deletions

‎docs/plugin-sdk/API_REFERENCE.md‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@
6565
| `bookmarks.remove` | קלט | קלט | קלט | קלט |
6666
| `search.fullText` | ✗ (ראה הערה) | ✓ | — | — |
6767
| `search.query` | ✓ | ✓ | ✓ | ✓ |
68+
| `semantic.nearest` | ✓ | ✓ | ✓ | ✓ |
69+
| `semantic.getCoveredBooks` | ✓ | ✓ | ✓ | ✓ |
6870
| `library.getBookContent` | ✗ | ✗ | ✓ | — |
6971
| `library.getBookToc` | ✗ | ✗ | ✓ | — |
7072
| `library.getBookAltToc` | ✗ | ✗ | ✓ | — |
@@ -228,6 +230,7 @@ if (response.success) {
228230
| `error.payload_too_large` / `error.section_too_large` | `too_large` | הקלט או הקטע גדולים מדי |
229231
| `error.unknown_method` | `unsupported` | ה-method אינו קיים במארח הזה — איות שגוי, או API חדש מ-`minAppVersion` שהוצהר |
230232
| `error.unavailable` | `unsupported` | ה-API קיים אך אינו זמין בהקשר הנוכחי (אין טאב קריאה פעיל, שירות כבוי) |
233+
| `error.preempted` | `conflict` | המשתמש הריץ חיפוש באוצריא, והוא קדם לפעולה של התוסף; אפשר לנסות שוב (`retryable: true`) |
231234
| `error.unsupported_context` / `error.unsupported_layer` | `unsupported` | ההקשר או השכבה אינם נתמכים לפעולה הזו |
232235
| `error.internal` | `internal` | שגיאה פנימית בצד אוצריא |
233236

@@ -299,6 +302,10 @@ if (response.success) {
299302
| `search.setFieldText` | 0.9.98.1 |
300303
| `search.setFieldActionState` | 0.9.98.1 |
301304
| `search.endFieldSession` | 0.9.98.1 |
305+
| `semantic.getStatus` | 0.9.99 |
306+
| `semantic.countTokens` | 0.9.99 |
307+
| `semantic.nearest` | 0.9.99 |
308+
| `semantic.getCoveredBooks` | 0.9.99 |
302309
| `reader.openBook` | 0.9.89 |
303310
| `reader.openBookAtRef` | 0.9.89 |
304311
| `reader.printRange` | 0.9.98.1 |
@@ -2057,6 +2064,127 @@ await Otzaria.call('search.endFieldSession', { sessionId, submit: true });
20572064

20582065
---
20592066

2067+
## semantic.* - חיפוש חכם (לפי משמעות)
2068+
2069+
מגרסה 0.9.99. **הרשאה:** `search.semantic.read`.
2070+
2071+
המודל והווקטורים שאוצריא מורידה לחיפוש החכם, לכלים שליד הקורא: מקבילות
2072+
לקטע הנקרא, השוואת מפרש לטקסט־הבסיס, אשכולות, מסלול בין קטעים. הכול רץ
2073+
במחשב של המשתמש.
2074+
2075+
**כללים**
2076+
2077+
- **הסכמה ונתונים.** הקריאות לנתונים זמינות ב-`phase: 'ready'`, כשהמשתמש
2078+
העניק הסכמה לחיפוש החכם והנתונים מותקנים. ביטול ההסכמה או הרשאת התוסף
2079+
עוצר פעולה פעילה. כל המתודות דורשות הרשאת תוסף, כולל `semantic.getStatus`.
2080+
- **ספרים.** החיפוש מוגבל לספרי הטקסט הרשמיים במסד ולמסכתות ה־PDF
2081+
המצורפות. הספרים חייבים להימצא בקטלוג הנוכחי.
2082+
- **הטקסט אינו בתשובות.** שורה שנמצאה מזוהה בזהות ספר ו-`index`; את הטקסט
2083+
קוראים ב-`library.getBookContent` בהרשאת `library.content.read`.
2084+
- **סריקה אחת לדף.** `semantic.nearest` חדש מאותו דף של התוסף מסיים את הקודם
2085+
(הוא מסתיים בלי chunk של `done`), כמו הקלדה במסך החיפוש. `return()` על
2086+
האיטרטור מבטל את הסריקה במנוע.
2087+
- **המשתמש קודם.** חיפוש שהמשתמש מריץ באוצריא מסיים סריקה פעילה של תוסף
2088+
ב-`error.preempted`. בקשות שמגיעות בזמן חיפוש פעיל נדחות באותו קוד.
2089+
- **ציונים.** `score` מדורג כמו במסך החיפוש, עם הקנס של חלונות בשורה ארוכה.
2090+
ציונים ברי־השוואה רק באותו `modelFamilyId` ובאותו `generation`.
2091+
2092+
### `semantic.getStatus`
2093+
**הרשאה:** `search.semantic.read`
2094+
2095+
```javascript
2096+
const { data } = await Otzaria.call('semantic.getStatus');
2097+
// {
2098+
// phase: 'ready', // 'consentRequired' | 'needsDownload' | 'vectorsNotPublished'
2099+
// // | 'downloading' | 'installing' | 'failed' | 'hidden'
2100+
// modelFamilyId: 'otzaria/Meivin-Embed-QA491-native256', dim: 256,
2101+
// vectorsReleaseTag: 'vectors-qa491-v30-…', vectorsLibraryVersion: 30, generation: 7,
2102+
// limits: { maxPoints: 64, maxK: 2000, defaultK: 50, maxCandidates: 5000, … }
2103+
// }
2104+
```
2105+
2106+
`hiddenReason` מופיע עם `'hidden'`, `failure` עם `'failed'`, ו-`progress`
2107+
(`{ item, fraction }`) בזמן הורדה או התקנה.
2108+
2109+
### `semantic.countTokens`
2110+
**הרשאה:** `search.semantic.read`
2111+
2112+
```javascript
2113+
const { data } = await Otzaria.call('semantic.countTokens', { texts: [a, b] });
2114+
// { counts: [41, 300], queryMaxTokens: 256, overheadTokens: 3 }
2115+
```
2116+
2117+
כל ספירה היא של הרצף המלא שהמודל רואה כשאילתה, כולל קידומת התפקיד והטוקנים
2118+
המיוחדים: טקסט נכנס בחלון אחד כש-`count <= queryMaxTokens`, וארוך ממנו נחתך.
2119+
עד 5,000 טקסטים ו-2,000,000 תווים בקריאה, ועד 20,000 תווים לטקסט. הקריאה הראשונה פותחת את המודל.
2120+
2121+
### `semantic.nearest`
2122+
**הרשאה:** `search.semantic.read`
2123+
2124+
השורות החיות הקרובות לעד 64 נקודות, במעבר אחד על הווקטורים. נקודה היא טקסט
2125+
(מקודד כשאילתה, או `as: 'passage'` כמו שורה שמורה) או וקטור ברוחב הסט
2126+
(`dim`), כ-base64 של float32 בסדר little-endian, למשל מרכז של אשכול.
2127+
קידוד כקטע זמין כשהמודל המתאים כבר מותקן.
2128+
2129+
```javascript
2130+
const stream = Otzaria.call('semantic.nearest', {
2131+
from: windows.map((text) => ({ text })),
2132+
k: 100,
2133+
rescore: true,
2134+
exclude: [{ ...book, from: 120, to: 135 }], // הקטע שממנו הנקודות נלקחו
2135+
categories: ['/תלמוד בבלי'],
2136+
});
2137+
2138+
for await (const chunk of stream) {
2139+
if (chunk.type === 'hits') show(chunk.hits);
2140+
if (chunk.type === 'done') console.log(chunk.generation);
2141+
}
2142+
```
2143+
2144+
| פרמטר | ברירת מחדל | משמעות |
2145+
|-------|-----------|--------|
2146+
| `from` | — (חובה) | 1 עד 64 נקודות: `{ text, as? }` (`'query'` או `'passage'`, עד 20,000 תווים) או `{ vector }` |
2147+
| `k` | `50` | כמה וקטורים כל נקודה מחזירה מהסריקה, עד 2,000. וקטור אחד יכול לייצג כמה שורות (אותו טקסט בכמה ספרים) |
2148+
| `pool` | `'best'` | `'best'`: רשימה אחת, כל שורה פעם אחת בציון הטוב ביותר שלה. `'perPoint'`: רשימה לכל נקודה, לפי הסדר (נקודות × `k` עד 20,000) |
2149+
| `maxCandidates` | `1000` | `'best'` בלבד: כמה וקטורים נשמרים לפני שהם נפתרים לשורות, עד 5,000 |
2150+
| `rescore` | `false` | `'best'` בלבד: ציון לכל שורה מול כל נקודה, ב-`pointScores` (`null` לשורה שאין לה וקטור) |
2151+
| `minScore` | — | שורות בציון נמוך ממנו מושמטות |
2152+
| `exclude` | `[]` | עד 1,000 טווחי שורות (`{ ...זהות ספר, from, to }`) שלא יוחזרו |
2153+
| `categories`, `books`, `authors`, `eras`, `baseBooksOnly`, `facets` | הספרייה הרשמית | ההיקף, כמו ב-[`search.query`](#searchquery), עם עד 128 ערכים בכל רשימה |
2154+
2155+
**ה-chunks**, לפי הסדר:
2156+
2157+
- `{ type: 'progress', phase: 'searching' }` — המודל נפתח והסריקה מתחילה.
2158+
- `{ type: 'hits', hits, point? }` — עד 500 שורות לכל chunk; `point` עם
2159+
`'perPoint'`. כל רשימה נשלחת, גם ריקה.
2160+
- `{ type: 'done', generation, vectorsLibraryVersion, clipped }`
2161+
— `clipped` מסמן שהוחזרו רק 20,000 השורות הראשונות.
2162+
2163+
כל שורה: זהות ספר, `book`, `categoryPath`, `reference`, `index`, `window` (החלון
2164+
בשורה ארוכה שנמצא; 0 לתחילת השורה), `score`, `point` (הנקודה שמצאה אותה בציון
2165+
הגבוה ביותר) ו-`pointScores` עם `rescore`.
2166+
2167+
שגיאות אפשריות: `error.invalid_params` (גם וקטור ברוחב שאינו של הסט),
2168+
`error.not_found` (ספר ב-`books` או ב-`exclude`), `error.unavailable`,
2169+
`error.preempted`, `error.timeout` (שתי דקות). בזרם, שגיאה נזרקת מהאיטרטור
2170+
עם `code` ו-`retryable` על אובייקט ה-`Error`.
2171+
2172+
**מגבלה ידועה:** עם היקף (`categories`, `books` וכו'), טקסט שהועתק לספר
2173+
בהיקף אחרי בניית הווקטורים אינו נמצא, עד שהנתונים מתעדכנים.
2174+
2175+
### `semantic.getCoveredBooks`
2176+
**הרשאה:** `search.semantic.read`
2177+
2178+
```javascript
2179+
const { data } = await Otzaria.call('semantic.getCoveredBooks');
2180+
// { books: [{ id, type, bookId, source, bookUid, title }, …] }
2181+
```
2182+
2183+
ספרים רשמיים שיש בהם לפחות שורה אחת שהווקטורים מכסים. אוצריא משתמשת
2184+
במטמון הכיסוי של החיפוש החכם ומאמתת את גרסאות האינדקס והווקטורים בכל קריאה.
2185+
2186+
---
2187+
20602188
## reader.* - פעולות קריאה
20612189
20622190
### `reader.openBook`
@@ -6985,6 +7113,7 @@ Otzaria.on('plugin.boot', async (payload) => {
69857113
"library.books.provide",
69867114
"search.fulltext.read",
69877115
"search.field_actions",
7116+
"search.semantic.read",
69887117
"reader.open",
69897118
"navigation.write",
69907119
"notes.read",

‎docs/plugin-sdk/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,10 @@ Otzaria.on('plugin.boot', (payload) => {
488488
| `search.fullText` | `search.fulltext.read` | `{ query, limit?, rawDivineNames? }` | `SearchResult[]` |
489489
| `search.query` | `search.fulltext.read` | `{ query, regex?, mode?, distance?, proximityScope?, order?, grouping?, wordMatchMode?, anyOrder?, options?, wordOptions?, alternativeWords?, customSpacing?, negativeQuery?, categories?, books?, authors?, eras?, baseBooksOnly?, limit?, offset?, includeBookCounts? }` | `AsyncIterable<{ sequence, results, total, groupCount, truncated, facets, bookCounts? }>` |
490490
| `search.getOptions` | `search.fulltext.read` | `{}` | הערכים החוקיים לכל פרמטר של `search.query` |
491+
| `semantic.getStatus` | `search.semantic.read` | — | `{ phase, modelFamilyId, dim, generation, limits, … }` |
492+
| `semantic.countTokens` | `search.semantic.read` | `{ texts }` | `{ counts, queryMaxTokens, overheadTokens }` |
493+
| `semantic.nearest` | `search.semantic.read` | `{ from, k?, pool?, maxCandidates?, rescore?, minScore?, exclude?, categories?, books?, authors?, eras?, baseBooksOnly? }` | `AsyncIterable` של `progress`, `hits` ו-`done` |
494+
| `semantic.getCoveredBooks` | `search.semantic.read` | — | `{ books }` |
491495
492496
ב-`search.query`, גודל עמוד מוגבל ל-500 וחלון הדפדוף (`offset + limit`
493497
לאחר החיתוך) מוגבל ל-10,000 כדי למנוע הקצאת זיכרון לא חסומה במנוע.
@@ -743,6 +747,7 @@ const { data: keys } = await Otzaria.call('storage.list');
743747
| `library.refresh` | סריקה מחדש של התיקיות האישיות ורענון הקטלוג (`library.refreshUserBooks`) |
744748
| `library.books.provide` | הוספת ספרים מהתוסף לאיתור הספרים במסך הספרייה (`contributes.startup.libraryBooks`); לחיצה על ספר כזה נמסרת לתוסף |
745749
| `search.fulltext.read` | חיפוש טקסט מלא |
750+
| `search.semantic.read` | חיפוש לפי משמעות במודל ובווקטורים של החיפוש החכם (`semantic.*`); מ־0.9.99 |
746751
| `reader.open` | פתיחת ספרים + קריאת מצב הקורא |
747752
| `reader.local_edit` | שכבת תיקונים זמנית בקורא הטקסט הרשמי, ללא כתיבה למקור; מ־0.9.98.1 |
748753
| `navigation.write` | ניווט בין מסכים |

‎docs/plugin-sdk/otzaria_plugin.d.ts‎

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,133 @@ export interface SearchOptionsCatalog {
576576
defaultLimit: number;
577577
}
578578

579+
// ---------------------------------------------------------------------------
580+
// semantic.* — the meaning-based search space (from 0.9.99)
581+
// ---------------------------------------------------------------------------
582+
583+
/** What `semantic.getStatus` reports. Access to search data requires `phase: 'ready'`. */
584+
export type SemanticPhase =
585+
| 'ready'
586+
| 'consentRequired'
587+
| 'needsDownload'
588+
| 'vectorsNotPublished'
589+
| 'downloading'
590+
| 'installing'
591+
| 'failed'
592+
| 'hidden';
593+
594+
export interface SemanticLimits {
595+
maxPoints: number;
596+
maxK: number;
597+
defaultK: number;
598+
maxCandidates: number;
599+
defaultMaxCandidates: number;
600+
/** All the lists of one `semantic.nearest` answer together. */
601+
maxHits: number;
602+
maxExcludeSpans: number;
603+
maxPointTextLength: number;
604+
maxTokenTexts: number;
605+
maxTokenTextsLength: number;
606+
maxScopeEntries: number;
607+
}
608+
609+
export interface SemanticStatus {
610+
phase: SemanticPhase;
611+
/** With `hidden`: `unsupportedPlatform` | `engineNotInBuild`. */
612+
hiddenReason?: string;
613+
/** With `failed`: the kind of the last failure. */
614+
failure?: string;
615+
/** While downloading or installing; `fraction` is null when the size is unknown. */
616+
progress?: { item: 'model' | 'vectors' | 'install'; fraction: number | null };
617+
modelFamilyId: string | null;
618+
/** The width of the vectors. */
619+
dim: number | null;
620+
vectorsReleaseTag: string | null;
621+
vectorsLibraryVersion: number | null;
622+
/** Changes with every install and compaction of the vectors. Scores are
623+
* comparable only within one `modelFamilyId` and one generation. */
624+
generation: number | null;
625+
limits: SemanticLimits;
626+
}
627+
628+
/** A text, embedded as a query (default) or as a stored line is embedded; or a
629+
* vector of the set's width, base64 of float32 little-endian, scaled to unit length. */
630+
export type SemanticPoint =
631+
| { text: string; as?: 'query' | 'passage' }
632+
| { vector: string };
633+
634+
/** Lines `from` to `to` (inclusive) of one book, by line index. */
635+
export type SemanticLineSpan = BookIdentity & { from: number; to: number };
636+
637+
export interface SemanticNearestParams {
638+
/** 1 to 64 points, searched in one pass over the vectors. */
639+
from: SemanticPoint[];
640+
/** Vectors each point's scan returns; default 50, at most 2000. A vector can
641+
* stand for several lines (the same text in several books). */
642+
k?: number;
643+
/** `best` (default): one list, every line once at its best score over the points.
644+
* `perPoint`: one list per point, in their order. */
645+
pool?: 'best' | 'perPoint';
646+
/** `best` only: the most vectors kept before they are resolved to lines;
647+
* default 1000, at most 5000. */
648+
maxCandidates?: number;
649+
/** `best` only: score every line against every point, in `pointScores`. */
650+
rescore?: boolean;
651+
minScore?: number;
652+
/** Lines never returned, such as the passage the points were taken from. */
653+
exclude?: SemanticLineSpan[];
654+
// Scope, as in `search.query`; all official books by default.
655+
categories?: string[];
656+
books?: BookIdentity[];
657+
authors?: string[];
658+
eras?: string[];
659+
baseBooksOnly?: boolean;
660+
facets?: string[];
661+
}
662+
663+
/** A line found. The text is not included: read it with `library.getBookContent`
664+
* under `library.content.read`. */
665+
export interface SemanticHit extends BookIdentity {
666+
book: string;
667+
categoryPath?: string | null;
668+
reference: string;
669+
index: number;
670+
/** Which window of a long line matched; 0 for the line's start. */
671+
window: number;
672+
/** Ranked as the search screen ranks, with its long-line penalties. */
673+
score: number;
674+
/** The point that found the line best, by its index in `from`. */
675+
point: number;
676+
/** With `rescore`: the score for each point; null where the line has no vector. */
677+
pointScores?: Array<number | null>;
678+
}
679+
680+
export type SemanticNearestChunk =
681+
| { type: 'progress'; phase: 'searching' }
682+
/** `point` is set with `pool: 'perPoint'`; a list may come in several chunks. */
683+
| { type: 'hits'; point?: number; hits: SemanticHit[] }
684+
| {
685+
type: 'done';
686+
generation: number;
687+
vectorsLibraryVersion: number;
688+
/** More lines than `limits.maxHits`; the lists were cut. */
689+
clipped: boolean;
690+
};
691+
692+
export interface SemanticTokenCounts {
693+
/** Each text as the query sequence the model sees, role prefix and special tokens
694+
* included: a text fits one window when its count is at most `queryMaxTokens`. */
695+
counts: number[];
696+
queryMaxTokens: number;
697+
/** What an empty query counts. */
698+
overheadTokens: number;
699+
}
700+
701+
export interface SemanticCoveredBooks {
702+
/** Official books in the current catalog with at least one covered line. */
703+
books: Array<BookIdentity & { title: string }>;
704+
}
705+
579706
/**
580707
* ההרשאה נקבעת לפי ה-host שב-`url`: `localhost` / `::1` / `127.0.0.0`–`127.0.0.255`
581708
* דורשים `network.localhost`; כל יעד אחר (אינטרנט) דורש `network.access`.
@@ -2687,6 +2814,10 @@ export type OtzariaMethod =
26872814
| 'search.setFieldText'
26882815
| 'search.setFieldActionState'
26892816
| 'search.endFieldSession'
2817+
| 'semantic.getStatus'
2818+
| 'semantic.countTokens'
2819+
| 'semantic.nearest'
2820+
| 'semantic.getCoveredBooks'
26902821
| 'reader.openBook'
26912822
| 'reader.openBookAtRef'
26922823
| 'reader.printRange'
@@ -2887,6 +3018,31 @@ export interface OtzariaGlobal {
28873018
payload: NetworkFetchParams
28883019
): AsyncIterable<NetworkFetchStreamChunk>;
28893020

3021+
/** The state of the meaning-based search (from 0.9.99). Requires search.semantic.read. */
3022+
call(method: 'semantic.getStatus'): Promise<OtzariaResponse<SemanticStatus>>;
3023+
3024+
/** Token counts, to cut a long passage into windows that fit (from 0.9.99). */
3025+
call(
3026+
method: 'semantic.countTokens',
3027+
payload: { texts: string[] }
3028+
): Promise<OtzariaResponse<SemanticTokenCounts>>;
3029+
3030+
/**
3031+
* The lines nearest up to 64 points, in one pass (from 0.9.99). A new call from
3032+
* the same plugin page ends the previous one (it finishes without a `done`
3033+
* chunk); a search the user runs in Otzaria ends it with `error.preempted`;
3034+
* `return()` on the iterator cancels it.
3035+
*/
3036+
call(
3037+
method: 'semantic.nearest',
3038+
payload: SemanticNearestParams
3039+
): AsyncIterable<SemanticNearestChunk>;
3040+
3041+
/** The books the installed vectors cover (from 0.9.99). */
3042+
call(
3043+
method: 'semantic.getCoveredBooks'
3044+
): Promise<OtzariaResponse<SemanticCoveredBooks>>;
3045+
28903046
/** Waits for the print dialog to finish, without the generic 30-second RPC timeout. */
28913047
call(
28923048
method: 'reader.printRange',

0 commit comments

Comments
 (0)