-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp_ai.py
More file actions
1779 lines (1545 loc) · 78.9 KB
/
Copy pathapp_ai.py
File metadata and controls
1779 lines (1545 loc) · 78.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import json
import math
import time
import sqlite3
import shutil
import threading
import zipfile
import hashlib
import functools
import uuid
import sys
import bisect
from dataclasses import dataclass
from collections import deque
from pathlib import Path
from typing import Dict, Optional, Set, List, Tuple
import tkinter as tk
from tkinter import filedialog
import requests
import numpy as np
import faiss
from flask import Flask, request, render_template_string, redirect, jsonify, flash, send_from_directory
from huggingface_hub import snapshot_download
# =========================
# CONFIG
# =========================
HF_REPO = "ArieLLL123/otzaria-embeddings"
def _find_default_db() -> str:
paths = [
r"C:\אוצריא\אוצריא\seforim.db",
r"C:\אוצריא\seforim.db",
os.path.join(os.environ.get('APPDATA', ''), 'io.github.kdroidfilter.seforimapp', 'databases', 'seforim.db'),
r"C:\Users\daniely\AppData\Roaming\io.github.kdroidfilter.seforimapp\databases\seforim.db",
os.path.join(os.environ.get('APPDATA', ''), 'Otzaria', 'books', 'seforim.db'),
r"C:\Users\daniely\AppData\Roaming\Otzaria\books\seforim.db"
]
for p in paths:
if p and os.path.exists(p):
return p
return paths[0]
DEFAULT_DB_PATH = _find_default_db()
DB_DOWNLOAD_URL = "https://github.com/Otzaria/otzaria-library/releases/download/library-db-1/seforim.zip"
EDITION_PATHS = {
"v1": "editions/otzaria_embeddings_v1",
"v2": "editions/otzaria_embeddings_v2",
"v3": "editions/otzaria_embeddings_v3",
}
if getattr(sys, 'frozen', False):
# במצב EXE:
# EXE_DIR = התיקייה שבה נמצא קובץ ה-EXE (לשמירת הגדרות ו-DB)
# BUNDLE_DIR = התיקייה הזמנית שבה נפתח ה-EXE (לקריאת המודל הארוז)
EXE_DIR = os.path.dirname(sys.executable)
BUNDLE_DIR = sys._MEIPASS
else:
# במצב פיתוח רגיל
EXE_DIR = os.path.dirname(os.path.abspath(__file__))
BUNDLE_DIR = EXE_DIR
BASE_DIR = EXE_DIR # תמיכה לאחור בקוד שמשתמש ב-BASE_DIR
def _user_data_dir() -> str:
if sys.platform == "darwin":
return os.path.expanduser("~/Library/Application Support/Otzaria AI")
return EXE_DIR
DATA_DIR = _user_data_dir() if getattr(sys, 'frozen', False) else EXE_DIR
CACHE_DIR = os.path.join(DATA_DIR, "hf_cache")
RUNTIME_DIR = os.path.join(DATA_DIR, "runtime")
DB_DIR = os.path.join(DATA_DIR, "db")
# בדיקה אם המודלים ארוזים בתוך ה-EXE או נמצאים בחוץ
# הגדרה קבועה לתיקייה מחוץ ל-EXE כדי שהעלאות דרך הממשק יישמרו לתמיד
MODELS_ZIPS_DIR = os.path.join(DATA_DIR, "models_zips")
if os.path.exists(os.path.join(BUNDLE_DIR, "static")):
STATIC_DIR = os.path.join(BUNDLE_DIR, "static")
else:
STATIC_DIR = os.path.join(DATA_DIR, "static")
LOCAL_MODELS_DIR = os.path.join(DATA_DIR, "local_models")
SETTINGS_PATH = os.path.join(RUNTIME_DIR, "settings.json")
DEFAULT_TOP_K = 20
DEFAULT_MIN_SCORE = 0.0
SEARCH_MIN_RESULTS = 12
SEARCH_TARGET_RESULTS = 40
SEARCH_MAX_RESULTS = 250
SEARCH_INITIAL_CANDIDATES = 160
SEARCH_MAX_CANDIDATES = 5000
SEARCH_CACHE_SIZE = 24
os.makedirs(CACHE_DIR, exist_ok=True)
os.makedirs(RUNTIME_DIR, exist_ok=True)
os.makedirs(DB_DIR, exist_ok=True)
os.makedirs(MODELS_ZIPS_DIR, exist_ok=True)
os.makedirs(LOCAL_MODELS_DIR, exist_ok=True)
os.makedirs(STATIC_DIR, exist_ok=True)
try:
from werkzeug.utils import secure_filename
except ImportError:
def secure_filename(filename): return filename
# הגדרות חלון מילים חכם (Smart Chunking)
IDEAL_CHUNK_WORDS = 50 # המספר שבו מתחילים לחפש סימן פיסוק
MAX_CHUNK_WORDS = 60 # הגבול העליון לחיתוך
DEFAULT_OVERLAP_WORDS = 10 # חפיפה בסיסית בין מקטעים
# =========================
# TEXT TOOLS & HEBREW NLP
# =========================
NIQQUD_RE = re.compile(r"[\u0591-\u05C7]")
HTML_TAG_RE = re.compile(r"<[^>]+>")
NON_WORD_RE = re.compile(r"[^0-9A-Za-z\u0590-\u05FF\"']+")
HEB_LETTERS = "אבגדהוזחטיכלמנסעפצקרשתםןףךץ"
def clean_text(s: str) -> str:
if not s: return ""
s = HTML_TAG_RE.sub(" ", s)
s = NIQQUD_RE.sub("", s)
s = s.replace('״', '"').replace('׳', "'")
s = NON_WORD_RE.sub(" ", s)
return " ".join(s.split())
def strip_niqqud(s: str) -> str:
if not s: return ""
return NIQQUD_RE.sub("", s)
@functools.lru_cache(maxsize=10000)
def hebrew_stem(word: str) -> str:
if len(word) < 4: return word
prefixes = ['וכש', 'וש', 'וה', 'וב', 'ול', 'ומ', 'כש', 'שב', 'שה', 'מש', 'מה', 'ו', 'ה', 'ב', 'ל', 'מ', 'ש', 'כ']
for p in prefixes:
if word.startswith(p) and len(word) > len(p) + 2:
return word[len(p):]
return word
def get_tokens(text: str) -> Set[str]:
words = clean_text(text).split()
return {hebrew_stem(w) for w in words if w}
def fts_query_from_text(q_clean: str) -> str:
toks = [t for t in clean_text(q_clean).split() if len(t) > 1]
return " ".join(toks) if toks else ""
# =========================
# SETTINGS PERSISTENCE
# =========================
def load_settings() -> dict:
if not os.path.exists(SETTINGS_PATH): return {}
try:
with open(SETTINGS_PATH, "r", encoding="utf-8") as f:
return json.load(f) or {}
except: return {}
def save_settings(data: dict) -> None:
try:
with open(SETTINGS_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except: pass
# =========================
# ZIP MODEL SUPPORT
# =========================
def sha256_file(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def ensure_zip_extracted(zip_path: str) -> str:
if not os.path.exists(zip_path): raise FileNotFoundError(f"ZIP לא נמצא: {zip_path}")
zhash = sha256_file(zip_path)[:16]
target_dir = os.path.join(LOCAL_MODELS_DIR, zhash)
marker = os.path.join(target_dir, ".extracted_ok")
if os.path.exists(marker): return target_dir
os.makedirs(target_dir, exist_ok=True)
with zipfile.ZipFile(zip_path, "r") as z:
for member in z.infolist():
member_path = os.path.join(target_dir, member.filename)
abs_target = os.path.abspath(target_dir)
abs_member = os.path.abspath(member_path)
if not abs_member.startswith(abs_target + os.sep) and abs_member != abs_target:
raise RuntimeError("ZIP לא תקין (path traversal).")
z.extractall(target_dir)
with open(marker, "w", encoding="utf-8") as f:
f.write(time.strftime("%Y-%m-%d %H:%M:%S"))
return target_dir
def find_model_files(root_dir: str, edition: str) -> tuple[str, str]:
candidates_vocab = list(Path(root_dir).rglob("vocab.json"))
candidates_emb = list(Path(root_dir).rglob("embeddings_last.npy"))
if not candidates_vocab or not candidates_emb:
raise FileNotFoundError("לא מצאתי בתוך ה-ZIP את vocab.json ו/או embeddings_last.npy.")
prefer_key = f"otzaria_embeddings_{edition}".lower()
def pick(cands):
for p in cands:
if prefer_key in str(p).lower(): return str(p)
return str(cands[0])
return pick(candidates_vocab), pick(candidates_emb)
def resolve_zip_model_path(edition: str, zip_path: str = "") -> str:
if zip_path and os.path.exists(zip_path):
return zip_path
local_zip_path = os.path.join(MODELS_ZIPS_DIR, f"otzaria_embeddings_{edition}.zip")
if os.path.exists(local_zip_path):
return local_zip_path
bundled_zip_path = os.path.join(BUNDLE_DIR, "models_zips", f"otzaria_embeddings_{edition}.zip")
if os.path.exists(bundled_zip_path):
return bundled_zip_path
return zip_path or local_zip_path
def has_model_source_available(cfg: dict) -> bool:
model_source = cfg.get("model_source", "zip")
edition = cfg.get("edition", "v3")
if model_source == "zip":
return os.path.exists(resolve_zip_model_path(edition, cfg.get("zip_path", "")))
return True
# =========================
# DATABASE & STREAMING
# =========================
def get_book_titles(db_path: str) -> Dict[int, str]:
titles = {}
if not os.path.exists(db_path): return titles
try:
con = sqlite3.connect(db_path)
cur = con.execute("SELECT id, title FROM book")
for r in cur: titles[r[0]] = r[1]
con.close()
except Exception as e: print(f"שגיאה בטעינת שמות ספרים: {e}")
return titles
def iter_rows_ordered(db_path: str, chunk_rows: int = 20000):
if not os.path.exists(db_path): raise FileNotFoundError(f"קובץ מסד הנתונים לא נמצא: {db_path}")
con = sqlite3.connect(db_path)
con.row_factory = sqlite3.Row
con.execute("PRAGMA journal_mode=OFF;")
table_name = "line"
try:
con.execute("SELECT 1 FROM lines LIMIT 1")
table_name = "lines"
except: pass
try: con.execute(f"SELECT 1 FROM {table_name} LIMIT 1")
except:
con.close(); return
q = f"SELECT id, bookId, lineIndex, content FROM {table_name} WHERE content IS NOT NULL AND content != '' ORDER BY bookId, lineIndex"
cur = con.execute(q)
while True:
rows = cur.fetchmany(chunk_rows)
if not rows: break
yield rows
con.close()
def iter_rows_ordered_filtered(db_path: str, book_ids: Optional[List[int]] = None, chunk_rows: int = 20000):
if not book_ids:
yield from iter_rows_ordered(db_path, chunk_rows=chunk_rows)
return
if not os.path.exists(db_path): raise FileNotFoundError(f"קובץ מסד הנתונים לא נמצא: {db_path}")
con = sqlite3.connect(db_path)
con.row_factory = sqlite3.Row
con.execute("PRAGMA journal_mode=OFF;")
table_name = "line"
try:
con.execute("SELECT 1 FROM lines LIMIT 1")
table_name = "lines"
except: pass
try: con.execute(f"SELECT 1 FROM {table_name} LIMIT 1")
except:
con.close(); return
placeholders = ",".join(["?"] * len(book_ids))
q = (
f"SELECT id, bookId, lineIndex, content FROM {table_name} "
f"WHERE content IS NOT NULL AND content != '' AND bookId IN ({placeholders}) "
"ORDER BY bookId, lineIndex"
)
cur = con.execute(q, list(book_ids))
while True:
rows = cur.fetchmany(chunk_rows)
if not rows: break
yield rows
con.close()
def iter_chunks(db_path: str, max_chunks: int, ideal_words: int = IDEAL_CHUNK_WORDS, max_words: int = MAX_CHUNK_WORDS, overlap_words: int = DEFAULT_OVERLAP_WORDS, book_ids: Optional[List[int]] = None):
rows_iter = iter_rows_ordered_filtered(db_path, book_ids=book_ids)
buf = []
cur_book = None
produced = 0
# סימני פיסוק שאנחנו מחשיבים כסוף משפט / רעיון
punctuation = ('.', ':', ';', '?', '!')
def flush_chunk(buffer_slice, b_id):
chunk_text = " ".join([w for _, w in buffer_slice])
cln_text = clean_text(chunk_text)
if len(cln_text) > 30:
return {"bookId": b_id, "startLine": buffer_slice[0][0], "endLine": buffer_slice[-1][0], "text": chunk_text, "clean": cln_text}
return None
for batch in rows_iter:
for r in batch:
b_id = r["bookId"]
# אם עברנו לספר חדש, נרוקן את החוצץ
if cur_book is not None and b_id != cur_book:
if buf and len(buf) > 15:
chunk_data = flush_chunk(buf, cur_book)
if chunk_data:
yield chunk_data
produced += 1
if produced >= max_chunks: return
buf = []
cur_book = b_id
txt = str(r["content"]).strip()
if not txt: continue
# מוסיפים מילים לחוצץ תוך שמירה על סימני הפיסוק המקוריים
for w in txt.split():
buf.append((r["lineIndex"], w))
# כל עוד יש לנו מספיק מילים לחפש חיתוך חכם
while len(buf) >= ideal_words:
split_idx = -1
# מחפשים סימן פיסוק בטווח שבין המינימום למקסימום
for i in range(ideal_words - 1, min(len(buf), max_words)):
if buf[i][1].endswith(punctuation):
split_idx = i
break
# אם לא מצאנו סימן פיסוק (למשל בספרות תורנית ישנה), נחתוך במקסימום
if split_idx == -1:
split_idx = min(len(buf) - 1, max_words - 1)
# יצירת המקטע ושליחתו
chunk_slice = buf[:split_idx + 1]
chunk_data = flush_chunk(chunk_slice, cur_book)
if chunk_data:
yield chunk_data
produced += 1
if produced >= max_chunks: return
# חישוב החפיפה (Overlap) - ננסה להתחיל את המקטע הבא מתחילת משפט
stride_start = (split_idx + 1) - overlap_words
if stride_start > 0:
# סריקה לאחור/קדימה כדי למצוא נקודה להתחיל ממנה את החפיפה (אחרי סימן פיסוק)
adjusted_start = stride_start
for i in range(max(1, stride_start - 15), min(len(buf), stride_start + 15)):
if buf[i-1][1].endswith(punctuation):
adjusted_start = i
break
stride_start = adjusted_start
else:
stride_start = 0
# חיתוך החוצץ להמשך העבודה
buf = buf[stride_start:]
# שאריות אחרונות
if buf and len(buf) > 15:
chunk_data = flush_chunk(buf, cur_book)
if chunk_data:
yield chunk_data
# =========================
# ENGINE CORE
# =========================
@dataclass
class LoadedModel:
edition: str
vocab: Dict[str, int]
emb_norm: np.ndarray
idf: np.ndarray
idx_to_word: Dict[int, str]
word_freqs: Dict[str, float]
sorted_vocab: List[str]
@dataclass
class BuiltIndex:
faiss_index: faiss.Index
meta_db_path: str
count: int
class Engine:
def __init__(self):
self.model: Optional[LoadedModel] = None
self.built: Optional[BuiltIndex] = None
self.book_map: Dict[int, str] = {}
self.clean_book_titles: List[Tuple[str, str]] = []
self.library_tree: List[Dict] = []
self.status = {"state": "idle", "msg": "המערכת מוכנה", "progress": 0}
self._lock = threading.RLock()
self._log_seq = 0
self.log_entries: deque = deque(maxlen=500)
self.search_cache: Dict[str, List[Dict]] = {}
self.last_cfg = load_settings()
self._append_log("idle", self.status["msg"], self.status["progress"])
def _append_log(self, state: str, msg: str, progress: Optional[int] = None):
self._log_seq += 1
self.log_entries.append({
"id": self._log_seq,
"ts": time.strftime("%H:%M:%S"),
"state": state,
"msg": msg,
"progress": int(progress if progress is not None else self.status.get("progress", 0)),
})
def _update(self, state, msg, progress):
with self._lock:
self.status = {"state": state, "msg": msg, "progress": int(progress)}
self._append_log(state, msg, progress)
print(f"[{state}] {msg} ({progress}%)")
def log(self, msg: str, state: str = "info", progress: Optional[int] = None):
with self._lock:
self._append_log(state, msg, progress)
print(f"[{state}] {msg}")
def get_logs(self, limit: int = 200) -> List[Dict]:
with self._lock:
return list(self.log_entries)[-max(1, int(limit)):]
def update_book_map(self, book_map: Dict[int, str]):
self.book_map = book_map
# Pre-calculate cleaned titles for fast autocomplete
temp = []
for title in book_map.values():
temp.append((clean_text(title), title))
# Sort by length (shortest match first)
temp.sort(key=lambda x: len(x[0]))
self.clean_book_titles = temp
def _hf_snapshot_offline_first(self, allow_patterns: List[str]) -> str:
try:
return snapshot_download(repo_id=HF_REPO, repo_type="model", cache_dir=CACHE_DIR, allow_patterns=allow_patterns, local_files_only=True)
except Exception:
return snapshot_download(repo_id=HF_REPO, repo_type="model", cache_dir=CACHE_DIR, allow_patterns=allow_patterns, local_files_only=False)
def load_resources(self, db_path: str, edition: str = "v3", model_source: str = "hf", zip_path: str = ""):
if db_path and os.path.exists(db_path):
self.update_book_map(get_book_titles(db_path))
self.library_tree = get_library_tree(db_path)
try:
self._update("downloading", f"טוען מודל {edition} ({model_source})...", 5)
if model_source == "zip":
zip_path = resolve_zip_model_path(edition, zip_path)
extracted_root = ensure_zip_extracted(zip_path)
vocab_path, emb_path = find_model_files(extracted_root, edition)
else:
path = EDITION_PATHS.get(edition, EDITION_PATHS["v3"])
local_dir = self._hf_snapshot_offline_first([f"{path}/vocab.json", f"{path}/embeddings_last.npy"])
base = os.path.join(local_dir, path)
vocab_path = os.path.join(base, "vocab.json")
emb_path = os.path.join(base, "embeddings_last.npy")
with open(vocab_path, "r", encoding="utf-8") as f: meta = json.load(f)
# Use mmap_mode to avoid loading the raw file entirely into RAM before normalization
emb = np.load(emb_path, mmap_mode='r')
norms = np.linalg.norm(emb, axis=1, keepdims=True)
norms[norms == 0] = 1
# This division creates a new in-memory array, but we saved the RAM of the raw 'emb'
emb_norm = emb / norms
vocab = meta["vocab"]
freqs = np.array(meta.get("freqs", []), dtype=np.float64)
if len(freqs) == len(vocab):
idf = np.log((np.sum(freqs) + 1) / (freqs + 1)) + 1
word_freqs = {w: float(freqs[idx]) for w, idx in vocab.items()}
else:
idf = np.ones(len(vocab), dtype=np.float32)
word_freqs = {w: 1.0 for w in vocab.keys()}
idx_to_word = {idx: w for w, idx in vocab.items()}
sorted_vocab = sorted(vocab.keys())
self.model = LoadedModel(edition, vocab, emb_norm, idf.astype(np.float32), idx_to_word, word_freqs, sorted_vocab)
self._update("idle", "המודל נטען בהצלחה", 100)
except Exception as e:
self._update("error", f"שגיאה בטעינת מודל: {e}", 0)
raise
def _stamp(self, edition: str, max_chunks: int, ideal: int, max_w: int, overlap: int, book_ids: Optional[List[int]] = None) -> str:
if book_ids:
normalized = ",".join(str(bid) for bid in sorted(set(book_ids)))
scope_hash = hashlib.sha1(normalized.encode("utf-8")).hexdigest()[:10]
scope = f"B{len(set(book_ids))}_{scope_hash}"
else:
scope = "ALL"
return f"{edition}_{scope}_N{max_chunks}_Ideal{ideal}_Max{max_w}_Overlap{overlap}"
def build_index(self, db_path: str, max_chunks: int, ideal: int = IDEAL_CHUNK_WORDS, max_w: int = MAX_CHUNK_WORDS, overlap: int = DEFAULT_OVERLAP_WORDS, book_ids: Optional[List[int]] = None):
if not self.model or self.status["state"] == "indexing": return
normalized_book_ids = sorted({int(bid) for bid in (book_ids or []) if str(bid).isdigit()})
stamp = self._stamp(self.model.edition, max_chunks, ideal, max_w, overlap, normalized_book_ids)
idx_path = os.path.join(RUNTIME_DIR, f"{stamp}.index")
meta_db_path = os.path.join(RUNTIME_DIR, f"{stamp}.sqlite")
if os.path.exists(idx_path) and os.path.exists(meta_db_path):
self._update("loading", "טוען אינדקס קיים...", 50)
# שימוש ב-Python open כדי לתמוך בנתיבי עברית ב-Windows
with open(idx_path, "rb") as f:
idx_data = np.frombuffer(f.read(), dtype=np.uint8)
idx = faiss.deserialize_index(idx_data)
self.built = BuiltIndex(idx, meta_db_path, idx.ntotal)
if not self.book_map: self.update_book_map(get_book_titles(db_path))
scope_msg = f", {len(normalized_book_ids):,} ספרים" if normalized_book_ids else ""
self._update("ready", f"מוכן לחיפוש ({idx.ntotal:,} רשומות{scope_msg})", 100)
return
if normalized_book_ids:
self._update("indexing", f"מתחיל בבניית אינדקס עבור {len(normalized_book_ids):,} ספרים...", 0)
else:
self._update("indexing", "מתחיל בבניית אינדקס (זה יקח זמן)...", 0)
# שימוש בקובץ זמני ייחודי כדי למנוע התנגשויות בין תהליכים/ת'רדים
temp_db_path = meta_db_path + f".{uuid.uuid4().hex}.tmp"
try:
if os.path.exists(temp_db_path): os.remove(temp_db_path)
except OSError: pass
con = sqlite3.connect(temp_db_path, timeout=30)
con.execute("PRAGMA journal_mode=WAL;")
con.execute("PRAGMA synchronous = NORMAL")
con.execute("DROP TABLE IF EXISTS chunks")
con.execute("DROP TABLE IF EXISTS chunks_fts")
con.execute("CREATE TABLE chunks (rowid INTEGER PRIMARY KEY, bookId INTEGER, startLine INTEGER, endLine INTEGER, text TEXT)")
con.execute("CREATE INDEX idx_book ON chunks(bookId)")
con.execute("CREATE VIRTUAL TABLE chunks_fts USING fts5(text, content='');")
d = self.model.emb_norm.shape[1]
# 🔹 OPTIMIZATION: Use IVF Index for large datasets (>20k chunks)
# This changes complexity from O(N) to O(log N) roughly.
use_ivf = max_chunks > 20000
train_size = 0
if use_ivf:
# FAISS requires at least one training vector per centroid.
# Keep the training sample bounded, but always large enough for nlist.
target_nlist = int(4 * math.sqrt(max_chunks))
train_size = min(max_chunks, max(10000, min(100000, target_nlist * 8)))
nlist = max(1, min(target_nlist, train_size))
quantizer = faiss.IndexFlatIP(d)
# IndexIVFFlat requires training
ivf_index = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_INNER_PRODUCT)
ivf_index.nprobe = 10 # Search 10 nearest clusters (Balance speed/accuracy)
index = faiss.IndexIDMap(ivf_index)
is_trained = False
else:
index = faiss.IndexIDMap(faiss.IndexFlatIP(d))
is_trained = True
vectors, ids, db_buffer, fts_buffer = [], [], [], []
batch_size = 5000
total_processed = 0
start_time = time.time()
for chunk in iter_chunks(db_path, max_chunks, ideal, max_w, overlap, book_ids=normalized_book_ids or None):
vec = self._text_to_vec(chunk["clean"])
if vec is None: continue
current_id = total_processed
vectors.append(vec)
ids.append(current_id)
db_buffer.append((current_id, chunk["bookId"], chunk["startLine"], chunk["endLine"], chunk["text"]))
fts_buffer.append((current_id, chunk["clean"]))
total_processed += 1
if len(vectors) >= batch_size:
if use_ivf and not is_trained and total_processed < train_size:
pct = min(20, int((total_processed / max(train_size, 1)) * 20))
self._update("indexing", f"צובר דגימות לאימון אינדקס IVF ({total_processed:,}/{train_size:,})", pct)
continue
# Train IVF index once enough samples were buffered
if use_ivf and not is_trained:
self._update("indexing", "מאמן אינדקס וקטורי (IVF)...", 5)
# We need to access the sub-index to train
index.index.train(np.vstack(vectors))
is_trained = True
index.add_with_ids(np.vstack(vectors), np.array(ids).astype("int64"))
con.executemany("INSERT INTO chunks VALUES (?,?,?,?,?)", db_buffer)
con.executemany("INSERT INTO chunks_fts(rowid, text) VALUES (?,?)", fts_buffer)
con.commit()
vectors, ids, db_buffer, fts_buffer = [], [], [], []
elapsed = time.time() - start_time
rate = total_processed / (elapsed + 0.1)
pct = min(95, int((total_processed / max_chunks) * 100))
self._update("indexing", f"עובדו {total_processed:,} רשומות ({int(rate)} לשנייה)", pct)
if vectors:
if use_ivf and not is_trained:
# Handle the final buffered training sample before the first add
index.index.train(np.vstack(vectors))
is_trained = True
index.add_with_ids(np.vstack(vectors), np.array(ids).astype("int64"))
con.executemany("INSERT INTO chunks VALUES (?,?,?,?,?)", db_buffer)
con.executemany("INSERT INTO chunks_fts(rowid, text) VALUES (?,?)", fts_buffer)
con.commit()
con.close()
# שימוש ב-Python open כדי לעקוף בעיות קידוד ב-Faiss C++ IO
os.makedirs(RUNTIME_DIR, exist_ok=True)
idx_data = faiss.serialize_index(index)
with open(idx_path, "wb") as f:
f.write(idx_data)
# החלפת הקובץ המקורי בקובץ הזמני
final_db_path = meta_db_path
try:
if os.path.exists(meta_db_path): os.remove(meta_db_path)
os.rename(temp_db_path, meta_db_path)
except OSError:
# במקרה של כישלון (קובץ נעול), נשתמש בקובץ הזמני לריצה הנוכחית
final_db_path = temp_db_path
self.built = BuiltIndex(index, final_db_path, total_processed)
scope_msg = f" עבור {len(normalized_book_ids):,} ספרים" if normalized_book_ids else ""
self._update("ready", f"הבנייה הושלמה בהצלחה{scope_msg}!", 100)
def _text_to_vec(self, text: str):
if not self.model: return None
words = text.split()
if not words: return None
indices = [self.model.vocab[w] for w in words if w in self.model.vocab]
if not indices: return None
idfs = self.model.idf[indices]
vecs = self.model.emb_norm[indices]
weighted = vecs * idfs[:, None]
avg_vec = np.sum(weighted, axis=0)
norm = np.linalg.norm(avg_vec)
if norm < 1e-9: return None
return avg_vec / norm
# 🔹 SPELL CHECK ALGORITHM (NORVIG)
def check_spelling(self, query: str) -> Optional[str]:
if not self.model or not query: return None
words = clean_text(query).split()
corrected = []
changed = False
for w in words:
if w in self.model.word_freqs or len(w) <= 2:
corrected.append(w)
else:
c = self._correct_word(w)
corrected.append(c)
if c != w: changed = True
return " ".join(corrected) if changed else None
def _correct_word(self, word: str) -> str:
candidates = (self._known([word]) or self._known(self._edits1(word)) or [word])
return max(candidates, key=lambda w: self.model.word_freqs.get(w, 0))
def _known(self, words):
return set(w for w in words if w in self.model.word_freqs)
def _edits1(self, word):
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1]
replaces = [L + c + R[1:] for L, R in splits if R for c in HEB_LETTERS]
inserts = [L + c + R for L, R in splits for c in HEB_LETTERS]
return set(deletes + transposes + replaces + inserts)
# 🔹 QUERY EXPANSION ALGORITHM
def _build_expanded_fts_query(self, q_clean: str, top_synonyms: int = 2, threshold: float = 0.7) -> str:
if not self.model or not self.model.idx_to_word:
return fts_query_from_text(q_clean)
tokens = [t for t in q_clean.split() if len(t) > 1]
if not tokens: return ""
expanded_parts = []
for t in tokens:
synonyms = [t]
if t in self.model.vocab:
idx = self.model.vocab[t]
vec = self.model.emb_norm[idx]
sims = np.dot(self.model.emb_norm, vec)
best_indices = np.argsort(sims)[-(top_synonyms + 2):][::-1]
for bi in best_indices:
if bi != idx and sims[bi] > threshold:
synonyms.append(self.model.idx_to_word[bi])
part = "(" + " OR ".join(f'"{s}"' for s in synonyms) + ")"
expanded_parts.append(part)
return " ".join(expanded_parts)
def get_expanded_terms(self, q_clean: str, top_synonyms: int = 2, threshold: float = 0.7) -> list[str]:
if not self.model or not self.model.idx_to_word:
return [t for t in q_clean.split() if len(t) > 1]
tokens = [t for t in q_clean.split() if len(t) > 1]
expanded = set(tokens) # נשמור את המילים המקוריות
for t in tokens:
if t in self.model.vocab:
idx = self.model.vocab[t]
vec = self.model.emb_norm[idx]
sims = np.dot(self.model.emb_norm, vec)
# מציאת המילים הקרובות ביותר (וקטורית)
best_indices = np.argsort(sims)[-(top_synonyms + 2):][::-1]
for bi in best_indices:
if bi != idx and sims[bi] > threshold:
expanded.add(self.model.idx_to_word[bi])
return list(expanded)
def _fts_candidates(self, q_clean: str, limit: int, book_filter: Optional[List[int]] = None) -> List[Tuple[int, float]]:
if not self.built: return []
fts_q = self._build_expanded_fts_query(q_clean)
if not fts_q: return []
con = sqlite3.connect(self.built.meta_db_path, timeout=30)
con.row_factory = sqlite3.Row
try:
if book_filter:
# סינון ברמת ה-SQL: חיפוש רק בתוך הספר הרלוונטי
placeholders = ",".join(["?"] * len(book_filter))
sql = f"SELECT f.rowid, bm25(f) AS bm FROM chunks_fts f JOIN chunks c ON f.rowid = c.rowid WHERE c.bookId IN ({placeholders}) AND f.chunks_fts MATCH ? LIMIT ?"
params = list(book_filter) + [fts_q, int(limit)]
else:
sql = "SELECT rowid, bm25(chunks_fts) AS bm FROM chunks_fts WHERE chunks_fts MATCH ? LIMIT ?"
params = (fts_q, int(limit))
rows = con.execute(sql, params).fetchall()
return [(int(r["rowid"]), float(r["bm"])) for r in rows]
except: return []
finally: con.close()
def search(self, query: str, book_filter: Optional[List[int]] = None, top_k: Optional[int] = 20):
if not self.model or not self.built: return []
q_clean = clean_text(query)
q_vec = self._text_to_vec(q_clean)
if q_vec is None: return []
requested_k = None if not top_k or top_k <= 0 else int(top_k)
index_count = int(self.built.count or 0)
# 1) מועמדים וקטוריים עם סינון מוקדם (Pre-filtering)
search_params = None
if book_filter:
con = sqlite3.connect(self.built.meta_db_path, timeout=30)
placeholders = ",".join(["?"] * len(book_filter))
# שליפת כל ה-rowids השייכים לספרים שנבחרו (בסדר ממוין לביצועים אופטימליים ב-FAISS)
res = con.execute(f"SELECT rowid FROM chunks WHERE bookId IN ({placeholders}) ORDER BY rowid", book_filter).fetchall()
con.close()
target_ids = np.array([r[0] for r in res], dtype=np.int64)
search_space_count = int(len(target_ids))
if len(target_ids) == 0:
return [] # אין מקטעים מאונדקסים עבור הספרים שנבחרו
selector = faiss.IDSelectorArray(target_ids)
# שימוש ב-downcast_index הכרחי כדי ש-Python יזהה שהאינדקס הפנימי הוא מסוג IVF
# ויאפשר יצירת SearchParametersIVF תקינים.
underlying_index = faiss.downcast_index(self.built.faiss_index.index)
if isinstance(underlying_index, faiss.IndexIVF):
search_params = faiss.SearchParametersIVF(sel=selector, nprobe=underlying_index.nprobe)
else:
search_params = faiss.SearchParameters(sel=selector)
# כשמסננים מראש, אין צורך ב-K ענקי כי כל התוצאות שיחזרו הן מהספרים הנכונים
vec_candidates_k = search_space_count if requested_k is None else max(requested_k * 4, 100)
else:
search_space_count = index_count
vec_candidates_k = index_count if requested_k is None else max(requested_k * 20, 200)
if search_space_count <= 0:
return []
scores, ids = self.built.faiss_index.search(np.array([q_vec]), vec_candidates_k, params=search_params)
vec_found_ids = [int(i) for i in ids[0] if i >= 0]
fts_candidates_k = search_space_count if requested_k is None else max(requested_k * 20, 200)
fts_rows = self._fts_candidates(q_clean, fts_candidates_k, book_filter=book_filter)
fts_found_ids = [rid for rid, _ in fts_rows]
union_ids = list(set(vec_found_ids + fts_found_ids))
if not union_ids: return []
con = sqlite3.connect(self.built.meta_db_path, timeout=30)
con.row_factory = sqlite3.Row
placeholders = ",".join(["?"] * len(union_ids))
sql = f"SELECT rowid, bookId, startLine, endLine, text FROM chunks WHERE rowid IN ({placeholders})"
params: List = list(union_ids)
if book_filter:
placeholders_books = ",".join(["?"] * len(book_filter))
sql += f" AND bookId IN ({placeholders_books})"
params.extend(book_filter)
rows = con.execute(sql, params).fetchall()
con.close()
vec_scores = {int(fid): float(scr) for fid, scr in zip(ids[0], scores[0]) if int(fid) >= 0}
fts_bm = {rid: bm for rid, bm in fts_rows}
def bm_to_rel(bm: Optional[float]) -> float:
return 1.0 / (1.0 + max(0.0, bm)) if bm is not None else 0.0
q_tokens = get_tokens(q_clean)
cfg = self.last_cfg or {}
w_vec = float(cfg.get("w_vec", 0.35))
w_bm = float(cfg.get("w_bm", 0.25))
w_overlap = float(cfg.get("w_overlap", 0.25))
w_phrase = float(cfg.get("w_phrase", 0.10))
w_proximity = float(cfg.get("w_proximity", 0.05))
total_weight = w_vec + w_bm + w_overlap + w_phrase + w_proximity
if total_weight == 0: total_weight = 1
results = []
for r in rows:
rid = int(r["rowid"])
chunk_txt = r["text"]
chunk_clean = clean_text(chunk_txt)
chunk_tokens = get_tokens(chunk_clean)
chunk_words = chunk_clean.split()
base_vec = vec_scores.get(rid, 0.0)
bm_rel = bm_to_rel(fts_bm.get(rid))
intersection = len(q_tokens & chunk_tokens)
overlap = (intersection / len(q_tokens)) if q_tokens else 0.0
phrase = 1.0 if (q_clean and q_clean in chunk_clean) else 0.0
proximity = 0.0
if intersection > 1 and q_tokens:
# חישוב קרבה עם דעיכה לחזרות (Decay for repetitions)
# 1st: 100%, others from config
d2 = float(cfg.get("decay_2", 0.75))
d3 = float(cfg.get("decay_3", 0.35))
d4 = float(cfg.get("decay_4", 0.05))
decay_factors = [1.0, d2, d3, d4]
found_indices = []
effective_count = 0.0
for qw in q_tokens:
qw_indices = [i for i, cw in enumerate(chunk_words) if hebrew_stem(cw) == qw]
if qw_indices:
found_indices.extend(qw_indices)
for k in range(len(qw_indices)):
if k < len(decay_factors):
effective_count += decay_factors[k]
if found_indices:
span = max(found_indices) - min(found_indices)
density = effective_count / (span + 1)
proximity = min(density, 1.0)
final_score = ((base_vec * w_vec) + (bm_rel * w_bm) + (overlap * w_overlap) + (phrase * w_phrase) + (proximity * w_proximity)) / total_weight
book_title = self.book_map.get(int(r["bookId"]), f"ספר {int(r['bookId'])}")
results.append({
"score": float(final_score),
"text": chunk_txt,
"source": f"{book_title}, שורה {int(r['startLine'])}",
"book_id": int(r["bookId"]),
"line_index": int(r["startLine"]),
"end_line": int(r["endLine"]),
"book_title": book_title,
"features": {"vec": float(base_vec), "bm": float(bm_rel), "overlap": float(overlap), "phrase": float(phrase), "prox": float(proximity)}
})
results.sort(key=lambda x: x["score"], reverse=True)
return results if requested_k is None else results[:requested_k]
def get_indexed_book_ids(self) -> Set[int]:
"""מחזיר את רשימת ה-IDs של הספרים שקיימים באינדקס בפועל"""
if not self.built or not os.path.exists(self.built.meta_db_path): return set()
try:
con = sqlite3.connect(self.built.meta_db_path)
# בדיקה מהירה בטבלת chunks (יש עליה אינדקס)
cur = con.execute("SELECT DISTINCT bookId FROM chunks")
ids = {r[0] for r in cur}
con.close()
return ids
except: return set()
ENGINE = Engine()
# =========================
# FLASK WEB APP
# =========================
app = Flask(__name__)
app.secret_key = "otzaria_ai_secret_v5"
BASE_DIR = Path(__file__).parent
HTML_TEMPLATE = (BASE_DIR / "app_ai.html").read_text(encoding="utf-8")
# =========================
# HELPER FILTERS
# =========================
def close_html_tags(html: str) -> str:
"""סוגר תגיות HTML פתוחות ומסיר תגיות חתוכות בסוף המחרוזת למניעת שיבוש בעיצוב הדף."""
# הסרת תגית שמתחילה בסוף המחרוזת אך לא נסגרה (למשל "טקסט <a")
html = re.sub(r'<[^>]*$', '', html)
# מציאת כל התגיות (פתיחה, סגירה, וסגירה עצמית)
tag_regex = re.compile(r'<(/?)([a-zA-Z0-9]+)[^>]*(/?)>')
stack = []
void_tags = {'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'}
for match in tag_regex.finditer(html):
is_closing = match.group(1) == '/'
tag_name = match.group(2).lower()
is_self_closing = match.group(3) == '/'
if tag_name in void_tags or is_self_closing:
continue
if is_closing:
if stack and stack[-1] == tag_name:
stack.pop()
else:
stack.append(tag_name)
# סגירת כל התגיות שנותרו פתוחות בסדר הפוך
while stack:
html += f'</{stack.pop()}>'
return html
def highlight_text(text, query):
text = close_html_tags(text)
if not query: return text
q_words = [hebrew_stem(w) for w in clean_text(query).split() if len(w) > 1]
if not q_words: return text
patterns = [r'(?:^|[\s\"\'\-])([ו|מ|ש|ה|ל|ב|כ]?' + re.escape(w) + r')(?=[\s\"\'\.\,\-]|$)' for w in q_words]
combined_pattern = "|".join(patterns)
def replacer(match):
full_match = match.group(0)
word_match = re.search(r'[א-ת]+', full_match)
if word_match: return full_match.replace(word_match.group(0), f'<mark>{word_match.group(0)}</mark>')
return full_match
try: return re.sub(combined_pattern, replacer, text)
except: return text
def highlight_text(text, query):
text = close_html_tags(text)
if not query: return text
q_words = [hebrew_stem(w) for w in clean_text(query).split() if len(w) > 1]
if not q_words: return text
prefixes = "ובשהלמכ"
token_pattern = "|".join(re.escape(w) for w in sorted(set(q_words), key=len, reverse=True))
combined_pattern = re.compile(
rf"(^|[\s\"'\-])([{prefixes}]?(?:{token_pattern}))(?=[\s\"'\.\,\-]|$)"
)
def highlight_plain_segment(segment: str) -> str:
normalized_chars = []
index_map = []
for idx, ch in enumerate(segment):
normalized = strip_niqqud(ch)
if not normalized:
continue
normalized_chars.append(normalized)
index_map.extend([idx] * len(normalized))
normalized_segment = "".join(normalized_chars)
if not normalized_segment:
return segment
ranges = []
for match in combined_pattern.finditer(normalized_segment):
start_norm, end_norm = match.span(2)
if start_norm >= len(index_map) or end_norm <= 0:
continue
start_idx = index_map[start_norm]
end_idx = index_map[end_norm - 1] + 1
ranges.append((start_idx, end_idx))
if not ranges:
return segment
merged = []
for start_idx, end_idx in ranges:
if merged and start_idx <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], end_idx))
else:
merged.append((start_idx, end_idx))
parts = []
last_idx = 0
for start_idx, end_idx in merged:
parts.append(segment[last_idx:start_idx])
parts.append(f"<mark>{segment[start_idx:end_idx]}</mark>")
last_idx = end_idx
parts.append(segment[last_idx:])
return "".join(parts)
try:
parts = re.split(r"(<[^>]+>)", text)
for i, part in enumerate(parts):
if part and not part.startswith("<"):
parts[i] = highlight_plain_segment(part)
return "".join(parts)