|
|
import json |
|
|
from pathlib import Path |
|
|
from pylate import models, indexes, retrieve |
|
|
|
|
|
|
|
|
MODEL_PATH = "/home/astgpu3/workspace/bolorjinbat/LFM2-ColBERT-350M" |
|
|
INPUT_JSON = Path("test.json") |
|
|
OUTPUT_JSON = Path("laws_with_emb.json") |
|
|
|
|
|
|
|
|
|
|
|
def load_data(path: Path): |
|
|
with open(path, "r", encoding="utf-8") as f: |
|
|
data = json.load(f) |
|
|
|
|
|
if not isinstance(data, list): |
|
|
raise ValueError("JSON root must be a list of objects") |
|
|
|
|
|
return data |
|
|
|
|
|
|
|
|
def main(): |
|
|
|
|
|
model = models.ColBERT(model_name_or_path=MODEL_PATH) |
|
|
|
|
|
|
|
|
data = load_data(INPUT_JSON) |
|
|
|
|
|
|
|
|
texts = [] |
|
|
idx_map = [] |
|
|
|
|
|
for i, row in enumerate(data): |
|
|
content = row.get("content") |
|
|
if not content: |
|
|
continue |
|
|
|
|
|
|
|
|
if isinstance(content, list): |
|
|
content = "\n".join(content) |
|
|
|
|
|
texts.append(content) |
|
|
idx_map.append(i) |
|
|
|
|
|
print(f"Embedding хийх нийт текст: {len(texts)}") |
|
|
|
|
|
if not texts: |
|
|
print("content талбар олдсонгүй, дууслаа.") |
|
|
return |
|
|
|
|
|
|
|
|
embs = model.encode( |
|
|
texts, |
|
|
batch_size=32, |
|
|
is_query=False, |
|
|
show_progress_bar=True, |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
embs_list = embs.tolist() |
|
|
|
|
|
for emb, row_idx in zip(embs_list, idx_map): |
|
|
|
|
|
data[row_idx]["embedding"] = emb |
|
|
|
|
|
|
|
|
with open(OUTPUT_JSON, "w", encoding="utf-8") as f: |
|
|
json.dump(data, f, ensure_ascii=False, indent=2) |
|
|
|
|
|
print(f"Бэлэн боллоо: {OUTPUT_JSON}") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |
|
|
|