majles_codes_update
This commit is contained in:
@@ -15,7 +15,7 @@ from app.common.elastic_helper import ElasticHelper
|
||||
from app.common.config_base import *
|
||||
|
||||
|
||||
def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = "", update_elastic = False, genrate_excel = True):
|
||||
def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, file_log, result_path = "", update_elastic = False, genrate_excel = True):
|
||||
|
||||
df = pd.read_excel(file_excel, sheet_name=0)
|
||||
|
||||
@@ -45,7 +45,7 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_
|
||||
dic_error_section_title={}
|
||||
rows_list_new = []
|
||||
bulk_data = []
|
||||
total_count=0
|
||||
total_update=0
|
||||
prevRow = None
|
||||
try:
|
||||
for row in rows_list:
|
||||
@@ -273,8 +273,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))
|
||||
total_update += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_update) , str(count))
|
||||
if update_elastic :
|
||||
elastic.updateBulkList(bulk_data, index_name_o)
|
||||
bulk_data = []
|
||||
@@ -282,8 +282,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) )
|
||||
total_update += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_update) , str(count) )
|
||||
if update_elastic :
|
||||
elastic.updateBulkList(bulk_data, index_name_o)
|
||||
|
||||
@@ -324,7 +324,7 @@ 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 = "", update_elastic = False, genrate_excel = True):
|
||||
def parseCodesToExcel(elastic, file_excel, index_name_o, tcode_label, file_log, result_path = ""):
|
||||
|
||||
df = pd.read_excel(file_excel, sheet_name=0, header=None)
|
||||
count = 0
|
||||
@@ -343,7 +343,7 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i
|
||||
dic_error_section_title={}
|
||||
rows_list_new = []
|
||||
bulk_data = []
|
||||
total_count=0
|
||||
total_update=0
|
||||
try:
|
||||
for row in rows_list:
|
||||
section_title = row[column_names[0]]
|
||||
@@ -414,51 +414,6 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i
|
||||
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 :
|
||||
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))
|
||||
if update_elastic :
|
||||
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) )
|
||||
if update_elastic :
|
||||
elastic.updateBulkList(bulk_data, index_name_o)
|
||||
|
||||
|
||||
# columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
|
||||
columns=[0, 1, 2, 3, 4, 5, 6, 7]
|
||||
@@ -469,10 +424,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')
|
||||
|
||||
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('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
|
||||
new_df.to_excel(file_excel2, index=False, engine='openpyxl')
|
||||
|
||||
|
||||
except Exception as e:
|
||||
@@ -489,25 +443,185 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i
|
||||
file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
|
||||
|
||||
|
||||
def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, file_log):
|
||||
|
||||
df = pd.read_excel(file_excel, sheet_name=0)
|
||||
count = 0
|
||||
rows_list = df.to_dict(orient='records')
|
||||
total = len(df[0])
|
||||
print('total : ', total)
|
||||
|
||||
def run_Codes_directory(elastic, directory, output, all_codes, update_elastic = False, genrate_excel = True):
|
||||
column_names = df.columns.tolist()
|
||||
print(column_names)
|
||||
|
||||
file = open(file_log, 'w+', encoding='utf8')
|
||||
|
||||
bulk_data = []
|
||||
total_update=0
|
||||
row_number = 0
|
||||
try:
|
||||
for row in rows_list:
|
||||
|
||||
section_title = row[column_names[0]]
|
||||
ts_date = row[column_names[1]]
|
||||
qanon_title = row[column_names[2]]
|
||||
code_state = row[column_names[3]]
|
||||
row_number = row[column_names[4]]
|
||||
qanon_id = row[column_names[5]]
|
||||
section_id = row[column_names[6]]
|
||||
state_match = row[column_names[7]]
|
||||
|
||||
section_id_new = 0
|
||||
c_name = 'حکم' # بعضی فایلهای اصلاحی، شناسه اینجا ذخیره شده بود
|
||||
if c_name in column_names :
|
||||
section_id_new = row[c_name]
|
||||
|
||||
if not is_nan_or_none_or_empty(section_id_new) and section_id_new != 0 :
|
||||
section_id = section_id_new
|
||||
|
||||
# dic_code_id={
|
||||
# "آب" : 1,
|
||||
# "آمار، برنامه و بودجه" : 2,
|
||||
# "آموزش و پرورش" : 3,
|
||||
# "آیین دادرسی مدنی" : 5,
|
||||
# "سلامت" : 30,
|
||||
# "فرهنگ و هنر" : 33,
|
||||
# "مسکن و شهرسازی" : 42,
|
||||
# "مناطق آزاد و ویژه اقتصادی" : 45,
|
||||
# "نفت و گاز" : 49
|
||||
# }
|
||||
count = count + 1
|
||||
if (count % 10) == 0 :
|
||||
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
|
||||
|
||||
|
||||
data={}
|
||||
# ذخیره کد در الاستیک برای شناسه های یافت شده
|
||||
if section_id and section_id != 0:
|
||||
try :
|
||||
item = elastic.get_doctument(index_name_o,section_id)
|
||||
except Exception as e:
|
||||
print('-------------Exception as e section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n')
|
||||
file.write('----section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n')
|
||||
continue
|
||||
|
||||
if not item['found'] :
|
||||
print('------------------------------ section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n')
|
||||
file.write('----section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n')
|
||||
continue
|
||||
|
||||
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"]
|
||||
|
||||
nead_to_update = False
|
||||
if code_state :
|
||||
item_found = [item for item in tcode_mains if item == tcode_label]
|
||||
if not item_found :
|
||||
tcode_mains.append(tcode_label)
|
||||
nead_to_update = True
|
||||
else:
|
||||
item_found = [item for item in tcode_subs if item == tcode_label]
|
||||
if not item_found :
|
||||
tcode_subs.append(tcode_label)
|
||||
nead_to_update = True
|
||||
|
||||
if nead_to_update :
|
||||
data={
|
||||
'_id':section_id,
|
||||
'_source' : {
|
||||
'tcode_mains': tcode_mains,
|
||||
'tcode_subs': tcode_subs,
|
||||
}
|
||||
}
|
||||
bulk_data.append(data)
|
||||
# else:
|
||||
# print(" ------------ section_id not valid row_number=", row_number, " -->", section_id)
|
||||
|
||||
|
||||
# انتقال دسته جمعی کدها به الاستیک
|
||||
if nead_to_update and len(bulk_data) >= 200:
|
||||
total_update += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_update) , str(count))
|
||||
elastic.updateBulkList(bulk_data, index_name_o)
|
||||
bulk_data = []
|
||||
|
||||
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_update += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_update) , str(count) )
|
||||
elastic.updateBulkList(bulk_data, index_name_o)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
print('######################## Exception error ---' + str(count) + ' ***' + str(e) + '\n')
|
||||
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
|
||||
|
||||
file.close()
|
||||
|
||||
def extract_codes_to_json( file_excel, tcode_label, file_json):
|
||||
|
||||
df = pd.read_excel(file_excel, sheet_name=0)
|
||||
count = 0
|
||||
rows_list = df.to_dict(orient='records')
|
||||
total = len(df[0])
|
||||
print('total : ', total)
|
||||
|
||||
column_names = df.columns.tolist()
|
||||
print(column_names)
|
||||
|
||||
bulk_data = []
|
||||
total_update=0
|
||||
row_number = 0
|
||||
try:
|
||||
for row in rows_list:
|
||||
|
||||
section_title = row[column_names[0]]
|
||||
# ts_date = row[column_names[1]]
|
||||
# qanon_title = row[column_names[2]]
|
||||
code_state = row[column_names[3]]
|
||||
row_number = row[column_names[4]]
|
||||
# qanon_id = row[column_names[5]]
|
||||
section_id = row[column_names[6]]
|
||||
# state_match = row[column_names[7]]
|
||||
|
||||
section_id_new = 0
|
||||
# c_name = 'حکم' # بعضی فایلهای اصلاحی، شناسه اینجا ذخیره شده بود
|
||||
# if c_name in column_names :
|
||||
# section_id_new = row[c_name]
|
||||
|
||||
if not is_nan_or_none_or_empty(section_id_new) and section_id_new != 0 :
|
||||
section_id = section_id_new
|
||||
|
||||
count = count + 1
|
||||
if (count % 10) == 0 :
|
||||
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
|
||||
|
||||
|
||||
data={}
|
||||
# ذخیره کد در الاستیک برای شناسه های یافت شده
|
||||
if section_id and section_id != 0:
|
||||
|
||||
tcode_mains = []
|
||||
tcode_subs = []
|
||||
|
||||
data={
|
||||
'id':section_id,
|
||||
'label': tcode_label,
|
||||
'is_main': int(code_state),
|
||||
}
|
||||
bulk_data.append(data)
|
||||
|
||||
with open(file_json, "w", encoding="utf8") as f:
|
||||
json.dump(bulk_data, f, ensure_ascii=False, indent=4)
|
||||
|
||||
except Exception as e:
|
||||
print('######################## Exception error ---' + str(count) + ' ***' + str(e) + '\n')
|
||||
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
|
||||
|
||||
|
||||
def run_codes_to_elastic_directory(elastic, directory, output, all_codes, update_elastic = False, genrate_excel = True):
|
||||
|
||||
# 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 :
|
||||
file_name = os.path.basename(file)
|
||||
code_name = os.path.splitext(file_name)[0]
|
||||
_name = os.path.splitext(file_name)[0]
|
||||
code_name = _name.split('_')[0]
|
||||
print('=========================== start code_name ===> ', code_name)
|
||||
w1 = text_normalizer.split_words(code_name)[0]
|
||||
log_file = output + "/log_r_"+w1+".txt"
|
||||
file_path = os.path.join(directory, file)
|
||||
@@ -515,30 +629,23 @@ def run_Codes_directory(elastic, directory, output, all_codes, update_elastic =
|
||||
os.makedirs(output, exist_ok=True)
|
||||
except Exception as e:
|
||||
print(output)
|
||||
|
||||
# if not code_name in ['پولی و مالی' ,'اداری و استخدامی'] :
|
||||
# continue
|
||||
|
||||
code_id = 0
|
||||
# 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)
|
||||
item_found = [item for item in all_codes if item.get("title") == code_name]
|
||||
if item_found :
|
||||
if genrate_excel :
|
||||
parseCodesToExcel(elastic, file_path, "mj_qa_section", code_name, log_file, "")
|
||||
if update_elastic :
|
||||
importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, log_file)
|
||||
else :
|
||||
print('00000 error 000000 ', code_name)
|
||||
|
||||
|
||||
|
||||
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 :
|
||||
file_name = os.path.basename(file)
|
||||
@@ -557,56 +664,87 @@ def run_Etebar_directory(elastic, directory, output, all_codes, update_elastic =
|
||||
except Exception as e:
|
||||
print(output)
|
||||
|
||||
code_id = 0
|
||||
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)
|
||||
importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, log_file, "", update_elastic, genrate_excel)
|
||||
else :
|
||||
print('00000 error 000000 ', code_name)
|
||||
|
||||
|
||||
def run_codes_extract_directory(directory, output, all_codes):
|
||||
|
||||
# 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 :
|
||||
file_name = os.path.basename(file)
|
||||
_name = os.path.splitext(file_name)[0]
|
||||
code_name = _name.split('_')[0]
|
||||
print('=========================== start code_name ===> ', code_name)
|
||||
w1 = text_normalizer.split_words(code_name)[0]
|
||||
log_file = output + "/log_r_"+w1+".txt"
|
||||
file_path = os.path.join(directory, file)
|
||||
try:
|
||||
os.makedirs(output, exist_ok=True)
|
||||
except Exception as e:
|
||||
print(output)
|
||||
|
||||
# if not code_name in ['پولی و مالی' ,'اداری و استخدامی'] :
|
||||
# continue
|
||||
|
||||
item_found = [item for item in all_codes if item.get("title") == code_name]
|
||||
if item_found :
|
||||
extract_codes_to_json(file_path, code_name, output + f"/{code_name}.json")
|
||||
else :
|
||||
print('00000 error 000000 ', code_name)
|
||||
|
||||
|
||||
# -------------------------------------------------------------------- Run
|
||||
if __name__ == "__main__":
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
host=os.getenv('HOST_160')
|
||||
password=os.getenv('HOST_160_PASS')
|
||||
|
||||
# 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_113')
|
||||
# password=os.getenv('HOST_113_PASS')
|
||||
|
||||
host=os.getenv('HOST_113')
|
||||
password=os.getenv('HOST_113_PASS')
|
||||
print('.... codes_import_from_excel ......', host)
|
||||
|
||||
print(password)
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
|
||||
all_codes = []
|
||||
with open("./data/codes49.json", "r", encoding="utf8") as f:
|
||||
codes_1 = json.load(f)
|
||||
all_codes = codes_1
|
||||
# all_codes = []
|
||||
# with open("./data/codes49.json", "r", encoding="utf8") as f:
|
||||
# codes_1 = json.load(f)
|
||||
# all_codes = codes_1
|
||||
|
||||
run_Codes_directory(elastic, "./data/tcodes", "./data/tcodes/result", all_codes, False, True)
|
||||
#-------------------------------------
|
||||
#----- انتقال مرحله اول اکسل خطایابی شده مجلس برای کدگذاری ها
|
||||
# run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_1", "./data/tcodes/result", all_codes, True, False)
|
||||
|
||||
# run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result")
|
||||
#-------------------------------------
|
||||
#----- انتقال مرحله دوم اکسل خطایابی شده مجلس برای کدگذاری ها
|
||||
# run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_2", "./data/tcodes/result", all_codes, True, False)
|
||||
|
||||
# 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")
|
||||
#-------------------------------------
|
||||
#----- انتقال مرحله سوم اکسل خطایابی شده مجلس برای کدگذاری ها
|
||||
# run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_3", "./data/tcodes/result", all_codes, True, False)
|
||||
|
||||
# run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result")
|
||||
|
||||
file_path="data/tcodes2/فایل سند پشتیبان کد ارتباطات 27 مهر 1404.xlsx"
|
||||
log_file = "/log_r_"+"ارتباطات"+".txt"
|
||||
#importEtebarToElastic(elastic, file_path, "mj_qa_section", "فناوری ارتباطات", "1", log_file)
|
||||
file_path="data/tcodes/tcodes_llm/فایل سند پشتیبان کد ارتباطات 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)
|
||||
# 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)
|
||||
|
||||
@@ -9,19 +9,28 @@ import sys
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
|
||||
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
from app.common.general_functions import getTitleType
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
def get_files(directory):
|
||||
# Pattern to match filenames like out_1.json, out_25.json, etc.
|
||||
pattern = re.compile(r"output_(\d+)\.json$")
|
||||
def get_files(directory, pattern_file=r"output_(\d+)\.json$"):
|
||||
|
||||
pattern = None
|
||||
if pattern_file :
|
||||
pattern = re.compile(pattern_file)
|
||||
|
||||
max_num = 0
|
||||
list_file = []
|
||||
|
||||
for filename in os.listdir(directory):
|
||||
match = pattern.match(filename)
|
||||
if match:
|
||||
list_file.append(directory+"/"+filename)
|
||||
if pattern :
|
||||
match = pattern.match(filename)
|
||||
if match:
|
||||
list_file.append(directory+"/"+filename)
|
||||
else:
|
||||
list_file.append(directory+"/"+filename)
|
||||
|
||||
return list_file
|
||||
|
||||
|
||||
@@ -41,6 +50,7 @@ def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", up
|
||||
processed_count = 0
|
||||
total = len(data)
|
||||
batch_size_number = 1
|
||||
total_update = 0
|
||||
|
||||
|
||||
list_section_id_notfound = []
|
||||
@@ -78,8 +88,13 @@ def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", up
|
||||
list_prccessed_negative_file.append(section_id)
|
||||
|
||||
source = {}
|
||||
|
||||
history_code_last = {}
|
||||
|
||||
if history_codes:
|
||||
history_code_last = history_codes[-1]
|
||||
# تکراری هست بخاطر اجراهای تکراری روی یک داده
|
||||
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 history_code_last and history_codes_new["sub_key"] == history_code_last["sub_key"] and history_codes_new["version_key"] == history_code_last["version_key"] and history_codes_new["label"] == history_code_last["label"] :
|
||||
if not by_ai_code :
|
||||
continue # دیگه چیزی برای بروز رسانی الاستیک نیست
|
||||
else :
|
||||
@@ -94,16 +109,24 @@ def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", up
|
||||
}
|
||||
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)
|
||||
##------------------------------------------
|
||||
#### ترمیم کدهای فرعی
|
||||
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_new.append(code)
|
||||
|
||||
|
||||
source["ai_codes"] = ai_codes_new
|
||||
# اگر کدگذاری جدید مدل با موجود مخالف بود، قبلی به کدهای فرعی اضافه شود
|
||||
if ai_code and "label" in ai_code and not ai_code["label"] == ai_code_new["label"] :
|
||||
ai_codes_new.append(ai_code)
|
||||
|
||||
source["ai_codes"] = ai_codes_new
|
||||
##------------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -117,13 +140,15 @@ def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", up
|
||||
)
|
||||
if len(list_bulk) >= batch_size :
|
||||
elastic.updateBulkList(list_bulk, index_name_o)
|
||||
total_update += len(list_bulk)
|
||||
list_bulk = []
|
||||
print("updated batch : ", batch_size_number, f"/{total} --->", file_path)
|
||||
print("updated batch : ", batch_size_number, f" {total_update}/{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)
|
||||
total_update += len(list_bulk)
|
||||
print(" .... finish updated batch : ", batch_size_number, f" {total_update}/{total} --->", file_path)
|
||||
batch_size_number += 1
|
||||
|
||||
return list_prccessed_negative_file
|
||||
@@ -225,6 +250,8 @@ def parse_and_update_multi_code(file_path, elastic, all_codes, index_name_o, upd
|
||||
"label" : label,
|
||||
}
|
||||
|
||||
|
||||
### fill ai_codes
|
||||
for code in reaseon_code_item["secondary_labels"] :
|
||||
label1 = code["label"]
|
||||
label1 = label1.strip()
|
||||
@@ -341,7 +368,7 @@ def genrate_list_negative(paths=[],list_minues=[]):
|
||||
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)
|
||||
json.dump(list_prccessed_negative, f, ensure_ascii=False, indent=4)
|
||||
except :
|
||||
list_prccessed_negative = []
|
||||
|
||||
@@ -360,7 +387,7 @@ def genrate_list_negative(paths=[],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)
|
||||
json.dump(list(l_set), f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
def import_codes_to_elastic(elastic, all_codes, by_ai_code, paths=[], list_minues=[]):
|
||||
@@ -390,7 +417,7 @@ def import_codes_to_elastic(elastic, all_codes, by_ai_code, paths=[], list_minue
|
||||
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)
|
||||
json.dump(list(l_set), f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
def parse_notvalid_multi_codes(paths, all_codes=[], file_not_valid="processed_id_notvalid"):
|
||||
@@ -428,12 +455,12 @@ def parse_notvalid_multi_codes(paths, all_codes=[], file_not_valid="processed_id
|
||||
|
||||
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)
|
||||
json.dump(json_no_valids, f, ensure_ascii=False, indent=4)
|
||||
|
||||
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)
|
||||
json.dump(list(l_set), f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
def extract_sectionid_in_files(paths, sections=[], file_result="section_id_files"):
|
||||
@@ -461,161 +488,483 @@ def extract_sectionid_in_files(paths, sections=[], file_result="section_id_files
|
||||
|
||||
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)
|
||||
json.dump(result, f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
|
||||
host=os.getenv('HOST_160')
|
||||
password=os.getenv('HOST_160_PASS')
|
||||
print( "---------------->>>>>>>>>>>>>>>", host )
|
||||
def repair_notvalid_number_ai_codes( elastic, all_codes, index_name, update_to_elastic=False, body={}):
|
||||
|
||||
try:
|
||||
data = elastic.es_iterate_all_documents(index_name, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
|
||||
list_bulk = []
|
||||
batch_size = 200
|
||||
processed_count = 0
|
||||
total = elastic.total
|
||||
batch_size_number = 1
|
||||
count = 0
|
||||
for mentry in data:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
eid = entry.get("id", "")
|
||||
|
||||
# host=os.getenv('HOST_113')
|
||||
# password=os.getenv('HOST_113_PASS')
|
||||
# if (count % 100) == 0 :
|
||||
# print("%s -> %.2f " % (id , (count / elastic.total) if elastic.total > 0 else 0))
|
||||
|
||||
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([])
|
||||
|
||||
ai_codes = entry.get("ai_codes", {})
|
||||
if not ai_codes :
|
||||
continue
|
||||
|
||||
ai_codes_new = []
|
||||
for code in ai_codes :
|
||||
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
|
||||
|
||||
ai_codes_new.append({
|
||||
"label": label1,
|
||||
"score" : code["score"]
|
||||
})
|
||||
|
||||
##----------------------------------------
|
||||
|
||||
source = {
|
||||
"ai_codes" : ai_codes_new
|
||||
}
|
||||
|
||||
if not update_to_elastic :
|
||||
continue
|
||||
|
||||
list_bulk.append({
|
||||
"_id" : eid,
|
||||
"_source": source
|
||||
}
|
||||
)
|
||||
|
||||
if len(list_bulk) >= batch_size :
|
||||
elastic.updateBulkList(list_bulk, index_name)
|
||||
list_bulk = []
|
||||
print("updated batch : ", batch_size_number, f"/{total} --->")
|
||||
batch_size_number += 1
|
||||
|
||||
if list_bulk:
|
||||
elastic.updateBulkList(list_bulk, index_name)
|
||||
print("updated batch : ", batch_size_number)
|
||||
batch_size_number += 1
|
||||
|
||||
|
||||
def repair_html_title_type( elastic, index_name, update_to_elastic=False, body={}):
|
||||
|
||||
try:
|
||||
data = elastic.es_iterate_all_documents(index_name, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
|
||||
list_bulk = []
|
||||
batch_size = 200
|
||||
processed_count = 0
|
||||
total = elastic.total
|
||||
batch_size_number = 1
|
||||
count = 0
|
||||
for mentry in data:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
eid = entry.get("id", "")
|
||||
|
||||
|
||||
qanon_title = entry.get("qanon_title", "")
|
||||
title_type = getTitleType(qanon_title)
|
||||
# if title_type == 'موافقتنامه' :
|
||||
# print(title_type[::-1]) # reverce
|
||||
|
||||
#------------------------------------------------
|
||||
#------ درج در الاستیک - بخش ا
|
||||
# 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)
|
||||
|
||||
source = {
|
||||
"title_type" : title_type
|
||||
}
|
||||
# if (count % 100) == 0 :
|
||||
# print("%s -> %.2f " % (id , (count / elastic.total) if elastic.total > 0 else 0))
|
||||
|
||||
##----------------------------------------
|
||||
html = entry.get("html", {})
|
||||
if html :
|
||||
html = text_normal.repair_qanon_html(html)
|
||||
source['html'] = html
|
||||
|
||||
#------------------------------------------------
|
||||
#------ درج در الاستیک - بخش 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
|
||||
|
||||
##----------------------------------------
|
||||
|
||||
if not update_to_elastic :
|
||||
continue
|
||||
|
||||
list_bulk.append({
|
||||
"_id" : eid,
|
||||
"_source": source
|
||||
}
|
||||
)
|
||||
|
||||
# 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)
|
||||
if len(list_bulk) >= batch_size :
|
||||
elastic.updateBulkList(list_bulk, index_name)
|
||||
list_bulk = []
|
||||
print("updated batch : ", batch_size_number, f"/{total} --->")
|
||||
batch_size_number += 1
|
||||
|
||||
if list_bulk:
|
||||
elastic.updateBulkList(list_bulk, index_name)
|
||||
print("updated batch : ", batch_size_number)
|
||||
batch_size_number += 1
|
||||
|
||||
|
||||
|
||||
# #------------------------------------------------
|
||||
# ##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند
|
||||
# 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
|
||||
|
||||
def extract_codes_diff_llm_tanghih( elastic, index_name, file_result, list_ignore=[], body={}):
|
||||
|
||||
try:
|
||||
data = elastic.es_iterate_all_documents(index_name, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
# #------------------------------------------------
|
||||
# ##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند
|
||||
# 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
|
||||
|
||||
list_data = []
|
||||
batch_size = 200
|
||||
processed_count = 0
|
||||
total = elastic.total
|
||||
batch_size_number = 1
|
||||
count = 0
|
||||
for mentry in data:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
eid = entry.get("id", "")
|
||||
|
||||
#------------------------------------------------
|
||||
##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند
|
||||
# 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
|
||||
if eid in list_ignore :
|
||||
continue
|
||||
|
||||
# if (count % 100) == 0 :
|
||||
# print("%s -> %.2f " % (id , (count / elastic.total) if elastic.total > 0 else 0))
|
||||
|
||||
|
||||
#------------------------------------------------
|
||||
##---- بررسی وضعیت بعضی کدها در خروجی فایلهای مدل
|
||||
# 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")
|
||||
|
||||
ai_code = entry.get("ai_code", {})
|
||||
ai_codes = entry.get("ai_codes", [])
|
||||
|
||||
tcode_mains = entry.get("tcode_mains", [])
|
||||
tcode_subs = entry.get("tcode_subs", [])
|
||||
|
||||
if not ai_code or not tcode_mains :
|
||||
continue
|
||||
|
||||
#آیا اختلاف بین دو کد هوش مصنوعی و تنقیح هست ؟
|
||||
label1 = ai_code['label']
|
||||
found = False
|
||||
for code in tcode_mains :
|
||||
if label1 == code :
|
||||
found = True
|
||||
break
|
||||
|
||||
# اختلافی نیست
|
||||
if found :
|
||||
continue
|
||||
|
||||
source = {}
|
||||
history_last = {}
|
||||
history_codes = entry.get("history_codes", [])
|
||||
if history_codes :
|
||||
history_last = history_codes[-1]
|
||||
|
||||
# محتوای توضیحی هوش
|
||||
if history_last and history_last["version_key"] == "D49_v2" and history_last["sub_key"] == "positive" :
|
||||
source["history_codes"] = []
|
||||
source["history_codes"].append(history_last)
|
||||
|
||||
source["tcode_mains"] = tcode_mains
|
||||
source["tcode_subs"] = tcode_subs
|
||||
source["ai_code"] = ai_code
|
||||
source["ai_codes"] = ai_codes
|
||||
source["id"] = eid
|
||||
source["content"] = entry.get("content", "")
|
||||
source["qanon_title"] = entry.get("qanon_title", "")
|
||||
|
||||
list_data.append(source)
|
||||
|
||||
with open(f"data/codes_reaseon_oss/{file_result}.json", "w", encoding="utf-8") as f:
|
||||
print("total diffffffffffff len is : " , len(list_data))
|
||||
json.dump(list_data, f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
|
||||
#-------------------------------------
|
||||
#--- مرحله پاکسازی- بخش 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"
|
||||
# }
|
||||
# }
|
||||
|
||||
def repair_diff_codes_llm(elastic, paths, index_name, file_result="diff_section_ids"):
|
||||
|
||||
json_no_valids = {}
|
||||
list_prccessed_negative = []
|
||||
total = 0
|
||||
result=[]
|
||||
bulk_data=[]
|
||||
total_update = 0
|
||||
list_section_id_notfound = []
|
||||
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)
|
||||
|
||||
print(" ...start data ", len(data))
|
||||
for item in data:
|
||||
section_id = item["id"]
|
||||
if not "diff_ai" in item or not "ai_result" in item["diff_ai"] :
|
||||
continue
|
||||
diff_ai = item["diff_ai"]["ai_result"]
|
||||
label_new = diff_ai["correct_domain"]
|
||||
description_new = diff_ai["correct_description"]
|
||||
|
||||
if label_new == "null":
|
||||
list_section_id_notfound.append(section_id)
|
||||
continue
|
||||
|
||||
res = None
|
||||
try :
|
||||
res = elastic.get_doctument(index_name, section_id)
|
||||
except:
|
||||
list_section_id_notfound.append(section_id)
|
||||
continue
|
||||
|
||||
if not res :
|
||||
continue
|
||||
|
||||
|
||||
history_codes = []
|
||||
ai_code = {}
|
||||
ai_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" in res["_source"] :
|
||||
history_codes = res["_source"]["history_codes"]
|
||||
|
||||
source = {}
|
||||
history_last = {}
|
||||
if history_codes :
|
||||
history_last = history_codes[-1]
|
||||
|
||||
#حذف آخرین مورد تکراری
|
||||
if history_last and history_last["version_key"] == "D49_v2" and history_last["sub_key"] == "positive" :
|
||||
history_codes = history_codes[:-1]
|
||||
|
||||
history_code_new = {
|
||||
"score" : ai_code["score"],
|
||||
"label" : label_new,
|
||||
"sub_key" : "positive",
|
||||
"version_key" : "D49_v2",
|
||||
"description" : description_new
|
||||
}
|
||||
history_codes.append(history_code_new)
|
||||
source["history_codes"] = history_codes
|
||||
|
||||
# if label_new != ai_code["label"] :
|
||||
ai_code_new = {
|
||||
"score" : ai_code["score"],
|
||||
"label" : label_new
|
||||
}
|
||||
|
||||
# کد اصلی قبلی ، اگر با کد جدید همنام نباشد و در کدهای فرعی نباشد به کدهای فرعی اضافه شود
|
||||
item_found = [item for item in ai_codes if item.get("label") == ai_code["label"]]
|
||||
if not item_found and ai_code["label"] != label_new:
|
||||
ai_code["score"] = ai_code["score"]/2
|
||||
ai_codes.append(ai_code)
|
||||
source["ai_codes"] = ai_codes
|
||||
|
||||
source["ai_code"] = ai_code_new
|
||||
data={
|
||||
'_id':section_id,
|
||||
'_source' : source
|
||||
}
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
# انتقال دسته جمعی کدها به الاستیک
|
||||
if len(bulk_data) >= 200:
|
||||
total_update += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_update))
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
bulk_data = []
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_update += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_update) )
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
bulk_data=[]
|
||||
|
||||
# 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, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
|
||||
# POST mj_qa_section/_update_by_query
|
||||
# {
|
||||
# "query": {
|
||||
# "bool": {
|
||||
# "must": [
|
||||
# {
|
||||
# "exists": {
|
||||
# "field": "code-ai"
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# }
|
||||
# }
|
||||
# ,"script": {
|
||||
# "source": """
|
||||
# ctx._source.remove("code-ai");
|
||||
# """,
|
||||
# "lang": "painless"
|
||||
# }
|
||||
# }
|
||||
#-------------------------------------
|
||||
# -------------------------------------------------------------------- Run
|
||||
if __name__ == "__main__":
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
|
||||
host=os.getenv('HOST_160')
|
||||
password=os.getenv('HOST_160_PASS')
|
||||
|
||||
# host=os.getenv('HOST_113')
|
||||
# password=os.getenv('HOST_113_PASS')
|
||||
|
||||
print( "---------------->>>>>>>>>>>>>>>", host )
|
||||
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
# extract_codes_diff_llm_tanghih( elastic, "mj_qa_section", "diff_llm_tanghih_2", body={})
|
||||
|
||||
#------------------------------------------------
|
||||
#---- بررسی آمار اولیه
|
||||
# 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_3', '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=["qs2138157"], file_result="section_id_files_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
|
||||
|
||||
body={}
|
||||
#repair_notvalid_number_ai_codes(elastic, all_codes, "mj_qa_section", True, body)
|
||||
|
||||
#-------------------------------------
|
||||
#--- مرحله پاکسازی- بخش 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"
|
||||
# }
|
||||
# }
|
||||
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
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
|
||||
from app.common.general_functions import getTitleType
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
from app.for_ai.codes_llm_update_to_elastic import repair_html_title_type, import_codes_to_elastic, extract_codes_diff_llm_tanghih, repair_diff_codes_llm
|
||||
from app.for_ai.codes_import_from_excel import run_codes_to_elastic_directory, run_codes_extract_directory
|
||||
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
|
||||
# host=os.getenv('HOST_160')
|
||||
# password=os.getenv('HOST_160_PASS')
|
||||
# print( "---------------->>>>>>>>>>>>>>>", host )
|
||||
|
||||
host=os.getenv('HOST_113')
|
||||
password=os.getenv('HOST_113_PASS')
|
||||
|
||||
|
||||
print('.... majles_codes_update_steps ......', host)
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
#------------------------------------------------
|
||||
#-- مرحله 1 : حذف فیلدهای اضافی
|
||||
# body = {
|
||||
# "query": {
|
||||
# "bool": {
|
||||
# "should": [
|
||||
# {
|
||||
# "exists": {"field": "tcode"}
|
||||
# },
|
||||
# {
|
||||
# "exists": {"field": "nlp_parser"}
|
||||
# },
|
||||
# {
|
||||
# "exists": {"field": "content_normal"}
|
||||
# },
|
||||
# {
|
||||
# "exists": {"field": "tcode_mains"}
|
||||
# },
|
||||
# {
|
||||
# "exists": {"field": "tcode_subs"}
|
||||
# },
|
||||
# {
|
||||
# "exists": {"field": "ners_v1"}
|
||||
# },
|
||||
# {
|
||||
# "exists": {"field": "level"}
|
||||
# },
|
||||
# {
|
||||
# "exists": {"field": "code-ai"}
|
||||
# },
|
||||
# ]
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
|
||||
# elastic.removeCustomFileds("mj_qa_section", ["tcode","nlp_parser","content_normal","tcode_mains","tcode_subs", "ners_v1", "level", "code-ai"], {}, body )
|
||||
# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_1_remove_fileds")
|
||||
|
||||
#-------------------------------------
|
||||
#---- مرحله دوم، اصلاح تاریخ فیلد html و اصلاح فیلد title_type
|
||||
# body={}
|
||||
# repair_html_title_type( elastic, "mj_qa_section", True, body)
|
||||
# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_2_html_title_type")
|
||||
|
||||
#-------------------------------------
|
||||
#--- مرحله پاکسازی
|
||||
# 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": {1
|
||||
# "source": """
|
||||
# ctx._source.remove("ai_code");
|
||||
# ctx._source.remove("ai_codes");
|
||||
# """,
|
||||
# "lang": "painless"
|
||||
# }
|
||||
# }
|
||||
|
||||
|
||||
#------------------------------------------------
|
||||
#------ درج در الاستیک - بخش ا
|
||||
# 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)
|
||||
# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_3_1_h100_codes")
|
||||
|
||||
# #------------------------------------------------
|
||||
# # #------ درج در الاستیک - بخش 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' ]
|
||||
# import_codes_to_elastic(elastic, all_codes, True, paths)
|
||||
# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_3_2_h100_full")
|
||||
|
||||
|
||||
#-------------------------------------
|
||||
#-------------------------------------
|
||||
#-------------------------------------
|
||||
|
||||
#----- انتقال مرحله اول اکسل خطایابی شده مجلس برای کدگذاری ها
|
||||
|
||||
all_codes = []
|
||||
with open("./data/codes49.json", "r", encoding="utf8") as f:
|
||||
codes_1 = json.load(f)
|
||||
all_codes = codes_1
|
||||
|
||||
# run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_1", "./data/tcodes/corrected_majles/edit_1/result", all_codes, True, False)
|
||||
|
||||
#-------------------------------------
|
||||
#----- انتقال مرحله دوم اکسل خطایابی شده مجلس برای کدگذاری ها
|
||||
# run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_2", "./data/tcodes/corrected_majles/edit_2/result", all_codes, True, False)
|
||||
|
||||
#-------------------------------------
|
||||
#----- انتقال مرحله سوم اکسل خطایابی شده مجلس برای کدگذاری ها
|
||||
# run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_3", "./data/tcodes/corrected_majles/edit_3/result", all_codes, True, False)
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_4_edit_1_3")
|
||||
|
||||
#-------------------------------------
|
||||
#------ برای بررسی و خطایابی استفاده شد
|
||||
#----- مواردی که کدگذاری ما مشکوک بود کشف شد و دوباره با
|
||||
#----- llm
|
||||
# ----- مورد ارزیابی و تولید نتیجه جدید شد که در مرحله بعد درج شد
|
||||
|
||||
# list_ignore = []
|
||||
# with open("data/codes_reaseon_oss/diff_llm_tanghih_1_3_step1.json", "r", encoding="utf8") as f:
|
||||
# codes_1 = json.load(f)
|
||||
# for item in codes_1 :
|
||||
# list_ignore.append(item["id"])
|
||||
# print(' list_ignore len ', len(list_ignore))
|
||||
|
||||
# extract_codes_diff_llm_tanghih( elastic, "mj_qa_section", "diff_llm_tanghih_1_3_step2", list_ignore, body={})
|
||||
|
||||
#-------------------------------------
|
||||
#------ درج کدهای اختلافی مرحله قبل که کدگذاری مجدد انجام شد
|
||||
|
||||
# paths=[ 'data/codes_reaseon_oss/data_llm_diff' ]
|
||||
# repair_diff_codes_llm( elastic, paths, "mj_qa_section", "diff_section_ids_1")
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_5_diff_1")
|
||||
|
||||
|
||||
#-------------------------------------
|
||||
#------ استخراج برخی کدهای باقیمانده که اکسل آنها از قبل موجود هست و تولید فایل مناسب برای درج فایل محور در بانک مجلس
|
||||
|
||||
|
||||
run_codes_extract_directory( "./data/tcodes/corrected_majles/not_edit", "./data/tcodes/corrected_majles/not_edit/result_json", all_codes)
|
||||
Reference in New Issue
Block a user