72 lines
3.0 KiB
Python
72 lines
3.0 KiB
Python
import json
|
|
import numpy as np
|
|
import faiss
|
|
import os
|
|
|
|
def create_faiss_index_from_json(json_file_path, faiss_index_path, metadata_file_path):
|
|
print(f'try to read {json_file_path} ...')
|
|
# --- 1. بارگذاری دادهها از JSON ---
|
|
with open(json_file_path, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
print(f'file reading finished')
|
|
|
|
# فرض بر این است که هر عنصر شامل فیلدهای زیر است:
|
|
# {
|
|
# "speech_title": "title",
|
|
# "sentence": "متن جمله",
|
|
# "embeddings": [0.12, 0.34, ...]
|
|
# }
|
|
|
|
sentences = []
|
|
titles = []
|
|
embeddings_list = []
|
|
prefix_list = []
|
|
for k, item in data.items():
|
|
sentences.append(item['content'])
|
|
titles.append(item['id'])
|
|
embeddings_list.append(item['embeddings'])
|
|
prefix_list.append(item['section-prefix'])
|
|
|
|
embeddings = np.array(embeddings_list).astype('float32') # ابعاد: (n, d)
|
|
dimension = embeddings.shape[1]
|
|
|
|
print(f"Loaded {len(embeddings)} embeddings with dimension {dimension}")
|
|
|
|
# --- 2. ایجاد ایندکس FAISS برای GPU ---
|
|
# اگر فقط CPU دارید، از faiss.IndexFlatL2 استفاده کنید.
|
|
# اگر GPU دارید، ابتدا ایندکس را روی CPU ایجاد و سپس به GPU انتقال دهید.
|
|
cpu_index = faiss.IndexFlatL2(dimension) # معیار فاصله L2 (Euclidean)
|
|
|
|
# انتقال ایندکس به GPU
|
|
if faiss.get_num_gpus() > 0:
|
|
print("Using GPU for FAISS index...")
|
|
res = faiss.StandardGpuResources()
|
|
gpu_index = faiss.index_cpu_to_gpu(res, 0, cpu_index)
|
|
else:
|
|
print("GPU not available, using CPU.")
|
|
gpu_index = cpu_index
|
|
|
|
# --- 3. افزودن دادهها به ایندکس ---
|
|
gpu_index.add(embeddings)
|
|
print(f"Total vectors indexed: {gpu_index.ntotal}")
|
|
|
|
# --- 4. ذخیره ایندکس به فایل ---
|
|
# برای ذخیره باید به CPU منتقل شود
|
|
final_index = faiss.index_gpu_to_cpu(gpu_index) if isinstance(gpu_index, faiss.Index) and faiss.get_num_gpus() > 0 else gpu_index
|
|
os.makedirs(os.path.dirname(faiss_index_path), exist_ok=True)
|
|
faiss.write_index(final_index, faiss_index_path)
|
|
print(f"FAISS index saved to {faiss_index_path}")
|
|
|
|
# --- 5. ذخیره متادیتا (برای نگاشت نتایج جستجو) ---
|
|
metadata = [{"id": id, "content": c, 'prefix': p} for id, c, p in zip(titles, sentences,prefix_list)]
|
|
with open(metadata_file_path, 'w', encoding='utf-8') as f:
|
|
json.dump(metadata, f, ensure_ascii=False, indent=2)
|
|
print(f"Metadata saved to {metadata_file_path}")
|
|
|
|
if __name__ == '__main__':
|
|
# استفاده از متد
|
|
json_file_path = './majles-output/sections-vec-285k.json'
|
|
faiss_index_path = './qavanin-faiss/faiss_index_qavanin_285k.index'
|
|
metadata_file_path = './qavanin-faiss/faiss_index_qavanin_285k_metadata.json'
|
|
|
|
create_faiss_index_from_json(json_file_path, faiss_index_path, metadata_file_path) |