This commit is contained in:
hsafaei
2026-02-17 18:07:16 +03:30
parent 9c99d816db
commit 3a57a2cfc2
8 changed files with 3850 additions and 3174 deletions
+536
View File
@@ -0,0 +1,536 @@
from time import time
import requests
from dotenv import load_dotenv
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from app.common.general_functions import *
from app.common.config_base import *
from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper
load_dotenv(dotenv_path="config.env")
host = os.getenv("HOST_160")
password = os.getenv("HOST_160_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 fill_nlp_tags(elastic, index_name_o = "mj_qa_section", path_resource='resource/my/') :
id = ""
body = {
### این فهرست قوانینی است که تعداد زیادی از اجزاء دارای لول بزرگتر از 8 دارند
# "query": {
# "bool": {
# "must_not": [
# {
# "terms": {
# "qanon_id":["qq86911", "qq83307", "qq178971", "qq111830", "qq233930", "qq85434"]
# }
# }
# ]
# }
# },
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "asc"}}
]
}
useful_ids = {}
# useful_titles_al = []
# useful_finded = []
# خواندن کلمات موجود در فایل
with open( path_resource+"qanon_usefull.txt", 'r', encoding='utf-8') as f:
for line in f :
id = line.strip().split('=')[0]
if id not in useful_ids :
useful_ids[id] = 1
bulk_data = []
total_count = 0
try:
try:
list = elastic.es_iterate_all_documents(index_name_o, body)
except Exception as e:
save_error(0, e)
count = 0
print('*' * 20 , ' count=', elastic.total)
path_heading=[]
level_parent= 0
file_error = open('error_fill_nlp_tags.txt', 'w+', encoding='utf-8')
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
#qanon_etebar = entry.get("qanon_etebar", "")
state_etebar = entry.get("state_etebar", "")
title_type = entry.get("title_type", "")
qanon_title = entry.get("qanon_title", "")
qanon_id = entry.get("qanon_id", "0")
other_info = entry.get("other_info", {})
parent_id = entry.get("parent_id", "0")
content = entry.get("content", "")
full_path = other_info["full_path"]
nlp_tags = []
#"full_path": "ماده واحده>فصل ششم>بخش سوم>قسمت چهارم>فصل هشتم>ماده 153>بند ب>جزء 4",
full_path = full_path.strip().strip('>')
paths = full_path.split('>')
last_path = ''
if paths :
last_path = paths[-1]
level_2 = len(paths)
###--------------------شناسایی بزرگی کوچکی متن -------------------
word_len = len(split_words(content))
###--------------------شناسایی بزرگی کوچکی متن -------------------
if word_len > 100 :
nlp_tags.append("words_big")
elif word_len > 50 :
nlp_tags.append("words_medium")
else :
nlp_tags.append("words_small")
###--------------------شناسایی هدینگ بودن -------------------
prefix, title, content_type = normalHeadingTitle(content, last_path)
if not parent_id or parent_id == '0' or parent_id==0 :
path_heading = []
level_parent = 0
###--------------------شناسایی قوانین پرکاربرد -------------------
if qanon_id in useful_ids:
nlp_tags.append("qanon_usefull")
###-------------------- تعیین مسیر هدینگ -------------------
## هرچند با پرنت آی دی این خالی می شود ولی برای مطمئن کاری این شرط اضافه شد
elif full_path=='عنوان' or full_path=='موخره' or full_path=='امضاء' :
path_heading = []
level_parent = 0
elif level_2 < level_parent :
diff = level_parent - level_2
while diff > 0 and path_heading :
path_heading.pop()
diff = diff - 1
level_parent = level_2
# print('id :', id , ' --diff ', diff, path_heading )
if level_2 >= level_parent :
# برای اجزاء بعدی شناسایی و ذخیره می شود نه جزء جاری
if prefix != '' and title != '':
if level_2 == level_parent and path_heading :
path_heading.pop()
if len(title) < 256 :
path_heading.append(title)
nlp_tags.append("heading")
level_parent = level_2
###--------------------------------------------------------
full_path_prev = full_path
full_path = title_type + ' :: ' + full_path
heading_in_content = ''
if "heading" in nlp_tags :
nlp_tags.append("concept_no")
elif 'تفسیر' in state_etebar or 'تفسیر' in last_path :
nlp_tags.append("concept_side")
elif 'عنوان' in last_path or 'موخره' in last_path or 'امضاء' in last_path or 'سربرگ' in last_path or 'فهرست' in last_path or 'منشور' in last_path :
nlp_tags.append("concept_no")
elif 'ماده' in last_path or 'اصل' in last_path or 'متن' in last_path or 'مقدمه' in last_path or 'نامه' in last_path or 'کلیات' in last_path or 'قسمت' in last_path or 'توضیح' in last_path or 'سوال' in last_path or 'استفساریه' in last_path :
nlp_tags.append("concept_base")
elif 'بند' in last_path or 'جزء' in last_path or 'زیرجزء' in last_path or 'شماره' in last_path or 'ردیف' in last_path or 'پاورقی' in last_path or 'اشاره' in last_path or 'تنبیه' in last_path or 'بخش' in last_path or 'جواب' in last_path or 'مقرره' in last_path :
nlp_tags.append("concept_week")
elif 'تبصره' in last_path or 'بخش' in last_path or 'تذکر' in last_path or 'توصیه' in last_path or 'توجه' in last_path :
nlp_tags.append("concept_middle")
elif 'الحاقی' in state_etebar or 'الحاقی' in last_path :
nlp_tags.append("concept_week")
elif 'جدول' in last_path :
nlp_tags.append("concept_bad")
elif content_type in ['تبصره','بخش','تذکر'] :
nlp_tags.append("concept_middle")
elif content_type in ['ماده'] :
nlp_tags.append("concept_base")
elif last_path in ['اول', 'دوم', 'سوم', 'چهارم', 'پنجم', 'ششم', 'هفتم', 'نهم', 'دهم']:
if title_type == 'بودجه' :
nlp_tags.append("concept_middle")
else:
nlp_tags.append("concept_week")
elif last_path in ['الف', 'ب', 'پ', 'ت', 'ث', 'ج', 'چ', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'ژ', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ک', 'گ', 'ل', 'م', 'ن', 'و', 'ه', 'ی']:
if title_type == 'بودجه' :
nlp_tags.append("concept_middle")
else:
nlp_tags.append("concept_week")
elif is_number_string(last_path.replace('-', '').replace('/', '').replace('\\', '')) :
if title_type == 'بودجه' :
nlp_tags.append("concept_middle")
else:
nlp_tags.append("concept_week")
# elif qanon_etebar == 'منسوخه' :
# pass
elif 'پروتکل' in full_path or 'موافقتنامه' in full_path or 'قطعنامه' in full_path or 'پیوست' in full_path or 'عهدنامه' in full_path or 'توافقنامه' in full_path or 'معاهده' in full_path or 'کنوانسیون' in full_path or 'قرارداد' in full_path :
if not title :
nlp_tags.append("concept_bad")
elif len(title) < 50 :
if prefix :
nlp_tags.append("concept_head")
heading_in_content = title
else :
nlp_tags.append("concept_week")
else :
nlp_tags.append("concept_base")
elif prefix :
if title and len(title) < 50 :
file_error.write('---***---- data id=' + id + ' full_path : ' + full_path + ' prefix : '+ prefix +' --- '+ title + '\n')
print('---***---- data id=', id, ' full_path : ', full_path , ' prefix : ', prefix ,' --- ', title)
else :
if title and len(title) < 50:
if 'فصل' in last_path or 'مبحث' in last_path :
nlp_tags.append("concept_head")
heading_in_content = title
if full_path_prev == '' :
nlp_tags.append("concept_bad")
else :
file_error.write('------- data id='+ id + ' full_path : '+ full_path + ' prefix : '+ prefix +' --- '+ title + '\n')
print('------- data id=', id, ' full_path : ', full_path , ' prefix : ', prefix ,' --- ', title)
elif len(title) >= 50 :
if full_path_prev == '' :
nlp_tags.append("concept_bad")
else :
file_error.write('### ####### error data id='+ id + ' full_path : '+ full_path + ' prefix : '+ prefix +' --- '+ title + '\n')
print('### ####### error data id=', id, ' full_path : ', full_path , ' prefix : ', prefix ,' --- ', title)
###--------------------------------------------------------
## فقط در همین جزء ثبت شود
path_heading2 = path_heading
if heading_in_content :
path_heading2.append(heading_in_content)
## ----------------------------------------
data = {}
data["nlp_tags"]= nlp_tags
data["path_headings"]= path_heading2
data["word_len"] = word_len
data["level"]= level_2
eid = id
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)
)
elastic.updateBulkList(bulk_data, index_name_o)
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_o)
bulk_data = []
except Exception as e:
save_error(id, e)
# print("Exception: " + str(e))
# print( e)
# print("%s -> %.2f " % (id , (counter / total) if total > 0 else 0))
# try:
# print('ts_date:'+ts_date)
# except:
# print('not definded')
file_error.close()
print("=" * 10, " fill_content_nlp finished")
##----- مرحله دوم -----------------
## شناسایی فرزندان اجزاء اصلی
def extract_nlp_childs(elastic, index_name_i = "mj_qa_section", index_name_o = "") :
counter = 0
total = 0
id = ""
body={
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "desc"}}
]
}
if not index_name_o :
index_name_o = index_name_i
dicParents = {}
bulk_data = []
total_count = 0
try:
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
count = 0
qanon_id_prev = ""
parent_id_prev = "0"
count_normal = 0
count_un_normal = 0
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
content = entry.get("content", "")
path_headings = entry.get("path_headings", [])
word_len = entry.get("word_len", [])
qanon_id = entry.get("qanon_id", "0")
parent_id = entry.get("parent_id", "0")
nlp_tags = entry.get("nlp_tags", [])
## ثبت اطلاعات
if qanon_id != qanon_id_prev and dicParents:
bulk_list = []
for key, value in dicParents.items():
bulk_list.append({
'_id': key,
'_source': {
"nlp_childs" : value
}
})
word_len = 0
for child in value :
word_len += child["word_len"]
if word_len > 512 :
count_un_normal +=1
print('--- id', key , ' child_count:', len(value), ' words:', word_len, ' count_normal:', count_normal, ' count_un_normal:', count_un_normal)
else :
count_normal +=1
elastic.updateBulkList(bulk_list, index_name_o)
dicParents = {}
qanon_id_prev = qanon_id
### نیازی به بردار سازی و جستجوی معنایی یا ارتباط یابی نیست
if 'concept_no' in nlp_tags or 'concept_bad' in nlp_tags or 'concept_base' in nlp_tags :
continue
### تا حد امکان با محتوای اصلی قبل، بردار شود و همانجا ذخیره شود
elif 'concept_week' in nlp_tags or 'concept_middle' in nlp_tags or 'concept_side' in nlp_tags :
if parent_id and parent_id != '0' and parent_id != 0 :
#if 'words_small' in nlp_tags or 'words_small' in nlp_tags :
if parent_id not in dicParents :
dicParents[parent_id] = []
dicParents[parent_id].append({
"word_len": word_len,
"id": id ,
# "content" : content
})
continue
except Exception as e:
# save_error(id, e)
print("Exception: " + e)
print( e)
print("%s -> %.2f " % (id , (counter / total) if total > 0 else 0))
print("=" * 10, "import_data_embeding finished")
def isMomSection(other_info, content):
if not other_info["full_path"] :
return True
paths = other_info["full_path"].split('>')
last_item = paths[len(paths)-1]
print(paths)
print(last_item)
if "ماده" in last_item :
return True
content = content.strip()
if re.match(r"^((ضمیمه)|(جدول))\s*\d*$", content):
return True
## ----------------------------------------------------------
def recursive_collect_child_sections(section_id, all_sections):
"""
تابع بازگشتی که تمام درخت زیرمجموعه یک سکشن را بازمیگرداند
"""
result = []
nlp_childs = all_sections.get(section_id, {}).get('nlp_childs', [])
if not nlp_childs:
return result
nlp_childs_ids = [_child['id'] for _child in nlp_childs]
for child_id in nlp_childs_ids:
result.extend(
recursive_collect_child_sections(child_id, all_sections)
)
result.append(child_id)
return result
def extract_qanon_group_text(elastic, qanon_id, path_out="data/chunks/" ):
text = ""
body={
"query": {
"term": {
"qanon_id": {
"value": qanon_id
}
}
},
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "asc"}}
]
}
all_sections = {}
try:
list_ = elastic.es_iterate_all_documents(index_name_o, )
for item in list_ :
all_sections[item["_id"]]=item["_source"]
except Exception as e:
save_error(0, e)
original_sections = []
qanon_sections_dict = {}
for section_id in all_sections:
if all_sections[section_id]['qanon_id'] == qanon_id:
# ذخیره سکشن های اصلی هر قانون
section_data = all_sections[section_id]
section_data['section_id'] = section_id
# ریختن تمام اطلاعات مربوط به هر سکشن در یک دیکشنری با کلید child_order
qanon_sections_dict[int(all_sections[section_id]['child_order'])] = section_data
# مرتب سازی سکشن های یک قانون بر اساس child_order
qanon_sections_dict = dict(sorted(qanon_sections_dict.items()))
for item in qanon_sections_dict:
original_sections.append(qanon_sections_dict[item]['section_id'])
# گرفتن تمام سکشن های مربوط به یک قانون
all_chunk_sections = []
qanoon_text = ''
# nlp_childs_list = []
nlp_childs_ids = []
child_sections_ids = []
row_counter = 1
for row_order, section_id in enumerate(original_sections, 1):
# لیست سکشن هایی که زیرجزء یک سکشن دیگر بوده اند در متغیر child_sections_ids قرار دارد و چک می کنیم که سکشن را در بازسازی متن قانون، تکرار نکنیم
if section_id in child_sections_ids:
continue
nlp_childs_ids = recursive_collect_child_sections(section_id, all_sections)
nlp_childs_ids.reverse()
# اضافه کردن سکشن های زیر مجموعه به لیست سکشن هایی که در دور بعد مجددا بررسی نشوند
child_sections_ids.extend(nlp_childs_ids)
qanoon_text += f"بخش (-- {row_counter} --)\n{all_sections[section_id]['content']}\n"
for sub_id in nlp_childs_ids:
qanoon_text += f"{all_sections[sub_id]['content']}\n"
nlp_childs_ids.clear()
qanoon_text += f'\n****************************************************\n'
row_counter += 1
# ذخیره کل قانون جدید(جزءنگاری جدید) با فرمت تکست
with open(f"./data_nlpchild/sample_chunking_{qanoon}.txt", 'w') as file:
file.write(qanoon_text)
qanoon_sections.clear()
qanoon_text = ''
def import_groups_to_elastic_context(elastic):
id = ""
body = {
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "asc"}}
]
}
bulk_data = []
total_count = 0
try:
list_ = elastic.es_iterate_all_documents(index_name_o, body)
except Exception as e:
print("********** Exception Error", str(e))
try:
prev_qanon_id = 0
dic_child_ids = {}
for mentry in list(list_):
count += 1
entry = mentry["source"]
id = entry.get("id", "")
qanon_id = entry.get("qanon_id", "")
nlp_childs = entry.get("nlp_childs", [])
except Exception as e:
print("***************** Exception Error", str(e))
if __name__ == "__main__":
fill_nlp_tags(elastic, index_name_o = "mj_qa_section", path_resource='data/')
extract_nlp_childs(elastic, index_name_i = "mj_qa_section", index_name_o = "")
#isMomSection({"full_path":"باب اول>فصل اول>ماده 8"})
+77 -7
View File
@@ -7,7 +7,6 @@ import uuid
import pandas as pd
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
@@ -199,7 +198,7 @@ def import_project_to_elastic(
print(t2 - t1)
def import_tlist_projects():
def import_tlist_projects_to_gn_tree():
config_env = load_dotenv(dotenv_path="./config.env")
MYSQL_username = os.getenv("MYSQL_username")
@@ -255,6 +254,8 @@ def import_option_to_elastic(
index_name_o="gn_option",
):
res = get_options(main_key)
if not res :
res = get_options_2(main_key)
titles = []
for item in res :
title = item["value"]
@@ -273,6 +274,7 @@ def import_option_to_elastic(
"titles": titles,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
return data
def import_option_base_list(elastic):
@@ -363,6 +365,69 @@ def import_option_base_list(elastic):
elastic, op["main_key"], op["main_label"], group_key, eid
)
def import_option_base_list_2(elastic):
op_list = [
{
"main_key": "receive_handle_type",
"main_label": "پرونده - اعلام وصول - نوع فوریت",
},
{
"main_key": "refer_commission_type",
"main_label": "پرونده - ارجاع - نوع کمیسیون",
},
{
"main_key": "commission_report_type",
"main_label": "پرونده - گزارش کمیسیون - نوع گزارش ",
},
{
"main_key": "parl_handle_info_type",
"main_label": "پرونده - اعلام وصول - نوع رسیدگی ",
},
{
"main_key": "parl_handle_demand_type",
"main_label": "پرونده - صحن - نوع تقاضاها ",
},
{
"main_key": "letter_result_type",
"main_label": "پرونده - ارسال و دریافت - نتیجه نامه ",
},
{
"main_key": "eblagh_qanon_time_type",
"main_label": "پرونده - نوع زمانی قانون (آزمایشی/موقت) ",
},
{
"main_key": "eblagh_qanon_template_type",
"main_label": "پرونده - نوع قالبی قانون ",
},
{
"main_key": "qasection_conformity",
"main_label": "پرونده - بررسی و تایید محتوا ",
},
{
"main_key": "qasection_eblagh_letters_type",
"main_label": "پرونده - ارسال و دریافت امضاء و انتشار ",
}
]
list_data = []
number = 0
for op in op_list:
number = number + 1
print(op["main_key"])
eid = "mb_op2_" + str(number)
group_key = "عناوین انتخابی فرمها"
if "group_key" in op:
group_key = op["group_key"]
_source = import_option_to_elastic(
elastic, op["main_key"], op["main_label"], group_key, eid
)
list_data.append({
'id': eid,
'_source' : _source
})
return list_data
def import_option_codes(elastic, index_name_o="gn_option"):
@@ -615,17 +680,22 @@ if __name__ == "__main__":
# ---مرحله اول
# import_tlist_projects()
# import_tlist_projects_to_gn_tree()
# import_option_base_list(elastic)
import_option_base_list(elastic)
# import_option_parleman_members(elastic)
import_option_parleman_members(elastic)
# import_option_codes(elastic)
import_option_codes(elastic)
# import_option_others(elastic)
import_option_others(elastic)
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_tree", "gn_tree")
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_option", "gn_option")
file_json = "app/../data/option_import_1.json"
list_data_import = import_option_base_list_2(elastic)
with open(file_json, "w", encoding="utf8") as f:
json.dump(list_data_import, f, ensure_ascii=False, indent=4)
+2808 -3038
View File
File diff suppressed because it is too large Load Diff