procces refactor majles

This commit is contained in:
hsafaei
2025-10-27 12:54:04 +03:30
parent c80813aaa8
commit 498c3c4bd1
8 changed files with 1395 additions and 312 deletions
+53 -10
View File
@@ -68,7 +68,7 @@ class ElasticHelper():
return resp
def exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[]) :
def exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[], mode='normal', collapse_field = '') :
print('*' * 50, ' start backup -->', index_name)
self.counter = 0
sid = None
@@ -77,8 +77,6 @@ class ElasticHelper():
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',
@@ -92,28 +90,69 @@ class ElasticHelper():
sid = s_res['_scroll_id']
scroll_size = len(s_res['hits']['hits'])
file_count = 1
pack_count = 1
out_json = []
if mode == 'dict' or collapse_field:
out_json = {}
prev_collapse_value = ''
pack_collapse = []
while scroll_size > 0:
"Scrolling..."
self.counter += scroll_size
print("progress -> %.2f %%" % ((self.counter / self.total)*100))
#### for test
# if pack_count > 2 :
# break
pack_count += 1
#############################
for item in s_res['hits']['hits']:
if fields :
id = item['_id']
item2=None
if mode =='id' : # فقط شناسه ها نیاز هست
item2=id
elif fields :
item2={}
item2['id']=item['_id']
item2['id']= id
for kf in fields :
#print(kf)
if kf in item['_source'] :
# print(item['_source'][kf])
item2[kf] = item['_source'][kf]
elif '.' in kf :
cols = kf.split('.')
subsource = item['_source']
for sub in cols :
if sub in subsource :
subsource = subsource[sub]
continue
else:
break
key = kf.replace(".", "__")
item2[key] = subsource
#exit()
else :
item2={}
item2=item
out_json.append(item2)
if collapse_field and collapse_field in item['_source']:
collapse_value = item['_source'][collapse_field]
if not prev_collapse_value :
prev_collapse_value = collapse_value
if not collapse_value == prev_collapse_value :
out_json[prev_collapse_value] = pack_collapse
pack_collapse = []
prev_collapse_value = collapse_value
pack_collapse.append(item2)
elif mode == 'dict':
out_json[id]=item2
else :
out_json.append(item2)
s_res = self.es.scroll(scroll_id=sid, scroll='2m', request_timeout=100000)
@@ -121,8 +160,12 @@ class ElasticHelper():
scroll_size = len(s_res['hits']['hits'])
sid = None
text = json.dumps(out_json, ensure_ascii=False)
fout.write(text)
if collapse_field and prev_collapse_value and pack_collapse :
out_json[prev_collapse_value] = pack_collapse
with open(path_back + "/"+ out, "w", encoding="utf-8") as fout:
json.dump(out_json, fout, ensure_ascii=False, indent=4)
##############################
+181 -17
View File
@@ -71,8 +71,21 @@ def get_section_title_sample(text):
text = re.sub(r"( |\u200C|\>|\<|-|ـ)+", "", text)
return text
def searchSectionId(elastic, index_name, qanon_id, section_title):
def searchSectionIdContent(elastic, index_name, qanon_id, section_title, content):
score = 100
should = []
should.append( {
"match": {
"other_info.full_path": section_title
}
})
should.append( {
"match": {
"content": content
}
})
body = {
"query": {
"bool": {
@@ -86,8 +99,61 @@ def searchSectionId(elastic, index_name, qanon_id, section_title):
},
{
"match": {
"other_info.full_path": section_title
"bool" : {
"should" : should
}
}
]
}
}
}
s_res = elastic.es.search(index=index_name, body=body)
content = get_section_title_sample(content)
for item in s_res["hits"]["hits"]:
content = item['_source']['content']
# حذف اضافات
content_sample = get_section_title_sample(content)
if content == content :
return item["_id"], 100, item
return 0, 0, {}
def searchSectionId(elastic, index_name, qanon_id, section_title, other_title=[]):
score = 100
should = []
should.append( {
"match": {
"other_info.full_path": section_title
}
})
for title in other_title :
if title and title != section_title :
should.append( {
"match": {
"other_info.full_path": title
}
})
body = {
"query": {
"bool": {
"must": [
{
"term": {
"qanon_id": {
"value": qanon_id
}
}
},
{
"bool" : {
"should" : should
}
}
]
@@ -100,11 +166,30 @@ def searchSectionId(elastic, index_name, qanon_id, section_title):
other_info = item['_source']['other_info']
title = other_info['full_path']
# حذف اضافات
title = get_section_title_sample(title)
title_sample = get_section_title_sample(title)
if title == section_title :
if title_sample == section_title :
return item["_id"], 100, item
title_sample2 = title
title_sample2 = re.sub(r'^(فصل|کتاب|قسمت|بخش)\s*?(اول|دوم|سوم|چهارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|یازدهم|دوازدهم|سیزدهم|هفدهم|هجدهم|نوزدهم|بیستم)', '', title_sample2)
title_sample2 = title_sample2.replace('ماده واحده', '')
title_sample2 = title_sample2.replace('متن', '')
title_sample2 = title_sample2.replace('پیوست', '')
title_sample2 = title_sample2.replace('ضمیمه', '')
title_sample2 = title_sample2.strip(' ><')
title_sample2 = title_sample2.lstrip(' ><')
title_sample2 = get_section_title_sample(title_sample2)
# if title_sample2 != title_sample :
# print('searchSectionId : ', title_sample, title_sample2)
if title_sample2 == section_title :
return item["_id"], 100, item
if title_sample2 in other_title or title in other_title :
return item["_id"], 95, item
return 0, 0, {}
def get_dict_qanon_title(file_path):
@@ -186,7 +271,7 @@ def searchQanonTitleOfContent(elastic, qanon_title, ts_data="", index_name="mj_q
return 0, 0, {}
def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"):
def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon", ts_ref=""):
score = 100
body = {
"query": {
@@ -226,6 +311,10 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"):
total = s_res["hits"]["total"]['value']
qanon_title_sample = re.sub(r"( |\u200C)+", "", qanon_title)
qanon_title_sample2 = re.sub(r"^(.+?)(\(.+\))$", r"\1", qanon_title_sample)
qanon_title_sample = get_qanon_title_sample(qanon_title_sample)
qanon_title_sample2 = get_qanon_title_sample(qanon_title_sample2)
list_equal = []
for item in s_res["hits"]["hits"]:
title = item['_source']['title']
@@ -233,14 +322,14 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"):
title_sample = get_qanon_title_sample(title)
title_sample = re.sub(r"( |\u200C)+", "", title_sample)
if title_sample == qanon_title_sample :
if title_sample == qanon_title_sample or title_sample == qanon_title_sample2:
list_equal.append(item)
else :
qanon_title_sample = get_qanon_title_sample(qanon_title)
title_sample = get_qanon_title_sample(title)
if title_sample == qanon_title_sample :
if title_sample == qanon_title_sample or title_sample == qanon_title_sample2:
list_equal.append(item)
if len(list_equal) == 1 :
@@ -251,7 +340,11 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"):
return item["_id"], score, item
for item in list_equal :
if ts_data == item['_source']['ts_date'] :
if ts_data and ts_data == item['_source']['ts_date'] :
score = 100
return item["_id"], score, item
if ts_ref and ts_ref == item['_source']['ts_ref'] :
score = 100
return item["_id"], score, item
@@ -263,17 +356,21 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"):
return 0, 0, {}
def get_qanon_date(title):
def get_qanon_date(title, byDateCorrection = True):
# regex = r"مصوب(\s*\d{1,4}/\d{1,4}/\d{1,4})\s*$"
regex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*$"
regex_ex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*((مجلس|کمیسیون|کمیسیونهای|هیات|شورای).{1,50})$"
regex1 = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*$"
regex2 = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*((مجلس|کمیسیون|نخست وزیر|کمیسیونهای|هیات|شورای).{1,50})$"
regex3 = r"تاریخ تصویب\s*:*\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*مرجع تصویب\s*:*\s*((مجلس|کمیسیون|نخست وزیر|کمیسیونهای|هیات|شورای).{1,50})$"
regex4 = r"مرجع تصویب\s*:*\s*((مجلس|کمیسیون|نخست وزیر|کمیسیونهای|هیات|شورای).{1,50})\s*تاریخ تصویب\s*:*\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*$"
ts_ref = ''
qanon_title = ''
ts_date = ''
title=title.strip().strip(' #=').strip()
title=title.replace("\r", " ").replace("\n", " ").replace(" ", " ").replace(" ", " ")
title=title.replace("=", "#")
title=title.replace("#مصوب#", "#مصوب ")
title=title.replace("#مصوب #", "#مصوب ")
items = title.split('#')
if len(items) == 1:
qanon_title = items[0]
@@ -294,29 +391,90 @@ def get_qanon_date(title):
if ts_date == '' :
# قانون كار مصوب 26/12/1337
match = re.search(regex, qanon_title)
match = re.search(regex1, qanon_title)
if match :
#print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}")
ts_date = match.group(1).strip()
qanon_title = qanon_title[0:match.start()]
if ts_date == '':
match = re.search(regex_ex, qanon_title)
match = re.search(regex2, qanon_title)
if match :
#print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}")
ts_date = match.group(1).strip()
ts_ref = match.group(2).strip()
qanon_title = qanon_title[0:match.start()]
if ts_date == '':
match = re.search(regex3, qanon_title)
if match :
#print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}")
ts_date = match.group(1).strip()
ts_ref = match.group(2).strip()
qanon_title = qanon_title[0:match.start()]
if ts_date == '':
match = re.search(regex4, qanon_title)
if match :
#print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}")
ts_ref = match.group(1).strip()
ts_date = match.group(3).strip()
qanon_title = qanon_title[0:match.start()]
if byDateCorrection and ts_date == '':
title = text_normalizer.date_correction(title)
return get_qanon_date(title, False)
return qanon_title, ts_date, ts_ref
# ماده 1 -> ماده یک
# ماده دوم -> ماده دیم
# ماده دوم -> ماده دویم
def get_section_title2(title):
regex1 = r"^(جزء|بند|ماده|فصل|مبحث|ردیف|جدول|تبصره|پیوست|قسمت)(\s*)(\d+?)$"
title=title.strip()
title2 = ''
title3 = ''
match = re.search(regex1, title)
if match :
try:
number = int(match.group(3).strip())
s_number1, s_number2 = number_to_persian(number)
if s_number1 :
title2 = match.group(1) + match.group(2) + s_number1
title3 = match.group(1) + match.group(2) + s_number2
except :
title2 = ''
title3 = ''
if title2 == '' :
title2 = title.replace('دیم', 'دوم')
title2 = title.replace('دویم', 'دوم')
return [title2, title3]
def number_to_persian(num):
ones = ["صفر", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه"]
ones2 = ["صفر", "اول", "دوم", "سوم", "چهارم", "پنجم", "ششم", "هفتم", "هشتم", "نهم"]
if 0 <= num < 10:
return ones[num], ones2[num]
else:
return ""
def get_section_correct(title):
title=title.strip().strip(' #=').strip()
if title == 'کل قانون' or title == 'متن قانون' or title == 'متن' or title == 'تمام قانون' or title == 'کل مصوبه':
all_titles = ['تمام ماده ها','همه ماده ها','تمام مواد','همه مواد','کل قانون','متن قانون','متن','تمام قانون','کل مصوبه']
if title in all_titles :
return ['all']
if re.match(r'^(.+)\(.*\)$', title) :
title_1 = re.sub(r'^(.+)\(.*\)$', r'\1', title)
if title_1 in all_titles :
return ['all']
title=title.replace('"', '')
title=title.replace('اصلاحی', '')
title = re.sub(r"(\(|\)|\>|\<|-|ـ)+", "", title)
@@ -324,9 +482,12 @@ def get_section_correct(title):
subs = title.split('،')
result = []
for item in subs :
item=re.sub(r"(جزء|بند|ماده|فصل|مبحث|ردیف|جدول|تبصره|پیوست|قسمت)", r"#\1", item)
if not item :
continue
item=re.sub(r"(جزء|بند|ماده|فصل|مبحث|ردیف|جدول|تبصره|باب|کتاب|پیوست|ضمیمه|قسمت)", r"#\1", item)
items = item.split('#')
items.reverse()
if re.match(r"(فصل|مبحث|ردیف|جدول|باب|کتاب|پیوست|ضمیمه|قسمت)", items[-1]) :
items.reverse()
item = '> '.join(items).strip(' >').replace(' ', '')
item = text_normalizer.word_digit_correction(item)
result.append(item)
@@ -365,3 +526,6 @@ def get__all_section_qanon(elastic, index_name, qanon_id):
# qanon_title="قانون الحاق دو تبصره بعنوان تبصره‌ های 3 و 4 به ماده 9 قانون روابط موجر و مستأجر مصوب 13 /2 /1362"
# qanon_title = get_qanon_title_sample(qanon_title)
# print(qanon_title)
# print( get_section_number_correct('ماده 1') )
@@ -4,187 +4,18 @@ import traceback
import json
import pandas as pd
from dotenv import load_dotenv
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
# from app.common.general_functions import *
from app.common.qanon_functions import *
from app.common.elastic_helper import ElasticHelper
from app.common.config_base import *
def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""):
# excel_helper = ExcelHelper()
# df = excel_helper.load_data(file)
# df = pd.read_excel('records.xlsx', sheet_name='Cars', usecols=['Car Name', 'Car Price'])
# print(df)
df = pd.read_excel(file_excel, sheet_name=0, header=None)
# print(df[0:10])
# print(df.columns.ravel())
# print(df.columns.tolist())
# print(df['EmpName'].tolist())
# print(df[0].tolist())
count = 0
rows_list = df.to_dict(orient='records')
total = len(df[0])
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=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]]
# if code_state :
# print ( 'ddddddddddddddcode_state' , code_state)
# else :
# print ( 'ccccccccccccccode_state' , code_state)
qanon_id = 0
section_id = 0
state = ''
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
if section_title is None or is_nan_or_none_or_empty(section_title) or qanon_title is None or is_nan_or_none_or_empty(qanon_title) :
file.write('!!!!!! nan error !!!!!!!' + str(count) + '\n')
state = 'خطا-پرش'
else:
section_title = text_normalizer.normalize_search_qanon(str(section_title))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
if qanon_id == 0 :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
dic_error_qanon_title[qanon_title]=count
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
else:
state = 'قانون-جستجو'
# اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ...
if not qanon_id == 0 :
section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title)
# - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود
if score < 90 :
dic_error_section_title[str(qanon_id)+'=='+section_title]=count
print('='*10 , str(count) , ' section error', qanon_id, ' --> ', section_title )
file.write('---- section error ---' + str(qanon_id) + ' ----- ' + section_title + '\n')
section_id = 0
state = 'خطا-جزء'
else :
state = 'صحیح'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row[5]=qanon_id
row[6]=section_id
row[7]=state
rows_list_new.append(row)
data={}
# ذخیره کد در الاستیک برای شناسه های یافت شده
if section_id and section_id != 0:
item = elastic.get_doctument(index_name_o,section_id)
tcode_mains = []
tcode_subs = []
if "tcode_mains" in item['_source'] :
tcode_mains= item['_source']["tcode_mains"]
if "tcode_subs" in item['_source'] :
tcode_subs= item['_source']["tcode_subs"]
code = {
"label" : tcode_label,
"id" : tcode_id
}
if code_state == True :
tcode_mains.append(code)
else:
tcode_subs.append(code)
data={
'_id':section_id,
'_source' : {
'tcode_mains': tcode_mains,
'tcode_subs': tcode_subs,
}
}
bulk_data.append(data)
# انتقال دسته جمعی کدها به الاستیک
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) )
elastic.updateBulkList(bulk_data, index_name_o)
##### columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
# columns=[0, 1, 2, 3, 4, 5, 6, 7]
# new_df = pd.DataFrame(rows_list_new, columns=columns)
# if result_path == '' :
# directory_path = os.path.dirname(file_excel)
# result_path = directory_path + "/result/"
# file_name = os.path.basename(file_excel)
# file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
# print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
file_log2= file_log.replace(".txt", "_2.txt")
with open(file_log2, 'w', encoding='utf8') as file2:
file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""):
def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = "", update_elastic = False, genrate_excel = True):
df = pd.read_excel(file_excel, sheet_name=0)
@@ -198,9 +29,17 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
total = len(df[column_names[0]])
print('total : ', total)
file = open(file_log, 'w+', encoding='utf8')
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
try:
os.makedirs(result_path, exist_ok=True)
except Exception as e:
print(result_path)
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
file = open(result_path + file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("app/repair_data/qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
@@ -210,17 +49,52 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
prevRow = None
try:
for row in rows_list:
row_number = row[column_names[0]]
title = row[column_names[1]]
section_title = row[column_names[2]]
ts_date = ""
code_state = ""
row_number = row[column_names[0]] # ردیف
# if row_number == 152:
# print(row_number)
c_name = 'عنوان و تاریخ تصویب قانون'
if not c_name in column_names :
c_name = 'عنوان'
if not c_name in column_names :
print("!!!!!!!!!!!! error column in title ", c_name)
continue
title = row[c_name]
if title is None or is_nan_or_none_or_empty(title) or title is None or is_nan_or_none_or_empty(title) :
title = prevRow[column_names[1]]
else:
prevRow = row
ts_date = ""
c_name = 'تاریخ تصویب'
if c_name in column_names :
ts_date = row[c_name]
ts_ref = ""
c_name = 'مرجع تصویب'
if c_name in column_names :
ts_ref = row[c_name]
content = ""
c_name = 'متن قانون'
if c_name in column_names :
content = row[c_name]
if content is None or is_nan_or_none_or_empty(content) :
content = ''
c_name = 'مواد مرتبط'
if not c_name in column_names :
print("!!!!!!!!!!!! error column in ", c_name)
continue
section_title = row[c_name]
code_state = ""
c_name = 'نوع ارتباط'
if c_name in column_names :
code_state = row[c_name]
qanon_id = 0
section_id = 0
state = ''
@@ -231,7 +105,11 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
title = text_normalizer.normalize_search_qanon(title)
qanon_title, ts_date, ts_ref = get_qanon_date(title)
qanon_title, ts_date_1, ts_ref_1 = get_qanon_date(title)
if not ts_date and ts_date_1:
ts_date = ts_date_1
if not ts_ref and ts_ref_1:
ts_ref = ts_ref_1
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
@@ -253,7 +131,7 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
# اگر پیدا نشد، از الاستیک جستجو کند
if qanon_id == 0 :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon", ts_ref)
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
dic_error_qanon_title[qanon_title]=count
@@ -261,22 +139,36 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
if qanon_title=='قانون مالياتهاي مستقيم':
print(ts_date)
print(ts_ref)
break
else:
state = 'قانون-جستجو'
# اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ...
section_title = text_normalizer.normalize_search_qanon(str(section_title))
result_section_title = get_section_correct(section_title)
result_section_id = []
result_section_title=[]
if qanon_id != 0 :
section_title = str(section_title).replace('\n', '،')
if qanon_id == 'qq83655' :
#if 'ماده 188> فصل سوم> باب دویم' in section_title:
print(qanon_id)
section_title = text_normalizer.normalize_search_qanon(str(section_title))
result_section_title = get_section_correct(section_title)
for section_title in result_section_title:
if section_title == 'all' :
state = 'صحیح'
result_section_id.append('all')
continue
section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title)
other_title2 = get_section_title2(section_title)
section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title, other_title2)
# - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود
if score < 90 :
dic_error_section_title[str(qanon_id)+'=='+section_title]=count
@@ -289,11 +181,27 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
result_section_id.append(section_id)
if content and state == 'خطا-جزء' :
section_id, score, section_item = searchSectionIdContent(elastic, "mj_qa_section", qanon_id , section_title, content)
# - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود
if score < 90 :
dic_error_section_title[str(qanon_id)+'=='+section_title]=count
print('='*10 , str(count) , ' section error', qanon_id, ' --> ', section_title )
file.write('---- section error ---' + str(qanon_id) + ' ----- ' + section_title + '\n')
section_id = 0
state = 'خطا-جزء'
elif state == '':
state = 'صحیح'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row[column_count+1]=qanon_id
row[column_count+2]= '#'.join(str(item) for item in result_section_id)
row[column_count+2]= ''
if result_section_id :
rrr = '#'.join(str(item) for item in result_section_id)
row[column_count+2]= rrr
row[column_count+3]=state
row[column_count+4]=qanon_title +'#'+ ts_date +'#'+ ts_ref
ttt = f'{qanon_title}#{ts_date}#{ts_ref}'
row[column_count+4]= ttt
row[column_count+5]='#'.join(result_section_title)
rows_list_new.append(row)
@@ -301,20 +209,25 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
tstate = 'نامعتبر'
c_name = 'وضعیت اعتبار'
if not c_name in column_names :
c_name = 'وضعیت تنقيحي'
if c_name in column_names :
tstate = row[c_name].replace('#', '').replace('=', '')
tstate = str(row[c_name]).replace('#', '').replace('=', '')
if tstate.startswith('نامعتبر') :
tstate = 'نامعتبر-' + tstate
treason = ''
c_name = 'مستند عدم اعتبار'
if not c_name in column_names :
c_name = 'مستندات و دلايل'
if c_name in column_names :
treason = row[c_name].replace('#','\n').replace('=','\n')
treason = str(row[c_name]).replace('#','\n').replace('=','\n')
description = ''
c_name = 'توضیحات'
if c_name in column_names :
description = row[c_name].replace('*', '')
description = str(row[c_name]).replace('*', '')
# ذخیره کد در الاستیک برای شناسه های یافت شده
for section_id in result_section_id :
@@ -362,7 +275,8 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data, index_name_o)
if update_elastic :
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
@@ -370,7 +284,8 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) )
elastic.updateBulkList(bulk_data, index_name_o)
if update_elastic :
elastic.updateBulkList(bulk_data, index_name_o)
# columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
@@ -381,15 +296,14 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
column_names.append(column_count+5)
columns= column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
if genrate_excel :
print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
new_df.to_excel(file_excel2, index=False, engine='openpyxl')
print('################# create excel file : ', file_excel2)
except Exception as e:
@@ -410,18 +324,9 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
# file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""):
# excel_helper = ExcelHelper()
# df = excel_helper.load_data(file)
def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = "", update_elastic = False, genrate_excel = True):
# df = pd.read_excel('records.xlsx', sheet_name='Cars', usecols=['Car Name', 'Car Price'])
# print(df)
df = pd.read_excel(file_excel, sheet_name=0, header=None)
# print(df[0:10])
# print(df.columns.ravel())
# print(df.columns.tolist())
# print(df['EmpName'].tolist())
# print(df[0].tolist())
count = 0
rows_list = df.to_dict(orient='records')
total = len(df[0])
@@ -432,7 +337,7 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
dict_qanon_id = get_dict_qanon_title("app/repair_data/qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
@@ -542,7 +447,8 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data, index_name_o)
if update_elastic :
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
@@ -550,7 +456,8 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) )
elastic.updateBulkList(bulk_data, index_name_o)
if update_elastic :
elastic.updateBulkList(bulk_data, index_name_o)
# columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
@@ -563,8 +470,9 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
if genrate_excel :
print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
@@ -582,18 +490,19 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i
def run_Codes_directory(elastic, directory, output):
dic_code_id={
"آب" : 1,
"آمار، برنامه و بودجه" : 2,
"آموزش و پرورش" : 3,
"آیین دادرسی مدنی" : 5,
"سلامت" : 30,
"فرهنگ و هنر" : 33,
"مسکن و شهرسازی" : 42,
"مناطق آزاد و ویژه اقتصادی" : 45,
"نفت و گاز" : 49
}
def run_Codes_directory(elastic, directory, output, all_codes, update_elastic = False, genrate_excel = True):
# dic_code_id={
# "آب" : 1,
# "آمار، برنامه و بودجه" : 2,
# "آموزش و پرورش" : 3,
# "آیین دادرسی مدنی" : 5,
# "سلامت" : 30,
# "فرهنگ و هنر" : 33,
# "مسکن و شهرسازی" : 42,
# "مناطق آزاد و ویژه اقتصادی" : 45,
# "نفت و گاز" : 49
# }
# List all files in the specified directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
for file in files :
@@ -608,26 +517,27 @@ def run_Codes_directory(elastic, directory, output):
print(output)
code_id = 0
if code_name in dic_code_id :
code_id = dic_code_id[code_name]
importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file)
else :
print('00000 error 000000 ', code_name)
# item_found = [item for item in all_codes if item.get("label") == code_name]
# if item_found :
# code_id = item_found.get("id")
importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file, "", update_elastic, genrate_excel)
# else :
# print('00000 error 000000 ', code_name)
def run_Etebar_directory(elastic, directory, output):
dic_code_id={
"آب" : 1,
"آمار، برنامه و بودجه" : 2,
"آموزش و پرورش" : 3,
"آیین دادرسی مدنی" : 5,
"سلامت" : 30,
"فرهنگ و هنر" : 33,
"مسکن و شهرسازی" : 42,
"مناطق آزاد و ویژه اقتصادی" : 45,
"نفت و گاز" : 49,
}
def run_Etebar_directory(elastic, directory, output, all_codes, update_elastic = False, genrate_excel = True):
# dic_code_id={
# "آب" : 1,
# "آمار، برنامه و بودجه" : 2,
# "آموزش و پرورش" : 3,
# "آیین دادرسی مدنی" : 5,
# "سلامت" : 30,
# "فرهنگ و هنر" : 33,
# "مسکن و شهرسازی" : 42,
# "مناطق آزاد و ویژه اقتصادی" : 45,
# "نفت و گاز" : 49,
# }
# List all files in the specified directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
for file in files :
@@ -648,16 +558,12 @@ def run_Etebar_directory(elastic, directory, output):
print(output)
code_id = 0
importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file)
# if code_name in dic_code_id :
# code_id = dic_code_id[code_name]
# importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file)
# else :
# print('00000 error 000000 ', code_name)
item_found = [item for item in all_codes if item.get("label") == code_name]
if item_found :
code_id = item_found.get("id")
importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file, "", update_elastic, genrate_excel)
else :
print('00000 error 000000 ', code_name)
@@ -678,35 +584,29 @@ path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#run_Codes_directory(elastic, "./data/tcodes", "./data/tcodes/result")
all_codes = []
with open("./data/codes49.json", "r", encoding="utf8") as f:
codes_1 = json.load(f)
all_codes = codes_1
run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result")
run_Codes_directory(elastic, "./data/tcodes", "./data/tcodes/result", all_codes, False, True)
# run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result")
# importCodesToElastic(elastic, "./data/tcodes/مسکن و شهرسازی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r3.txt")
# importCodesToElastic(elastic, "./data/tcodes/آمار، برنامه و بودجه.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_آمار.txt")
# importCodesToElastic(elastic, "./data/tcodes/آیین دادرسی مدنی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_دادرسی.txt")
# importCodesToElastic(elastic, "./data/tcodes/نفت و گاز.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_نفت.txt")
# text="قانون  بلدیه"
#text = text.replace("\u00a0", " ") # No Break space
# text="قانون تشکیلات، وظایف و انتخابات شوراهای اسلامی کشور و انتخاب شهرداران مصوب 1 /3 /1375 و اصلاحات بعدی آن"
# text="ائین‌نامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28ر12ر1345"
# text="قانون بودجه سال 1369کل کشور"
# text="قانون تشکیلات، وظایف و انتخابات شوراهای اسلامی کشور و انتخاب شهرداران مصوب 1/3/1375 و اصلاحات بعدی آن"
text="قانون بودجه سال 1369کل کشور"
text="پیوست 3>متن >ضمیمه 1>قسمت الف>فصل پنجم>جدول الف-1-1-1 /5"
# searchSectionId(elastic, "mj_qa_section", "qq240970", text )
# text = text_normalizer.date_correction(text)
# text = re.sub(r"(\d+?) /(\d+?) /(\d+?)", r"\1/\2/\3", text)
# text = re.sub(r"(\d)/(\d)/(\d{4})", r"0\1/0\2/\3", text)
# print(text.split('/'))
# text1 = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", text)
# print(text)
# print(text1)
# print(text1==text)
# print( searchQanonId(elastic, text) )
file_path="data/tcodes2/فایل سند پشتیبان کد ارتباطات 27 مهر 1404.xlsx"
log_file = "/log_r_"+"ارتباطات"+".txt"
#importEtebarToElastic(elastic, file_path, "mj_qa_section", "فناوری ارتباطات", "1", log_file)
# qanon_title= 'قانون مالياتهاي مستقيم'
# qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
# qanon_title = qanon_title.replace("–", "-")
# ts_date = '1366/12/03'
# qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# print(qanon_id, score)
+621
View File
@@ -0,0 +1,621 @@
import numbers
import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch, helpers
import json
import re
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from app.common.elastic_helper import ElasticHelper
def get_files(directory):
# Pattern to match filenames like out_1.json, out_25.json, etc.
pattern = re.compile(r"output_(\d+)\.json$")
max_num = 0
list_file = []
for filename in os.listdir(directory):
match = pattern.match(filename)
if match:
list_file.append(directory+"/"+filename)
return list_file
def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", update_to_elastic=False, by_ai_code = False):
try:
# Read JSON file
with open(file_path, 'r', encoding="utf8") as f:
data = json.load(f)
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse JSON file: {str(e)}")
except FileNotFoundError:
raise FileNotFoundError(f"File not found: {file_path}")
list_bulk = []
batch_size = 200
processed_count = 0
total = len(data)
batch_size_number = 1
list_section_id_notfound = []
list_prccessed_negative_file = []
for item in data:
section_id = item["id"]
reaseon_code_item = item["history_codes"]
#آخرین مورد برداشته میشود، برای هر دو حالت ذخیره کامل از الاستیک و فقط جدید نیز جواب میده
history_codes_new = reaseon_code_item[-1]
history_codes = []
ai_code = {}
ai_codes = []
res = None
try :
if elastic :
res = elastic.get_doctument(index_name_o, section_id)
except:
list_section_id_notfound.append(section_id)
continue
if res :
if "history_codes" in res["_source"] :
history_codes = res["_source"]["history_codes"]
if "ai_code" in res["_source"] :
ai_code = res["_source"]["ai_code"]
if "ai_codes" in res["_source"] :
ai_codes = res["_source"]["ai_codes"]
if history_codes_new["sub_key"] == "negative" :
list_prccessed_negative_file.append(section_id)
source = {}
# تکراری هست بخاطر اجراهای تکراری روی یک داده
if history_codes and history_codes_new["sub_key"] == history_codes[-1]["sub_key"] and history_codes_new["version_key"] == history_codes[-1]["version_key"] :
if not by_ai_code :
continue # دیگه چیزی برای بروز رسانی الاستیک نیست
else :
history_codes.append(history_codes_new)
source["history_codes"] = history_codes
if by_ai_code and history_codes_new["sub_key"] == 'positive':
ai_code_new = {
"label": history_codes_new["label"],
"score": history_codes_new["score"]
}
source["ai_code"] = ai_code_new
# اگر کدگذاری جدید مدل با موجود مخالف بود، قبلی به کدهای فرعی اضافه شود
if not ai_code["label"] == ai_code_new["label"] :
ai_codes_new = []
ai_code_found = False
for code in ai_codes :
if ai_code_new["score"] == code["score"] and ai_code_new["label"] == code["label"] :
ai_code_found = True
ai_codes.append(code)
source["ai_codes"] = ai_codes_new
if not update_to_elastic :
continue
list_bulk.append({
"_id" : section_id,
"_source": source
}
)
if len(list_bulk) >= batch_size :
elastic.updateBulkList(list_bulk, index_name_o)
list_bulk = []
print("updated batch : ", batch_size_number, f"/{total} --->", file_path)
batch_size_number += 1
if list_bulk:
elastic.updateBulkList(list_bulk, index_name_o)
print("updated batch : ", batch_size_number, " --->", file_path)
batch_size_number += 1
return list_prccessed_negative_file
def parse_and_update_multi_code(file_path, elastic, all_codes, index_name_o, update_to_elastic=False, by_ai_code = False):
try:
# Read JSON file
with open(file_path, 'r', encoding="utf8") as f:
data = json.load(f)
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse JSON file: {str(e)}")
except FileNotFoundError:
raise FileNotFoundError(f"File not found: {file_path}")
list_bulk = []
batch_size = 200
processed_count = 0
total = len(data)
batch_size_number = 1
list_section_id_notfound = []
list_prccessed_negative_file = []
for item in data:
section_id = item["id"]
reaseon_code_item = item["history_codes"][0]
if reaseon_code_item["sub_key"] == "negative" :
print('==!!!!!!!!!!=== warning .... negative is ', section_id, ' ' , file_path)
list_prccessed_negative_file.append(section_id)
continue
##----------------------------------------
### بررسی معتربر بودن کد مدل
label = reaseon_code_item["label_ai"]
label = label.strip()
try:
number = int(label) # or int(value) for integers
if all_codes and number > 0 and number <= 49 :
label = all_codes[number-1]
except ValueError:
label = label.strip('0123456789. ')
label = label.lstrip('0123456789. ')
if all_codes and not label in all_codes :
list_prccessed_negative_file.append(section_id)
continue
##----------------------------------------
history_codes = []
ai_code = {}
ai_codes = []
res = None
try :
if elastic :
res = elastic.get_doctument(index_name_o, section_id)
except:
list_section_id_notfound.append(section_id)
continue
if res :
if "history_codes" in res["_source"] :
history_codes = res["_source"]["history_codes"]
# print(history_codes)
source = {}
history_last = history_codes[-1]
# تکراری هست بخاطر اجراهای تکراری روی یک داده
if history_codes and reaseon_code_item["version_key"] == history_last["version_key"] :
if not "sub_key" in history_last :
history_last["sub_key"] = "positive" # موقتا بخاطر خطایی در وسط کار
if reaseon_code_item["sub_key"] == history_last["sub_key"] :
continue # دیگه چیزی برای بروز رسانی الاستیک نیست
history_code_new = {
"score" : reaseon_code_item["score"],
"label" : label,
"sub_key" : reaseon_code_item["sub_key"],
"version_key" : reaseon_code_item["version_key"],
"description" : reaseon_code_item["description"]
}
history_codes.append(history_code_new)
source["history_codes"] = history_codes
if by_ai_code and reaseon_code_item["sub_key"] == 'positive':
ai_code = {
"score" : reaseon_code_item["score"],
"label" : label,
}
for code in reaseon_code_item["secondary_labels"] :
label1 = code["label"]
label1 = label1.strip()
#--------------------------------
#--- بررسی تکراری
try:
number = int(label1) # or int(value) for integers
if all_codes and number > 0 and number <= 49 :
label1 = all_codes[number-1]
except ValueError:
label1 = label1.strip('0123456789. ')
label1 = label1.lstrip('0123456789. ')
if all_codes and not label1 in all_codes :
continue
#--------------------------------
if not label1 == ai_code["label"] :
ai_codes.append({
"score" : code["confidence"],
"label" : code["label"],
})
source["ai_code"] = ai_code
source["ai_codes"] = ai_codes
if not update_to_elastic :
continue
list_bulk.append({
"_id" : section_id,
"_source": source
}
)
if len(list_bulk) >= batch_size :
elastic.updateBulkList(list_bulk, index_name_o)
list_bulk = []
print("updated batch : ", batch_size_number, f"/{total} --->", file_path)
batch_size_number += 1
if list_bulk:
elastic.updateBulkList(list_bulk, index_name_o)
print("updated batch : ", batch_size_number, " --->", file_path)
batch_size_number += 1
return list_prccessed_negative_file
def get_proccesed_count():
#////بررسی آمار اولیه
all_ids_list = []
try:
with open("data/codes_reaseon_oss/all_ids_list.json", "r", encoding="utf8") as f:
all_ids_list = json.load(f)
except :
all_ids_list = []
print("len candids ", len(all_ids_list), len(set(all_ids_list)))
list_proccess = []
with open("data/codes_reaseon_oss/process_id_final_1.json", "r", encoding="utf8") as f:
list_proccess1 = json.load(f)
list_proccess.extend(list_proccess1)
with open("data/codes_reaseon_oss/process_id_final_2.json", "r", encoding="utf8") as f:
list_proccess1 = json.load(f)
list_proccess.extend(list_proccess1)
with open("data/codes_reaseon_oss/process_id_final_3.json", "r", encoding="utf8") as f:
list_proccess1 = json.load(f)
list_proccess.extend(list_proccess1)
print("len proccessed ", len(list_proccess), len(set(list_proccess)))
return list_proccess
def extract_list_week_sections(elastic, index_name="mj_qa_section"):
body = {
"query": {
"bool": {
"must": [
{
"range": {
"content_len": {
"lte": 50
}
}
}
]
}
}
}
list_weeks = []
try:
list = elastic.es_iterate_all_documents(index_name, body)
except Exception as e:
print("extract_list_week_sections --> ", str(e))
return []
for mentry in list:
entry = mentry["source"]
id = entry.get("id", "")
list_weeks.append(id)
return list_weeks
def genrate_list_negative(paths=[],list_minues=[]):
elastic = None
list_prccessed_negative = []
try:
with open("data/codes_reaseon_oss/processed_id_negative.json", "w", encoding="utf8") as f:
json.dump(list_prccessed_negative, f)
except :
list_prccessed_negative = []
for path in paths :
print('*', 100)
print('******** ', path)
for file in get_files(path):
print(file)
list_prccessed_negative_file = parse_and_update_code(file, elastic, "mj_qa_section", False)
list_prccessed_negative.extend(list_prccessed_negative_file)
if list_minues :
print("start list minues ..... wait several minutes .... ")
list_prccessed_negative = [x for x in list_prccessed_negative if x not in list_minues]
with open("data/codes_reaseon_oss/processed_id_negative.json", "w", encoding="utf8") as f:
l_set = set(list_prccessed_negative)
print("total negative len is : " , len(l_set))
json.dump(list(l_set), f)
def import_codes_to_elastic(elastic, all_codes, by_ai_code, paths=[], list_minues=[]):
list_prccessed_negative = []
try:
with open("data/codes_reaseon_oss/processed_id_negative.json", "r", encoding="utf8") as f:
list_prccessed_negative = json.load(f)
except :
list_prccessed_negative = []
for path in paths :
print('*', 100)
print('******** ', path)
for file in get_files(path):
print(file)
if 'data_h100_full' in path : # data_h100_full_1 , ..., data_h100_full_4
list_prccessed_negative_file = parse_and_update_multi_code(file, elastic, all_codes, "mj_qa_section", True, by_ai_code)
else:
list_prccessed_negative_file = parse_and_update_code(file, elastic, "mj_qa_section", True, by_ai_code)
list_prccessed_negative.extend(list_prccessed_negative_file)
if list_minues :
print("start list minues ..... wait several minutes .... ")
list_prccessed_negative = [x for x in list_prccessed_negative if x not in list_minues]
with open("data/codes_reaseon_oss/processed_id_negative.json", "w", encoding="utf8") as f:
l_set = set(list_prccessed_negative)
print("total negative len is : " , len(l_set))
json.dump(list(l_set), f)
def parse_notvalid_multi_codes(paths, all_codes=[], file_not_valid="processed_id_notvalid"):
json_no_valids = {}
list_prccessed_negative = []
total = 0
for path in paths :
print('*', 100)
print('******** ', path)
for file in get_files(path):
print(file)
data = []
with open(file, 'r', encoding="utf8") as f:
data = json.load(f)
for item in data:
section_id = item["id"]
reaseon_code_item = item["history_codes"][0]
label = reaseon_code_item["label_ai"]
label = label.strip()
try:
number = int(label) # or int(value) for integers
if number > 0 and number <= 49 :
label = all_codes[number-1]
except ValueError:
label = label.strip('0123456789. ')
label = label.lstrip('0123456789. ')
if not label in all_codes :
if not label in json_no_valids :
json_no_valids[label] = []
json_no_valids[label].append(item)
list_prccessed_negative.append(section_id)
total +=1
with open("data/codes_reaseon_oss/code_no_valids.json", "w", encoding="utf8") as f:
print("total not valid len is : " , total, len(json_no_valids.items()))
json.dump(json_no_valids, f)
with open(f"data/codes_reaseon_oss/{file_not_valid}.json", "w", encoding="utf8") as f:
l_set = set(list_prccessed_negative)
print("total negative len is : " , len(l_set))
json.dump(list(l_set), f)
def extract_sectionid_in_files(paths, sections=[], file_result="section_id_files"):
json_no_valids = {}
list_prccessed_negative = []
total = 0
result=[]
for path in paths :
print('*', 100)
print('******** ', path)
for file in get_files(path):
print(file)
data = []
with open(file, 'r', encoding="utf8") as f:
data = json.load(f)
for item in data:
section_id = item["id"]
if section_id in sections :
result.append({
"id": section_id,
"file": file,
"history_codes": item["history_codes"]
})
with open(f"data/codes_reaseon_oss/{file_result}.json", "w", encoding="utf8") as f:
print("total negative len is : " , len(result))
json.dump(result, f)
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')
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#------------------------------------------------
#---- بررسی آمار اولیه
# get_proccesed_count()
#------------------------------------------------
#------ استخراج موارد منفی - مرحله 1 ، بعد از انتقال به سرور جدید
# list_week_sections = extract_list_week_sections(elastic,)
# print(" list_week_sections --> ", len(list_week_sections))
# paths= [ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2' ]
# genrate_list_negative(paths, list_week_sections)
#------------------------------------------------
#------ استخراج موارد منفی مرحله 2 ، بعد از اتمام یک دور کامل
# paths= [ 'data/codes_reaseon_oss/data_h100_3' ]
# genrate_list_negative([])
#------------------------------------------------
#------ درج در الاستیک - بخش ا
# list_week_sections = []
# # list_week_sections = extract_list_week_sections(elastic,)
# paths=[ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2', 'data/codes_reaseon_oss/data_h100_3' ]
# import_codes_to_elastic(elastic, [], True, paths, list_week_sections)
#------------------------------------------------
#------ درج در الاستیک - بخش 2
# all_codes = []
# with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f:
# codes_1 = json.load(f)
# all_codes = codes_1
# paths=[ 'data/codes_reaseon_oss/data_h100_full_1', 'data/codes_reaseon_oss/data_h100_full_2', 'data/codes_reaseon_oss/data_h100_full_3', 'data/codes_reaseon_oss/data_h100_full_4' ]
# paths=[ 'data/codes_reaseon_oss/data_h100_full_test1' ]
# print(all_codes)
# import_codes_to_elastic(elastic, all_codes, False, paths)
# #------------------------------------------------
# ##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند
# all_codes = []
# with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f:
# codes_1 = json.load(f)
# all_codes = codes_1
# paths=[ 'data/codes_reaseon_oss/data_h100_full_1' ]
# parse_notvalid_multi_codes(paths, all_codes, "processed_id_notvalid_step_1")
####---- count = 3080
# #------------------------------------------------
# ##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند
# all_codes = []
# with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f:
# codes_1 = json.load(f)
# all_codes = codes_1
# paths=[ 'data/codes_reaseon_oss/data_h100_full_2' ]
# parse_notvalid_multi_codes(paths, all_codes, "processed_id_notvalid_step_2")
####---- count = 1110
#------------------------------------------------
##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند
# all_codes = []
# with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f:
# codes_1 = json.load(f)
# all_codes = codes_1
# paths=[ 'data/codes_reaseon_oss/data_h100_full_3' ]
# parse_notvalid_multi_codes(paths, all_codes, "processed_id_notvalid_step_3")
####---- count = 600
#------------------------------------------------
##---- بررسی وضعیت بعضی کدها در خروجی فایلهای مدل
# paths=[ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2', 'data/codes_reaseon_oss/data_h100_full_1', 'data/codes_reaseon_oss/data_h100_full_2', 'data/codes_reaseon_oss/data_h100_full_3', 'data/codes_reaseon_oss/data_h100_full_4' ]
# extract_sectionid_in_files(paths, sections=["qs688df5c54ea9f_017", "qs3353621", "qs3026464"], "section_id_files_1")
#-------------------------------------
#--- مرحله پاکسازی- بخش 1
# POST mj_qa_section/_update_by_query
# {
# "query": {
# "bool": {
# "must": [
# {
# "exists": {
# "field": "ai_code.label"
# }
# },
# {
# "bool": {
# "should": [
# {
# "match": {
# "other_info.full_path": "امضاء"
# }
# },
# {
# "match": {
# "other_info.full_path": "موخره"
# }
# }
# ]
# }
# }
# ]
# }
# }
# ,"script": {
# "source": """
# ctx._source.remove("ai_code");
# ctx._source.remove("ai_codes");
# """,
# "lang": "painless"
# }
# }
# POST mj_qa_section/_update_by_query
# {
# "query": {
# "bool": {
# "must": [
# {
# "exists": {
# "field": "code-ai"
# }
# }
# ]
# }
# }
# ,"script": {
# "source": """
# ctx._source.remove("code-ai");
# """,
# "lang": "painless"
# }
# }
#-------------------------------------
+117
View File
@@ -0,0 +1,117 @@
import io
import os
import json
from dotenv import load_dotenv
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper
# def get_custom_fileds(elastci, index_name, fields=[])
load_dotenv(dotenv_path='config.env')
host=os.getenv('HOST_160')
password=os.getenv('HOST_160_PASS')
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# elastic.exportToJsonForAI("output","mj_qa_section", "mj_qa_section.json", {}, ["content", "qanon_title", "ts_date", "other_info.full_path"])
##### qanon_id !!
# elastic.exportToJsonForAI("output","mj_qa_section", "mj_qa_section_childs.json", {}, ["content", "qanon_title", "ts_date", "other_info.full_path", "parent_id", "child_order", "nlp_childs"])
body = {
"query": {
"bool": {
"must": [
{
"bool" :{
"must_not":[
{
"terms": {
"title_type": [
"موافقتنامه"
]
}
}
]
}
},
{
"term":{
"ai_code.label":"فناوری اطلاعات و ارتباطات"
}
}
]
}
}
}
# body = {
# "query":{
# "term":{
# "ai_code.label":"فناوری اطلاعات و ارتباطات"
# }
# }
# }
elastic.exportToJsonForAI("output","mj_qa_section", "section_codes_ertabatat.json", body, ["ai_codes", "ai_code", "content", "qanon_title", "qanon_id", "other_info.full_path"], "normal")
body = {
"sort": [
{"qanon_id": {"order": "asc"} },
{ "child_order":{ "order": "asc" } }
]
}
# elastic.exportToJsonForAI("output","mj_qa_section", "mj_qa_section_qanon.json", body, ["other_info.full_path"], 'normal', 'qanon_id')
###--- مناسب برای پرش در تسک کدگذاری
body = {
"query": {
"bool": {
"must": [
{
"bool": {
"should": [
{
"terms": {
"title_type": [
"موافقتنامه"
]
}
},
{
"match": {
"other_info.full_path": "عنوان"
}
},
{
"match": {
"other_info.full_path": "امضاء"
}
},
{
"match": {
"other_info.full_path": "موخره"
}
}
]
}
}
]
}
}
}
# elastic.exportToJsonForAI("output","mj_qa_section", "ignore_sections_code.json", body, [], 'id', '')
+63
View File
@@ -0,0 +1,63 @@
import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch, helpers
import json
import re
load_dotenv()
def run_folder(dir):
pattern = re.compile(r"output_(\d+)\.json$")
process_ids = []
filename = ''
processed_id = []
# processed_id_set = set(processed_id)
try:
for filename in os.listdir(dir):
# match = pattern.match(filename)
# if match:
# # Read JSON file
# data = {}
print(filename)
with open(dir + filename, 'r', encoding="utf-8") as f:
data = json.load(f)
for item in data :
processed_id.append(item["id"])
except json.JSONDecodeError as e:
print(f"File not found: {filename}")
raise ValueError(f"Failed to parse JSON file: {str(e)}")
except FileNotFoundError:
raise FileNotFoundError(f"File not found: {filename}")
return processed_id
processed_id_1 = run_folder("data/codes_reaseon_oss/data_g3090/")
print("processed_id 1 ", len(processed_id_1))
processed_id_2 = run_folder("data/codes_reaseon_oss/data_h100/")
print("processed_id 2 ", len(processed_id_2))
processed_id_1.extend(processed_id_2)
print("total ", len(processed_id_1))
processed_id_set1 = set(processed_id_1)
print("total set ", len(processed_id_set1))
with open("data/codes_reaseon_oss/process_tt_id.json", "w") as f:
json.dump(list(processed_id_set1), f)
# with open("data/codes_reaseon_oss/section_codes.json", 'r', encoding="utf-8") as f:
# data = json.load(f)
# print("section_codes ", len(data.items()))
# with open("data/codes_reaseon_oss/mj_qa_section.json", 'r', encoding="utf-8") as f:
# data = json.load(f)
# print("mj_qa_section ", len(data))
+170
View File
@@ -0,0 +1,170 @@
import os
from dotenv import load_dotenv
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import time
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper
##--------------------------------
# لازم است این فیلد پرشود تا مجلس بتواند دسترسی تغییر داشته باشد
##------------------------------------
def fill_doc_state( elastic, index_name_i, index_name_o, file_log) :
body = {
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "asc"}}
]
}
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
count = 0
text_normal = TextNormalizer()
result = {}
result_new = {}
total_count = 0
bulk_data = []
bulk_data_section = []
t1= datetime.datetime.now()
print(t1)
file = open(file_log, 'a+', encoding='utf8')
i = 0
doc_tags=[]
qanon_id=0
prev_qanon_id = 0
siyasatha_list = ["qq85859", "qq260090", "qq121403", "qq222873", "qq198729", "qq121413", "qq118359", "qq305009", "qq118373", "qq286578"]
for mentry in list:
entry = mentry["source"]
id = entry.get("id", "")
qanon_id = entry.get("qanon_id", "")
qanon_title = entry.get("qanon_title", "")
nlp_tags = entry.get("nlp_tags", [])
ref_state = entry.get("ref_state", [])
# title_type = entry.get("title_type", "عادی")
title_type = getTitleType(qanon_title)
if prev_qanon_id == 0 :
prev_qanon_id = qanon_id
elif prev_qanon_id != qanon_id :
data={
'_id':prev_qanon_id,
'_source' : {
'doc_tags': doc_tags
}
}
body = {
"script": {
"source": "ctx._source.doc_tags=params.doc_tags",
"lang": "painless",
"params" : { 'doc_tags' : doc_tags }
},
"query": {
"term": {
"qanon_id": { "value" : prev_qanon_id }
}
}
}
elastic.updateByQueryIndex(index_name_i, body)
bulk_data.append(data)
doc_tags=[]
if len(ref_state) > 0 :
if "مهذب" not in doc_tags :
doc_tags.append("مهذب")
elif title_type not in ["عادی", "اصلی", "موافقتنامه", "بودجه"] :
if "تبعی" not in doc_tags :
doc_tags.append("تبعی")
elif title_type in ["عادی", "اصلی", "موافقتنامه", "بودجه"] :
if "اصلی" not in doc_tags :
doc_tags.append("اصلی")
if qanon_id in siyasatha_list :
if "سیاستهای کلی" not in doc_tags :
doc_tags.append("سیاستهای کلی")
if "qanon_usefull" in nlp_tags :
if "پرکاربرد" not in doc_tags :
doc_tags.append("پرکاربرد")
prev_qanon_id = qanon_id
i=i+1
if len(bulk_data) >= 10:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + qanon_id)
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if prev_qanon_id != 0:
data={
'_id':prev_qanon_id,
'_source' : {
'doc_tags': doc_tags
}
}
body = {
"script": {
"source": "ctx._source.doc_tags=params.doc_tags",
"lang": "painless",
"params" : { 'doc_tags' : doc_tags }
},
"query": {
"term": {
"qanon_id": { "value" : prev_qanon_id }
}
}
}
elastic.updateByQueryIndex(index_name_i, body)
bulk_data.append(data)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + qanon_id )
elastic.updateBulkList(bulk_data, index_name_o)
file.close()
print('end success import_law_section_to_elastic')
t2= datetime.datetime.now()
print(t2-t1)
load_dotenv(dotenv_path='config.env')
host=os.getenv('HOST_160')
password=os.getenv('HOST_160_PASS')
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# print(dict_effected_sections)
# try:
# item = elastic.get_doctument("mj_qa_section", "3223423")
# except Exception as e:
# print(e)
# print(type(e).__name__)
# print(str(e))
fill_doc_state( elastic, "mj_qa_section", "mj_qa_qanon", "./output/log_r1.txt")
+7 -2
View File
@@ -1,5 +1,10 @@
import os
from dotenv import load_dotenv
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from app.common.text_normalizer import TextNormalizer
# from general import *
@@ -43,7 +48,7 @@ path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_mashruh")
#elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section.zip', 'mj_qa_section', 'majles', False, 'mj_qa_section')
# elastic.restorFileToElastic2('G:/Project2/111/gn_setting.zip', 'gn_setting', 'general', False, 'gn_setting')
@@ -59,7 +64,7 @@ elastic = ElasticHelper(host, password, "elastic", path_base_map)
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section-m1")
# elastic.createIndex( 'mj_qa_section-m1', 'majles', 'mj_qa_section')
# elastic.restorFileToElastic2('G:/Project2/111/server112/mj_qa_section-m1.zip', 'mj_qa_section-m1', 'majles', False, 'mj_qa_section')
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section-m1.zip', 'mj_qa_section-m1', 'majles', False, 'mj_qa_section')
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_calendar")
# elastic.createIndex( 'gn_calendar', 'general', 'gn_calendar')