import os from dotenv import load_dotenv import json import requests from config_base import * import pyodbc import requests from bs4 import BeautifulSoup from html import escape import json from decimal import Decimal import datetime import time from config_base import * from general_functions import * from text_normalizer import TextNormalizer from 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 = {} 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 return result def repair_law_section_text(cursor, elastic, index_name, dict_changed, file_log) : query = ''' select s.ID as sectionId ,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره 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) 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] == 'جایگزین': continue #word_len = len(split_words(text)) 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_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 = 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)) #repair_law_section_text(cursor, elastic, "mj_qa_section", dict_effected_sections, "./output/log_r1.txt") repair_law_section_ref_state(cursor, elastic, "mj_qa_section", dict_effected_sections, "./output/log_r2.txt")