all_sql_steps , repair qa_qanon
This commit is contained in:
@@ -0,0 +1,594 @@
|
||||
from time import time
|
||||
import requests
|
||||
from app.common.general_functions import *
|
||||
from app.common.config_base import *
|
||||
from app.common.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 = []
|
||||
|
||||
|
||||
#"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 = {}
|
||||
parent_entry = {}
|
||||
prev_entry_child = {}
|
||||
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", [])
|
||||
|
||||
qanon_id_prev = qanon_id
|
||||
### نیازی به بردار سازی و جستجوی معنایی یا ارتباط یابی نیست
|
||||
if 'concept_no' in nlp_tags or 'concept_bad' in nlp_tags or not content:
|
||||
continue
|
||||
|
||||
content_emb = ''
|
||||
content_offset = ' '
|
||||
data = entry
|
||||
word_len_childs = 0
|
||||
if nlp_childs and len(nlp_childs) :
|
||||
|
||||
## اگر پدر و فرزندهای قبلی چیزی هنوز مونده ، بردارسازی باید شود
|
||||
if prev_entry_child :
|
||||
eid = prev_entry_child.get("id", "")
|
||||
content = prev_entry_child.get(field_content, "")
|
||||
data = prev_entry_child
|
||||
content_offset = parent_state["content_offset"]
|
||||
content_emb = parent_state["content"] + "\n" + content + "\n"+ parent_state["content_emb"]
|
||||
data["content_emb"] = content_emb
|
||||
prev_entry_child = {}
|
||||
|
||||
# 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" : 0,
|
||||
"content_emb" : "",
|
||||
"is_parent_embedded" : 0
|
||||
}
|
||||
parent_entry = entry
|
||||
### تا حد امکان با محتوای اصلی قبل، بردار شود و همانجا ذخیره شود
|
||||
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"] == 1: ## قبلا محتوای پدر با فرزندان در حد طول 512 بردارسازی شده و ذخیره شده است
|
||||
## حالا محتوای فرزندهای باقیمانده با کمک محتوای پدرا باید تا طول 512 بردارسازی شوند
|
||||
if prev_entry_child :
|
||||
eid = prev_entry_child.get("id", "")
|
||||
content = prev_entry_child.get(field_content, "")
|
||||
data = prev_entry_child
|
||||
content_offset = parent_state["content_offset"]
|
||||
content_emb = parent_state["content"] + "\n" + content + "\n"+ parent_state["content_emb"]
|
||||
data["content_emb"] = content_emb
|
||||
else : ## تست شد : پیش نمی آید
|
||||
print('------ no prev entry for child ####### error data id=', id, ' wl_em : ', wl_em, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
|
||||
|
||||
prev_entry_child = entry
|
||||
parent_state["word_len_childs"] = 0
|
||||
parent_state["content_emb"] = ''
|
||||
|
||||
|
||||
elif parent_entry :
|
||||
|
||||
parent_state["is_parent_embedded"] = 1
|
||||
eid = parent_state["id"]
|
||||
data = parent_entry
|
||||
|
||||
content_offset = parent_state["content_offset"]
|
||||
content_emb = parent_state["content"] + "\n" + parent_state["content_emb"]
|
||||
data["content_emb"] = content_emb
|
||||
|
||||
prev_entry_child = entry
|
||||
parent_entry={}
|
||||
parent_state["word_len_childs"] = 0
|
||||
parent_state["content_emb"] = ''
|
||||
|
||||
else : ## تست شد : پیش نمی آید
|
||||
print('### no parent for child ####### error data id=', id, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
|
||||
|
||||
else :
|
||||
|
||||
#if parent_id != 0 :
|
||||
## مواردی هستند که با پدر خود فاصله ایجاد شده است مثل qs918484
|
||||
## فعلا کمک محتوایی براشون نمی کنیم
|
||||
#print('### child withuot parent ####### error data id=', id, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
|
||||
eid = id
|
||||
content_offset = 'در ' + qanon_title + ' درباره '
|
||||
for hed in path_headings :
|
||||
content_offset += ' ' + hed.strip()
|
||||
content_emb = content
|
||||
|
||||
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:
|
||||
if "pos_tags" in data:
|
||||
del data["pos_tags"]
|
||||
if "chunk_tags" in data:
|
||||
del data["chunk_tags"]
|
||||
|
||||
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"})
|
||||
@@ -557,32 +557,43 @@ def extract_codes_to_json( file_excel, tcode_label, file_json):
|
||||
df = pd.read_excel(file_excel, sheet_name=0)
|
||||
count = 0
|
||||
rows_list = df.to_dict(orient='records')
|
||||
total = len(df[0])
|
||||
print('total : ', total)
|
||||
|
||||
|
||||
column_names = df.columns.tolist()
|
||||
print(column_names)
|
||||
|
||||
number_base = 0
|
||||
total = len(df)
|
||||
|
||||
print('total : ', total)
|
||||
|
||||
bulk_data = []
|
||||
total_update=0
|
||||
row_number = 0
|
||||
try:
|
||||
for row in rows_list:
|
||||
|
||||
section_title = row[column_names[0]]
|
||||
# ts_date = row[column_names[1]]
|
||||
# qanon_title = row[column_names[2]]
|
||||
code_state = row[column_names[3]]
|
||||
row_number = row[column_names[4]]
|
||||
# qanon_id = row[column_names[5]]
|
||||
section_id = row[column_names[6]]
|
||||
# state_match = row[column_names[7]]
|
||||
section_title = ""
|
||||
section_id = ""
|
||||
try:
|
||||
section_title = row[column_names[number_base]]
|
||||
# ts_date = row[column_names[1]]
|
||||
# qanon_title = row[column_names[2]]
|
||||
code_state = row[column_names[number_base+3]]
|
||||
row_number = row[column_names[number_base+4]]
|
||||
# qanon_id = row[column_names[5]]
|
||||
section_id = row[column_names[number_base+6]]
|
||||
# state_match = row[column_names[7]]
|
||||
except :
|
||||
pass
|
||||
|
||||
section_id_new = 0
|
||||
# c_name = 'حکم' # بعضی فایلهای اصلاحی، شناسه اینجا ذخیره شده بود
|
||||
# if c_name in column_names :
|
||||
# section_id_new = row[c_name]
|
||||
|
||||
if is_nan_or_none_or_empty(section_title) :
|
||||
continue
|
||||
|
||||
if not is_nan_or_none_or_empty(section_id_new) and section_id_new != 0 :
|
||||
section_id = section_id_new
|
||||
|
||||
@@ -625,7 +636,7 @@ def run_codes_to_elastic_directory(elastic, directory, output, all_codes, update
|
||||
file_name = os.path.basename(file)
|
||||
_name = os.path.splitext(file_name)[0]
|
||||
code_name = _name.split('_')[0]
|
||||
print('=========================== start code_name ===> ', code_name)
|
||||
print('=========================== start code_name ===> ', code_name[::-1])
|
||||
w1 = text_normalizer.split_words(code_name)[0]
|
||||
log_file = output + "/log_r_"+w1+".txt"
|
||||
file_path = os.path.join(directory, file)
|
||||
|
||||
@@ -7,6 +7,7 @@ from collections import defaultdict
|
||||
from dotenv import load_dotenv
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
from app.common.general_functions import excel_to_json
|
||||
import pandas as pd
|
||||
import json
|
||||
from pathlib import Path
|
||||
@@ -31,32 +32,6 @@ from openpyxl import Workbook
|
||||
text_normalizer = TextNormalizer()
|
||||
|
||||
|
||||
def excel_to_json(excel_file, required_columns=None, sheet_name=0):
|
||||
"""
|
||||
خواندن یک sheet از فایل اکسل و تبدیل به لیست دیکشنری.
|
||||
|
||||
Args:
|
||||
sheet_name: نام sheet (رشته) یا شماره آن (عدد). پیشفرض: 0 (اولین sheet)
|
||||
"""
|
||||
sheet_names = pd.ExcelFile(excel_file).sheet_names
|
||||
|
||||
print("all sheet")
|
||||
for i, name in enumerate(sheet_names, start=1):
|
||||
print(f" {i}. {name}")
|
||||
|
||||
df = pd.read_excel(excel_file, sheet_name=sheet_name)
|
||||
|
||||
if required_columns is None:
|
||||
selected_columns = df.columns.tolist()
|
||||
else:
|
||||
missing = [col for col in required_columns if col not in df.columns]
|
||||
if missing:
|
||||
raise ValueError(f"ستونهای مفقوده در sheet '{sheet_name}': {missing}")
|
||||
selected_columns = required_columns
|
||||
|
||||
return df[selected_columns].to_dict(orient="records")
|
||||
|
||||
|
||||
def update_history_code(elastic, data, index_name_o, sub_key, label_name, version_key):
|
||||
|
||||
send_round = 1
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
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 app.common.elastic_helper import ElasticHelper
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
from app.for_ai.codes_import_from_excel import run_codes_extract_directory
|
||||
from app.parvande_qanon.import_qavanin_files_to_elastic import import_excel_before_to_elastic, import_excel_after_to_elastic, import_excel_tasmimat_to_elastic
|
||||
from app.parvande_qanon.repair_qa_qanon_for_map_new import *
|
||||
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
|
||||
host=os.getenv('HOST_160')
|
||||
password=os.getenv('HOST_160_PASS')
|
||||
# print( "---------------->>>>>>>>>>>>>>>", host )
|
||||
|
||||
# host=os.getenv('HOST_113')
|
||||
# password=os.getenv('HOST_113_PASS')
|
||||
|
||||
|
||||
print('.... majles_codes_update_steps ......', host)
|
||||
|
||||
path_base_map = "G:/Project2/gateway_php/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
#-------------------------------------
|
||||
#--- مواردی از قانونهای جدید که فیلد زیر را ندارند باید اصلاح شوند
|
||||
#--- main_type
|
||||
|
||||
# POST mj_qa_qanon/_update_by_query
|
||||
body= {
|
||||
"query": {
|
||||
"bool": {
|
||||
"must_not": [
|
||||
{"exists": {"field": "main_type"}}
|
||||
]
|
||||
}
|
||||
},
|
||||
"script": {
|
||||
"source": """
|
||||
|
||||
ctx._source.main_type = 'قانون'
|
||||
""",
|
||||
|
||||
"lang": "painless"
|
||||
}
|
||||
}
|
||||
|
||||
# elastic.updateByQueryIndex("mj_qa_qanon", body)
|
||||
|
||||
|
||||
# POST mj_qa_qanon/_update_by_query
|
||||
body = {
|
||||
"query": {
|
||||
"terms": {
|
||||
"main_type": [
|
||||
"اصلی",
|
||||
"تبعی"
|
||||
]
|
||||
}
|
||||
}
|
||||
,
|
||||
"script": {
|
||||
"source": """
|
||||
|
||||
ctx._source.sub_type = ctx._source.main_type;
|
||||
ctx._source.main_type = 'قانون'
|
||||
""",
|
||||
|
||||
"lang": "painless"
|
||||
}
|
||||
}
|
||||
# elastic.updateByQueryIndex("mj_qa_qanon", body)
|
||||
|
||||
|
||||
#-------------------------------------
|
||||
#------ استخراج برخی کدهای باقیمانده که اکسل آنها از قبل موجود هست و تولید فایل مناسب برای درج فایل محور در بانک مجلس
|
||||
#---
|
||||
all_codes = []
|
||||
with open("./data/codes49.json", "r", encoding="utf8") as f:
|
||||
codes_1 = json.load(f)
|
||||
all_codes = codes_1
|
||||
|
||||
# run_codes_extract_directory( "./data/tcodes/corrected_majles/not_edit2", "./data/tcodes/corrected_majles/not_edit2/result_json", all_codes)
|
||||
|
||||
#-------------------------------------
|
||||
#----- پشتیبان گیری از داده های جدید داتیک
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_rg_section_temp", "mj_rg_section_doctic_14040824")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_section_temp", "mj_qa_section_doctic_14040824")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_opinion_temp", "mj_qa_opinion_doctic_14040824")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon_temp", "mj_qa_qanon_doctic_14040824")
|
||||
|
||||
#-------------------------------------
|
||||
#----- ترمیم داده های تاریخ ایندکس قبلی
|
||||
# -- qaqanon
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_qanon")
|
||||
|
||||
# file_path = 'G:/Project2/111/mj_qa_qanon.zip'
|
||||
file_path = 'G:/Project2/160_dotic/mj_qa_qanon_112.zip'
|
||||
index_name = "mj_qa_qanon"
|
||||
|
||||
elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
|
||||
# restore_correct_data_to_elastic(elastic, file_path, index_name )
|
||||
elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_112.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
|
||||
|
||||
#-------------------------------------
|
||||
#-------------------------------------
|
||||
|
||||
#-- حذف مقرره های قبلی
|
||||
body = {
|
||||
"query": {
|
||||
"term": {
|
||||
"main_type": {
|
||||
"value": "مقرره"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
# elastic.deleteByQueryIndex("mj_qa_qanon", body)
|
||||
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_base")
|
||||
|
||||
#-------------------------------------
|
||||
#----- موقتی برای تستهای از این مرحله به بعد یه پشتیبان تمیز باشه ...
|
||||
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
|
||||
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_base.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
|
||||
|
||||
|
||||
# import_data_new_qaqanon(elastic, "G:/Project2/160_dotic/mj_qa_qanon_doctic_14040824.zip")
|
||||
|
||||
#-------------------------------------
|
||||
#-------------------------------------
|
||||
#-------------------------------------
|
||||
|
||||
# file_excel = "G:\Project2\NLP\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
|
||||
# import_excel_before_to_elastic(elastic, file_excel, "mj_qa_qanon")
|
||||
|
||||
|
||||
# file_excel = "G:\Project2\NLP\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
|
||||
# import_excel_after_to_elastic(elastic, file_excel, "mj_qa_qanon")
|
||||
|
||||
|
||||
# file_excel = "G:\Project2\NLP\dataParsers\data\qavanin_files\فهرست تصمیمات قانونی.elsx"
|
||||
# import_excel_tasmimat_to_elastic(elastic, file_excel, "mj_qa_qanon")
|
||||
@@ -0,0 +1,102 @@
|
||||
import os
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
# from general import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
|
||||
|
||||
|
||||
def moveDataset1(elastic, file, index_name_o):
|
||||
try:
|
||||
try:
|
||||
list_data = elastic.iterateJsonFile(file)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
lst = list(list_data)
|
||||
index = 0
|
||||
percent_prev = 0
|
||||
text_normal = TextNormalizer()
|
||||
dict_order={}
|
||||
for mentry in lst:
|
||||
#print(mentry)
|
||||
|
||||
index += 1
|
||||
percent = int((index / len(lst)) * 100)
|
||||
if percent != percent_prev:
|
||||
print("progress -> %.2f %%" % percent)
|
||||
percent_prev = percent
|
||||
|
||||
|
||||
entry = mentry["source"]
|
||||
id = entry.get("id", "")
|
||||
content = entry.get("content", "")
|
||||
domain = entry.get("domain", "")
|
||||
order = entry.get("order", "")
|
||||
time_edit = entry.get("timestamp", "")
|
||||
user_create = entry.get("user_create", "")
|
||||
users = entry.get("user_show", [])
|
||||
result_objects = entry.get("result_objects", [])
|
||||
meta = entry.get("meta", [])
|
||||
group_key=domain
|
||||
ref_info = {
|
||||
"url" : entry.get("ref_url", ""),
|
||||
"key" : entry.get("ref_key", ""),
|
||||
"id" : entry.get("ref_id", "")
|
||||
}
|
||||
|
||||
if domain == 'تغییرات قانون':
|
||||
continue
|
||||
# elif domain == "استخراج کلیدواژه 11 هزارتایی":
|
||||
# group_key = "پیکره 11 هزارتایی قانون برای کلیدواژه"
|
||||
elif domain == "AI استخراج کلیدواژه" :
|
||||
group_key = "پیکره 7 هزار قوانین برای کلیداوژه"
|
||||
elif domain == "پیکره قوانین 480":
|
||||
group_key = "پیکره 480 هزار توکن قوانین"
|
||||
# elif domain == "استخراج کلیدواژه 15 هزارتایی":
|
||||
# group_key = "پیکره 15 هزار قانون برای کلیدواژه"
|
||||
#"پیکره آرمان
|
||||
#"پیکره پیما",
|
||||
#,
|
||||
if not order :
|
||||
if group_key in dict_order :
|
||||
order = dict_order[group_key]+1
|
||||
dict_order[group_key] = order
|
||||
else:
|
||||
dict_order[group_key] = 1
|
||||
order = 1
|
||||
|
||||
|
||||
results = []
|
||||
for item in result_objects :
|
||||
item["user_id"] = user_create
|
||||
item["time_edit"] = time_edit
|
||||
results.append(item)
|
||||
|
||||
#print(id)
|
||||
|
||||
#if len(users) == 0 :
|
||||
users.append(0) ## یعنی عمومی هست و همه می توانند ببینند
|
||||
users.append(user_create)
|
||||
|
||||
data = {}
|
||||
data["id"]= id
|
||||
data["content"]= content
|
||||
data["group_key"]= group_key
|
||||
data["order"]= order
|
||||
data["ref_info"]= ref_info
|
||||
data["time_edit"]= time_edit
|
||||
data["user_create"]= user_create
|
||||
data["users"]= users
|
||||
data["meta"]= meta
|
||||
data["result_objects"]= results
|
||||
update = False
|
||||
eid = id
|
||||
try:
|
||||
resp = elastic.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)
|
||||
Reference in New Issue
Block a user