Files
init_dataParser/app/update_mj_qa_rules_embedding.py
T
2026-11-23 20:06:18 +03:30

166 lines
4.8 KiB
Python

from dotenv import load_dotenv
import os, sys, re
from app.common.elastic_helper import ElasticHelper
from app.common.data_helper import DataHelper
from pydantic import BaseModel
from typing import Literal, List, Dict, Any, Optional
from pathlib import Path
from elasticsearch import helpers
from elasticsearch.helpers import scan
load_dotenv(dotenv_path=r"D:\init_mahdi\dataParsers\config.env")
host = os.getenv("HOST_99")
password = os.getenv("PASSWORD_99")
print(f"host {host} password {password}")
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
def creat_index(
elastic: ElasticHelper,
input_path=Path(
r"D:\init_mahdi\dataParsers\data\hamyar_bk_section_step2\finall_data"
# r"D:\init_mahdi\dataParsers\data\data_context\output_dir"
# r"D:\init_mahdi\dataParsers\data\hamyar_bk_section\finall_data.json"
# r"D:\init_mahdi\dataParsers\data\output_dir"
# r"D:\init_mahdi\dataParsers\data\jinav5_rule_v3_p1_embed\embedings"
),
index_name="hamyar_bk_section",
batch_size=1000,
):
"""
Update existing Elasticsearch documents with embeddings.
Each JSON file must contain:
{
"id": "...",
"emb": [...]
}
The document with the corresponding _id must already exist in Elasticsearch.
"""
actions = []
total = 0
success = 0
failed = 0
print("=" * 80)
print("START BULK EMBEDDING UPDATE")
print(f"Index : {index_name}")
print(f"Input path : {input_path}")
print(f"Batch size : {batch_size}")
print("=" * 80)
# in_data = list(input_path.rglob("*.json"))
# print(f"in_data {len(in_data)}")
############################################################
query = {
"_source": ["id"],
"query": {
"bool": {
# "filter": [{"term": {"version_key": "base_v3"}}],
"must": [{"exists": {"field": "embedding"}}],
}
},
}
# process_ids = set(
# hit["_id"]
# for hit in scan(
# elastic.es, # اگر نام کلاینت داخل ElasticHelper چیز دیگری است، آن را جایگزین کنید
# index=index_name,
# query=query,
# size=1000,
# )
# )
process_ids = set()
print(f"process_ids {len(process_ids)} ")
############################################################
# for data in DataHelper.load_orjson(input_path):
for j_path in input_path.rglob("*.json"):
for data in DataHelper.load_orjson(j_path):
try:
# data = DataHelper.load_orjson(j_path)
doc_id = data["id"]
embedding = data["embed"]
if doc_id in process_ids:
# print(f"doc_id {doc_id}")
continue
# doc_id = re.sub(r"(_v3)(\d+)$", r"\1-\2", data["id"])
# print(f"doc_id {doc_id}")
# return
action = {
"_op_type": "update",
"_index": index_name,
"_id": doc_id,
"doc": {"embedding": embedding},
}
actions.append(action)
total += 1
# Send batch
if len(actions) >= batch_size:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print(
f"processed={total:,} | "
f"success={success:,} | "
f"failed={failed:,}"
)
actions.clear()
except Exception as e:
failed += 1
print(f"[ERROR] {input_path}")
print(f" {type(e).__name__}: {e}")
# Remaining documents
if actions:
for ok, result in helpers.streaming_bulk(
elastic.es,
actions,
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
):
if ok:
success += 1
else:
failed += 1
print("ERROR:", result)
print()
print("=" * 80)
print("BULK UPDATE FINISHED")
print(f"Total : {total:,}")
print(f"Success: {success:,}")
print(f"Failed : {failed:,}")
print("=" * 80)
creat_index(elastic=elastic)
# python -m app.update_mj_qa_rules_embedding