nlp4j-llm-embedding-e5 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,173 @@
1
+ # e5_model.py
2
+
3
+ import time
4
+ import threading
5
+ from sentence_transformers import SentenceTransformer, util
6
+
7
+ MODEL_NAME = "intfloat/multilingual-e5-large"
8
+
9
+ _model = None
10
+ _model_lock = threading.Lock()
11
+
12
+
13
+ def get_model():
14
+ global _model
15
+
16
+ if _model is None:
17
+ with _model_lock:
18
+ if _model is None:
19
+ start = time.time()
20
+
21
+ print(f"[nlp4j-embedding] Loading model: {MODEL_NAME}", flush=True)
22
+ print("[nlp4j-embedding] If this is the first run, model files may be downloaded.", flush=True)
23
+ print("[nlp4j-embedding] Loading SentenceTransformer...", flush=True)
24
+
25
+ _model = SentenceTransformer(MODEL_NAME)
26
+
27
+ print("[nlp4j-embedding] Running warmup embedding...", flush=True)
28
+ _model.encode(["passage: test"], normalize_embeddings=True)
29
+
30
+ elapsed = time.time() - start
31
+ print(f"[nlp4j-embedding] Model loaded successfully. elapsed={elapsed:.2f} sec", flush=True)
32
+
33
+ return _model
34
+
35
+
36
+ def is_model_loaded() -> bool:
37
+ """
38
+ モデルがロード済みかどうかを確認する。
39
+
40
+ Returns:
41
+ bool: モデルがロード済みならTrue、未ロードならFalse
42
+ """
43
+ return _model is not None
44
+
45
+
46
+ def ensure_e5_prefix(text: str, text_type: str = "passage") -> str:
47
+ if text is None:
48
+ return ""
49
+
50
+ if not isinstance(text, str):
51
+ text = str(text)
52
+
53
+ if text_type == "none":
54
+ return text
55
+
56
+ if text.startswith("passage:") or text.startswith("query:"):
57
+ return text
58
+
59
+ if text_type == "query":
60
+ return "query: " + text
61
+
62
+ return "passage: " + text
63
+
64
+
65
+ def embed_texts(
66
+ texts,
67
+ text_type: str = "passage",
68
+ normalize_embeddings: bool = True,
69
+ max_length: int | None = None
70
+ ):
71
+ model = get_model()
72
+ e5_texts = [ensure_e5_prefix(text, text_type=text_type) for text in texts]
73
+
74
+ old_max_seq_length = getattr(model, "max_seq_length", None)
75
+
76
+ if max_length is not None:
77
+ model.max_seq_length = max_length
78
+
79
+ try:
80
+ start = time.time()
81
+ embeddings = model.encode(
82
+ e5_texts,
83
+ normalize_embeddings=normalize_embeddings
84
+ )
85
+ elapsed = time.time() - start
86
+
87
+ return embeddings.tolist(), elapsed
88
+ finally:
89
+ if old_max_seq_length is not None:
90
+ model.max_seq_length = old_max_seq_length
91
+
92
+
93
+ def embed_text(
94
+ text,
95
+ text_type: str = "passage",
96
+ normalize_embeddings: bool = True,
97
+ max_length: int | None = None
98
+ ):
99
+ vectors, elapsed = embed_texts(
100
+ [text],
101
+ text_type=text_type,
102
+ normalize_embeddings=normalize_embeddings,
103
+ max_length=max_length
104
+ )
105
+ return vectors[0], elapsed
106
+
107
+
108
+ def count_tokens(text, text_type: str = "passage") -> int:
109
+ model = get_model()
110
+ tokenizer = getattr(model, "tokenizer", None)
111
+
112
+ if tokenizer is None:
113
+ return 0
114
+
115
+ e5_text = ensure_e5_prefix(text, text_type=text_type)
116
+
117
+ encoded = tokenizer(
118
+ e5_text,
119
+ truncation=False,
120
+ add_special_tokens=True,
121
+ return_attention_mask=False,
122
+ return_token_type_ids=False
123
+ )
124
+ return len(encoded["input_ids"])
125
+
126
+
127
+ def semantic_search(query, corpus_texts, top_k=10):
128
+ model = get_model()
129
+
130
+ query_text = ensure_e5_prefix(query, text_type="query")
131
+ passage_texts = [
132
+ ensure_e5_prefix(text, text_type="passage")
133
+ for text in corpus_texts
134
+ ]
135
+
136
+ query_embedding = model.encode(
137
+ [query_text],
138
+ normalize_embeddings=True
139
+ )[0]
140
+
141
+ corpus_embeddings = model.encode(
142
+ passage_texts,
143
+ normalize_embeddings=True
144
+ )
145
+
146
+ return util.semantic_search(
147
+ query_embedding,
148
+ corpus_embeddings,
149
+ top_k=top_k
150
+ )[0]
151
+
152
+
153
+ def cos_sim(text1, text2, text_type: str = "none"):
154
+ """
155
+ 2つのテキスト間のコサイン類似度を計算する。
156
+
157
+ Args:
158
+ text1: 1つ目のテキスト
159
+ text2: 2つ目のテキスト
160
+ text_type: E5 prefix の種類 ("passage", "query", "none")
161
+
162
+ Returns:
163
+ float: コサイン類似度 (-1.0 ~ 1.0)
164
+ """
165
+ vectors, _ = embed_texts(
166
+ [text1, text2],
167
+ text_type=text_type,
168
+ normalize_embeddings=True
169
+ )
170
+ score = util.cos_sim(vectors[0], vectors[1])
171
+ return score.item()
172
+
173
+ # Made with Bob
@@ -0,0 +1,296 @@
1
+ # coding: utf-8
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+
7
+ from tqdm import tqdm
8
+
9
+ try:
10
+ import psutil
11
+ except ImportError:
12
+ psutil = None
13
+
14
+ # e5_model から関数をインポート
15
+ from . import e5_model
16
+
17
+
18
+ # ===== Memory helpers =====
19
+
20
+ def get_memory_mb():
21
+ if psutil is None:
22
+ return None
23
+ process = psutil.Process(os.getpid())
24
+ return process.memory_info().rss / 1024 / 1024
25
+
26
+
27
+ # ===== JSONL processing =====
28
+
29
+ def flush_batch(
30
+ batch,
31
+ outfile,
32
+ text_attr,
33
+ vector_attr,
34
+ text_type,
35
+ max_length,
36
+ check_token_count,
37
+ verbose
38
+ ):
39
+ """
40
+ batch 内の JSON object に embedding 結果を追加して outfile に書き出す。
41
+ """
42
+ if not batch:
43
+ return 0, 0.0
44
+
45
+ texts = []
46
+ text_indexes = []
47
+
48
+ for i, item in enumerate(batch):
49
+ data = item["data"]
50
+ text = data.get(text_attr)
51
+
52
+ if text is not None and text != "":
53
+ texts.append(text)
54
+ text_indexes.append(i)
55
+
56
+ embedded_count = 0
57
+ total_embed_time = 0.0
58
+
59
+ if texts:
60
+ if check_token_count:
61
+ for text in texts:
62
+ token_count = e5_model.count_tokens(text, text_type=text_type)
63
+ if token_count > max_length:
64
+ print(
65
+ f"[WARN][TOKEN_LIMIT] token_count={token_count} "
66
+ f"max_length={max_length} truncated=True"
67
+ )
68
+
69
+ vectors, embed_time = e5_model.embed_texts(
70
+ texts,
71
+ text_type=text_type,
72
+ normalize_embeddings=True,
73
+ max_length=max_length
74
+ )
75
+
76
+ total_embed_time += embed_time
77
+ embedded_count += len(vectors)
78
+
79
+ for idx, vector in zip(text_indexes, vectors):
80
+ batch[idx]["data"][vector_attr] = vector
81
+
82
+ if verbose:
83
+ print(
84
+ f"batch_size={len(texts)} "
85
+ f"embed_time={embed_time:.6f} sec"
86
+ )
87
+
88
+ for item in batch:
89
+ json.dump(item["data"], outfile, ensure_ascii=False)
90
+ outfile.write("\n")
91
+
92
+ return embedded_count, total_embed_time
93
+
94
+
95
+ def process_jsonl(
96
+ input_file,
97
+ output_file,
98
+ text_attr,
99
+ vector_attr,
100
+ text_type="passage",
101
+ batch_size=32,
102
+ max_length=512,
103
+ check_token_count=False,
104
+ verbose=False
105
+ ):
106
+ """
107
+ JSONLファイルを読み込み、指定された属性のテキストを embedding し、
108
+ 結果を vector_attr に追加して新しい JSONL として書き出す。
109
+ """
110
+
111
+ initial_memory = get_memory_mb()
112
+
113
+ embed_times_per_item = []
114
+
115
+ total_embedded = 0
116
+ total_records = 0
117
+
118
+ # tqdm の total 表示用。巨大ファイルではここにも時間がかかるが、以前の仕様を維持する。
119
+ with open(input_file, "r", encoding="utf-8") as infile:
120
+ total_lines = sum(1 for _ in infile)
121
+
122
+ batch = []
123
+
124
+ with open(input_file, "r", encoding="utf-8") as infile, \
125
+ open(output_file, "w", encoding="utf-8") as outfile:
126
+
127
+ for line_no, line in enumerate(
128
+ tqdm(infile, desc="Processing lines", total=total_lines),
129
+ start=1
130
+ ):
131
+ line = line.strip()
132
+ if not line:
133
+ continue
134
+
135
+ try:
136
+ data = json.loads(line)
137
+ except json.JSONDecodeError as e:
138
+ raise ValueError(f"Invalid JSON at line {line_no}: {e}") from e
139
+
140
+ batch.append({
141
+ "line_no": line_no,
142
+ "data": data
143
+ })
144
+ total_records += 1
145
+
146
+ # embedding 対象の件数ベースで batch_size を見る
147
+ embeddable_count = sum(
148
+ 1 for item in batch
149
+ if item["data"].get(text_attr) is not None
150
+ and item["data"].get(text_attr) != ""
151
+ )
152
+
153
+ if embeddable_count >= batch_size:
154
+ embedded_count, embed_time = flush_batch(
155
+ batch=batch,
156
+ outfile=outfile,
157
+ text_attr=text_attr,
158
+ vector_attr=vector_attr,
159
+ text_type=text_type,
160
+ max_length=max_length,
161
+ check_token_count=check_token_count,
162
+ verbose=verbose
163
+ )
164
+
165
+ if embedded_count > 0:
166
+ embed_times_per_item.append(embed_time / embedded_count)
167
+
168
+ total_embedded += embedded_count
169
+ batch = []
170
+
171
+ # 残りを処理
172
+ if batch:
173
+ embedded_count, embed_time = flush_batch(
174
+ batch=batch,
175
+ outfile=outfile,
176
+ text_attr=text_attr,
177
+ vector_attr=vector_attr,
178
+ text_type=text_type,
179
+ max_length=max_length,
180
+ check_token_count=check_token_count,
181
+ verbose=verbose
182
+ )
183
+
184
+ if embedded_count > 0:
185
+ embed_times_per_item.append(embed_time / embedded_count)
186
+
187
+ total_embedded += embedded_count
188
+
189
+ final_memory = get_memory_mb()
190
+
191
+ # モデル情報を取得(モデルがロード済みの場合のみ)
192
+ if e5_model.is_model_loaded():
193
+ model = e5_model.get_model()
194
+ device = model.device if hasattr(model, 'device') else 'unknown'
195
+ else:
196
+ device = "not loaded"
197
+
198
+ print("\n" + "=" * 60)
199
+ print("処理統計情報")
200
+ print("=" * 60)
201
+ print(f"入力レコード数: {total_records}")
202
+ print(f"Embedding 実行件数: {total_embedded}")
203
+ print(f"text_attr: {text_attr}")
204
+ print(f"vector_attr: {vector_attr}")
205
+ print(f"text_type: {text_type}")
206
+ print(f"batch_size: {batch_size}")
207
+ print(f"max_length: {max_length}")
208
+ print(f"device: {device}")
209
+
210
+ if embed_times_per_item:
211
+ avg_embed = sum(embed_times_per_item) / len(embed_times_per_item)
212
+ print(f"埋め込み処理の平均処理時間/件: {avg_embed:.6f} 秒")
213
+
214
+ if initial_memory is not None and final_memory is not None:
215
+ print(f"初期メモリ使用量: {initial_memory:.2f} MB")
216
+ print(f"最終メモリ使用量: {final_memory:.2f} MB")
217
+ print(f"メモリ増加量: {final_memory - initial_memory:.2f} MB")
218
+ else:
219
+ print("メモリ使用量: psutil がインストールされていないため未計測")
220
+
221
+ print("=" * 60)
222
+
223
+
224
+ # ===== CLI =====
225
+
226
+ def main():
227
+ parser = argparse.ArgumentParser(
228
+ description="JSONLファイルを読み込み、指定された属性を E5 embedding し、結果を新しいJSONLに書き出します。"
229
+ )
230
+
231
+ parser.add_argument(
232
+ "input_file",
233
+ help="入力JSONLファイルのパス"
234
+ )
235
+ parser.add_argument(
236
+ "output_file",
237
+ help="出力JSONLファイルのパス"
238
+ )
239
+ parser.add_argument(
240
+ "--text-attr",
241
+ default="text",
242
+ help="テキストを取得する属性名(デフォルト: text)"
243
+ )
244
+ parser.add_argument(
245
+ "--vector-attr",
246
+ default="vector",
247
+ help="ベクトルをセットする属性名(デフォルト: vector)"
248
+ )
249
+ parser.add_argument(
250
+ "--text-type",
251
+ choices=["passage", "query", "none"],
252
+ default="passage",
253
+ help="E5 prefix の種類。文書は passage、検索クエリは query、prefix なしは none(デフォルト: passage)"
254
+ )
255
+ parser.add_argument(
256
+ "--batch-size",
257
+ type=int,
258
+ default=32,
259
+ help="Embedding のバッチサイズ(デフォルト: 32)"
260
+ )
261
+ parser.add_argument(
262
+ "--max-length",
263
+ type=int,
264
+ default=512,
265
+ help="tokenizer の max_length(デフォルト: 512)"
266
+ )
267
+ parser.add_argument(
268
+ "--check-token-count",
269
+ action="store_true",
270
+ help="truncation 前の token 数を確認し、max_length を超える場合に警告を出す"
271
+ )
272
+ parser.add_argument(
273
+ "--verbose",
274
+ action="store_true",
275
+ help="バッチごとの処理時間を表示する"
276
+ )
277
+
278
+ args = parser.parse_args()
279
+
280
+ process_jsonl(
281
+ input_file=args.input_file,
282
+ output_file=args.output_file,
283
+ text_attr=args.text_attr,
284
+ vector_attr=args.vector_attr,
285
+ text_type=args.text_type,
286
+ batch_size=args.batch_size,
287
+ max_length=args.max_length,
288
+ check_token_count=args.check_token_count,
289
+ verbose=args.verbose
290
+ )
291
+
292
+
293
+ if __name__ == "__main__":
294
+ main()
295
+
296
+ # Made with Bob