refactor codes and names

This commit is contained in:
hsafaei
2026-02-12 11:19:58 +03:30
parent 56084b0c8e
commit 9c99d816db
25 changed files with 395 additions and 2360 deletions
+566
View File
@@ -0,0 +1,566 @@
# 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
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"]
item_obj = OutputLabels.model_validate(item)
new_item = convert_OutputLabels_to_es_schema(item_obj)
old_data["label_object"] = new_item
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_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()
# ### ----------------------------------------------
# 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")
+631
View File
@@ -0,0 +1,631 @@
import mariadb
from dotenv import load_dotenv
import os
import datetime
import json
import uuid
import pandas as pd
import sys
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.majles_options import *
load_dotenv(dotenv_path="config.env")
host = os.getenv("HOST_160")
# host = os.getenv("HOST_160_LOCAL")
password = os.getenv("HOST_160_PASS")
# host = os.getenv("HOST_60")
# password = os.getenv("HOST_60_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()
def import_simple_list_to_elastic(
elastic,
items,
prefix_id,
tree_label,
tree_key,
group_key="",
index_name_o="gn_tree",
):
bulk_data = []
total_count = 0
t1 = datetime.datetime.now()
print(t1)
i = 0
for item in items:
# print(i)
i = i + 1
row = cursor.fetchone()
if not item:
break
id = prefix_id + str(i).zfill(5)
# eid = uuid.uuid4().hex[:8]
eid = id
title = item.strip()
title = text_normalize.normalize_qanon(title)
parent_id = "0"
child_order = i
data = {
"id": eid,
"version_key": "base_1",
"tree_key": tree_key,
"tree_label": tree_label,
"main_type": "list",
"group_key": group_key,
"title": title,
"parent_id": parent_id,
"child_order": child_order,
}
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print(
"=" * 10,
"to_elastic , total=" + str(total_count),
str(i) + ", id=" + eid,
)
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
bulk_data.append({"_id": eid, "_source": data})
if len(bulk_data) > 0:
total_count += len(bulk_data)
print("=" * 10, " to_elastic , total=" + str(total_count))
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
print("end success import_to_elastic")
t2 = datetime.datetime.now()
print(t2 - t1)
def import_project_to_elastic(
cursor, elastic, project_id, project_title, index_name_o="gn_tree"
):
query = f"""
SELECT id, title, parent, child_order, meta, tags from tlist.tl_subjects
where project_id={project_id}
ORDER BY parent, child_order
"""
# print('-'*10)
# print(query)
# print('-'*10)
cursor.execute(query)
parent_nodes = {}
bulk_data = []
total_count = 0
t1 = datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i = i + 1
row = cursor.fetchone()
if not row:
break
id = row[0]
# eid = uuid.uuid4().hex[:8]
eid = "gnt" + str(id).zfill(5)
title = row[1]
if title is None: # داده های خراب
continue
title = row[1].strip()
title = text_normalize.normalize_qanon(title)
parent = row[2]
parent_id = 0
if parent != 0:
parent_id = "gnt" + str(parent).zfill(5)
child_order = row[3]
meta = row[4]
tags = row[5]
meta_info = {}
if meta:
meta_info["id1"] = str(meta)
tags_list = []
if tags:
for tt in tags.strip().split(","):
if tt and not tt in tags_list:
tags_list.append(tt)
main_type_key = "tree" + str(project_id)
data = {
"id": eid,
"version_key": "base_1",
"tree_key": main_type_key,
"tree_label": project_title,
"main_type": "tree",
# "group_key" : "",
"title": title,
"parent_id": parent_id,
"child_order": child_order,
"tags": tags_list,
"meta_info": meta_info,
}
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print(
"=" * 10,
"to_elastic , total=" + str(total_count),
str(i) + ", id=" + eid,
)
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
bulk_data.append({"_id": eid, "_source": data})
if len(bulk_data) > 0:
total_count += len(bulk_data)
print("=" * 10, " to_elastic , total=" + str(total_count))
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
print("end success import_to_elastic")
t2 = datetime.datetime.now()
print(t2 - t1)
def import_tlist_projects():
config_env = load_dotenv(dotenv_path="./config.env")
MYSQL_username = os.getenv("MYSQL_username")
MYSQL_root_password = os.getenv("MYSQL_root_password")
MYSQL_port = os.getenv("MYSQL_port")
# MYSQL_host = os.getenv("MYSQL_import_host")
# MYSQL_host = os.getenv("MYSQL_import_host_60")
MYSQL_host = os.getenv("MYSQL_import_host_160")
cnx = mariadb.connect(user="root", password=MYSQL_root_password, host=MYSQL_host)
cursor = cnx.cursor()
query = "select id, title from tlist.tl_projects"
cursor.execute(query)
list_projects = []
while 1:
row = cursor.fetchone()
if not row:
break
pid = row[0] # "id"
title = row[1] # "title"
title = text_normalize.normalize_qanon(title)
# print(title)
# پلانهای استفاده نشده در مجلس
if pid >= 100 and pid <= 200:
continue
# کدهای تنقیح مجلس که در جای دیگه اضافه میشود
if pid == 4 or pid == 5 or pid == 8:
continue
# موضوعات درختی قدیم و نهادهای حاکمیتی که دیگه جایگزین با 6 شد
if pid == 1 or pid == 2:
continue
list_projects.append({"id": pid, "title": title})
for item in list_projects:
print("*" * 100)
print(item)
import_project_to_elastic(cursor, elastic, item["id"], item["title"], "gn_tree")
cursor.close()
def import_option_to_elastic(
elastic,
main_key,
main_label,
group_key="majles_base",
eid="",
index_name_o="gn_option",
):
res = get_options(main_key)
titles = []
for item in res :
title = item["value"]
title = text_normalize.normalize_qanon(title)
titles.append(title)
if not eid:
eid = uuid.uuid4().hex[:8]
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"main_type": "list_simple",
"titles": titles,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
def import_option_base_list(elastic):
op_list = [
{
"main_key": "qasection_before_info_plan_type",
"main_label": "پرونده - تقدیم - نوع پیش نویس",
},
{
"main_key": "qasection_before_info_discuss_type",
"main_label": "پرونده - نوع شور ",
},
{"main_key": "qasection_letters_type", "main_label": "پرونده - نوع نامه نگاری"},
{
"main_key": "qasection_before_info_commission_type",
"main_label": "پرونده - نوع کمیسیون ",
},
{
"main_key": "qasection_before_info_commission",
"main_label": "پروند - عنوان کمیسیونها",
},
{"main_key": "rgsection_tsref", "main_label": "شناسنامه مقررات - مرجع تصویب ها"},
{"main_key": "qasection_tsref", "main_label": "شناسنامه قانون - مرجع تصویب ها"},
{
"group_key": "majles_it_base",
"main_key": "qasection_qanon_etebar",
"main_label": "قانون - وضعیت اعتبار",
},
{
"group_key": "majles_it_base",
"main_key": "qasection_state_etebar",
"main_label": "قانون - وضعیت اعتبار جزء",
},
{"main_key": "qasection_doc_tags", "main_label": "انواع قانون برای فهرست سازی"},
{"main_key": "qasection_doc_states", "main_label": "صحت سنجی - وضعیت قانون"},
{
"main_key": "qasection_title_type",
"main_label": "شناسنامه قانون - نوع عنوان",
},
{
"main_key": "qasection_main_type",
"main_label": "شناسنامه قانون - نوع اصلی-تبعی",
},
{"main_key": "qasection_sub_type", "main_label": "شناسنامه قانون - نوع فرعی"},
{"main_key": "rgsection_sub_type", "main_label": "شناسنامه مقررات - نوع فرعی"},
{"main_key": "qaopinion_main_type", "main_label": "شناسنامه آراء - نوع اصلی"},
{"main_key": "qaopinion_sub_type", "main_label": "شناسنامه آراء - نوع فرعی"},
{"main_key": "qaopinion_tsref", "main_label": "شناسنامه آراء - مرجع تصویب ها"},
{
"group_key": "majles_it_base",
"main_key": "dfqanon_effect_type",
"main_label": "ورود قانون - نوع اثرگذاری",
},
{"main_key": "relation_type", "main_label": "ارتباطات قانون - نوع ارتباط"},
{
"group_key": "majles_it_base",
"main_key": "relation_to",
"main_label": "ارتباطات قانون - نوق مقصد",
},
{
"group_key": "majles_it_base",
"main_key": "relation_from",
"main_label": "ارتباطات قانون - نوع مبدا",
},
{"main_key": "mashruh_majles", "main_label": "مشروح مذاکرات - نوع مجلس"},
{"main_key": "qasection_mom_type", "main_label": "نوع اصلی-تبعی-مهذب"},
# {
# "main_key": "ref_id",
# "main_label": ""
# },
# {
# "main_key": "diff_type",
# "main_label": ""
# },
]
number = 0
for op in op_list:
number = number + 1
print(op["main_key"])
eid = "mb_op_" + str(number)
group_key = "عناوین انتخابی فرمها"
if "group_key" in op:
group_key = op["group_key"]
import_option_to_elastic(
elastic, op["main_key"], op["main_label"], group_key, eid
)
def import_option_codes(elastic, index_name_o="gn_option"):
###-------------------------------------------
titles = get_codes54()
eid = "mb_op_codes54"
group_key = "کدهای تنقیح"
main_key = "codes54"
main_label = "کدهای تنقیح 54 باب"
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"main_type": "list_simple",
"titles": titles,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
###-------------------------------------------
titles = get_codes51()
eid = "mb_op_codes51"
group_key = "کدهای تنقیح"
main_key = "codes51"
main_label = "کدهای تنقیح 51 باب"
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"main_type": "list_simple",
"titles": titles,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
###-------------------------------------------
titles = get_codes50()
eid = "mb_op_codes50"
group_key = "کدهای تنقیح"
main_key = "codes50"
main_label = "کدهای تنقیح 50 باب"
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"main_type": "list_simple",
"titles": titles,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
###-------------------------------------------
titles = get_codes49()
eid = "mb_op_codes49"
group_key = "کدهای تنقیح"
main_key = "codes49"
main_label = "کدهای تنقیح 49 باب"
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"main_type": "list_simple",
"titles": titles,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
###-------------------------------------------
def import_option_parleman_members(elastic, index_name_o="gn_option"):
excel_file1 = "data/qavanin_files/list_فهرست نمایندگان دوره 9 تا 12.xlsx"
df = pd.read_excel(excel_file1, sheet_name=1)
column_names = df.columns.tolist()
rows_list = df.to_dict(orient="records")
print(column_names)
prev_term = 0
pm_list = []
for row in rows_list:
code = row[column_names[0]]
lname = row[column_names[1]]
name = row[column_names[2]]
print(code)
if code is None:
continue
code = str(code)
if not is_number_string(code) or code == "810102" or len(code) != len("77101"):
continue
id = int(code)
scode = code
sterm = scode[0:2]
if sterm == "99":
sterm = "9"
elif sterm == "88":
sterm = "8"
elif sterm == "77":
sterm = "7"
elif sterm == "66":
sterm = "6"
elif sterm == "55":
sterm = "5"
elif sterm == "44":
sterm = "4"
elif sterm == "33":
sterm = "3"
elif sterm == "22":
sterm = "2"
term = int(sterm)
if prev_term == 0:
prev_term = term
if term != prev_term and pm_list:
main_key = "pm_" + str(prev_term)
main_label = "نمایندگان دوره " + str(prev_term)
group_key = "نمایندگان ادوار مجلس"
main_type = "table"
object_columns = [
{"key": "title", "title": "نام نماینده", "width": 8},
{"key": "id", "title": "کد نماینده", "width": 4},
]
eid = "mj_" + main_key
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"object_columns": object_columns,
"object_values": pm_list,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
pm_list = []
prev_term = term
title = lname + " " + name
title = text_normalize.normalize_qanon(title)
pm_list.append({"id": str(id), "title": title})
if pm_list:
main_key = "pm_" + str(prev_term)
main_label = "نمایندگان دوره " + str(prev_term)
group_key = "نمایندگان ادوار مجلس"
main_type = "table"
object_columns = [
{"key": "title", "title": "نام نماینده", "width": 8},
{"key": "id", "title": "کد نماینده", "width": 4},
]
eid = "mj_" + main_key
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"main_type": main_type,
"group_key": group_key,
"object_columns": object_columns,
"object_values": pm_list,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
def import_option_others(elastic, index_name_o="gn_option"):
###-------------------------------------------
res = get_organs()
titles = []
for title in res :
title = text_normalize.normalize_qanon(title)
titles.append(title)
eid = "mb_op_organs1"
group_key = "عناوین انتخابی فرمها"
main_key = "mj_qa_organs"
main_label = "سازمانها و نهادهای حاکمیتی"
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"main_type": "list_simple",
"titles": titles,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
###------------------------------------------
res = [
"دفتر مقام معظم رهبری",
"دفتر رئیس جمهور",
"دفتر ریاست قوه قضائیه",
"دفتر ریاست مجلس شورای اسلامی",
"دبیرخانه مجمع تشخیص مصلحت نظام",
"دبیرخانه شورای نگهبان",
"دفتر معاون اول رئیس جمهور",
"معاونت امور مجلس رئیس جمهور",
"معاونت حقوقی رئیس جمهور",
"کلیه وزارتخانه ها،سازمان ها، مؤسسات دولتی،نهادهای انقلاب اسلامی و استانداری های سراسر کشور",
"دیوان محاسبات کشور",
"دفتر هیأت دولت",
"دبیرخانه شورای اطلاع رسانی دولت",
"معاونت امور تقنینی معاونت امور مجلس ریاست جمهوری",
"معاونت قوانین مجلس شورای اسلامی",
"معاونت نظارت مجلس شورای اسلامی",
"معاونت ارتباطات و اطلاع رسانی دفتر رئیس جمهور",
"معاونت تدوین، تنقیح و انتشار قوانین و مقررات نهاد ریاست جمهوری",
"اداره کل پیگیری طرح ها و لوایح معاونت امور مجلس ریاست جمهوری",
"اداره کل اسناد و اطلاع رسانی قوانین مجلس شورای اسلامی",
"اداره کل امور تقنینی و کمیسیونها مجلس شورای اسلامی",
"سامانه ملی قوانین و مقررات جمهوری اسلامی ایران",
"روزنامه رسمی جمهوری اسلامی ایران",
]
titles = []
for title in res :
title = text_normalize.normalize_qanon(title)
titles.append(title)
eid = "mb_organ_1"
group_key = "عناوین انتخابی فرمها"
main_key = "organ_defualt"
main_label = "سازمانهای پیش فرض قانون جدید"
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"main_type": "list_simple",
"titles": titles,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
if __name__ == "__main__":
index_name_o="gn_option"
# ---مرحله اول
# import_tlist_projects()
# import_option_base_list(elastic)
# import_option_parleman_members(elastic)
# import_option_codes(elastic)
# import_option_others(elastic)
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_tree", "gn_tree")
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_option", "gn_option")
File diff suppressed because it is too large Load Diff
+519
View File
@@ -0,0 +1,519 @@
import numbers
import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch, helpers
import json
import re
import zipfile
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from ..common.text_normalizer import TextNormalizer
# from general import *
from ..common.general_functions import *
from ..common.elastic_helper import ElasticHelper
text_normal = TextNormalizer()
def validate_value(value):
if pd.isna(value):
return ""
value = str(value)
if value is None or ".." in value:
return ""
temp = value.replace("0", "")
if not temp:
return ""
return value.strip(" \n")
# اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
def correct_qanon_date_json(data, error_list):
data_new = []
for item in data:
id = item["_id"]
# یکبار فقط نیاز بود
id = str(id).replace('mj_mashruh_', 'mh')
item["_id"] = id
item["_source"]["id"] = id
item["_source"] = repair_object_persian_date(
item["_source"], "ts_date", error_list, id, ""
)
#--> mj_mashruh
if "meet_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "meet_date", error_list, id, ""
)
if "exec_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "exec_date", error_list, id, ""
)
if "expire_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "expire_date", error_list, id, ""
)
if "date_edit" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "date_edit", error_list, id, ""
)
if "fixed_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "fixed_date", error_list, id, ""
)
if "renewal_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "renewal_date", error_list, id, ""
)
if "eblagh" in item["_source"]:
item["_source"]["eblagh"] = repair_object_persian_date(
item["_source"]["eblagh"], "date", error_list, id, "eblagh"
)
if "rrk" in item["_source"]:
item["_source"]["rrk"] = repair_object_persian_date(
item["_source"]["rrk"], "date", error_list, id, "rrk"
)
if "ref_state" in item["_source"]:
ref_state=[]
for ref_item in item["_source"]["ref_state"] :
ref_item_new = repair_object_persian_date(ref_item, "qanon_date", error_list, id, "ref_state")
ref_item_new = repair_object_persian_date(ref_item_new, "effect_date", error_list, id, "ref_state")
ref_state.append(ref_item_new)
item["_source"]["ref_state"]=ref_state
data_new.append(item)
return data_new
def normal_mashruh_data_json(data):
data_new = []
for item in data:
id = item["_id"]
if 'content' in item["_source"] :
item["_source"]['content'] = text_normal.normalize_qanon(item["_source"]['content'])
if 'majles_name' in item["_source"] :
item["_source"]['majles_name'] = text_normal.normalize_qanon(item["_source"]['majles_name'])
if 'title' in item["_source"] :
item["_source"]['title'] = text_normal.normalize_qanon(item["_source"]['title'])
if 'content_type' in item["_source"] :
item["_source"]['content_type'] = text_normal.normalize_qanon(item["_source"]['content_type']).strip()
if 'title_type' in item["_source"] :
item["_source"]['title_type'] = text_normal.normalize_qanon(item["_source"]['title_type']).strip()
if "talker" in item["_source"]:
talker = item["_source"]["talker"]
if 'organ' in talker :
talker['organ'] = text_normal.normalize_qanon(talker['organ'])
if 'semat' in talker :
talker['semat'] = text_normal.normalize_qanon(talker['semat'])
if 'name' in talker :
talker['name'] = text_normal.normalize_qanon(talker['name'])
item["_source"]["talker"]=talker
data_new.append(item)
return data_new
# اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
def restore_correct_date_to_elastic(elastic, file_path, index_name, file_error=''):
error_list = []
fileNo = 0
with zipfile.ZipFile(file_path, "r") as zObject:
fileNo += 1
packNo = 0
counter = 0
for filename in zObject.namelist():
packNo += 1
print("index:", index_name, "=>", filename)
data = []
with zObject.open(filename) as file:
data = json.loads(file.read())
data_new = correct_qanon_date_json(data, error_list)
if index_name == 'mj_mashruh' :
data_new = normal_mashruh_data_json(data_new)
elastic.importJsonDataToElastic(data_new, index_name, [], True)
counter += len(data)
# print('-'*10, 'len()', str(counter) + '/ ' + str(len(data)) + ' , ' +str(len(data_new)) )
elastic.es.indices.refresh(index=index_name)
print(elastic.es.cat.count(index=index_name, format="json"))
file_log_error = file_error
if not file_error :
file_log_error = "G:/Project2/160_dotic/date_log_error.txt"
with open(file_log_error, "w", encoding="utf8") as f:
json.dump(error_list, f, ensure_ascii=False, indent=4)
def import_data_new_qaqanon(elastic, path_file):
jsonData = []
count = 0
id = ""
try:
try:
list_ = elastic.iterateJsonFile(path_file, True)
except Exception as e:
print("Exception es_iterate_all_documents : " + str(e))
print("*" * 20, " count=", elastic.total)
for mentry in list(list_):
count += 1
entry = mentry["source"]
id = entry.get("id", "")
main_type = entry.get("main_type", "")
# قانونها را نباید بروزرسانی کنیم ...چون از طرف مجلس تغییرات شناسانامه در ایندکس داشته است
if main_type == "قانون":
continue
jsonData.append({"_id": id, "_source": entry})
except Exception as e:
print("Exception: " + str(e))
error_list = []
jsonData_new = correct_qanon_date_json(jsonData, error_list)
pack_size = 1000
bulk = []
total = len(jsonData_new)
count = 0
for item in jsonData_new:
bulk.append(item)
if len(bulk) >= pack_size:
count += len(bulk)
elastic.importJsonDataToElastic(bulk, "mj_qa_qanon", [], True)
print(" count update ", str(count), "/", str(total))
bulk = []
if len(bulk):
count += len(bulk)
elastic.importJsonDataToElastic(bulk, "mj_qa_qanon", [], True)
print(" count update ", str(count), "/", str(total))
bulk = []
def import_content_opinion_to_qaqanon(elastic, path_file, index_name_o):
bulk_list = []
bulk_list_import = []
pack_size = 100
count = 0
id = ""
try:
try:
list_ = elastic.iterateJsonFile(path_file, True)
except Exception as e:
print("Exception es_iterate_all_documents : " + str(e))
list_items = list(list_)
total = elastic.total
print("*" * 20, " count=", elastic.total)
total_count = 0
for mentry in list_items:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
qanon_id = entry.get("qanon_id", "")
eid = qanon_id
# if not qanon_id == "qq296834" :
# continue
ref_id = entry.get("ref_id", "")
ref_key = entry.get("ref_key", "")
title_popular = entry.get("title_popular", "")
title = entry.get("title", "")
title_type = entry.get("title_type", "")
ts_year = entry.get("ts_year", "")
ts_ref = entry.get("ts_ref", "")
sub_type = entry.get("sub_type", "")
qanon_etebar = entry.get("qanon_etebar", "")
sort_date_timestamp = entry.get("sort_date_timestamp", "")
ts_date = entry.get("ts_date", "")
ts_date, err_msg = convert_persian_date(ts_date)
expire_date = entry.get("expire_date", "")
expire_date, err_msg = convert_persian_date(expire_date)
aproveDate = entry.get("aproveDate", "")
aproveDate, err_msg = convert_persian_date(aproveDate)
content = entry.get("content", "")
content = text_normal.normalize_qanon(content)
html = entry.get("html", "")
html = text_normal.yeke_normal(html)
content_len = entry.get("content_len", "")
eblagh_number = validate_value(entry.get("eblagh_number", ""))
eblagh_date = entry.get("eblagh_date", "")
eblagh_date, err_msg = convert_persian_date(eblagh_date)
eblagh = {}
if eblagh_number or eblagh_date:
eblagh["number"] = eblagh_number
if eblagh_date:
eblagh["date"] = eblagh_date
item = {}
is_update = True
try:
item = elastic.get_document(index_name_o, eid)
except:
is_update = False
data = {}
if not is_update:
main_type = "آراء"
data = {
"id": eid,
"ref_id": ref_id,
"ref_key": ref_key,
"main_type": main_type,
"sub_type": sub_type,
"title": title,
"ts_year": ts_year,
"ts_ref": ts_ref,
"qanon_etebar": qanon_etebar,
"sort_date_timestamp": sort_date_timestamp, # created from repairQanon.getSortTimestamp
}
if title_type:
data["title_type"] = title_type
if title_popular:
data["title_popular"] = title_popular
if ts_date:
data["ts_date"] = ts_date
if expire_date:
data["expire_date"] = expire_date
if aproveDate:
data["exec_date"] = aproveDate
if html: # ساختن دوباره و بهتر
content = html_to_text_preserve_lines(html)
content = text_normal.normalize_qanon(content)
content_len = len(content)
data["content"] = content
if html and isNeedHtml(html):
data["html"] = html
data["content_len"] = content_len
if eblagh:
data["eblagh"] = eblagh
if is_update:
bulk_list.append({"_id": eid, "_source": data})
else:
bulk_list_import.append({"_id": eid, "_source": data})
if len(bulk_list) >= pack_size:
total_count += len(bulk_list)
elastic.updateBulkList(bulk_list, index_name_o, True)
print(
" count update ", str(count), "/", str(total_count), "/", str(total)
)
bulk_list = []
if len(bulk_list_import) >= pack_size:
total_count += len(bulk_list_import)
elastic.importBulkList(bulk_list_import, index_name_o, True)
print(
" count import ", str(count), "/", str(total_count), "/", str(total)
)
bulk_list_import = []
if len(bulk_list):
total_count += len(bulk_list)
elastic.updateBulkList(bulk_list, index_name_o, True)
print(" count update ", str(count), "/", str(total_count), "/", str(total))
bulk_list = []
if len(bulk_list_import):
total_count += len(bulk_list_import)
elastic.importBulkList(bulk_list_import, index_name_o, True)
print(" count import ", str(count), "/", str(total_count), "/", str(total))
bulk_list_import = []
except Exception as e:
print("Exception: " + str(e))
def extract_content_opinion_to_qaqanon(elastic, path_file, index_name_o, path_out = "./data/"):
bulk_list = []
bulk_list_import = []
pack_size = 100
count = 0
id = ""
try:
try:
list_ = elastic.iterateJsonFile(path_file, True)
except Exception as e:
print("Exception es_iterate_all_documents : " + str(e))
list_items = list(list_)
total = elastic.total
print("*" * 20, " count=", elastic.total)
total_count = 0
percent_prev = 0
for mentry in list_items:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
qanon_id = entry.get("qanon_id", "")
eid = qanon_id
percent = int((count / len(list_items)) * 100)
if percent != percent_prev:
print("progress -> %.2f %%" % percent)
percent_prev = percent
# if not qanon_id == "qq296834" :
# continue
ref_id = entry.get("ref_id", "")
ref_key = entry.get("ref_key", "")
title_popular = entry.get("title_popular", "")
title = entry.get("title", "")
title_type = entry.get("title_type", "")
ts_year = entry.get("ts_year", "")
ts_ref = entry.get("ts_ref", "")
sub_type = entry.get("sub_type", "")
qanon_etebar = entry.get("qanon_etebar", "")
sort_date_timestamp = entry.get("sort_date_timestamp", "")
ts_date = entry.get("ts_date", "")
ts_date, err_msg = convert_persian_date(ts_date)
expire_date = entry.get("expire_date", "")
expire_date, err_msg = convert_persian_date(expire_date)
aproveDate = entry.get("aproveDate", "")
aproveDate, err_msg = convert_persian_date(aproveDate)
content = entry.get("content", "")
content = text_normal.normalize_qanon(content)
html = entry.get("html", "")
html = text_normal.yeke_normal(html)
content_len = entry.get("content_len", "")
eblagh_number = validate_value(entry.get("eblagh_number", ""))
eblagh_date = entry.get("eblagh_date", "")
eblagh_date, err_msg = convert_persian_date(eblagh_date)
eblagh = {}
if eblagh_number or eblagh_date:
eblagh["number"] = eblagh_number
if eblagh_date:
eblagh["date"] = eblagh_date
item = {}
is_update = True
try:
item = elastic.get_document(index_name_o, eid)
except:
is_update = False
data = {}
if not is_update:
main_type = "آراء"
data = {
"id": eid,
"ref_id": ref_id,
"ref_key": ref_key,
"main_type": main_type,
"sub_type": sub_type,
"title": title,
"ts_year": ts_year,
"ts_ref": ts_ref,
"qanon_etebar": qanon_etebar,
"sort_date_timestamp": sort_date_timestamp, # created from repairQanon.getSortTimestamp
}
if title_type:
data["title_type"] = title_type
if title_popular:
data["title_popular"] = title_popular
if ts_date:
data["ts_date"] = ts_date
if expire_date:
data["expire_date"] = expire_date
if aproveDate:
data["exec_date"] = aproveDate
if html: # ساختن دوباره و بهتر
content = html_to_text_preserve_lines(html)
content = text_normal.normalize_qanon(content)
content_len = len(content)
data["content"] = content
if html and isNeedHtml(html):
data["html"] = html
data["content_len"] = content_len
if eblagh:
data["eblagh"] = eblagh
if is_update:
bulk_list.append({"id": eid, "_source": data})
else:
bulk_list_import.append({"id": eid, "_source": data})
file1 = path_out + "1_opinion_update.json"
with open(file1, 'w', encoding='utf8') as f :
json.dump(bulk_list, f, ensure_ascii=False, indent=4)
file1 = path_out + "1_opinion_import.json"
with open(file1, 'w', encoding='utf8') as f :
json.dump(bulk_list_import, f, ensure_ascii=False, indent=4)
except Exception as e:
print("Exception: " + str(e))
+348
View File
@@ -0,0 +1,348 @@
import os
from dotenv import load_dotenv
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from app.common.text_normalizer import TextNormalizer
# from general import *
from app.common.general_functions import *
from app.common.elastic_helper import ElasticHelper
from app.for_ai.create_relation_tags import *
# from app.temp_refactor_gn_dataset 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')
# host=os.getenv('HOST_113')
# password=os.getenv('HOST_113_PASS')
# host=os.getenv('HOST_118')
# password=os.getenv('HOST_118_PASS')
# host=os.getenv('HOST_60')
# password=os.getenv('HOST_60_PASS')
# host=os.getenv('HOST_161')
# password=os.getenv('HOST_161_PASS')
# host=os.getenv('HOST_80')
# password=os.getenv('HOST_80_PASS')
host=os.getenv('HOST_133')
password=os.getenv('HOST_133_PASS')
print(host)
# print(password)
path_base_map = "G:/Project2/gateway_php/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_112")
# elastic.removeCustomFileds("mj_qa_section", ["tcode","nlp_parser","content_normal","tcode_mains","tcode_subs", "ners_v1", "level", "code-ai"])
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section-m1")
# elastic.createIndex( index_name='mj_qa_section-m1', app_key='majles', map_name='mj_qa_section')
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section-m1.zip', 'mj_qa_section-m1', 'majles', False, 'mj_qa_section')
# elastic.restorFileToElastic2(path_file='G:/Project2/111/server112/mj_qa_section-m1.zip', index_name='mj_qa_section-m1', app_key='majles', queryDelete=False, map_name='mj_qa_section')
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_plan")
# elastic.createIndex( 'mj_plan', 'majles', 'mj_plan')
# elastic.restorFileToElastic2('G:/Project2/111/mj_plan.zip', 'mj_plan', 'majles', False, 'mj_plan')
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_mashruh")
# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section")
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section.zip', 'mj_qa_section', 'majles', False, 'mj_qa_section')
# elastic.restorFileToElastic2('G:/Project2/111/gn_setting.zip', 'gn_setting', 'general', False, 'gn_setting')
# elastic.backupIndexToZipfile("G:/Project2/111", "mn_spr_sanad")
#elastic.createIndex( 'mn_spr_sanad', 'monir', 'mn_spr_sanad')
# elastic.restorFileToElastic2('G:/Project2/111/mn_spr_sanad.zip', 'mn_spr_sanad', 'monir', False, 'mn_spr_sanad')
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_domain")
# elastic.createIndex( 'mj_qa_domain', 'majles', 'mj_qa_domain')
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_domain.zip', 'mj_qa_domain', 'majles', False, 'mj_qa_domain')
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_calendar")
# elastic.createIndex( 'gn_calendar', 'general', 'gn_calendar')
# elastic.restorFileToElastic2('G:/Project2/111/gn_calendar.zip', 'gn_calendar', 'general', False, 'gn_calendar')
# elastic.createIndex( 'gn_synonym', 'general', 'gn_synonym')
# elastic.restorFileToElastic2('G:/Project2/111/server112/gn_synonym.zip', 'gn_synonym', 'general', False, 'gn_synonym')
# elastic.backupIndexToZipfile("G:/Project2/111", "mn_sanad")
# elastic.createIndex( 'mn_sanad', 'monir', 'mn_sanad')
# elastic.restorFileToElastic2('G:/Project2/111/mn_sanad.zip', 'mn_sanad', 'monir', False, 'mn_sanad')
# -------------------------------------------------------
##
# elastic.backupIndexToZipfile("G:/Project2/111", "dh_haditha")
# elastic.backupIndexToZipfile("G:/Project2/111", "dh_parag_bge")
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_dataset")
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section_ai")
# elastic.backupIndexToZipfile("G:/Project2/111", "mn_crition")
# moveDataset1(elastic, "G:/Project2/111/gn_dataset_14031125.zip", "gn_dataset2")
# elastic.restorFileToElastic2('G:/Project2/111/mn_crition.zip', 'mn_crition', 'monir', False, 'mn_critions')
# -------------------------------------------------------
## backup from hamfahmi.ir
# -------------------------------------------------------
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_bayanat")
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_synonym")
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_log_search")
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_log_change")
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_calendar") # ???
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_entity")
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_setting")
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_research") # ???
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_jahat")
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_crition")
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_sanad") # ???
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_steps") # ???
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_nesha")
# -------------------------------------------------------
# -------------------------------------------------------
## backup from 160
# -------------------------------------------------------
path_back = "G:/Project2/111/server112/"
# elastic.backupIndexToZipfile(path_back, "gn_log_change")
# elastic.backupIndexToZipfile(path_back, "gn_log_action")
# elastic.backupIndexToZipfile(path_back, "gn_log_search")
# elastic.backupIndexToZipfile(path_back, "gn_dataset")
# elastic.backupIndexToZipfile(path_back, "gn_setting")
# elastic.backupIndexToZipfile(path_back, "gn_bayanat")
# elastic.backupIndexToZipfile(path_back, "gn_entity")
# elastic.backupIndexToZipfile(path_back, "gn_research")
# elastic.backupIndexToZipfile(path_back, "gn_synonym")
# elastic.backupIndexToZipfile(path_back, "mj_mashruh")
# elastic.backupIndexToZipfile(path_back, "qanonindex")
# elastic.backupIndexToZipfile(path_back, "mj_qa_section")
# elastic.backupIndexToZipfile(path_back, "mj_qa_opinion")
# elastic.backupIndexToZipfile(path_back, "mj_rg_section")
# elastic.backupIndexToZipfile(path_back, "mj_qa_qanon")
############elastic.backupIndexToZipfile(path_back, "rrk_index")
# elastic.backupIndexToZipfile(path_back, "mj_df_qanon")
######elastic.backupIndexToZipfile(path_back, "mj_qa_qanon_ai")
# elastic.backupIndexToZipfile(path_back, "mj_qa_section_ai")
# elastic.backupIndexToZipfile(path_back, "mj_qa_section-m1")
# elastic.backupIndexToZipfile(path_back, "gn_setting_help")
# gn_version
# mj_tmp_qanon
# gn_dataset2
# gn_setting2
# -------------------------------------------------------
# -------------------------------------------------------
##
# ## کد نمونه بازیابی از فایل
# path_back = 'G:/Project2/111/mj_qa_section.zip'
# elastic.createIndex('mj_qa_section', 'majles', 'mj_qa_section')
# elastic.zipFileToElastic(path_back, 'mj_qa_section')
# selastic.backupIndexToZipfile("G:/Project2/111", "dh_haditha")
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_calendar")
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
# elastic.backupIndexToZipfile("G:/Project2/111", "dh_haditha")
# elastic.backupIndexToZipfile("G:/Project2/111", "dh_volume_temp")
# elastic.restorFileToElastic("G:/Project2/111", "mj_qa_section_ai", 'majles', True, "mj_qa_section")
# elastic.restorFileToElastic('G:/Project2/111', 'mj_model', 'majles', True, 'mj_model' )
# elastic.restorFileToElastic2('G:/Project2/111/mj_model_20250512-003003.zip', 'mj_model', 'majles', True, 'mj_model')
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section_2_majles_repair.zip', 'mj_qa_section', 'majles', False, 'mj_qa_section')
# body= {
# "query": {
# "terms": {
# "qanon_id": [
# "qq83354",
# "qq83382",
# "qq112748",
# "qq112296",
# "qq83435",
# "qq114127",
# "qq175888",
# "qq85335",
# "qq84208",
# "qq114652",
# "qq114640"
# ]
# }
# },
# "sort": [
# {
# "qanon_id": {
# "order": "asc"
# },
# "child_order": {
# "order": "asc"
# }
# }
# ]
# }
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section", "mj_qa_section_Aab", body, False, ["content", "simplifies", "tcode_sub_old", "tcode_main_old", "code-ai", "ai_keywords"])
# -------------------------------------------------------
#### فایده ای نداشت ....!!!
## مسیر درختی مفید تولید نشد و عنوان قانون هم که فیلد مجزا داریم !
# create_context_ai(elastic, "mj_qa_section" )
# -------------------------------------------------------
##
# ai_url_chunk = os.getenv("ai_url_chunk")
# fill_chunk_tags(elastic, ai_url_chunk, "mj_qa_section")
# -------------------------------------------------------
##
# برچسبهای هوشمند
# payload={
# "text":"سلام علیکم"
# }
# response = requests.request("POST", ai_url_vec, headers=HEADERS, json=payload)
# print(response.text)
# print(response)
# payload={
# "text":"طرفین به منظور اتمام مطالعات و احداث نیروگاه‌های جریانی ارس و تأسیسات مربوطه، منطقه مشترک ساختمانی و مطالعاتی را تعیین و امنیت این منطقه را در طول مدت اجراء و بهره‌برداری تأمین می‌نمایند. "
# }
# response = requests.request("POST", ai_url_class, headers=HEADERS, json=payload)
# print(response.text)
# print(response)
# resp = json.loads(response.text)
# print(resp['result'])
# -------------------------------------------------------
##
## پشتیبان گیری
# path_back = os.getcwd() + '/data_back'
path_back = "G:/Project2/111"
# if not os.path.exists(path_back) :
# os.makedirs(path_back)
# print('---> path_back = ' + path_back)
# elastic.backupIndexToZipfile(path_back, "mj_qa_qanon")
# elastic.backupIndexToZipfile(path_back, "mj_qa_section")
# elastic.backupIndexToZipfile(path_back, "mj_qa_section", '', {}, True, [], ["pos_tags", "chunk_tags", "version_info"])
# elastic.backupIndexToZipfile(path_back, "mj_qa_section_ai")
# elastic.backupIndexToZipfile(path_back, "mj_rg_section")
# elastic.backupIndexToZipfile(path_back, "mj_qa_opinion")
## کد نمونه بازیابی از فایل
# path_back = 'G:/Project2/_back/back_data/data_majles/elastic/v1.0/full'
# elastic.restorFileToElastic(path_back, 'mj_qa_section', 'majles')
# elastic.restorFileToElastic(path_back, 'gn_log_action')
# -------------------------------------------------------
##
# -------------------------------------------------------
##
# -------------------------------------------------------
# -- جهت استخراج دیتاست بخشی از الاستیک برای استفاده در هوش مصنوعی
body = {
"query": {
"bool": {
"must": [
{
"bool": {
"must_not": [
{"terms": {"nlp_tags": ["concept_no"]}},
{"exists": {"field": "ai_keywords"}},
]
}
},
{
"bool": {
"filter": {
"bool": {
"must": [
{"terms": {"qanon_etebar": ["", "معتبر"]}},
{
"terms": {
"title_type": [
"عادی",
"اصلی",
"موافقتنامه",
"بودجه",
]
}
},
]
}
}
}
},
]
}
}
}
# elastic.exportToJsonForAI("./data/", "mj_qa_section", "keywords_extract_40K", body, ["content"])
# body={
# "query": {
# "term": {
# "main_type": {
# "value": "قانون"
# }
# }
# }
# }
# elastic.exportToJsonForAI("./data/", "mj_qa_qanon", "qanon_title", body, ["title", "ts_date", "ts_year"])
# body={
# "query": {
# "term": {
# "main_type": {
# "value": "مقرره"
# }
# }
# }
# }
# elastic.exportToJsonForAI("./data/", "mj_qa_qanon", "regular_title", body, ["title", "ts_date", "ts_year"])
# -------------------------------------------------------
print("finished")
+748
View File
@@ -0,0 +1,748 @@
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import sys
import traceback
from thefuzz import fuzz
import re
from app.common.jalali import Persian
from app.common.config_base import *
from app.common.config_base import *
from app.common.general_functions import *
def read_section_table():
cursor, cnxn = create_cursor()
query = """SELECT s.ID as section_id,s.SECTIONTEXT as section_text, l.ID as law_id, l.ISLAW as law_islaw
from lwSection s
left join lwLaw l on s.F_LWLAWID = l.ID
where l.ISLAW = 1"""
cursor.execute(query)
section_list = {}
i = 0
for item in cursor.fetchall():
i += 1
# if i == 10000:# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! برداشته شود
# break
# if i%1000 == 0:
# print(i)
# row = cursor.fetchone()
id = int(item.section_id)
try:
text = removeHtmlNoTableTag(item.section_text)
except Exception as e:
text = item.section_text
section_text = normalize_content(text)
section_list[id] = {"id": id, "section_text": section_text}
cursor.close()
cnxn.close()
return section_list
def read_law_table():
cursor, cnxn = create_cursor()
query = """SELECT [ID],[CAPTION],[APPROVEDATE]
FROM [Qavanin].[dbo].[lwLaw]
where [ISLAW] = 1
order by [APPROVEDATE] desc"""
cursor.execute(query)
law_dict = {}
approve_date_error = []
for item in cursor.fetchall():
# row = cursor.fetchone()
id = int(item.ID)
caption = normalize_content(item.CAPTION)
# تبدیل تاریخ با فرمت رشته به فرمت تاریخ
date = str(item.APPROVEDATE).split("/")
try:
approve_date = Persian(int(date[0]), int(date[1]), int(date[2]))
except:
approve_date_error.append(date)
# در موارد خطا، اپروو دیت کنترل شود
law_dict[id] = {"id": id, "caption": caption, "approve_date": approve_date}
cursor.close()
cnxn.close()
return law_dict
def law_recognizer(text, law_dict):
i = 0
try:
nlp_parser, normalized_content = getMetaData(text)
except Exception as e:
filename = "law_section_errors.txt"
exc_type, exc_value, exc_traceback = sys.exc_info()
frame = exc_traceback.tb_frame
function_array = traceback.extract_tb(exc_traceback)
current_function = function_array[len(function_array) - 1]
error = f"""
table : Law
filename : {current_function.filename}
function : {current_function.name}
err line no : {current_function.lineno}
err line : {current_function.line}
err message : {e}
"""
save_error(error, filename)
text_token_list = normalized_content.strip().split()
matched_token_index_list = []
# جمع آوری عناوین احتمالی قانون در یک متن بر اساس کلیدواژه قانون
for index, token in enumerate(text_token_list):
if "قانون" in token:
matched_token_index_list.append(index)
content_token_list = []
law_token_list = []
for index, item in enumerate(matched_token_index_list):
# اگر آیتم، آخرین عنصر موجود در آرایه نبود ...
if index < len(text_token_list):
# content_token_list.append(text_token_list[item])
# نُه توکن بعدی را به عنوان عبارات تکمیلی احتمالی عنوان قانون ذخیره می کنیم
if index + 9 < len(text_token_list):
for i in range(9):
if item + (i + 1) >= len(text_token_list):
break
content_token_list.append(text_token_list[item + (i + 1)])
i = 0
# توکن های باقیمانده تا پایان آرایه را ذخیره کن
else:
j = 0
while j < len(text_token_list) - index:
if item + (j + 1) >= len(text_token_list) - index:
break
content_token_list.append(text_token_list[item + (j + 1)])
j += 1
j = 0
law_token_list.append(content_token_list)
content_token_list = []
matched_law_list = {}
for index, item in enumerate(law_token_list):
found_law_list_1 = {}
found_law_list_2 = {}
found_law_list_3 = {}
found_law_list_4 = {}
found_law_list_5 = {}
found_law_list_6 = {}
found_law_list_7 = {}
found_law_list_8 = {}
found_law_list_9 = {}
previous_found_count = 0
# در ابتدا اولین توکن عبارتی که احتمالا عنوان یک قانون است را در عنوان قانون موجود در بانک بررسی می کنیم
# در مراحل بعدی تا به نُه گام برسیم، یکی یکی توکن ها را به توکن اول اضافه و سپس با عناوین قانون ها مقایسه می کنیم
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، صفر بود،
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
if len(item) < 1:
break
law_section = item[0]
for id, value in law_dict.items():
# عنوان قانونی که در حال مقایسه متن مورد نظر با آن هستیم
current_caption = value["caption"]
current_approve_date = value["approve_date"]
# بررسی وجود عبارت مورد نظر در عنوان قانون
if current_caption.__contains__(law_section):
# به دست آوردن اولین توکن از عنوان قانون
current_law_first_token = current_caption.strip().split(" ")[0]
# اگر اولین توکن از عنوان قانون برابر با کلمه "قانون" بود، این کلمه را نادیده میگیریم
# زیرا در لیست مربوط به لیست توکن های احتمالی مربوط به قوانین، کلمه قانون را در نظر نگرفته ایم
if current_law_first_token == "قانون":
current_law_first_token = current_caption.strip().split(" ")[1]
if law_section == current_law_first_token:
# اگر زیر رشته موردنظر ما در عنوان قانون وجود داشت، نام قانون را در یک لیست ذخیره می کنیم.
# در مرحله بعد متن احتمالی قانون که در حال بررسی آن هستیم را با این لیست مقایسه می کنیم تا مقایسه محدود تری داشته باشیم
found_law_list_1[id] = {
"id": id,
"caption": current_caption,
"approve_date": current_approve_date,
}
else:
continue
if len(found_law_list_1) == 0:
continue
else:
if len(found_law_list_1) == 1:
found_law = found_law_list_1.popitem()
k = 0
matched_string = ""
found_law_caption = (
found_law[1]["caption"].strip().removeprefix("قانون")
)
found_law_caption_tokens = found_law_caption.strip().split()
if item[0] != "لازم":
for k in range(len(item)):
if k >= len(found_law_caption_tokens):
break
if item[k] == found_law_caption_tokens[k]:
matched_string += item[k] + " "
else:
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": matched_string.strip(),
"original_string": item,
"multi_flag": False,
}
break
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": matched_string.strip(),
"original_string": item,
"multi_flag": False,
}
continue
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، یکی بود،
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
if len(item) < 2:
continue
law_section = item[0] + " " + item[1]
for id, value in found_law_list_1.items():
current_caption = value["caption"]
current_approve_date = value["approve_date"]
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
# if current_caption.__contains__(law_section):
if rate == 100:
found_law_list_2[id] = {
"id": id,
"caption": current_caption,
"approve_date": current_approve_date,
}
if len(found_law_list_2) == 0:
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
if len(found_law_list_1) > 1:
# به دقت کنترل شود
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
sorted_found_law_list = dict(
sorted(found_law_list_1.items(), key=lambda item: item[0])
)
found_law = sorted_found_law_list.popitem()
matched_law_list[index] = {
"found_law_list": sorted_found_law_list,
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": True,
}
continue
else:
if len(found_law_list_2) == 1:
found_law = found_law_list_2.popitem()
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": False,
}
# اگر در جستجوی عنوان قانون، به یک مورد منحصر به فرد رسیده بودیم، فقط همین یک عنوان را ذخیره کند
continue
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، دوتا بود،
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
if len(item) < 3:
continue
law_section = item[0] + " " + item[1] + " " + item[2]
for id, value in found_law_list_2.items():
current_caption = value["caption"]
current_approve_date = value["approve_date"]
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
# if current_caption.__contains__(law_section):
if rate == 100:
found_law_list_3[id] = {
"id": id,
"caption": current_caption,
"approve_date": current_approve_date,
}
if len(found_law_list_3) == 0:
if len(found_law_list_2) > 1:
# به دقت کنترل شود
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
sorted_found_law_list = dict(
sorted(found_law_list_2.items(), key=lambda item: item[0])
)
found_law = sorted_found_law_list.popitem()
matched_law_list[index] = {
"found_law_list": sorted_found_law_list,
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": True,
}
continue
else:
if len(found_law_list_3) == 1:
found_law = found_law_list_3.popitem()
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": False,
}
continue
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، سه تا بود،
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
if len(item) < 4:
continue
law_section = item[0] + " " + item[1] + " " + item[2] + " " + item[3]
for id, value in found_law_list_3.items():
current_caption = value["caption"]
current_approve_date = value["approve_date"]
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
# if current_caption.__contains__(law_section):
if rate == 100:
found_law_list_4[id] = {
"id": id,
"caption": current_caption,
"approve_date": current_approve_date,
}
if len(found_law_list_4) == 0:
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
if len(found_law_list_3) > 1:
# به دقت کنترل شود
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
sorted_found_law_list = dict(
sorted(found_law_list_3.items(), key=lambda item: item[0])
)
found_law = sorted_found_law_list.popitem()
matched_law_list[index] = {
"found_law_list": sorted_found_law_list,
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": True,
}
continue
else:
if len(found_law_list_4) == 1:
found_law = found_law_list_4.popitem()
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": False,
}
continue
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، چهارتا بود،
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
if len(item) < 5:
continue
law_section = (
item[0] + " " + item[1] + " " + item[2] + " " + item[3] + " " + item[4]
)
for id, value in found_law_list_4.items():
current_caption = value["caption"]
current_approve_date = value["approve_date"]
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
# if current_caption.__contains__(law_section):
if rate == 100:
found_law_list_5[id] = {
"id": id,
"caption": current_caption,
"approve_date": current_approve_date,
}
if len(found_law_list_5) == 0:
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
if len(found_law_list_4) > 1:
# به دقت کنترل شود
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
sorted_found_law_list = dict(
sorted(found_law_list_4.items(), key=lambda item: item[0])
)
found_law = sorted_found_law_list.popitem()
matched_law_list[index] = {
"found_law_list": sorted_found_law_list,
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": True,
}
continue
else:
if len(found_law_list_5) == 1:
found_law = found_law_list_5.popitem()
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": False,
}
continue
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، پنج تا بود،
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
if len(item) < 6:
continue
law_section = (
item[0]
+ " "
+ item[1]
+ " "
+ item[2]
+ " "
+ item[3]
+ " "
+ item[4]
+ " "
+ item[5]
)
for id, value in found_law_list_5.items():
current_caption = value["caption"]
current_approve_date = value["approve_date"]
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
# if current_caption.__contains__(law_section):
if rate == 100:
found_law_list_6[id] = {
"id": id,
"caption": current_caption,
"approve_date": current_approve_date,
}
if len(found_law_list_6) == 0:
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
if len(found_law_list_5) > 1:
# به دقت کنترل شود
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
sorted_found_law_list = dict(
sorted(found_law_list_5.items(), key=lambda item: item[0])
)
found_law = sorted_found_law_list.popitem()
matched_law_list[index] = {
"found_law_list": sorted_found_law_list,
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": True,
}
continue
else:
if len(found_law_list_6) == 1:
found_law = found_law_list_6.popitem()
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": False,
}
continue
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، شش تا بود،
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
if len(item) < 7:
continue
law_section = (
item[0]
+ " "
+ item[1]
+ " "
+ item[2]
+ " "
+ item[3]
+ " "
+ item[4]
+ " "
+ item[5]
+ " "
+ item[6]
)
for id, value in found_law_list_6.items():
current_caption = value["caption"]
current_approve_date = value["approve_date"]
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
# if current_caption.__contains__(law_section):
if rate == 100:
found_law_list_7[id] = {
"id": id,
"caption": current_caption,
"approve_date": current_approve_date,
}
if len(found_law_list_7) == 0:
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
if len(found_law_list_6) > 1:
# به دقت کنترل شود
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
sorted_found_law_list = dict(
sorted(found_law_list_6.items(), key=lambda item: item[0])
)
found_law = sorted_found_law_list.popitem()
matched_law_list[index] = {
"found_law_list": sorted_found_law_list,
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": True,
}
continue
else:
if len(found_law_list_7) == 1:
found_law = found_law_list_7.popitem()
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": False,
}
continue
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، هفت تا بود،
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
if len(item) < 8:
continue
law_section = (
item[0]
+ " "
+ item[1]
+ " "
+ item[2]
+ " "
+ item[3]
+ " "
+ item[4]
+ " "
+ item[5]
+ " "
+ item[6]
+ " "
+ item[7]
)
for id, value in found_law_list_7.items():
current_caption = value["caption"]
current_approve_date = value["approve_date"]
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
# if current_caption.__contains__(law_section):
if rate == 100:
found_law_list_8[id] = {
"id": id,
"caption": current_caption,
"approve_date": current_approve_date,
}
if len(found_law_list_8) == 0:
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
if len(found_law_list_7) > 1:
# به دقت کنترل شود
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
sorted_found_law_list = dict(
sorted(found_law_list_7.items(), key=lambda item: item[0])
)
found_law = sorted_found_law_list.popitem()
matched_law_list[index] = {
"found_law_list": sorted_found_law_list,
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": True,
}
continue
else:
if len(found_law_list_8) == 1:
found_law = found_law_list_8.popitem()
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": False,
}
continue
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، هشت تا بود،
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
if len(item) < 9:
continue
law_section = (
item[0]
+ " "
+ item[1]
+ " "
+ item[2]
+ " "
+ item[3]
+ " "
+ item[4]
+ " "
+ item[5]
+ " "
+ item[6]
+ " "
+ item[7]
+ " "
+ item[8]
)
for id, value in found_law_list_8.items():
current_caption = value["caption"]
current_approve_date = value["approve_date"]
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
# if current_caption.__contains__(law_section):
if rate == 100:
found_law_list_9[id] = {
"id": id,
"caption": current_caption,
"approve_date": current_approve_date,
}
if len(found_law_list_9) == 0:
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
if len(found_law_list_8) > 1:
# به دقت کنترل شود
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
sorted_found_law_list = dict(
sorted(found_law_list_8.items(), key=lambda item: item[0])
)
found_law = sorted_found_law_list.popitem()
matched_law_list[index] = {
"found_law_list": sorted_found_law_list,
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": True,
}
continue
else:
if len(found_law_list_9) == 1:
found_law = found_law_list_9.popitem()
matched_law_list[index] = {
"law_id": found_law[1]["id"],
"law_captions": found_law[1]["caption"],
"matched_string": law_section,
"original_string": item,
"multi_flag": False,
}
# law_token_list = law_token_list
return matched_law_list, law_token_list
def law_title_search():
section_dict = read_section_table()
law_dict = read_law_table()
i = 0
probable = 0
foundlist = 0
found_law = 0
final_found_law = {}
for id, value in section_dict.items():
text = value["section_text"]
matched_law_list, law_token_list = law_recognizer(text, law_dict)
if (len(law_token_list)) > 0:
probable += len(law_token_list)
for k, v in matched_law_list.items():
if v["multi_flag"]:
foundlist += 1
final_found_law[i] = {
"law_id": v["law_id"],
"multi_flag": v["multi_flag"],
"found_law_list": v["found_law_list"],
"law_caption": v["law_captions"],
"matched_string": v["matched_string"],
"original_string": v["original_string"],
}
if not v["multi_flag"]:
found_law += 1
final_found_law[i] = {
"law_id": v["law_id"],
"multi_flag": v["multi_flag"],
"law_caption": v["law_captions"],
"matched_string": v["matched_string"],
"original_string": v["original_string"],
}
print(i + 1)
i += 1
print("************ Result ************")
print("probable: " + str(probable))
print(
"found_law: "
+ str(found_law)
+ " - "
+ str(int((found_law / probable) * 100))
+ " %"
)
print(
"found_list: "
+ str(foundlist)
+ " - "
+ str(int((foundlist / probable) * 100))
+ " %"
)
return final_found_law
final_found_law = law_title_search()
ref_parser = []
for ref_item in final_found_law.items():
ref_parser.append(
{
"index_start": int(ref_item["start_token_state"]),
"index_end": int(ref_item["end_token_state"]),
"text": ref_item[
"founded_item"
], # توکن هایی که متناظر آنها در عناوین قانون ها وجود داشته
"text_tokens": ref_item[
"founded_item"
], # ده توکنی که احتمالا عنوان یک قانون باشد
"result": ref_item["pattern_value"], # لیست عناوین یافت شده
"type": "law_title",
"ref_link": "",
}
)
# try:
# nlp_parser = getMetaData(text)
# except Exception as e:
# filename = 'law_section_errors.txt'
# exc_type, exc_value, exc_traceback = sys.exc_info()
# frame = exc_traceback.tb_frame
# function_array = traceback.extract_tb(exc_traceback)
# current_function = function_array[len(function_array)-1]
# error = f'''
# filename : {current_function.filename}
# function : {current_function.name}
# err line no : {current_function.lineno}
# err line : {current_function.line}
# err message : {e}
# err date : {datetime.datetime.now()}
# '''
# print(error +'\n' + '*'*50)
# save_error(error, filename)
# print(nlp_parser)