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
@@ -4,17 +4,19 @@ import re
from tqdm import tqdm
import unicodedata
import logging
import uuid
import traceback
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from ..common.text_normalizer import TextNormalizer
from app.common.text_normalizer import TextNormalizer
# from general import *
from ..common.general_functions import *
from ..common.elastic_helper import ElasticHelper
from app.common.general_functions import *
from app.common.elastic_helper import ElasticHelper
# ---------------------------------------------
# قبل انقلاب
@@ -27,12 +29,29 @@ from ..common.elastic_helper import ElasticHelper
# خواندن اطلاعات اکسل و درج در qaqanon
# برای تصمیمات قانونی، خواندن اکسل مخصوص و درج در qaqanon
# ---------------------------------------------
def validate_value(value) :
if pd.isna(value) :
return ''
def import_excel_before_to_elastic(elastic, path_file, index_name_o):
value = str(value)
if value is None or '..' in value :
return ''
return value.strip(" \n")
def validate_id(value) :
value = validate_value(value)
# qq112475?ls=list
value = value.split('?')[0]
return value
def import_excel_before_to_elastic(elastic, path_file, index_name_o, duplicate_list):
bulk_data_import=[]
bulk_data_update=[]
total_count = 0
count = 0
dict_id = {}
id = ""
try:
@@ -79,65 +98,62 @@ def import_excel_before_to_elastic(elastic, path_file, index_name_o):
count += 1
error_files_state = item.get("مدیریت خطا", "")
title = item.get("عنوان", "")
title = item.get("عنوان", "").strip(" \n")
title = text_normalizer.normalize_qanon(title)
sub_type = item.get("نوع", "")
sub_type = validate_value(sub_type)
sub_type = text_normalizer.normalize_qanon(sub_type)
_id = item.get("_id", "")
_id = validate_id(item.get("_id", ""))
davam_type = ''
eid = _id
number_all = item.get("شماره کلی", "")
number_row_duplicate = item.get("شماره ردیف با احتساب مکرر", "")
number_row_duplicate = number_row_duplicate if not '..' in number_row_duplicate else ''
number_row_duplicate = str(item.get("شماره ردیف با احتساب مکرر", ""))
number_row_duplicate = validate_value(number_row_duplicate)
number_row = item.get("شماره پرونده و ردیف ", "")
number_row = number_row if not '..' in number_row else ''
number_row=validate_value(number_row)
number_lib_folder = item.get("شماره فولدر کتابخانه", "")
number_lib_folder = number_lib_folder if not '..' in number_lib_folder else ''
number_lib_folder=validate_value(number_lib_folder)
number_sena = item.get("شماره پرونده سنا", "")
number_sena = number_sena if not '..' in number_sena else ''
number_sena=validate_value(number_sena)
description = item.get("توضیحات", "")
description = text_normalizer.normalize_qanon(description)
term = item.get("دوره قانونگذاری", "") # ???? term
term = text_normalizer.normalize_qanon(term)
term = term if not '..' in term else ''
ts_date_dotic = item.get("تاریخ تصویب در dotic ", "")
if not is_match_persian_date_format(ts_date_dotic):
ts_date_dotic = ''
term=validate_value(term)
ts_date_dotic = item.get("تاریخ تصویب در dotic ", "")
ts_date_dotic, err_msg = convert_persian_date(ts_date_dotic)
ts_date1 = item.get("تاريخ‌تصويب 1", "")
if not is_match_persian_date_format(ts_date1):
ts_date1 = ''
ts_date1, err_msg = convert_persian_date(ts_date1)
ts_ref1 = item.get("مرجع تصويب ", "") # ????? ts_ref
ts_ref1 = text_normalizer.normalize_qanon(ts_ref1)
ts_ref1 = ts_ref1 if not '..' in ts_ref1 else ''
ts_ref1 = validate_value(ts_ref1)
ts_date2 = item.get("تاریخ تصویب 2", "")
if not is_match_persian_date_format(ts_date2):
ts_date2 = ''
ts_date2, err_msg = convert_persian_date(ts_date2)
ts_ref2 = item.get("مرجع تصویب 2", "")
ts_ref2 = text_normalizer.normalize_qanon(ts_ref2)
ts_ref2 = ts_ref2 if not '..' in ts_ref2 else ''
ts_ref2 = validate_value(ts_ref2)
qanon_etebar = item.get("وضعيت", "")
qanon_etebar = text_normalizer.normalize_qanon(qanon_etebar)
qanon_etebar = qanon_etebar if not '..' in qanon_etebar else ''
qanon_etebar = validate_value(qanon_etebar)
path_folder = item.get("مسیر", "")
name_files = item.get("فایلها", "")
path_folder = validate_value(item.get("مسیر", ""))
name_files = validate_value(item.get("فایلها", ""))
# title = item.get("شماره پرونده های مرتبط", "") # فیلد معادل ندارد
# title = item.get("اصلی/تبعی", "") # فیلد معادل ندارد
@@ -156,24 +172,39 @@ def import_excel_before_to_elastic(elastic, path_file, index_name_o):
main_type = 'تصمیم قانونی'
else :
sub_type='بودجه'
else:
print('.#'*10,'error subtype , ', count)
elif not sub_type :
sub_type = 'عادی'
is_update = True
if not _id.startswith('qq') :
if not _id or not _id.startswith('qq') :
eid = 0
is_update= False
if sub_type =='تصمیم قانونی' :
eid='qt_'+ uuid.uuid4().hex[:8]
else :
eid='qe_'+ uuid.uuid4().hex[:8]
eid='qe_'+ uuid.uuid4().hex[:8]
sub_type='نامشخص'
if _id=='قانون جدید - موقت' :
davam_type='موقت'
sub_type='عادی'
files_info=[]
number = {}
if number_all :
number["all"] = number_all
if number_row_duplicate :
number["row_duplicate"] = number_row_duplicate
if number_row :
number["row"] = number_row
if number_lib_folder :
number["lib_folder"] = number_lib_folder
if number_sena :
number["sena"] = number_sena
files_info=[]
for name in name_files.split(','):
if not name :
continue
@@ -201,70 +232,96 @@ def import_excel_before_to_elastic(elastic, path_file, index_name_o):
"main_type": main_type,
"sub_type": sub_type,
"term": term,
"qanon_etebar": qanon_etebar,
"davam_type": davam_type,
"ts_date_dotic": ts_date_dotic,
"ts_date1": ts_date1,
"ts_ref1": ts_ref1,
"ts_date2": ts_date2,
"ts_ref2": ts_ref2,
"description": description,
"files": files_info,
"number" :{
"all" : number_all,
"row_duplicate" : number_row_duplicate,
"row" : number_row,
"lib_folder" : number_lib_folder,
"sena" : number_sena
}
}
if qanon_etebar :
data["qanon_etebar"] = qanon_etebar
if files_info :
data["files"] = files_info
if number :
data["number"] = number
if ts_ref1 :
data["ts_ref1"] = ts_ref1
data["ts_ref"] = ts_ref1
if ts_date_dotic :
data["ts_date_dotic"] = ts_date_dotic
if ts_date1 :
data["ts_date1"] = ts_date1
data["ts_date"] = ts_date1
data["sort_date_timestamp"] = dateTimestamp(ts_date1)
if ts_date2 :
data["ts_date2"] = ts_date2
if eid in duplicate_list :
duplicate_list[eid]["duplicate1"] = { "excel":"before", "row2": str(count), "is_update_row2": is_update}
continue
if eid in dict_id :
duplicate_list[eid] = { "excel":"before", "type_duplicate":"inner", "id":eid, "row1": dict_id[eid], "row2": str(count), "is_update_row2": is_update}
continue
dict_id[eid] = str(count)
if is_update :
bulk_data_update.append({
"_id": id,
"_id": eid,
"_source": data
})
else :
bulk_data_import.append({
"_id": id,
"_id": eid,
"_source": data
})
})
if len(bulk_data_update) >= 100:
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data_update, index_name_o)
elastic.updateBulkList(bulk_data_update, index_name_o, True)
bulk_data_update = []
if len(bulk_data_import) >= 100:
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
elastic.importBulkList(bulk_data_import, index_name_o, True)
bulk_data_import = []
if len(bulk_data_update):
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data_update, index_name_o)
elastic.updateBulkList(bulk_data_update, index_name_o, True)
bulk_data_update = []
if len(bulk_data_import):
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
bulk_data_import = []
elastic.importBulkList(bulk_data_import, index_name_o, True)
bulk_data_import = []
elastic.es.indices.refresh(index=index_name_o)
print(elastic.es.cat.count(index=index_name_o, format="json"))
except Exception as e:
print("Exception: " + str(e))
traceback.print_exc()
def import_excel_after_to_elastic(elastic, path_file, index_name_o):
def import_excel_after_to_elastic(elastic, path_file, index_name_o, duplicate_list):
bulk_data_import=[]
bulk_data_update=[]
total_count = 0
count = 0
dict_id={}
id = ""
try:
@@ -306,52 +363,46 @@ def import_excel_after_to_elastic(elastic, path_file, index_name_o):
count += 1
error_files_state = item.get("مدیریت خطا", "")
title = item.get("عنوان", "")
title = text_normalizer.normalize_qanon(tile)
_id = item.get("_id", "")
title = item.get("عنوان", "").strip(" \n")
title = text_normalizer.normalize_qanon(title)
_id = validate_id(item.get("_id", ""))
davam_type = ''
eid = _id
number_all = item.get("شماره عمومی", "")
number_row_duplicate = item.get("شماره ردیف", "")
number_row = item.get("شماره پرونده ", "")
ts_date = item.get("تاريخ‌تصويب", "")
if not is_match_persian_date_format(ts_date):
ts_date = ''
number_all = validate_value(item.get("شماره عمومی", ""))
number_row_duplicate = validate_value(item.get("شماره ردیف", ""))
number_row = validate_value(item.get("شماره پرونده ", ""))
ts_date = validate_value(item.get("تاريخ‌تصويب", ""))
ts_date, err_msg = convert_persian_date(ts_date)
ts_ref = item.get("مرجع تصويب", "") # ????? ts_ref
ts_ref = validate_value(item.get("مرجع تصويب", "")) # ????? ts_ref
ts_ref = text_normalizer.normalize_qanon(ts_ref)
shora_date = item.get("تاریخ تایید", "")
if not is_match_persian_date_format(shora_date):
shora_date = ''
shora_date = validate_value(item.get("تاریخ تایید", ""))
shora_date, err_msg = convert_persian_date(shora_date)
exec_date = item.get("تاریخ لازم الاجرا شدن", "")
if not is_match_persian_date_format(exec_date):
exec_date = ''
exec_date, err_msg = convert_persian_date(exec_date)
rrk_number = item.get("شماره روزنامه رسمی کشور", "")
rrk_number = rrk_number if not '..' in rrk_number else ''
rrk_number = validate_value(item.get("شماره روزنامه رسمی کشور", ""))
rrk_date = item.get("تاریخ انتشار روزنامه رسمی کشور", "")
if not is_match_persian_date_format(rrk_date):
rrk_date = ''
rrk_date, err_msg = convert_persian_date(rrk_date)
number_qanon = item.get("شماره شناسه قانون", "")
# number_qanon = item.get("شماره شناسه قانون", "") ? ////?????
description = item.get("مستندات", "")
description = text_normalizer.normalize_qanon(description)
term = item.get("دوره قانونگذاری", "") # ???? term
term = validate_value(item.get("دوره قانونگذاری", "")) # ???? term
term = text_normalizer.normalize_qanon(term)
term = term if not '..' in term else ''
qanon_etebar = item.get("وضعيت", "")
qanon_etebar = validate_value(item.get("وضعيت", ""))
qanon_etebar = text_normalizer.normalize_qanon(qanon_etebar)
path_folder = item.get("مسیر", "")
name_files = item.get("فایلها", "")
path_folder = validate_value(item.get("مسیر", ""))
name_files = validate_value(item.get("فایلها", ""))
# title = item.get("شماره پرونده های مرتبط", "") # فیلد معادل ندارد - تبعی های مرتبط و مثل این منظورهست که خودکار پر میشود یا سامانه می دهد
# title = item.get("اصلی/تبعی", "") # فیلد معادل ندارد
@@ -361,6 +412,15 @@ def import_excel_after_to_elastic(elastic, path_file, index_name_o):
main_type='قانون'
sub_type = 'عادی'
number = {}
if number_all :
number["all"] = number_all
if number_row_duplicate :
number["row_duplicate"] = number_row_duplicate
if number_row :
number["row"] = number_row
letters = []
if shora_date :
letters.append({
@@ -369,11 +429,14 @@ def import_excel_after_to_elastic(elastic, path_file, index_name_o):
})
if rrk_number or rrk_date :
letters.append({
r_item = {
"type" : "انتشار در روزنامه رسمی",
"number" : rrk_number,
"date" : rrk_date
})
"number" : rrk_number
}
if rrk_date :
r_item["date"] = rrk_date
letters.append(r_item)
@@ -381,7 +444,7 @@ def import_excel_after_to_elastic(elastic, path_file, index_name_o):
if not _id.startswith('qq') :
eid = 0
is_update= False
eid='qe_'+ uuid.uuid4().hex[:8]
eid='qe_'+ uuid.uuid4().hex[:8]
sub_type='نامشخص'
@@ -412,32 +475,45 @@ def import_excel_after_to_elastic(elastic, path_file, index_name_o):
"main_type": main_type,
"sub_type": sub_type,
"term": term,
"qanon_etebar": qanon_etebar,
"davam_type": davam_type,
"ts_date_dotic": ts_date_dotic,
"ts_date1": ts_date1,
"ts_ref1": ts_ref1,
"ts_date2": ts_date2,
"ts_ref2": ts_ref2,
"description": description,
"files": files_info,
"number" :{
"all" : number_all,
"row_duplicate" : number_row_duplicate,
"row" : number_row,
"lib_folder" : number_lib_folder,
"sena" : number_sena
}
"description": description
}
if qanon_etebar :
data["qanon_etebar"] = qanon_etebar
if ts_ref :
data["ts_ref"] = ts_ref
if files_info :
data["files"] = files_info
if number :
data["number"] = number
if letters :
data["letters"] = letters
if ts_date :
data["ts_date"] = ts_date
data["sort_date_timestamp"] = dateTimestamp(ts_date)
if exec_date :
data["exec_date"] = exec_date
if eid in duplicate_list :
duplicate_list[eid]["duplcate2"] = { "excel":"after", "row2": str(count), "is_update_row2": is_update}
continue
if eid in dict_id :
duplicate_list[eid] = { "excel":"after", "type_duplicate":"inner", "id":eid, "row1": dict_id[eid], "row2": str(count), "is_update_row2": is_update}
continue
dict_id[eid] = str(count)
if is_update :
bulk_data_update.append({
"_id": id,
"_id": eid,
"_source": data
})
else :
bulk_data_import.append({
"_id": id,
"_id": eid,
"_source": data
})
@@ -445,36 +521,43 @@ def import_excel_after_to_elastic(elastic, path_file, index_name_o):
if len(bulk_data_update) >= 100:
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data_update, index_name_o)
elastic.updateBulkList(bulk_data_update, index_name_o, True)
bulk_data_update = []
if len(bulk_data_import) >= 100:
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
elastic.importBulkList(bulk_data_import, index_name_o, True)
bulk_data_import = []
if len(bulk_data_update):
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data_update, index_name_o)
elastic.updateBulkList(bulk_data_update, index_name_o, True)
bulk_data_update = []
if len(bulk_data_import):
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
elastic.importBulkList(bulk_data_import, index_name_o, True)
bulk_data_import = []
elastic.es.indices.refresh(index=index_name_o)
print(elastic.es.cat.count(index=index_name_o, format="json"))
except Exception as e:
print("Exception: " + str(e))
traceback.print_exc()
def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o):
def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o, duplicate_list ):
error_list = []
bulk_data_import=[]
total_count = 0
count = 0
dict_id = {}
id = ""
try:
@@ -494,24 +577,26 @@ def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o):
for item in data:
count += 1
row = item.get("ردیف", "")
description = item.get("مستند قانونی", "")
row = validate_value(item.get("ردیف", ""))
description = validate_value(item.get("مستند قانونی", ""))
description = text_normalizer.normalize_qanon(description)
subject = item.get("موضوع", "")
subject = validate_value(item.get("موضوع", ""))
subject = text_normalizer.normalize_qanon(subject)
content = item.get("نتیجه", "")
content = validate_value(item.get("نتیجه", ""))
content = text_normalizer.normalize_qanon(content)
number = item.get("جلسه", "")
ts_date = item.get("تاریخ", "")
if not is_match_persian_date_format(ts_date):
ts_date = ''
print('.*'*10, ' error ts_date in ', row)
number = validate_value(item.get("جلسه", ""))
ts_date = validate_value(item.get("تاریخ", ""))
ts_date_f = text_normalizer.date_correction(ts_date, False)
ts_date, err_message = convert_persian_date(ts_date_f)
if not ts_date or err_message:
error_list.append({'row':row, "value":ts_date, "message": err_message })
print('.*'*10, ' error ts_date in ', err_message, ' ', ts_date, ' ', row)
continue
title = subject + ' - جلسه ' + number + ' تاریخ ' + ts_date
title = subject + ' - جلسه ' + number + ' تاریخ ' + ts_date_f
main_type='تصمیم قانونی'
ts_ref='مجلس شورای اسلامی'
@@ -520,7 +605,7 @@ def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o):
is_update = False
eid ='qt_'+ uuid.uuid4().hex[:8]
eid ='qt_'+ uuid.uuid4().hex[:8]
data = {
"id": eid,
@@ -533,9 +618,20 @@ def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o):
"description": description,
"content": content
}
data["sort_date_timestamp"] = dateTimestamp(ts_date)
if eid in duplicate_list :
duplicate_list[eid]["duplicate3"] = { "excel":"tasmim", "row2": str(count), "is_update_row2": is_update}
continue
if eid in dict_id :
duplicate_list[eid] = { "excel":"tasmim", "type_duplicate":"inner", "id":eid, "row1": dict_id[eid], "row2": str(count), "is_update_row2": is_update}
continue
dict_id[eid] = str(count)
bulk_data_import.append({
"_id": id,
"_id": eid,
"_source": data
})
@@ -543,16 +639,26 @@ def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o):
if len(bulk_data_import) >= 100:
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
elastic.importBulkList(bulk_data_import, index_name_o, True)
bulk_data_import = []
if len(bulk_data_import):
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
elastic.importBulkList(bulk_data_import, index_name_o, True)
bulk_data_import = []
elastic.es.indices.refresh(index=index_name_o)
print(elastic.es.cat.count(index=index_name_o, format="json"))
file_log_error = 'G:/Project2/160_dotic/tasmimat_log_error.txt'
with open(file_log_error, 'w', encoding='utf8') as f :
json.dump(error_list, f, ensure_ascii=False, indent=4)
except Exception as e:
print("Exception: " + str(e))
traceback.print_exc()
+265 -102
View File
@@ -8,149 +8,312 @@ 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()
text_normal = TextNormalizer()
def repair_persian_date(item, key, id, error_list, key2=''):
res = ''
path_key = key2+'.'+key if key2 else key
if key in item :
_date = item[key]
if not _date or _date == '' :
del item[key]
return item
if _date and not is_match_persian_date_format(_date):
error_list.append({'id':id, 'key': path_key, "value":_date, "message": "match_persian_date_format" })
del item[key]
return item
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"]
item["_source"] = repair_object_persian_date(
item["_source"], "ts_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 "fixed_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "fixed_date", error_list, id, ""
)
if _date :
try :
res = jdate2Gregorian(_date)
except Exception as e:
error_list.append({'id':id, 'key': path_key, "value":_date, "message": "convert persian_date" })
del item[key]
return item
if res :
item[key] = res
return item
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 correct_qanono_data_json( data, error_list ) :
data_new = []
for item in data :
id = item['_id']
item['_source'] = repair_persian_date(item['_source'], 'ts_date', id, error_list, '')
item['_source'] = repair_persian_date(item['_source'], 'exec_date', id, error_list, '')
item['_source'] = repair_persian_date(item['_source'], 'expire_date', id, error_list, '')
item['_source'] = repair_persian_date(item['_source'], 'fixed_date', id, error_list, '')
item['_source'] = repair_persian_date(item['_source'], 'renewal_date', id, error_list, '')
if 'eblagh' in item['_source'] :
item['_source']['eblagh'] = repair_persian_date(item['_source']['eblagh'], 'date', id, error_list, 'eblagh')
if 'rrk' in item['_source'] :
item['_source']['rrk'] = repair_persian_date(item['_source']['rrk'], 'date', id, error_list, 'rrk')
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
def restore_correct_data_to_elastic(elastic, file_path, index_name ) :
error_list = []
fileNo = 0
with zipfile.ZipFile(file_path, "r") as zObject:
fileNo += 1
print("index:", index_name, "=>", filename)
data = []
with zObject.open(filename) as file:
data = json.loads(file.read())
packNo = 0
counter = 0
for filename in zObject.namelist():
packNo += 1
data_new = correct_qanon_date_json(data, error_list)
elastic.importJsonDataToElastic(data_new, index_name, [], True)
counter += len(data)
# print('-'*10, 'len()', str(counter) + '/ ' + str(len(data)) + ' , ' +str(len(data_new)) )
# print("index:", index_name, "=>", filename)
data = []
with zObject.open(filename) as file:
data = json.loads(file.read())
data_new = correct_qanono_data_json(data, error_list)
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 = '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)
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=[]
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)
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 == 'قانون') :
if main_type == "قانون":
continue
jsonData.append({
"_id": id,
"_source": entry
})
jsonData.append({"_id": id, "_source": entry})
except Exception as e:
print("Exception: " + str(e))
error_list = []
jsonData_new = correct_qanono_data_json(jsonData, error_list)
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")
print( ' count update ', str(count), '/', str(total))
bulk = []
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")
print( ' count update ', str(count), '/', str(total))
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["ts_date"] = expire_date
if aproveDate:
data["ts_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))