refactor 2
This commit is contained in:
@@ -0,0 +1,588 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import json
|
||||
import requests
|
||||
import pyodbc
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
import time
|
||||
from common.config_base import *
|
||||
from common.general_functions import *
|
||||
from common.text_normalizer import TextNormalizer
|
||||
from common.elastic_helper import ElasticHelper
|
||||
|
||||
##--------------------------------
|
||||
# بخاطر خطایی که در تبدیل داده به الاستیک برای مواردی که حرف کشیده به جای خط تیر استفاده شده بود، ایجاد شد
|
||||
# و این داده به مجلس ارسال شد و کارمندان مجلس هم در داده قانون تغییراتی ایجاد کردند
|
||||
# لازم شد داده مجلس گرفته شود و اصلاح با احتیاط انجام شود تا تغییرات مجلس نیز حفظ شود
|
||||
# طبیعتا دیگر نیاز به اجرای این برنامه نخواهد بود
|
||||
##------------------------------------
|
||||
|
||||
# cursor, cnxn = create_cursor()
|
||||
|
||||
def extract_all_effecteds(elastic, index_name, body={}):
|
||||
try:
|
||||
list = elastic.es_iterate_all_documents(index_name, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
count = 0
|
||||
text_normal = TextNormalizer()
|
||||
result = {}
|
||||
result_new = {}
|
||||
|
||||
for mentry in list:
|
||||
entry = mentry["source"]
|
||||
id = entry.get("id", "")
|
||||
effects = entry.get("effects", [])
|
||||
for effect in effects :
|
||||
to_section_id = effect["to_section_id"]
|
||||
effect_type = effect["effect_type"]
|
||||
result[to_section_id] = effect_type
|
||||
if effect_type == 'الحاقی' or effect_type =='یتفسیر' :
|
||||
id = effect["id"]
|
||||
result_new[id] = to_section_id
|
||||
return result, result_new
|
||||
|
||||
|
||||
def repair_law_section_text(cursor, elastic, index_name, dict_changed, file_log) :
|
||||
|
||||
query = '''
|
||||
select
|
||||
s.ID as sectionId
|
||||
,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره
|
||||
,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
|
||||
from lwSection s
|
||||
left join lwLaw l on s.F_LWLAWID = l.ID
|
||||
where l.ISLAW = 1
|
||||
order by s.F_LWLAWID,textOrder
|
||||
'''
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
|
||||
file = open(file_log, 'a+', encoding='utf8')
|
||||
i = 0
|
||||
while 1:
|
||||
# print(i)
|
||||
i=i+1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
# if i > 1000:
|
||||
# break
|
||||
# print(row.sectionId)
|
||||
|
||||
try:
|
||||
soup = BeautifulSoup(row.sectionText, "html.parser")
|
||||
text = soup.get_text("\n", strip=True)
|
||||
# text = removeHtmlNoTableTag(row.sectionText) # خطا داره
|
||||
except Exception as e:
|
||||
text = row.sectionText
|
||||
|
||||
|
||||
text = text_normal.normalize_qanon(text)
|
||||
text2 = text_normal.normalize_qanon(text,True)
|
||||
|
||||
# در این صورت مشکل خطای حذف خط تیره کشیده در این متن نبوده و نیازه به بروز رسانی متن نیست
|
||||
if len(text) == len(text2) :
|
||||
if text != text2 :
|
||||
print(' ??????????> changed content : ', eid, "\ntext:", text , "\ntext2:", text2)
|
||||
continue
|
||||
|
||||
content_len = text.__len__()
|
||||
|
||||
eid='qs'+ str(row.sectionId)
|
||||
ts_year = ''
|
||||
if row.aproveDate :
|
||||
items = row.aproveDate.split("/")
|
||||
if items.__len__() > 0:
|
||||
ts_year = items[0]
|
||||
|
||||
|
||||
data={}
|
||||
if eid in dict_changed :
|
||||
print( ' ------------------> chenged effected : ', dict_changed[eid])
|
||||
file.write(' ------------------> chenged effected : '+ dict_changed[eid] + '\n')
|
||||
if dict_changed[eid] == 'اصلاحی' or dict_changed[eid] == 'جایگزین':
|
||||
# اصلاح تاریخ تصویب که بخاطر خطای سامانه ایجاد شده است
|
||||
data={
|
||||
'_id':eid,
|
||||
'_source' : {
|
||||
'ts_date': row.aproveDate,
|
||||
'ts_year': ts_year,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
#word_len = len(split_words(text))
|
||||
if not data :
|
||||
data={
|
||||
'_id':eid,
|
||||
'_source' : {
|
||||
'content': text,
|
||||
'content_len': content_len,
|
||||
}
|
||||
}
|
||||
|
||||
item = {}
|
||||
try:
|
||||
item = elastic.get_doctument(index_name, eid)
|
||||
# در اینصورت محتوای ماده توسط مجلس تغییر یافته است
|
||||
text_m = text_normal.normalize_qanon(item['_source']['content'], True).strip().replace(' ', '')
|
||||
text_m2 = text_normal.normalize_qanon(text, True).strip().replace(' ', '')
|
||||
if text_m != text_m2 :
|
||||
print(' ==========> changed content : ', eid, "\ntext:", text_m , "\ntext:", text_m2)
|
||||
file.write(' ==========> changed content : '+ eid + '\n')
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
# print(type(e).__name__)
|
||||
continue
|
||||
|
||||
# _source = item['_source']
|
||||
# if 'ref_state' in _source :
|
||||
# for ref in _source['ref_state'] :
|
||||
|
||||
|
||||
if len(bulk_data) >= 200:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
bulk_data = []
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid )
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
|
||||
file.close()
|
||||
print('end success import_law_section_to_elastic')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
|
||||
def repair_error_new_section_ts_date( elastic, index_name, dict_changed, file_log) :
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
|
||||
file = open(file_log, 'a+', encoding='utf8')
|
||||
i = 0
|
||||
for key in dict_changed.keys():
|
||||
# باعث خطای کوئری میشد و نیاز نبود
|
||||
# print(i)
|
||||
i=i+1
|
||||
|
||||
eid=key
|
||||
|
||||
eid_prev = dict_changed[key]
|
||||
ts_year = ''
|
||||
item = {}
|
||||
try:
|
||||
item = elastic.get_doctument(index_name, eid_prev)
|
||||
ts_date = item['_source']['ts_date']
|
||||
ts_year = item['_source']['ts_year']
|
||||
sort_date_timestamp = item['_source']['sort_date_timestamp']
|
||||
# در اینصورت محتوای ماده توسط مجلس تغییر یافته است
|
||||
|
||||
except Exception as e:
|
||||
continue
|
||||
|
||||
data={
|
||||
'_id':eid,
|
||||
'_source' : {
|
||||
'ts_date': ts_date,
|
||||
'ts_year': ts_year,
|
||||
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
|
||||
}
|
||||
}
|
||||
|
||||
if len(bulk_data) >= 10:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
bulk_data = []
|
||||
|
||||
if data :
|
||||
bulk_data.append(data)
|
||||
|
||||
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid )
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
|
||||
file.close()
|
||||
print('end success import_law_section_to_elastic')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
|
||||
|
||||
def repair_error_section_ts_date(cursor, elastic, index_name, dict_changed, file_log) :
|
||||
ids = ''
|
||||
for key in dict_changed.keys():
|
||||
# باعث خطای کوئری میشد و نیاز نبود
|
||||
|
||||
if '_' in key :
|
||||
continue
|
||||
|
||||
key = key.replace('qs', '')
|
||||
# if key == 'qs1414840_2512221' or key == 'qs1414840_2511' or key=='qs67f53e80b9949_008' :
|
||||
# continue
|
||||
# number = False
|
||||
# try :
|
||||
# number = int(key)
|
||||
# except :
|
||||
# number = False
|
||||
|
||||
# if not number :
|
||||
# continue
|
||||
|
||||
|
||||
if ids != '' :
|
||||
ids = ids + ','
|
||||
|
||||
ids = ids + key[2:]
|
||||
|
||||
|
||||
query = f'''
|
||||
select
|
||||
s.ID as sectionId
|
||||
,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره
|
||||
,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
|
||||
from lwSection s
|
||||
left join lwLaw l on s.F_LWLAWID = l.ID
|
||||
where l.ISLAW = 1 and s.ID in ({ids})
|
||||
order by s.F_LWLAWID,textOrder
|
||||
'''
|
||||
|
||||
print(query)
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
|
||||
file = open(file_log, 'a+', encoding='utf8')
|
||||
i = 0
|
||||
while 1:
|
||||
# print(i)
|
||||
i=i+1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
# if i > 1000:
|
||||
# break
|
||||
# print(row.sectionId)
|
||||
|
||||
try:
|
||||
soup = BeautifulSoup(row.sectionText, "html.parser")
|
||||
text = soup.get_text("\n", strip=True)
|
||||
# text = removeHtmlNoTableTag(row.sectionText) # خطا داره
|
||||
except Exception as e:
|
||||
text = row.sectionText
|
||||
|
||||
|
||||
text = text_normal.normalize_qanon(text)
|
||||
text2 = text_normal.normalize_qanon(text,True)
|
||||
|
||||
# در این صورت مشکل خطای حذف خط تیره کشیده در این متن نبوده و نیازه به بروز رسانی متن نیست
|
||||
if len(text) == len(text2) :
|
||||
if text != text2 :
|
||||
print(' ??????????> changed content : ', eid, "\ntext:", text , "\ntext2:", text2)
|
||||
continue
|
||||
|
||||
content_len = text.__len__()
|
||||
|
||||
eid='qs'+ str(row.sectionId)
|
||||
ts_year = ''
|
||||
if row.aproveDate :
|
||||
items = row.aproveDate.split("/")
|
||||
if items.__len__() > 0:
|
||||
ts_year = items[0]
|
||||
|
||||
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
|
||||
try:
|
||||
sort_date_timestamp = getSortTimestamp(row.aproveDate)
|
||||
except Exception as e:
|
||||
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
|
||||
|
||||
|
||||
|
||||
data={}
|
||||
if eid in dict_changed :
|
||||
# if dict_changed[eid] == 'اصلاحی' or dict_changed[eid] == 'جایگزین':
|
||||
# اصلاح تاریخ تصویب که بخاطر خطای سامانه ایجاد شده است
|
||||
data={
|
||||
'_id':eid,
|
||||
'_source' : {
|
||||
'ts_date': row.aproveDate,
|
||||
'ts_year': ts_year,
|
||||
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
|
||||
}
|
||||
}
|
||||
|
||||
if len(bulk_data) >= 10:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
bulk_data = []
|
||||
|
||||
if data :
|
||||
bulk_data.append(data)
|
||||
|
||||
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid )
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
|
||||
file.close()
|
||||
print('end success import_law_section_to_elastic')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
|
||||
def repair_law_section_ref_state(cursor, elastic, index_name, dict_changed, file_log) :
|
||||
|
||||
query = '''
|
||||
SELECT
|
||||
gl1.ID as id,
|
||||
gl4.APPROVEDATE as effect_Date,
|
||||
gl3.[SECTIONTEXT] as effect_text,
|
||||
gl3.FULLPATH as effect_section_title,
|
||||
ls2.SECTIONTEXT as effect_prev_text,
|
||||
gl4.CAPTION as effect_qanon,
|
||||
gl1.F_LWLAWID_EFFECTIVE as effect_qanon_id,
|
||||
gl1.[F_LWSECTIONID_EFFECTIVE] as effect_section_id,
|
||||
gl1.[F_LWSECTIONID_EFFECTED] as sectionId,
|
||||
gl2.[SECTIONTEXT],
|
||||
ls1.CAPTION as effect_section_type,
|
||||
gl1.DESCRIPTION as description,
|
||||
gl1.ISIMPLICIT -- تاثیر ضمنی
|
||||
FROM [Qavanin].[dbo].[lwSectionChange] gl1
|
||||
left join [lwLawSectionStatus] ls1 on ls1.ID=gl1.[F_CMBASETABLEID_SECTIONSTATUS]
|
||||
left join lwSection gl2 on gl2.ID=gl1.[F_LWSECTIONID_EFFECTED]
|
||||
left join lwSection gl3 on gl3.ID=gl1.[F_LWSECTIONID_EFFECTIVE]
|
||||
left join lwLaw gl4 on gl1.F_LWLAWID_EFFECTIVE=gl4.ID
|
||||
left join lwSectionLog ls2 on ls2.ID=gl1.[F_LWSECTIONLOGID_EFFECTED]
|
||||
|
||||
where
|
||||
gl4.ISLAW = 1
|
||||
and gl1.[F_LWSECTIONID_EFFECTED] is not null
|
||||
|
||||
order by gl1.[F_LWSECTIONID_EFFECTED], gl4.APPROVEDATE
|
||||
|
||||
'''
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
previd = ''
|
||||
prev_effect_type = ''
|
||||
prev_efect_section_id = ''
|
||||
ref_state_array = []
|
||||
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
|
||||
file = open(file_log, 'a+', encoding='utf8')
|
||||
i = 0
|
||||
while 1:
|
||||
# print(i)
|
||||
i=i+1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
# if i > 3:
|
||||
# break
|
||||
# print(row.sectionId)
|
||||
|
||||
eid='qs'+ str(row.sectionId)
|
||||
# lawId='qq'+ str(row.lawId)
|
||||
|
||||
if previd == '':
|
||||
previd = eid
|
||||
|
||||
|
||||
if eid in dict_changed :
|
||||
print( ' ------------------> chenged effected : ', eid, ' : ', dict_changed[eid])
|
||||
file.write(' ------------------> chenged effected : '+ eid+ ' : ' + dict_changed[eid] + '\n')
|
||||
if dict_changed[eid] == 'اصلاحی' or dict_changed[eid] == 'جایگزین':
|
||||
continue
|
||||
|
||||
|
||||
effect_type = ''
|
||||
if row.effect_section_type == 'معتبر' :
|
||||
effect_type = ''
|
||||
elif row.effect_section_type == 'ساختار الحاقي' or row.effect_section_type == 'ساختار الحاقي مكرر' :
|
||||
effect_type = 'الحاقی'
|
||||
elif row.effect_section_type == 'اصلاحي' or row.effect_section_type == 'نامه اصلاحي':
|
||||
effect_type = 'اصلاحی'
|
||||
elif row.effect_section_type == 'منسوخه' :
|
||||
effect_type = 'نسخی'
|
||||
elif row.effect_section_type == 'احياء' or row.effect_section_type == 'تنفيذ' or row.effect_section_type == 'تمديد':
|
||||
effect_type = 'تمدیدی'
|
||||
elif row.effect_section_type == 'تفسير' :
|
||||
effect_type = 'تفسیری'
|
||||
elif row.effect_section_type == 'ساختار جايگزين' or row.effect_section_type == 'جايگزين شده':
|
||||
effect_type = 'جایگزین'
|
||||
elif row.effect_section_type == 'آزمايشي' :
|
||||
effect_type = ''
|
||||
elif row.effect_section_type == 'موقت' :
|
||||
effect_type = ''
|
||||
elif row.effect_section_type == 'موقوف الاجراء' :
|
||||
effect_type = ''
|
||||
elif row.effect_section_type == 'بااجرامنتفي مي شود' :
|
||||
effect_type = ''
|
||||
|
||||
if row.ISIMPLICIT :
|
||||
effect_type += ' ضمنی'
|
||||
|
||||
# if i == 1 : # اولین بار
|
||||
# prev_effect_type = effect_type
|
||||
|
||||
ref_state = {}
|
||||
if row.effect_qanon_id :
|
||||
efect_section_id='qs'+ str(row.effect_section_id)
|
||||
efect_qanon_id= 'qq'+ str(row.effect_qanon_id)
|
||||
|
||||
if prev_efect_section_id == '' :
|
||||
prev_efect_section_id = efect_section_id
|
||||
|
||||
ref_state = {
|
||||
"id" : row.id,
|
||||
"qanon_id": efect_qanon_id,
|
||||
"qanon_title" : text_normal.normalize_qanon(row.effect_qanon),
|
||||
"qanon_date": row.effect_Date,
|
||||
"section_id": efect_section_id,
|
||||
"section_title": normalYehKe(row.effect_section_title),
|
||||
"ref_key": "qavanin",
|
||||
"effect_type" : effect_type,
|
||||
"new_text" : text_normal.normalize_qanon(row.effect_text),
|
||||
"prev_text" : text_normal.normalize_qanon(row.effect_prev_text),
|
||||
"description" : text_normal.normalize_qanon(row.description)
|
||||
}
|
||||
|
||||
|
||||
if previd == eid :
|
||||
# موارد کاملا تکراری افزوده نشود
|
||||
if efect_section_id != prev_efect_section_id or prev_effect_type != effect_type:
|
||||
ref_state_array.append(ref_state)
|
||||
prev_efect_section_id = efect_section_id
|
||||
prev_effect_type = effect_type
|
||||
ref_state={}
|
||||
continue
|
||||
|
||||
|
||||
data={
|
||||
'_id':previd,
|
||||
'_source' : {
|
||||
'ref_state' : ref_state_array
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
ref_state_array = []
|
||||
previd = eid
|
||||
prev_efect_section_id = efect_section_id
|
||||
prev_effect_type = effect_type
|
||||
ref_state_array.append(ref_state)
|
||||
|
||||
if len(bulk_data) >= 100:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
bulk_data = []
|
||||
|
||||
|
||||
|
||||
|
||||
if ref_state_array.__len__() > 0 :
|
||||
data={
|
||||
'_id':previd,
|
||||
'_source' : {
|
||||
'ref_state' : ref_state_array
|
||||
}
|
||||
}
|
||||
bulk_data.append(data)
|
||||
# print(bulk_data)
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
elastic.updateBulkList(bulk_data, index_name)
|
||||
bulk_data = []
|
||||
|
||||
print('end success import_law_section_update_ref_state')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
|
||||
host=os.getenv('HOST_160')
|
||||
password=os.getenv('HOST_160_PASS')
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
cursor, cnxn = create_cursor()
|
||||
|
||||
|
||||
body={
|
||||
"query": {
|
||||
"exists": {"field": "effects"}
|
||||
}
|
||||
}
|
||||
dict_effected_sections, dict_effected_new_sections = extract_all_effecteds(elastic, "mj_df_qanon", body)
|
||||
# print(dict_effected_sections)
|
||||
|
||||
# try:
|
||||
# item = elastic.get_doctument("mj_qa_section", "3223423")
|
||||
# except Exception as e:
|
||||
# print(e)
|
||||
# print(type(e).__name__)
|
||||
# print(str(e))
|
||||
|
||||
###### step 1 repair text - ###########################
|
||||
repair_law_section_text(cursor, elastic, "mj_qa_section", dict_effected_sections, "./output/log_r1.txt")
|
||||
|
||||
###### step 2 : repair date #############
|
||||
repair_error_section_ts_date(cursor, elastic, "mj_qa_section", dict_effected_sections, "./output/log_r1.txt")
|
||||
repair_error_new_section_ts_date( elastic, "mj_qa_section", dict_effected_new_sections, "./output/log_r1.txt")
|
||||
|
||||
|
||||
###### step 3 : not nead #############
|
||||
#repair_law_section_ref_state(cursor, elastic, "mj_qa_section", dict_effected_sections, "./output/log_r2.txt")
|
||||
Reference in New Issue
Block a user