Files
init_dataParser/app/majles/ai_create_chunks.py
T
2026-02-21 10:51:06 +03:30

543 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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, all_sections={}, path_out="data/chunks/" ):
text = ""
body={
"query": {
"term": {
"qanon_id": {
"value": qanon_id
}
}
},
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "asc"}}
]
}
if not all_sections :
try:
list_ = elastic.es_iterate_all_documents(index_name_o, body)
for item in list_ :
all_sections[item["_id"]]=item["_source"]
except Exception as e:
print("Exception 1", str(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 section_id, data in all_sections.items():
# لیست سکشن هایی که زیرجزء یک سکشن دیگر بوده اند در متغیر 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)
group_content = ""
# 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"})