Mazenbs commited on
Commit
6cfbbda
·
verified ·
1 Parent(s): 216dd77

Update embeddingonnx.py

Browse files
Files changed (1) hide show
  1. embeddingonnx.py +35 -74
embeddingonnx.py CHANGED
@@ -2,36 +2,36 @@ import onnxruntime as ort
2
  import re
3
  import numpy as np
4
  from transformers import AutoTokenizer
 
 
5
 
6
  # ==============================
7
- # إعداد النموذج والتوكنيزر
8
  # ==============================
9
  MODEL_PATH = "lib/intfloat_multilingual-e5-small_merged_int8.onnx"
10
  TOKENIZER_PATH = "./lib/"
11
 
12
- # جلسة ONNX سريعة (تحسينات مهمة)
 
 
 
 
13
  session = ort.InferenceSession(
14
  MODEL_PATH,
15
  providers=['CPUExecutionProvider'],
16
- sess_options=ort.SessionOptions()
17
  )
18
 
19
- # تعطيل التحقق من المخرجات (يوفر وقت)
20
- session.disable_fallback()
21
-
22
- # تقليل عدد الـ threads = أسرع على الأجهزة الضعيفة
23
- session.set_providers(['CPUExecutionProvider'],
24
- provider_options=[{"intra_op_num_threads": 1}])
25
-
26
- # تحميل التوكنيزر
27
- tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, local_files_only=True)
28
-
29
 
30
  # ==============================
31
- # دوال مساعدة
32
  # ==============================
 
33
  def normalize_arabic(text: str) -> str:
34
- text = re.sub(r'[ًٌٍَُِّْـ]', '', text)
 
35
  text = re.sub(r'[إأآ]', 'ا', text)
36
  text = re.sub(r'ى', 'ي', text)
37
  text = re.sub(r'ؤ', 'و', text)
@@ -41,76 +41,37 @@ def normalize_arabic(text: str) -> str:
41
  text = re.sub(r'\s+', ' ', text)
42
  return text.strip()
43
 
44
-
45
- def split_sentences(text: str):
46
- return [
47
- s.strip() for s in
48
- re.split(r'[.\n:؛؟!]', text)
49
- if len(s.strip()) > 0
50
- ]
51
-
52
-
53
- # ==============================
54
- # النسخة المحسنة جداً لتحويل النص إلى Embedding
55
- # ==============================
56
- def text_to_embedding(text: str, normalize: bool = True) -> np.ndarray:
57
- if not text.strip():
58
- return None
59
-
60
- if normalize:
61
- text = normalize_arabic(text)
62
-
63
- sentences = split_sentences(text)
64
- if not sentences:
65
- return None
66
-
67
- # ⚡ تجميع كل الجمل في batch واحد → أسرع ×6
68
- batch_inputs = tokenizer(
69
- ["passage: " + s for s in sentences],
70
- return_tensors="np",
71
- truncation=True,
72
- padding=True,
73
- max_length=256
74
- )
75
-
76
- # تشغيل النموذج دفعة واحدة
77
- ort_outs = session.run(None, dict(batch_inputs))
78
- vectors = ort_outs[1] # (num_sentences, 384)
79
-
80
- # تطبيع كل متجه دفعة واحدة (أسرع)
81
- norms = np.linalg.norm(vectors, axis=1, keepdims=True) + 1e-10
82
- vectors = vectors / norms
83
-
84
- # متوسط embeddings
85
- embedding = vectors.mean(axis=0)
86
-
87
- # تطبيع نهائي
88
- embedding = embedding / (np.linalg.norm(embedding) + 1e-10)
89
-
90
- return embedding.astype(np.float32)
91
-
92
-
93
  # ==============================
94
- # نموذج البحث optimized
95
  # ==============================
96
  def query_to_embedding(query: str, normalize: bool = True) -> np.ndarray:
97
- print(f"search : {query}")
98
- if not query.strip():
99
  return None
100
-
 
 
101
  if normalize:
102
  query = normalize_arabic(query)
103
-
 
104
  inputs = tokenizer(
105
  "query: " + query,
106
  return_tensors="np",
107
  truncation=True,
108
  padding=True,
109
- max_length=256
 
 
110
  )
111
-
 
112
  ort_outs = session.run(None, dict(inputs))
113
  vector = ort_outs[1][0]
114
-
115
- vector = vector / (np.linalg.norm(vector) + 1e-10)
116
- return vector.astype(np.float32)
 
 
 
 
 
2
  import re
3
  import numpy as np
4
  from transformers import AutoTokenizer
5
+ from functools import lru_cache
6
+ import threading
7
 
8
  # ==============================
9
+ # إعداد النموذج والتوكنيزر - محسّن
10
  # ==============================
11
  MODEL_PATH = "lib/intfloat_multilingual-e5-small_merged_int8.onnx"
12
  TOKENIZER_PATH = "./lib/"
13
 
14
+ # تحسين جلسة ONNX
15
+ session_options = ort.SessionOptions()
16
+ session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
17
+ session_options.optimized_model_filepath = "optimized_model.onnx"
18
+
19
  session = ort.InferenceSession(
20
  MODEL_PATH,
21
  providers=['CPUExecutionProvider'],
22
+ sess_options=session_options
23
  )
24
 
25
+ # تحميل التوكنيزر مع التخزين المؤقت
26
+ tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, local_files_only=True, use_fast=True)
 
 
 
 
 
 
 
 
27
 
28
  # ==============================
29
+ # دوال مساعدة - محسّنة
30
  # ==============================
31
+ @lru_cache(maxsize=1024)
32
  def normalize_arabic(text: str) -> str:
33
+ """تطبيع النص العربي مع تخزين مؤقت"""
34
+ text = re.sub(r'[ًٌٍَُِّْـ]', '', text)
35
  text = re.sub(r'[إأآ]', 'ا', text)
36
  text = re.sub(r'ى', 'ي', text)
37
  text = re.sub(r'ؤ', 'و', text)
 
41
  text = re.sub(r'\s+', ' ', text)
42
  return text.strip()
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  # ==============================
45
+ # دالة Embedding المحسّنة
46
  # ==============================
47
  def query_to_embedding(query: str, normalize: bool = True) -> np.ndarray:
48
+ """تحويل الاستعلام إلى embedding بكفاءة عالية"""
49
+ if not query or not query.strip():
50
  return None
51
+
52
+ query = query.strip()
53
+
54
  if normalize:
55
  query = normalize_arabic(query)
56
+
57
+ # استخدام التوكنيز مع المعلمات المثلى
58
  inputs = tokenizer(
59
  "query: " + query,
60
  return_tensors="np",
61
  truncation=True,
62
  padding=True,
63
+ max_length=256,
64
+ return_attention_mask=True,
65
+ return_token_type_ids=False
66
  )
67
+
68
+ # تشغيل النموذج
69
  ort_outs = session.run(None, dict(inputs))
70
  vector = ort_outs[1][0]
71
+
72
+ # تطبيع المتجه بكفاءة
73
+ norm = np.linalg.norm(vector)
74
+ if norm > 0:
75
+ vector = vector / norm
76
+
77
+ return vector.astype(np.float32)