546 lines
22 KiB
Python
546 lines
22 KiB
Python
from time import time
|
|
import requests
|
|
from general_functions import *
|
|
from config_base import *
|
|
from text_normalizer import TextNormalizer
|
|
|
|
|
|
#def saveEmbedingContent()
|
|
|
|
##----- مرحله اول -----------------
|
|
## پردازش و پرکردن فیلدهای متنوع کمکی
|
|
def fill_nlp_tags(elasticHelper, index_name_o = "mj_qa_section_ai", 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
|
|
|
|
|
|
try:
|
|
try:
|
|
list = elasticHelper.es_iterate_all_documents(index_name_o, body)
|
|
except Exception as e:
|
|
save_error(0, e)
|
|
count = 0
|
|
print('*' * 20 , ' count=', elasticHelper.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 = entry.get("nlp_tags", "")
|
|
# nlp_tags = []
|
|
|
|
|
|
# #"full_path": "ماده واحده>فصل ششم>بخش سوم>قسمت چهارم>فصل هشتم>ماده 153>بند ب>جزء 4",
|
|
# 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 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
|
|
|
|
update = True
|
|
eid = id
|
|
try:
|
|
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
|
|
|
|
except Exception as e:
|
|
save_error(id, e)
|
|
|
|
|
|
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(elasticHelper, 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 = {}
|
|
try:
|
|
try:
|
|
list = elasticHelper.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:
|
|
list = []
|
|
for key, value in dicParents.items():
|
|
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
|
|
|
|
elasticHelper.updateBulkList(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 import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_section", index_name_o = "mj_qa_section_ai", field_content="content") :
|
|
|
|
id = ""
|
|
body={
|
|
# "query": {
|
|
# "bool": {
|
|
# "must_not": [
|
|
# {
|
|
# "terms": {
|
|
# "nlp_tags": ["concept_no","concept_bad"]
|
|
# }
|
|
# }
|
|
# ]
|
|
# }
|
|
# },
|
|
"sort": [
|
|
{"qanon_id": {"order": "asc"}},
|
|
{"child_order": {"order": "asc"}}
|
|
]
|
|
}
|
|
|
|
dicParents = {}
|
|
try:
|
|
try:
|
|
list = elasticHelper.es_iterate_all_documents(index_name_i, body)
|
|
except Exception as e:
|
|
save_error(0, e)
|
|
count = 0
|
|
qanon_id_prev = ""
|
|
parent_state = {}
|
|
for mentry in list:
|
|
count += 1
|
|
entry = mentry["source"]
|
|
|
|
id = entry.get("id", "")
|
|
content = entry.get(field_content, "")
|
|
path_headings = entry.get("path_headings", [])
|
|
qanon_title = entry.get("qanon_title", [])
|
|
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", [])
|
|
nlp_childs = entry.get("nlp_childs", [])
|
|
|
|
content_emb = ''
|
|
content_offset = ' '
|
|
qanon_id_prev = qanon_id
|
|
### نیازی به بردار سازی و جستجوی معنایی یا ارتباط یابی نیست
|
|
if 'concept_no' in nlp_tags or 'concept_bad' in nlp_tags or not content:
|
|
continue
|
|
|
|
data = entry
|
|
word_len_childs = 0
|
|
if nlp_childs and len(nlp_childs) :
|
|
word_len_childs = 0
|
|
for item in nlp_childs :
|
|
word_len_childs += item["word_len"]
|
|
|
|
#word_len_total = word_len + word_len_childs
|
|
content_offset = 'در ' + qanon_title + ' درباره '
|
|
for hed in path_headings :
|
|
content_offset += ' ' + hed.strip()
|
|
word_len_offset = len(split_words(content_offset))
|
|
parent_state = {
|
|
"id" : id,
|
|
"word_len" : word_len,
|
|
"word_len_offset" : word_len_offset,
|
|
"nlp_childs" : nlp_childs,
|
|
"content" : content,
|
|
"content_offset" : content_offset,
|
|
"word_len_childs" : word_len_childs,
|
|
"content_emb" : "",
|
|
"is_parent_embedded" : 0
|
|
}
|
|
### تا حد امکان با محتوای اصلی قبل، بردار شود و همانجا ذخیره شود
|
|
elif 'concept_week' in nlp_tags or 'concept_middle' in nlp_tags or 'concept_side' in nlp_tags :
|
|
if parent_state and parent_state["id"] == parent_id :
|
|
wl = parent_state["word_len"]
|
|
wl_of = parent_state["word_len_offset"]
|
|
wl_em = parent_state["word_len_childs"]
|
|
len_total = wl + wl_of + wl_em + word_len
|
|
## اگر جا داره که با محتوای ماده اصلی=، بردار سازی باشد
|
|
if len_total < 512 :
|
|
parent_state["word_len_childs"] += word_len
|
|
parent_state["content_emb"] = parent_state["content_emb"] + "\n" + content
|
|
|
|
## محتوای اصلی با بخشی از محتوای بندها و زیرجزءها، بردارسازی و ذخیره شود و مابقی در ادامه
|
|
else :
|
|
if parent_state["is_parent_embedded"] :
|
|
eid = id
|
|
else :
|
|
eid = parent_state["id"]
|
|
parent_state["is_parent_embedded"] = 1
|
|
|
|
content_offset = parent_state["content_offset"]
|
|
content_emb = parent_state["content"] + "\n" + parent_state["content_emb"]
|
|
data["content_emb"] = content_emb
|
|
|
|
parent_state["word_len_childs"] = 0
|
|
parent_state["content_emb"] = ''
|
|
|
|
## پیش نمی آید
|
|
# else :
|
|
# print('### ####### error data id=', id, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
|
|
|
|
else :
|
|
eid = id
|
|
content_offset = 'در ' + qanon_title + ' درباره '
|
|
for hed in path_headings :
|
|
content_offset += ' ' + hed.strip()
|
|
|
|
content_emb = content
|
|
|
|
|
|
|
|
if content_emb :
|
|
|
|
payload={
|
|
'text': content_offset + ' ' + content_emb
|
|
}
|
|
response = requests.request("POST", ai_url_vec, headers=HEADERS, json=payload)
|
|
if response.status_code == 500 :
|
|
print(response.text)
|
|
bulk_data = []
|
|
continue
|
|
|
|
resp = json.loads(response.text)
|
|
data["embeddings"]=resp['result']
|
|
|
|
update = False
|
|
try:
|
|
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
|
|
|
|
except Exception as e:
|
|
save_error(eid, e)
|
|
|
|
except Exception as e:
|
|
save_error(id, e)
|
|
|
|
print("=" * 10, "import_data_embeding finished")
|
|
|
|
|
|
|
|
|
|
def import_classification(elasticHelper, ai_url_class, index_name_o = "mj_qa_section_ai") :
|
|
id = ""
|
|
body={
|
|
"query": {
|
|
"bool": {
|
|
"must_not": [
|
|
{
|
|
"exists": {
|
|
"field": "code-ai"
|
|
}
|
|
}
|
|
]
|
|
}
|
|
}
|
|
}
|
|
|
|
dicIds = {}
|
|
try:
|
|
try:
|
|
list = elasticHelper.es_iterate_all_documents(index_name_o, body)
|
|
except Exception as e:
|
|
save_error(0, e)
|
|
count = 0
|
|
print('*' * 20 , ' count=', elasticHelper.total)
|
|
|
|
for mentry in list:
|
|
count += 1
|
|
entry = mentry["source"]
|
|
|
|
id = entry.get("id", "")
|
|
content = entry.get("content", "")
|
|
data = {}
|
|
if content :
|
|
payload={
|
|
'text':content
|
|
}
|
|
response = requests.request("POST", ai_url_class, headers=HEADERS, json=payload)
|
|
if response.status_code == 500 :
|
|
print(response.text)
|
|
continue
|
|
|
|
resp = json.loads(response.text)
|
|
data["code-ai"]=resp['result']
|
|
|
|
update = True
|
|
|
|
eid = id
|
|
try:
|
|
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
|
|
if not update :
|
|
dicIds[eid] = True
|
|
|
|
except Exception as e:
|
|
save_error(id, e)
|
|
|
|
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')
|
|
|
|
|
|
print("=" * 10, " 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
|
|
|
|
|
|
#isMomSection({"full_path":"باب اول>فصل اول>ماده 8"}) |