refactor codes and names

This commit is contained in:
hsafaei
2026-02-12 11:19:58 +03:30
parent 56084b0c8e
commit 9c99d816db
25 changed files with 395 additions and 2360 deletions
@@ -1,373 +0,0 @@
import numbers
import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch, helpers
import json
import re
import zipfile
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from ..common.text_normalizer import TextNormalizer
# from general import *
from ..common.general_functions import *
from ..common.elastic_helper import ElasticHelper
text_normal = TextNormalizer()
def validate_value(value):
if pd.isna(value):
return ""
value = str(value)
if value is None or ".." in value:
return ""
temp = value.replace("0", "")
if not temp:
return ""
return value.strip(" \n")
# اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
def correct_qanon_date_json(data, error_list):
data_new = []
for item in data:
id = item["_id"]
# یکبار فقط نیاز بود
id = str(id).replace('mj_mashruh_', 'mh')
item["_id"] = id
item["_source"]["id"] = id
item["_source"] = repair_object_persian_date(
item["_source"], "ts_date", error_list, id, ""
)
#--> mj_mashruh
if "meet_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "meet_date", error_list, id, ""
)
if "exec_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "exec_date", error_list, id, ""
)
if "expire_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "expire_date", error_list, id, ""
)
if "date_edit" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "date_edit", error_list, id, ""
)
if "fixed_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "fixed_date", error_list, id, ""
)
if "renewal_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "renewal_date", error_list, id, ""
)
if "eblagh" in item["_source"]:
item["_source"]["eblagh"] = repair_object_persian_date(
item["_source"]["eblagh"], "date", error_list, id, "eblagh"
)
if "rrk" in item["_source"]:
item["_source"]["rrk"] = repair_object_persian_date(
item["_source"]["rrk"], "date", error_list, id, "rrk"
)
if "ref_state" in item["_source"]:
ref_state=[]
for ref_item in item["_source"]["ref_state"] :
ref_item_new = repair_object_persian_date(ref_item, "qanon_date", error_list, id, "ref_state")
ref_item_new = repair_object_persian_date(ref_item_new, "effect_date", error_list, id, "ref_state")
ref_state.append(ref_item_new)
item["_source"]["ref_state"]=ref_state
data_new.append(item)
return data_new
def normal_mashruh_data_json(data):
data_new = []
for item in data:
id = item["_id"]
if 'content' in item["_source"] :
item["_source"]['content'] = text_normal.normalize_qanon(item["_source"]['content'])
if 'majles_name' in item["_source"] :
item["_source"]['majles_name'] = text_normal.normalize_qanon(item["_source"]['majles_name'])
if 'title' in item["_source"] :
item["_source"]['title'] = text_normal.normalize_qanon(item["_source"]['title'])
if 'content_type' in item["_source"] :
item["_source"]['content_type'] = text_normal.normalize_qanon(item["_source"]['content_type']).strip()
if 'title_type' in item["_source"] :
item["_source"]['title_type'] = text_normal.normalize_qanon(item["_source"]['title_type']).strip()
if "talker" in item["_source"]:
talker = item["_source"]["talker"]
if 'organ' in talker :
talker['organ'] = text_normal.normalize_qanon(talker['organ'])
if 'semat' in talker :
talker['semat'] = text_normal.normalize_qanon(talker['semat'])
if 'name' in talker :
talker['name'] = text_normal.normalize_qanon(talker['name'])
item["_source"]["talker"]=talker
data_new.append(item)
return data_new
# اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
def restore_correct_date_to_elastic(elastic, file_path, index_name, file_error=''):
error_list = []
fileNo = 0
with zipfile.ZipFile(file_path, "r") as zObject:
fileNo += 1
packNo = 0
counter = 0
for filename in zObject.namelist():
packNo += 1
print("index:", index_name, "=>", filename)
data = []
with zObject.open(filename) as file:
data = json.loads(file.read())
data_new = correct_qanon_date_json(data, error_list)
if index_name == 'mj_mashruh' :
data_new = normal_mashruh_data_json(data_new)
elastic.importJsonDataToElastic(data_new, index_name, [], True)
counter += len(data)
# print('-'*10, 'len()', str(counter) + '/ ' + str(len(data)) + ' , ' +str(len(data_new)) )
elastic.es.indices.refresh(index=index_name)
print(elastic.es.cat.count(index=index_name, format="json"))
file_log_error = file_error
if not file_error :
file_log_error = "G:/Project2/160_dotic/date_log_error.txt"
with open(file_log_error, "w", encoding="utf8") as f:
json.dump(error_list, f, ensure_ascii=False, indent=4)
def import_data_new_qaqanon(elastic, path_file):
jsonData = []
count = 0
id = ""
try:
try:
list_ = elastic.iterateJsonFile(path_file, True)
except Exception as e:
print("Exception es_iterate_all_documents : " + str(e))
print("*" * 20, " count=", elastic.total)
for mentry in list(list_):
count += 1
entry = mentry["source"]
id = entry.get("id", "")
main_type = entry.get("main_type", "")
# قانونها را نباید بروزرسانی کنیم ...چون از طرف مجلس تغییرات شناسانامه در ایندکس داشته است
if main_type == "قانون":
continue
jsonData.append({"_id": id, "_source": entry})
except Exception as e:
print("Exception: " + str(e))
error_list = []
jsonData_new = correct_qanon_date_json(jsonData, error_list)
pack_size = 1000
bulk = []
total = len(jsonData_new)
count = 0
for item in jsonData_new:
bulk.append(item)
if len(bulk) >= pack_size:
count += len(bulk)
elastic.importJsonDataToElastic(bulk, "mj_qa_qanon", [], True)
print(" count update ", str(count), "/", str(total))
bulk = []
if len(bulk):
count += len(bulk)
elastic.importJsonDataToElastic(bulk, "mj_qa_qanon", [], True)
print(" count update ", str(count), "/", str(total))
bulk = []
def import_content_opinion_to_qaqanon(elastic, path_file, index_name_o):
bulk_list = []
bulk_list_import = []
pack_size = 100
count = 0
id = ""
try:
try:
list_ = elastic.iterateJsonFile(path_file, True)
except Exception as e:
print("Exception es_iterate_all_documents : " + str(e))
list_items = list(list_)
total = elastic.total
print("*" * 20, " count=", elastic.total)
total_count = 0
for mentry in list_items:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
qanon_id = entry.get("qanon_id", "")
eid = qanon_id
ref_id = entry.get("ref_id", "")
ref_key = entry.get("ref_key", "")
title_popular = entry.get("title_popular", "")
title = entry.get("title", "")
title_type = entry.get("title_type", "")
ts_year = entry.get("ts_year", "")
ts_ref = entry.get("ts_ref", "")
sub_type = entry.get("sub_type", "")
qanon_etebar = entry.get("qanon_etebar", "")
sort_date_timestamp = entry.get("sort_date_timestamp", "")
ts_date = entry.get("ts_date", "")
ts_date, err_msg = convert_persian_date(ts_date)
expire_date = entry.get("expire_date", "")
expire_date, err_msg = convert_persian_date(expire_date)
aproveDate = entry.get("aproveDate", "")
aproveDate, err_msg = convert_persian_date(aproveDate)
content = entry.get("content", "")
content = text_normal.normalize_qanon(content)
html = entry.get("html", "")
html = text_normal.yeke_normal(html)
content_len = entry.get("content_len", "")
eblagh_number = validate_value(entry.get("eblagh_number", ""))
eblagh_date = entry.get("eblagh_date", "")
eblagh_date, err_msg = convert_persian_date(eblagh_date)
eblagh = {}
if eblagh_number or eblagh_date:
eblagh["number"] = eblagh_number
if eblagh_date:
eblagh["date"] = eblagh_date
item = {}
is_update = True
try:
item = elastic.get_document(index_name_o, eid)
except:
is_update = False
data = {}
if not is_update:
main_type = "آراء"
data = {
"id": eid,
"ref_id": ref_id,
"ref_key": ref_key,
"main_type": main_type,
"sub_type": sub_type,
"title": title,
"ts_year": ts_year,
"ts_ref": ts_ref,
"qanon_etebar": qanon_etebar,
"sort_date_timestamp": sort_date_timestamp, # created from repairQanon.getSortTimestamp
}
if title_type:
data["title_type"] = title_type
if title_popular:
data["title_popular"] = title_popular
if ts_date:
data["ts_date"] = ts_date
if expire_date:
data["expire_date"] = expire_date
if aproveDate:
data["exec_date"] = aproveDate
if html: # ساختن دوباره و بهتر
content = html_to_text_preserve_lines(html)
content_len = len(content)
data["content"] = content
if html and isNeedHtml(html):
data["html"] = html
data["content_len"] = content_len
if eblagh:
data["eblagh"] = eblagh
if is_update:
bulk_list.append({"_id": eid, "_source": data})
else:
bulk_list_import.append({"_id": eid, "_source": data})
if len(bulk_list) >= pack_size:
total_count += len(bulk_list)
elastic.updateBulkList(bulk_list, index_name_o, True)
print(
" count update ", str(count), "/", str(total_count), "/", str(total)
)
bulk_list = []
if len(bulk_list_import) >= pack_size:
total_count += len(bulk_list_import)
elastic.importBulkList(bulk_list_import, index_name_o, True)
print(
" count import ", str(count), "/", str(total_count), "/", str(total)
)
bulk_list_import = []
if len(bulk_list):
total_count += len(bulk_list)
elastic.updateBulkList(bulk_list, index_name_o, True)
print(" count update ", str(count), "/", str(total_count), "/", str(total))
bulk_list = []
if len(bulk_list_import):
total_count += len(bulk_list_import)
elastic.importBulkList(bulk_list_import, index_name_o, True)
print(" count import ", str(count), "/", str(total_count), "/", str(total))
bulk_list_import = []
except Exception as e:
print("Exception: " + str(e))
@@ -459,5 +459,9 @@ def main_proccess():
### --------------------------------------
### استخراج فایلهای مرتبط با هر قانون در اکسل خروجی
### qavanin_output4.xlsx
### --------------------------------------
if __name__ == "__main__":
main_proccess()
@@ -45,7 +45,7 @@ def validate_id(value) :
value = value.split('?')[0]
return value
#### ارسال اطلاعات از اکسل قبل انقلاب به ایندکس الاستیک mj_qa_qanon
def import_excel_before_to_elastic(elastic, path_file, index_name_o, duplicate_list):
bulk_data_import=[]
bulk_data_update=[]
@@ -315,7 +315,7 @@ def import_excel_before_to_elastic(elastic, path_file, index_name_o, duplicate_l
traceback.print_exc()
#### ارسال اطلاعات از اکسل بعد انقلاب به ایندکس الاستیک mj_qa_qanon
def import_excel_after_to_elastic(elastic, path_file, index_name_o, duplicate_list):
bulk_data_import=[]
bulk_data_update=[]
@@ -551,7 +551,7 @@ def import_excel_after_to_elastic(elastic, path_file, index_name_o, duplicate_li
traceback.print_exc()
#### ارسال تصمیمات قانونی از اکسل قبل انقلاب به ایندکس الاستیک mj_qa_qanon
def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o, duplicate_list ):
error_list = []
bulk_data_import=[]