import context v2

This commit is contained in:
hsafaei
2026-02-18 20:39:22 +03:30
parent 34bde90258
commit 6a6bed90d7
2 changed files with 653 additions and 4 deletions
+644
View File
@@ -0,0 +1,644 @@
# import mariadb
from dotenv import load_dotenv
import os
import datetime
import json
import uuid
import pandas as pd
import zipfile
import sys
import time
from tqdm import tqdm
from pydantic import BaseModel
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from app.common.elastic_helper import ElasticHelper
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
from app.common.data_helper import DataHelper
# from app.majles.majles_options import *
class OutputLabels(BaseModel):
class Subject(BaseModel):
subject_type: str
subject_detail: str
class Clause(BaseModel):
exists: bool
text: str
subject: Subject
action: str
object: str
condition: Clause
rule_verdict: str
scope: Clause | None
exception: Clause | None
load_dotenv(dotenv_path="config.env")
host = os.getenv("HOST_160")
password = os.getenv("HOST_160_PASS")
# host = os.getenv("HOST_112")
# password = os.getenv("HOST_112_PASS")
# host = os.getenv("HOST_H101")
# password = os.getenv("HOST_H101_PASS")
# path_base_map = (
# r"G:/Project2/gateaway_py/elastic_backend/elastic_backend/app/schemas/mappings/"
# )
elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic")
text_normalize = TextNormalizer()
log_file = None
def convert_OutputLabels_to_es_schema(item: OutputLabels):
return {
"action": item.action,
"condition": item.condition.text,
"exception": item.exception.text if item.exception.text else None,
"object": item.object,
"rule_verdict": item.rule_verdict,
"scope": item.scope.text if item.scope.text else None,
"subject_detail": item.subject.subject_detail,
"subject_type": item.subject.subject_type,
}
def extract_json_context_id_rules_labels(
json_path,
elastic,
index_name="mj_qa_rule",
):
input_data = DataHelper.load_orjson(json_path)
print(f"input_data {len(input_data)}")
bulk_data = []
total_count = 0
failed = 0
pass_data = 0
for _id1, (context_id, rule_label_data) in enumerate(input_data.items(), start=1):
# print(f"context_id {context_id}")
for _id2, item in enumerate(rule_label_data, start=1):
rule_id = context_id + "-" + str(_id2)
try:
old_data = elastic.get_document(index_name, rule_id)
old_data = old_data["_source"]
_old_detail = old_data.get("label_object", None)
if not _old_detail:
item_obj = OutputLabels.model_validate(item)
new_item = convert_OutputLabels_to_es_schema(item_obj)
old_data["label_object"] = new_item
else:
pass_data += 1
if pass_data >= 1000:
print(f"pass_data {pass_data}")
pass_data = 0
continue
except:
failed += 1
continue
bulk_data.append({"_id": old_data["id"], "_source": old_data})
# qs648706-1
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print("=" * 10, "to_elastic , total=" + str(total_count))
elastic.updateBulkList(bulk_data, index_name)
bulk_data = []
if len(bulk_data) >= 0:
total_count += len(bulk_data)
print("=" * 10, "to_elastic , total=" + str(total_count))
elastic.updateBulkList(bulk_data, index_name)
bulk_data = []
# qs648706-1
print(f"failed -=>{failed}<=-")
def extract_json_files(elastic, file_json, file_import_ids, file_type="groups", version_key="v2"):
bulk_data = []
total_count = 0
jump_ids = []
if os.path.exists(file_import_ids):
with open(file_import_ids, "r") as f:
jump_ids = f.readlines()
index_name_o = "mj_qa_context"
data_json = DataHelper.load_orjson(file_json)
for qanon_id, data in data_json.items() :
print(
f"***** {file_type} : ",
index_name_o,
"=>",
" qanon_id=",
qanon_id,
)
try:
index_name_o = "mj_qa_context"
bulk_data, total_count = import_groups_qanon(
elastic,
qanon_id,
data,
bulk_data,
total_count,
index_name_o,
version_key
)
jump_ids.append(qanon_id)
except Exception as e:
print("error in file " + qanon_id + str(e))
if len(bulk_data) > 0:
total_count += len(bulk_data)
print("=" * 10, " to_elastic , total=" + str(total_count))
if file_type == "rules" or file_type == "groups":
elastic.importBulkList(bulk_data, index_name_o)
else:
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
with open(file_import_ids, "w") as f:
f.write("\n".join(jump_ids))
print("end success import_to_elastic")
def extract_zip_files(elastic, filezip, file_import_ids, file_type="groups", version_key=""):
bulk_data = []
total_count = 0
jump_ids = []
if os.path.exists(file_import_ids):
with open(file_import_ids, "r") as f:
jump_ids = f.readlines()
fileNo = 0
with zipfile.ZipFile(filezip, "r") as zObject:
fileNo += 1
print(
"=" * 10,
" zip fileNo: ",
fileNo,
" ) | File Numbers:",
len(zObject.namelist()),
"=" * 10,
)
counter = 0
files = zObject.namelist()
index_name_o = "mj_qa_context"
for filename in tqdm(files, total=len(files), desc="groups "):
qanon_id = (
filename.replace("parents_for_", "")
.replace("context_for_", "")
.replace("terms_for_", "")
.replace("rule_for_", "")
.replace(".json", "")
)
if qanon_id in jump_ids:
continue
print(
f"***** {file_type} : ",
index_name_o,
"=>",
filename,
" qanon_id=",
qanon_id,
)
with zObject.open(filename) as file:
data = json.loads(file.read())
try:
if file_type == "groups":
index_name_o = "mj_qa_context"
bulk_data, total_count = import_groups_qanon(
elastic,
qanon_id,
data,
bulk_data,
total_count,
index_name_o,
version_key
)
jump_ids.append(qanon_id)
if file_type == "contexts":
index_name_o = "mj_qa_context"
bulk_data, total_count = import_contexts_qanon(
elastic,
qanon_id,
data,
bulk_data,
total_count,
index_name_o,
version_key
)
jump_ids.append(qanon_id)
if file_type == "terms":
index_name_o = "mj_qa_context"
bulk_data, total_count = import_terms_qanon(
elastic,
qanon_id,
data,
bulk_data,
total_count,
index_name_o,
version_key
)
jump_ids.append(qanon_id)
if file_type == "rules":
index_name_o = "mj_qa_rule"
bulk_data, total_count = import_rules_qanon(
elastic,
qanon_id,
data,
bulk_data,
total_count,
index_name_o,
)
jump_ids.append(qanon_id)
except Exception as e:
print("error in file " + qanon_id + str(e))
if len(bulk_data) > 0:
total_count += len(bulk_data)
print("=" * 10, " to_elastic , total=" + str(total_count))
if file_type == "rules" or file_type == "groups":
elastic.importBulkList(bulk_data, index_name_o)
else:
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
with open(file_import_ids, "w") as f:
f.write("\n".join(jump_ids))
print("end success import_to_elastic")
def import_groups_qanon(elastic, qanon_id, data, bulk_data, total_count, index_name_o, version_key):
chuk_order = 0
index_name_i = "mj_qa_section"
items = data
if "chunks" in data :
items = data["chunks"]
for item in items:
if len(item) == 0:
continue
section_mom_id = item[0]
eid = item[0] + "_" + version_key
section_ids = item
chuk_order = chuk_order + 1
qanon_title = ""
qanon_etebar = ""
state_etebar = ""
ts_date = None
ts_ref = ""
title = ""
content = ""
for section_id in section_ids:
source = None
try:
res = elastic.get_document(index_name_i, section_id)
source = res["_source"]
except:
error = (
" section_id not found in qa_section :"
+ qanon_id
+ ":"
+ section_id
)
if log_file:
log_file.write(5 * "*" + error + "\n")
continue
if not qanon_title and "qanon_etebar" in source:
qanon_title = source["qanon_title"]
if not qanon_etebar and "qanon_etebar" in source:
qanon_etebar = source["qanon_etebar"]
if not ts_date and "ts_date" in source:
ts_date = source["ts_date"]
if not ts_ref and "ts_ref" in source:
ts_ref = source["ts_ref"]
if section_id == section_mom_id:
if "state_etebar" in source:
state_etebar = source["state_etebar"]
if "other_info" in source:
title = source["other_info"]["full_path"]
if content:
content += "\n"
content += source["content"]
data = {
"id": eid,
"section_mom_id": section_mom_id,
"version_key": "base_"+version_key,
"qanon_id": qanon_id,
"qanon_title": qanon_title,
"qanon_etebar": qanon_etebar,
"state_etebar": state_etebar,
"ts_date": ts_date,
"title": title,
"ts_ref": ts_ref,
"chuk_order": chuk_order,
"content": content,
"group_section_ids": section_ids,
"time_create": int(round(time.time() * 1000)),
}
bulk_data.append({"_id": eid, "_source": data})
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print("=" * 10, "to_elastic , total=" + str(total_count), ", id=" + eid)
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
return bulk_data, total_count
def import_contexts_qanon(
elastic, qanon_id, data, bulk_data, total_count, index_name_o, version_key=""
):
chuk_order = 0
for key, value in data.items():
section_mom_id = key
eid = key
if version_key :
eid = key + "_" + version_key
context = []
for item in value:
items = item.split("=")
title = ""
content = ""
context_type = "ابهام"
if len(items) == 2:
title = items[0]
content = items[1]
else:
content = item
context_type = "ابهام-نامشخص"
context.append(
{"title": title, "content": content, "context_type": context_type}
)
data = {"context": context}
bulk_data.append({"_id": eid, "_source": data})
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print("=" * 10, "to_elastic , total=" + str(total_count), ", id=" + eid)
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
return bulk_data, total_count
def import_terms_qanon(elastic, qanon_id, data, bulk_data, total_count, index_name_o):
chuk_order = 0
terms = data["terms"]
for item in terms:
title = item["term"]
content = item["definition"]
article_ids = item["article_ids"]
context_type = "تعریف"
for section_id in article_ids:
source = None
try:
body = {
"query" : {
"term" :{
"group_section_ids" : {
"value" : section_id
}
}
}
}
res = elastic.search(index_name_o, body)
if res["hits"]["hits"] :
source = res["hits"]["hits"][0]["_source"]
except:
error = (
" section_id not found in :"
+ index_name_o
+ " "
+ qanon_id
+ ":"
+ section_id
)
if log_file:
log_file.write(5 * "*" + error + "\n")
continue
eid = section_id
if version_key :
eid = key + "_" + version_key
context = []
if "context" in source:
context = source["context"]
context.append(
{"title": title, "content": content, "context_type": context_type}
)
data = {"context": context}
bulk_data.append({"_id": eid, "_source": data})
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print(
"=" * 10, "to_elastic , total=" + str(total_count), ", id=" + eid
)
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
return bulk_data, total_count
def import_rules_qanon(elastic, qanon_id, data, bulk_data, total_count, index_name_o):
index_name_i = "mj_qa_context"
for key, value in data.items():
context_id = key
qanon_title = ""
qanon_etebar = ""
state_etebar = ""
ts_date = None
ts_ref = ""
group_section_ids = []
source = None
try:
res = elastic.get_document(index_name_i, context_id)
source = res["_source"]
except:
error = (
" section_mom_id not found in qa_context :"
+ qanon_id
+ ":"
+ context_id
)
if log_file:
log_file.write(5 * "*" + error + "\n")
continue
if "qanon_etebar" in source:
qanon_title = source["qanon_title"]
if "qanon_etebar" in source:
qanon_etebar = source["qanon_etebar"]
if "ts_date" in source:
ts_date = source["ts_date"]
if "ts_ref" in source:
ts_ref = source["ts_ref"]
if "state_etebar" in source:
state_etebar = source["state_etebar"]
if "group_section_ids" in source:
group_section_ids = source["group_section_ids"]
rule_order = 0
for item in value:
rule_id = item["id"]
content = item["content"]
rule_type = item["main_type"]
rule_order = rule_order + 1
eid = rule_id
data = {
"id": eid,
"context_id": context_id,
"version_key": "base_1",
"qanon_id": qanon_id,
"qanon_title": qanon_title,
"qanon_etebar": qanon_etebar,
"state_etebar": state_etebar,
"ts_date": ts_date,
"ts_ref": ts_ref,
"rule_order": rule_order,
"rule_type": rule_type,
"content": content,
"group_section_ids": group_section_ids,
"time_create": int(round(time.time() * 1000)),
}
bulk_data.append({"_id": eid, "_source": data})
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print(
"=" * 10, "to_elastic , total=" + str(total_count), ", id=" + eid
)
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
return bulk_data, total_count
if __name__ == "__main__":
### ----------------------------------------------
# data_key = "groups"
# log_file = open(f"G:/Project2/102_gpu/v2/log_{data_key}_1.txt", mode="w", encoding="utf8")
# file = f"G:/Project2/102_gpu/v2/mj_qa_chunks.json"
# file_import_ids = f"G:/Project2/102_gpu/v2/{data_key}_import_ids.txt"
# extract_json_files(elastic, file, file_import_ids, data_key, "v2")
# log_file.close()
# ### ----------------------------------------------
data_key = "contexts"
log_file = open(f"G:/Project2/102_gpu/log_{data_key}_1.txt", mode="w", encoding="utf8")
filezip = f"G:/Project2/102_gpu/{data_key}.zip"
file_import_ids = f"G:/Project2/102_gpu/{data_key}_import_ids.txt"
extract_zip_files(elastic, filezip, file_import_ids, data_key, "v2")
log_file.close()
# ### ----------------------------------------------
data_key = "terms"
log_file = open(
f"G:/Project2/102_gpu/log_{data_key}_1.txt", mode="w", encoding="utf8"
)
filezip = f"G:/Project2/102_gpu/{data_key}.zip"
file_import_ids = f"G:/Project2/102_gpu/{data_key}_import_ids.txt"
extract_zip_files(elastic, filezip, file_import_ids, data_key, "v2")
log_file.close()
# ### ----------------------------------------------
# data_key = "rules"
# log_file = open(
# f"G:/Project2/102_gpu/log_{data_key}_1.txt", mode="w", encoding="utf8"
# )
# filezip = f"G:/Project2/102_gpu/{data_key}.zip"
# file_import_ids = f"G:/Project2/102_gpu/{data_key}_import_ids.txt"
# extract_zip_files(elastic, filezip, file_import_ids, data_key)
# log_file.close()
# ### ----------------------------------------------
# data_key = "rules_labels"
# # label_object
# index_name = "mj_qa_rule"
# json_path = r"D:\init_mahdi\dataParsers\merge_labels.json"
# extract_json_context_id_rules_labels(
# elastic=elastic, index_name=index_name, json_path=json_path
# )
# ### ----------------------------------------------
# elastic.backupIndexToZipfile("G:/Project2/102_gpu", "mj_qa_context", "mj_qa_context")
# elastic.backupIndexToZipfile("G:/Project2/102_gpu", "mj_qa_rule", "mj_qa_rule")
# mapping_file_path = "G:/\Project2/tavasi_160/src/repo/_other/majles/mj_qa_context.json"
# elastic.restorFileToElastic2('G:/Project2/102_gpu/mj_qa_context.zip', 'mj_qa_context', 'majles', False, 'mj_qa_context', mapping_file_path)
# mapping_file_path = "G:/\Project2/tavasi_160/src/repo/_other/majles/mj_qa_rule.json"
# elastic.restorFileToElastic2('G:/Project2/102_gpu/mj_qa_rule.zip', 'mj_qa_rule', 'majles', False, 'mj_qa_rule', mapping_file_path)
# ### ----------------------------------------------
# python -m dataParsers.app.import_context_rules
# print(":D")
+9 -4
View File
@@ -26,11 +26,11 @@ text_normal = TextNormalizer()
load_dotenv(dotenv_path="config.env")
# host = os.getenv("HOST_160")
# password = os.getenv("HOST_160_PASS")
host = os.getenv("HOST_160")
password = os.getenv("HOST_160_PASS")
host = os.getenv("HOST_112")
password = os.getenv("HOST_112_PASS")
# host = os.getenv("HOST_112")
# password = os.getenv("HOST_112_PASS")
# host = os.getenv("HOST_H102")
@@ -393,3 +393,8 @@ error_section_ids = [
"qs236537_437141",
"qs236537_4371521"
]
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_rule", "mj_qa_rule")
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_context", "mj_qa_context")
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_conflict", "mj_qa_conflict")