procces refactor majles
This commit is contained in:
@@ -0,0 +1,612 @@
|
||||
import os
|
||||
import re
|
||||
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 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)
|
||||
|
||||
count = 0
|
||||
rows_list = df.to_dict(orient='records')
|
||||
|
||||
column_names = df.columns.tolist()
|
||||
column_count = len(column_names)
|
||||
# print(column_names)
|
||||
|
||||
total = len(df[column_names[0]])
|
||||
print('total : ', total)
|
||||
|
||||
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)
|
||||
|
||||
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={}
|
||||
rows_list_new = []
|
||||
bulk_data = []
|
||||
total_count=0
|
||||
prevRow = None
|
||||
try:
|
||||
for row in rows_list:
|
||||
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 = ''
|
||||
|
||||
count = count + 1
|
||||
if (count % 10) == 0 :
|
||||
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
|
||||
|
||||
|
||||
title = text_normalizer.normalize_search_qanon(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)
|
||||
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
|
||||
# قانون بودجه سال 1369کل کشور
|
||||
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
|
||||
|
||||
# قانون ساختمان شاهراه تهران – كرج
|
||||
qanon_title = qanon_title.replace("–", "-")
|
||||
|
||||
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", ts_ref)
|
||||
# اگر قابل اطمینان نبود، خطا ثبت کند
|
||||
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 = 'خطا-قانون'
|
||||
if qanon_title=='قانون مالياتهاي مستقيم':
|
||||
print(ts_date)
|
||||
print(ts_ref)
|
||||
break
|
||||
|
||||
|
||||
else:
|
||||
state = 'قانون-جستجو'
|
||||
|
||||
# اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ...
|
||||
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
|
||||
|
||||
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
|
||||
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 = 'صحیح'
|
||||
|
||||
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]= ''
|
||||
if result_section_id :
|
||||
rrr = '#'.join(str(item) for item in result_section_id)
|
||||
row[column_count+2]= rrr
|
||||
row[column_count+3]=state
|
||||
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)
|
||||
|
||||
data={}
|
||||
|
||||
tstate = 'نامعتبر'
|
||||
c_name = 'وضعیت اعتبار'
|
||||
if not c_name in column_names :
|
||||
c_name = 'وضعیت تنقيحي'
|
||||
|
||||
if c_name in column_names :
|
||||
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 = str(row[c_name]).replace('#','\n').replace('=','\n')
|
||||
|
||||
description = ''
|
||||
c_name = 'توضیحات'
|
||||
if c_name in column_names :
|
||||
description = str(row[c_name]).replace('*', '')
|
||||
|
||||
# ذخیره کد در الاستیک برای شناسه های یافت شده
|
||||
for section_id in result_section_id :
|
||||
|
||||
if section_id == '' or section_id == 0 :
|
||||
continue
|
||||
|
||||
if section_id =='all':
|
||||
tstate = tstate + ' کل '
|
||||
result = get__all_section_qanon(elastic, index_name_o, qanon_id)
|
||||
for sid in result :
|
||||
tvalid_state={
|
||||
"tstate": tstate.strip(),
|
||||
"description": description,
|
||||
"treason": treason,
|
||||
# "treason_type": treason_type
|
||||
}
|
||||
|
||||
data={
|
||||
'_id':sid,
|
||||
'_source' : {
|
||||
'tvalid_state': tvalid_state
|
||||
}
|
||||
}
|
||||
bulk_data.append(data)
|
||||
break
|
||||
|
||||
tvalid_state={
|
||||
"tstate": tstate.strip(),
|
||||
"description": description,
|
||||
"treason": treason,
|
||||
# "treason_type": treason_type
|
||||
}
|
||||
|
||||
data={
|
||||
'_id':section_id,
|
||||
'_source' : {
|
||||
'tvalid_state': tvalid_state
|
||||
}
|
||||
}
|
||||
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=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
|
||||
column_names.append(column_count+1)
|
||||
column_names.append(column_count+2)
|
||||
column_names.append(column_count+3)
|
||||
column_names.append(column_count+4)
|
||||
column_names.append(column_count+5)
|
||||
columns= column_names
|
||||
new_df = pd.DataFrame(rows_list_new, columns=columns)
|
||||
|
||||
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('################# create excel file : ', file_excel2)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
tb = traceback.extract_tb(e.__traceback__)
|
||||
print(tb)
|
||||
line_number = tb[-1].lineno # Get the line number of the last call
|
||||
print(f"Error: {e} on line {line_number}")
|
||||
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 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(file_excel, sheet_name=0, header=None)
|
||||
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("app/repair_data/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]]
|
||||
|
||||
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 :
|
||||
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]
|
||||
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')
|
||||
|
||||
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:
|
||||
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 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 :
|
||||
file_name = os.path.basename(file)
|
||||
code_name = os.path.splitext(file_name)[0]
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
|
||||
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)
|
||||
if '~$' in file_name :
|
||||
continue
|
||||
code_name = os.path.splitext(file_name)[0]
|
||||
code_name = code_name.replace("نامعتبر-", "").strip()
|
||||
w1 = text_normalizer.split_words(code_name)[0]
|
||||
log_file = output + "/log_r_"+w1+".txt"
|
||||
file_path = os.path.join(directory, file)
|
||||
# if code_name != 'سلامت' :
|
||||
# continue
|
||||
|
||||
try:
|
||||
os.makedirs(output, exist_ok=True)
|
||||
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)
|
||||
else :
|
||||
print('00000 error 000000 ', code_name)
|
||||
|
||||
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
|
||||
# host=os.getenv('HOST_160')
|
||||
# password=os.getenv('HOST_160_PASS')
|
||||
|
||||
# host=os.getenv('HOST_112')
|
||||
# password=os.getenv('HOST_112_PASS')
|
||||
|
||||
host=os.getenv('HOST_113')
|
||||
password=os.getenv('HOST_113_PASS')
|
||||
|
||||
print(password)
|
||||
|
||||
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
|
||||
|
||||
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")
|
||||
|
||||
|
||||
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)
|
||||
@@ -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"
|
||||
# }
|
||||
# }
|
||||
#-------------------------------------
|
||||
@@ -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', '')
|
||||
@@ -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))
|
||||
Reference in New Issue
Block a user