refactor auto import
This commit is contained in:
@@ -5,7 +5,10 @@ node_modules
|
||||
/html
|
||||
|
||||
|
||||
|
||||
# local env files
|
||||
config.env
|
||||
.env/
|
||||
.env.local
|
||||
.env.*.local
|
||||
/__pycache__
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
from decimal import Decimal
|
||||
from config_base import *
|
||||
from general_functions import *
|
||||
from dotenv import load_dotenv
|
||||
from elastic_helper import ElasticHelper
|
||||
from create_ai_index import *
|
||||
# from move_to_other import *
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
# host=os.getenv('HOST_160_LOCAL')
|
||||
host=os.getenv('HOST_160')
|
||||
password=os.getenv('HOST_160_PASS')
|
||||
print(host)
|
||||
# print(password)
|
||||
|
||||
elastic = ElasticHelper(host, password)
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
### انتقال اطلاعات قبلی به اینجا
|
||||
#elastic.moveCustomFileds("mj_qa_section", "mj_qa_section_temp", ["ners_v1", "nlp_parser", "code-ai"])
|
||||
|
||||
elastic.renameElasticIndex("mj_qa_opinion_temp", "mj_qa_opinion", "majles", "mj_qa_opinion")
|
||||
elastic.renameElasticIndex("mj_qa_qanon_temp", "mj_qa_qanon", "majles", "mj_qa_qanon")
|
||||
elastic.renameElasticIndex("mj_qa_section_temp", "mj_qa_section", "majles", "mj_qa_section")
|
||||
elastic.renameElasticIndex("mj_rg_section_temp", "mj_rg_section", "majles", "mj_qa_section")
|
||||
|
||||
|
||||
ai_url_base=os.getenv("AI_URL_BASE")
|
||||
ai_url_vec=ai_url_base+'/vecsim/vector'
|
||||
# ai_url_class=ai_url_base+'/vec_sim/class'
|
||||
ai_url_class='http://192.168.23.51:6111/class'
|
||||
# ai_url_ner=ai_url_base+'/vec_sim/ner'
|
||||
|
||||
# import_classification(elastic, ai_url_class, "mj_qa_section_temp")
|
||||
# create_ai_Index(elastic, ai_url_vec ,"mj_qa_section_temp", "majles", "mj_qa_section")
|
||||
|
||||
|
||||
# payload={
|
||||
# "text":"سلام علیکم"
|
||||
# }
|
||||
# response = requests.request("POST", ai_url_vec, headers=HEADERS, json=payload)
|
||||
# print(response.text)
|
||||
# print(response)
|
||||
|
||||
|
||||
payload={
|
||||
"text":"طرفین به منظور اتمام مطالعات و احداث نیروگاههای جریانی ارس و تأسیسات مربوطه، منطقه مشترک ساختمانی و مطالعاتی را تعیین و امنیت این منطقه را در طول مدت اجراء و بهرهبرداری تأمین مینمایند. "
|
||||
}
|
||||
response = requests.request("POST", ai_url_class, headers=HEADERS, json=payload)
|
||||
print(response.text)
|
||||
print(response)
|
||||
|
||||
resp = json.loads(response.text)
|
||||
print(resp['result'])
|
||||
|
||||
|
||||
@@ -9,11 +9,11 @@ from s2_LawSection_ToElastic import *
|
||||
from s3_opinion_ToElastic import *
|
||||
from s4_RegulationSection_ToElastic import *
|
||||
from s5_LawSection_update_ref_state import *
|
||||
# from s6_RegulationSection_update_ref_state import *
|
||||
# from s7_LawReg_qanon_ToElastic import *
|
||||
# from s8_Relations_qanon_LWReg import *
|
||||
# from s9_Relations_qanon_opinion import *
|
||||
# from s10_LawReg_lwphase_Info import *
|
||||
from s6_RegulationSection_update_ref_state import *
|
||||
from s7_LawReg_qanon_ToElastic import *
|
||||
from s8_Relations_qanon_LWReg import *
|
||||
from s9_Relations_qanon_opinion import *
|
||||
from s10_LawReg_lwphase_Info import *
|
||||
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
@@ -28,14 +28,13 @@ from s5_LawSection_update_ref_state import *
|
||||
# DELETE mj_qa_opinion_temp
|
||||
# -----------------------------------------------------------------
|
||||
|
||||
|
||||
cursor, cnxn = create_cursor()
|
||||
|
||||
### ایجاد فهرست موضوعات قانون
|
||||
# projectid = insertProejct()
|
||||
# insertProjectItems(cursor, projectid)
|
||||
## ایجاد فهرست موضوعات قانون
|
||||
projectid = insertProejct()
|
||||
insertProjectItems(cursor, projectid)
|
||||
|
||||
## 2
|
||||
# 2
|
||||
import_law_section_to_elastic(cursor)
|
||||
|
||||
|
||||
@@ -44,9 +43,25 @@ import_opinion_to_elastic(cursor)
|
||||
|
||||
import_regulation_section_to_elastic(cursor)
|
||||
|
||||
### از ابتدا تا اینجا حدودا 24 ساعت کشید
|
||||
|
||||
|
||||
import_law_section_update_ref_state(cursor)
|
||||
|
||||
|
||||
import_regulation_section_update_ref_state(cursor)
|
||||
|
||||
|
||||
import_law_reg_qanon_to_elastic(cursor)
|
||||
|
||||
## تا اینجا رسید و خطا داد
|
||||
import_relations_qanon_lwreg(cursor)
|
||||
|
||||
## اینجا خطا داد
|
||||
import_relations_qanon_opinion(cursor)
|
||||
|
||||
|
||||
import_lawreg_lwphase_info(cursor)
|
||||
|
||||
cursor.close()
|
||||
cnxn.close()
|
||||
@@ -0,0 +1,139 @@
|
||||
from time import time
|
||||
import requests
|
||||
from general_functions import *
|
||||
from config_base import *
|
||||
|
||||
def create_ai_Index(elasticHelper, index_name, app_key, map_file="") :
|
||||
elasticHelper.createIndex(index_name, app_key, 'general/', map_file )
|
||||
|
||||
def import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_section", index_name_o = "mj_qa_section_ai", field_content="content") :
|
||||
counter = 0
|
||||
total = 0
|
||||
id = ""
|
||||
body={}
|
||||
|
||||
dicIds = {}
|
||||
try:
|
||||
try:
|
||||
list = elasticHelper.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
count = 0
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
|
||||
id = entry.get("id", "")
|
||||
content = entry.get(field_content, "")
|
||||
data = entry
|
||||
if content :
|
||||
payload={
|
||||
'text':content
|
||||
}
|
||||
response = requests.request("POST", ai_url_vec, headers=HEADERS, json=payload)
|
||||
if response.status_code == 500 :
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
continue
|
||||
|
||||
resp = json.loads(response.text)
|
||||
data["embeddings"]=resp['result']
|
||||
|
||||
update = False
|
||||
|
||||
eid = id
|
||||
try:
|
||||
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
|
||||
if not update :
|
||||
dicIds[eid] = True
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
# print("Exception: " + str(e))
|
||||
# print( e)
|
||||
# print("%s -> %.2f " % (id , (counter / total) if total > 0 else 0))
|
||||
|
||||
# try:
|
||||
# print('ts_date:'+ts_date)
|
||||
# except:
|
||||
# print('not definded')
|
||||
|
||||
|
||||
print("=" * 10, "setting finished")
|
||||
|
||||
def import_classification(elasticHelper, ai_url_class, index_name_o = "mj_qa_section_ai") :
|
||||
counter = 0
|
||||
total = 0
|
||||
id = ""
|
||||
body={
|
||||
"query": {
|
||||
"bool": {
|
||||
"must_not": [
|
||||
{
|
||||
"exists": {
|
||||
"field": "code-ai"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dicIds = {}
|
||||
try:
|
||||
try:
|
||||
list = elasticHelper.es_iterate_all_documents(index_name_o, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
count = 0
|
||||
print('*' * 20 , ' count=', elasticHelper.total)
|
||||
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
|
||||
id = entry.get("id", "")
|
||||
content = entry.get("content", "")
|
||||
data = {}
|
||||
if content :
|
||||
payload={
|
||||
'text':content
|
||||
}
|
||||
response = requests.request("POST", ai_url_class, headers=HEADERS, json=payload)
|
||||
if response.status_code == 500 :
|
||||
print(response.text)
|
||||
continue
|
||||
|
||||
resp = json.loads(response.text)
|
||||
data["code-ai"]=resp['result']
|
||||
|
||||
update = True
|
||||
|
||||
eid = id
|
||||
try:
|
||||
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
|
||||
if not update :
|
||||
dicIds[eid] = True
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
# print("Exception: " + str(e))
|
||||
# print( e)
|
||||
# print("%s -> %.2f " % (id , (counter / total) if total > 0 else 0))
|
||||
|
||||
# try:
|
||||
# print('ts_date:'+ts_date)
|
||||
# except:
|
||||
# print('not definded')
|
||||
|
||||
|
||||
print("=" * 10, " finished")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
import zipfile
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from time import sleep
|
||||
from elasticsearch import Elasticsearch,helpers
|
||||
|
||||
class ElasticHelper():
|
||||
|
||||
counter = 0
|
||||
total = 0
|
||||
id = ""
|
||||
|
||||
def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic"):
|
||||
if es_pass == '' :
|
||||
self.es = Elasticsearch(es_url)
|
||||
else:
|
||||
self.es = Elasticsearch(
|
||||
es_url,
|
||||
http_auth=(es_user, es_pass),
|
||||
)
|
||||
|
||||
# print(es_url)
|
||||
# print(self.es)
|
||||
|
||||
self.success_connect = False
|
||||
for a in range(0,10):
|
||||
try :
|
||||
if not self.es.ping():
|
||||
sleep(30)
|
||||
continue
|
||||
else:
|
||||
self.success_connect = True
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
break
|
||||
if not self.success_connect :
|
||||
print('******','not access to elastic service')
|
||||
return
|
||||
|
||||
|
||||
self.counter = 0
|
||||
self.total = 0
|
||||
self.id = ""
|
||||
|
||||
|
||||
def update_index_doc(self, is_update_state, index_name_o, eid, data):
|
||||
if is_update_state:
|
||||
resp = self.es.update(index=index_name_o, id=eid, doc=data)
|
||||
# resp = self.es.update(index=index_name_o, id=eid, body={'doc':data})
|
||||
else:
|
||||
resp = self.es.index(index=index_name_o, id=eid, document=data)
|
||||
return resp
|
||||
|
||||
|
||||
def backupIndexToZipfile(self, path_back, index_name, out_name, query={}, byzip = True) :
|
||||
print('*' * 50, ' start backup -->', index_name)
|
||||
self.counter = 0
|
||||
out = out_name
|
||||
|
||||
if byzip:
|
||||
fout = zipfile.ZipFile(path_back + "/"+ out + '.zip', 'w')
|
||||
else:
|
||||
fout = open( path_back + "/"+ out + '.json', 'a+' , encoding='utf-8')
|
||||
|
||||
s_res = self.es.search(
|
||||
index=index_name,
|
||||
scroll='5m',
|
||||
size=1000,
|
||||
body=query
|
||||
)
|
||||
self.total = s_res["hits"]["total"]['value']
|
||||
|
||||
print('start index = %s' % index_name)
|
||||
print('total = %d' % self.total)
|
||||
|
||||
sid = s_res['_scroll_id']
|
||||
scroll_size = len(s_res['hits']['hits'])
|
||||
file_count = 1
|
||||
while scroll_size > 0:
|
||||
"Scrolling..."
|
||||
self.counter += scroll_size
|
||||
print("progress -> %.2f %%" % ((self.counter / self.total)*100))
|
||||
#############################
|
||||
out_json = []
|
||||
for item in s_res['hits']['hits']:
|
||||
out_json.append(item)
|
||||
|
||||
|
||||
text = json.dumps(out_json, ensure_ascii=False)
|
||||
if byzip:
|
||||
filename = out + str(file_count) + '.json'
|
||||
file_count +=1
|
||||
fout.writestr(filename, text.encode('utf-8'), zipfile.ZIP_DEFLATED )
|
||||
else:
|
||||
fout.write(text)
|
||||
|
||||
##############################
|
||||
s_res = self.es.scroll(scroll_id=sid, scroll='2m', request_timeout=100000)
|
||||
sid = s_res['_scroll_id']
|
||||
scroll_size = len(s_res['hits']['hits'])
|
||||
|
||||
|
||||
def renameElasticIndex(self, index_name_i, index_name_o, app_key = '', map_name='') :
|
||||
if self.createIndex(index_name_o, app_key, map_name) :
|
||||
self.es.reindex(
|
||||
body={
|
||||
"source": {"index": index_name_i},
|
||||
"dest": {"index": index_name_o}
|
||||
},
|
||||
wait_for_completion=True)
|
||||
|
||||
|
||||
|
||||
|
||||
def restorFileToElastic(self, path_back, index_name, app_key = '', queryDelete = True) :
|
||||
if not os.path.exists(path_back) :
|
||||
return False
|
||||
|
||||
file_path = path_back + '/' + index_name + '.zip'
|
||||
if not os.path.exists(file_path ) :
|
||||
return False
|
||||
|
||||
if queryDelete :
|
||||
# اگر وجود داشته باشد، از کاربر برای حذفش سوال میکند
|
||||
if self.deleteIndex(index_name) :
|
||||
self.createIndex(index_name, app_key)
|
||||
self.zipFileToElastic(file_path, index_name)
|
||||
else : # اگر وجود داشته باشد پرش می کند و کاری نمیکند
|
||||
self.createIndex(index_name, app_key)
|
||||
self.zipFileToElastic(file_path, index_name)
|
||||
|
||||
def deleteIndex(self, index_name) :
|
||||
if not self.es.indices.exists(index=index_name) :
|
||||
print(' ' * 10, " for delete NOT exist index :", index_name )
|
||||
return True
|
||||
|
||||
question = 'Is DELETE elastic index (' + index_name +') ? '
|
||||
if self.query_yes_no(question) :
|
||||
self.es.indices.delete(index = index_name)
|
||||
print('%' * 10 , " Finish DELETE index :", index_name )
|
||||
return True
|
||||
else :
|
||||
return False
|
||||
|
||||
def query_yes_no(self, question, default="no"):
|
||||
valid = { "yes": True, "y": True, "ye": True, "no": False, "n": False }
|
||||
if default is None:
|
||||
prompt = " [y/n] "
|
||||
elif default == "yes":
|
||||
prompt = " [Y/n] "
|
||||
elif default == "no":
|
||||
prompt = " [y/N] "
|
||||
else:
|
||||
raise ValueError("invalid default answer: '%s'" % default)
|
||||
|
||||
while True:
|
||||
print('%'*10, ' quistion ', '%'*10 , '\n')
|
||||
sys.stdout.write(question + prompt)
|
||||
choice = input().lower()
|
||||
if default is not None and choice == "":
|
||||
return valid[default]
|
||||
elif choice in valid:
|
||||
return valid[choice]
|
||||
else:
|
||||
sys.stdout.write("لطفا یکی از موارد روبرو را وارد کنید : 'yes' or 'no' " "(or 'y' or 'n').\n")
|
||||
|
||||
def createIndexIfNotExist(self, index_name_o, mapping_o=""):
|
||||
try:
|
||||
if not self.es.indices.exists(index=index_name_o):
|
||||
response = self.es.indices.create(index=index_name_o, body=mapping_o)
|
||||
# print out the response:
|
||||
print("create index response:", response)
|
||||
except:
|
||||
print("....... index exist ! ... not created")
|
||||
|
||||
|
||||
def createIndex(self, index_name, app_key='', sub_path='general/', map_name=''):
|
||||
|
||||
path_base = os.getcwd() + '/repo/_other/'
|
||||
path_mapping1 = path_base + 'general/'
|
||||
if app_key == '' :
|
||||
app_key = 'tavasi'
|
||||
path_mapping2 = path_base + app_key + '/'
|
||||
|
||||
|
||||
if map_name == '':
|
||||
map_name = index_name
|
||||
|
||||
if self.es.indices.exists(index=index_name) :
|
||||
print("============== exist index :", index_name )
|
||||
return True
|
||||
|
||||
path_mapping = path_base + sub_path
|
||||
mapping_file_path = path_mapping + map_name + '.json'
|
||||
print("mapping_file_path : " , mapping_file_path)
|
||||
if not os.path.isfile(mapping_file_path):
|
||||
# if map_name[-3]=='_ai':
|
||||
# map_name=[0-len(map_name)-3]
|
||||
# print(map_name)
|
||||
# el
|
||||
if map_name == 'mj_rg_section' or map_name == 'semantic_search' :
|
||||
map_name = 'mj_qa_section'
|
||||
mapping_file_path = path_mapping + map_name + '.json'
|
||||
|
||||
if not os.path.isfile(mapping_file_path):
|
||||
mapping_file_path = path_mapping1 + map_name + '.json'
|
||||
if not os.path.isfile(mapping_file_path):
|
||||
mapping_file_path = path_mapping2 + map_name + '.json'
|
||||
|
||||
print("mapping_file_path : " , mapping_file_path)
|
||||
|
||||
|
||||
# Create Index With Mapping
|
||||
if os.path.isfile(mapping_file_path):
|
||||
mapping_file =open(mapping_file_path,'r')
|
||||
mapping_file_read = mapping_file.read()
|
||||
mapping_data = json.loads(mapping_file_read)
|
||||
mapping_file.close()
|
||||
if self.es.indices.exists(index=index_name) :
|
||||
print("============== exist index :", index_name )
|
||||
return True
|
||||
self.es.indices.create(index = index_name , body = mapping_data)
|
||||
else:
|
||||
print('*** error not find maping file elastic : *******', mapping_file_path)
|
||||
return False
|
||||
|
||||
|
||||
def importJsonDataToElastic(self, jsonData, index_name):
|
||||
chunk_size=100000
|
||||
raise_on_error=False
|
||||
raise_on_exception=False
|
||||
stats_only=True
|
||||
yield_ok = False
|
||||
|
||||
for item in jsonData:
|
||||
actions = [{
|
||||
"_op_type": "index",
|
||||
"_index": index_name,
|
||||
"_id" : item['_id'],
|
||||
"_source": item['_source']
|
||||
}
|
||||
]
|
||||
helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok )
|
||||
# actions = []
|
||||
# for item in jsonData:
|
||||
# actions.append(
|
||||
# {
|
||||
# "_op_type": "index",
|
||||
# "_index": index_name,
|
||||
# "_id" : item['_id'],
|
||||
# "_source": item['_source']
|
||||
# }
|
||||
# )
|
||||
|
||||
# helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok )
|
||||
# self.es.indices.refresh(index=index_name)
|
||||
# self.counter = self.es.cat.count(index=index_name, format="json")
|
||||
# print('-' * 5, 'import data count : ', str(self.counter), '\n' )
|
||||
|
||||
|
||||
def fileToElastic(self, file_path, index_name, limit_pack = -1):
|
||||
if not os.path.exists(file_path):
|
||||
print("file zip:" , file_path , " not exist")
|
||||
return
|
||||
print("index:" , index_name , '=>' , file_path )
|
||||
self.counter = 0
|
||||
with open(file_path) as file:
|
||||
data = json.loads(file.read())
|
||||
self.importJsonDataToElastic(data, index_name)
|
||||
|
||||
self.es.indices.refresh(index=index_name)
|
||||
print(self.es.cat.count(index=index_name, format="json"))
|
||||
|
||||
def zipFileToElastic(self, file_path, index_name, limit_pack = -1):
|
||||
if not os.path.exists(file_path):
|
||||
print("file zip:" , file_path , " not exist for imort to elastic : ", index_name )
|
||||
return
|
||||
|
||||
fileNo = 0
|
||||
with zipfile.ZipFile(file_path, 'r') as zObject:
|
||||
fileNo +=1
|
||||
print("="*10, " zip fileNo: " , fileNo ," - ( ", index_name," ) | File Numbers:" ,len(zObject.namelist()) , "=" * 10)
|
||||
|
||||
packNo = 0
|
||||
self.counter = 0
|
||||
for filename in zObject.namelist():
|
||||
packNo += 1
|
||||
if limit_pack != -1 :
|
||||
if packNo > limit_pack :
|
||||
print('limit_data ', index_name, ' ', limit_pack)
|
||||
break
|
||||
|
||||
print("index:" , index_name , '=>' , filename )
|
||||
with zObject.open(filename) as file:
|
||||
data = json.loads(file.read())
|
||||
self.importJsonDataToElastic(data, index_name)
|
||||
|
||||
self.es.indices.refresh(index=index_name)
|
||||
print(self.es.cat.count(index=index_name, format="json"))
|
||||
print(" END Of Import to elastic ", index_name ,"\n")
|
||||
|
||||
|
||||
|
||||
def es_iterate_all_documents(self, index, body="", pagesize=250, scroll_timeout="25m", **kwargs):
|
||||
"""
|
||||
Helper to iterate ALL values from a single index
|
||||
Yields all the documents.
|
||||
"""
|
||||
is_first = True
|
||||
while True:
|
||||
# Scroll next
|
||||
if is_first: # Initialize scroll
|
||||
# result = self.es.search(index=index, scroll="2m", **kwargs, body={
|
||||
# "size": pagesize
|
||||
# })
|
||||
if body :
|
||||
result = self.es.search(
|
||||
index=index,
|
||||
scroll=scroll_timeout,
|
||||
**kwargs,
|
||||
size=pagesize,
|
||||
body=body
|
||||
)
|
||||
else :
|
||||
result = self.es.search(
|
||||
index=index,
|
||||
scroll=scroll_timeout,
|
||||
**kwargs,
|
||||
size=pagesize
|
||||
)
|
||||
|
||||
self.total = result["hits"]["total"]["value"]
|
||||
if self.total > 0:
|
||||
print("total = %d" % self.total)
|
||||
is_first = False
|
||||
else:
|
||||
# result = es.scroll(body={
|
||||
# "scroll_id": scroll_id,
|
||||
# "scroll": scroll_timeout
|
||||
# })
|
||||
result = self.es.scroll(scroll_id=scroll_id, scroll=scroll_timeout)
|
||||
|
||||
scroll_id = result["_scroll_id"]
|
||||
hits = result["hits"]["hits"]
|
||||
self.counter += len(hits)
|
||||
if self.total > 0 :
|
||||
print("progress -> %.2f %%" % ((self.counter / self.total) * 100))
|
||||
# Stop after no more docs
|
||||
if not hits:
|
||||
break
|
||||
# Yield each entry
|
||||
yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in hits)
|
||||
|
||||
|
||||
def moveCustomFileds(self, index_name_i, index_name_o, fields=[], renameFileds={}):
|
||||
try:
|
||||
body = {}
|
||||
list = []
|
||||
try:
|
||||
list = self.es_iterate_all_documents(index_name_i)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
count = 0
|
||||
for mentry in list:
|
||||
count += 1
|
||||
|
||||
entry = mentry["source"]
|
||||
id = mentry["id"]
|
||||
# print(id)
|
||||
eid = id
|
||||
|
||||
if (count % 100) == 0 :
|
||||
print("%s -> %.2f " % (id , (count / self.total) if self.total > 0 else 0))
|
||||
|
||||
data_filled = False
|
||||
data = {}
|
||||
for col in fields:
|
||||
|
||||
if '.' in col :
|
||||
cols = col.split('.')
|
||||
subsource = entry
|
||||
for sub in cols :
|
||||
dCol = subsource.get(sub, None)
|
||||
if dCol :
|
||||
subsource = dCol
|
||||
else :
|
||||
break
|
||||
else :
|
||||
dCol = entry.get(col, None)
|
||||
|
||||
if dCol is None:
|
||||
continue
|
||||
|
||||
if col in renameFileds :
|
||||
data[renameFileds[col]] = dCol
|
||||
else:
|
||||
data[col] = dCol
|
||||
|
||||
data_filled = True
|
||||
|
||||
if not data_filled :
|
||||
continue
|
||||
|
||||
try:
|
||||
resp = self.update_index_doc(True, index_name_o, eid, data)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
# save_error(id, e)
|
||||
|
||||
except Exception as e:
|
||||
# print("1111")
|
||||
print(e)
|
||||
|
||||
# save_error(id, e)
|
||||
@@ -1,3 +0,0 @@
|
||||
:: G:\Project2\NLP\SqlToElasticMajles\import_all.bat >> import_all.txt 2>&1
|
||||
|
||||
python .\1_LWTopic.py > output1.txt
|
||||
@@ -1,15 +0,0 @@
|
||||
:: G:\Project2\NLP\SqlToElasticMajles\import_all.bat >> import_all.txt 2>&1
|
||||
|
||||
:: python .\1_LWTopic.py > output1.txt
|
||||
:: python .\2_LawSection_ToElastic.py > output2.txt
|
||||
:: python .\3_opinion_ToElastic.py > output3.txt
|
||||
:: python .\4_RegulationSection_ToElastic.py > output4.txt
|
||||
:: python .\5_LawSection_update_ref_state.py > output5.txt
|
||||
:: python .\6_RegulationSection_update_ref_state.py > output6.txt
|
||||
|
||||
:: python .\7_LawReg_qanon_ToElastic.py > output7.txt
|
||||
python .\8_Relations_qanon_LWReg.py > output8.txt
|
||||
|
||||
python .\9_Relations_qanon_opinion.py > output9.txt
|
||||
|
||||
:: python .\10_LawReg_lwphase_Info.py > output10.txt
|
||||
@@ -0,0 +1,167 @@
|
||||
from general_functions import *
|
||||
|
||||
# هدف تغییر در قالب شناسه قانون برای سادگی بیشتر بود
|
||||
# mj_qa_qavanin_1234 --> qq1234
|
||||
def changeIdbyCopyToNewIndex(elastic, index_name_i, index_name_o, is_update_state):
|
||||
try:
|
||||
body = {}
|
||||
try:
|
||||
list = elastic.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
count = 0
|
||||
novalid = -15000000000
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
id = "qs" + str(int(entry.get("ref_id", "")))
|
||||
eid = id
|
||||
|
||||
data = entry
|
||||
data["id"] = eid
|
||||
data["parent_id"] = str(data["parent_id"]).replace("mj_qa_section_", "qs")
|
||||
data["qanon_id"] = str(data["qanon_id"]).replace("mj_qa_qavanin_", "qq")
|
||||
if "nlp_parser" in data:
|
||||
for i in range(len(data["nlp_parser"])):
|
||||
if (
|
||||
"law_id" in data["nlp_parser"][i]
|
||||
and data["nlp_parser"][i]["law_id"] != 0
|
||||
):
|
||||
data["nlp_parser"][i]["qanon_id"] = "qq" + str(
|
||||
data["nlp_parser"][i]["law_id"]
|
||||
)
|
||||
|
||||
if "ref_state" in data:
|
||||
for i in range(len(data["ref_state"])):
|
||||
if "section_id" in data["ref_state"][i]:
|
||||
data["ref_state"][i]["section_id"] = str(data["ref_state"][i]["section_id"]).replace("mj_qa_section_", "qs")
|
||||
if "qanon_id" in data["ref_state"][i]:
|
||||
data["ref_state"][i]["qanon_id"] = str(data["ref_state"][i]["qanon_id"]).replace("mj_qa_qavanin_", "qq")
|
||||
|
||||
try:
|
||||
resp = elastic.update_index_doc(
|
||||
is_update_state, index_name_o, eid, data
|
||||
)
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
except Exception as e:
|
||||
# print(repr(e))
|
||||
# exit
|
||||
save_error(id, e)
|
||||
|
||||
|
||||
|
||||
# فعالیتهای گروه مدل سازی منتقل شود
|
||||
def moveEmbedingsToNewIndex(elastic, index_name_i, index_name_o):
|
||||
try:
|
||||
body = {}
|
||||
# body = {"query": {"match": {"qanon_id": "mj_qa_qavanin_303040"}}}
|
||||
try:
|
||||
list = elastic.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
count = 0
|
||||
novalid = -15000000000
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
id = "qs" + str(int(entry.get("ref_id", "")))
|
||||
eid = id
|
||||
|
||||
rules = entry.get("embeddings", [])
|
||||
data = {"embeddings": rules}
|
||||
|
||||
try:
|
||||
resp = elastic.update_index_doc(True, index_name_o, eid, data)
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
# فعالیتهای گروه مدل سازی منتقل شود
|
||||
def moveRulesToNewIndex(elastic, index_name_i, index_name_o):
|
||||
try:
|
||||
body = {"query": {"bool": {"must": [{"exists": {"field": "rules.state"}}]}}}
|
||||
try:
|
||||
list = elastic.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
count = 0
|
||||
novalid = -15000000000
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
id = "qs" + str(int(entry.get("ref_id", "")))
|
||||
eid = id
|
||||
|
||||
rules = entry.get("rules", [])
|
||||
data = {"rules": rules}
|
||||
|
||||
try:
|
||||
resp = elastic.update_index_doc(True, index_name_o, eid, data)
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
|
||||
def moveCustomFileds(elastic, index_name_i, index_name_o, fields=[], body = {}):
|
||||
|
||||
try:
|
||||
|
||||
try:
|
||||
list = elastic.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
count = 0
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
id = mentry["id"]
|
||||
eid = id
|
||||
|
||||
if (count % 100) == 0 :
|
||||
print("%s -> %.2f " % (id , (count / elastic.total) if elastic.total > 0 else 0))
|
||||
|
||||
data_filled = False
|
||||
data = {}
|
||||
for col in fields:
|
||||
dCol = entry.get(col, None)
|
||||
if dCol is None:
|
||||
continue
|
||||
data[col] = dCol
|
||||
data_filled = True
|
||||
|
||||
if not data_filled :
|
||||
continue
|
||||
|
||||
try:
|
||||
resp = elastic.update_index_doc(True, index_name_o, eid, data)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
# save_error(id, e)
|
||||
|
||||
except Exception as e:
|
||||
print("1111")
|
||||
print(e)
|
||||
|
||||
# save_error(id, e)
|
||||
|
||||
|
||||
# elastic = ElasticHelper("http://127.0.0.1:6900", "FuVur05YO60I7YWIP*lc")
|
||||
# elastic.checkIndex(index_name_o)
|
||||
|
||||
#copyToNewIndex(elastic, "mj_qa_section-v05", "mj_qa_section-v01", False)
|
||||
#print("**********copyToNewIndex finished**********")
|
||||
# moveEmbedingsToNewIndex(elastic, "semantic_search-v06", "mj_qa_section-v02")
|
||||
# print("**********moveEmbedings finished**********")
|
||||
# moveRulesToNewIndex(elastic, "qanon_section-v02", "mj_qa_section-v02")
|
||||
# moveCustomFileds(elastic, "mj_qa_section-v01", "mj_qa_section-v02", ["ners_v1", "nlp_parser", "code-ai"])
|
||||
# print("finished")
|
||||
@@ -0,0 +1,5 @@
|
||||
requests
|
||||
python-dotenv
|
||||
pyodbc
|
||||
bs4
|
||||
elasticsearch
|
||||
@@ -7,10 +7,9 @@ from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
|
||||
|
||||
from config_base import *
|
||||
from general_functions import *
|
||||
from text_normalizer import TextNormalizer
|
||||
|
||||
def import_lawreg_lwphase_info(cursor):
|
||||
query='SELECT ID,CAPTION FROM [Qavanin].[dbo].[cmOrganization]'
|
||||
@@ -27,7 +26,7 @@ def import_lawreg_lwphase_info(cursor):
|
||||
rr = {"id" : int(row.ID), 'title': row.CAPTION}
|
||||
ORG_DICT[str(int(row.ID))] = {"id" : row.ID, 'title': row.CAPTION}
|
||||
|
||||
#نکته : برای مقررات هیچ موردی نبود که جدولی باشد
|
||||
|
||||
query = '''
|
||||
|
||||
SELECT
|
||||
@@ -49,6 +48,7 @@ def import_lawreg_lwphase_info(cursor):
|
||||
'''
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
|
||||
url = BASE_URL + "repo/majles/qaqanon/multi/update"
|
||||
@@ -185,6 +185,7 @@ def import_lawreg_lwphase_info(cursor):
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(bulk_data)
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
@@ -202,7 +203,8 @@ def import_lawreg_lwphase_info(cursor):
|
||||
print('=' * 10, ' lawreg_lwphase_info , total='+str(total_count) )
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code == 500 :
|
||||
if response.status_code != 200 :
|
||||
print(bulk_data)
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ def import_regulation_section_update_ref_state(cursor):
|
||||
|
||||
'''
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
|
||||
url = BASE_URL + "repo/majles/rgsection/multi/update"
|
||||
@@ -127,16 +128,15 @@ def import_regulation_section_update_ref_state(cursor):
|
||||
ref_state = {
|
||||
"id" : row.id,
|
||||
"qanon_id": efect_qanon_id,
|
||||
"qanon_title" : normalYehKe(row.effect_qanon),
|
||||
"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" : normalYehKe(row.effect_text),
|
||||
"prev_text" : normalYehKe(row.effect_prev_text),
|
||||
"description" : normalYehKe(row.description)
|
||||
}
|
||||
"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 :
|
||||
|
||||
@@ -56,6 +56,7 @@ def import_law_reg_qanon_to_elastic(cursor):
|
||||
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
|
||||
url = BASE_URL + "repo/majles/qaqanon/multi/add"
|
||||
@@ -80,7 +81,7 @@ def import_law_reg_qanon_to_elastic(cursor):
|
||||
# print(row.sectionId)
|
||||
|
||||
|
||||
title = normalYehKe( row.title )
|
||||
title = text_normal.normalize_qanon( row.title )
|
||||
title_type = getTitleType(title)
|
||||
|
||||
eid='qq'+ str(row.Id)
|
||||
@@ -127,7 +128,7 @@ def import_law_reg_qanon_to_elastic(cursor):
|
||||
|
||||
qanon_etebar = ''
|
||||
if row.qanon_etebar :
|
||||
qanon_etebar = row.qanon_etebar
|
||||
qanon_etebar = normalYehKe(row.qanon_etebar)
|
||||
|
||||
|
||||
data={
|
||||
|
||||
@@ -7,10 +7,9 @@ from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
|
||||
|
||||
from config_base import *
|
||||
from general_functions import *
|
||||
from text_normalizer import TextNormalizer
|
||||
|
||||
|
||||
def import_relations_qanon_lwreg(cursor):
|
||||
@@ -38,6 +37,7 @@ def import_relations_qanon_lwreg(cursor):
|
||||
"""
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
url = BASE_URL + "repo/majles/qaqanon/multi/update"
|
||||
|
||||
@@ -105,9 +105,9 @@ def import_relations_qanon_lwreg(cursor):
|
||||
|
||||
from_section_title = ''
|
||||
if row.from_section_title :
|
||||
from_section_title = row.from_section_title
|
||||
from_section_title = text_normal.normalize_qanon(row.from_section_title)
|
||||
|
||||
to_title = normalYehKe( row.to_title )
|
||||
to_title = text_normal.normalize_qanon( row.to_title )
|
||||
to_type = row.to_type
|
||||
|
||||
|
||||
@@ -140,8 +140,8 @@ def import_relations_qanon_lwreg(cursor):
|
||||
}
|
||||
|
||||
total_count = total_count+1
|
||||
if total_count < 2560 :
|
||||
continue
|
||||
# if total_count < 2560 :
|
||||
# continue
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
@@ -198,12 +198,14 @@ def import_relations_qanon_lwreg(cursor):
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code == 500 :
|
||||
if response.status_code != 200 :
|
||||
print(bulk_data)
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
|
||||
bulk_data = pops_data
|
||||
if not bulk_data :
|
||||
break
|
||||
|
||||
|
||||
t2= datetime.datetime.now()
|
||||
|
||||
@@ -7,10 +7,9 @@ from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
|
||||
|
||||
from config_base import *
|
||||
from general_functions import *
|
||||
from text_normalizer import TextNormalizer
|
||||
|
||||
def import_relations_qanon_opinion(cursor):
|
||||
# اجرای کوئری SQL و خواندن دادهها به یک DataFrame
|
||||
@@ -39,6 +38,7 @@ def import_relations_qanon_opinion(cursor):
|
||||
"""
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
url = BASE_URL + "repo/majles/qaqanon/multi/update"
|
||||
|
||||
@@ -95,9 +95,9 @@ def import_relations_qanon_opinion(cursor):
|
||||
|
||||
from_section_title = ''
|
||||
if row.from_section_title :
|
||||
from_section_title = row.from_section_title
|
||||
from_section_title = text_normal.normalize_qanon(row.from_section_title)
|
||||
|
||||
to_title = normalYehKe( row.to_title )
|
||||
to_title = text_normal.normalize_qanon( row.to_title )
|
||||
|
||||
|
||||
to_type = ''
|
||||
@@ -164,7 +164,8 @@ def import_relations_qanon_opinion(cursor):
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code == 500 :
|
||||
if response.status_code != 200 :
|
||||
print(bulk_data)
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
@@ -176,7 +177,7 @@ def import_relations_qanon_opinion(cursor):
|
||||
|
||||
|
||||
|
||||
if len(relations) :
|
||||
if len(relations) > 0 :
|
||||
data={
|
||||
'id' : prev_eid,
|
||||
'opinion_relations' : relations
|
||||
@@ -197,10 +198,13 @@ def import_relations_qanon_opinion(cursor):
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(bulk_data)
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
|
||||
bulk_data = pops_data
|
||||
if not bulk_data :
|
||||
break
|
||||
|
||||
|
||||
t2= datetime.datetime.now()
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
python.exe .\6_RegulationSection_update_ref_state.py
|
||||
|
||||
python.exe .\8_Tanghih_plan_move.py
|
||||
|
||||
|
||||
python.exe .\20_LawReg_qanon_ToElastic.py
|
||||
|
||||
python.exe .\21_Relations_qanon_LWReg.py
|
||||
|
||||
python.exe .\22_Relations_qanon_opinion.py
|
||||
@@ -24,7 +24,7 @@ class JSONEncoder(json.JSONEncoder):
|
||||
return float(obj)
|
||||
return json.JSONEncoder.default(self, obj)
|
||||
|
||||
#نکته : برای مقررات هیچ موردی نبود که جدولی باشد
|
||||
|
||||
query = '''
|
||||
SELECT s.ID as sectionId
|
||||
,isnull(lss2.CAPTION,'') as qanon_etebar -- lwLawSectionStatus_table: ... منسوخه، معتبر، اصلاحی، موقت و
|
||||
|
||||
@@ -24,7 +24,7 @@ class JSONEncoder(json.JSONEncoder):
|
||||
return float(obj)
|
||||
return json.JSONEncoder.default(self, obj)
|
||||
|
||||
#نکته : برای مقررات هیچ موردی نبود که جدولی باشد
|
||||
|
||||
query = '''
|
||||
SELECT s.ID as sectionId
|
||||
,isnull(lss2.CAPTION,'') as qanon_etebar -- lwLawSectionStatus_table: ... منسوخه، معتبر، اصلاحی، موقت و
|
||||
|
||||
@@ -24,7 +24,7 @@ class JSONEncoder(json.JSONEncoder):
|
||||
return float(obj)
|
||||
return json.JSONEncoder.default(self, obj)
|
||||
|
||||
#نکته : برای مقررات هیچ موردی نبود که جدولی باشد
|
||||
|
||||
query = '''SELECT * FROM [Qavanin].[dbo].[lwLaw]
|
||||
where ISLAW=1
|
||||
'''
|
||||
|
||||
+748
@@ -0,0 +1,748 @@
|
||||
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 sys
|
||||
import traceback
|
||||
import re
|
||||
from jalali import Persian
|
||||
from config_base import *
|
||||
from general_functions import *
|
||||
from thefuzz import fuzz
|
||||
|
||||
|
||||
def read_section_table():
|
||||
cursor, cnxn = create_cursor()
|
||||
query = """SELECT s.ID as section_id,s.SECTIONTEXT as section_text, l.ID as law_id, l.ISLAW as law_islaw
|
||||
from lwSection s
|
||||
left join lwLaw l on s.F_LWLAWID = l.ID
|
||||
where l.ISLAW = 1"""
|
||||
|
||||
cursor.execute(query)
|
||||
|
||||
section_list = {}
|
||||
i = 0
|
||||
for item in cursor.fetchall():
|
||||
i += 1
|
||||
# if i == 10000:# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! برداشته شود
|
||||
# break
|
||||
# if i%1000 == 0:
|
||||
# print(i)
|
||||
# row = cursor.fetchone()
|
||||
id = int(item.section_id)
|
||||
try:
|
||||
text = removeHtmlNoTableTag(item.section_text)
|
||||
except Exception as e:
|
||||
text = item.section_text
|
||||
section_text = normalize_content(text)
|
||||
section_list[id] = {"id": id, "section_text": section_text}
|
||||
cursor.close()
|
||||
cnxn.close()
|
||||
return section_list
|
||||
|
||||
|
||||
def read_law_table():
|
||||
cursor, cnxn = create_cursor()
|
||||
query = """SELECT [ID],[CAPTION],[APPROVEDATE]
|
||||
FROM [Qavanin].[dbo].[lwLaw]
|
||||
where [ISLAW] = 1
|
||||
order by [APPROVEDATE] desc"""
|
||||
cursor.execute(query)
|
||||
|
||||
law_dict = {}
|
||||
approve_date_error = []
|
||||
for item in cursor.fetchall():
|
||||
# row = cursor.fetchone()
|
||||
id = int(item.ID)
|
||||
caption = normalize_content(item.CAPTION)
|
||||
# تبدیل تاریخ با فرمت رشته به فرمت تاریخ
|
||||
date = str(item.APPROVEDATE).split("/")
|
||||
try:
|
||||
approve_date = Persian(int(date[0]), int(date[1]), int(date[2]))
|
||||
except:
|
||||
approve_date_error.append(date)
|
||||
# در موارد خطا، اپروو دیت کنترل شود
|
||||
|
||||
law_dict[id] = {"id": id, "caption": caption, "approve_date": approve_date}
|
||||
|
||||
cursor.close()
|
||||
cnxn.close()
|
||||
return law_dict
|
||||
|
||||
|
||||
def law_recognizer(text, law_dict):
|
||||
|
||||
i = 0
|
||||
|
||||
try:
|
||||
nlp_parser, normalized_content = getMetaData(text)
|
||||
except Exception as e:
|
||||
filename = "law_section_errors.txt"
|
||||
exc_type, exc_value, exc_traceback = sys.exc_info()
|
||||
frame = exc_traceback.tb_frame
|
||||
function_array = traceback.extract_tb(exc_traceback)
|
||||
current_function = function_array[len(function_array) - 1]
|
||||
error = f"""
|
||||
table : Law
|
||||
filename : {current_function.filename}
|
||||
function : {current_function.name}
|
||||
err line no : {current_function.lineno}
|
||||
err line : {current_function.line}
|
||||
err message : {e}
|
||||
"""
|
||||
save_error(error, filename)
|
||||
|
||||
text_token_list = normalized_content.strip().split()
|
||||
matched_token_index_list = []
|
||||
|
||||
# جمع آوری عناوین احتمالی قانون در یک متن بر اساس کلیدواژه قانون
|
||||
for index, token in enumerate(text_token_list):
|
||||
if "قانون" in token:
|
||||
matched_token_index_list.append(index)
|
||||
|
||||
content_token_list = []
|
||||
law_token_list = []
|
||||
for index, item in enumerate(matched_token_index_list):
|
||||
# اگر آیتم، آخرین عنصر موجود در آرایه نبود ...
|
||||
if index < len(text_token_list):
|
||||
# content_token_list.append(text_token_list[item])
|
||||
# نُه توکن بعدی را به عنوان عبارات تکمیلی احتمالی عنوان قانون ذخیره می کنیم
|
||||
if index + 9 < len(text_token_list):
|
||||
for i in range(9):
|
||||
if item + (i + 1) >= len(text_token_list):
|
||||
break
|
||||
content_token_list.append(text_token_list[item + (i + 1)])
|
||||
i = 0
|
||||
# توکن های باقیمانده تا پایان آرایه را ذخیره کن
|
||||
else:
|
||||
j = 0
|
||||
while j < len(text_token_list) - index:
|
||||
if item + (j + 1) >= len(text_token_list) - index:
|
||||
break
|
||||
content_token_list.append(text_token_list[item + (j + 1)])
|
||||
j += 1
|
||||
j = 0
|
||||
law_token_list.append(content_token_list)
|
||||
content_token_list = []
|
||||
matched_law_list = {}
|
||||
for index, item in enumerate(law_token_list):
|
||||
found_law_list_1 = {}
|
||||
found_law_list_2 = {}
|
||||
found_law_list_3 = {}
|
||||
found_law_list_4 = {}
|
||||
found_law_list_5 = {}
|
||||
found_law_list_6 = {}
|
||||
found_law_list_7 = {}
|
||||
found_law_list_8 = {}
|
||||
found_law_list_9 = {}
|
||||
previous_found_count = 0
|
||||
# در ابتدا اولین توکن عبارتی که احتمالا عنوان یک قانون است را در عنوان قانون موجود در بانک بررسی می کنیم
|
||||
# در مراحل بعدی تا به نُه گام برسیم، یکی یکی توکن ها را به توکن اول اضافه و سپس با عناوین قانون ها مقایسه می کنیم
|
||||
|
||||
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، صفر بود،
|
||||
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
|
||||
if len(item) < 1:
|
||||
break
|
||||
law_section = item[0]
|
||||
for id, value in law_dict.items():
|
||||
# عنوان قانونی که در حال مقایسه متن مورد نظر با آن هستیم
|
||||
current_caption = value["caption"]
|
||||
current_approve_date = value["approve_date"]
|
||||
# بررسی وجود عبارت مورد نظر در عنوان قانون
|
||||
if current_caption.__contains__(law_section):
|
||||
# به دست آوردن اولین توکن از عنوان قانون
|
||||
current_law_first_token = current_caption.strip().split(" ")[0]
|
||||
# اگر اولین توکن از عنوان قانون برابر با کلمه "قانون" بود، این کلمه را نادیده میگیریم
|
||||
# زیرا در لیست مربوط به لیست توکن های احتمالی مربوط به قوانین، کلمه قانون را در نظر نگرفته ایم
|
||||
if current_law_first_token == "قانون":
|
||||
current_law_first_token = current_caption.strip().split(" ")[1]
|
||||
if law_section == current_law_first_token:
|
||||
# اگر زیر رشته موردنظر ما در عنوان قانون وجود داشت، نام قانون را در یک لیست ذخیره می کنیم.
|
||||
# در مرحله بعد متن احتمالی قانون که در حال بررسی آن هستیم را با این لیست مقایسه می کنیم تا مقایسه محدود تری داشته باشیم
|
||||
found_law_list_1[id] = {
|
||||
"id": id,
|
||||
"caption": current_caption,
|
||||
"approve_date": current_approve_date,
|
||||
}
|
||||
else:
|
||||
continue
|
||||
|
||||
if len(found_law_list_1) == 0:
|
||||
continue
|
||||
else:
|
||||
if len(found_law_list_1) == 1:
|
||||
found_law = found_law_list_1.popitem()
|
||||
k = 0
|
||||
matched_string = ""
|
||||
found_law_caption = (
|
||||
found_law[1]["caption"].strip().removeprefix("قانون")
|
||||
)
|
||||
found_law_caption_tokens = found_law_caption.strip().split()
|
||||
if item[0] != "لازم":
|
||||
for k in range(len(item)):
|
||||
if k >= len(found_law_caption_tokens):
|
||||
break
|
||||
if item[k] == found_law_caption_tokens[k]:
|
||||
matched_string += item[k] + " "
|
||||
else:
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": matched_string.strip(),
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
break
|
||||
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": matched_string.strip(),
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
continue
|
||||
|
||||
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، یکی بود،
|
||||
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
|
||||
if len(item) < 2:
|
||||
continue
|
||||
|
||||
law_section = item[0] + " " + item[1]
|
||||
for id, value in found_law_list_1.items():
|
||||
current_caption = value["caption"]
|
||||
current_approve_date = value["approve_date"]
|
||||
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
|
||||
# if current_caption.__contains__(law_section):
|
||||
if rate == 100:
|
||||
found_law_list_2[id] = {
|
||||
"id": id,
|
||||
"caption": current_caption,
|
||||
"approve_date": current_approve_date,
|
||||
}
|
||||
|
||||
if len(found_law_list_2) == 0:
|
||||
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
|
||||
if len(found_law_list_1) > 1:
|
||||
# به دقت کنترل شود
|
||||
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
|
||||
sorted_found_law_list = dict(
|
||||
sorted(found_law_list_1.items(), key=lambda item: item[0])
|
||||
)
|
||||
found_law = sorted_found_law_list.popitem()
|
||||
matched_law_list[index] = {
|
||||
"found_law_list": sorted_found_law_list,
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": True,
|
||||
}
|
||||
|
||||
continue
|
||||
else:
|
||||
if len(found_law_list_2) == 1:
|
||||
found_law = found_law_list_2.popitem()
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
# اگر در جستجوی عنوان قانون، به یک مورد منحصر به فرد رسیده بودیم، فقط همین یک عنوان را ذخیره کند
|
||||
continue
|
||||
|
||||
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، دوتا بود،
|
||||
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
|
||||
if len(item) < 3:
|
||||
continue
|
||||
law_section = item[0] + " " + item[1] + " " + item[2]
|
||||
for id, value in found_law_list_2.items():
|
||||
current_caption = value["caption"]
|
||||
current_approve_date = value["approve_date"]
|
||||
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
|
||||
# if current_caption.__contains__(law_section):
|
||||
if rate == 100:
|
||||
found_law_list_3[id] = {
|
||||
"id": id,
|
||||
"caption": current_caption,
|
||||
"approve_date": current_approve_date,
|
||||
}
|
||||
if len(found_law_list_3) == 0:
|
||||
if len(found_law_list_2) > 1:
|
||||
# به دقت کنترل شود
|
||||
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
|
||||
sorted_found_law_list = dict(
|
||||
sorted(found_law_list_2.items(), key=lambda item: item[0])
|
||||
)
|
||||
found_law = sorted_found_law_list.popitem()
|
||||
matched_law_list[index] = {
|
||||
"found_law_list": sorted_found_law_list,
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": True,
|
||||
}
|
||||
|
||||
continue
|
||||
else:
|
||||
if len(found_law_list_3) == 1:
|
||||
found_law = found_law_list_3.popitem()
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
continue
|
||||
|
||||
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، سه تا بود،
|
||||
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
|
||||
if len(item) < 4:
|
||||
continue
|
||||
law_section = item[0] + " " + item[1] + " " + item[2] + " " + item[3]
|
||||
for id, value in found_law_list_3.items():
|
||||
current_caption = value["caption"]
|
||||
current_approve_date = value["approve_date"]
|
||||
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
|
||||
# if current_caption.__contains__(law_section):
|
||||
if rate == 100:
|
||||
found_law_list_4[id] = {
|
||||
"id": id,
|
||||
"caption": current_caption,
|
||||
"approve_date": current_approve_date,
|
||||
}
|
||||
if len(found_law_list_4) == 0:
|
||||
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
|
||||
if len(found_law_list_3) > 1:
|
||||
# به دقت کنترل شود
|
||||
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
|
||||
sorted_found_law_list = dict(
|
||||
sorted(found_law_list_3.items(), key=lambda item: item[0])
|
||||
)
|
||||
found_law = sorted_found_law_list.popitem()
|
||||
matched_law_list[index] = {
|
||||
"found_law_list": sorted_found_law_list,
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": True,
|
||||
}
|
||||
|
||||
continue
|
||||
else:
|
||||
if len(found_law_list_4) == 1:
|
||||
found_law = found_law_list_4.popitem()
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
continue
|
||||
|
||||
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، چهارتا بود،
|
||||
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
|
||||
if len(item) < 5:
|
||||
continue
|
||||
law_section = (
|
||||
item[0] + " " + item[1] + " " + item[2] + " " + item[3] + " " + item[4]
|
||||
)
|
||||
for id, value in found_law_list_4.items():
|
||||
current_caption = value["caption"]
|
||||
current_approve_date = value["approve_date"]
|
||||
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
|
||||
# if current_caption.__contains__(law_section):
|
||||
if rate == 100:
|
||||
found_law_list_5[id] = {
|
||||
"id": id,
|
||||
"caption": current_caption,
|
||||
"approve_date": current_approve_date,
|
||||
}
|
||||
|
||||
if len(found_law_list_5) == 0:
|
||||
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
|
||||
if len(found_law_list_4) > 1:
|
||||
# به دقت کنترل شود
|
||||
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
|
||||
sorted_found_law_list = dict(
|
||||
sorted(found_law_list_4.items(), key=lambda item: item[0])
|
||||
)
|
||||
found_law = sorted_found_law_list.popitem()
|
||||
matched_law_list[index] = {
|
||||
"found_law_list": sorted_found_law_list,
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": True,
|
||||
}
|
||||
|
||||
continue
|
||||
else:
|
||||
if len(found_law_list_5) == 1:
|
||||
found_law = found_law_list_5.popitem()
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
continue
|
||||
|
||||
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، پنج تا بود،
|
||||
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
|
||||
if len(item) < 6:
|
||||
continue
|
||||
law_section = (
|
||||
item[0]
|
||||
+ " "
|
||||
+ item[1]
|
||||
+ " "
|
||||
+ item[2]
|
||||
+ " "
|
||||
+ item[3]
|
||||
+ " "
|
||||
+ item[4]
|
||||
+ " "
|
||||
+ item[5]
|
||||
)
|
||||
for id, value in found_law_list_5.items():
|
||||
current_caption = value["caption"]
|
||||
current_approve_date = value["approve_date"]
|
||||
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
|
||||
# if current_caption.__contains__(law_section):
|
||||
if rate == 100:
|
||||
found_law_list_6[id] = {
|
||||
"id": id,
|
||||
"caption": current_caption,
|
||||
"approve_date": current_approve_date,
|
||||
}
|
||||
if len(found_law_list_6) == 0:
|
||||
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
|
||||
if len(found_law_list_5) > 1:
|
||||
# به دقت کنترل شود
|
||||
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
|
||||
sorted_found_law_list = dict(
|
||||
sorted(found_law_list_5.items(), key=lambda item: item[0])
|
||||
)
|
||||
found_law = sorted_found_law_list.popitem()
|
||||
matched_law_list[index] = {
|
||||
"found_law_list": sorted_found_law_list,
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": True,
|
||||
}
|
||||
|
||||
continue
|
||||
else:
|
||||
if len(found_law_list_6) == 1:
|
||||
found_law = found_law_list_6.popitem()
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
continue
|
||||
|
||||
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، شش تا بود،
|
||||
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
|
||||
if len(item) < 7:
|
||||
continue
|
||||
law_section = (
|
||||
item[0]
|
||||
+ " "
|
||||
+ item[1]
|
||||
+ " "
|
||||
+ item[2]
|
||||
+ " "
|
||||
+ item[3]
|
||||
+ " "
|
||||
+ item[4]
|
||||
+ " "
|
||||
+ item[5]
|
||||
+ " "
|
||||
+ item[6]
|
||||
)
|
||||
for id, value in found_law_list_6.items():
|
||||
current_caption = value["caption"]
|
||||
current_approve_date = value["approve_date"]
|
||||
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
|
||||
# if current_caption.__contains__(law_section):
|
||||
if rate == 100:
|
||||
found_law_list_7[id] = {
|
||||
"id": id,
|
||||
"caption": current_caption,
|
||||
"approve_date": current_approve_date,
|
||||
}
|
||||
if len(found_law_list_7) == 0:
|
||||
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
|
||||
if len(found_law_list_6) > 1:
|
||||
# به دقت کنترل شود
|
||||
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
|
||||
sorted_found_law_list = dict(
|
||||
sorted(found_law_list_6.items(), key=lambda item: item[0])
|
||||
)
|
||||
found_law = sorted_found_law_list.popitem()
|
||||
matched_law_list[index] = {
|
||||
"found_law_list": sorted_found_law_list,
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": True,
|
||||
}
|
||||
|
||||
continue
|
||||
else:
|
||||
if len(found_law_list_7) == 1:
|
||||
found_law = found_law_list_7.popitem()
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
continue
|
||||
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، هفت تا بود،
|
||||
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
|
||||
if len(item) < 8:
|
||||
continue
|
||||
law_section = (
|
||||
item[0]
|
||||
+ " "
|
||||
+ item[1]
|
||||
+ " "
|
||||
+ item[2]
|
||||
+ " "
|
||||
+ item[3]
|
||||
+ " "
|
||||
+ item[4]
|
||||
+ " "
|
||||
+ item[5]
|
||||
+ " "
|
||||
+ item[6]
|
||||
+ " "
|
||||
+ item[7]
|
||||
)
|
||||
for id, value in found_law_list_7.items():
|
||||
current_caption = value["caption"]
|
||||
current_approve_date = value["approve_date"]
|
||||
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
|
||||
# if current_caption.__contains__(law_section):
|
||||
if rate == 100:
|
||||
found_law_list_8[id] = {
|
||||
"id": id,
|
||||
"caption": current_caption,
|
||||
"approve_date": current_approve_date,
|
||||
}
|
||||
if len(found_law_list_8) == 0:
|
||||
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
|
||||
if len(found_law_list_7) > 1:
|
||||
# به دقت کنترل شود
|
||||
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
|
||||
sorted_found_law_list = dict(
|
||||
sorted(found_law_list_7.items(), key=lambda item: item[0])
|
||||
)
|
||||
found_law = sorted_found_law_list.popitem()
|
||||
matched_law_list[index] = {
|
||||
"found_law_list": sorted_found_law_list,
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": True,
|
||||
}
|
||||
|
||||
continue
|
||||
else:
|
||||
if len(found_law_list_8) == 1:
|
||||
found_law = found_law_list_8.popitem()
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
continue
|
||||
# اگر تعداد توکن های متنی که احتمالا عنوان یک قانون است، هشت تا بود،
|
||||
# از حلقه خارج می شویم و به سراغ بررسی عنوان قانون بعدی می رویم
|
||||
if len(item) < 9:
|
||||
continue
|
||||
law_section = (
|
||||
item[0]
|
||||
+ " "
|
||||
+ item[1]
|
||||
+ " "
|
||||
+ item[2]
|
||||
+ " "
|
||||
+ item[3]
|
||||
+ " "
|
||||
+ item[4]
|
||||
+ " "
|
||||
+ item[5]
|
||||
+ " "
|
||||
+ item[6]
|
||||
+ " "
|
||||
+ item[7]
|
||||
+ " "
|
||||
+ item[8]
|
||||
)
|
||||
for id, value in found_law_list_8.items():
|
||||
current_caption = value["caption"]
|
||||
current_approve_date = value["approve_date"]
|
||||
rate = fuzz.partial_token_sort_ratio(current_caption, law_section)
|
||||
# if current_caption.__contains__(law_section):
|
||||
if rate == 100:
|
||||
found_law_list_9[id] = {
|
||||
"id": id,
|
||||
"caption": current_caption,
|
||||
"approve_date": current_approve_date,
|
||||
}
|
||||
if len(found_law_list_9) == 0:
|
||||
# اگر در مرحله قبل بیش از یک مورد پیدا کرده اما در این مرحله تعداد موارد مشابه به صفر رسیده
|
||||
if len(found_law_list_8) > 1:
|
||||
# به دقت کنترل شود
|
||||
# مرتب سازی بر اساس قدیم به جدیدترین شناسه
|
||||
sorted_found_law_list = dict(
|
||||
sorted(found_law_list_8.items(), key=lambda item: item[0])
|
||||
)
|
||||
found_law = sorted_found_law_list.popitem()
|
||||
matched_law_list[index] = {
|
||||
"found_law_list": sorted_found_law_list,
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": True,
|
||||
}
|
||||
|
||||
continue
|
||||
else:
|
||||
if len(found_law_list_9) == 1:
|
||||
found_law = found_law_list_9.popitem()
|
||||
matched_law_list[index] = {
|
||||
"law_id": found_law[1]["id"],
|
||||
"law_captions": found_law[1]["caption"],
|
||||
"matched_string": law_section,
|
||||
"original_string": item,
|
||||
"multi_flag": False,
|
||||
}
|
||||
|
||||
# law_token_list = law_token_list
|
||||
return matched_law_list, law_token_list
|
||||
|
||||
|
||||
def law_title_search():
|
||||
section_dict = read_section_table()
|
||||
law_dict = read_law_table()
|
||||
i = 0
|
||||
probable = 0
|
||||
foundlist = 0
|
||||
found_law = 0
|
||||
final_found_law = {}
|
||||
for id, value in section_dict.items():
|
||||
text = value["section_text"]
|
||||
matched_law_list, law_token_list = law_recognizer(text, law_dict)
|
||||
|
||||
if (len(law_token_list)) > 0:
|
||||
probable += len(law_token_list)
|
||||
for k, v in matched_law_list.items():
|
||||
if v["multi_flag"]:
|
||||
foundlist += 1
|
||||
final_found_law[i] = {
|
||||
"law_id": v["law_id"],
|
||||
"multi_flag": v["multi_flag"],
|
||||
"found_law_list": v["found_law_list"],
|
||||
"law_caption": v["law_captions"],
|
||||
"matched_string": v["matched_string"],
|
||||
"original_string": v["original_string"],
|
||||
}
|
||||
if not v["multi_flag"]:
|
||||
found_law += 1
|
||||
final_found_law[i] = {
|
||||
"law_id": v["law_id"],
|
||||
"multi_flag": v["multi_flag"],
|
||||
"law_caption": v["law_captions"],
|
||||
"matched_string": v["matched_string"],
|
||||
"original_string": v["original_string"],
|
||||
}
|
||||
print(i + 1)
|
||||
i += 1
|
||||
|
||||
print("************ Result ************")
|
||||
print("probable: " + str(probable))
|
||||
print(
|
||||
"found_law: "
|
||||
+ str(found_law)
|
||||
+ " - "
|
||||
+ str(int((found_law / probable) * 100))
|
||||
+ " %"
|
||||
)
|
||||
print(
|
||||
"found_list: "
|
||||
+ str(foundlist)
|
||||
+ " - "
|
||||
+ str(int((foundlist / probable) * 100))
|
||||
+ " %"
|
||||
)
|
||||
return final_found_law
|
||||
|
||||
|
||||
final_found_law = law_title_search()
|
||||
ref_parser = []
|
||||
for ref_item in final_found_law.items():
|
||||
ref_parser.append(
|
||||
{
|
||||
"index_start": int(ref_item["start_token_state"]),
|
||||
"index_end": int(ref_item["end_token_state"]),
|
||||
"text": ref_item[
|
||||
"founded_item"
|
||||
], # توکن هایی که متناظر آنها در عناوین قانون ها وجود داشته
|
||||
"text_tokens": ref_item[
|
||||
"founded_item"
|
||||
], # ده توکنی که احتمالا عنوان یک قانون باشد
|
||||
"result": ref_item["pattern_value"], # لیست عناوین یافت شده
|
||||
"type": "law_title",
|
||||
"ref_link": "",
|
||||
}
|
||||
)
|
||||
# try:
|
||||
# nlp_parser = getMetaData(text)
|
||||
# except Exception as e:
|
||||
# filename = 'law_section_errors.txt'
|
||||
# exc_type, exc_value, exc_traceback = sys.exc_info()
|
||||
# frame = exc_traceback.tb_frame
|
||||
# function_array = traceback.extract_tb(exc_traceback)
|
||||
# current_function = function_array[len(function_array)-1]
|
||||
# error = f'''
|
||||
# filename : {current_function.filename}
|
||||
# function : {current_function.name}
|
||||
# err line no : {current_function.lineno}
|
||||
# err line : {current_function.line}
|
||||
# err message : {e}
|
||||
# err date : {datetime.datetime.now()}
|
||||
# '''
|
||||
# print(error +'\n' + '*'*50)
|
||||
# save_error(error, filename)
|
||||
|
||||
|
||||
# print(nlp_parser)
|
||||
+1
-1
@@ -4,7 +4,7 @@ import requests
|
||||
|
||||
|
||||
|
||||
url = " https://api.tavasi.ir/nlp/keywords?content="
|
||||
url = " https://tavasi.ir/api/nlp/keywords?content="
|
||||
|
||||
headers = HEADERS
|
||||
text = '''
|
||||
|
||||
@@ -15,10 +15,15 @@ class TextNormalizer:
|
||||
}
|
||||
|
||||
def split_words(self, text) :
|
||||
if not text :
|
||||
return []
|
||||
words = re.split(r"[\t\n\r\.\"«»\)\(\]\[,;،؛ \-!?:]+", text)
|
||||
return words
|
||||
|
||||
def normalize_qanon(self, text):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = text.strip()
|
||||
# اصلاح خطاهای متن در کد خط
|
||||
|
||||
@@ -44,6 +49,8 @@ class TextNormalizer:
|
||||
return text
|
||||
|
||||
def normalize_qanon_test(self, text):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = self.space_correction(text)
|
||||
text = self.heha_correction(text)
|
||||
@@ -52,6 +59,9 @@ class TextNormalizer:
|
||||
|
||||
|
||||
def normalize_text(self, text):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = text.strip()
|
||||
# اصلاح خطاهای متن در کد خط
|
||||
if self.options.get("errorLine", False):
|
||||
@@ -86,6 +96,9 @@ class TextNormalizer:
|
||||
return text
|
||||
|
||||
def replace_alphabets(self, text):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = re.sub(r"\u00AD|\u00AC", "\u200C", text) # نیم اسپیس خاص
|
||||
text = re.sub(r"(\u002C)+", "\u200C", text) # نیم اسپیس تکراری
|
||||
text = re.sub(r"ﺁ|آ", "آ", text)
|
||||
|
||||
Reference in New Issue
Block a user