refactor 2

This commit is contained in:
hsafaei
2025-09-02 12:15:47 +03:30
parent cfe3cff77c
commit 5a6647bbf2
62 changed files with 151 additions and 160 deletions
+2
View File
@@ -0,0 +1,2 @@
+588
View File
@@ -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")
+105
View File
@@ -0,0 +1,105 @@
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
def moveModelToQaSectionMirror(elastic, index_name_i, index_name_o):
try:
body={}
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
dtime = myTimestamp(-100)
count = 0
for mentry in list:
count += 1
entry = mentry["source"]
if (count % 100) == 0 :
print("%s -> %.2f " % (id , (count / elastic.total) if elastic.total > 0 else 0))
id = entry.get("ref_id", "")
qanon_title = entry.get("qanon_title", "")
ts_date = entry.get("ts_date", "")
qanon_id = entry.get("qanon_id", "")
other_info = entry.get("other_info", {})
model_work_tags = entry.get("work_tags", [])
model_work_state = entry.get("work_state", [])
model_rules = entry.get("rules", [])
model_rules_logics = entry.get("rules_logics", [])
model_rules_logics_triples = entry.get("rules_logics_triples", [])
model_rules_spins = entry.get("rules_spins", [])
model_files = entry.get("files", [])
user_edit = entry.get("user_edit", "")
time_edit = entry.get("time_edit", dtime)
user_logs = entry.get("user_log", [])
doc_states = ['user', 'model']
edit_type = 'model'
is_delete = 0
eid = edit_type + str(id) + '_' + str(user_edit)
data = {
"id" : id,
"qanon_title" : qanon_title,
"ts_date" : ts_date,
"qanon_id" : qanon_id,
"other_info" : other_info,
"model_work_tags" : model_work_tags,
"model_work_state" : model_work_state,
"model_rules" : model_rules,
"model_rules_logics" : model_rules_logics,
"model_rules_logics_triples" : model_rules_logics_triples,
"model_rules_spins" : model_rules_spins,
"model_files" : model_files,
"user_edit" : user_edit,
"time_edit" : time_edit,
"user_logs" : user_logs,
"doc_states" : doc_states,
"edit_type" : edit_type,
"is_delete" : is_delete,
}
try:
resp = elastic.update_index_doc(False, index_name_o, eid, data)
except Exception as e:
print(e)
# save_error(id, e)
except Exception as e:
print("1111")
print(e)
load_dotenv(dotenv_path='config.env')
# host=os.getenv('HOST_160')
# password=os.getenv('HOST_160_PASS')
host=os.getenv('HOST_112')
password=os.getenv('HOST_112_PASS')
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
elastic.createIndex("mj_qa_section-m1", 'majles', "mj_qa_section" )
moveModelToQaSectionMirror(elastic, "mj_model", "mj_qa_section-m1")
+712
View File
@@ -0,0 +1,712 @@
import os
import re
import traceback
import json
import pandas as pd
from dotenv import load_dotenv
# from common.general_functions import *
from common.qanon_functions import *
from common.elastic_helper import ElasticHelper
from common.config_base import *
def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""):
# excel_helper = ExcelHelper()
# df = excel_helper.load_data(file)
# df = pd.read_excel('records.xlsx', sheet_name='Cars', usecols=['Car Name', 'Car Price'])
# print(df)
df = pd.read_excel(file_excel, sheet_name=0, header=None)
# print(df[0:10])
# print(df.columns.ravel())
# print(df.columns.tolist())
# print(df['EmpName'].tolist())
# print(df[0].tolist())
count = 0
rows_list = df.to_dict(orient='records')
total = len(df[0])
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=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]]
# if code_state :
# print ( 'ddddddddddddddcode_state' , code_state)
# else :
# print ( 'ccccccccccccccode_state' , code_state)
qanon_id = 0
section_id = 0
state = ''
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
if section_title is None or is_nan_or_none_or_empty(section_title) or qanon_title is None or is_nan_or_none_or_empty(qanon_title) :
file.write('!!!!!! nan error !!!!!!!' + str(count) + '\n')
state = 'خطا-پرش'
else:
section_title = text_normalizer.normalize_search_qanon(str(section_title))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
if qanon_id == 0 :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
dic_error_qanon_title[qanon_title]=count
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
else:
state = 'قانون-جستجو'
# اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ...
if not qanon_id == 0 :
section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title)
# - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود
if score < 90 :
dic_error_section_title[str(qanon_id)+'=='+section_title]=count
print('='*10 , str(count) , ' section error', qanon_id, ' --> ', section_title )
file.write('---- section error ---' + str(qanon_id) + ' ----- ' + section_title + '\n')
section_id = 0
state = 'خطا-جزء'
else :
state = 'صحیح'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row[5]=qanon_id
row[6]=section_id
row[7]=state
rows_list_new.append(row)
data={}
# ذخیره کد در الاستیک برای شناسه های یافت شده
if section_id and section_id != 0:
item = elastic.get_doctument(index_name_o,section_id)
tcode_mains = []
tcode_subs = []
if "tcode_mains" in item['_source'] :
tcode_mains= item['_source']["tcode_mains"]
if "tcode_subs" in item['_source'] :
tcode_subs= item['_source']["tcode_subs"]
code = {
"label" : tcode_label,
"id" : tcode_id
}
if code_state == True :
tcode_mains.append(code)
else:
tcode_subs.append(code)
data={
'_id':section_id,
'_source' : {
'tcode_mains': tcode_mains,
'tcode_subs': tcode_subs,
}
}
bulk_data.append(data)
# انتقال دسته جمعی کدها به الاستیک
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) )
elastic.updateBulkList(bulk_data, index_name_o)
##### columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
# columns=[0, 1, 2, 3, 4, 5, 6, 7]
# new_df = pd.DataFrame(rows_list_new, columns=columns)
# if result_path == '' :
# directory_path = os.path.dirname(file_excel)
# result_path = directory_path + "/result/"
# file_name = os.path.basename(file_excel)
# file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
# print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
file_log2= file_log.replace(".txt", "_2.txt")
with open(file_log2, 'w', encoding='utf8') as file2:
file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""):
df = pd.read_excel(file_excel, sheet_name=0)
count = 0
rows_list = df.to_dict(orient='records')
column_names = df.columns.tolist()
column_count = len(column_names)
# print(column_names)
total = len(df[column_names[0]])
print('total : ', total)
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
prevRow = None
try:
for row in rows_list:
row_number = row[column_names[0]]
title = row[column_names[1]]
section_title = row[column_names[2]]
ts_date = ""
code_state = ""
if title is None or is_nan_or_none_or_empty(title) or title is None or is_nan_or_none_or_empty(title) :
title = prevRow[column_names[1]]
else:
prevRow = row
qanon_id = 0
section_id = 0
state = ''
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
title = text_normalizer.normalize_search_qanon(title)
qanon_title, ts_date, ts_ref = get_qanon_date(title)
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
# قانون ساختمان شاهراه تهران – كرج
qanon_title = qanon_title.replace("–", "-")
score = 100
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
if qanon_id == 0 :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
dic_error_qanon_title[qanon_title]=count
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
else:
state = 'قانون-جستجو'
# اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ...
section_title = text_normalizer.normalize_search_qanon(str(section_title))
result_section_title = get_section_correct(section_title)
result_section_id = []
if qanon_id != 0 :
for section_title in result_section_title:
if section_title == 'all' :
state = 'صحیح'
result_section_id.append('all')
continue
section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title)
# - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود
if score < 90 :
dic_error_section_title[str(qanon_id)+'=='+section_title]=count
print('='*10 , str(count) , ' section error', qanon_id, ' --> ', section_title )
file.write('---- section error ---' + str(qanon_id) + ' ----- ' + section_title + '\n')
section_id = 0
state = 'خطا-جزء'
elif state == '':
state = 'صحیح'
result_section_id.append(section_id)
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row[column_count+1]=qanon_id
row[column_count+2]= '#'.join(str(item) for item in result_section_id)
row[column_count+3]=state
row[column_count+4]=qanon_title +'#'+ ts_date +'#'+ ts_ref
row[column_count+5]='#'.join(result_section_title)
rows_list_new.append(row)
data={}
tstate = 'نامعتبر'
c_name = 'وضعیت اعتبار'
if c_name in column_names :
tstate = row[c_name].replace('#', '').replace('=', '')
if tstate.startswith('نامعتبر') :
tstate = 'نامعتبر-' + tstate
treason = ''
c_name = 'مستند عدم اعتبار'
if c_name in column_names :
treason = row[c_name].replace('#','\n').replace('=','\n')
description = ''
c_name = 'توضیحات'
if c_name in column_names :
description = row[c_name].replace('*', '')
# ذخیره کد در الاستیک برای شناسه های یافت شده
for section_id in result_section_id :
if section_id == '' or section_id == 0 :
continue
if section_id =='all':
tstate = tstate + ' کل '
result = get__all_section_qanon(elastic, index_name_o, qanon_id)
for sid in result :
tvalid_state={
"tstate": tstate.strip(),
"description": description,
"treason": treason,
# "treason_type": treason_type
}
data={
'_id':sid,
'_source' : {
'tvalid_state': tvalid_state
}
}
bulk_data.append(data)
break
tvalid_state={
"tstate": tstate.strip(),
"description": description,
"treason": treason,
# "treason_type": treason_type
}
data={
'_id':section_id,
'_source' : {
'tvalid_state': tvalid_state
}
}
bulk_data.append(data)
# انتقال دسته جمعی کدها به الاستیک
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) )
elastic.updateBulkList(bulk_data, index_name_o)
# columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
column_names.append(column_count+1)
column_names.append(column_count+2)
column_names.append(column_count+3)
column_names.append(column_count+4)
column_names.append(column_count+5)
columns= column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
tb = traceback.extract_tb(e.__traceback__)
print(tb)
line_number = tb[-1].lineno # Get the line number of the last call
print(f"Error: {e} on line {line_number}")
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
# file_log1= file_log.replace(".txt", "_1.txt")
# with open(file_log1, 'w', encoding='utf8') as file1:
# file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
# file_log2= file_log.replace(".txt", "_2.txt")
# with open(file_log2, 'w', encoding='utf8') as file2:
# file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""):
# excel_helper = ExcelHelper()
# df = excel_helper.load_data(file)
# df = pd.read_excel('records.xlsx', sheet_name='Cars', usecols=['Car Name', 'Car Price'])
# print(df)
df = pd.read_excel(file_excel, sheet_name=0, header=None)
# print(df[0:10])
# print(df.columns.ravel())
# print(df.columns.tolist())
# print(df['EmpName'].tolist())
# print(df[0].tolist())
count = 0
rows_list = df.to_dict(orient='records')
total = len(df[0])
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=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]]
qanon_id = 0
section_id = 0
state = ''
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
if section_title is None or is_nan_or_none_or_empty(section_title) or qanon_title is None or is_nan_or_none_or_empty(qanon_title) :
file.write('!!!!!! nan error !!!!!!!' + str(count) + '\n')
state = 'خطا-پرش'
else:
section_title = text_normalizer.normalize_search_qanon(str(section_title))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
if qanon_id == 0 :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
dic_error_qanon_title[qanon_title]=count
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
else:
state = 'قانون-جستجو'
# اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ...
if not qanon_id == 0 :
section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title)
# - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود
if score < 90 :
dic_error_section_title[str(qanon_id)+'=='+section_title]=count
print('='*10 , str(count) , ' section error', qanon_id, ' --> ', section_title )
file.write('---- section error ---' + str(qanon_id) + ' ----- ' + section_title + '\n')
section_id = 0
state = 'خطا-جزء'
else :
state = 'صحیح'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row[5]=qanon_id
row[6]=section_id
row[7]=state
rows_list_new.append(row)
data={}
# ذخیره کد در الاستیک برای شناسه های یافت شده
if section_id and section_id != 0:
item = elastic.get_doctument(index_name_o,section_id)
tcode_mains = []
tcode_subs = []
if "tcode_mains" in item['_source'] :
tcode_mains= item['_source']["tcode_mains"]
if "tcode_subs" in item['_source'] :
tcode_subs= item['_source']["tcode_subs"]
code = {
"label" : tcode_label,
"id" : tcode_id
}
if code_state :
tcode_mains.append(code)
else:
tcode_subs.append(code)
data={
'_id':section_id,
'_source' : {
'tcode_mains': tcode_mains,
'tcode_subs': tcode_subs,
}
}
bulk_data.append(data)
# انتقال دسته جمعی کدها به الاستیک
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) )
elastic.updateBulkList(bulk_data, index_name_o)
# columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
columns=[0, 1, 2, 3, 4, 5, 6, 7]
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
file_log2= file_log.replace(".txt", "_2.txt")
with open(file_log2, 'w', encoding='utf8') as file2:
file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
def run_Codes_directory(elastic, directory, output):
dic_code_id={
"آب" : 1,
"آمار، برنامه و بودجه" : 2,
"آموزش و پرورش" : 3,
"آیین دادرسی مدنی" : 5,
"سلامت" : 30,
"فرهنگ و هنر" : 33,
"مسکن و شهرسازی" : 42,
"مناطق آزاد و ویژه اقتصادی" : 45,
"نفت و گاز" : 49
}
# List all files in the specified directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
for file in files :
file_name = os.path.basename(file)
code_name = os.path.splitext(file_name)[0]
w1 = text_normalizer.split_words(code_name)[0]
log_file = output + "/log_r_"+w1+".txt"
file_path = os.path.join(directory, file)
try:
os.makedirs(output, exist_ok=True)
except Exception as e:
print(output)
code_id = 0
if code_name in dic_code_id :
code_id = dic_code_id[code_name]
importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file)
else :
print('00000 error 000000 ', code_name)
def run_Etebar_directory(elastic, directory, output):
dic_code_id={
"آب" : 1,
"آمار، برنامه و بودجه" : 2,
"آموزش و پرورش" : 3,
"آیین دادرسی مدنی" : 5,
"سلامت" : 30,
"فرهنگ و هنر" : 33,
"مسکن و شهرسازی" : 42,
"مناطق آزاد و ویژه اقتصادی" : 45,
"نفت و گاز" : 49,
}
# List all files in the specified directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
for file in files :
file_name = os.path.basename(file)
if '~$' in file_name :
continue
code_name = os.path.splitext(file_name)[0]
code_name = code_name.replace("نامعتبر-", "").strip()
w1 = text_normalizer.split_words(code_name)[0]
log_file = output + "/log_r_"+w1+".txt"
file_path = os.path.join(directory, file)
# if code_name != 'سلامت' :
# continue
try:
os.makedirs(output, exist_ok=True)
except Exception as e:
print(output)
code_id = 0
importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file)
# if code_name in dic_code_id :
# code_id = dic_code_id[code_name]
# importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file)
# else :
# print('00000 error 000000 ', code_name)
load_dotenv(dotenv_path='config.env')
# host=os.getenv('HOST_160')
# password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_112')
# password=os.getenv('HOST_112_PASS')
host=os.getenv('HOST_113')
password=os.getenv('HOST_113_PASS')
print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#run_Codes_directory(elastic, "./data/tcodes", "./data/tcodes/result")
run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result")
# importCodesToElastic(elastic, "./data/tcodes/مسکن و شهرسازی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r3.txt")
# importCodesToElastic(elastic, "./data/tcodes/آمار، برنامه و بودجه.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_آمار.txt")
# importCodesToElastic(elastic, "./data/tcodes/آیین دادرسی مدنی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_دادرسی.txt")
# importCodesToElastic(elastic, "./data/tcodes/نفت و گاز.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_نفت.txt")
# text="قانون  بلدیه"
#text = text.replace("\u00a0", " ") # No Break space
# text="قانون تشکیلات، وظایف و انتخابات شوراهای اسلامی کشور و انتخاب شهرداران مصوب 1 /3 /1375 و اصلاحات بعدی آن"
# text="ائین‌نامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28ر12ر1345"
# text="قانون بودجه سال 1369کل کشور"
# text="قانون تشکیلات، وظایف و انتخابات شوراهای اسلامی کشور و انتخاب شهرداران مصوب 1/3/1375 و اصلاحات بعدی آن"
text="قانون بودجه سال 1369کل کشور"
text="پیوست 3>متن >ضمیمه 1>قسمت الف>فصل پنجم>جدول الف-1-1-1 /5"
# searchSectionId(elastic, "mj_qa_section", "qq240970", text )
# text = text_normalizer.date_correction(text)
# text = re.sub(r"(\d+?) /(\d+?) /(\d+?)", r"\1/\2/\3", text)
# text = re.sub(r"(\d)/(\d)/(\d{4})", r"0\1/0\2/\3", text)
# print(text.split('/'))
# text1 = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", text)
# print(text)
# print(text1)
# print(text1==text)
# print( searchQanonId(elastic, text) )
+120
View File
@@ -0,0 +1,120 @@
import pandas as pd
import requests
import json
from common.text_normalizer import TextNormalizer
# from common.config_base import *
from common.general_functions import *
ADD_ITEM_ROUTE = "subject/add"
# TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDgyNTY3MTYsImp0aSI6IlZWejlWRDFGMUx5UkEyd01EaW5od3M3cTJRRkVqYW9kIiwiaXNzIjpudWxsLCJleHAiOjE3NDk1NTY3MTUsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDY0NVx1MDYyZlx1MDZjY1x1MDYzMSBcdTA2NDFcdTA2NDZcdTA2Y2MiLCJsYXN0X25hbWUiOiJcdTA2MzNcdTA2MjdcdTA2NDVcdTA2MjdcdTA2NDZcdTA2NDciLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.QljFs4f0HFT7S8qrib6q54kMWg7z381v2uqoiSFDfR4'
TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDk1NjU0NDksImp0aSI6IlwvODBxR2pEUHlleFZVRFErTkhKcGl0ejd6TmdvaDdHSiIsImlzcyI6bnVsbCwiZXhwIjoxNzUwODY1NDQ4LCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjIsImZpcnN0X25hbWUiOiJcdTA2MmRcdTA2NDVcdTA2Y2NcdTA2MmYiLCJsYXN0X25hbWUiOiJcdTA2MzVcdTA2NDFcdTA2MjdcdTA2Y2NcdTA2Y2MiLCJlbWFpbCI6InNhZmFlaS5oYW1pZEBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImhzYWZhZWkiLCJ1c2VyX2xldmVsIjoyfX0.XmEEA_DhVbUQe76guQxuNrEoTUxPRMYd5Zbi7l7m5M4'
ACCEPT = "application/json"
HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT}
# BASE_URL = "http://192.168.23.160/api/"
BASE_URL = "http://192.168.23.113/api/"
# TITLE = ""
def read_excel_data(file_path ):
df = pd.read_excel(file_path )
df.fillna("", inplace=True)
data = df.to_dict(orient="records")
text_normal = TextNormalizer()
for row in data:
row["CAPTION"] = text_normal.normalize_qanon(row["عنوان"])
row["ID"] = int(row["ردیف"])
row["META"] = row.get("توضیحات", "")
return data
def insert_project(title, id=''):
projectid = 8 # فرض کنید projectid ثابت است
return projectid
def insertProejct(title, id=''):
# ایجاد فهرست جدید
url = "project/add"
item = {
"id": id,
"title": title,
"type": 3,
"item_state": 1,
"ispublic" : 1,
}
result = requests.post(BASE_URL + 'list/' + url, data=item, headers = HEADERS)
res = json.loads(result.text)
if result.status_code == 200 :
# print(result.text)
New_ID = res["data"]["id"]
print(str('project added =' + str(New_ID)))
projectid = New_ID
return projectid
else :
New_ID = res["data"]["id"]
print(str('project exist=' + str(New_ID)))
projectid = New_ID
# print(res)
return projectid
def process_excel_data(file_path, send_to_server=True):
data = read_excel_data(file_path)
data = sorted(data, key=lambda x: x["ID"])
# projectid = insert_project('کدهای تنقیح 50 باب', 8)
projectid = insertProejct('کدهای تنقیح 50 باب', 8)
id_counter = 1 # برای fake_id
local_id_map = {} # برای نگه‌داشتن ID ساختگی در حالت تست
output_data = [] # لیستی برای ذخیره خروجی نهایی
for row in data:
caption = row["CAPTION"]
row_id = row["ID"]
meta = row.get("META", "")
meta = '{"description":"'+meta+'"}'
insertProejct('پلان ' + caption, 100+row_id)
# در حالت تست، parent_id از local map خونده میشه
payload = {
"title": caption,
"projectid": projectid,
"meta": meta,
"otherid": row_id,
"listtype": 0,
}
if send_to_server:
try:
response = requests.post(
BASE_URL + 'list/' + ADD_ITEM_ROUTE, data=payload, headers=HEADERS )
if response.status_code == 200:
res_json = response.json()
new_id = res_json["data"][0]["id"]
print(f"✅ Inserted {caption} => ID: {new_id}")
payload["id"] = new_id
else:
print(f"❌ Error inserting {caption} => Status Code: {response.status_code}")
except Exception as e:
print(f"❌ Failed to insert {caption} (ID={row_id}): {e}")
else:
fake_id = id_counter
local_id_map[row_id] = fake_id
id_counter += 1
# print(f"🧪 TEST MODE: Would insert => {payload} | Fake ID: {fake_id}")
output_data.append(payload)
file_name = "mmm1.json"
with open(file_name, "w", encoding="utf-8") as file:
json.dump(output_data, file, ensure_ascii=False, indent=4)
print(f"\n📁 خروجی در فایل «{file_name}» ذخیره شد.")
if __name__ == "__main__":
file_path = "data/کدهای 50 گانه.xlsx"
process_excel_data(file_path ,send_to_server=True ) # False for test
+224
View File
@@ -0,0 +1,224 @@
import pandas as pd
import requests
import json
import os
from common.text_normalizer import TextNormalizer
# from common.config_base import *
from common.general_functions import *
ADD_ITEM_ROUTE = "subject/add"
# TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDgyNTY3MTYsImp0aSI6IlZWejlWRDFGMUx5UkEyd01EaW5od3M3cTJRRkVqYW9kIiwiaXNzIjpudWxsLCJleHAiOjE3NDk1NTY3MTUsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDY0NVx1MDYyZlx1MDZjY1x1MDYzMSBcdTA2NDFcdTA2NDZcdTA2Y2MiLCJsYXN0X25hbWUiOiJcdTA2MzNcdTA2MjdcdTA2NDVcdTA2MjdcdTA2NDZcdTA2NDciLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.QljFs4f0HFT7S8qrib6q54kMWg7z381v2uqoiSFDfR4'
TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDk1NjU0NDksImp0aSI6IlwvODBxR2pEUHlleFZVRFErTkhKcGl0ejd6TmdvaDdHSiIsImlzcyI6bnVsbCwiZXhwIjoxNzUwODY1NDQ4LCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjIsImZpcnN0X25hbWUiOiJcdTA2MmRcdTA2NDVcdTA2Y2NcdTA2MmYiLCJsYXN0X25hbWUiOiJcdTA2MzVcdTA2NDFcdTA2MjdcdTA2Y2NcdTA2Y2MiLCJlbWFpbCI6InNhZmFlaS5oYW1pZEBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImhzYWZhZWkiLCJ1c2VyX2xldmVsIjoyfX0.XmEEA_DhVbUQe76guQxuNrEoTUxPRMYd5Zbi7l7m5M4'
ACCEPT = "application/json"
HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT}
# BASE_URL = "http://192.168.23.160/api/"
BASE_URL = "http://192.168.23.113/api/"
# TITLE = ""
def read_excel_data(file_path ,sheet_name):
df = pd.read_excel(file_path , sheet_name=sheet_name)
df.fillna("", inplace=True)
data = df.to_dict(orient="records")
column_names = df.columns.tolist()
text_normal = TextNormalizer()
for row in data:
row["CAPTION"] = text_normal.normalize_qanon(row["عنوان"])
row["ID"] = int(row["ردیف"])
row["F_PARENTID"] = int(row["سطح"]) - 1 if row["سطح"] > 1 else 0
row["LEVEL"] = int(row["سطح"])
row["CODE"] = row.get("کد", "")
return data, column_names
# def insert_project():
# projectid = 7 # فرض کنید projectid ثابت است
# return projectid
def insert_project(sheet_name):
json_file = 'کدهای 50 گانه.json'
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
for row in data:
if row.get("title") == sheet_name:
base_id = row.get("otherid", 0)
return base_id + 100 # افزایش ۱۰۰ واحدی
print(f"❌ Sheet name '{sheet_name}' not found in JSON data.")
return None
def insert_real_old(rows, projectid, IDS_DICT, childs,otherid):
remains = []
for row in rows:
try:
f_parentid = row["F_PARENTID"]
row_id = row["ID"]
caption = row["CAPTION"]
except KeyError:
print("Missing data in row:", row)
continue
# تعیین والد
if f_parentid == 0:
parent = 0
elif str(f_parentid) in IDS_DICT:
parent = IDS_DICT[str(f_parentid)]["id"]
else:
print(f"❗️ Parent not found for F_PARENTID={f_parentid}")
remains.append(row)
continue
# محاسبه شماره فرزند
number = childs.get(parent, 0) + 1
childs[parent] = number
# آماده‌سازی درخواست
ADD_ITEM_QUERY = {
"title": caption,
"projectid": projectid,
"otherid": otherid,
"meta": row.get("CODE", ""),
"childorder": number,
"listtype": 0,
"parent": parent,
}
try:
response = requests.post(
BASE_URL + 'list/' + ADD_ITEM_ROUTE,
data=ADD_ITEM_QUERY,
headers=HEADERS
)
response.raise_for_status()
res_json = response.json()
new_id = res_json["data"][0]["id"]
print(f"✅ {row_id}: {caption} -> ID={new_id}")
except Exception as e:
print(f"❌ Failed to insert {caption}: {e}")
remains.append(row)
continue
IDS_DICT[str(row_id)] = {
"id": new_id,
**ADD_ITEM_QUERY
}
return remains
def insert_real(rows, projectid, IDS_DICT, column_names,otherid):
remains = []
dic_level_parent = {1:0}
child_count = {}
prev_level = 0
prev_id = 0
new_row_list=[]
column_count = len(column_names)
for row in rows:
row_id = row["ID"]
caption = row["CAPTION"]
level = row["LEVEL"]
parent = 0
if level == 1 :
parent = 0
elif level == prev_level+1 :
parent = prev_id
dic_level_parent[level]=prev_id
elif level in dic_level_parent:
parent = dic_level_parent[level]
else :
print("error", level, row_id)
child_order = child_count.get(parent, 0) + 1
child_count[parent] = child_order
row[column_count+1] = parent
row[column_count+2] = child_order
new_row_list.append(row)
# آماده‌سازی درخواست
body = {
"title": caption,
"projectid": projectid,
"otherid": otherid,
"meta": row.get("CODE", ""),
"child_order": child_order,
"listtype": 0,
"parent": parent,
}
prev_level = level
try:
response = requests.post(
BASE_URL + 'list/' + ADD_ITEM_ROUTE,
data=body,
headers=HEADERS
)
response.raise_for_status()
res_json = response.json()
new_id = res_json["data"][0]["id"]
print(f"✅ {row_id}: {caption} -> ID={new_id}")
prev_id = new_id
except Exception as e:
print(f"❌ Failed to insert {caption}: {e}")
remains.append(row)
continue
IDS_DICT[str(row_id)] = {
"id": new_id,
**body
}
return new_row_list
def process_excel_data(file_path , sheet_name):
row_list, column_names = read_excel_data(file_path , sheet_name)
row_list = sorted(row_list, key=lambda x: x["ID"])
print(f"❗️ Parent not found for F_PARENTID={row_list}")
IDS_DICT = {}
childs = {}
projectid = insert_project(sheet_name)
otherid = projectid-100
if not projectid:
return
print("🚀 شروع درج داده‌ها")
rows_list_new = insert_real(row_list, projectid, IDS_DICT, column_names , otherid)
column_count=len(column_names)
column_names.append(column_count+1)
column_names.append(column_count+2)
columns=column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
result_path = os.path.dirname(file_path)
file_name = sheet_name
file_excel2 = result_path +'/پلن-'+ file_name + '.xlsx'
# print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
# json_file_path = f'{sheet_name}.json'
# with open(json_file_path, "w", encoding="utf-8") as file:
# json.dump(IDS_DICT, file, ensure_ascii=False, indent=4)
# print(f"\n✅ تمام داده‌ها ثبت شدند و در {sheet_name} ذخیره شدند.")
if __name__ == "__main__":
file_path = "data/Plan.xlsx"
sheet_name = 'آموزش و پرورش'
process_excel_data(file_path , sheet_name)
sheet_name = 'مناطق آزاد و ویژه اقتصادی'
process_excel_data(file_path , sheet_name)
sheet_name = 'فرهنگ و هنر'
process_excel_data(file_path , sheet_name)
+538
View File
@@ -0,0 +1,538 @@
import os
import re
import traceback
import pandas as pd
import json
from dotenv import load_dotenv
from common.config_base import *
from common.elastic_helper import ElasticHelper
from common.qanon_functions import *
def parseBeforeInfos_SearchQanonTitle(elastic, file_excel, file_log, result_path = ""):
# 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')
total = len(rows_list)
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
id2_index = column_names.index("_id2")
id3_index = column_names.index("_id3")
id_index = column_names.index("_id")
if not id_index :
id_index = len(column_names)
column_names.append("_id")
error_index = column_names.index("error")
if not error_index :
error_index = len(column_names)+1
column_names.append("error")
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
row_number = 0
try:
for row in rows_list:
row_id = row[column_names[0]]
qanon_title = row[column_names[1]]
# print(qanon_title)
ts_date = row[column_names[3]]
_id2 = ''
_id3 = ''
if id2_index :
_id2 = row[column_names[id2_index]]
if id3_index :
_id3 = row[column_names[id3_index]]
# print(ts_date)
row_number = row_number + 1
qanon_id = 0
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
state='قانون-جستجو'
qanon_id = 0
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
else :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
qanon_title = get_qanon_title_sample(qanon_title, False)
qanon_title, ts_date, ts_ref = get_qanon_date(qanon_title)
if ts_date or ts_ref :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
if _id3 :
qanon_id=_id3
state = 'دستی-مجلس'
elif score == 80 :
state = 'عنوان-تکراری'
elif score < 80 :
dic_error_qanon_title[qanon_title]= str(count) + ' - ' + str(row_number)
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row["_id"]=qanon_id
row["error"]=state
rows_list_new.append(row)
columns = column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
def parseQaaninKol_SearchQanonTitle(elastic, file_excel, file_log, sheet_name=0, result_path = ""):
# df = pd.read_excel(file_excel, sheet_name=0, header=None)
df = pd.read_excel(file_excel, sheet_name=sheet_name)
count = 0
rows_list = df.to_dict(orient='records')
total = len(rows_list)
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
id_index=30
try:
id_index = column_names.index("_id")
except ValueError:
id_index = len(column_names)
column_names.append("_id")
error_index=30
try:
error_index = column_names.index("error")
except ValueError:
error_index = len(column_names)
column_names.append("error")
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
row_number = 0
try:
for row in rows_list:
if sheet_name == 0 :
qanon_title = row[column_names[4]]
ts_date = row[column_names[6]]
else :
qanon_title = row[column_names[4]]
ts_date = row[column_names[5]]
row_number = row_number + 1
qanon_id = 0
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
state='قانون-جستجو'
qanon_id = 0
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
else :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
qanon_title = get_qanon_title_sample(qanon_title, False)
qanon_title, ts_date, ts_ref = get_qanon_date(qanon_title)
if ts_date or ts_ref :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score == 80 :
state = 'عنوان-تکراری'
elif score < 80 :
dic_error_qanon_title[qanon_title]= str(count) + ' - ' + str(row_number)
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row["_id"]=qanon_id
row["error"]=state
rows_list_new.append(row)
columns = column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_'+str(sheet_name+1) + '_result.xlsx')
new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
def convertField(name ):
base_items = [
{"type": "ابلاغ به رئیس جمهور", "order": 1},
{"type": "توشیح و امضاء قانون", "order": 2},
{"type": "ابلاغ به مجریان", "order": 3},
{"type": "ارسال به روزنامه رسمی", "order": 4},
{"type": "انتشار در روزنامه رسمی", "order": 5},
]
res_type=""
res_order=0
col=""
if name == "شماره":
col= "number"
elif name == "تاریخ اعلام نظر":
col="date"
elif name == "متن نظریه":
col="content"
elif name == "تاریخ ابلاغ به رئیس جمهور":
res_type=base_items[0]["type"]
res_order=base_items[0]["order"]
col="date"
elif name == "شماره ابلاغ به رئیس جمهور":
res_type=base_items[0]["type"]
res_order=base_items[0]["order"]
col="number"
elif name == "تاریخ توشیح و امضا قانون":
res_type=base_items[1]["type"]
res_order=base_items[1]["order"]
col="date"
elif name == "تاریخ ابلاغ به مجریان":
res_type=base_items[2]["type"]
res_order=base_items[2]["order"]
col="date"
elif name == "شماره ابلاغ به مجریان":
res_type=base_items[2]["type"]
res_order=base_items[2]["order"]
col="number"
elif name == "تاریخ ارسال به روزنامه رسمی":
res_type=base_items[3]["type"]
res_order=base_items[3]["order"]
col="date"
elif name == "شماره ارسال به روزنامه رسمی":
res_type=base_items[3]["type"]
res_order=base_items[3]["order"]
col="number"
elif name == "تاریخ انتشار در روزنامه رسمی":
res_type=base_items[4]["type"]
res_order=base_items[4]["order"]
col="date"
elif name == "شماره انتشار در روزنامه رسمی":
res_type=base_items[4]["type"]
res_order=base_items[4]["order"]
col="number"
# elif name == "تاریخ نظریه شورای نگهبان":
# col="date"
# elif name == "شماره نظریه شورای نگهبان":
# col="number"
# elif name == "مغایرت نظریه شورای نگهبان":
# col="content"
# elif name == "استمحالی":
# col=""
# elif name == "استنکافی":
# col=""
# elif name == "دستگاههای اجرایی مرتبط":
# col=""
return col, res_type, res_order
def getDictBeforeInfos(file_excel, sheet_name):
df = pd.read_excel(file_excel, sheet_name=sheet_name)
rows_list = df.to_dict(orient='records')
total = len(rows_list)
print('total : ', total)
column_names = df.columns.tolist()
result={}
try:
for row in rows_list:
row_id = row[column_names[0]]
if sheet_name == 1 : # eblagh
letters = []
letters_dict = {}
for col in column_names:
name, type, order = convertField(col)
if name != '' :
if order not in letters_dict :
letters.append({"order":order, "type":type})
letters_dict[order] = len(letters)-1
index = letters_dict[order]
letters[index][name] = row[col]
elif col == "استمحالی" or name == "استنکافی":
pass
elif col == "دستگاههای اجرایی مرتبط":
result["exceuter_organs"] = row[col]
except Exception as e:
# file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
pass
return result
def parseBeforeInfos_SendData(elastic, file_excel, file_log, result_path = ""):
# df = pd.read_excel(file_excel, sheet_name=0, header=None)
df_main = pd.read_excel(file_excel, sheet_name=0)
count = 0
rows_list = df_main.to_dict(orient='records')
total = len(rows_list)
print('total : ', total)
column_names = df_main.columns.tolist()
print(column_names)
id2_index = column_names.index("_id2")
id3_index = column_names.index("_id3")
id_index = column_names.index("_id")
if not id_index :
id_index = len(column_names)
column_names.append("_id")
error_index = column_names.index("error")
if not error_index :
error_index = len(column_names)+1
column_names.append("error")
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
row_number = 0
try:
for row in rows_list:
row_id = row[column_names[0]]
qanon_title = row[column_names[1]]
# print(qanon_title)
ts_date = row[column_names[3]]
_id2 = ''
_id3 = ''
if id2_index :
_id2 = row[column_names[id2_index]]
if id3_index :
_id3 = row[column_names[id3_index]]
# print(ts_date)
row_number = row_number + 1
qanon_id = 0
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
state='قانون-جستجو'
qanon_id = 0
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
else :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
qanon_title = get_qanon_title_sample(qanon_title, False)
qanon_title, ts_date, ts_ref = get_qanon_date(qanon_title)
if ts_date or ts_ref :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
if _id3 :
qanon_id=_id3
state = 'دستی-مجلس'
elif score == 80 :
state = 'عنوان-تکراری'
elif score < 80 :
dic_error_qanon_title[qanon_title]= str(count) + ' - ' + str(row_number)
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row["_id"]=qanon_id
row["error"]=state
rows_list_new.append(row)
columns = column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
# ---------------------------------------------------------
# ---------------------------------------------------------
load_dotenv(dotenv_path='config.env')
# host=os.getenv('HOST_160')
# password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_112')
# password=os.getenv('HOST_112_PASS')
host=os.getenv('HOST_113')
password=os.getenv('HOST_113_PASS')
print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# ---------------------------------------------------------
# ---------------------------------------------------------
# parseBeforeInfos_SearchQanonTitle(elastic, "./data/جداول بانک قوانین_info-شناسه قانون یار.xlsx" , "./data/result/پیشا قانون.txt", "./data/result/")
#parseQaaninKol_SearchQanonTitle(elastic, "./data/فهرست تمام قوانین.xlsx", "./data/result/فهرست 1 تمام قوانین.txt", 0, "./data/result/")
#parseQaaninKol_SearchQanonTitle(elastic, "./data/فهرست تمام قوانین.xlsx", "./data/result/فهرست 2 تمام قوانین.txt", 1, "./data/result/")
# ---------------------------------------------------------
# ---------------------------------------------------------
parseBeforeInfos_SendData(elastic, "./data/جداول بانک قوانین_info-شناسه قانون یار.xlsx" , "./data/result/پیشا قانون.txt", "./data/result/")
qanon_title=" قانون الحاق دو تبصره به عنوان تبصره های 3 و 4 به ماده 9 قانون روابط موجر و مستأجر مصوب 1362.2.13"
ts_data="1369/07/08"
# qanon_title = get_qanon_title_sample(qanon_title, False)
# print(get_qanon_date(qanon_title))
# searchQanonId(elastic, qanon_title, ts_data)
# searchQanonTitleOfContent(elastic, qanon_title, ts_data)
+170
View File
@@ -0,0 +1,170 @@
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
##--------------------------------
# لازم است این فیلد پرشود تا مجلس بتواند دسترسی تغییر داشته باشد
##------------------------------------
def fill_doc_state( elastic, index_name_i, index_name_o, file_log) :
body = {
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "asc"}}
]
}
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
count = 0
text_normal = TextNormalizer()
result = {}
result_new = {}
total_count = 0
bulk_data = []
bulk_data_section = []
t1= datetime.datetime.now()
print(t1)
file = open(file_log, 'a+', encoding='utf8')
i = 0
doc_tags=[]
qanon_id=0
prev_qanon_id = 0
siyasatha_list = ["qq85859", "qq260090", "qq121403", "qq222873", "qq198729", "qq121413", "qq118359", "qq305009", "qq118373", "qq286578"]
for mentry in list:
entry = mentry["source"]
id = entry.get("id", "")
qanon_id = entry.get("qanon_id", "")
qanon_title = entry.get("qanon_title", "")
nlp_tags = entry.get("nlp_tags", [])
ref_state = entry.get("ref_state", [])
# title_type = entry.get("title_type", "عادی")
title_type = getTitleType(qanon_title)
if prev_qanon_id == 0 :
prev_qanon_id = qanon_id
elif prev_qanon_id != qanon_id :
data={
'_id':prev_qanon_id,
'_source' : {
'doc_tags': doc_tags
}
}
body = {
"script": {
"source": "ctx._source.doc_tags=params.doc_tags",
"lang": "painless",
"params" : { 'doc_tags' : doc_tags }
},
"query": {
"term": {
"qanon_id": { "value" : prev_qanon_id }
}
}
}
elastic.updateByQueryIndex(index_name_i, body)
bulk_data.append(data)
doc_tags=[]
if len(ref_state) > 0 :
if "مهذب" not in doc_tags :
doc_tags.append("مهذب")
elif title_type not in ["عادی", "اصلی", "موافقتنامه", "بودجه"] :
if "تبعی" not in doc_tags :
doc_tags.append("تبعی")
elif title_type in ["عادی", "اصلی", "موافقتنامه", "بودجه"] :
if "اصلی" not in doc_tags :
doc_tags.append("اصلی")
if qanon_id in siyasatha_list :
if "سیاستهای کلی" not in doc_tags :
doc_tags.append("سیاستهای کلی")
if "qanon_usefull" in nlp_tags :
if "پرکاربرد" not in doc_tags :
doc_tags.append("پرکاربرد")
prev_qanon_id = qanon_id
i=i+1
if len(bulk_data) >= 10:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + qanon_id)
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if prev_qanon_id != 0:
data={
'_id':prev_qanon_id,
'_source' : {
'doc_tags': doc_tags
}
}
body = {
"script": {
"source": "ctx._source.doc_tags=params.doc_tags",
"lang": "painless",
"params" : { 'doc_tags' : doc_tags }
},
"query": {
"term": {
"qanon_id": { "value" : prev_qanon_id }
}
}
}
elastic.updateByQueryIndex(index_name_i, body)
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=' + qanon_id )
elastic.updateBulkList(bulk_data, index_name_o)
file.close()
print('end success import_law_section_to_elastic')
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)
# 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))
fill_doc_state( elastic, "mj_qa_section", "mj_qa_qanon", "./output/log_r1.txt")