run_codes_extract_directory

This commit is contained in:
hsafaei
2025-12-04 13:47:58 +03:30
parent e616d748c5
commit 1c6d446110
8 changed files with 960 additions and 382 deletions
+105 -49
View File
@@ -26,7 +26,7 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, file_l
column_count = len(column_names)
# print(column_names)
total = len(df[column_names[0]])
total = len(rows_list)
print('total : ', total)
if result_path == '' :
@@ -324,16 +324,29 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, file_l
# file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
def parseCodesToExcel(elastic, file_excel, index_name_o, tcode_label, file_log, result_path = ""):
def parseCodesToExcel(elastic, file_excel, index_name_o, tcode_label, file_log, result_path, col_index, head_top=False):
df = pd.read_excel(file_excel, sheet_name=0, header=None)
if head_top :
df = pd.read_excel(file_excel, sheet_name=0, header=1)
else:
df = pd.read_excel(file_excel, sheet_name=0, header=None)
count = 0
rows_list = df.to_dict(orient='records')
total = len(df[0])
total = len(rows_list)
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
print('=========== parseCodesToExcel ===== column_names : ', column_names)
col_names = {}
col_new_count = 0
for key, value in col_index.items() :
if value in column_names :
col_names[key]=column_names[value]
else :
col_names[key]=len(column_names)+col_new_count
col_new_count +=1
file = open(file_log, 'w+', encoding='utf8')
@@ -344,13 +357,21 @@ def parseCodesToExcel(elastic, file_excel, index_name_o, tcode_label, file_log,
rows_list_new = []
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]]
section_title = row[col_names["section_title"]]
ts_date = row[col_names["ts_date"]]
qanon_title = row[col_names["qanon_title"]]
code_state = row[col_names["code_state"]]
row_number = row[col_names["row_number"]]
if section_title != section_title : # Nan
continue
if isinstance(section_title, int) : # ردیف اول
continue
qanon_id = 0
section_id = 0
@@ -409,14 +430,20 @@ def parseCodesToExcel(elastic, file_excel, index_name_o, tcode_label, file_log,
state = 'صحیح'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row[5]=qanon_id
row[6]=section_id
row[7]=state
row[col_names["qanon_id"]]=qanon_id
row[col_names["section_id"]]=section_id
row[col_names["state_match"]]=state
rows_list_new.append(row)
# columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
columns=[0, 1, 2, 3, 4, 5, 6, 7]
columns=[]
c = 0
for item in col_names.items() :
columns.append(c)
c += 1
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
@@ -430,7 +457,9 @@ def parseCodesToExcel(elastic, file_excel, index_name_o, tcode_label, file_log,
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
print('----Exception error --- row_number : ' , str(row_number), '/', str(count) , ' ***' , str(e) )
print(str(traceback.print_exc()) )
file.write('----Exception error --- row_number : ' + str(row_number)+ '/' + str(count) + ' ***' + str(e) + '\n' + str(traceback.print_exc()) + '\n')
file.close()
@@ -443,17 +472,25 @@ def parseCodesToExcel(elastic, file_excel, index_name_o, tcode_label, file_log,
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):
def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, file_log, col_index, head_top=False):
df = pd.read_excel(file_excel, sheet_name=0)
if head_top :
df = pd.read_excel(file_excel, sheet_name=0, header=1)
else :
df = pd.read_excel(file_excel, sheet_name=0)
count = 0
rows_list = df.to_dict(orient='records')
total = len(df[0])
total = len(rows_list)
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
col_names = {}
for key, value in col_index.items() :
col_names[key]=column_names[value]
file = open(file_log, 'w+', encoding='utf8')
bulk_data = []
@@ -461,15 +498,16 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, file_lo
row_number = 0
try:
for row in rows_list:
section_title = row[col_names["section_title"]]
ts_date = row[col_names["ts_date"]]
qanon_title = row[col_names["qanon_title"]]
code_state = row[col_names["code_state"]]
row_number = row[col_names["row_number"]]
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]]
qanon_id = row[col_names["qanon_id"]]
section_id = row[col_names["section_id"]]
state_match = row[col_names["state_match"]]
section_id_new = 0
c_name = 'حکم' # بعضی فایلهای اصلاحی، شناسه اینجا ذخیره شده بود
@@ -552,39 +590,44 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, file_lo
file.close()
def extract_codes_to_json( file_excel, tcode_label, file_json):
df = pd.read_excel(file_excel, sheet_name=0)
def extract_codes_to_json( file_excel, tcode_label, file_json, col_index, head_top=False):
if head_top :
df = pd.read_excel(file_excel, sheet_name=0, header=1)
else:
df = pd.read_excel(file_excel, sheet_name=0, header=None)
count = 0
rows_list = df.to_dict(orient='records')
column_names = df.columns.tolist()
print(column_names)
print('column_names --> ', column_names)
col_names = {}
for key, value in col_index.items() :
col_names[key]=column_names[value]
number_base = 0
total = len(df)
total = len(rows_list)
print('total : ', total)
bulk_data = []
total_update=0
row_number = 0
try:
for row in rows_list:
section_title = ""
section_id = ""
try:
section_title = row[column_names[number_base]]
# ts_date = row[column_names[1]]
# qanon_title = row[column_names[2]]
code_state = row[column_names[number_base+3]]
row_number = row[column_names[number_base+4]]
# qanon_id = row[column_names[5]]
section_id = row[column_names[number_base+6]]
# state_match = row[column_names[7]]
except :
pass
row_number = row[col_names["row_number"]]
section_title = row[col_names["section_title"]]
code_state = row[col_names["code_state"]]
section_id = row[col_names["section_id"]]
section_id_new = 0
# c_name = 'حکم' # بعضی فایلهای اصلاحی، شناسه اینجا ذخیره شده بود
@@ -624,12 +667,25 @@ def extract_codes_to_json( file_excel, tcode_label, file_json):
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')
print('######################## Exception error --- row_number : ' , str(row_number), '/', str(count) , ' ***' , str(e) )
print(str(traceback.print_exc()) )
def run_codes_to_elastic_directory(elastic, directory, output, all_codes, update_elastic = False, genrate_excel = True):
def run_codes_to_elastic_directory(elastic, directory, output, all_codes, update_elastic = False, genrate_excel = True, col_index={}, head_top=False):
if not col_index :
col_index = {
"section_title" : 0,
"ts_date" : 1,
"qanon_title" : 2,
"code_state" : 3,
"row_number" : 4,
"qanon_id" : 5,
"section_id" : 6,
"state_match" : 7,
}
# 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 :
@@ -651,9 +707,9 @@ def run_codes_to_elastic_directory(elastic, directory, output, all_codes, update
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, "")
parseCodesToExcel(elastic, file_path, "mj_qa_section", code_name, log_file, "", col_index, head_top)
if update_elastic :
importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, log_file)
importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, log_file, col_index, head_top)
else :
print('00000 error 000000 ', code_name)
@@ -686,7 +742,7 @@ def run_Etebar_directory(elastic, directory, output, all_codes, update_elastic =
print('00000 error 000000 ', code_name)
def run_codes_extract_directory(directory, output, all_codes):
def run_codes_extract_directory(directory, output, all_codes, col_index={}, head_top=False):
# List all files in the specified directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
@@ -708,7 +764,7 @@ def run_codes_extract_directory(directory, output, all_codes):
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")
extract_codes_to_json(file_path, code_name, output + f"/{code_name}.json", col_index, head_top)
else :
print('00000 error 000000 ', code_name)
+183 -82
View File
@@ -7,55 +7,56 @@ import re
import zipfile
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from app.common.elastic_helper import ElasticHelper
from app.common.general_functions import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
from app.for_ai.codes_import_from_excel import run_codes_extract_directory
from app.parvande_qanon.import_qavanin_files_to_elastic import import_excel_before_to_elastic, import_excel_after_to_elastic, import_excel_tasmimat_to_elastic
from app.for_ai.codes_import_from_excel import (
run_codes_extract_directory,
run_codes_to_elastic_directory,
)
from app.parvande_qanon.import_qavanin_excels_to_elastic import (
import_excel_before_to_elastic,
import_excel_after_to_elastic,
import_excel_tasmimat_to_elastic,
)
from app.parvande_qanon.repair_qa_qanon_for_map_new import *
text_normal = TextNormalizer()
load_dotenv(dotenv_path='config.env')
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")
# print( "---------------->>>>>>>>>>>>>>>", host )
# host=os.getenv('HOST_113')
# password=os.getenv('HOST_113_PASS')
print('.... majles_codes_update_steps ......', host)
print(".... majles_codes_update_steps ......", host)
path_base_map = "G:/Project2/gateway_php/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#-------------------------------------
#--- مواردی از قانونهای جدید که فیلد زیر را ندارند باید اصلاح شوند
#--- main_type
# -------------------------------------
# --- مواردی از قانونهای جدید که فیلد زیر را ندارند باید اصلاح شوند
# --- main_type
# POST mj_qa_qanon/_update_by_query
body= {
"query": {
"bool": {
"must_not": [
{"exists": {"field": "main_type"}}
]
}
},
"script": {
body = {
"query": {"bool": {"must_not": [{"exists": {"field": "main_type"}}]}},
"script": {
"source": """
ctx._source.main_type = 'قانون'
""",
"lang": "painless"
}
"lang": "painless",
},
}
# elastic.updateByQueryIndex("mj_qa_qanon", body)
@@ -63,94 +64,194 @@ body= {
# POST mj_qa_qanon/_update_by_query
body = {
"query": {
"terms": {
"main_type": [
"اصلی",
"تبعی"
]
}
}
,
"script": {
"query": {"terms": {"main_type": ["اصلی", "تبعی"]}},
"script": {
"source": """
ctx._source.sub_type = ctx._source.main_type;
ctx._source.main_type = 'قانون'
""",
"lang": "painless"
}
"lang": "painless",
},
}
# elastic.updateByQueryIndex("mj_qa_qanon", body)
#-------------------------------------
#------ استخراج برخی کدهای باقیمانده که اکسل آنها از قبل موجود هست و تولید فایل مناسب برای درج فایل محور در بانک مجلس
#---
# PUT mj_df_qanon/_mapping
# {
# "properties":{
# "mom_type": {
# "type": "keyword"
# },
# "main_type_key": {
# "type": "keyword"
# }
# }
# }
# POST mj_df_qanon/_update_by_query
body = {
"query": {"terms": {"main_type": ["اصلی", "تبعی"]}},
"script": {
"source": """
ctx._source.mom_type = ctx._source.main_type;
ctx._source.main_type = 'قانون';
ctx._source.main_type_key = 'qasection';
""",
"lang": "painless",
},
}
# elastic.updateByQueryIndex("mj_df_qanon", body)
# -------------------------------------
# ------ استخراج برخی کدهای باقیمانده که اکسل آنها از قبل موجود هست و تولید فایل مناسب برای درج فایل محور در بانک مجلس
# ---
all_codes = []
with open("./data/codes49.json", "r", encoding="utf8") as f:
codes_1 = json.load(f)
codes_1 = json.load(f)
all_codes = codes_1
# run_codes_extract_directory( "./data/tcodes/corrected_majles/not_edit2", "./data/tcodes/corrected_majles/not_edit2/result_json", all_codes)
col_index = {
"row_number": 0,
"section_title": 1,
"ts_date": 2,
"qanon_title": 3,
"code_state": 4,
"code_label": 5,
"qanon_id": 6,
"section_id": 7,
"state_match": 8,
}
#-------------------------------------
#----- پشتیبان گیری از داده های جدید داتیک
run_codes_to_elastic_directory( elastic, "./data/tcodes/corrected_majles/not_edit2", "./data/tcodes/corrected_majles/not_edit2/result", all_codes, False, True, col_index, False)
run_codes_extract_directory("./data/tcodes/corrected_majles/not_edit2/result","./data/tcodes/corrected_majles/not_edit2/result_json",all_codes,col_index,True)
# -------------------------------------
# ----- پشتیبان گیری از داده های جدید داتیک
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_rg_section_temp", "mj_rg_section_doctic_14040824")
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_section_temp", "mj_qa_section_doctic_14040824")
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_opinion_temp", "mj_qa_opinion_doctic_14040824")
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon_temp", "mj_qa_qanon_doctic_14040824")
#-------------------------------------
#----- ترمیم داده های تاریخ ایندکس قبلی
# -------------------------------------
# ----- ترمیم داده های تاریخ ایندکس قبلی
# -- qaqanon
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_qanon")
# file_path = 'G:/Project2/111/mj_qa_qanon.zip'
file_path = 'G:/Project2/160_dotic/mj_qa_qanon_112.zip'
file_path = "G:/Project2/160_dotic/mj_qa_qanon_112.zip"
index_name = "mj_qa_qanon"
elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
# restore_correct_data_to_elastic(elastic, file_path, index_name )
elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_112.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
#-------------------------------------
#-------------------------------------
#-- حذف مقرره های قبلی
body = {
"query": {
"term": {
"main_type": {
"value": "مقرره"
}
}
}
}
# elastic.deleteByQueryIndex("mj_qa_qanon", body)
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_base")
#-------------------------------------
#----- موقتی برای تستهای از این مرحله به بعد یه پشتیبان تمیز باشه ...
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_base.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
###### اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
# restore_correct_date_to_elastic(elastic, file_path, index_name, "G:/Project2/160_dotic/date_log_error_qaqanon.txt" )
# -------------------------------------
# -------------------------------------
# -- حذف مقرره های قبلی
body = {"query": {"term": {"main_type": {"value": "مقرره"}}}}
# elastic.deleteByQueryIndex("mj_qa_qanon", body)
# -------------------------------------
# ----- موقتی برای تستهای از این مرحله به بعد یه پشتیبان تمیز باشه ...
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_base")
# -------------------------------------
# import_data_new_qaqanon(elastic, "G:/Project2/160_dotic/mj_qa_qanon_doctic_14040824.zip")
#-------------------------------------
#-------------------------------------
#-------------------------------------
# ----- موقتی برای تستهای از این مرحله به بعد یه پشتیبان تمیز باشه ...
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_base_dotic")
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_base_dotic.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
# file_excel = "G:\Project2\NLP\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
# import_excel_before_to_elastic(elastic, file_excel, "mj_qa_qanon")
# -------------------------------------
# -------------------------------------
# -------------------------------------
file_before = "G:/Project2/160_dotic/duplicate_before.json"
file_after = "G:/Project2/160_dotic/duplicate_after.json"
file_tasmim = "G:/Project2/160_dotic/duplicate_tasmim.json"
# file_excel = "G:\Project2\NLP\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
# import_excel_after_to_elastic(elastic, file_excel, "mj_qa_qanon")
# #------------------------------------------
# duplicate_list = {}
# file_excel = r"G:\Project2\NLP\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
# import_excel_before_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list)
# with open(file_before, 'w', encoding='utf8') as f :
# json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# file_excel = "G:\Project2\NLP\dataParsers\data\qavanin_files\فهرست تصمیمات قانونی.elsx"
# import_excel_tasmimat_to_elastic(elastic, file_excel, "mj_qa_qanon")
# # #------------------------------------------
# duplicate_list = {}
# with open(file_before, 'r', encoding='utf8') as f :
# duplicate_list = json.loads( f.read())
# file_excel = r"G:\Project2\NLP\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
# import_excel_after_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list)
# with open(file_after, 'w', encoding='utf8') as f :
# json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# # #------------------------------------------
# duplicate_list = {}
# with open(file_after, 'r', encoding='utf8') as f :
# duplicate_list = json.loads( f.read())
# file_excel = r"G:\Project2\NLP\dataParsers\data\qavanin_files\فهرست تصمیمات قانونی.xlsx"
# import_excel_tasmimat_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list)
# with open(file_tasmim, 'w', encoding='utf8') as f :
# json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# ----- موقتی برای تستهای از این مرحله به بعد یه پشتیبان تمیز باشه ...
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_base_excel")
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_base_excel.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
# -------------------------------------
# ----- انتقال داده های آراء به
# -- qaqanon
# file_path = 'G:/Project2/160_dotic/mj_qa_opinion_doctic_14040824.zip'
# index_name = "mj_qa_qanon"
#### بخاطر لزوم تغییر روش کار، لازم شد محتوای آراء به اینجا منتفل شود
#### البته بقیه فراداده قبلا منتقل شده بودند
# import_content_opinion_to_qaqanon(elastic, file_path, index_name )
# -------------------------------------
# ---- اصلاح تاریخهای اجزاء طبق ساختار جدید date
# -- qasection
#### ------>> expire_date, ts_date, ref_state.qanon_date, ref_state.effect_date
file_path = "G:/Project2/160_dotic/mj_qa_section_doctic_14040824.zip"
# elastic.createIndex( 'mj_qa_section', 'majles', 'mj_qa_section')
###### اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
# restore_correct_date_to_elastic(elastic, file_path, "mj_qa_section", "G:/Project2/160_dotic/date_log_error_qasection.txt" )
# ---- اصلاح تاریخهای اجزاء طبق ساختار جدید date
# -- rgsection
file_path = "G:/Project2/160_dotic/mj_rg_section_doctic_14040824.zip"
# elastic.createIndex( 'mj_rg_section', 'majles', 'mj_rg_section')
##### اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
# restore_correct_date_to_elastic(elastic, file_path, "mj_rg_section", "G:/Project2/160_dotic/date_log_error_rgsection.txt" )
# .....
# --------------
# ---- تذکر فرانت و بک
# -- اصلاح ساختار اسکیما نماش و تغییرات برای ساختار تاریخ تغییر یافته و تست و بررسی
# .....
# .....
# ------------------------------------
# ------------------------------------
# بررسی پر بودن main_type مجلس برای نوع اصلی/تبعی/مهذب
# و تغییر به mom_type
# 'key' => 'mom_type',
# 'label' => 'نوع اصلی/تبعی/مهذب',