This commit is contained in:
hsafaei
2025-02-09 16:45:52 +03:30
parent d2b56991a0
commit b54683638a
11 changed files with 765 additions and 216 deletions
+1
View File
@@ -4,6 +4,7 @@ node_modules
/dist
/html
data_back/
data/
# local env files
config.env
+9 -42
View File
@@ -7,8 +7,6 @@ from general_functions import *
from dotenv import load_dotenv
from elastic_helper import ElasticHelper
from create_ai_index import *
from create_context_ai import *
# from move_to_other import *
load_dotenv(dotenv_path='config.env')
@@ -16,8 +14,8 @@ 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_112')
# password=os.getenv('HOST_112_PASS')
# host=os.getenv('HOST_60')
# password=os.getenv('HOST_60_PASS')
@@ -29,14 +27,6 @@ print(host)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
#elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section_ai")
#elastic.restorFileToElastic("G:/Project2/111", "mj_qa_section_ai", 'majles', True, "mj_qa_section")
#### فایده ای نداشت ....!!!
## مسیر درختی مفید تولید نشد و عنوان قانون هم که فیلد مجزا داریم !
# create_context_ai(elastic, "mj_qa_section" )
## 1 ##-----------------------------------------------------------------
##----- انتقال اطلاعات قبلی به اینجا
@@ -59,50 +49,28 @@ elastic = ElasticHelper(host, password, "elastic", path_base_map)
## 3 ##-----------------------------------------------------------------
## محاسبات پردازش داده ای واجب و پیچیده که پایه تمیزی داده در فاز2 و 3 هست اینجا انجام می شود
fill_nlp_tags(elastic, "mj_qa_section")
#fill_nlp_tags(elastic, "mj_qa_section")
#extract_nlp_childs(elastic,"mj_qa_section")
## 4 ## --------------------------------------------------------------
## پرکردن فیلدهای هوش مصنوعی برای اجزاء یا قانونهای جدید
##///////////////////////////////////////////////////////////
ai_url_base=os.getenv("AI_URL_BASE")
ai_url_vec=ai_url_base+'/vecsim/vector'
# ai_url_class=ai_url_base+'/vec_sim/class'
ai_url_class='http://192.168.23.51:6111/class'
# ai_url_ner=ai_url_base+'/vec_sim/ner'
## 4.1 ## -----------------------------------------------------------------
# تولید بردار برای اجزائی که لازم هست
# elastic.createIndex("mj_qa_section_ai", 'majles/', "mj_qa_section" )
# import_data_embeding(elastic, ai_url_vec ,"mj_qa_section", "mj_qa_section_ai", "content" )
#extract_nlp_childs(elastic,"mj_qa_section")
#elastic.createIndex("mj_qa_section_ai", 'majles/', "mj_qa_section" )
ai_url_vec=os.getenv("ai_url_vec")
import_data_embeding(elastic, ai_url_vec ,"mj_qa_section", "mj_qa_section_ai", "content" )
## 4.2 ## -----------------------------------------------------------------
# برچسبهای هوشمند
# import_classification(elastic, ai_url_class, "mj_qa_section_temp")
# 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'])
## 5 ## --------------------------------------------------------------
## پشتیبان گیری از داده جدید تکمیلی
@@ -118,7 +86,6 @@ ai_url_class='http://192.168.23.51:6111/class'
# 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')
+179 -131
View File
@@ -66,138 +66,137 @@ def fill_nlp_tags(elasticHelper, index_name_o = "mj_qa_section_ai", path_resourc
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 = []
nlp_tags = []
# #"full_path": "ماده واحده>فصل ششم>بخش سوم>قسمت چهارم>فصل هشتم>ماده 153>بند ب>جزء 4",
# paths = full_path.split('>')
# last_path = ''
# if paths :
# last_path = paths[-1]
#"full_path": "ماده واحده>فصل ششم>بخش سوم>قسمت چهارم>فصل هشتم>ماده 153>بند ب>جزء 4",
paths = full_path.split('>')
last_path = ''
if paths :
last_path = paths[-1]
# level_2 = len(paths)
level_2 = len(paths)
# ###--------------------شناسایی بزرگی کوچکی متن -------------------
# word_len = len(split_words(content))
###--------------------شناسایی بزرگی کوچکی متن -------------------
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")
###--------------------شناسایی بزرگی کوچکی متن -------------------
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
###--------------------شناسایی هدینگ بودن -------------------
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 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
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 )
level_parent = level_2
# print('id :', id , ' --diff ', diff, path_heading )
# if level_2 >= level_parent :
if level_2 >= level_parent :
# # برای اجزاء بعدی شناسایی و ذخیره می شود نه جزء جاری
# if prefix != '' and title != '':
# if level_2 == level_parent and path_heading :
# path_heading.pop()
# برای اجزاء بعدی شناسایی و ذخیره می شود نه جزء جاری
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 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)
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)
###--------------------------------------------------------
## فقط در همین جزء ثبت شود
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
data["path_headings"]= path_heading2
data["word_len"] = word_len
data["level"]= level_2
update = True
eid = id
@@ -343,6 +342,8 @@ def import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_sectio
count = 0
qanon_id_prev = ""
parent_state = {}
parent_entry = {}
prev_entry_child = {}
for mentry in list:
count += 1
entry = mentry["source"]
@@ -357,19 +358,30 @@ def import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_sectio
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
content_emb = ''
content_offset = ' '
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"]
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 + ' درباره '
@@ -383,10 +395,11 @@ def import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_sectio
"nlp_childs" : nlp_childs,
"content" : content,
"content_offset" : content_offset,
"word_len_childs" : word_len_childs,
"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 :
@@ -401,22 +414,52 @@ def import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_sectio
## محتوای اصلی با بخشی از محتوای بندها و زیرجزءها، بردارسازی و ذخیره شود و مابقی در ادامه
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
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"] )
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"] )
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
@@ -427,7 +470,7 @@ def import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_sectio
content_emb = content
if content_emb :
payload={
@@ -444,6 +487,11 @@ def import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_sectio
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:
+167
View File
@@ -0,0 +1,167 @@
from time import time
import requests
from general_functions import *
from config_base import *
from text_normalizer import TextNormalizer
def fill_chunk_tags(elasticHelper, ai_url, 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"}}
]
}
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')
text_normal = TextNormalizer()
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
qanon_id = entry.get("qanon_id", "0")
other_info = entry.get("other_info", {})
content = entry.get("content", "")
html = entry.get("html", "")
chunk_tags = []
if html :
content = ''
if not content :
continue
content_normal = text_normal.normalize_qanon_test(content)
payload={
'text': content_normal
}
response = requests.request("POST", ai_url, headers=HEADERS, json=payload)
if response.status_code == 500 :
print(response.text)
continue
resp = json.loads(response.text)
# print(resp)
pos_tags = []
chunk_tags = ''
for item in resp['data'] :
item_pos_tags = item['pos_tags']
for pt in item_pos_tags :
pos_tags.append({
"word": pt[0],
"hazm_tags": pt[1].split(',')
})
if chunk_tags :
chunk_tags += ' ' + item['chunk_tree']
else :
chunk_tags = item['chunk_tree']
####--------------------------------------
# chunk_keywords = []
# # chunks = chunk_tags.replace('] [', ']#[').split('#')
# pattern = r'\[([^\[\]]+) ([A-Z]{1,10})\] '
# iter = re.finditer(pattern, chunk_tags.strip())
# index = 0
# prev_tag = ''
# prev_text = ''
# for item in iter :
# # print(item)
# text = item[0]
# tag = item[1]
# start_index = item.start()
# end_index = item.end()
# if index < start_index :
# word = chunk_tags[index:start_index].strip('()[]:.?!-/«»؟,،؛ ').strip()
# if word in ['که', 'و', 'از', 'تا', 'ولی', 'مگر', 'چنانچه', ''] :
# chunk_keywords.append({
# "text": word,
# "tag": ['PP']
# })
# elif word in ['است', 'شد', 'شود', 'گردد'] :
# if prev_tag in ['V', 'VP'] :
# ck = chunk_keywords[-1]
# ck['text'] += ' ' + word
# chunk_keywords[-1] = ck
# elif prev_tag in ['NOUN'] :
# ck = chunk_keywords[-1]
# ck['text'] += ' ' + word
# ck['tag'] = 'VP'
# chunk_keywords[-1] = ck
# elif word:
# print('id ', id, ' ', word)
# # chunk_keywords.append({
# # "text": word,
# # "tag": ['nnn']
# # })
# else :
# if text in ['است', 'شد', 'شود', 'گردد'] :
# pass
# else:
# pass
# chunk_keywords.append({
# "text": item[1],
# "tag": item[2]
# })
# index = item.end()
# # print(chunk_keywords)
#### ----------------------------------------
data = {}
data["pos_tags"]= pos_tags
data["chunk_tags"]= chunk_tags
if content_normal != content :
data["content_normal"]= content_normal
# data["chunk_keywords"]= chunk_keywords
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")
+74 -4
View File
@@ -2,6 +2,7 @@ import zipfile
import sys
import os
import json
from copy import deepcopy
from time import sleep
from elasticsearch import Elasticsearch,helpers
@@ -59,7 +60,65 @@ class ElasticHelper():
return resp
def backupIndexToZipfile(self, path_back, index_name, out_name= '', query={}, byzip = True) :
def exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[]) :
print('*' * 50, ' start backup -->', index_name)
self.counter = 0
out = out_name
if out_name == '' :
out = index_name
fout = open( path_back + "/"+ out + '.json', 'a+' , encoding='utf-8')
s_res = self.es.search(
index=index_name,
scroll='5m',
size=1000,
body=body
)
self.total = s_res["hits"]["total"]['value']
print('start index = %s' % index_name)
print('total = %d' % self.total)
sid = s_res['_scroll_id']
scroll_size = len(s_res['hits']['hits'])
file_count = 1
out_json = []
while scroll_size > 0:
"Scrolling..."
self.counter += scroll_size
print("progress -> %.2f %%" % ((self.counter / self.total)*100))
#############################
for item in s_res['hits']['hits']:
if fields :
#item2 = deepcopy(item)
item2={}
item2['id']=item['_id']
for kf in fields :
#print(kf)
if kf in item['_source'] :
# print(item['_source'][kf])
item2[kf] = item['_source'][kf]
#exit()
else :
item2=item
out_json.append(item2)
s_res = self.es.scroll(scroll_id=sid, scroll='2m', request_timeout=100000)
sid = s_res['_scroll_id']
scroll_size = len(s_res['hits']['hits'])
text = json.dumps(out_json, ensure_ascii=False)
fout.write(text)
##############################
def backupIndexToZipfile(self, path_back, index_name, out_name= '', body={}, byzip = True, fields=[]) :
print('*' * 50, ' start backup -->', index_name)
self.counter = 0
@@ -76,7 +135,7 @@ class ElasticHelper():
index=index_name,
scroll='5m',
size=1000,
body=query
body=body
)
self.total = s_res["hits"]["total"]['value']
@@ -92,11 +151,22 @@ class ElasticHelper():
print("progress -> %.2f %%" % ((self.counter / self.total)*100))
#############################
out_json = []
for item in s_res['hits']['hits']:
out_json.append(item)
for item in s_res['hits']['hits']:
if fields :
#item2 = deepcopy(item)
item2={}
item2['id']=item['_id']
for kf in fields :
if kf in item['_source'] :
item2['_source'][kf] = item['_source'][kf]
else :
item2=item
out_json.append(item2)
text = json.dumps(out_json, ensure_ascii=False)
out_json = []
if byzip:
filename = out + str(file_count) + '.json'
file_count +=1
View File
+3 -3
View File
@@ -914,8 +914,8 @@ def getTitleType(caption: str) -> str:
if caption.startswith("الحاق ") or caption.startswith("قانون الحاق ") or caption.startswith("قانون الحاقیه "):
return "الحاقی"
elif re.match(r"^قانون اضافه.*قانون", caption):
return "الحاقی"
elif caption.startswith("اصلاح ") or re.match(r"^قانون اصلاح(?:ی)? .*قانون", caption):
return "الحاقی"
elif caption.startswith("اصلاح ") or re.match(r"^قانون اصلاح(?:ی)? .*قانون", caption) or re.match(r"^لایحه قانونی اصلاح(?:ی)? .*لایحه", caption):
return "اصلاحی"
elif re.match(r"^قانون اصلاحیه.*قانون", caption):
return "اصلاحی"
@@ -929,7 +929,7 @@ def getTitleType(caption: str) -> str:
return "نظر"
elif caption.startswith("نامه "):
return "نامه"
elif caption.startswith("قانون لغو ") or caption.startswith("قانون الغای ") or caption.startswith("قانون الغاء "):
elif caption.startswith("قانون لغو ") or caption.startswith("قانون الغای ") or caption.startswith("قانون الغاء ") or caption.startswith("قانون فهرست قوانین و احکام نامعتبر"):
return "لغو"
elif caption.startswith("قانون برنامه "):
return "برنامه"
+101
View File
@@ -0,0 +1,101 @@
import os
from dotenv import load_dotenv
from text_normalizer import TextNormalizer
# from general import *
from general_functions import *
from elastic_helper import ElasticHelper
### --------------------------------------------------------------
## این کد برای استخراج و بهینه سازی کلیدواژه های تولید شده با مدلهای زبانی بزرگ و انتقال به الاستیک نوشته شد
## کلیدواژه ها با ساختار مشخص و مقداری خطا تولید شده بودند
def moveKeywords(elastic, index_name_o, fields=['content'], body={}):
text_normal = TextNormalizer()
dic_main = json.loads(open("data/sections_kw_llama8b_170k_concatenated.json",'r', encoding="utf-8").read())
index = 0
percent_prev = 0
list=[]
for item in dic_main:
index += 1
percent = int((index / len(dic_main)) * 100)
if percent != percent_prev:
print("progress -> %.2f %%" % percent)
percent_prev = percent
id = item['id']
keywords = set()
for key in item['keywords']:
# "•\t1.\tقانون جدید",
# "2.\tکلاه برداری"
key = text_normal.normalize_qanon(key)
key = key.replace('\t', ' ').strip()
key = key.replace('\n', ' ').strip()
key = key.replace('\r', ' ').strip()
key = key.strip(' •.')
key = re.sub(r"^[ \t]*[\d•]+[ .\t]*", '', key).strip()
if key :
key = text_normal.normalize_qanon(key)
keywords.add(key)
content = item['content']
words = text_normal.split_words(content)
sorted_keys=[]
if len(keywords) > 10 and (len(words) * 2) < len(keywords) :
# print('id ', id , ' content', content)
print('id ', id , 'len words ', len(words) , ' len keywords', len(keywords) )
list_temp = sorted(keywords, key=len)
sorted_keys=list_temp[0:len(words)]
# print( ' keywords : ', sorted_keys)
# exit()
else:
sorted_keys = sorted(keywords, key=len)
list.append({
'_id': id,
'_source': {
"ai_keywords" : sorted_keys
}
})
if len(list) > 200 :
elastic.updateBulkList(list, index_name_o)
list = []
if len(list) :
elastic.updateBulkList(list, index_name_o)
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_60')
# password=os.getenv('HOST_60_PASS')
print(host)
# print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#moveKeywords(elastic,"mj_qa_section")
+47 -23
View File
@@ -1,5 +1,6 @@
import os
from dotenv import load_dotenv
from text_normalizer import TextNormalizer
# from general import *
from general_functions import *
from elastic_helper import ElasticHelper
@@ -20,7 +21,7 @@ body = {
def exportTokensMulti(elastic, index_name_i, prefixname, fields=['content'], body={}):
def exportTokensMulti(elastic, index_name_i, prefixname, fields=['content'], body={}, path_out="./data/"):
counter = 0
total = 0
id = ""
@@ -44,7 +45,7 @@ def exportTokensMulti(elastic, index_name_i, prefixname, fields=['content'], bod
for field in fields :
content = entry.get(field, "")
# words = content.split()
words = re.split(r"[\t\n\r\.\"«»\)\(\]\[,;،؛ \-!?:]+", content)
words = text_normal.split_words(content)
for word in words:
if word in dict_word_count :
dict_word_count[word] += 1
@@ -52,8 +53,8 @@ def exportTokensMulti(elastic, index_name_i, prefixname, fields=['content'], bod
dict_word_count[word] = 1
content = text_normal.normalize_qanon(content)
words = re.split(r"[\t\n\r\.\"«»\)\(\]\[,;،؛ \-!?:]+", content)
content = text_normal.normalize_qanon_test(content)
words = text_normal.split_words(content)
for word in words:
if word in dict_word_count2 :
dict_word_count2[word] += 1
@@ -65,13 +66,15 @@ def exportTokensMulti(elastic, index_name_i, prefixname, fields=['content'], bod
if dict_word_count :
sorted_dict_words = dict(sorted(dict_word_count.items(), key=lambda x: x[1], reverse=True))
with open(prefixname+".txt", "w", encoding="utf-8") as f:
json.dump(sorted_dict_words, f, ensure_ascii=False, indent=4)
filtered_dict = {k:v for (k,v) in sorted_dict_words.items() if not re.match(r'[a-zA-Z\d]+', k) }
with open(path_out+prefixname+"1.txt", "w", encoding="utf-8") as f:
json.dump(filtered_dict, f, ensure_ascii=False, indent=4)
if dict_word_count2 :
sorted_dict_words = dict(sorted(dict_word_count2.items(), key=lambda x: x[1], reverse=True))
with open(prefixname+"2.txt", "w", encoding="utf-8") as f:
json.dump(sorted_dict_words, f, ensure_ascii=False, indent=4)
filtered_dict = {k:v for (k,v) in sorted_dict_words.items() if not re.match(r'[a-zA-Z\d]+', k) }
with open(path_out+prefixname+"2.txt", "w", encoding="utf-8") as f:
json.dump(filtered_dict, f, ensure_ascii=False, indent=4)
except Exception as e:
save_error(id, e)
@@ -100,9 +103,9 @@ def exportTokens(elastic, index_name_i, fields=['content'], body={}):
for field in fields :
content = entry.get(field, "")
content = text_normal.replace_alphabets(content)
# content = text_normal.replace_alphabets(content)
# words = content.split()
words = re.split(r"[\t\n\r\.\"«»\)\(,;،؛ \-!?:]+", content)
words = text_normal.split_words(content)
for word in words:
if word in dict_word_count :
@@ -115,20 +118,21 @@ def exportTokens(elastic, index_name_i, fields=['content'], body={}):
except Exception as e:
save_error(id, e)
def exportTokensToFile(elastic, index_name_i, filename, fields=['content'], body={}):
def exportTokensToFile(elastic, index_name_i, filename, fields=['content'], body={}, path_out="./data/"):
dict_words = exportTokens(elastic, index_name_i, fields, body)
if dict_words :
sorted_dict_words = dict(sorted(dict_words.items(), key=lambda x: x[1], reverse=True))
with open(filename, "w", encoding="utf-8") as f:
json.dump(sorted_dict_words, f, ensure_ascii=False, indent=4)
filtered_dict = {k:v for (k,v) in sorted_dict_words.items() if not re.match(r'[a-zA-Z\d]+', k) }
with open(path_out+filename, "w", encoding="utf-8") as f:
json.dump(filtered_dict, f, ensure_ascii=False, indent=4)
def diff_files_to_file(file_dict1, file_dict2, filename):
def diff_files_to_file(file_dict1, file_dict2, filename, path_out="./data/"):
dict1 = json.loads(open(file_dict1, "r", encoding="utf-8").read())
dict2 = json.loads(open(file_dict2, "r", encoding="utf-8").read())
return diff_to_file(dict1, dict2, filename)
return diff_to_file(dict1, dict2, filename, False, path_out)
def diff_to_file(dict1, dict2, filename, by_diff_count=False):
def diff_to_file(dict1, dict2, filename, by_diff_count=False, path_out="./data/"):
dict_no_exist = {}
dict_diff_count = {}
for item in dict1:
@@ -137,17 +141,37 @@ def diff_to_file(dict1, dict2, filename, by_diff_count=False):
elif dict1[item] != dict2[item] :
dict_diff_count[item] = dict2[item] - dict1[item]
with open(filename, "w", encoding="utf-8") as f:
with open(path_out+filename, "w", encoding="utf-8") as f:
json.dump(dict_no_exist, f, ensure_ascii=False, indent=4)
if by_diff_count :
with open(filename, "a+", encoding="utf-8") as f:
with open(path_out+filename, "a+", encoding="utf-8") as f:
json.dump(dict_diff_count, f, ensure_ascii=False, indent=4)
elastic = ElasticHelper("http://192.168.23.160:6900", "icI1nbkmMQy3WoeaHpBJ")
# exportTokensToFile(elastic,"mj_qa_section", "content_mj_qa_section_1.txt")
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_60')
# password=os.getenv('HOST_60_PASS')
print(host)
# print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#exportTokensToFile(elastic,"mj_qa_section", "content_mj_qa_section_1.txt")
# exportTokensToFile(elastic,"test_qa_section", "content_test_qa_section_1.txt")
# exportTokensToFile(elastic,"test_qa_section", "content_test_qa_section_normal_1.txt", ["content_normal"])
@@ -161,7 +185,7 @@ elastic = ElasticHelper("http://192.168.23.160:6900", "icI1nbkmMQy3WoeaHpBJ")
# exportTokensToFile(elastic,"mj_qa_section", "content_mj_qa_section_1.txt")
exportTokensMulti(elastic,"mj_qa_section", "mj_qa_section")
diff_files_to_file("mj_qa_section.txt", "mj_qa_section2.txt", "diff_1_2.txt")
diff_files_to_file("mj_qa_section2.txt", "mj_qa_section.txt", "diff_2_1.txt")
diff_files_to_file("mj_qa_section1.txt", "mj_qa_section2.txt", "diff_1_2.txt")
diff_files_to_file("mj_qa_section2.txt", "mj_qa_section1.txt", "diff_2_1.txt")
print("finished")
+154
View File
@@ -0,0 +1,154 @@
import os
from dotenv import load_dotenv
from text_normalizer import TextNormalizer
# from general import *
from general_functions import *
from elastic_helper import ElasticHelper
from create_relation_tags 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_60')
# password=os.getenv('HOST_60_PASS')
print(host)
# print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#-------------------------------------------------------
##
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
#elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section_ai")
#elastic.restorFileToElastic("G:/Project2/111", "mj_qa_section_ai", 'majles', True, "mj_qa_section")
#-------------------------------------------------------
#### فایده ای نداشت ....!!!
## مسیر درختی مفید تولید نشد و عنوان قانون هم که فیلد مجزا داریم !
# 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 = 'G:/Project2/_back/back_data/data_majles/elastic/v1.0/full'
# elastic.restorFileToElastic(path_back, 'mj_qa_section', 'majles')
#-------------------------------------------------------
##
#-------------------------------------------------------
##
#-------------------------------------------------------
# -- جهت استخراج دیتاست بخشی از الاستیک برای استفاده در هوش مصنوعی
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"])
#-------------------------------------------------------
print("finished")
+30 -13
View File
@@ -16,8 +16,9 @@ class TextNormalizer:
def split_words(self, text) :
if not text :
return []
words = re.split(r"[\t\n\r\.\"«»\)\(\]\[,;،؛ \-!?:]+", text)
return []
### “”
words = re.split(r"[\t\n\r\.\'\"«»\)\(\]\[\{\}\%\#\$\*\<\>\/,;،؛ \-!?:٭؟]+", text)
return words
def normalize_qanon(self, text):
@@ -35,13 +36,13 @@ class TextNormalizer:
# یکسان سازی اختلاف حروف کیبوردهای مختلف - کدهای مختلف ولی نمایش یکسان
text = self.replace_alphabets(text)
# اعداد چسبیده به کلمات را با یک فاصله جدا می کند
text = self.word_digit_correction(text)
#فاصله های تکراری و خطوط خالی تکراری را یکی می کند
text = re.sub(r"( )+", " ", text)
text = re.sub(r"(\n)+", "\n", text)
# اعداد چسبیده به کلمات را با یک فاصله جدا می کند
text = self.word_digit_correction(text)
# نرمال کردن حروف اختلافی عربی و فارسی
text = text.replace("ي", "ی")
text = text.replace("ك", "ک")
@@ -52,8 +53,15 @@ class TextNormalizer:
if not text :
return ""
text = text.replace("\u00a0", " ") # No Break space
text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL
text = self.word_digit_correction(text)
text = re.sub(r"( )+", " ", text)
text = self.space_correction(text)
text = self.heha_correction(text)
return text
@@ -99,6 +107,9 @@ class TextNormalizer:
if not text :
return ""
text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL
text = re.sub(r"\u00AD|\u00AC", "\u200C", text) # نیم اسپیس خاص
text = re.sub(r"(\u002C)+", "\u200C", text) # نیم اسپیس تکراری
text = re.sub(r"ﺁ|آ", "آ", text)
@@ -178,22 +189,28 @@ class TextNormalizer:
# اعداد چسبیده به کلمات را با یک فاصله جدا می کند
def word_digit_correction(self, text):
text = re.sub(r"(\200C)(\d+)", r" \2", text)
text = re.sub(r"(\d+)(\200C)", r"\1 ", text)
text = re.sub(r"(\200C)([\t\n\r\.\'\"«»\)\(\]\[\{\}\#\$\*\<\>\/,;،؛ \-!?:٭؟])", r" \2", text)
text = re.sub(r"([\t\n\r\.\'\"«»\)\(\]\[\{\}\#\$\*\<\>\/,;،؛ \-!?:٭؟])(\200C)", r"\1 ", text)
# ## شماره22 -> شماره 22 22/ش2
# ### no ش/22 شد\22
# text = re.sub(r"([^\d \/\\]+?)(\d)", r"\1 \2", text)
# text = re.sub(r"(\d+)([^\d \/\\]+?)", r"\1 \2", text)
# ر54ر44ر135
text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1\/\2\/\3", text)
text = re.sub(r"(\d+?)ر(\d+?)", r"\1\/\2", text)
# text = re.sub(r"(\w+)(\d+)", r"\1 \2", text)
# text = re.sub(r"(\d+)(\w+)", r"\1 \2", text)
# words = re.split(r"[\t\n\r\.\"«»\)\(\]\[,;،؛ \-!?:]+", text)
text = re.sub(r"([^\d \/\\]+?)(\d)", r"\1 \2", text)
text = re.sub(r"(\d+)([^\d \/\\]+?)", r"\1 \2", text)
#ر5ر135
# text = re.sub(r"((\d+)ر)+\d", r"\1 \2", text)
return text
## رسیدگیها -> رسیدگی‌ها
def heha_correction(self, text):
text = re.sub(r"(ه)(ها )", r"\1‌\2", text)
text = re.sub(r"(ه)(های )", r"\1‌\2", text)