Files
init_dataParser/app/import_context_rules.py
T
2026-01-22 13:37:24 +03:30

458 lines
15 KiB
Python

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
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.majles_options import *
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")
# print(host)
# print(password)
path_base_map = (
"G:\Project2\gateaway_py\elastic_backend/elastic_backend/app/schemas/mappings/"
)
elastic = ElasticHelper(host, password, "elastic", path_base_map)
text_normalize = TextNormalizer()
log_file = None
def extract_zip_files(elastic, filezip, file_import_ids, file_type="groups"):
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,
)
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,
)
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,
)
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):
chuk_order = 0
index_name_i = "mj_qa_section"
for item in data["chunks"]:
if len(item) == 0:
continue
section_mom_id = item[0]
eid = item[0]
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_1",
"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
):
chuk_order = 0
for key, value in data.items():
section_mom_id = key
eid = 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 context_id in article_ids:
source = None
try:
res = elastic.get_document(index_name_o, context_id)
source = res["_source"]
except:
error = (
" context_id not found in :"
+ index_name_o
+ " "
+ qanon_id
+ ":"
+ context_id
)
if log_file:
log_file.write(5 * "*" + error + "\n")
continue
eid = context_id
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/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 = "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)
# 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)
# 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()
# ### ----------------------------------------------
# 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/_back/_to_majles/14041022/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/_back/_to_majles/14041022/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)
# ### ----------------------------------------------