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
+31 -4
View File
@@ -580,7 +580,7 @@ class ElasticHelper:
# - داده‌ها را به صورت bulk آپدیت می‌کند
# - از helpers.bulk Elasticsearch استفاده می‌کند
# -----------------------------end----------------------------
def updateBulkList(self, listData, index_name):
def updateBulkList(self, listData, index_name, streem_state=False):
chunk_size = 100000
raise_on_error = False
raise_on_exception = False
@@ -597,6 +597,19 @@ class ElasticHelper:
"doc": item["_source"],
}
)
if streem_state :
### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk(
self.es,
actions,
raise_on_error=False,
raise_on_exception=False,
):
if not ok:
print("Error:", result)
else :
helpers.bulk(
self.es,
actions,
@@ -617,22 +630,36 @@ class ElasticHelper:
# - داده‌ها را به صورت bulk وارد می‌کند
# - از helpers.bulk Elasticsearch استفاده می‌کند
# -----------------------------end----------------------------
def importBulkList(self, listData, index_name):
def importBulkList(self, listData, index_name, streem_state=False):
chunk_size = 100000
raise_on_error = False
raise_on_exception = False
stats_only = True
yield_ok = False
actions=[]
for item in listData:
actions = [
actions.append(
{
"_op_type": "index",
"_index": index_name,
"_id": item["_id"],
"_source": item["_source"],
}
]
)
if streem_state :
### /// برای مواردی که نیاز هست خطا فهمیده شود
for ok, result in helpers.streaming_bulk(
self.es,
actions,
raise_on_error=False,
raise_on_exception=False,
):
if not ok:
print("Error:", result)
else :
helpers.bulk(
self.es,
actions,
+109 -1
View File
@@ -5,7 +5,7 @@ import re
import sys
from re import sub
import textwrap
from html import escape
from html import escape, unescape
from bs4 import BeautifulSoup
import json
from decimal import Decimal
@@ -13,6 +13,8 @@ import traceback
# from lxml import etree
import datetime
from datetime import timedelta
import pandas as pd
#enumerate(token_list):
_normalizer = Normalizer(date_normalizing_needed=True)
@@ -62,6 +64,52 @@ def isNeedHtml(html):
else:
return False
def html_to_text_preserve_lines(html_str: str) -> str:
"""
Convert HTML -> plain text while preserving line breaks for tags like
<p>, <br>, <li>, <tr>/<td> (tables) etc.
"""
soup = BeautifulSoup(html_str, "html.parser")
# <br> -> newline
for br in soup.find_all("br"):
br.replace_with("\n")
# <p> -> ensure separated paragraphs (one blank line between paragraphs)
for p in soup.find_all("p"):
# put newline before and after paragraph content (avoid duplicate)
p.insert_before("\n")
p.append("\n")
# <li> -> prefix with "- " and newline before each item
for li in soup.find_all("li"):
li.insert_before("\n- ")
# keep li content as-is; ensure newline after
li.append("\n")
# table: make cells separated by tabs and rows end with newline
for td in soup.find_all(["td", "th"]):
# append a tab after each cell (so cells become column-separated)
td.append("\t")
for tr in soup.find_all("tr"):
tr.append("\n")
# Optional: collapse multiple consecutive whitespace-only newlines later
text = soup.get_text()
# convert HTML entities (&amp; &nbsp; etc.)
text = unescape(text)
# Normalize: convert runs of >2 newlines to max 2, strip trailing spaces on lines
text = re.sub(r'\n\s*\n\s*\n+', '\n\n', text) # 3+ newlines -> 2
text = '\n'.join(line.rstrip() for line in text.splitlines()) # rstrip each line
text = text.strip("\n ") # remove leading/trailing blanks/newlines
# convert tabs used for table cells to single spaces if you prefer:
text = text.replace("\t", " ") # or keep \t for programmatic use
return text
# erab
def remove_arabic_diacritics(text):
# Regular expression to match all Arabic diacritics
@@ -423,6 +471,20 @@ def jdate2Gregorian(text):
def dateTimestamp(gdate):
empty_date = -15000000000
ts_ts = empty_date
try:
base = datetime.datetime(1970, 1, 1)
gd = datetime.datetime.strptime(gdate, "%Y-%m-%d")
rr = (gd-base).total_seconds()
ts_ts = int( round(rr) * 1000)
except Exception as e:
ts_ts = empty_date
return ts_ts
def getSortTimestamp(ts_date):
empty_date = -15000000000
ts_ts = empty_date
@@ -1134,12 +1196,20 @@ def myTimestamp(days=0):
#////////////////////////////////////////////////////////////
#////////////////////////////////////////////////////////////
def is_match_persian_date_format(text):
#چون NaN تنها مقداری است که خودش با خودش برابر نیست
if not text or text != text : # True اگر NaN باشد:
return False
text = str(text)
if text == '0000/00/00' :
return False
if text == '00/00/00' :
return False
# items = text.split('/')
pattern = r'\d{4}/\d{1,2}/\d{1,2}'
@@ -1148,6 +1218,44 @@ def is_match_persian_date_format(text):
return False
def convert_persian_date(value):
res = ''
_date = value
if not _date or _date == '' :
return res, ''
#چون NaN تنها مقداری است که خودش با خودش برابر نیست
if _date != _date : # True اگر NaN باشد:
return res, ''
if _date and not is_match_persian_date_format(_date):
return res, "error match_persian_date_format"
if _date :
try :
res = jdate2Gregorian(_date)
except Exception as e:
return res, "error convert persian_date"
return res, ''
def repair_object_persian_date(item, key, error_list=None, id='', key2=''):
res = ''
path_key = key2+'.'+key if key2 else key
if key in item :
_date = item[key]
res, error = convert_persian_date(_date)
if not res :
if not error_list is None :
error_list.append({'id':id, 'key': path_key, "value":_date, "message": error })
del item[key]
return item
if res :
item[key] = res
return item
def excel_to_json(excel_file, required_columns=None, sheet_name=0):
"""
خواندن یک sheet از فایل اکسل و تبدیل به لیست دیکشنری.
+9 -6
View File
@@ -202,7 +202,7 @@ def get_dict_qanon_title(file_path):
return dict
def searchQanonTitleOfContent(elastic, qanon_title, ts_data="", index_name="mj_qa_section"):
def searchQanonTitleOfContent(elastic, qanon_title, ts_date="", index_name="mj_qa_section"):
score = 100
@@ -254,12 +254,12 @@ def searchQanonTitleOfContent(elastic, qanon_title, ts_data="", index_name="mj_q
if len(list_equal) == 1 :
item = list_equal[0]
score = 90
if ts_data == item['_source']['ts_date'] :
if ts_date == ts_date_ref :
score = 100
return item['_source']["qanon_id"], score, item
for item in list_equal :
if ts_data == item['_source']['ts_date'] :
if ts_date == ts_date_ref :
score = 100
return item['_source']["qanon_id"], score, item
@@ -271,7 +271,7 @@ def searchQanonTitleOfContent(elastic, qanon_title, ts_data="", index_name="mj_q
return 0, 0, {}
def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon", ts_ref=""):
def searchQanonId(elastic, qanon_title, ts_date="", index_name="mj_qa_qanon", ts_ref=""):
score = 100
body = {
"query": {
@@ -332,15 +332,18 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon", ts
if title_sample == qanon_title_sample or title_sample == qanon_title_sample2:
list_equal.append(item)
ts_date_ref = ''
if 'ts_date' in item['_source'] :
ts_date_ref = item['_source']['ts_date']
if len(list_equal) == 1 :
item = list_equal[0]
score = 90
if ts_data == item['_source']['ts_date'] :
if ts_date == ts_date_ref :
score = 100
return item["_id"], score, item
for item in list_equal :
if ts_data and ts_data == item['_source']['ts_date'] :
if ts_date and ts_date == ts_date_ref :
score = 100
return item["_id"], score, item
+19 -5
View File
@@ -58,6 +58,10 @@ class TextNormalizer:
if not text:
return ""
#چون NaN تنها مقداری است که خودش با خودش برابر نیست
if text != text : # True اگر NaN باشد:
return ""
text = text.strip()
# اصلاح خطاهای متن در کد خط
@@ -315,7 +319,7 @@ class TextNormalizer:
return text
def date_correction(self, text):
def date_correction(self, text, day_to_year=True):
text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1/\2/\3", text)
text = re.sub(r"(\d+?)ر(\d+?)", r"\1/\2", text)
@@ -326,11 +330,21 @@ class TextNormalizer:
# # فرمت YYYY/MM/DD یا YYYY-MM-DD --> YYYY/MM/DD
# text = re.sub(r'(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})', r'\1/\2/\3', text)
if not day_to_year :
# فرمت DD/MM/YYYY یا DD-MM-YYYY ---> YYYY/MM/DD
text = re.sub(r"(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})", r"\3/\2/\1", text)
text = re.sub(r" (\d{1})[\/\-](\d{1})[\/\-](\d{4})", r" 0\1/0\2/\3", text)
text = re.sub(r" (\d{1})[\/\-](\d{2})[\/\-](\d{4})", r" 0\1/\2/\3", text)
text = re.sub(r" (\d{2})[\/\-](\d{1})[\/\-](\d{4})", r" \1/0\2/\3", text)
text = re.sub(r"^(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})", r"\1/\2/\3", text)
text = re.sub(r"^(\d{2})[\/\-](\d{2})[\/\-](\d{4})", r"\3/\2/\1", text)
text = re.sub(r"^(\d{1})[\/\-](\d{1})[\/\-](\d{4})", r"\3/0\2/0\1", text)
text = re.sub(r"^(\d{1})[\/\-](\d{2})[\/\-](\d{4})", r"\3/\2/0\1", text)
text = re.sub(r"^(\d{2})[\/\-](\d{1})[\/\-](\d{4})", r"\3/0\2/\1", text)
else :
# فرمت DD/MM/YYYY یا DD-MM-YYYY ---> YYYY/MM/DD
text = re.sub(r"^(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})", r"\3/\2/\1", text)
text = re.sub(r"^(\d{2})[\/\-](\d{2})[\/\-](\d{4})", r"\1/\2/\3", text)
text = re.sub(r"^(\d{1})[\/\-](\d{1})[\/\-](\d{4})", r"0\1/0\2/\3", text)
text = re.sub(r"^(\d{1})[\/\-](\d{2})[\/\-](\d{4})", r"0\1/\2/\3", text)
text = re.sub(r"^(\d{2})[\/\-](\d{1})[\/\-](\d{4})", r"\1/0\2/\3", text)
return text
def space_correction(self, text):
+102 -46
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):
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):
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 = []
@@ -462,14 +499,15 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, file_lo
try:
for row in rows_list:
section_title = row[column_names[0]]
ts_date = row[column_names[1]]
qanon_title = row[column_names[2]]
code_state = row[column_names[3]]
row_number = row[column_names[4]]
qanon_id = row[column_names[5]]
section_id = row[column_names[6]]
state_match = row[column_names[7]]
section_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"]]
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):
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)
df = pd.read_excel(file_excel, sheet_name=0)
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,11 +667,24 @@ 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))]
@@ -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)
+176 -75
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.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"}}
]
}
},
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": [
"اصلی",
"تبعی"
]
}
}
,
"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)
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' => 'نوع اصلی/تبعی/مهذب',
@@ -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 ''
term=validate_value(term)
ts_date_dotic = item.get("تاریخ تصویب در dotic ", "")
if not is_match_persian_date_format(ts_date_dotic):
ts_date_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,11 +172,11 @@ 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 =='تصمیم قانونی' :
@@ -173,7 +189,22 @@ def import_excel_before_to_elastic(elastic, path_file, index_name_o):
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
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)
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("شماره پرونده ", "")
number_all = validate_value(item.get("شماره عمومی", ""))
number_row_duplicate = validate_value(item.get("شماره ردیف", ""))
number_row = validate_value(item.get("شماره پرونده ", ""))
ts_date = item.get("تاريخ‌تصويب", "")
if not is_match_persian_date_format(ts_date):
ts_date = ''
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 = ''
exec_date = item.get("تاریخ لازم الاجرا شدن", "")
if not is_match_persian_date_format(exec_date):
exec_date = ''
shora_date = validate_value(item.get("تاریخ تایید", ""))
shora_date, err_msg = convert_persian_date(shora_date)
rrk_number = item.get("شماره روزنامه رسمی کشور", "")
rrk_number = rrk_number if not '..' in rrk_number else ''
exec_date = item.get("تاریخ لازم الاجرا شدن", "")
exec_date, err_msg = convert_persian_date(exec_date)
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)
@@ -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='مجلس شورای اسلامی'
@@ -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()
+224 -61
View File
@@ -8,67 +8,84 @@ 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
def validate_value(value):
if pd.isna(value):
return ""
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
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
value = str(value)
if value is None or ".." in value:
return ""
temp = value.replace("0", "")
if not temp:
return ""
return value.strip(" \n")
def correct_qanono_data_json( data, error_list ) :
# اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
def correct_qanon_date_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, '')
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 "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
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
def restore_correct_data_to_elastic(elastic, file_path, index_name ) :
# اصلاح تاریخ فارسی به ذخیره سازی استاندارد 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:
@@ -79,29 +96,28 @@ def restore_correct_data_to_elastic(elastic, file_path, index_name ) :
for filename in zObject.namelist():
packNo += 1
# print("index:", index_name, "=>", filename)
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)
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)) )
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 :
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:
@@ -111,7 +127,7 @@ def import_data_new_qaqanon(elastic, path_file):
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
@@ -121,19 +137,16 @@ def import_data_new_qaqanon(elastic, path_file):
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)
jsonData_new = correct_qanon_date_json(jsonData, error_list)
pack_size = 1000
bulk = []
@@ -141,16 +154,166 @@ def import_data_new_qaqanon(elastic, path_file):
count = 0
for item in jsonData_new:
bulk.append(item)
if len(bulk) >= pack_size :
if len(bulk) >= pack_size:
count += len(bulk)
elastic.importJsonDataToElastic(bulk, "mj_qa_qanon")
print( ' count update ', str(count), '/', str(total))
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))
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))