common -> app.common.
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
import pyodbc
|
||||
|
||||
# region constant values
|
||||
# این توکن بسیار مهم است. چون هر از گاهی این توکن منقضی می شود
|
||||
# و باید توکن معتبر جدید از سایت قوانین درحالت لاگین شده،
|
||||
# دریافت شود و به جای توکن زیر جایگزین شود
|
||||
|
||||
# TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3Mzk3ODc1NTQsImp0aSI6IlpKRnhHUjFPR2p6b2RqWGxoVzJpSzFSeks5VVNwdXE0IiwiaXNzIjpudWxsLCJleHAiOjE3NDEwODc1NTMsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDY0NVx1MDYyZlx1MDZjY1x1MDYzMSBcdTA2NDFcdTA2NDZcdTA2Y2MiLCJsYXN0X25hbWUiOiJcdTA2MzNcdTA2MjdcdTA2NDVcdTA2MjdcdTA2NDZcdTA2NDciLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.orS-RbJkYY2nT6r7WKDfL2Wy2M0rJ9Gh_RpZv5kvVvU'
|
||||
# TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDM4NTQ0MTEsImp0aSI6IjhDOWErR3BPMGk5U3Blc0ZFT251RDNoM2t3XC82R1BWTiIsImlzcyI6bnVsbCwiZXhwIjoxNzQ1MTU0NDEwLCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjEsImZpcnN0X25hbWUiOiJcdTA2NDVcdTA2MmZcdTA2Y2NcdTA2MzEgXHUwNjQxXHUwNjQ2XHUwNmNjIiwibGFzdF9uYW1lIjoiXHUwNjMzXHUwNjI3XHUwNjQ1XHUwNjI3XHUwNjQ2XHUwNjQ3IiwiZW1haWwiOiJkZXZAZ21haWwuY29tIiwidXNlcm5hbWUiOiJkZXYiLCJ1c2VyX2xldmVsIjoyfX0.jke3m7QD2pj7E18fBJYjiz9FrYbl6ZxVaYbLt9jfZu0'
|
||||
# TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDQ5MDExMzgsImp0aSI6IldsWnRWa0dxZTUwbHQwc1VRXC82TW1zeUFGcytTdXVwWSIsImlzcyI6bnVsbCwiZXhwIjoxNzQ2MjAxMTM3LCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjEsImZpcnN0X25hbWUiOiJcdTA2NDVcdTA2MmZcdTA2Y2NcdTA2MzEgXHUwNjQxXHUwNjQ2XHUwNmNjIiwibGFzdF9uYW1lIjoiXHUwNjMzXHUwNjI3XHUwNjQ1XHUwNjI3XHUwNjQ2XHUwNjQ3IiwiZW1haWwiOiJkZXZAZ21haWwuY29tIiwidXNlcm5hbWUiOiJkZXYiLCJ1c2VyX2xldmVsIjoyfX0.EXMgeLkudzt9_94SoYQm09ERf6ES2FIleXgMAPXkygk'
|
||||
# TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDY2MDA0NjUsImp0aSI6Im9IRjJiRW81ZzhXZm9UdGdrb1BZWmpTb3Arem84N3llIiwiaXNzIjpudWxsLCJleHAiOjE3NDc5MDA0NjQsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MiwiZmlyc3RfbmFtZSI6Ilx1MDYyZFx1MDY0NVx1MDZjY1x1MDYyZiIsImxhc3RfbmFtZSI6Ilx1MDYzNVx1MDY0MVx1MDYyN1x1MDZjY1x1MDZjYyIsImVtYWlsIjoic2FmYWVpLmhhbWlkQGdtYWlsLmNvbSIsInVzZXJuYW1lIjoiaHNhZmFlaSIsInVzZXJfbGV2ZWwiOjJ9fQ.rKb7fD7hnszRSK2720hvnTE28AFceBRWZIN1H1fC0sw'
|
||||
TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDgyNTY3MTYsImp0aSI6IlZWejlWRDFGMUx5UkEyd01EaW5od3M3cTJRRkVqYW9kIiwiaXNzIjpudWxsLCJleHAiOjE3NDk1NTY3MTUsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDY0NVx1MDYyZlx1MDZjY1x1MDYzMSBcdTA2NDFcdTA2NDZcdTA2Y2MiLCJsYXN0X25hbWUiOiJcdTA2MzNcdTA2MjdcdTA2NDVcdTA2MjdcdTA2NDZcdTA2NDciLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.QljFs4f0HFT7S8qrib6q54kMWg7z381v2uqoiSFDfR4'
|
||||
ACCEPT = "application/json"
|
||||
HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT}
|
||||
|
||||
# BASE_URL = "https://api.tavasi.ir/"
|
||||
#BASE_URL = "https://hamfahmi.ir/api/"
|
||||
BASE_URL = "http://192.168.23.160/api/"
|
||||
# BASE_URL = "http://192.168.23.60/api/"
|
||||
|
||||
# endregion
|
||||
|
||||
def create_cursor(dbname = ''):
|
||||
if dbname == '':
|
||||
dbname = "Qavanin"
|
||||
|
||||
server = "DESKTOP-ENVCI85"
|
||||
database = dbname
|
||||
username = "Mofid3"
|
||||
password = "hs110saf"
|
||||
|
||||
# ******** مهم *********
|
||||
# uncomment for jokar pc
|
||||
# server = "MOFID5"
|
||||
# database = dbname
|
||||
# username = "Mofid5"
|
||||
# password = "12345"
|
||||
|
||||
# ENCRYPT defaults to yes starting in ODBC Driver SQL Server. It's good to always specify ENCRYPT=yes on the client side to avoid MITM attacks.
|
||||
cnxn = pyodbc.connect(
|
||||
"DRIVER={SQL Server};SERVER="
|
||||
+ server
|
||||
+ ";DATABASE="
|
||||
+ database
|
||||
+ ";Trusted_Connection=yes;UID="
|
||||
+ username
|
||||
+ ";PWD="
|
||||
+ password
|
||||
)
|
||||
# cnxn = pyodbc.connect('DSN=sqldsn;')
|
||||
cursor = cnxn.cursor()
|
||||
return cursor, cnxn
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import pickle
|
||||
import re
|
||||
import string
|
||||
import os
|
||||
|
||||
|
||||
class DataHelper():
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def clean_text(self, text_doc, new_line_elimination):
|
||||
punctuations = r')(}{:؟!،؛»«.' + r"/<>?.,:;"
|
||||
punctuations = '[' + punctuations + string.punctuation + ']'
|
||||
punctuations = punctuations.replace("@", "")
|
||||
|
||||
text_doc.strip()
|
||||
|
||||
# pattern = ur'\s*@[a-zA-Z0-9]*\s*'
|
||||
# tmp = re.findall(pattern, text_doc)
|
||||
# newstring = re.sub(pattern, eliminate_pattern, text_doc)
|
||||
|
||||
|
||||
#finding the numbers
|
||||
pattern = r"[-+]?\d*\.\d+|\d+"
|
||||
nums_list = re.findall(pattern, text_doc)
|
||||
newstring = re.sub(pattern, 'floatingpointnumber', text_doc)
|
||||
|
||||
|
||||
#pattern = '\s*' + punctuations + '+' + '\s*'
|
||||
#tmp = re.findall(pattern, newstring)
|
||||
#newstring = re.sub(pattern, self.add_space, newstring)
|
||||
|
||||
# pattern = u'([a-zA-Z0-9]+)(\s*)(' + punctuations + u')(\s*)([a-zA-Z0-9]+)'
|
||||
# rep = ur'\1\3\5'
|
||||
# tmp = re.findall(pattern, newstring)
|
||||
# newstring = re.sub(pattern, rep, newstring)
|
||||
|
||||
pattern = r'[\n]+'
|
||||
tmp = re.findall(pattern, newstring)
|
||||
if new_line_elimination:
|
||||
newstring = re.sub(pattern, " ", newstring)
|
||||
else:
|
||||
# newstring = re.sub(pattern, "\n", newstring)
|
||||
pass
|
||||
|
||||
punctuations = r")(}{:؟!-،؛»«.@$&%" + r"/<>?.,:;"
|
||||
latinLettersDigits = r"a-zA-Z0-9"
|
||||
pattern = r'[^' + punctuations + latinLettersDigits + 'آ-ی' + '' + '\d\s:]'
|
||||
tmp = re.findall(pattern, newstring)
|
||||
newstring = re.sub(pattern, self.eliminate_pattern, newstring)
|
||||
|
||||
pattern = r'[ ]+'
|
||||
tmp = re.findall(pattern, newstring)
|
||||
newstring = re.sub(pattern, ' ', newstring)
|
||||
|
||||
for number in nums_list:
|
||||
pattern = 'floatingpointnumber'
|
||||
newstring = re.sub(pattern, number, newstring, 1)
|
||||
|
||||
return newstring
|
||||
|
||||
def add_space(self, mystring):
|
||||
mystring = mystring.group() # this method return the string matched by re
|
||||
mystring = mystring.strip(' ') # ommiting the whitespace around the pucntuation
|
||||
mystring = " " + mystring + " " # adding a space after and before punctuation
|
||||
return mystring
|
||||
|
||||
def replace_newline_with_dot(self, mystring):
|
||||
return ' . '
|
||||
|
||||
def eliminate_pattern(self, mystring):
|
||||
return ""
|
||||
|
||||
def load_var(self, load_path):
|
||||
file = open(load_path, 'rb')
|
||||
variable = pickle.load(file)
|
||||
file.close()
|
||||
return variable
|
||||
|
||||
def save_var(self, save_path, variable):
|
||||
print("saving vars ...")
|
||||
file = open(save_path, 'wb')
|
||||
pickle.dump(variable, file)
|
||||
print("variable saved.")
|
||||
file.close()
|
||||
|
||||
def build_stem_dictionary(self, normalizer, verb_tense_path, mokasar_noun_path):
|
||||
path_dir = "resource/Persian_Dependency_Treebank/Data/2ndRep"
|
||||
lexicon_stem = set()
|
||||
verb_stem = set()
|
||||
#verb_tense_map = {}
|
||||
verb_p2f_map = {}
|
||||
verb_f2p_map = {}
|
||||
for fileName in os.listdir(path_dir):
|
||||
file_path = path_dir + "/" + fileName
|
||||
with open(file_path, "r") as input:
|
||||
input_content = input.readlines()
|
||||
for el in input_content:
|
||||
el = normalizer.sub_alphabets(el)
|
||||
el = el.split("\t")
|
||||
if (len(el) > 2):
|
||||
if (el[3] == 'V'):
|
||||
tmp_pos = "V"
|
||||
else:
|
||||
tmp_pos = "N"
|
||||
stem_word = el[2]
|
||||
stem_word = stem_word.split("#")
|
||||
stem_word = [x.strip('\u200c') for x in stem_word]
|
||||
if (tmp_pos == "V" and len(stem_word) == 2):
|
||||
if (len(stem_word[0]) != 0 and len(stem_word[1]) != 0):
|
||||
verb_p2f_map[stem_word[0]] = stem_word[1]
|
||||
verb_f2p_map[stem_word[1]] = stem_word[0]
|
||||
verb_stem.add(stem_word[0])
|
||||
verb_stem.add(stem_word[1])
|
||||
if(tmp_pos == 'V' and len(stem_word) == 3):
|
||||
if(len(stem_word[0]) != 0 and len(stem_word[1]) != 0 and len(stem_word[2]) !=0):
|
||||
#verb_prifix.add(stem_word[0])
|
||||
verb_p2f_map[stem_word[1]] = stem_word[2]
|
||||
verb_f2p_map[stem_word[2]] = stem_word[1]
|
||||
verb_stem.add(stem_word[1])
|
||||
verb_stem.add(stem_word[2])
|
||||
for t in stem_word:
|
||||
if len(t) > 1:
|
||||
if (tmp_pos == 'N'):
|
||||
lexicon_stem.add(t)
|
||||
|
||||
with open(verb_tense_path, "r") as bon_file:
|
||||
bon_file_content = bon_file.readlines()
|
||||
for el in bon_file_content:
|
||||
el = el.strip()
|
||||
el = normalizer.sub_alphabets(el)
|
||||
el = el.split()
|
||||
el = [x.strip('\u200c') for x in el]
|
||||
|
||||
verb_p2f_map[el[0]] = el[1]
|
||||
verb_f2p_map[el[1]] = el[0]
|
||||
verb_stem.add(el[0])
|
||||
verb_stem.add(el[1])
|
||||
|
||||
irregular_noun = {}
|
||||
with open(mokasar_noun_path, "r") as input:
|
||||
input_content = input.readlines()
|
||||
for el in input_content:
|
||||
el = normalizer.sub_alphabets(el)
|
||||
el = el.replace("\t\t", "\t")
|
||||
el = el.strip().split("\t")
|
||||
el = [x.strip('\u200c') for x in el]
|
||||
irregular_noun[el[0]] = el[1]
|
||||
lexicon_stem.add(el[0])
|
||||
|
||||
verb_tense_map = [verb_p2f_map, verb_f2p_map]
|
||||
return lexicon_stem, verb_stem, verb_tense_map, irregular_noun
|
||||
@@ -0,0 +1,677 @@
|
||||
import zipfile
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from time import sleep
|
||||
from elasticsearch import Elasticsearch,helpers
|
||||
|
||||
class ElasticHelper():
|
||||
|
||||
counter = 0
|
||||
total = 0
|
||||
id = ""
|
||||
path_mappings = os.getcwd() + '/repo/_other/'
|
||||
|
||||
def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mappings = ""):
|
||||
|
||||
if path_mappings :
|
||||
self.path_mappings = path_mappings
|
||||
|
||||
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():
|
||||
print('elastic not ping, sleep 30 s : ', a)
|
||||
sleep(5)
|
||||
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 get_doctument(self, index_name, id):
|
||||
res = self.es.get(index=index_name, id=id)
|
||||
return res
|
||||
|
||||
def exist_doctument(self, index_name, id):
|
||||
res = self.es.exists(index=index_name, id=id)
|
||||
return res
|
||||
|
||||
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 exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[]) :
|
||||
print('*' * 50, ' start backup -->', index_name)
|
||||
self.counter = 0
|
||||
sid = None
|
||||
|
||||
out = out_name
|
||||
if out_name == '' :
|
||||
out = index_name
|
||||
|
||||
fout = open( path_back + "/"+ out + '.json', 'a+' , encoding='utf-8')
|
||||
|
||||
s_res = self.es.search(
|
||||
index=index_name,
|
||||
scroll='5m',
|
||||
size=1000,
|
||||
body=body
|
||||
)
|
||||
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
|
||||
out_json = []
|
||||
while scroll_size > 0:
|
||||
"Scrolling..."
|
||||
self.counter += scroll_size
|
||||
print("progress -> %.2f %%" % ((self.counter / self.total)*100))
|
||||
#############################
|
||||
for item in s_res['hits']['hits']:
|
||||
|
||||
if fields :
|
||||
item2={}
|
||||
item2['id']=item['_id']
|
||||
for kf in fields :
|
||||
#print(kf)
|
||||
if kf in item['_source'] :
|
||||
# print(item['_source'][kf])
|
||||
item2[kf] = item['_source'][kf]
|
||||
#exit()
|
||||
else :
|
||||
item2=item
|
||||
|
||||
out_json.append(item2)
|
||||
|
||||
|
||||
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'])
|
||||
|
||||
sid = None
|
||||
text = json.dumps(out_json, ensure_ascii=False)
|
||||
fout.write(text)
|
||||
|
||||
##############################
|
||||
|
||||
def backupIndexToZipfile(self, path_back, index_name, out_name= '', body={}, byzip = True, fields=[], noFields=[]) :
|
||||
print('*' * 50, ' start backup -->', index_name)
|
||||
self.counter = 0
|
||||
sid = None
|
||||
|
||||
out = out_name
|
||||
if out_name == '' :
|
||||
out = index_name
|
||||
|
||||
|
||||
if body == {} :
|
||||
s_res = self.es.search(
|
||||
index=index_name,
|
||||
scroll='5m',
|
||||
size=1000
|
||||
)
|
||||
else:
|
||||
s_res = self.es.search(
|
||||
index=index_name,
|
||||
scroll='5m',
|
||||
size=1000,
|
||||
body=body
|
||||
)
|
||||
|
||||
self.total = s_res["hits"]["total"]['value']
|
||||
if self.total == 0 :
|
||||
print('total index_name by query = %d' % self.total)
|
||||
return False
|
||||
|
||||
if byzip:
|
||||
fout = zipfile.ZipFile(path_back + "/"+ out + '.zip', 'w')
|
||||
else:
|
||||
fout = open( path_back + "/"+ out + '.json', 'a+' , encoding='utf-8')
|
||||
|
||||
|
||||
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']:
|
||||
if fields :
|
||||
item2={}
|
||||
item2['id']=item['_id']
|
||||
item2['_source']={}
|
||||
for kf in fields :
|
||||
if kf in item['_source'] :
|
||||
item2['_source'][kf] = item['_source'][kf]
|
||||
else :
|
||||
item2=item
|
||||
|
||||
if noFields :
|
||||
for kf in noFields :
|
||||
if kf in item2['_source']:
|
||||
del item2['_source'][kf]
|
||||
|
||||
|
||||
out_json.append(item2)
|
||||
|
||||
|
||||
text = json.dumps(out_json, ensure_ascii=False)
|
||||
out_json = []
|
||||
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'])
|
||||
sid = None
|
||||
fout.close()
|
||||
|
||||
|
||||
def restorFileToElastic(self, path_back, index_name, app_key = '', queryDelete = True, map_name='') :
|
||||
if not os.path.exists(path_back) :
|
||||
print(' **** error *** path not exist: ', 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, map_name)
|
||||
self.zipFileToElastic(file_path, index_name)
|
||||
else : # اگر وجود داشته باشد پرش می کند و کاری نمیکند
|
||||
self.createIndex(index_name, app_key, map_name)
|
||||
self.zipFileToElastic(file_path, index_name)
|
||||
|
||||
def restorFileToElastic2(self, path_file, index_name, app_key = '', queryDelete = True, map_name='') :
|
||||
if not os.path.exists(path_file) :
|
||||
print(' **** error *** path not exist: ', path_file)
|
||||
return False
|
||||
|
||||
file_path = path_file
|
||||
if not os.path.exists(file_path ) :
|
||||
return False
|
||||
|
||||
if queryDelete :
|
||||
# اگر وجود داشته باشد، از کاربر برای حذفش سوال میکند
|
||||
if self.deleteIndex(index_name) :
|
||||
self.createIndex(index_name, app_key, map_name)
|
||||
self.zipFileToElastic(file_path, index_name)
|
||||
else : # اگر وجود داشته باشد پرش می کند و کاری نمیکند
|
||||
self.createIndex(index_name, app_key, map_name)
|
||||
self.zipFileToElastic(file_path, index_name)
|
||||
|
||||
|
||||
def renameElasticIndex(self, index_name_i, index_name_o, app_key = '', map_name='') :
|
||||
|
||||
if self.createIndex(index_name_o, app_key, map_name) :
|
||||
res = self.es.reindex(
|
||||
body={
|
||||
"source": {"index": index_name_i},
|
||||
"dest": {"index": index_name_o}
|
||||
},
|
||||
wait_for_completion=False)
|
||||
|
||||
print(type(res))
|
||||
print(res)
|
||||
|
||||
taskid = res["task"] if res["task"] else ""
|
||||
#tasks = client.TasksClient(self.es)
|
||||
tasks = self.es.tasks
|
||||
while True :
|
||||
res = tasks.get(task_id = taskid)
|
||||
if res["completed"] :
|
||||
break
|
||||
|
||||
# print( res["task"])
|
||||
print( '----', index_name_o, ' imported : ', res["task"]["status"]["total"] , ' / ', res["task"]["status"]["created"])
|
||||
sleep(1)
|
||||
print( '----', index_name_o, ' complated')
|
||||
|
||||
|
||||
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='', map_name=''):
|
||||
|
||||
path_base = self.path_mappings
|
||||
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
|
||||
|
||||
if map_name == 'mj_rg_section' or map_name == 'semantic_search' :
|
||||
map_name = 'mj_qa_section'
|
||||
elif map_name[-3]=='_ai':
|
||||
map_name=[0-len(map_name)-3]
|
||||
print(map_name)
|
||||
|
||||
mapping_file_path = path_mapping1 + map_name + '.json'
|
||||
print("mapping_file_path : " , mapping_file_path)
|
||||
if not os.path.isfile(mapping_file_path):
|
||||
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', encoding='utf-8' )
|
||||
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 )
|
||||
else :
|
||||
self.es.indices.create(index = index_name , body = mapping_data)
|
||||
return True
|
||||
else:
|
||||
print('*** error not find maping file elastic : *******', mapping_file_path)
|
||||
return False
|
||||
|
||||
|
||||
def updateBulkList(self, listData, index_name):
|
||||
chunk_size=1000
|
||||
raise_on_error=False
|
||||
raise_on_exception=False
|
||||
stats_only=True
|
||||
yield_ok = False
|
||||
|
||||
actions=[]
|
||||
for item in listData:
|
||||
actions.append({
|
||||
"_op_type": "update",
|
||||
"_index": index_name,
|
||||
"_id" : item['_id'],
|
||||
"doc": item['_source']
|
||||
}
|
||||
)
|
||||
helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok )
|
||||
|
||||
def importBulkList(self, listData, index_name):
|
||||
chunk_size=100000
|
||||
raise_on_error=False
|
||||
raise_on_exception=False
|
||||
stats_only=True
|
||||
yield_ok = False
|
||||
|
||||
for item in listData:
|
||||
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 )
|
||||
|
||||
|
||||
def importJsonDataToElastic(self, jsonData, index_name, fields=[]):
|
||||
chunk_size=1000
|
||||
raise_on_error=False
|
||||
raise_on_exception=False
|
||||
stats_only=True
|
||||
yield_ok = False
|
||||
|
||||
actions=[]
|
||||
|
||||
for item in jsonData:
|
||||
id = item['_id'] if item['_id'] else item['id']
|
||||
source = item['_source']
|
||||
if fields :
|
||||
source = {}
|
||||
for col in fields :
|
||||
if col in item['_source'] :
|
||||
source[col] = item['_source']
|
||||
|
||||
|
||||
actions.append({
|
||||
"_op_type": "index",
|
||||
"_index": index_name,
|
||||
"_id" : id,
|
||||
"_source": source
|
||||
})
|
||||
helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok )
|
||||
|
||||
|
||||
def fileToElastic(self, file_path, index_name, limit_pack = -1, fields=[]):
|
||||
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, fields)
|
||||
|
||||
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, fields=[]):
|
||||
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, fields)
|
||||
|
||||
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 iterateJsonFile(self, file_path, isZip=True, limit_pack = -1):
|
||||
if not os.path.exists(file_path):
|
||||
print("file zip:" , file_path , " not exist iterateJsonFile " )
|
||||
return
|
||||
|
||||
if isZip :
|
||||
fileNo = 0
|
||||
with zipfile.ZipFile(file_path, 'r') as zObject:
|
||||
fileNo +=1
|
||||
print("="*10, " zip fileNo: " , fileNo ," iterateJsonFile - | 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 iterateJsonFile ', limit_pack)
|
||||
break
|
||||
|
||||
print("index iterateJsonFile :", '=>' , filename )
|
||||
with zObject.open(filename) as file:
|
||||
data = json.loads(file.read())
|
||||
# Yield each entry
|
||||
# yield data
|
||||
yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in data)
|
||||
else :
|
||||
with open(filename, 'r', encoding='utf-8') as file:
|
||||
data = json.loads(file.read())
|
||||
# Yield each entry
|
||||
# yield from (hit for hit in data)
|
||||
#return data
|
||||
yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in data)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
def mappingIndex(self, index_name_i):
|
||||
# فقط از طریق کیبانا میشه تغییر مپ داد
|
||||
|
||||
# با پایتون نمیشه
|
||||
# باید ایندکس جدیدی با مپ مطلوب ایجاد کرد و رایندکس کرد
|
||||
pass
|
||||
|
||||
def updateByQueryIndex(self, index_name_i, body):
|
||||
## sample
|
||||
# body = {
|
||||
# "script": {
|
||||
# "inline": "ctx._source.Device='Test'",
|
||||
# "lang": "painless"
|
||||
# },
|
||||
# "query": {
|
||||
# "match": {
|
||||
# "Device": "Boiler"
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
try:
|
||||
self.es.update_by_query(body=body, index=index_name_i)
|
||||
|
||||
except Exception as e:
|
||||
print(e)
|
||||
# save_error(id, e)
|
||||
|
||||
|
||||
def deleteByQueryIndex(self, index_name_i, body):
|
||||
## sample
|
||||
# body = {
|
||||
# "query": {
|
||||
# "match": {
|
||||
# "Device": "Boiler"
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
try:
|
||||
self.es.delete_by_query(index=index_name_i, body=body )
|
||||
|
||||
except Exception as e:
|
||||
print(e)
|
||||
# save_error(id, e)
|
||||
|
||||
def delete_by_ids(self, index_name_i, ids):
|
||||
try:
|
||||
# ids = ['test1', 'test2', 'test3']
|
||||
|
||||
query = {"query": {"terms": {"_id": ids}}}
|
||||
res = self.es.delete_by_query(index=index_name_i, body=query)
|
||||
print(res)
|
||||
|
||||
except Exception as e:
|
||||
print(e)
|
||||
# save_error(id, e)
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
from elasticsearch import AsyncElasticsearch
|
||||
from elasticsearch.helpers import async_bulk
|
||||
import sys
|
||||
import os
|
||||
import asyncio
|
||||
import aiofiles
|
||||
import json
|
||||
from dotenv import load_dotenv
|
||||
from zipfile import ZipFile
|
||||
from time import sleep
|
||||
import gc
|
||||
|
||||
|
||||
|
||||
class elastic_helper_async:
|
||||
|
||||
def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mapping = ""):
|
||||
|
||||
# self.limit_data = os.getenv("ELASTIC_LIMIT_IMPORT")
|
||||
# self.app_key = os.getenv("APP_KEY")
|
||||
|
||||
if path_mapping :
|
||||
self.path_mapping = path_mapping
|
||||
|
||||
if es_pass == '' :
|
||||
self.aes = AsyncElasticsearch(es_url, timeout=100000000)
|
||||
else:
|
||||
self.aes = AsyncElasticsearch(es_url, basic_auth=(es_user, es_pass),timeout=100000000)
|
||||
|
||||
print(es_url)
|
||||
print(self.aes)
|
||||
|
||||
self.success_connect = False
|
||||
for a in range(0,10):
|
||||
try :
|
||||
if not self.es.ping():
|
||||
print('elastic not ping, sleep 30 s : ', a)
|
||||
sleep(5)
|
||||
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 = ""
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
async def test_file(self,array: list, name_s):
|
||||
for a in array:
|
||||
if a == name_s:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
async def name_file(self,array: list, namber_claer:str):
|
||||
data = []
|
||||
for a in array:
|
||||
data.append(a[:-namber_claer])
|
||||
|
||||
print(data)
|
||||
return data
|
||||
|
||||
async def read_file_json_mapping(self, name_map_general ):
|
||||
async with aiofiles.open(f"{self.path_mapping}/general/" + name_map_general + ".json", mode="r", encoding="utf8") as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
return data_mapping_josn
|
||||
|
||||
|
||||
async def create_general_indexes(self):
|
||||
mapping_general = f"{self.path_mapping}/general/"
|
||||
list_general=['gn_setting','gn_calendar' ,'gn_dataset','gn_entity','gn_log_action','gn_log_change','gn_log_search','gn_research' ]
|
||||
|
||||
for seed_general in list_general:
|
||||
print("mapping "+seed_general)
|
||||
data_json_mapping = await self.read_file_json_mapping(seed_general)
|
||||
try:
|
||||
await self.aes.indices.create(index=seed_general, body=data_json_mapping)
|
||||
except:
|
||||
print("This file has already been created, and I cannot create it again.")
|
||||
|
||||
|
||||
async def create_mapping_delete(self,location_file_zip:str, app_key="majles"):
|
||||
locations_data_ok = []
|
||||
location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/")
|
||||
location_mapping_general = os.listdir(f"{self.path_mapping}/general/")
|
||||
location_filezip = os.listdir(location_file_zip)
|
||||
name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5)
|
||||
name_locations_mapping_general = await self.name_file(location_mapping_general, 5)
|
||||
name_locations_filezip = await self.name_file(location_filezip, 4)
|
||||
|
||||
for a in name_locations_filezip:
|
||||
if await self.test_file(name_locations_mapping_majles, a):
|
||||
print(a)
|
||||
async with aiofiles.open(f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8") as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
|
||||
await self.delete_index(a)
|
||||
await asyncio.sleep(10)
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
elif await self.test_file(name_locations_mapping_general, a):
|
||||
print(a)
|
||||
async with aiofiles.open(
|
||||
f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8"
|
||||
) as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
|
||||
await self.delete_index(a)
|
||||
await asyncio.sleep(10)
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
else:
|
||||
if a == "mj_rg_section" or a == "semantic_search":
|
||||
mapping_read = "mj_qa_section"
|
||||
async with aiofiles.open(
|
||||
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
|
||||
) as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
|
||||
await self.delete_index(a)
|
||||
await asyncio.sleep(10)
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
elif a[-3:] == "_ai":
|
||||
mapping_read = a[:-3]
|
||||
try:
|
||||
|
||||
async with aiofiles.open(
|
||||
f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8"
|
||||
) as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
|
||||
await self.delete_index(a)
|
||||
await asyncio.sleep(10)
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
except:
|
||||
async with aiofiles.open(
|
||||
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
|
||||
) as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
print("+++++++++++++ delete_index "+a+"+++++++++++++++++++")
|
||||
await self.delete_index(a)
|
||||
await asyncio.sleep(10)
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
else:
|
||||
print(f"not funds map {a}")
|
||||
|
||||
return locations_data_ok
|
||||
## error for to for
|
||||
|
||||
|
||||
async def create_mapping(self,location_file_zip:str, app_key="majles"):
|
||||
locations_data_ok = []
|
||||
location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/")
|
||||
location_mapping_general = os.listdir(f"{self.path_mapping}/general/")
|
||||
location_filezip = os.listdir(location_file_zip)
|
||||
name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5)
|
||||
name_locations_mapping_general = await self.name_file(location_mapping_general, 5)
|
||||
name_locations_filezip = await self.name_file(location_filezip, 4)
|
||||
|
||||
for a in name_locations_filezip:
|
||||
if await self.test_file(name_locations_mapping_majles, a):
|
||||
print(a)
|
||||
async with aiofiles.open(
|
||||
f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8"
|
||||
) as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
elif await self.test_file(name_locations_mapping_general, a):
|
||||
print(a)
|
||||
async with aiofiles.open(
|
||||
f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8"
|
||||
) as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
else:
|
||||
if a == "mj_rg_section" or a == "semantic_search":
|
||||
mapping_read = "mj_qa_section"
|
||||
async with aiofiles.open(
|
||||
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
|
||||
) as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
elif a[-3:] == "_ai":
|
||||
mapping_read = a[:-3]
|
||||
try:
|
||||
|
||||
async with aiofiles.open(
|
||||
f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8"
|
||||
) as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
except:
|
||||
async with aiofiles.open(
|
||||
f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8"
|
||||
) as file_json:
|
||||
data_mapping_josn = await file_json.read()
|
||||
data_mapping_josn = json.loads(data_mapping_josn)
|
||||
locations_data_ok.append(a)
|
||||
try:
|
||||
await self.aes.indices.create(index=a, body=data_mapping_josn)
|
||||
await self.aes.indices.refresh(index=a)
|
||||
|
||||
except:
|
||||
print(
|
||||
f" ******************* There is a mapping {a} ***********************"
|
||||
)
|
||||
|
||||
else:
|
||||
print(f"not funds map {a}")
|
||||
|
||||
return locations_data_ok
|
||||
## error for to for
|
||||
|
||||
|
||||
async def data_unzip(self,location_file_zip:str,namefile: str):
|
||||
|
||||
current_directory = os.getcwd()
|
||||
file_name = f"{location_file_zip}/{namefile}.zip"
|
||||
sleep(10)
|
||||
print(" -----> start to unzip ... ",file_name)
|
||||
data1 = []
|
||||
os.system(f"del /q /S .\\data\\tmp\\edb\\{namefile}")
|
||||
os.system(f"mkdir .\\data\\tmp\\edb\\{namefile}")
|
||||
# os.system(f"del -rf /q .\\data\\tmp\\edb\\{namefile}\\*")
|
||||
os.system(f"tar -xf {file_name} -C .\\data\\tmp\\edb\\{namefile}\\")
|
||||
#await asyncio.sleep(1)
|
||||
list_file_json = os.listdir(f".\\data\\tmp\\edb\\{namefile}\\")
|
||||
await asyncio.sleep(10)
|
||||
for a in list_file_json:
|
||||
try:
|
||||
with open(f"{current_directory}\\data\\tmp\\edb\\{namefile}\\{a}", "r", encoding="utf8") as file_json:
|
||||
data = file_json.read()
|
||||
data = json.loads(data)
|
||||
for a1 in data:
|
||||
#await asyncio.sleep(0.001)
|
||||
try:
|
||||
yield (
|
||||
{
|
||||
"_op_type": "index",
|
||||
"_index": namefile,
|
||||
"_id": a1["_id"],
|
||||
"_source": a1["_source"],
|
||||
}
|
||||
)
|
||||
except:
|
||||
print("error type document")
|
||||
|
||||
except Exception as e:
|
||||
print(f"read file {current_directory}\\data\\tmp\\edb\\{namefile}\\{a}" + " " + {e})
|
||||
|
||||
|
||||
|
||||
async def go_to_data(list_data: list, namefile: str):
|
||||
with open(f"T:{namefile}.json", "a") as a:
|
||||
a.write(str(list_data))
|
||||
a.close()
|
||||
|
||||
|
||||
async def run_elastic_import(self,loc:str):
|
||||
locations_data = await self.create_mapping(loc)
|
||||
print(locations_data)
|
||||
await self.create_general_indexes()
|
||||
#await asyncio.sleep(5)
|
||||
for file_list in locations_data:
|
||||
# try :
|
||||
await async_bulk(self.aes, self.data_unzip(loc,file_list), True)
|
||||
gc.collect()
|
||||
# except:
|
||||
# await asyncio.sleep(10)
|
||||
# await async_bulk(self.aes, self.data_unzip(file_list), True)
|
||||
|
||||
print("finash")
|
||||
#await asyncio.sleep(10)
|
||||
|
||||
|
||||
async def run_elastic_import_delete(self,loc:str):
|
||||
locations_data = await self.create_mapping_delete(loc)
|
||||
#await asyncio.sleep(1000)
|
||||
print(locations_data)
|
||||
await self.create_general_indexes()
|
||||
#await asyncio.sleep(5)
|
||||
|
||||
for file_list in locations_data:
|
||||
# try :
|
||||
await async_bulk(self.aes, self.data_unzip(loc,file_list), True)
|
||||
gc.collect()
|
||||
# except:
|
||||
# await asyncio.sleep(10)
|
||||
# await async_bulk(self.aes, self.data_unzip(file_list), True)
|
||||
|
||||
print("finash")
|
||||
#await asyncio.sleep(10)
|
||||
|
||||
async def delete_index(self,name_index:str):
|
||||
await self.aes.indices.delete(index=name_index, ignore=[400, 404]) # await go_to_data( data2,"gn_dataset")
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,192 @@
|
||||
# In The Name Of Allah
|
||||
#
|
||||
# Jalali date converter
|
||||
# 2014 07 25
|
||||
# Ported from PHP (http://jdf.scr.ir/) to Python (2&3) by Mohammad Javad Naderi <mjnaderi@gmail.com>
|
||||
#
|
||||
# As mentioned in http://jdf.scr.ir/, the original code is free and open source,
|
||||
# and you are not allowed to sell it. You can read more in http://jdf.scr.ir/.
|
||||
#
|
||||
# Original License Notes:
|
||||
#
|
||||
# /** Software Hijri_Shamsi , Solar(Jalali) Date and Time
|
||||
# Copyright(C)2011, Reza Gholampanahi , http://jdf.scr.ir
|
||||
# version 2.55 :: 1391/08/24 = 1433/12/18 = 2012/11/15 */
|
||||
#
|
||||
# /** Convertor from and to Gregorian and Jalali (Hijri_Shamsi,Solar) Functions
|
||||
# Copyright(C)2011, Reza Gholampanahi [ http://jdf.scr.ir/jdf ] version 2.50 */
|
||||
#
|
||||
# Example Usage:
|
||||
#
|
||||
# >>> import jalali
|
||||
#
|
||||
# >>> jalali.Persian('1393-1-11').gregorian_string()
|
||||
# '2014-3-31'
|
||||
# >>> jalali.Persian(1393, 1, 11).gregorian_datetime()
|
||||
# datetime.date(2014, 3, 31)
|
||||
# >>> jalali.Persian('1393/1/11').gregorian_string("{}/{}/{}")
|
||||
# '2014/3/31'
|
||||
# >>> jalali.Persian((1393, 1, 11)).gregorian_tuple()
|
||||
# (2014, 3, 31)
|
||||
#
|
||||
# >>> jalali.Gregorian('2014-3-31').persian_string()
|
||||
# '1393-1-11'
|
||||
# >>> jalali.Gregorian('2014,03,31').persian_tuple()
|
||||
# (1393, 1, 11)
|
||||
# >>> jalali.Gregorian(2014, 3, 31).persian_year
|
||||
# 1393
|
||||
|
||||
import re
|
||||
import datetime
|
||||
|
||||
|
||||
class Gregorian:
|
||||
|
||||
def __init__(self, *date):
|
||||
# Parse date
|
||||
if len(date) == 1:
|
||||
date = date[0]
|
||||
if type(date) is str:
|
||||
m = re.match(r'^(\d{4})\D(\d{1,2})\D(\d{1,2})$', date)
|
||||
if m:
|
||||
[year, month, day] = [int(m.group(1)), int(m.group(2)), int(m.group(3))]
|
||||
else:
|
||||
raise Exception("Invalid Input String")
|
||||
elif type(date) is datetime.date:
|
||||
[year, month, day] = [date.year, date.month, date.day]
|
||||
elif type(date) is tuple:
|
||||
year, month, day = date
|
||||
year = int(year)
|
||||
month = int(month)
|
||||
day = int(day)
|
||||
else:
|
||||
raise Exception("Invalid Input Type")
|
||||
elif len(date) == 3:
|
||||
year = int(date[0])
|
||||
month = int(date[1])
|
||||
day = int(date[2])
|
||||
else:
|
||||
raise Exception("Invalid Input")
|
||||
|
||||
# Check the validity of input date
|
||||
try:
|
||||
datetime.datetime(year, month, day)
|
||||
except:
|
||||
raise Exception("Invalid Date")
|
||||
|
||||
self.gregorian_year = year
|
||||
self.gregorian_month = month
|
||||
self.gregorian_day = day
|
||||
|
||||
# Convert date to Jalali
|
||||
d_4 = year % 4
|
||||
g_a = [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
|
||||
doy_g = g_a[month] + day
|
||||
if d_4 == 0 and month > 2:
|
||||
doy_g += 1
|
||||
d_33 = int(((year - 16) % 132) * .0305)
|
||||
a = 286 if (d_33 == 3 or d_33 < (d_4 - 1) or d_4 == 0) else 287
|
||||
if (d_33 == 1 or d_33 == 2) and (d_33 == d_4 or d_4 == 1):
|
||||
b = 78
|
||||
else:
|
||||
b = 80 if (d_33 == 3 and d_4 == 0) else 79
|
||||
if int((year - 10) / 63) == 30:
|
||||
a -= 1
|
||||
b += 1
|
||||
if doy_g > b:
|
||||
jy = year - 621
|
||||
doy_j = doy_g - b
|
||||
else:
|
||||
jy = year - 622
|
||||
doy_j = doy_g + a
|
||||
if doy_j < 187:
|
||||
jm = int((doy_j - 1) / 31)
|
||||
jd = doy_j - (31 * jm)
|
||||
jm += 1
|
||||
else:
|
||||
jm = int((doy_j - 187) / 30)
|
||||
jd = doy_j - 186 - (jm * 30)
|
||||
jm += 7
|
||||
self.persian_year = jy
|
||||
self.persian_month = jm
|
||||
self.persian_day = jd
|
||||
|
||||
def persian_tuple(self):
|
||||
return self.persian_year, self.persian_month, self.persian_day
|
||||
|
||||
def persian_string(self, date_format="{}-{}-{}"):
|
||||
return date_format.format(self.persian_year, self.persian_month, self.persian_day)
|
||||
|
||||
|
||||
class Persian:
|
||||
|
||||
def __init__(self, *date):
|
||||
# Parse date
|
||||
if len(date) == 1:
|
||||
date = date[0]
|
||||
if type(date) is str:
|
||||
m = re.match(r'^(\d{4})\D(\d{1,2})\D(\d{1,2})$', date)
|
||||
if m:
|
||||
[year, month, day] = [int(m.group(1)), int(m.group(2)), int(m.group(3))]
|
||||
else:
|
||||
raise Exception("Invalid Input String")
|
||||
elif type(date) is tuple:
|
||||
year, month, day = date
|
||||
year = int(year)
|
||||
month = int(month)
|
||||
day = int(day)
|
||||
else:
|
||||
raise Exception("Invalid Input Type")
|
||||
elif len(date) == 3:
|
||||
year = int(date[0])
|
||||
month = int(date[1])
|
||||
day = int(date[2])
|
||||
else:
|
||||
raise Exception("Invalid Input")
|
||||
|
||||
# Check validity of date. TODO better check (leap years)
|
||||
if year < 1 or month < 1 or month > 12 or day < 1 or day > 31 or (month > 6 and day == 31):
|
||||
raise Exception("Incorrect Date")
|
||||
|
||||
self.persian_year = year
|
||||
self.persian_month = month
|
||||
self.persian_day = day
|
||||
|
||||
# Convert date
|
||||
d_4 = (year + 1) % 4
|
||||
if month < 7:
|
||||
doy_j = ((month - 1) * 31) + day
|
||||
else:
|
||||
doy_j = ((month - 7) * 30) + day + 186
|
||||
d_33 = int(((year - 55) % 132) * .0305)
|
||||
a = 287 if (d_33 != 3 and d_4 <= d_33) else 286
|
||||
if (d_33 == 1 or d_33 == 2) and (d_33 == d_4 or d_4 == 1):
|
||||
b = 78
|
||||
else:
|
||||
b = 80 if (d_33 == 3 and d_4 == 0) else 79
|
||||
if int((year - 19) / 63) == 20:
|
||||
a -= 1
|
||||
b += 1
|
||||
if doy_j <= a:
|
||||
gy = year + 621
|
||||
gd = doy_j + b
|
||||
else:
|
||||
gy = year + 622
|
||||
gd = doy_j - a
|
||||
for gm, v in enumerate([0, 31, 29 if (gy % 4 == 0) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]):
|
||||
if gd <= v:
|
||||
break
|
||||
gd -= v
|
||||
|
||||
self.gregorian_year = gy
|
||||
self.gregorian_month = gm
|
||||
self.gregorian_day = gd
|
||||
|
||||
def gregorian_tuple(self):
|
||||
return self.gregorian_year, self.gregorian_month, self.gregorian_day
|
||||
|
||||
def gregorian_string(self, date_format="{}-{}-{}"):
|
||||
return date_format.format(self.gregorian_year, self.gregorian_month, self.gregorian_day)
|
||||
|
||||
def gregorian_datetime(self):
|
||||
return datetime.date(self.gregorian_year, self.gregorian_month, self.gregorian_day)
|
||||
@@ -0,0 +1,167 @@
|
||||
from app.common.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")
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,367 @@
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
import json
|
||||
from dotenv import load_dotenv
|
||||
from app.common.config_base import *
|
||||
# from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
# from excel_helper import ExcelHelper
|
||||
import pandas as pd
|
||||
|
||||
text_normalizer = TextNormalizer()
|
||||
|
||||
def is_nan_or_none_or_empty(value):
|
||||
"""
|
||||
Checks if a value is NaN, None, or an empty string.
|
||||
|
||||
Args:
|
||||
value: The value to check.
|
||||
|
||||
Returns:
|
||||
True if the value is NaN, None, or an empty string, False otherwise.
|
||||
"""
|
||||
if value is None:
|
||||
return True
|
||||
if isinstance(value, str) and value == "":
|
||||
return True
|
||||
if isinstance(value, float) :
|
||||
return True
|
||||
if pd.isna(value):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def get_qanon_title_sample(text, maxState=True):
|
||||
|
||||
spell_list = [
|
||||
"ائیننامه[آئین نامه]=آئین نامه",
|
||||
"انگیس[انگلیس]=انگلیس",
|
||||
"انگیس=انگلیس",
|
||||
"ائیننامه=آئین نامه",
|
||||
"بوزارت=به وزارت"
|
||||
"تهرات=تهران"
|
||||
]
|
||||
|
||||
|
||||
text = re.sub(r"(\d+?)\.(\d+?)\.(\d+?)", r"\1/\2/\3", text)
|
||||
text = text_normalizer.date_correction(text)
|
||||
text = text_normalizer.word_digit_correction(text)
|
||||
text = text_normalizer.hamzah_normal(text)
|
||||
text = re.sub(r"(\u200C)+", "", text)
|
||||
# بدون : /
|
||||
text = re.sub(r"[\t\n\r\.\'\"«»\)\(\]\[\{\}\%\#\$\*\<\>,;،؛\-!?:٭؟]+", "", text)
|
||||
if maxState :
|
||||
text = text_normalizer.alaem_normal(text)
|
||||
text = re.sub(r"( |\u200C)+", "", text)
|
||||
text = text.replace("اء", "ا")
|
||||
|
||||
if text.startswith('فصل'):
|
||||
# در آدرس دهی چون براساس شماره ماده هست فصل مهم نیست. چون شماره ماده کلی هست
|
||||
text = re.sub(r"^(فصل[^>]>)+", "", text)
|
||||
|
||||
return text
|
||||
|
||||
def get_section_title_sample(text):
|
||||
text = text_normalizer.normalize_search_qanon(text)
|
||||
text = text_normalizer.remove_arabic_diacritics(text)
|
||||
text = text_normalizer.hamzah_normal(text)
|
||||
text = text_normalizer.alaem_normal(text)
|
||||
text = re.sub(r"( |\u200C|\>|\<|-|ـ)+", "", text)
|
||||
return text
|
||||
|
||||
def searchSectionId(elastic, index_name, qanon_id, section_title):
|
||||
score = 100
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"term": {
|
||||
"qanon_id": {
|
||||
"value": qanon_id
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"other_info.full_path": section_title
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
s_res = elastic.es.search(index=index_name, body=body)
|
||||
section_title = get_section_title_sample(section_title)
|
||||
for item in s_res["hits"]["hits"]:
|
||||
other_info = item['_source']['other_info']
|
||||
title = other_info['full_path']
|
||||
# حذف اضافات
|
||||
title = get_section_title_sample(title)
|
||||
|
||||
if title == section_title :
|
||||
return item["_id"], 100, item
|
||||
|
||||
return 0, 0, {}
|
||||
|
||||
def get_dict_qanon_title(file_path):
|
||||
dict = {}
|
||||
with open(file_path, 'r', encoding='utf8') as file1:
|
||||
for line in file1.readlines() :
|
||||
items = line.split('=')
|
||||
if len(items) == 2 :
|
||||
dict[items[0]] = items[1]
|
||||
return dict
|
||||
|
||||
|
||||
def searchQanonTitleOfContent(elastic, qanon_title, ts_data="", index_name="mj_qa_section"):
|
||||
score = 100
|
||||
|
||||
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"more_like_this": {
|
||||
"fields": [
|
||||
"content.fa"
|
||||
],
|
||||
"like": qanon_title,
|
||||
"min_term_freq": 1,
|
||||
"max_query_terms": 12
|
||||
}
|
||||
},
|
||||
{
|
||||
"match": {
|
||||
"other_info.full_path": "عنوان"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s_res = elastic.es.search(index=index_name, body=body)
|
||||
total = s_res["hits"]["total"]['value']
|
||||
|
||||
qanon_title_sample = re.sub(r"( |\u200C)+", "", qanon_title)
|
||||
list_equal = []
|
||||
for item in s_res["hits"]["hits"]:
|
||||
title = item['_source']['content']
|
||||
# حذف اسپیسها
|
||||
title_sample = re.sub(r"( |\u200C)+", "", title)
|
||||
|
||||
|
||||
if title_sample == qanon_title_sample :
|
||||
list_equal.append(item)
|
||||
else :
|
||||
qanon_title_sample = get_qanon_title_sample(qanon_title)
|
||||
|
||||
title_sample = get_qanon_title_sample(title)
|
||||
|
||||
if title_sample == qanon_title_sample :
|
||||
list_equal.append(item)
|
||||
|
||||
if len(list_equal) == 1 :
|
||||
item = list_equal[0]
|
||||
score = 90
|
||||
if ts_data == item['_source']['ts_date'] :
|
||||
score = 100
|
||||
return item['_source']["qanon_id"], score, item
|
||||
|
||||
for item in list_equal :
|
||||
if ts_data == item['_source']['ts_date'] :
|
||||
score = 100
|
||||
return item['_source']["qanon_id"], score, item
|
||||
|
||||
if len(list_equal) :
|
||||
score = 80
|
||||
item = list_equal[0]
|
||||
return item['_source']["qanon_id"], score, item
|
||||
|
||||
return 0, 0, {}
|
||||
|
||||
|
||||
def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"):
|
||||
score = 100
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"term": {
|
||||
"title.keyword": {
|
||||
"value": qanon_title
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
s_res = elastic.es.search(index=index_name, body=body)
|
||||
total = s_res["hits"]["total"]['value']
|
||||
if total == 1 :
|
||||
item = s_res["hits"]["hits"][0]
|
||||
return item["_id"], score, item
|
||||
|
||||
if total == 0 :
|
||||
body = {
|
||||
"query": {
|
||||
"more_like_this": {
|
||||
"fields": [
|
||||
"title.fa"
|
||||
],
|
||||
"like": qanon_title,
|
||||
"min_term_freq": 1,
|
||||
"max_query_terms": 12
|
||||
}
|
||||
}
|
||||
}
|
||||
s_res = elastic.es.search(index=index_name, body=body)
|
||||
total = s_res["hits"]["total"]['value']
|
||||
|
||||
qanon_title_sample = re.sub(r"( |\u200C)+", "", qanon_title)
|
||||
list_equal = []
|
||||
for item in s_res["hits"]["hits"]:
|
||||
title = item['_source']['title']
|
||||
# حذف اسپیسها
|
||||
title_sample = get_qanon_title_sample(title)
|
||||
title_sample = re.sub(r"( |\u200C)+", "", title_sample)
|
||||
|
||||
if title_sample == qanon_title_sample :
|
||||
list_equal.append(item)
|
||||
else :
|
||||
qanon_title_sample = get_qanon_title_sample(qanon_title)
|
||||
|
||||
title_sample = get_qanon_title_sample(title)
|
||||
|
||||
if title_sample == qanon_title_sample :
|
||||
list_equal.append(item)
|
||||
|
||||
if len(list_equal) == 1 :
|
||||
item = list_equal[0]
|
||||
score = 90
|
||||
if ts_data == item['_source']['ts_date'] :
|
||||
score = 100
|
||||
return item["_id"], score, item
|
||||
|
||||
for item in list_equal :
|
||||
if ts_data == item['_source']['ts_date'] :
|
||||
score = 100
|
||||
return item["_id"], score, item
|
||||
|
||||
if len(list_equal) :
|
||||
score = 80
|
||||
item = list_equal[0]
|
||||
return item["_id"], score, item
|
||||
|
||||
return 0, 0, {}
|
||||
|
||||
|
||||
def get_qanon_date(title):
|
||||
# regex = r"مصوب(\s*\d{1,4}/\d{1,4}/\d{1,4})\s*$"
|
||||
regex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*$"
|
||||
regex_ex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*((مجلس|کمیسیون|کمیسیونهای|هیات|شورای).{1,50})$"
|
||||
ts_ref = ''
|
||||
qanon_title = ''
|
||||
ts_date = ''
|
||||
title=title.strip().strip(' #=').strip()
|
||||
title=title.replace("=", "#")
|
||||
title=title.replace("#مصوب#", "#مصوب ")
|
||||
title=title.replace("#مصوب #", "#مصوب ")
|
||||
items = title.split('#')
|
||||
if len(items) == 1:
|
||||
qanon_title = items[0]
|
||||
elif items :
|
||||
last = items[-1].strip()
|
||||
if last.startswith('مصوب'):
|
||||
ts_date = last.replace('مصوب', '').strip()
|
||||
qanon_title= ' '.join(items[:-1])
|
||||
# قانون تشكيل#وزارت جهاد سازندگي مصوب 08/09/1362 مجلس شوراي اسلامي
|
||||
elif 'مصوب' in last :
|
||||
qanon_title= ' '.join(items)
|
||||
elif last :
|
||||
ts_ref=last
|
||||
qanon_title= ' '.join(items[:-1])
|
||||
|
||||
# print('qanon_title', qanon_title)
|
||||
|
||||
|
||||
if ts_date == '' :
|
||||
# قانون كار مصوب 26/12/1337
|
||||
match = re.search(regex, qanon_title)
|
||||
if match :
|
||||
#print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}")
|
||||
ts_date = match.group(1).strip()
|
||||
qanon_title = qanon_title[0:match.start()]
|
||||
|
||||
if ts_date == '':
|
||||
match = re.search(regex_ex, qanon_title)
|
||||
if match :
|
||||
#print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}")
|
||||
ts_date = match.group(1).strip()
|
||||
ts_ref = match.group(2).strip()
|
||||
qanon_title = qanon_title[0:match.start()]
|
||||
|
||||
|
||||
return qanon_title, ts_date, ts_ref
|
||||
|
||||
def get_section_correct(title):
|
||||
title=title.strip().strip(' #=').strip()
|
||||
|
||||
if title == 'کل قانون' or title == 'متن قانون' or title == 'متن' or title == 'تمام قانون' or title == 'کل مصوبه':
|
||||
return ['all']
|
||||
|
||||
title=title.replace('"', '')
|
||||
title=title.replace('اصلاحی', '')
|
||||
title = re.sub(r"(\(|\)|\>|\<|-|ـ)+", "", title)
|
||||
|
||||
subs = title.split('،')
|
||||
result = []
|
||||
for item in subs :
|
||||
item=re.sub(r"(جزء|بند|ماده|فصل|مبحث|ردیف|جدول|تبصره|پیوست|قسمت)", r"#\1", item)
|
||||
items = item.split('#')
|
||||
items.reverse()
|
||||
item = '> '.join(items).strip(' >').replace(' ', '')
|
||||
item = text_normalizer.word_digit_correction(item)
|
||||
result.append(item)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get__all_section_qanon(elastic, index_name, qanon_id):
|
||||
body = {
|
||||
"_source" : ["ref_id"],
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"term": {
|
||||
"qanon_id": {
|
||||
"value": qanon_id
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
s_res = elastic.es.search(index=index_name, body=body)
|
||||
result = []
|
||||
for item in s_res["hits"]["hits"] :
|
||||
result.append(item["_id"])
|
||||
return result
|
||||
|
||||
|
||||
|
||||
# qanon_title=" قانون الحاق دو تبصره به عنوان تبصره های 3 و 4 به ماده 9 قانون روابط موجر و مستأجر مصوب 1362.2.13"
|
||||
# qanon_title = get_qanon_title_sample(qanon_title)
|
||||
# print(qanon_title)
|
||||
# qanon_title="قانون الحاق دو تبصره بعنوان تبصره های 3 و 4 به ماده 9 قانون روابط موجر و مستأجر مصوب 13 /2 /1362"
|
||||
# qanon_title = get_qanon_title_sample(qanon_title)
|
||||
# print(qanon_title)
|
||||
@@ -0,0 +1,46 @@
|
||||
import mariadb
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
|
||||
class sql_helper:
|
||||
def __init__(self):
|
||||
config_env = load_dotenv(dotenv_path="./config.env")
|
||||
MYSQL_username = os.getenv("MYSQL_username")
|
||||
MYSQL_root_password = os.getenv("MYSQL_root_password")
|
||||
MYSQL_port = os.getenv("MYSQL_port")
|
||||
MYSQL_host = os.getenv("MYSQL_import_host")
|
||||
self.cnx = mariadb.connect(user="root", password=MYSQL_root_password, host=MYSQL_host)
|
||||
self.cursor = self.cnx.cursor()
|
||||
def create_users(self):
|
||||
password = os.getenv("MYSQL_password")
|
||||
users = os.getenv("MYSQL_username")
|
||||
try:
|
||||
self.cursor.execute(f"CREATE USER '{users}'@'%' IDENTIFIED BY '{password}'")
|
||||
self.cursor.execute(f" GRANT ALL PRIVILEGES ON *.* to '{users}'@'%'")
|
||||
print("create user")
|
||||
except:
|
||||
print("not create user")
|
||||
|
||||
|
||||
def read_file_import(self,filename,name_database):
|
||||
self.cursor.execute(f"use {name_database}")
|
||||
with open(filename, 'r') as file:
|
||||
sqlFile = file.read()
|
||||
file.close()
|
||||
|
||||
sqlCommands = sqlFile.split(';\n')
|
||||
|
||||
for command in sqlCommands:
|
||||
try:
|
||||
if command.rstrip() != '':
|
||||
self.cursor.execute(command)
|
||||
self.cnx.commit()
|
||||
except ValueError as msg:
|
||||
print ("Command skipped: ", msg)
|
||||
def create_database(self,name_database):
|
||||
try:
|
||||
self.cursor.execute(f"CREATE DATABASE {name_database};")
|
||||
self.cnx.commit()
|
||||
print(f"create database {name_database}")
|
||||
except:
|
||||
print(f"not create database {name_database}")
|
||||
@@ -0,0 +1,87 @@
|
||||
import os
|
||||
# from text_normalaizer import TextNormalizer
|
||||
# text_normalaizer = TextNormalizer()
|
||||
# text_normalaizer.split_words("سلام خوبی")
|
||||
|
||||
# from nltk.stem.api import StemmerI
|
||||
# class Stemmer(StemmerI):
|
||||
class Stemmer():
|
||||
"""این کلاس شامل توابعی برای ریشهیابی کلمات است."""
|
||||
|
||||
def __init__(self: "Stemmer") -> None:
|
||||
self.ends = [
|
||||
"ات",
|
||||
"ان",
|
||||
"ترین",
|
||||
"تر",
|
||||
"م",
|
||||
"ت",
|
||||
"ش",
|
||||
"یی",
|
||||
"ی",
|
||||
"ها",
|
||||
"ٔ",
|
||||
"ا",
|
||||
"",
|
||||
]
|
||||
self.dir_path = os.path.dirname(os.path.realpath(__file__)) + "/"
|
||||
self.mokasar_noun_path = self.dir_path + "resource/stemmer/mokasar.txt"
|
||||
self.createDict()
|
||||
|
||||
def createDict(self):
|
||||
self.Plural_dict={}
|
||||
with open(self.mokasar_noun_path, 'r', encoding='utf-8') as file:
|
||||
lines = file.readlines()
|
||||
for line in lines:
|
||||
words = line.strip().split('\t')
|
||||
if len(words) == 2:
|
||||
self.Plural_dict[words[0]] = words[1]
|
||||
def stem(self: "Stemmer", word: str) -> str:
|
||||
"""ریشهٔ کلمه را پیدا میکند.
|
||||
|
||||
Examples:
|
||||
>>> stemmer = Stemmer()
|
||||
>>> stemmer.stem('کتابی')
|
||||
'کتاب'
|
||||
>>> stemmer.stem('کتابها')
|
||||
'کتاب'
|
||||
>>> stemmer.stem('کتابهایی')
|
||||
'کتاب'
|
||||
>>> stemmer.stem('کتابهایشان')
|
||||
'کتاب'
|
||||
>>> stemmer.stem('اندیشهاش')
|
||||
'اندیشه'
|
||||
>>> stemmer.stem('خانۀ')
|
||||
'خانه'
|
||||
|
||||
Args:
|
||||
word: کلمهای که باید ریشهٔ آن پیدا شود.
|
||||
|
||||
Returns:
|
||||
ریشهٔ کلمه.
|
||||
|
||||
"""
|
||||
# این بخش برای حذف پسوندهای اسمی در استمینگ هضم طراحی شده است
|
||||
for end in self.ends:
|
||||
if word.endswith(end):
|
||||
word = word[:-len(end)]
|
||||
|
||||
if word.endswith("ۀ"):
|
||||
word = word[:-1] + "ه"
|
||||
|
||||
# این بخش برای تبدیل جمع مکسر به دستور استمینگ هضم اضافه شده است. بعد از حذف پسوندها، جمع مکسر باشد، تبدیل به مفرد می شود
|
||||
if word in self.Plural_dict:
|
||||
word = self.Plural_dict.get(word)
|
||||
|
||||
return word
|
||||
|
||||
# if __name__ == "__main__":
|
||||
# mokasar = "StemLemma/resource/mokasar.txt"
|
||||
# with open(mokasar, 'r', encoding='utf-8') as file:
|
||||
# lines = file.readlines()
|
||||
# dictionary = {}
|
||||
# for line in lines:
|
||||
# words = line.strip().split('\t')
|
||||
# if len(words) == 2:
|
||||
# dictionary[words[0]] = words[1]
|
||||
# print(dictionary)
|
||||
@@ -0,0 +1,410 @@
|
||||
|
||||
import re
|
||||
|
||||
class TextNormalizer:
|
||||
def __init__(self, options=None):
|
||||
|
||||
self.options = options if options else {
|
||||
"charArNormal": True,
|
||||
"errorLine": True,
|
||||
"alphabetsNormal": False,
|
||||
"emptylinesNormal": False,
|
||||
"hamzehNormal": False,
|
||||
"spaceCorrection": False,
|
||||
"trimLine": False
|
||||
}
|
||||
|
||||
def split_words(self, text) :
|
||||
if not text :
|
||||
return []
|
||||
### “”
|
||||
words = re.split(r"[\t\n\r\.\'\"«»\)\(\]\[\{\}\%\#\$\*\<\>\/,;،؛ \-!?:٭؟]+", text)
|
||||
return words
|
||||
|
||||
def normalize_search_qanon(self, text, error_state=False):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = text.strip()
|
||||
# اصلاح خطاهای متن در کد خط
|
||||
|
||||
text = self.replace_alphabets(text)
|
||||
|
||||
# اعداد چسبیده به کلمات را با یک فاصله جدا می کند
|
||||
# text = self.word_digit_correction(text)
|
||||
|
||||
text = text.replace("\u00a0", " ") # No Break space
|
||||
text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL
|
||||
|
||||
#فاصله های تکراری و خطوط خالی تکراری را یکی می کند
|
||||
text = re.sub(r"( )+", " ", text)
|
||||
text = re.sub(r"(\n)+", "", text)
|
||||
|
||||
# نرمال کردن حروف اختلافی عربی و فارسی
|
||||
text = self.yeke_normal(text)
|
||||
|
||||
|
||||
# text = self.hamzah_normal(text)
|
||||
# text = self.alaem_normal(text)
|
||||
|
||||
return text
|
||||
|
||||
def normalize_qanon(self, text, error_state=False):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = text.strip()
|
||||
# اصلاح خطاهای متن در کد خط
|
||||
|
||||
text = text.replace("\\n", "\n")
|
||||
text = text.replace("\\r", "\r")
|
||||
text = re.sub(r"(\r\n)+", "\n", text)
|
||||
text = text.replace("\r", "\n")
|
||||
|
||||
# یکسان سازی اختلاف حروف کیبوردهای مختلف - کدهای مختلف ولی نمایش یکسان
|
||||
if error_state :
|
||||
text = self.replace_alphabets_error(text)
|
||||
else :
|
||||
text = self.replace_alphabets(text)
|
||||
|
||||
# اعداد چسبیده به کلمات را با یک فاصله جدا می کند
|
||||
text = self.word_digit_correction(text)
|
||||
|
||||
#فاصله های تکراری و خطوط خالی تکراری را یکی می کند
|
||||
text = re.sub(r"( )+", " ", text)
|
||||
text = re.sub(r"(\n)+", "\n", text)
|
||||
|
||||
# نرمال کردن حروف اختلافی عربی و فارسی
|
||||
text = text.replace("ي", "ی")
|
||||
text = text.replace("ك", "ک")
|
||||
|
||||
return text
|
||||
|
||||
def normalize_qanon_test(self, text):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = text.replace("\u00a0", " ") # No Break space
|
||||
text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL
|
||||
|
||||
text = self.word_digit_correction(text)
|
||||
text = re.sub(r"( )+", " ", text)
|
||||
|
||||
text = self.space_correction(text)
|
||||
text = self.heha_correction(text)
|
||||
|
||||
return text
|
||||
|
||||
|
||||
def normalize_text(self, text):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = text.strip()
|
||||
# اصلاح خطاهای متن در کد خط
|
||||
if self.options.get("errorLine", False):
|
||||
text = text.replace("\\n", "\n")
|
||||
text = text.replace("\\r", "\r")
|
||||
text = re.sub(r"(\r\n)+", "\n", text)
|
||||
text = text.replace("\r", "\n")
|
||||
# یکسان سازی اختلاف حروف کیبوردهای مختلف - کدهای مختلف ولی نمایش یکسان
|
||||
if self.options.get("alphabetsNormal", False):
|
||||
text = self.replace_alphabets(text)
|
||||
# حذف خطوط و فاصلههای خالی
|
||||
if self.options.get("emptylinesNormal", False):
|
||||
text = re.sub(r"( )+", " ", text)
|
||||
text = re.sub(r"(\n)+", "\n", text)
|
||||
# نرمال کردن حروف اختلافی عربی و فارسی
|
||||
if self.options.get("charArNormal", True):
|
||||
text = self.yeke_normal(text)
|
||||
# پرش از اختلافات همزها
|
||||
if self.options.get("hamzehNormal", False):
|
||||
text = self.hamzah_normal(text)
|
||||
|
||||
# اصلاح فاصلهها در ترکیب کلمات
|
||||
if self.options.get("spaceCorrection", False):
|
||||
text = self.space_correction(text)
|
||||
# حذف خطوط اضافی اول و انتهای متن
|
||||
if self.options.get("trimLine", False):
|
||||
text = text.strip()
|
||||
|
||||
return text
|
||||
|
||||
def alaem_normal(self, text):
|
||||
text = re.sub(r"[\t\n\r\.\'\"«»\)\(\]\[\{\}\%\#\$\*\<\>\/,;،؛\-!?:٭؟]+", "", text)
|
||||
return text
|
||||
|
||||
def yeke_normal(self, text):
|
||||
text = text.replace("ي", "ی")
|
||||
text = text.replace("ك", "ک")
|
||||
return text
|
||||
|
||||
def hamzah_normal(self, text):
|
||||
text = re.sub(r"ئ|ﺋ", "ی", text)
|
||||
text = re.sub(r"ؤ|ﺅ", "و", text)
|
||||
text = re.sub(r"ﺔ|ۀ|ة", "ه", text)
|
||||
text = re.sub(r"إ|أ", "ا", text)
|
||||
return text
|
||||
|
||||
|
||||
def replace_alphabets_error(self, text):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL
|
||||
|
||||
text = re.sub(r"\u00AD|\u00AC", "\u200C", text) # نیم اسپیس خاص
|
||||
text = re.sub(r"(\u002C)+", "\u200C", text) # نیم اسپیس تکراری
|
||||
text = re.sub(r"ﺁ|آ", "آ", text)
|
||||
text = re.sub(r"ﺎ|ٱ|ﺍ", "ا", text)
|
||||
text = re.sub(r"ٲ|أ|ﺄ|ﺃ", "أ", text)
|
||||
text = re.sub(r"ﺈ|ﺇ", "إ", text)
|
||||
text = re.sub(r"ﺐ|ﺏ|ﺑ|ﺒ", "ب", text)
|
||||
text = re.sub(r"ﭖ|ﭗ|ﭙ|ﭘ", "پ", text)
|
||||
text = re.sub(r"ﭡ|ٺ|ٹ|ﭞ|ٿ|ټ|ﺕ|ﺗ|ﺖ|ﺘ", "ت", text)
|
||||
text = re.sub(r"ﺙ|ﺛ|ﺚ|ﺜ", "ث", text)
|
||||
text = re.sub(r"ﺝ|ڃ|ﺠ|ﺟ", "ج", text)
|
||||
text = re.sub(r"ڃ|ﭽ|ﭼ", "چ", text)
|
||||
text = re.sub(r"ﺢ|ﺤ|څ|ځ|ﺣ", "ح", text)
|
||||
text = re.sub(r"ﺥ|ﺦ|ﺨ|ﺧ", "خ", text)
|
||||
text = re.sub(r"ڏ|ډ|ﺪ|ﺩ", "د", text)
|
||||
text = re.sub(r"ﺫ|ﺬ|ذ", "ذ", text)
|
||||
text = re.sub(r"ڙ|ڗ|ڒ|ڑ|ڕ|ﺭ|ﺮ", "ر", text)
|
||||
text = re.sub(r"ﺰ|ﺯ", "ز", text)
|
||||
text = re.sub(r"ﮊ", "ژ", text)
|
||||
text = re.sub(r"ݭ|ݜ|ﺱ|ﺲ|ښ|ﺴ|ﺳ", "س", text)
|
||||
text = re.sub(r"ﺵ|ﺶ|ﺸ|ﺷ", "ش", text)
|
||||
text = re.sub(r"ﺺ|ﺼ|ﺻ|ﺹ", "ص", text)
|
||||
text = re.sub(r"ﺽ|ﺾ|ﺿ|ﻀ", "ض", text)
|
||||
text = re.sub(r"ﻁ|ﻂ|ﻃ|ﻄ", "ط", text)
|
||||
text = re.sub(r"ﻆ|ﻇ|ﻈ", "ظ", text)
|
||||
text = re.sub(r"ڠ|ﻉ|ﻊ|ﻋ|ﻌ", "ع", text)
|
||||
text = re.sub(r"ﻎ|ۼ|ﻍ|ﻐ|ﻏ", "غ", text)
|
||||
text = re.sub(r"ﻒ|ﻑ|ﻔ|ﻓ", "ف", text)
|
||||
text = re.sub(r"ﻕ|ڤ|ﻖ|ﻗ|ﻘ", "ق", text)
|
||||
text = re.sub(r"ڭ|ﻚ|ﮎ|ﻜ|ﮏ|ګ|ﻛ|ﮑ|ﮐ|ڪ|ك", "ک", text)
|
||||
text = re.sub(r"ﮚ|ﮒ|ﮓ|ﮕ|ﮔ", "گ", text)
|
||||
text = re.sub(r"ﻝ|ﻞ|ﻠ|ڵ|ﻟ", "ل", text)
|
||||
text = re.sub(r"ﻵ|ﻶ|ﻷ|ﻸ|ﻹ|ﻺ|ﻻ|ﻼ", "لا", text)
|
||||
text = re.sub(r"ﻡ|ﻤ|ﻢ|ﻣ", "م", text)
|
||||
text = re.sub(r"ڼ|ﻦ|ﻥ|ﻨ|ﻧ", "ن", text)
|
||||
text = re.sub(r"ވ|ﯙ|ۈ|ۋ|ﺆ|ۊ|ۇ|ۏ|ۅ|ۉ|ﻭ|ﻮ|ؤ", "و", text)
|
||||
text = re.sub(r"ﻬ|ھ|ﻩ|ﻫ|ﻪ|ە|ہ", "ه", text)
|
||||
text = re.sub(r"ﭛ|ﻯ|ۍ|ﻰ|ﻱ|ﻲ|ں|ﻳ|ﻴ|ﯼ|ې|ﯽ|ﯾ|ﯿ|ێ|ے|ى|ي", "ی", text)
|
||||
text = re.sub(r"¬", "", text)
|
||||
text = re.sub(r"•|·|●|·|・|∙|。|ⴰ", ".", text)
|
||||
text = re.sub(r",|٬|٫|‚|،", "،", text)
|
||||
text = re.sub(r"ʕ", "؟", text)
|
||||
text = re.sub(r"”|“", "\"", text)
|
||||
text = re.sub(r"۰|٠", "0", text)
|
||||
text = re.sub(r"۱|١", "1", text)
|
||||
text = re.sub(r"۲|٢", "2", text)
|
||||
text = re.sub(r"۳|٣", "3", text)
|
||||
text = re.sub(r"۴|٤", "4", text)
|
||||
text = re.sub(r"۵", "5", text)
|
||||
text = re.sub(r"۶|٦", "6", text)
|
||||
text = re.sub(r"۷|٧", "7", text)
|
||||
text = re.sub(r"۸|٨", "8", text)
|
||||
text = re.sub(r"۹|٩", "9", text)
|
||||
text = re.sub(r"²", "2", text)
|
||||
text = re.sub(r"|ِ|ُ|َ|ٍ|ٌ|ً|", "", text)
|
||||
|
||||
text = re.sub(r"ـ", "", text) # حذف حروف کشیده # این باعث خطای حذف اضافی شد و با خط بعدی جایگزین شد
|
||||
return text
|
||||
|
||||
def replace_alphabets(self, text):
|
||||
if not text :
|
||||
return ""
|
||||
|
||||
text = re.sub(r"\u200e|\u200f", " ", text) # LTR, RTL
|
||||
|
||||
|
||||
text = re.sub(r"\u00AD|\u00AC", "\u200C", text) # نیم اسپیس خاص
|
||||
text = re.sub(r"(\u002C)+", "\u200C", text) # نیم اسپیس تکراری
|
||||
text = re.sub(r"ﺁ|آ", "آ", text)
|
||||
text = re.sub(r"ﺎ|ٱ|ﺍ", "ا", text)
|
||||
text = re.sub(r"ٲ|أ|ﺄ|ﺃ", "أ", text)
|
||||
text = re.sub(r"ﺈ|ﺇ", "إ", text)
|
||||
text = re.sub(r"ﺐ|ﺏ|ﺑ|ﺒ", "ب", text)
|
||||
text = re.sub(r"ﭖ|ﭗ|ﭙ|ﭘ", "پ", text)
|
||||
text = re.sub(r"ﭡ|ٺ|ٹ|ﭞ|ٿ|ټ|ﺕ|ﺗ|ﺖ|ﺘ", "ت", text)
|
||||
text = re.sub(r"ﺙ|ﺛ|ﺚ|ﺜ", "ث", text)
|
||||
text = re.sub(r"ﺝ|ڃ|ﺠ|ﺟ", "ج", text)
|
||||
text = re.sub(r"ڃ|ﭽ|ﭼ", "چ", text)
|
||||
text = re.sub(r"ﺢ|ﺤ|څ|ځ|ﺣ", "ح", text)
|
||||
text = re.sub(r"ﺥ|ﺦ|ﺨ|ﺧ", "خ", text)
|
||||
text = re.sub(r"ڏ|ډ|ﺪ|ﺩ", "د", text)
|
||||
text = re.sub(r"ﺫ|ﺬ|ذ", "ذ", text)
|
||||
text = re.sub(r"ڙ|ڗ|ڒ|ڑ|ڕ|ﺭ|ﺮ", "ر", text)
|
||||
text = re.sub(r"ﺰ|ﺯ", "ز", text)
|
||||
text = re.sub(r"ﮊ", "ژ", text)
|
||||
text = re.sub(r"ݭ|ݜ|ﺱ|ﺲ|ښ|ﺴ|ﺳ", "س", text)
|
||||
text = re.sub(r"ﺵ|ﺶ|ﺸ|ﺷ", "ش", text)
|
||||
text = re.sub(r"ﺺ|ﺼ|ﺻ|ﺹ", "ص", text)
|
||||
text = re.sub(r"ﺽ|ﺾ|ﺿ|ﻀ", "ض", text)
|
||||
text = re.sub(r"ﻁ|ﻂ|ﻃ|ﻄ", "ط", text)
|
||||
text = re.sub(r"ﻆ|ﻇ|ﻈ", "ظ", text)
|
||||
text = re.sub(r"ڠ|ﻉ|ﻊ|ﻋ|ﻌ", "ع", text)
|
||||
text = re.sub(r"ﻎ|ۼ|ﻍ|ﻐ|ﻏ", "غ", text)
|
||||
text = re.sub(r"ﻒ|ﻑ|ﻔ|ﻓ", "ف", text)
|
||||
text = re.sub(r"ﻕ|ڤ|ﻖ|ﻗ|ﻘ", "ق", text)
|
||||
text = re.sub(r"ڭ|ﻚ|ﮎ|ﻜ|ﮏ|ګ|ﻛ|ﮑ|ﮐ|ڪ|ك", "ک", text)
|
||||
text = re.sub(r"ﮚ|ﮒ|ﮓ|ﮕ|ﮔ", "گ", text)
|
||||
text = re.sub(r"ﻝ|ﻞ|ﻠ|ڵ|ﻟ", "ل", text)
|
||||
text = re.sub(r"ﻵ|ﻶ|ﻷ|ﻸ|ﻹ|ﻺ|ﻻ|ﻼ", "لا", text)
|
||||
text = re.sub(r"ﻡ|ﻤ|ﻢ|ﻣ", "م", text)
|
||||
text = re.sub(r"ڼ|ﻦ|ﻥ|ﻨ|ﻧ", "ن", text)
|
||||
text = re.sub(r"ވ|ﯙ|ۈ|ۋ|ﺆ|ۊ|ۇ|ۏ|ۅ|ۉ|ﻭ|ﻮ|ؤ", "و", text)
|
||||
text = re.sub(r"ﻬ|ھ|ﻩ|ﻫ|ﻪ|ە|ہ", "ه", text)
|
||||
text = re.sub(r"ﭛ|ﻯ|ۍ|ﻰ|ﻱ|ﻲ|ں|ﻳ|ﻴ|ﯼ|ې|ﯽ|ﯾ|ﯿ|ێ|ے|ى|ي", "ی", text)
|
||||
text = re.sub(r"¬", "", text)
|
||||
text = re.sub(r"•|·|●|·|・|∙|。|ⴰ", ".", text)
|
||||
text = re.sub(r",|٬|٫|‚|،", "،", text)
|
||||
text = re.sub(r"ʕ", "؟", text)
|
||||
text = re.sub(r"”|“", "\"", text)
|
||||
text = re.sub(r"۰|٠", "0", text)
|
||||
text = re.sub(r"۱|١", "1", text)
|
||||
text = re.sub(r"۲|٢", "2", text)
|
||||
text = re.sub(r"۳|٣", "3", text)
|
||||
text = re.sub(r"۴|٤", "4", text)
|
||||
text = re.sub(r"۵", "5", text)
|
||||
text = re.sub(r"۶|٦", "6", text)
|
||||
text = re.sub(r"۷|٧", "7", text)
|
||||
text = re.sub(r"۸|٨", "8", text)
|
||||
text = re.sub(r"۹|٩", "9", text)
|
||||
text = re.sub(r"²", "2", text)
|
||||
text = re.sub(r"|ِ|ُ|َ|ٍ|ٌ|ً|", "", text)
|
||||
|
||||
#text = re.sub(r"ـ", "", text) # حذف حروف کشیده # این باعث خطای حذف اضافی شد و با خط بعدی جایگزین شد
|
||||
text = re.sub(r'([\u0600-\u06FF])ـ([\u0600-\u06FF])', r'\1\2', text) # حذف حروف کشیده
|
||||
text = re.sub(r'([\u0600-\u06FF])ـ', r'\1', text) # حذف حروف کشیده
|
||||
|
||||
return text
|
||||
|
||||
|
||||
def date_correction(self, text):
|
||||
|
||||
text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1/\2/\3", text)
|
||||
text = re.sub(r"(\d+?)ر(\d+?)", r"\1/\2", text)
|
||||
|
||||
text = re.sub(r"(\d+?) /(\d+?) /(\d+?)", r"\1/\2/\3", text)
|
||||
# text = re.sub(r"(\d+?) \\(\d+?) \\(\d+?)", r"\1/\2/\3", text)
|
||||
|
||||
|
||||
# # فرمت YYYY/MM/DD یا YYYY-MM-DD --> YYYY/MM/DD
|
||||
# text = re.sub(r'(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})', r'\1/\2/\3', text)
|
||||
|
||||
# فرمت DD/MM/YYYY یا DD-MM-YYYY ---> YYYY/MM/DD
|
||||
text = re.sub(r'(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})', r'\3/\2/\1', text)
|
||||
text = re.sub(r' (\d{1})[\/\-](\d{1})[\/\-](\d{4})', r' 0\1/0\2/\3', text)
|
||||
text = re.sub(r' (\d{1})[\/\-](\d{2})[\/\-](\d{4})', r' 0\1/\2/\3', text)
|
||||
text = re.sub(r' (\d{2})[\/\-](\d{1})[\/\-](\d{4})', r' \1/0\2/\3', text)
|
||||
return text
|
||||
|
||||
|
||||
def space_correction(self, text):
|
||||
|
||||
text = re.sub(r"^(بی|می|نمی)( )", r"\1", text)
|
||||
text = re.sub(r"( )(می|نمی|بی)( )", r"\1\2", text)
|
||||
text = re.sub(
|
||||
r"( )(هایی|ها|های|ایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|ات|ان|ین|انی|بان|ام|ای|یم|ید|اید|اند|بودم|بودی|بود|بودیم|بودید|بودند|ست)( )",
|
||||
r"\2\3",
|
||||
text,
|
||||
)
|
||||
# text = re.sub(r"( )(شده|نشده)( )", r"\2", text)
|
||||
text = re.sub(
|
||||
r"( )(طلبان|طلب|گرایی|گرایان|شناس|شناسی|گذاری|گذار|گذاران|شناسان|گیری|پذیری|بندی|آوری|سازی|بندی|کننده|کنندگان|گیری|پرداز|پردازی|پردازان|آمیز|سنجی|ریزی|داری|دهنده|آمیز|پذیری|پذیر|پذیران|گر|ریز|ریزی|رسانی|یاب|یابی|گانه|گانهای|انگاری|گا|بند|رسانی|دهندگان|دار)( )",
|
||||
r"\2\3",
|
||||
text,
|
||||
)
|
||||
return text
|
||||
|
||||
|
||||
# اعداد چسبیده به کلمات را با یک فاصله جدا می کند
|
||||
def word_digit_correction(self, text):
|
||||
|
||||
text = re.sub(r"(\200C)(\d+)", r" \2", text)
|
||||
text = re.sub(r"(\d+)(\200C)", r"\1 ", text)
|
||||
|
||||
text = re.sub(r"(\200C)([\t\n\r\.\'\"«»\)\(\]\[\{\}\#\$\*\<\>\/,;،؛ \-!?:٭؟])", r" \2", text)
|
||||
text = re.sub(r"([\t\n\r\.\'\"«»\)\(\]\[\{\}\#\$\*\<\>\/,;،؛ \-!?:٭؟])(\200C)", r"\1 ", text)
|
||||
|
||||
# ## شماره22 -> شماره 22 22/ش2
|
||||
# ### no ش/22 شد\22
|
||||
# text = re.sub(r"([^\d \/\\]+?)(\d)", r"\1 \2", text)
|
||||
# text = re.sub(r"(\d+)([^\d \/\\]+?)", r"\1 \2", text)
|
||||
text = re.sub(r"[^\/](\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1 \2", text)
|
||||
text = re.sub(r"([\u0600-\u06FF\u0750-\u077F]+?)(\d+)", r"\1 \2", text)
|
||||
|
||||
|
||||
# ر54ر44ر135
|
||||
text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1\/\2\/\3", text)
|
||||
text = re.sub(r"(\d+?)ر(\d+?)", r"\1\/\2", text)
|
||||
|
||||
# text = re.sub(r"(\w+)(\d+)", r"\1 \2", text)
|
||||
# text = re.sub(r"(\d+)(\w+)", r"\1 \2", text)
|
||||
|
||||
return text
|
||||
|
||||
## رسیدگیها -> رسیدگیها
|
||||
def heha_correction(self, text):
|
||||
text = re.sub(r"(ه)(ها )", r"\1\2", text)
|
||||
text = re.sub(r"(ه)(های )", r"\1\2", text)
|
||||
|
||||
text = re.sub(r"(ی)(ها )", r"\1\2", text)
|
||||
text = re.sub(r"(ی)(های )", r"\1\2", text)
|
||||
return text
|
||||
|
||||
|
||||
def pad_left(self, s, length, char=' '):
|
||||
if len(s) >= length:
|
||||
return s
|
||||
else:
|
||||
return char * (length - len(s)) + s
|
||||
# erab
|
||||
def remove_arabic_diacritics(self, text):
|
||||
# Regular expression to match all Arabic diacritics
|
||||
diacritics_pattern = r'[\u064B-\u0652\u0670]'
|
||||
return re.sub(diacritics_pattern, '', text)
|
||||
|
||||
|
||||
|
||||
|
||||
# # تست برنامه
|
||||
# options = {
|
||||
# "charArNormal": True, # نرمال کردن حروف عربی و فارسی
|
||||
# "errorLine": True, # اصلاح خطاهای مربوط به خطوط و کاراکترها
|
||||
# "alphabetsNormal": True, # نرمالسازی حروف
|
||||
# "emptylinesNormal": True, # حذف فاصلههای اضافی
|
||||
# "hamzehNormal": True, # اصلاح همزهها
|
||||
# "spaceCorrection": True, # اصلاح فاصلهها در ترکیب کلمات
|
||||
# "trimLine": True # حذف فضای خالی اضافی در ابتدا و انتهای متن
|
||||
# }
|
||||
|
||||
# normalizer = TextNormalizer()
|
||||
# text = """
|
||||
# سلام -- ـ ـ خوبی
|
||||
# دادی ییی بی داد
|
||||
# آیا ١٢۳۴۴۵۶۷٨ ، دادی یا ندادی؟
|
||||
# ـ تغییرات جدید ٠۹۸٧٦٥٤٣٢١
|
||||
# دربارهی ﻻ|ﻻ یا مثلا ﻷ صحبت کنیم.
|
||||
# """
|
||||
# text = """
|
||||
# بند 2 ـ متن زير جايگزين ماده (17) قانون مي شود و مواد (19)، (20) و (22) و مواد (27) تا (32) و تبصره هاي آنها حذف مي شوند:
|
||||
# ماده 17 ـ اموال و دارايي هايي كه در نتيجه فوت شخص اعم از فوت واقعي يا فرضي انتقال مي يابد، به شرح زير مشمول ماليات است:
|
||||
# 1 ـ نسبت به سپرده هاي بانكي، اوراق مشاركت و ساير اوراق بهادار به استثناي موارد مندرج در بند (2) اين ماده و سودهاي متعلق به آنها و همچنين سود سهام و سهم الشركه تا تاريخ ثبت انتقال به نام وراث و يا پرداخت و تحويل به آنها به نرخ سه درصد (3 ٪)
|
||||
# 2 ـ نسبت به سهام و سهم الشركه و حق تقدم آنها يك و نيم (5 /1) برابر نرخهاي مذكور در تبصره (1) ماده (143) و ماده (143 مكرر) اين قانون طبق مقررات مزبور در تاريخ ثبت انتقال به نام وراث
|
||||
# 3 ـ نسبت به حق الامتياز و ساير اموال و حقوق مالي كه در بندهاي مذكور به آنها تصريح نشده است، به نرخ ده درصد (10 ٪) ارزش روز در تاريخ تحويل يا ثبت انتقال به نام وراث
|
||||
# 4 ـ نسبت به انواع وسايل نقليه موتوري، زميني، دريايي و هوايي به نرخ دو درصد (2 ٪) بهاي اعلامي توسط سازمان امور مالياتي كشور در تاريخ ثبت انتقال به نام وراث
|
||||
# 5 ـ نسبت به املاك و حق واگذاري محل يك و نيم (5 /1) برابر نرخهاي مذكور در ماده (59) اين قانون به مأخذ ارزش معاملاتي املاك و يا به مأخذ ارزش روز حق واگذاري حسب مورد، در تاريخ ثبت انتقال به نام وراث
|
||||
# 6 ـ نسبت به اموال و دارايي هاي متعلق به متوفاي ايراني كه در خارج از كشور واقع شده است پس از كسر ماليات بر ارثي كه از آن بابت به دولت محل وقوع اموال و دارايي ها پرداخت شده است به نرخ ده درصد (10 ٪) ارزش ماترك كه مأخذ محاسبه ماليات بر ارث در كشور محل وقوع مال قرار گرفته است. در صورت عدم شمول ماليات بر ارث در كشور مزبور به مأخذ ارزش روز انتقال يا تحويل به نام وراث
|
||||
# تبصره 1 ـ محاسبه و اخذ ماليات بر ارث در مورد متوفيان قبل از لازم الاجراء شدن اين قانون (1 /1 /1395) اعم از اينكه پرونده مالياتي براي آنها تشكيل شده يا نشده باشد، مشمول حكم اين ماده نخواهد بود.
|
||||
# تبصره 2 ـ نرخهاي مذكور در اين ماده مربوط به وراث طبقه اول است. در صورتي كه وراث طبقات دوم و سوم باشند، نرخهاي مذكور در اين ماده به ترتيب دو و چهار برابر خواهد شد.
|
||||
# تبصره 3 ـ در صورتي كه متوفي و وراث، تبعه خارجي باشند، اموال و دارايي هاي متوفي كه در ايران واقع است، مشمول ماليات به نرخ وراث طبقه اول خواهد بود.
|
||||
# تبصره 4 ـ در مواردي كه وراث سهم خود از اموال موضوع بندهاي (2)، (4) و (5) اين ماده را به اشخاص ثالث يا وراث ديگر انتقال دهند، علاوه بر ماليات بر ارث به شرح اين فصل، مشمول ماليات طبق مقررات فصول مربوط خواهند بود.
|
||||
# تبصره 5 ـ حقوق ناشي از عقود اجاره به شرط تمليك با بانكها و ساير نهادهاي مالي و اعتباري، نسبت به عرصه و اعيان املاك بر اساس ارزش معاملاتي در تاريخ ثبت انتقال به نام وراث محاسبه خواهد شد.
|
||||
# """
|
||||
# # text="سلـام"
|
||||
# # text="46- متون زیر به عنوان تبصره های ( 3 ) و ( 4 ) به ماده (-187-) قانون الحاق می شود:"
|
||||
# normalized_text = normalizer.normalize_qanon(text)
|
||||
# print(normalized_text)
|
||||
@@ -0,0 +1,59 @@
|
||||
import re
|
||||
|
||||
|
||||
class Tokenizer():
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def tokenize_words(self, doc_string):
|
||||
token_list = doc_string.strip().split()
|
||||
#token_list = [x.strip("\u200c").strip('\u200f') for x in token_list if len(x.strip("\u200c")) != 0]
|
||||
new_token_list = []
|
||||
new_token = ''
|
||||
for index,token in enumerate(token_list):
|
||||
if len(token.strip("\u200c")) != 0:
|
||||
new_token = token.strip("\u200c")
|
||||
if len(token.strip("\u200f")) != 0:
|
||||
new_token = new_token.strip('\u200f')
|
||||
new_token_list.append(new_token)
|
||||
return new_token_list
|
||||
|
||||
def tokenize_sentences(self, doc_string):
|
||||
#finding the numbers
|
||||
pattern = r"[-+]?\d*\.\d+|\d+"
|
||||
nums_list = re.findall(pattern, doc_string)
|
||||
doc_string = re.sub(pattern, 'floatingpointnumber', doc_string)
|
||||
|
||||
pattern = r'([!\.\?؟]+)[\n]*'
|
||||
tmp = re.findall(pattern, doc_string)
|
||||
doc_string = re.sub(pattern, self.add_tab, doc_string)
|
||||
|
||||
pattern = r':\n'
|
||||
tmp = re.findall(pattern, doc_string)
|
||||
doc_string = re.sub(pattern, self.add_tab, doc_string)
|
||||
|
||||
pattern = r';\n'
|
||||
tmp = re.findall(pattern, doc_string)
|
||||
doc_string = re.sub(pattern, self.add_tab, doc_string)
|
||||
|
||||
pattern = r'؛\n'
|
||||
tmp = re.findall(pattern, doc_string)
|
||||
doc_string = re.sub(pattern, self.add_tab, doc_string)
|
||||
|
||||
pattern = r'[\n]+'
|
||||
doc_string = re.sub(pattern, self.add_tab, doc_string)
|
||||
|
||||
for number in nums_list:
|
||||
pattern = 'floatingpointnumber'
|
||||
doc_string = re.sub(pattern, number, doc_string, 1)
|
||||
|
||||
doc_string = doc_string.split('\t\t')
|
||||
doc_string = [x for x in doc_string if len(x) > 0]
|
||||
return doc_string
|
||||
|
||||
def add_tab(self, mystring):
|
||||
mystring = mystring.group() # this method return the string matched by re
|
||||
mystring = mystring.strip(' ') # ommiting the whitespace around the pucntuation
|
||||
mystring = mystring.strip('\n') # ommiting the newline around the pucntuation
|
||||
mystring = " " + mystring + "\t\t" # adding a space after and before punctuation
|
||||
return mystring
|
||||
@@ -0,0 +1,92 @@
|
||||
|
||||
import os
|
||||
import yaml
|
||||
|
||||
|
||||
class VersionUtil():
|
||||
|
||||
data_t_location = "./data/"
|
||||
def __init__(self, data_t_location):
|
||||
self.data_t_location = data_t_location
|
||||
|
||||
def chack_folder_full(self, list_folder: list):
|
||||
for a in list_folder:
|
||||
if a == "full":
|
||||
return True
|
||||
if a == "update":
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def chack_version(self, version_old : dict, version_new : dict, name_part : str):
|
||||
if version_old[name_part] < version_new[name_part]:
|
||||
return True
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def find_version(self):
|
||||
data_file_version_local = {}
|
||||
try:
|
||||
with open(f"{self.data_t_location}VERSION_local", "r") as file_yaml_version_local:
|
||||
data_file_version_local = yaml.safe_load(file_yaml_version_local)
|
||||
|
||||
except:
|
||||
print("not fund file version local")
|
||||
|
||||
if data_file_version_local == {} or data_file_version_local == None:
|
||||
print("None data for local")
|
||||
data_file_version_local = {"version": {"db": 0.0, "elastic": 0.0, "dist": 0.0}}
|
||||
|
||||
try:
|
||||
with open(f"{self.data_t_location}VERSION", "r") as file_yaml_version_new:
|
||||
data_file_version_new = yaml.safe_load(file_yaml_version_new)
|
||||
|
||||
except:
|
||||
print("not fund file yaml new VERSION")
|
||||
exit(1)
|
||||
try:
|
||||
return {"ver_new":data_file_version_new["version"],"ver_local":data_file_version_local["version"]}
|
||||
except:
|
||||
print("file yaml local empety")
|
||||
data_file_version_local = {"version": {"db": 0.0, "elastic": 0.0, "dist": 0.0}}
|
||||
return {"ver_new":data_file_version_new["version"],"ver_local":data_file_version_local["version"]}
|
||||
|
||||
|
||||
def find_location_folder_version(self, version_local:str,version_new:str,name_service:str):
|
||||
|
||||
version_local = str(version_local).split(".")
|
||||
version_new = str(version_new).split(".")
|
||||
version_local_full_namber = int(version_local[0])
|
||||
version_local_update_namber = int(version_local[1])
|
||||
version_new_full_namber = int(version_new[0])
|
||||
version_new_update_namber = int(version_new[1])
|
||||
list_location = []
|
||||
if version_local_full_namber == version_new_full_namber :
|
||||
for versions in range(version_local_update_namber,version_new_update_namber):
|
||||
list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{versions+1}/update")
|
||||
if version_local_update_namber == version_new_update_namber :
|
||||
list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{version_new_update_namber}/update")
|
||||
print(list_location)
|
||||
else :
|
||||
list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{0}/full")
|
||||
for versions in range(0,version_new_update_namber):
|
||||
list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{versions+1}/update")
|
||||
if version_local_update_namber == version_new_update_namber :
|
||||
list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{version_new_update_namber}/full")
|
||||
print(list_location)
|
||||
|
||||
return list_location
|
||||
|
||||
|
||||
def version_local_write(self, data_version_file:dict):
|
||||
try:
|
||||
os.remove(f"{self.data_t_location}VERSION_local")
|
||||
except:
|
||||
print("not fund file local")
|
||||
with open(f"{self.data_t_location}VERSION_local","w") as file_local:
|
||||
yaml.dump(data_version_file,file_local)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import zipfile
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from ..common.text_normalizer import TextNormalizer
|
||||
# from general import *
|
||||
from ..common.general_functions import *
|
||||
from ..common.elastic_helper import ElasticHelper
|
||||
|
||||
### --------------------------------------------------------------
|
||||
## این کد برای استخراج و بهینه سازی کلیدواژه های تولید شده با مدلهای زبانی بزرگ و انتقال به الاستیک نوشته شد
|
||||
## کلیدواژه ها با ساختار مشخص و مقداری خطا تولید شده بودند
|
||||
|
||||
def moveKeywords(elastic, index_name_o, path_file, fields=['content'], body={}):
|
||||
text_normal = TextNormalizer()
|
||||
dic_main = json.loads(open(path_file,'r', encoding="utf-8").read())
|
||||
index = 0
|
||||
percent_prev = 0
|
||||
list=[]
|
||||
for item in dic_main:
|
||||
index += 1
|
||||
percent = int((index / len(dic_main)) * 100)
|
||||
if percent != percent_prev:
|
||||
print("progress -> %.2f %%" % percent)
|
||||
percent_prev = percent
|
||||
|
||||
id = item['id']
|
||||
keywords = set()
|
||||
for key in item['keywords']:
|
||||
# "•\t1.\tقانون جدید",
|
||||
# "2.\tکلاه برداری"
|
||||
key = text_normal.normalize_qanon(key)
|
||||
key = key.replace('\t', ' ').strip()
|
||||
key = key.replace('\n', ' ').strip()
|
||||
key = key.replace('\r', ' ').strip()
|
||||
key = key.strip(' •.')
|
||||
|
||||
key = re.sub(r"^[ \t]*[\d•]+[ .\t]*", '', key).strip()
|
||||
if key :
|
||||
key = text_normal.normalize_qanon(key)
|
||||
keywords.add(key)
|
||||
|
||||
content = item['content']
|
||||
words = text_normal.split_words(content)
|
||||
sorted_keys=[]
|
||||
if len(keywords) > 10 and (len(words) * 2) < len(keywords) :
|
||||
# print('id ', id , ' content', content)
|
||||
print('id ', id , 'len words ', len(words) , ' len keywords', len(keywords) )
|
||||
list_temp = sorted(keywords, key=len)
|
||||
sorted_keys=list_temp[0:len(words)]
|
||||
# print( ' keywords : ', sorted_keys)
|
||||
# exit()
|
||||
else:
|
||||
sorted_keys = sorted(keywords, key=len)
|
||||
|
||||
list.append({
|
||||
'_id': id,
|
||||
'_source': {
|
||||
"ai_keywords" : sorted_keys
|
||||
}
|
||||
})
|
||||
|
||||
if len(list) > 200 :
|
||||
elastic.updateBulkList(list, index_name_o)
|
||||
list = []
|
||||
|
||||
if len(list) :
|
||||
elastic.updateBulkList(list, index_name_o)
|
||||
|
||||
|
||||
### --------------------------------------------------------------
|
||||
## برای انتقال جملات ساده سازی شده توسط مدلهای زبانی بزرگ به الاستیک قانون نوشته شد
|
||||
def moveZipSimplifies(elastic, index_name, file_path):
|
||||
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
|
||||
for filename in zObject.namelist():
|
||||
packNo += 1
|
||||
print("index:" , index_name , '=>' , filename )
|
||||
with zObject.open(filename) as file:
|
||||
data = json.loads(file.read())
|
||||
moveSimplifies(elastic, index_name, data)
|
||||
|
||||
elastic.es.indices.refresh(index=index_name)
|
||||
print(elastic.es.cat.count(index=index_name, format="json"))
|
||||
print(" END Of Import to elastic ", index_name ,"\n")
|
||||
|
||||
def moveSimplifies(elastic, index_name_o, data):
|
||||
text_normal = TextNormalizer()
|
||||
index = 0
|
||||
percent_prev = 0
|
||||
list_bulk=[]
|
||||
for item in data:
|
||||
index += 1
|
||||
# percent = int((index / len(data)) * 100)
|
||||
# if percent != percent_prev:
|
||||
# print("progress -> %.2f %%" % percent)
|
||||
# percent_prev = percent
|
||||
|
||||
id = item['id']
|
||||
simplified = item['simplified']
|
||||
list_simp = simplified.split('\n')
|
||||
simplifies = set()
|
||||
for key in list_simp:
|
||||
# "1.ddddd",
|
||||
key = key.replace('\t', ' ').strip()
|
||||
key = key.replace('\r', ' ').strip()
|
||||
key = key.strip(' •.')
|
||||
|
||||
key = re.sub(r"^[ \t]*[\d•]+[ .\t]*", '', key).strip()
|
||||
if key :
|
||||
key = text_normal.normalize_qanon(key)
|
||||
simplifies.add(key)
|
||||
|
||||
|
||||
list_bulk.append({
|
||||
'_id': id,
|
||||
'_source': {
|
||||
"simplifies" : list(simplifies)
|
||||
}
|
||||
})
|
||||
|
||||
if len(list_bulk) > 200 :
|
||||
elastic.updateBulkList(list_bulk, index_name_o)
|
||||
list_bulk = []
|
||||
|
||||
if len(list_bulk) :
|
||||
elastic.updateBulkList(list_bulk, index_name_o)
|
||||
|
||||
|
||||
|
||||
def moveClassifierAiCodes(elastic, index_name_o, data):
|
||||
text_normal = TextNormalizer()
|
||||
index = 0
|
||||
percent_prev = 0
|
||||
send_round = 1
|
||||
list_bulk=[]
|
||||
for item in data:
|
||||
index += 1
|
||||
percent = int((index / len(data)) * 100)
|
||||
if percent != percent_prev:
|
||||
print("progress -> %.2f %%" % percent)
|
||||
percent_prev = percent
|
||||
|
||||
id = item
|
||||
best_code = data[item]['best-class']
|
||||
other_codes = data[item]['other-classes']
|
||||
|
||||
|
||||
ai_code = best_code
|
||||
ai_codes = other_codes
|
||||
|
||||
#----------------------------------------------
|
||||
for label_doc in ai_codes:
|
||||
label = label_doc["label"]
|
||||
label = re.sub(r"\u00AD|\u00AC", "\u200C", label) # نیم اسپیس خاص
|
||||
label = label.replace(" ", " ")
|
||||
label = label.replace("ـ", "")
|
||||
label = label.strip().strip("\u200C")
|
||||
label_doc["label"] = label
|
||||
if label_doc["score"] >= 1 :
|
||||
label_doc["score"] = label_doc["score"] / 100
|
||||
|
||||
if ai_code["score"] >= 1 :
|
||||
ai_code["score"] = ai_code["score"] / 100
|
||||
|
||||
label = ai_code["label"]
|
||||
label = re.sub(r"\u00AD|\u00AC", "\u200C", label) # نیم اسپیس خاص
|
||||
label = label.replace(" ", " ")
|
||||
label = label.replace("ـ", "")
|
||||
label = label.strip().strip("\u200C")
|
||||
ai_code["label"] = label
|
||||
#----------------------------------------------
|
||||
|
||||
list_bulk.append({
|
||||
'_id': id,
|
||||
'_source': {
|
||||
"ai_code" : ai_code,
|
||||
"ai_codes" : ai_codes
|
||||
}
|
||||
})
|
||||
|
||||
if len(list_bulk) > 200 :
|
||||
elastic.updateBulkList(list_bulk, index_name_o)
|
||||
list_bulk = []
|
||||
# print(f"send_round -> {send_round}")
|
||||
send_round += 1
|
||||
|
||||
if len(list_bulk) :
|
||||
elastic.updateBulkList(list_bulk, index_name_o)
|
||||
# print(f"last ::: send_round -> {send_round}")
|
||||
|
||||
|
||||
|
||||
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')
|
||||
|
||||
# host=os.getenv('HOST_60')
|
||||
# password=os.getenv('HOST_60_PASS')
|
||||
|
||||
|
||||
print(host)
|
||||
# print(password)
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
|
||||
# moveKeywords(elastic,"mj_qa_section", "data/sections_kw_llama8b_170k_concatenated.json")
|
||||
# moveKeywords(elastic,"mj_qa_section", "data/sections_kw_llama8b_40k_concatenated.json")
|
||||
|
||||
# moveZipSimplifies(elastic,"mj_qa_section", "G:\Work\_majles\_data\simpilified_final.zip")
|
||||
|
||||
|
||||
#-----نسخه قبلی اجرای مدل
|
||||
# with open("./data/all_sections_classes.json", "r", encoding="utf-8") as f:
|
||||
# classes = json.load(f)
|
||||
|
||||
#-----نسخه آخر اجرای مدل
|
||||
# with open("./data/all_sections_classes_full_140405.json", "r", encoding="utf-8") as f:
|
||||
# classes = json.load(f)
|
||||
|
||||
# moveClassifierAiCodes(elastic,"mj_qa_section", classes)
|
||||
# print('finished!')
|
||||
|
||||
#-----داده های جدید نسخه آخر اجرای مدل
|
||||
with open("./data/all_sections_classes_new_140406.json", "r", encoding="utf-8") as f:
|
||||
classes = json.load(f)
|
||||
|
||||
moveClassifierAiCodes(elastic,"mj_qa_section", classes)
|
||||
print('finished!')
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import json
|
||||
import datetime
|
||||
|
||||
from app.common.general_functions import read_file_by_address, read_from_json
|
||||
|
||||
if __name__ == "__main__":
|
||||
start_time = datetime.datetime.now()
|
||||
print(f'start time: {start_time}')
|
||||
|
||||
# inputfile = open('./data/main_classes_dataset_03.json', "r", encoding='utf-8')
|
||||
# inputfile = open('./data/sections_40k_normalized.json', "r", encoding='utf-8')
|
||||
# data = json.load(inputfile)
|
||||
# inputfile.close()
|
||||
|
||||
# prev_ids = read_file_by_address('./data/prev_kw_ids_170k.txt').splitlines()
|
||||
|
||||
counter = 1
|
||||
file_counter = 1
|
||||
temp_dict = []
|
||||
temp_data_text = ''
|
||||
period_sections = []
|
||||
period_ids_text = f'***** file number: {file_counter} *****\n'
|
||||
|
||||
finall_sections = []
|
||||
for file_counter in range(1,41):
|
||||
|
||||
# inputfile = open(f'./data/sections_kw_llama8b_170k_{str(file_counter)}.json', "a+", encoding='utf-8')
|
||||
data = read_from_json(f'./data/sections_kw_llama8b_40k_{str(file_counter)}.json')
|
||||
|
||||
print(f'file {file_counter} is in proccess ... ')
|
||||
for item in data:
|
||||
id = item['id']
|
||||
finall_sections.append(item)
|
||||
|
||||
outputfile = open(f'./data/sections_kw_llama8b_40k_concatenated.json', "a+", encoding='utf-8')
|
||||
outputfile.write(json.dumps(finall_sections, ensure_ascii=False, indent=2))
|
||||
outputfile.close()
|
||||
|
||||
end_time = datetime.datetime.now()
|
||||
print(f"end_time: {end_time}")
|
||||
print("end")
|
||||
@@ -0,0 +1,117 @@
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
from app.common.general_functions import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
|
||||
|
||||
dict_qanon = {}
|
||||
|
||||
def getContext(parent_id, qanon_title):
|
||||
context = ''
|
||||
context += f"\n** قانون: {qanon_title} "
|
||||
pid = parent_id
|
||||
|
||||
path=''
|
||||
while True:
|
||||
if not pid or pid == '0' or pid not in dict_qanon:
|
||||
break # اگر pid '0' است یا در dict_qanon وجود ندارد، حلقه متوقف میشود
|
||||
|
||||
# دریافت content والد
|
||||
parent_content = dict_qanon[pid].get("content", "")
|
||||
if parent_content :
|
||||
path += f"\\{parent_content}"
|
||||
|
||||
# بروزرسانی pid به والد بالاتر
|
||||
pid = dict_qanon[pid].get("parent_id", '0')
|
||||
|
||||
if path :
|
||||
context += f"\n** سرفصل: {qanon_title} "
|
||||
|
||||
return context
|
||||
|
||||
|
||||
def create_context_ai(elastic, index_name_i, fields=["qanon_title", "tree" ], index_name_o = '' ):
|
||||
|
||||
body={
|
||||
# "query": {
|
||||
# "bool": {
|
||||
# "must_not": [
|
||||
# {"exists": {"field": "nlp_parser.type"}},
|
||||
# {"match": {"content_len": 0}},
|
||||
# {"match": {"parse_state": 1}},
|
||||
# {"match": {"parse_state": 2}}
|
||||
# ]
|
||||
# }
|
||||
# },
|
||||
"sort": [
|
||||
{
|
||||
"qanon_id": {"order": "asc"},
|
||||
"child_order": {"order": "asc"}
|
||||
}
|
||||
]
|
||||
|
||||
}
|
||||
|
||||
if index_name_o == '' :
|
||||
index_name_o = index_name_i
|
||||
|
||||
try:
|
||||
try:
|
||||
list = elastic.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
count = 0
|
||||
cur_qanon_id = 0
|
||||
text_normal = TextNormalizer()
|
||||
result = []
|
||||
|
||||
data={}
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
id = entry.get("id", "")
|
||||
|
||||
content = entry.get("content", "")
|
||||
content = text_normal.normalize_qanon(content)
|
||||
qanon_title = entry.get("qanon_title", "")
|
||||
parent_id = entry.get("parent_id", "")
|
||||
other_info = entry.get("other_info", "")
|
||||
level = other_info["level"]
|
||||
qanon_id = entry.get("qanon_id", "")
|
||||
|
||||
|
||||
data = {}
|
||||
### /////////////////////////////////
|
||||
# جمله اصلی برای سند فعلی
|
||||
|
||||
if parent_id == '0' or parent_id == 0 or parent_id == '':
|
||||
dict_qanon = {}
|
||||
|
||||
if qanon_id != cur_qanon_id :
|
||||
dict_qanon = {}
|
||||
cur_qanon_id = qanon_id
|
||||
|
||||
dict_qanon[id] = {
|
||||
"content" : content,
|
||||
"other_info" : other_info,
|
||||
"id" : id,
|
||||
"parent_id" : parent_id,
|
||||
}
|
||||
|
||||
context = getContext(parent_id, qanon_title)
|
||||
data["context_llm"] = context
|
||||
|
||||
#### ///////////////////////////////////
|
||||
|
||||
|
||||
eid = id
|
||||
try:
|
||||
resp = elastic.update_index_doc(True, 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)
|
||||
@@ -0,0 +1,167 @@
|
||||
from time import time
|
||||
import requests
|
||||
from app.common.general_functions import *
|
||||
from app.common.config_base import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
|
||||
|
||||
def fill_chunk_tags(elasticHelper, ai_url, index_name_o = "mj_qa_section", path_resource='resource/my/') :
|
||||
id = ""
|
||||
body = {
|
||||
### این فهرست قوانینی است که تعداد زیادی از اجزاء دارای لول بزرگتر از 8 دارند
|
||||
# "query": {
|
||||
# "bool": {
|
||||
# "must_not": [
|
||||
# {
|
||||
# "terms": {
|
||||
# "qanon_id":["qq86911", "qq83307", "qq178971", "qq111830", "qq233930", "qq85434"]
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# }
|
||||
# },
|
||||
"sort": [
|
||||
{"qanon_id": {"order": "asc"}},
|
||||
{"child_order": {"order": "asc"}}
|
||||
]
|
||||
}
|
||||
|
||||
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)
|
||||
path_heading=[]
|
||||
level_parent= 0
|
||||
file_error = open('error_fill_nlp_tags.txt', 'w+', encoding='utf-8')
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
|
||||
id = entry.get("id", "")
|
||||
qanon_id = entry.get("qanon_id", "0")
|
||||
other_info = entry.get("other_info", {})
|
||||
content = entry.get("content", "")
|
||||
html = entry.get("html", "")
|
||||
chunk_tags = []
|
||||
|
||||
if html :
|
||||
content = ''
|
||||
|
||||
if not content :
|
||||
continue
|
||||
|
||||
content_normal = text_normal.normalize_qanon_test(content)
|
||||
payload={
|
||||
'text': content_normal
|
||||
}
|
||||
response = requests.request("POST", ai_url, headers=HEADERS, json=payload)
|
||||
if response.status_code == 500 :
|
||||
print(response.text)
|
||||
continue
|
||||
|
||||
resp = json.loads(response.text)
|
||||
# print(resp)
|
||||
pos_tags = []
|
||||
chunk_tags = ''
|
||||
for item in resp['data'] :
|
||||
item_pos_tags = item['pos_tags']
|
||||
for pt in item_pos_tags :
|
||||
pos_tags.append({
|
||||
"word": pt[0],
|
||||
"hazm_tags": pt[1].split(',')
|
||||
})
|
||||
|
||||
|
||||
if chunk_tags :
|
||||
chunk_tags += ' ' + item['chunk_tree']
|
||||
else :
|
||||
chunk_tags = item['chunk_tree']
|
||||
|
||||
####--------------------------------------
|
||||
# chunk_keywords = []
|
||||
# # chunks = chunk_tags.replace('] [', ']#[').split('#')
|
||||
|
||||
# pattern = r'\[([^\[\]]+) ([A-Z]{1,10})\] '
|
||||
# iter = re.finditer(pattern, chunk_tags.strip())
|
||||
# index = 0
|
||||
# prev_tag = ''
|
||||
# prev_text = ''
|
||||
# for item in iter :
|
||||
# # print(item)
|
||||
# text = item[0]
|
||||
# tag = item[1]
|
||||
# start_index = item.start()
|
||||
# end_index = item.end()
|
||||
# if index < start_index :
|
||||
# word = chunk_tags[index:start_index].strip('()[]:.?!-/«»؟,،؛ ').strip()
|
||||
# if word in ['که', 'و', 'از', 'تا', 'ولی', 'مگر', 'چنانچه', ''] :
|
||||
# chunk_keywords.append({
|
||||
# "text": word,
|
||||
# "tag": ['PP']
|
||||
# })
|
||||
# elif word in ['است', 'شد', 'شود', 'گردد'] :
|
||||
# if prev_tag in ['V', 'VP'] :
|
||||
# ck = chunk_keywords[-1]
|
||||
# ck['text'] += ' ' + word
|
||||
# chunk_keywords[-1] = ck
|
||||
# elif prev_tag in ['NOUN'] :
|
||||
# ck = chunk_keywords[-1]
|
||||
# ck['text'] += ' ' + word
|
||||
# ck['tag'] = 'VP'
|
||||
# chunk_keywords[-1] = ck
|
||||
|
||||
|
||||
# elif word:
|
||||
# print('id ', id, ' ', word)
|
||||
# # chunk_keywords.append({
|
||||
# # "text": word,
|
||||
# # "tag": ['nnn']
|
||||
# # })
|
||||
# else :
|
||||
# if text in ['است', 'شد', 'شود', 'گردد'] :
|
||||
# pass
|
||||
# else:
|
||||
# pass
|
||||
# chunk_keywords.append({
|
||||
# "text": item[1],
|
||||
# "tag": item[2]
|
||||
# })
|
||||
# index = item.end()
|
||||
# # print(chunk_keywords)
|
||||
#### ----------------------------------------
|
||||
data = {}
|
||||
|
||||
data["pos_tags"]= pos_tags
|
||||
data["chunk_tags"]= chunk_tags
|
||||
if content_normal != content :
|
||||
data["content_normal"]= content_normal
|
||||
|
||||
# data["chunk_keywords"]= chunk_keywords
|
||||
|
||||
update = True
|
||||
eid = id
|
||||
try:
|
||||
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
|
||||
|
||||
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')
|
||||
|
||||
file_error.close()
|
||||
print("=" * 10, " fill_content_nlp finished")
|
||||
@@ -0,0 +1,191 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
# from general import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
|
||||
|
||||
body = {
|
||||
# "query": {
|
||||
# "bool": {
|
||||
# "must_not": [
|
||||
# {"exists": {"field": "nlp_parser.type"}},
|
||||
# {"match": {"content_len": 0}},
|
||||
# {"match": {"parse_state": 1}},
|
||||
# {"match": {"parse_state": 2}}
|
||||
# ]
|
||||
# }
|
||||
# }
|
||||
}
|
||||
|
||||
|
||||
|
||||
def exportTokensMulti(elastic, index_name_i, prefixname, fields=['content'], body={}, path_out="./data/"):
|
||||
counter = 0
|
||||
total = 0
|
||||
id = ""
|
||||
|
||||
dict_word_count = {}
|
||||
dict_word_count2 = {}
|
||||
try:
|
||||
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 = []
|
||||
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
id = entry.get("id", "")
|
||||
|
||||
for field in fields :
|
||||
content = entry.get(field, "")
|
||||
# words = content.split()
|
||||
words = text_normal.split_words(content)
|
||||
for word in words:
|
||||
if word in dict_word_count :
|
||||
dict_word_count[word] += 1
|
||||
else :
|
||||
dict_word_count[word] = 1
|
||||
|
||||
|
||||
content = text_normal.normalize_qanon_test(content)
|
||||
words = text_normal.split_words(content)
|
||||
for word in words:
|
||||
if word in dict_word_count2 :
|
||||
dict_word_count2[word] += 1
|
||||
else :
|
||||
dict_word_count2[word] = 1
|
||||
|
||||
|
||||
|
||||
|
||||
if dict_word_count :
|
||||
sorted_dict_words = dict(sorted(dict_word_count.items(), key=lambda x: x[1], reverse=True))
|
||||
filtered_dict = {k:v for (k,v) in sorted_dict_words.items() if not re.match(r'[a-zA-Z\d]+', k) }
|
||||
with open(path_out+prefixname+"1.txt", "w", encoding="utf-8") as f:
|
||||
json.dump(filtered_dict, f, ensure_ascii=False, indent=4)
|
||||
|
||||
if dict_word_count2 :
|
||||
sorted_dict_words = dict(sorted(dict_word_count2.items(), key=lambda x: x[1], reverse=True))
|
||||
filtered_dict = {k:v for (k,v) in sorted_dict_words.items() if not re.match(r'[a-zA-Z\d]+', k) }
|
||||
with open(path_out+prefixname+"2.txt", "w", encoding="utf-8") as f:
|
||||
json.dump(filtered_dict, f, ensure_ascii=False, indent=4)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
|
||||
|
||||
def exportTokens(elastic, index_name_i, fields=['content'], body={}):
|
||||
dict_word_count={}
|
||||
counter = 0
|
||||
total = 0
|
||||
id = ""
|
||||
|
||||
try:
|
||||
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 = []
|
||||
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
id = entry.get("id", "")
|
||||
|
||||
for field in fields :
|
||||
content = entry.get(field, "")
|
||||
# content = text_normal.replace_alphabets(content)
|
||||
# words = content.split()
|
||||
words = text_normal.split_words(content)
|
||||
|
||||
for word in words:
|
||||
if word in dict_word_count :
|
||||
dict_word_count[word] += 1
|
||||
else :
|
||||
dict_word_count[word] = 1
|
||||
return dict(dict_word_count)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
def exportTokensToFile(elastic, index_name_i, filename, fields=['content'], body={}, path_out="./data/"):
|
||||
dict_words = exportTokens(elastic, index_name_i, fields, body)
|
||||
if dict_words :
|
||||
sorted_dict_words = dict(sorted(dict_words.items(), key=lambda x: x[1], reverse=True))
|
||||
filtered_dict = {k:v for (k,v) in sorted_dict_words.items() if not re.match(r'[a-zA-Z\d]+', k) }
|
||||
with open(path_out+filename, "w", encoding="utf-8") as f:
|
||||
json.dump(filtered_dict, f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
def diff_files_to_file(file_dict1, file_dict2, filename, path_out="./data/"):
|
||||
dict1 = json.loads(open(path_out+file_dict1, "r", encoding="utf-8").read())
|
||||
dict2 = json.loads(open(path_out+file_dict2, "r", encoding="utf-8").read())
|
||||
return diff_to_file(dict1, dict2, filename, False, path_out)
|
||||
|
||||
def diff_to_file(dict1, dict2, filename, by_diff_count=False, path_out="./data/"):
|
||||
dict_no_exist = {}
|
||||
dict_diff_count = {}
|
||||
for item in dict1:
|
||||
if item not in dict2 :
|
||||
dict_no_exist[item] = dict1[item]
|
||||
elif dict1[item] != dict2[item] :
|
||||
dict_diff_count[item] = dict2[item] - dict1[item]
|
||||
|
||||
with open(path_out+filename, "w", encoding="utf-8") as f:
|
||||
json.dump(dict_no_exist, f, ensure_ascii=False, indent=4)
|
||||
|
||||
if by_diff_count :
|
||||
with open(path_out+filename, "a+", encoding="utf-8") as f:
|
||||
json.dump(dict_diff_count, f, 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_60')
|
||||
# password=os.getenv('HOST_60_PASS')
|
||||
|
||||
|
||||
print(host)
|
||||
# print(password)
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
|
||||
#exportTokensToFile(elastic,"mj_qa_section", "content_mj_qa_section_1.txt")
|
||||
# exportTokensToFile(elastic,"test_qa_section", "content_test_qa_section_1.txt")
|
||||
# exportTokensToFile(elastic,"test_qa_section", "content_test_qa_section_normal_1.txt", ["content_normal"])
|
||||
|
||||
|
||||
# diff_files_to_file("content_mj_qa_section_1.txt", "content_test_qa_section_1.txt", "diff_prev_content.txt")
|
||||
# diff_files_to_file("content_test_qa_section_1.txt", "content_mj_qa_section_1.txt", "diff_content_prev.txt")
|
||||
|
||||
# diff_files_to_file("content_test_qa_section_normal_1.txt", "content_test_qa_section_1.txt", "diff_normal_content.txt")
|
||||
# diff_files_to_file("content_test_qa_section_1.txt", "content_test_qa_section_normal_1.txt", "diff_content_normal.txt")
|
||||
|
||||
|
||||
# exportTokensToFile(elastic,"mj_qa_section", "content_mj_qa_section_1.txt")
|
||||
#exportTokensMulti(elastic,"mj_qa_section", "mj_qa_section")
|
||||
diff_files_to_file("mj_qa_section1.txt", "mj_qa_section2.txt", "diff_1_2.txt")
|
||||
diff_files_to_file("mj_qa_section2.txt", "mj_qa_section1.txt", "diff_2_1.txt")
|
||||
|
||||
print("finished")
|
||||
@@ -0,0 +1,144 @@
|
||||
import re
|
||||
import json
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
text_normal = TextNormalizer()
|
||||
def tag_separation(text, default_tag):
|
||||
parts = text.split("=")
|
||||
title = parts[0].strip()
|
||||
tag = parts[1].strip() if len(parts) > 1 else default_tag
|
||||
return title, tag
|
||||
|
||||
def recursiveMatch(startIndex , i, tokens, dict, result):
|
||||
end = -1
|
||||
if i >= len(tokens):
|
||||
return end
|
||||
|
||||
word = tokens[i]
|
||||
if word in dict:
|
||||
end = recursiveMatch(startIndex, i+1, tokens, dict[word], result)
|
||||
if end and end != -1: # finded
|
||||
return end
|
||||
elif '=' in dict[word]:
|
||||
end = i+1
|
||||
result.append({
|
||||
"begin": startIndex,
|
||||
"end": i,
|
||||
"text": " ".join(tokens[startIndex:end]),
|
||||
"result_key": dict[word]['='],
|
||||
|
||||
})
|
||||
return end
|
||||
else:
|
||||
return end
|
||||
|
||||
def find_entities(text, entity_dict):
|
||||
words = text_normal.split_words(text)
|
||||
results = []
|
||||
i = 0
|
||||
while i < len(words):
|
||||
end = recursiveMatch(i, i, words, entity_dict, results)
|
||||
if end and end != -1:
|
||||
i = end
|
||||
else:
|
||||
i += 1
|
||||
return results
|
||||
|
||||
def create_nested_dictionary(lines, nested_dict={}):
|
||||
for line in lines:
|
||||
line = text_normal.normalize_qanon(line)
|
||||
title, tag = tag_separation(line, '')
|
||||
words = text_normal.split_words(title)
|
||||
dict_current_level = nested_dict
|
||||
for word in words:
|
||||
if word not in dict_current_level:
|
||||
dict_current_level[word] = {}
|
||||
dict_current_level = dict_current_level[word]
|
||||
if '=' in dict_current_level and dict_current_level['='] != tag:
|
||||
dict_current_level['='] += ',' + tag
|
||||
else:
|
||||
dict_current_level['='] = tag
|
||||
return nested_dict
|
||||
|
||||
def create_title_tree(title_with_tag, tree):
|
||||
title, tag = tag_separation(title_with_tag, "ref")
|
||||
words = text_normal.split_words(title)
|
||||
dict_current_level = tree
|
||||
for word in words:
|
||||
if word not in dict_current_level:
|
||||
dict_current_level[word] = {}
|
||||
dict_current_level = dict_current_level[word]
|
||||
dict_current_level['='] = tag
|
||||
|
||||
def create_province_tree(data, tree):
|
||||
for key, values in data.items():
|
||||
province_name, province_tag = tag_separation(key, "loc")
|
||||
words = text_normal.split_words(province_name)
|
||||
dict_current_level = tree
|
||||
for word in words:
|
||||
if word not in dict_current_level:
|
||||
dict_current_level[word] = {}
|
||||
dict_current_level = dict_current_level[word]
|
||||
dict_current_level['='] = province_tag
|
||||
for value in values:
|
||||
city_name, city_tag = tag_separation(value, "loc")
|
||||
city_words = text_normal.split_words(city_name)
|
||||
city_level = tree
|
||||
for word in city_words:
|
||||
if word not in city_level:
|
||||
city_level[word] = {}
|
||||
city_level = city_level[word]
|
||||
city_level['='] = city_tag
|
||||
|
||||
try:
|
||||
with open('./data/list_ORG.txt', 'r', encoding='utf-8') as f:
|
||||
org_text = f.read()
|
||||
except FileNotFoundError:
|
||||
print("Error: list_ORG.txt file not found.")
|
||||
exit()
|
||||
|
||||
org_lines = org_text.strip().split('\n')
|
||||
organization_dict = create_nested_dictionary(org_lines)
|
||||
|
||||
try:
|
||||
with open("./data/qanon_titles.json", "r", encoding="utf-8") as f:
|
||||
title_data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
print("Error: qanon_titles.json file not found.")
|
||||
exit()
|
||||
|
||||
title_tree = {}
|
||||
for item in title_data:
|
||||
create_title_tree(item["title"], title_tree)
|
||||
|
||||
text = "تمامی وزارتخانه ها و سازمانهای کشور از جمله وزارت فرهنگ و ارشاد اسلامی وزارت کشور با جمعی از کارکنان وزارت نیرو در محل سازمان حفظ محیط زیست دیدار و گفتگو کردند. همچنین ماده 5 قانون اساسی جمهوری اسلامی ایران بر این امر تأکید دارد. قانون الحاق یک ماده به قانون حمایت از خانواده و جوانی جمعیت در استان تهران تهران و قم جعفريه"
|
||||
# #text = "وزارت فرهنگ و ارشاد اسلامی با جمعی از کارکنان وزارت نیرو در محل سازمان حفظ محیط زیست دیدار و گفتگو کردند"
|
||||
# #text = "تمامی وزارتخانهها و سازمانهای کشور از جمله وزارت فرهنگ و ارشاد اسلامی وزارت کشور با جمعی از کارکنان وزارت نیرو در محل سازمان حفظ محیط زیست دیدار و گفتگو کردند"
|
||||
# #text = "تمامی وزارتخانه ها و سازمانهای کشور از جمله وزارت فرهنگ و ارشاد اسلامی وزارت کشور با جمعی از کارکنان وزارت نیرو در محل سازمان حفظ محیط زیست دیدار و گفتگو کردند"
|
||||
# #text = "تمامی ## و ## ## از جمله ## ## ## ## ## ## ## با جمعی از کارکنان ## ## در محل ## ## ## ## دیدار و گفتگو کردند"
|
||||
# #text = "ماده 1 - براساس اصل 45 قانون اساسی جمهوری اسلامی ایران، آبهای دریاها و آبهای جاری در رودها و انهار طبیعی و درهها و هر مسیر طبیعی دیگر اعم از سطحی و زیر زمینی، سیلابها و فاضلابها و زهآبها و دریاچهها و مردابها و برکههای طبیعی و چشمه سارها و آبهای معدنی و منابع آبهای زیرزمینی از مشترکات بوده و در اختیار حکومت اسلامی است و طبق مصالح عامه از آنها بهره برداری میشود. مسئولیت حفظ و اجازه و نظارت بر بهره برداری از آنها به دولت محول میشود."
|
||||
|
||||
try:
|
||||
with open("./data/province_tree.json", "r", encoding="utf-8") as f:
|
||||
province_data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
print("Error: province_tree.json file not found.")
|
||||
exit()
|
||||
|
||||
province_tree = {}
|
||||
create_province_tree(province_data, province_tree)
|
||||
|
||||
|
||||
found_orgs = find_entities(text, organization_dict)
|
||||
found_titles = find_entities(text, title_tree)
|
||||
found_provinces = find_entities(text, province_tree)
|
||||
|
||||
# ترکیب نتایج
|
||||
found_entities = found_orgs + found_titles + found_provinces
|
||||
|
||||
# ذخیره خروجی در فایل JSON
|
||||
output_file = "./output/ner_found_entities.json"
|
||||
with open(output_file, "w", encoding="utf-8") as f:
|
||||
json.dump(found_entities, f, ensure_ascii=False, indent=4)
|
||||
|
||||
print(f"نتایج در فایل {output_file} ذخیره شد.")
|
||||
@@ -0,0 +1,120 @@
|
||||
import os
|
||||
import sys
|
||||
from dotenv import load_dotenv
|
||||
import asyncio
|
||||
from time import sleep
|
||||
from app.common.elastic_helper_async import elastic_helper_async
|
||||
from app.common.sql_helper import sql_helper
|
||||
|
||||
# from docker import docker_import
|
||||
# from app.common.version_util import VersionUtil
|
||||
|
||||
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')
|
||||
|
||||
# host=os.getenv('HOST_60')
|
||||
# password=os.getenv('HOST_60_PASS')
|
||||
|
||||
# host=os.getenv('HOST_161')
|
||||
# password=os.getenv('HOST_161_PASS')
|
||||
|
||||
# host=os.getenv('HOST_80')
|
||||
# password=os.getenv('HOST_80_PASS')
|
||||
|
||||
# host=os.getenv('HOST_133')
|
||||
# password=os.getenv('HOST_133_PASS')
|
||||
|
||||
|
||||
current_directory = os.getcwd()
|
||||
data_t_location = current_directory + "\\data\\"
|
||||
default_location_data= current_directory + "\\data"
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elasticImport = elastic_helper_async(host, password, "elastic", path_base_map)
|
||||
|
||||
name_zip_file = "data_back040615.zip"
|
||||
|
||||
# versionUtil = VersionUtil(data_t_location)
|
||||
|
||||
|
||||
def download_file():
|
||||
pass
|
||||
|
||||
|
||||
def update_elastic():
|
||||
pass
|
||||
|
||||
|
||||
def update_mysql():
|
||||
pass
|
||||
|
||||
def update_dist():
|
||||
pass
|
||||
|
||||
|
||||
|
||||
# async def elastic(dict_version_info):
|
||||
# elasticImport = elastic_helper_async()
|
||||
# if versionUtil.chack_version(dict_version_info["ver_local"],dict_version_info["ver_new"],"elastic"):
|
||||
# location_elastic=versionUtil.find_location_folder_version(dict_version_info["ver_local"]["elastic"],dict_version_info["ver_new"]["elastic"],"elastic")
|
||||
# for loc in location_elastic:
|
||||
# await elasticImport.run_elastic_import(loc)
|
||||
|
||||
|
||||
|
||||
# async def mariadb(dict_version_info:dict):
|
||||
# sqlImport = sql_helper()
|
||||
# sqlImport.create_users()
|
||||
# if versionUtil.chack_version(dict_version_info["ver_local"],dict_version_info["ver_new"],"db"):
|
||||
# location_db=versionUtil.find_location_folder_version(dict_version_info["ver_local"]["db"],dict_version_info["ver_new"]["db"],"db")
|
||||
# for loc in location_db:
|
||||
# list_file_sql = os.listdir(loc)
|
||||
# for file in list_file_sql:
|
||||
# print(f"----> create_database ... {file[:-4]}")
|
||||
# sqlImport.create_database(file[:-4])
|
||||
# print(f"----> read_file_import ... {loc}/{file}")
|
||||
# sqlImport.read_file_import(f"{loc}/{file}",file[:-4])
|
||||
|
||||
|
||||
|
||||
async def main():
|
||||
|
||||
|
||||
|
||||
# name_zip_file_arry = sys.argv[1:]
|
||||
# name_zip_file = name_zip_file_arry[0]
|
||||
|
||||
# arg2 = sys.argv[2:]
|
||||
# print(arg2)
|
||||
|
||||
# mode = 'normal'
|
||||
# if len(arg2) :
|
||||
# mode = arg2[0]y
|
||||
# print('mode', mode)
|
||||
|
||||
|
||||
sub_folder=name_zip_file[:-4]
|
||||
|
||||
# os.system(f"mkdir {default_location_data}\\elastic")
|
||||
# os.system(f"mkdir {default_location_data}\\elastic\\{sub_folder}")
|
||||
# os.system(f"copy {default_location_data}\\{name_zip_file} {default_location_data}\\elastic\\{sub_folder}")
|
||||
# # ؟؟؟؟؟ ??? اگر پوشه ای بود ...
|
||||
# os.system(f"Expand-Archive -Path {default_location_data}\\elastic\\{sub_folder}\\{name_zip_file} && del {name_zip_file}")
|
||||
|
||||
loc=f"{default_location_data}\\elastic\\{sub_folder}"
|
||||
os.system("del /f /q /S data\\tmp\\edb\\*")
|
||||
await elasticImport.run_elastic_import_delete(loc)
|
||||
os.system("del /f /q /S data\\tmp\\edb\\*")
|
||||
|
||||
##docker_import(data_t_location)
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.run_until_complete(main())
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
|
||||
@@ -0,0 +1,594 @@
|
||||
from time import time
|
||||
import requests
|
||||
from app.common.general_functions import *
|
||||
from app.common.config_base import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
|
||||
#def saveEmbedingContent()
|
||||
|
||||
##----- مرحله اول -----------------
|
||||
## پردازش و پرکردن فیلدهای متنوع کمکی
|
||||
def fill_nlp_tags(elasticHelper, index_name_o = "mj_qa_section_ai", path_resource='resource/my/') :
|
||||
id = ""
|
||||
body = {
|
||||
### این فهرست قوانینی است که تعداد زیادی از اجزاء دارای لول بزرگتر از 8 دارند
|
||||
# "query": {
|
||||
# "bool": {
|
||||
# "must_not": [
|
||||
# {
|
||||
# "terms": {
|
||||
# "qanon_id":["qq86911", "qq83307", "qq178971", "qq111830", "qq233930", "qq85434"]
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# }
|
||||
# },
|
||||
"sort": [
|
||||
{"qanon_id": {"order": "asc"}},
|
||||
{"child_order": {"order": "asc"}}
|
||||
]
|
||||
}
|
||||
|
||||
useful_ids = {}
|
||||
# useful_titles_al = []
|
||||
# useful_finded = []
|
||||
# خواندن کلمات موجود در فایل
|
||||
with open( path_resource+"qanon_usefull.txt", 'r', encoding='utf-8') as f:
|
||||
for line in f :
|
||||
id = line.strip().split('=')[0]
|
||||
if id not in useful_ids :
|
||||
useful_ids[id] = 1
|
||||
|
||||
|
||||
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)
|
||||
path_heading=[]
|
||||
level_parent= 0
|
||||
file_error = open('error_fill_nlp_tags.txt', 'w+', encoding='utf-8')
|
||||
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
|
||||
id = entry.get("id", "")
|
||||
#qanon_etebar = entry.get("qanon_etebar", "")
|
||||
state_etebar = entry.get("state_etebar", "")
|
||||
title_type = entry.get("title_type", "")
|
||||
qanon_title = entry.get("qanon_title", "")
|
||||
qanon_id = entry.get("qanon_id", "0")
|
||||
other_info = entry.get("other_info", {})
|
||||
parent_id = entry.get("parent_id", "0")
|
||||
content = entry.get("content", "")
|
||||
full_path = other_info["full_path"]
|
||||
nlp_tags = []
|
||||
|
||||
|
||||
#"full_path": "ماده واحده>فصل ششم>بخش سوم>قسمت چهارم>فصل هشتم>ماده 153>بند ب>جزء 4",
|
||||
paths = full_path.split('>')
|
||||
last_path = ''
|
||||
if paths :
|
||||
last_path = paths[-1]
|
||||
|
||||
level_2 = len(paths)
|
||||
|
||||
###--------------------شناسایی بزرگی کوچکی متن -------------------
|
||||
word_len = len(split_words(content))
|
||||
|
||||
###--------------------شناسایی بزرگی کوچکی متن -------------------
|
||||
if word_len > 100 :
|
||||
nlp_tags.append("words_big")
|
||||
elif word_len > 50 :
|
||||
nlp_tags.append("words_medium")
|
||||
else :
|
||||
nlp_tags.append("words_small")
|
||||
|
||||
|
||||
###--------------------شناسایی هدینگ بودن -------------------
|
||||
prefix, title, content_type = normalHeadingTitle(content, last_path)
|
||||
if not parent_id or parent_id == '0' or parent_id==0 :
|
||||
path_heading = []
|
||||
level_parent = 0
|
||||
|
||||
###--------------------شناسایی قوانین پرکاربرد -------------------
|
||||
if qanon_id in useful_ids:
|
||||
nlp_tags.append("qanon_usefull")
|
||||
|
||||
###-------------------- تعیین مسیر هدینگ -------------------
|
||||
## هرچند با پرنت آی دی این خالی می شود ولی برای مطمئن کاری این شرط اضافه شد
|
||||
elif full_path=='عنوان' or full_path=='موخره' or full_path=='امضاء' :
|
||||
path_heading = []
|
||||
level_parent = 0
|
||||
|
||||
elif level_2 < level_parent :
|
||||
diff = level_parent - level_2
|
||||
while diff > 0 and path_heading :
|
||||
path_heading.pop()
|
||||
diff = diff - 1
|
||||
|
||||
level_parent = level_2
|
||||
# print('id :', id , ' --diff ', diff, path_heading )
|
||||
|
||||
if level_2 >= level_parent :
|
||||
|
||||
# برای اجزاء بعدی شناسایی و ذخیره می شود نه جزء جاری
|
||||
if prefix != '' and title != '':
|
||||
if level_2 == level_parent and path_heading :
|
||||
path_heading.pop()
|
||||
|
||||
if len(title) < 256 :
|
||||
path_heading.append(title)
|
||||
nlp_tags.append("heading")
|
||||
level_parent = level_2
|
||||
###--------------------------------------------------------
|
||||
full_path_prev = full_path
|
||||
full_path = title_type + ' :: ' + full_path
|
||||
heading_in_content = ''
|
||||
|
||||
if "heading" in nlp_tags :
|
||||
nlp_tags.append("concept_no")
|
||||
elif 'تفسیر' in state_etebar or 'تفسیر' in last_path :
|
||||
nlp_tags.append("concept_side")
|
||||
elif 'عنوان' in last_path or 'موخره' in last_path or 'امضاء' in last_path or 'سربرگ' in last_path or 'فهرست' in last_path or 'منشور' in last_path :
|
||||
nlp_tags.append("concept_no")
|
||||
elif 'ماده' in last_path or 'اصل' in last_path or 'متن' in last_path or 'مقدمه' in last_path or 'نامه' in last_path or 'کلیات' in last_path or 'قسمت' in last_path or 'توضیح' in last_path or 'سوال' in last_path or 'استفساریه' in last_path :
|
||||
nlp_tags.append("concept_base")
|
||||
elif 'بند' in last_path or 'جزء' in last_path or 'زیرجزء' in last_path or 'شماره' in last_path or 'ردیف' in last_path or 'پاورقی' in last_path or 'اشاره' in last_path or 'تنبیه' in last_path or 'بخش' in last_path or 'جواب' in last_path or 'مقرره' in last_path :
|
||||
nlp_tags.append("concept_week")
|
||||
elif 'تبصره' in last_path or 'بخش' in last_path or 'تذکر' in last_path or 'توصیه' in last_path or 'توجه' in last_path :
|
||||
nlp_tags.append("concept_middle")
|
||||
elif 'الحاقی' in state_etebar or 'الحاقی' in last_path :
|
||||
nlp_tags.append("concept_week")
|
||||
elif 'جدول' in last_path :
|
||||
nlp_tags.append("concept_bad")
|
||||
elif content_type in ['تبصره','بخش','تذکر'] :
|
||||
nlp_tags.append("concept_middle")
|
||||
elif content_type in ['ماده'] :
|
||||
nlp_tags.append("concept_base")
|
||||
# elif qanon_etebar == 'منسوخه' :
|
||||
# pass
|
||||
elif 'پروتکل' in full_path or 'موافقتنامه' in full_path or 'قطعنامه' in full_path or 'پیوست' in full_path or 'عهدنامه' in full_path or 'توافقنامه' in full_path or 'معاهده' in full_path or 'کنوانسیون' in full_path or 'قرارداد' in full_path :
|
||||
if not title :
|
||||
nlp_tags.append("concept_bad")
|
||||
elif len(title) < 50 :
|
||||
if prefix :
|
||||
nlp_tags.append("concept_head")
|
||||
heading_in_content = title
|
||||
else :
|
||||
nlp_tags.append("concept_week")
|
||||
else :
|
||||
nlp_tags.append("concept_base")
|
||||
elif prefix :
|
||||
if title and len(title) < 50 :
|
||||
file_error.write('---***---- data id=' + id + ' full_path : ' + full_path + ' prefix : '+ prefix +' --- '+ title + '\n')
|
||||
print('---***---- data id=', id, ' full_path : ', full_path , ' prefix : ', prefix ,' --- ', title)
|
||||
else :
|
||||
if title and len(title) < 50:
|
||||
if 'فصل' in last_path or 'مبحث' in last_path :
|
||||
nlp_tags.append("concept_head")
|
||||
heading_in_content = title
|
||||
if full_path_prev == '' :
|
||||
nlp_tags.append("concept_bad")
|
||||
else :
|
||||
file_error.write('------- data id='+ id + ' full_path : '+ full_path + ' prefix : '+ prefix +' --- '+ title + '\n')
|
||||
print('------- data id=', id, ' full_path : ', full_path , ' prefix : ', prefix ,' --- ', title)
|
||||
elif len(title) >= 50 :
|
||||
if full_path_prev == '' :
|
||||
nlp_tags.append("concept_bad")
|
||||
else :
|
||||
file_error.write('### ####### error data id='+ id + ' full_path : '+ full_path + ' prefix : '+ prefix +' --- '+ title + '\n')
|
||||
print('### ####### error data id=', id, ' full_path : ', full_path , ' prefix : ', prefix ,' --- ', title)
|
||||
|
||||
###--------------------------------------------------------
|
||||
## فقط در همین جزء ثبت شود
|
||||
path_heading2 = path_heading
|
||||
if heading_in_content :
|
||||
path_heading2.append(heading_in_content)
|
||||
|
||||
## ----------------------------------------
|
||||
data = {}
|
||||
|
||||
data["nlp_tags"]= nlp_tags
|
||||
data["path_headings"]= path_heading2
|
||||
data["word_len"] = word_len
|
||||
data["level"]= level_2
|
||||
|
||||
update = True
|
||||
eid = id
|
||||
try:
|
||||
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
|
||||
|
||||
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')
|
||||
|
||||
file_error.close()
|
||||
print("=" * 10, " fill_content_nlp finished")
|
||||
|
||||
|
||||
##----- مرحله دوم -----------------
|
||||
## شناسایی فرزندان اجزاء اصلی
|
||||
def extract_nlp_childs(elasticHelper, index_name_i = "mj_qa_section", index_name_o = "") :
|
||||
counter = 0
|
||||
total = 0
|
||||
id = ""
|
||||
body={
|
||||
"sort": [
|
||||
{"qanon_id": {"order": "asc"}},
|
||||
{"child_order": {"order": "desc"}}
|
||||
]
|
||||
}
|
||||
if not index_name_o :
|
||||
index_name_o = index_name_i
|
||||
dicParents = {}
|
||||
try:
|
||||
try:
|
||||
list = elasticHelper.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
count = 0
|
||||
qanon_id_prev = ""
|
||||
parent_id_prev = "0"
|
||||
count_normal = 0
|
||||
count_un_normal = 0
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
|
||||
id = entry.get("id", "")
|
||||
content = entry.get("content", "")
|
||||
path_headings = entry.get("path_headings", [])
|
||||
word_len = entry.get("word_len", [])
|
||||
qanon_id = entry.get("qanon_id", "0")
|
||||
parent_id = entry.get("parent_id", "0")
|
||||
nlp_tags = entry.get("nlp_tags", [])
|
||||
|
||||
## ثبت اطلاعات
|
||||
if qanon_id != qanon_id_prev and dicParents:
|
||||
list = []
|
||||
for key, value in dicParents.items():
|
||||
list.append({
|
||||
'_id': key,
|
||||
'_source': {
|
||||
"nlp_childs" : value
|
||||
}
|
||||
})
|
||||
word_len = 0
|
||||
for child in value :
|
||||
word_len += child["word_len"]
|
||||
|
||||
if word_len > 512 :
|
||||
count_un_normal +=1
|
||||
print('--- id', key , ' child_count:', len(value), ' words:', word_len, ' count_normal:', count_normal, ' count_un_normal:', count_un_normal)
|
||||
else :
|
||||
count_normal +=1
|
||||
|
||||
elasticHelper.updateBulkList(list, index_name_o)
|
||||
dicParents = {}
|
||||
|
||||
qanon_id_prev = qanon_id
|
||||
### نیازی به بردار سازی و جستجوی معنایی یا ارتباط یابی نیست
|
||||
if 'concept_no' in nlp_tags or 'concept_bad' in nlp_tags or 'concept_base' in nlp_tags :
|
||||
continue
|
||||
### تا حد امکان با محتوای اصلی قبل، بردار شود و همانجا ذخیره شود
|
||||
elif 'concept_week' in nlp_tags or 'concept_middle' in nlp_tags or 'concept_side' in nlp_tags :
|
||||
if parent_id and parent_id != '0' and parent_id != 0 :
|
||||
#if 'words_small' in nlp_tags or 'words_small' in nlp_tags :
|
||||
if parent_id not in dicParents :
|
||||
dicParents[parent_id] = []
|
||||
|
||||
dicParents[parent_id].append({
|
||||
"word_len": word_len,
|
||||
"id": id ,
|
||||
# "content" : content
|
||||
})
|
||||
continue
|
||||
|
||||
|
||||
except Exception as e:
|
||||
# save_error(id, e)
|
||||
print("Exception: " + e)
|
||||
print( e)
|
||||
print("%s -> %.2f " % (id , (counter / total) if total > 0 else 0))
|
||||
|
||||
|
||||
print("=" * 10, "import_data_embeding finished")
|
||||
|
||||
|
||||
##----- مرحله سوم -----------------
|
||||
## تولید بردار برای اجزاء به همراه اطلاعات کناری و کمکی
|
||||
def import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_section", index_name_o = "mj_qa_section_ai", field_content="content") :
|
||||
|
||||
id = ""
|
||||
body={
|
||||
# "query": {
|
||||
# "bool": {
|
||||
# "must_not": [
|
||||
# {
|
||||
# "terms": {
|
||||
# "nlp_tags": ["concept_no","concept_bad"]
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# }
|
||||
# },
|
||||
"sort": [
|
||||
{"qanon_id": {"order": "asc"}},
|
||||
{"child_order": {"order": "asc"}}
|
||||
]
|
||||
}
|
||||
|
||||
dicParents = {}
|
||||
try:
|
||||
try:
|
||||
list = elasticHelper.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
count = 0
|
||||
qanon_id_prev = ""
|
||||
parent_state = {}
|
||||
parent_entry = {}
|
||||
prev_entry_child = {}
|
||||
for mentry in list:
|
||||
count += 1
|
||||
entry = mentry["source"]
|
||||
|
||||
id = entry.get("id", "")
|
||||
content = entry.get(field_content, "")
|
||||
path_headings = entry.get("path_headings", [])
|
||||
qanon_title = entry.get("qanon_title", [])
|
||||
word_len = entry.get("word_len", [])
|
||||
qanon_id = entry.get("qanon_id", "0")
|
||||
parent_id = entry.get("parent_id", "0")
|
||||
nlp_tags = entry.get("nlp_tags", [])
|
||||
nlp_childs = entry.get("nlp_childs", [])
|
||||
|
||||
qanon_id_prev = qanon_id
|
||||
### نیازی به بردار سازی و جستجوی معنایی یا ارتباط یابی نیست
|
||||
if 'concept_no' in nlp_tags or 'concept_bad' in nlp_tags or not content:
|
||||
continue
|
||||
|
||||
content_emb = ''
|
||||
content_offset = ' '
|
||||
data = entry
|
||||
word_len_childs = 0
|
||||
if nlp_childs and len(nlp_childs) :
|
||||
|
||||
## اگر پدر و فرزندهای قبلی چیزی هنوز مونده ، بردارسازی باید شود
|
||||
if prev_entry_child :
|
||||
eid = prev_entry_child.get("id", "")
|
||||
content = prev_entry_child.get(field_content, "")
|
||||
data = prev_entry_child
|
||||
content_offset = parent_state["content_offset"]
|
||||
content_emb = parent_state["content"] + "\n" + content + "\n"+ parent_state["content_emb"]
|
||||
data["content_emb"] = content_emb
|
||||
prev_entry_child = {}
|
||||
|
||||
# word_len_childs = 0
|
||||
# for item in nlp_childs :
|
||||
# word_len_childs += item["word_len"]
|
||||
|
||||
#word_len_total = word_len + word_len_childs
|
||||
content_offset = 'در ' + qanon_title + ' درباره '
|
||||
for hed in path_headings :
|
||||
content_offset += ' ' + hed.strip()
|
||||
word_len_offset = len(split_words(content_offset))
|
||||
parent_state = {
|
||||
"id" : id,
|
||||
"word_len" : word_len,
|
||||
"word_len_offset" : word_len_offset,
|
||||
"nlp_childs" : nlp_childs,
|
||||
"content" : content,
|
||||
"content_offset" : content_offset,
|
||||
"word_len_childs" : 0,
|
||||
"content_emb" : "",
|
||||
"is_parent_embedded" : 0
|
||||
}
|
||||
parent_entry = entry
|
||||
### تا حد امکان با محتوای اصلی قبل، بردار شود و همانجا ذخیره شود
|
||||
elif 'concept_week' in nlp_tags or 'concept_middle' in nlp_tags or 'concept_side' in nlp_tags :
|
||||
if parent_state and parent_state["id"] == parent_id :
|
||||
wl = parent_state["word_len"]
|
||||
wl_of = parent_state["word_len_offset"]
|
||||
wl_em = parent_state["word_len_childs"]
|
||||
len_total = wl + wl_of + wl_em + word_len
|
||||
## اگر جا داره که با محتوای ماده اصلی=، بردار سازی باشد
|
||||
if len_total < 512 :
|
||||
parent_state["word_len_childs"] += word_len
|
||||
parent_state["content_emb"] = parent_state["content_emb"] + "\n" + content
|
||||
|
||||
## محتوای اصلی با بخشی از محتوای بندها و زیرجزءها، بردارسازی و ذخیره شود و مابقی در ادامه
|
||||
else :
|
||||
if parent_state["is_parent_embedded"] == 1: ## قبلا محتوای پدر با فرزندان در حد طول 512 بردارسازی شده و ذخیره شده است
|
||||
## حالا محتوای فرزندهای باقیمانده با کمک محتوای پدرا باید تا طول 512 بردارسازی شوند
|
||||
if prev_entry_child :
|
||||
eid = prev_entry_child.get("id", "")
|
||||
content = prev_entry_child.get(field_content, "")
|
||||
data = prev_entry_child
|
||||
content_offset = parent_state["content_offset"]
|
||||
content_emb = parent_state["content"] + "\n" + content + "\n"+ parent_state["content_emb"]
|
||||
data["content_emb"] = content_emb
|
||||
else : ## تست شد : پیش نمی آید
|
||||
print('------ no prev entry for child ####### error data id=', id, ' wl_em : ', wl_em, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
|
||||
|
||||
prev_entry_child = entry
|
||||
parent_state["word_len_childs"] = 0
|
||||
parent_state["content_emb"] = ''
|
||||
|
||||
|
||||
elif parent_entry :
|
||||
|
||||
parent_state["is_parent_embedded"] = 1
|
||||
eid = parent_state["id"]
|
||||
data = parent_entry
|
||||
|
||||
content_offset = parent_state["content_offset"]
|
||||
content_emb = parent_state["content"] + "\n" + parent_state["content_emb"]
|
||||
data["content_emb"] = content_emb
|
||||
|
||||
prev_entry_child = entry
|
||||
parent_entry={}
|
||||
parent_state["word_len_childs"] = 0
|
||||
parent_state["content_emb"] = ''
|
||||
|
||||
else : ## تست شد : پیش نمی آید
|
||||
print('### no parent for child ####### error data id=', id, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
|
||||
|
||||
else :
|
||||
|
||||
#if parent_id != 0 :
|
||||
## مواردی هستند که با پدر خود فاصله ایجاد شده است مثل qs918484
|
||||
## فعلا کمک محتوایی براشون نمی کنیم
|
||||
#print('### child withuot parent ####### error data id=', id, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
|
||||
eid = id
|
||||
content_offset = 'در ' + qanon_title + ' درباره '
|
||||
for hed in path_headings :
|
||||
content_offset += ' ' + hed.strip()
|
||||
content_emb = content
|
||||
|
||||
else :
|
||||
eid = id
|
||||
content_offset = 'در ' + qanon_title + ' درباره '
|
||||
for hed in path_headings :
|
||||
content_offset += ' ' + hed.strip()
|
||||
|
||||
content_emb = content
|
||||
|
||||
|
||||
|
||||
if content_emb :
|
||||
|
||||
payload={
|
||||
'text': content_offset + ' ' + content_emb
|
||||
}
|
||||
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
|
||||
try:
|
||||
if "pos_tags" in data:
|
||||
del data["pos_tags"]
|
||||
if "chunk_tags" in data:
|
||||
del data["chunk_tags"]
|
||||
|
||||
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
|
||||
|
||||
except Exception as e:
|
||||
save_error(eid, e)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
print("=" * 10, "import_data_embeding finished")
|
||||
|
||||
|
||||
|
||||
|
||||
def import_classification(elasticHelper, ai_url_class, index_name_o = "mj_qa_section_ai") :
|
||||
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")
|
||||
|
||||
|
||||
def isMomSection(other_info, content):
|
||||
if not other_info["full_path"] :
|
||||
return True
|
||||
|
||||
paths = other_info["full_path"].split('>')
|
||||
last_item = paths[len(paths)-1]
|
||||
print(paths)
|
||||
print(last_item)
|
||||
if "ماده" in last_item :
|
||||
return True
|
||||
|
||||
content = content.strip()
|
||||
if re.match(r"^((ضمیمه)|(جدول))\s*\d*$", content):
|
||||
return True
|
||||
|
||||
|
||||
#isMomSection({"full_path":"باب اول>فصل اول>ماده 8"})
|
||||
@@ -0,0 +1,107 @@
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from decimal import Decimal
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
from app.common.create_ai_index import *
|
||||
|
||||
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_60')
|
||||
# password=os.getenv('HOST_60_PASS')
|
||||
|
||||
|
||||
print(host)
|
||||
# print(password)
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
## 0 ##--------------------------------------------------
|
||||
##----- تولید داده های جدید از اس کیو ال با مجموعه دستورات موجود در فایل زیر
|
||||
##----- import_from_sql.all_sql_steps.py
|
||||
##-- و تولید ایندکسهای جدید
|
||||
##-- mj_qa_qanon_temp
|
||||
##-- mj_rg_section_temp
|
||||
##-- mj_qa_section_temp
|
||||
##-- mj_qa_opinion_temp
|
||||
|
||||
|
||||
## 1 ##-----------------------------------------------------------------
|
||||
##----- انتقال اطلاعات قبلی به اینجا
|
||||
#elastic.moveCustomFileds("mj_qa_section", "mj_qa_section_temp", ["ners_v1", "nlp_parser", "code-ai"])
|
||||
|
||||
## 2 ##-----------------------------------------------------------------
|
||||
## ----- تغییر ایندکسهای موقت به ایندکسهای اصلی
|
||||
# elastic.deleteIndex("mj_qa_opinion")
|
||||
# elastic.renameElasticIndex("mj_qa_opinion_temp", "mj_qa_opinion", "majles", "mj_qa_opinion")
|
||||
|
||||
# elastic.deleteIndex("mj_qa_qanon")
|
||||
# elastic.renameElasticIndex("mj_qa_qanon_temp", "mj_qa_qanon", "majles", "mj_qa_qanon")
|
||||
|
||||
# elastic.deleteIndex("mj_qa_section")
|
||||
# elastic.renameElasticIndex("mj_qa_section_temp", "mj_qa_section", "majles", "mj_qa_section")
|
||||
|
||||
# elastic.deleteIndex("mj_rg_section")
|
||||
# elastic.renameElasticIndex("mj_rg_section_temp", "mj_rg_section", "majles", "mj_qa_section")
|
||||
|
||||
## 3 ##-----------------------------------------------------------------
|
||||
|
||||
## محاسبات پردازش داده ای واجب و پیچیده که پایه تمیزی داده در فاز2 و 3 هست اینجا انجام می شود
|
||||
#fill_nlp_tags(elastic, "mj_qa_section")
|
||||
#extract_nlp_childs(elastic,"mj_qa_section")
|
||||
|
||||
## 4 ## --------------------------------------------------------------
|
||||
## پرکردن فیلدهای هوش مصنوعی برای اجزاء یا قانونهای جدید
|
||||
|
||||
##///////////////////////////////////////////////////////////
|
||||
## 4.1 ## -----------------------------------------------------------------
|
||||
# تولید بردار برای اجزائی که لازم هست
|
||||
|
||||
|
||||
# elastic.createIndex("mj_qa_section_ai", 'majles/', "mj_qa_section" )
|
||||
|
||||
# ai_url_vec=os.getenv("ai_url_vec")
|
||||
# import_data_embeding(elastic, ai_url_vec ,"mj_qa_section", "mj_qa_section_ai", "content" )
|
||||
|
||||
|
||||
## 4.2 ## -----------------------------------------------------------------
|
||||
# برچسبهای هوشمند
|
||||
|
||||
# import_classification(elastic, ai_url_class, "mj_qa_section_temp")
|
||||
|
||||
## 5 ## --------------------------------------------------------------
|
||||
## پشتیبان گیری از داده جدید تکمیلی
|
||||
|
||||
##///////////////////////////////////////////////////////////
|
||||
## پشتیبان گیری
|
||||
|
||||
# path_back = os.getcwd() + '/data_back'
|
||||
path_back = 'G:/Project2/111'
|
||||
# if not os.path.exists(path_back) :
|
||||
# os.makedirs(path_back)
|
||||
# print('---> path_back = ' + path_back)
|
||||
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_qa_qanon")
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_qa_section")
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_qa_section", '', {}, True, [], ["pos_tags", "chunk_tags", "version_info"])
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_qa_section_ai")
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_rg_section")
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_qa_opinion")
|
||||
|
||||
## کد نمونه بازیابی از فایل
|
||||
#path_back = 'G:/Project2/_back/back_data/data_majles/elastic/v1.0/full'
|
||||
# path_back = 'G:/Project2/111'
|
||||
# elastic.restorFileToElastic(path_back, 'mj_qa_section_ai', 'majles', True, 'mj_qa_section')
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import requests
|
||||
import json
|
||||
from decimal import Decimal
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from s1_LWTopic import *
|
||||
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 s11_Tanghih_plan_move import *
|
||||
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
## ابتدا دستورات زیر را به ترتیب در دیتابیس فهرست اجرا شود
|
||||
# SELECT id from tl_projects where title='موضوعات درختی قانون'
|
||||
# DELETE from tl_subjects where project_id= (SELECT id from tl_projects where title='موضوعات درختی قانون')
|
||||
# -----------------------------------------------------------------
|
||||
# اجرای دستورات زیر در الاستیک
|
||||
# DELETE mj_qa_qanon_temp
|
||||
# DELETE mj_rg_section_temp
|
||||
# DELETE mj_qa_section_temp
|
||||
# DELETE mj_qa_opinion_temp
|
||||
# -----------------------------------------------------------------
|
||||
|
||||
# cursor, cnxn = create_cursor()
|
||||
|
||||
## ایجاد فهرست موضوعات قانون
|
||||
#projectid = insertProejct()
|
||||
#insertProjectItems(cursor, projectid)
|
||||
|
||||
# 2
|
||||
#import_law_section_to_elastic(cursor)
|
||||
|
||||
|
||||
# import_regulation_section_to_elastic(cursor)
|
||||
|
||||
# import_opinion_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()
|
||||
|
||||
|
||||
cursor, cnxn = create_cursor('db4minaei')
|
||||
# #####import_tangih_tree_to_list(cursor)
|
||||
import_tanghih_plan_codes(cursor)
|
||||
|
||||
cursor.close()
|
||||
cnxn.close()
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,219 @@
|
||||
import json
|
||||
import requests
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
def import_lawreg_lwphase_info(cursor):
|
||||
query='SELECT ID,CAPTION FROM [Qavanin].[dbo].[cmOrganization]'
|
||||
cursor.execute(query)
|
||||
|
||||
ORG_DICT = {}
|
||||
|
||||
while True:
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
|
||||
text = text_normal.normalize_qanon(row.CAPTION)
|
||||
rr = {"id" : int(row.ID), 'title': text}
|
||||
ORG_DICT[str(int(row.ID))] = {"id" : row.ID, 'title': text}
|
||||
|
||||
|
||||
query = '''
|
||||
|
||||
SELECT
|
||||
F_LWLAWID as F_LWLAWID,
|
||||
p.ID as Phase_ID,
|
||||
isnull(COMMANDDATE,'') as COMMANDDATE ,
|
||||
isnull(COMMANDNO,'') as COMMANDNO,
|
||||
isnull(NEWSPAPERDATE,'') as NEWSPAPERDATE,
|
||||
isnull(NEWSPAPERNO,'') as NEWSPAPERNO,
|
||||
isnull(o.CAPTION,'') as organization_title
|
||||
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_CMORGANIZATIONID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM [lwReceiver] where F_LWLAWID=p.[F_LWLAWID]) as receiver
|
||||
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_CMORGANIZATIONID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM [lwExecutor] where F_LWLAWID=p.[F_LWLAWID]) as exceuter
|
||||
,(SELECT top (1) [EXECUTIONDATE] FROM [lwExecuteCondition] where [F_PHASEID]=p.id) as EXECUTIONDATE
|
||||
FROM [Qavanin].[dbo].[lwPhase] p
|
||||
left join cmOrganization o on p.F_CMORGANIZATIONID = o.ID
|
||||
left join lwLaw l1 on p.F_LWLAWID= l1.ID
|
||||
|
||||
-- order by F_LWLAWID --بعضی موارد تکرار شده اند
|
||||
'''
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
|
||||
url = BASE_URL + "repo/majles/qaqanon/multi/update"
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
previd = ''
|
||||
ref_state_array = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print("start time: " + str(t1))
|
||||
i = 0
|
||||
all_data = []
|
||||
repeat_data = []
|
||||
while 1:
|
||||
|
||||
i += 1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
phase_id = str(int(row.Phase_ID.real))
|
||||
law_id = str(int(row.F_LWLAWID.real))
|
||||
eb_number = row.COMMANDNO.strip() if row.COMMANDNO else ''
|
||||
eb_date = row.COMMANDDATE.strip() if row.COMMANDDATE else ''
|
||||
eb_ref = row.organization_title.strip() if row.organization_title else '' # نرمالایز میخواد؟
|
||||
rrk_number = row.NEWSPAPERNO.strip() if row.NEWSPAPERNO else ''
|
||||
rrk_date = row.NEWSPAPERDATE.strip() if row.NEWSPAPERDATE else ''
|
||||
exec_date = row.EXECUTIONDATE.strip() if row.EXECUTIONDATE else ''
|
||||
receiver_ids = row.receiver
|
||||
exceuter_ids = row.exceuter
|
||||
|
||||
if eb_date == '0000/00/00' :
|
||||
eb_date = ''
|
||||
if rrk_date == '0000/00/00' :
|
||||
rrk_date = ''
|
||||
if exec_date == '0000/00/00' :
|
||||
exec_date = ''
|
||||
|
||||
if eb_number == 'نامعلوم' or eb_number == 'ندارد':
|
||||
eb_number = ''
|
||||
if rrk_number == 'نامعلوم' or rrk_number == 'ندارد':
|
||||
rrk_number = ''
|
||||
|
||||
# # جایگذاری مقدار خالی به جای نامعلوم
|
||||
# if eb_number.__contains__("معلوم"):
|
||||
# eb_number = ""
|
||||
# if eb_date.__contains__("معلوم"):
|
||||
# eb_date = ""
|
||||
# if eb_ref.__contains__("معلوم"):
|
||||
# eb_ref = ""
|
||||
# if rrk_number.__contains__("معلوم"):
|
||||
# rrk_number = ""
|
||||
# if rrk_date.__contains__("معلوم"):
|
||||
# rrk_date = ""
|
||||
|
||||
# کمتر از 10 مورد تکرار داشتند، ظاهرا چند بار در روزنامه رسمی منتشر شده و هر بار بخشی از آن ، لذا اولین اطلاعات پر آن برداشته شد
|
||||
if law_id == '178971':
|
||||
eb_number = "7644 ج"
|
||||
if law_id == '244878':
|
||||
eb_number = ""
|
||||
if law_id == '83695':
|
||||
eb_number = "3923"
|
||||
if law_id == '115887':
|
||||
eb_number = ""
|
||||
if law_id == '113211':
|
||||
eb_number = ""
|
||||
if law_id == '83452':
|
||||
eb_number = "70445"
|
||||
if law_id == '111876':
|
||||
eb_number = "7848"
|
||||
if law_id == '198907':
|
||||
eb_number = "36094"
|
||||
if law_id == '87694':
|
||||
eb_number = "36341/ 1"
|
||||
|
||||
if law_id in all_data:
|
||||
repeat_data.append(law_id)
|
||||
continue
|
||||
|
||||
all_data.append(law_id)
|
||||
# print("row: %s" % str(i))
|
||||
|
||||
receiver_organs = []
|
||||
if receiver_ids :
|
||||
for id in receiver_ids.split(',') :
|
||||
if id in ORG_DICT :
|
||||
receiver_organs.append({ "id": id, "title":ORG_DICT[id]["title"]})
|
||||
|
||||
exceuter_organs = []
|
||||
if exceuter_ids :
|
||||
for id in exceuter_ids.split(',') :
|
||||
if id in ORG_DICT :
|
||||
exceuter_organs.append({ "id": id, "title":ORG_DICT[id]["title"]})
|
||||
|
||||
|
||||
|
||||
eid= 'qq' + law_id
|
||||
|
||||
eblagh = {
|
||||
'number' : eb_number,
|
||||
'date' : eb_date,
|
||||
'from' : eb_ref,
|
||||
}
|
||||
|
||||
rrk = {
|
||||
'number' : rrk_number,
|
||||
'date' : rrk_date,
|
||||
}
|
||||
|
||||
data={
|
||||
'id' : eid,
|
||||
'eblagh' : eblagh,
|
||||
'rrk': rrk,
|
||||
'exec_date' : exec_date,
|
||||
'receiver_organs' : receiver_organs,
|
||||
'exceuter_organs' : exceuter_organs,
|
||||
}
|
||||
|
||||
|
||||
if len(bulk_data) >= 100:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' lawreg_lwphase_info , total='+str(total_count) , str(i)+ ', id=' + eid )
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(bulk_data)
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
# print(bulk_count)
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
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 != 200 :
|
||||
print(bulk_data)
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
|
||||
# print(response.text )
|
||||
|
||||
|
||||
t2= datetime.datetime.now()
|
||||
print("update rows count: " + str(len(all_data)))
|
||||
print("finished time: " + str(t2))
|
||||
print("process time: " + str(t2-t1))
|
||||
print(' end success lawreg_lwphase_info ')
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
import json
|
||||
import requests
|
||||
import requests
|
||||
from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
# این برنامه یک بار فقط جهت انتقال کدهای دیتابیس آقای شاهنوش به دیتابیس نهایی قوانین انجام شد
|
||||
# تکرار لازم نیست
|
||||
# در بقیه حالات اگر کدها تغییر نکرده باشد در خود الاستیک بروز رسانی می شود
|
||||
|
||||
|
||||
#cursor, cnxn = create_cursor('db4minaei')
|
||||
|
||||
def import_tanghih_plan_codes(cursor):
|
||||
|
||||
plan1 = {}
|
||||
query = """select * from dbo.[lwplan] where [f_parentid]=766 order by [ordno] """
|
||||
cursor.execute(query)
|
||||
i = 0
|
||||
while 1:
|
||||
i=i+1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
plan1[row.ID] = normalYehKe(row.caption)
|
||||
|
||||
# print(plan1)
|
||||
|
||||
plan2 = {}
|
||||
query = """select * from dbo.[lwplan] where [f_parentid]=21185 order by [ordno] """
|
||||
cursor.execute(query)
|
||||
i = 0
|
||||
while 1:
|
||||
i=i+1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
plan2[row.ID] = normalYehKe(row.caption)
|
||||
|
||||
# print(plan2)
|
||||
|
||||
# #########################################################
|
||||
|
||||
query = '''
|
||||
SELECT [f_lwplanid]
|
||||
,[f_lwlawsecid]
|
||||
,[planstate]
|
||||
,[ID]
|
||||
FROM [db4minaei].[dbo].[lwlawplan]
|
||||
where f_lwlawsecid is not null and f_lwlawsecid > 0
|
||||
order by f_lwlawsecid, planstate, f_lwplanid
|
||||
|
||||
'''
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
url = BASE_URL + "repo/majles/section/multi/update"
|
||||
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
previd = ''
|
||||
|
||||
tcode_main_old = []
|
||||
tcode_sub_old = []
|
||||
tcode_main = []
|
||||
tcode_sub = []
|
||||
prev_sectionid = 0
|
||||
prev_planid = 0
|
||||
prev_planstate = 0
|
||||
|
||||
prev2_sectionid = 0
|
||||
prev2_planid = 0
|
||||
prev2_planstate = 0
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
i = 0
|
||||
while 1:
|
||||
# print(i)
|
||||
i=i+1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
# if i > 3:
|
||||
# break
|
||||
# print(row.sectionId)
|
||||
|
||||
sectionid = row.f_lwlawsecid
|
||||
planid = row.f_lwplanid
|
||||
planstate = row.planstate
|
||||
|
||||
if prev_sectionid == 0 :
|
||||
prev_sectionid = sectionid
|
||||
prev_planid = planid
|
||||
prev_planstate = planstate
|
||||
continue
|
||||
|
||||
|
||||
if sectionid == prev_sectionid and planid == prev_planid and planstate == prev_planstate :
|
||||
continue
|
||||
|
||||
|
||||
if sectionid == prev_sectionid :
|
||||
if prev_planid in plan1 :
|
||||
if prev_planstate == 1 :
|
||||
tcode_main_old.append(plan1[prev_planid])
|
||||
else :
|
||||
tcode_sub_old.append(plan1[prev_planid])
|
||||
|
||||
|
||||
elif prev_planid in plan2 :
|
||||
if prev_planstate == 1 :
|
||||
tcode_main.append(plan2[prev_planid])
|
||||
else :
|
||||
tcode_sub.append(plan2[prev_planid])
|
||||
prev_planid = planid
|
||||
prev_planstate = planstate
|
||||
continue
|
||||
|
||||
|
||||
eid='qs'+ str(prev_sectionid)
|
||||
# data={
|
||||
# 'id' : eid,
|
||||
# 'tcode_main' : tcode_main,
|
||||
# 'tcode_sub' : tcode_sub,
|
||||
# 'tcode_main_old' : tcode_main_old,
|
||||
# 'tcode_sub_old' : tcode_sub_old,
|
||||
# }
|
||||
|
||||
data={
|
||||
'id' : eid,
|
||||
'tcode':{
|
||||
'mains' : tcode_main,
|
||||
'subs' : tcode_sub,
|
||||
'mains_old' : tcode_main_old,
|
||||
'subs_old' : tcode_sub_old,
|
||||
}
|
||||
}
|
||||
|
||||
# print(eid)
|
||||
|
||||
bulk_data.append(data)
|
||||
prev_sectionid = sectionid
|
||||
tcode_main_old = []
|
||||
tcode_sub_old = []
|
||||
tcode_main = []
|
||||
tcode_sub = []
|
||||
|
||||
if len(bulk_data) >= 100:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ', total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
# /////////////////
|
||||
prev2_sectionid = prev_sectionid
|
||||
prev2_planid = prev_planid
|
||||
prev2_planstate = prev_planstate
|
||||
|
||||
prev_sectionid = sectionid
|
||||
prev_planid = planid
|
||||
prev_planstate = planstate
|
||||
|
||||
|
||||
|
||||
|
||||
# if prev2_sectionid == prev_sectionid :
|
||||
if prev_planid in plan1 :
|
||||
if prev_planstate == 1 :
|
||||
tcode_main_old.append(plan1[prev_planid])
|
||||
else :
|
||||
tcode_sub_old.append(plan1[prev_planid])
|
||||
|
||||
|
||||
elif prev_planid in plan2 :
|
||||
if prev_planstate == 1 :
|
||||
tcode_main.append(plan2[prev_planid])
|
||||
else :
|
||||
tcode_sub.append(plan2[prev_planid])
|
||||
# else :
|
||||
|
||||
|
||||
eid='qs'+ str(prev_sectionid)
|
||||
data={
|
||||
'id' : eid,
|
||||
'tcode':{
|
||||
'mains' : tcode_main,
|
||||
'subs' : tcode_sub,
|
||||
'mains_old' : tcode_main_old,
|
||||
'subs_old' : tcode_sub_old,
|
||||
}
|
||||
}
|
||||
|
||||
# data={
|
||||
# 'id' : eid,
|
||||
# 'tcode_main' : tcode_main,
|
||||
# 'tcode_sub' : tcode_sub,
|
||||
# 'tcode_main_old' : tcode_main_old,
|
||||
# 'tcode_sub_old' : tcode_sub_old,
|
||||
# }
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ', total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
|
||||
# print(response.text)
|
||||
|
||||
t2= datetime.datetime.now()
|
||||
print("finished time: " + str(t2))
|
||||
print("process time: " + str(t2-t1))
|
||||
print(' end success lawreg_lwphase_info ')
|
||||
|
||||
|
||||
|
||||
def import_tangih_tree_to_list(cursor):
|
||||
# -----------------------------------------------------------------
|
||||
# BASE_URL = "https://api.tavasi.ir/list/"
|
||||
# ADD_LIST_ROUTE = "project/add"
|
||||
# ADD_ITEM_ROUTE = "subject/add"
|
||||
# TITLE = "فهرست موضوعات قانون"
|
||||
# TYPE = 3
|
||||
# ADD_LIST_QUERY = {"title": TITLE, "type": TYPE, "item_state": 1}
|
||||
GET_H = lambda x: x["HIERARCHY"]
|
||||
GET_F = lambda x: x["F_PARENTID"]
|
||||
|
||||
|
||||
# ADD_LIST_QUERY = {
|
||||
# "title": TITLE,
|
||||
# "listtype": 3,
|
||||
# "item_state": 1,
|
||||
# "ispublic" : 1,
|
||||
# }
|
||||
|
||||
# requests.post(BASE_URL + ADD_LIST_ROUTE, data=ADD_LIST_QUERY, headers = HEADERS)
|
||||
projectid = 3
|
||||
|
||||
EXAMPLE_ADD_ITEM_QUERY = {
|
||||
"title": "",
|
||||
"projectid": projectid,
|
||||
"listtype": 0,
|
||||
"parent": 0,
|
||||
}
|
||||
|
||||
|
||||
|
||||
query = """select * from dbo.[lwplan]"""
|
||||
cursor.execute(query)
|
||||
|
||||
|
||||
result = []
|
||||
|
||||
while True:
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
HIERARCHY = row.hierarchy
|
||||
HIERARCHY = HIERARCHY.split(".")[-2]
|
||||
HIERARCHY = HIERARCHY.rjust(3, "0")
|
||||
|
||||
result.append(
|
||||
{
|
||||
"ID": int(row.ID),
|
||||
"CODE": row.CODE,
|
||||
"CAPTION": row.CAPTION,
|
||||
"F_PARENTID": int(row.F_PARENTID) if row.F_PARENTID else 0,
|
||||
"HIERARCHY": HIERARCHY,
|
||||
}
|
||||
)
|
||||
# result = sorted(result, key=GET_F)
|
||||
result = sorted(result, key=GET_H)
|
||||
|
||||
|
||||
childs = {}
|
||||
IDS_DICT = {}
|
||||
|
||||
def insert(rows):
|
||||
remains =[]
|
||||
for row in rows:
|
||||
number = 1
|
||||
try:
|
||||
F_PARENTID = row["F_PARENTID"]
|
||||
except KeyError:
|
||||
F_PARENTID = -1
|
||||
print('*'*20)
|
||||
print(row)
|
||||
print('#'*20)
|
||||
continue
|
||||
|
||||
# try:
|
||||
if F_PARENTID == 0:
|
||||
parent = 0
|
||||
elif str(F_PARENTID) in IDS_DICT:
|
||||
parent = IDS_DICT[str(F_PARENTID)]['id']
|
||||
else:
|
||||
print(F_PARENTID)
|
||||
print(IDS_DICT)
|
||||
print(row)
|
||||
break
|
||||
remains.append(row)
|
||||
continue
|
||||
|
||||
# except KeyError:
|
||||
# print('error')
|
||||
# print(row)
|
||||
# continue
|
||||
|
||||
if parent in childs:
|
||||
number = childs[parent] + 1
|
||||
childs[parent] = number
|
||||
|
||||
ADD_ITEM_QUERY = {
|
||||
"title": row["CAPTION"],
|
||||
"projectid": projectid,
|
||||
"otherid": row["ID"],
|
||||
"meta": row["CODE"],
|
||||
"childorder": number,
|
||||
"listtype": 0,
|
||||
"parent": parent,
|
||||
}
|
||||
# result = requests.post(BASE_URL + ADD_ITEM_ROUTE, data=ADD_ITEM_QUERY, headers=HEADERS)
|
||||
|
||||
New_ID = json.loads(result.text)["data"][0]["id"]
|
||||
print(str(row["ID"]) + '=' + str(New_ID))
|
||||
IDS_DICT[str(row["ID"])] = {"id" : int(New_ID), 'title': row["CAPTION"]}
|
||||
|
||||
return remains
|
||||
|
||||
remains = insert(result)
|
||||
# print(IDS_DICT)
|
||||
|
||||
count = 1
|
||||
while remains.__len__() > 0 and count < 2:
|
||||
print('##################' + str(count))
|
||||
print( remains.__len__() )
|
||||
remains = insert(remains)
|
||||
# print(IDS_DICT)
|
||||
count = count + 1
|
||||
|
||||
with open("list_Tanghih.json", 'w') as file:
|
||||
file.write(json.dumps(IDS_DICT))
|
||||
@@ -0,0 +1,207 @@
|
||||
import json
|
||||
import os
|
||||
from html import escape
|
||||
import json
|
||||
import datetime
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
from app.common.qanon_functions import *
|
||||
|
||||
# ضرورتا
|
||||
# این برنامه ضرورت دارد اجرا شود
|
||||
# بسیاری از اجزاء قانون دارای وضعیت مثل منسوخه و جایگزین شده بودند که اطلاعات اثرگذ اری شون پر نشده بود
|
||||
# مشخص شد اینها با کلیت یک قانون اثرگذ ار ثبت شده نه بخش مشخص از قانون
|
||||
# لذا این ناقصی با این برنامه تکمیل شد
|
||||
|
||||
def check_duplicate_ref_state(list):
|
||||
dict_index={}
|
||||
res = []
|
||||
for item in list :
|
||||
if item["id"] in dict_index :
|
||||
index = dict_index[item["id"]]
|
||||
if res[index]["qanon_id"] == item["qanon_id"] and res[index]["section_id"] == item["section_id"]:
|
||||
continue # duplicate
|
||||
dict_index[item["id"]] = len(res)
|
||||
res.append(item)
|
||||
return res
|
||||
|
||||
|
||||
def import_law_section_repair_ref_state(cursor, elastic, index_name_o, file_log):
|
||||
query = '''
|
||||
SELECT l1.[ID] as sectionId
|
||||
,l1.F_CMBASETABLEID_SECTIONSTATUS
|
||||
,l1.[F_LWLAWCHANGEID] as id
|
||||
,l2.F_LWLAWID_EFFECTED
|
||||
,l2.F_LWLAWID_EFFECTIVE as effect_qanon_id
|
||||
,l3.CAPTION as effect_qanon
|
||||
,l3.APPROVEDATE as effect_Date
|
||||
,ls1.CAPTION as effect_section_type
|
||||
-- ,l4.ID as id_1
|
||||
|
||||
FROM [Qavanin].[dbo].[lwSection] l1
|
||||
left join [Qavanin].[dbo].[lwLawSectionStatus] ls1 on ls1.ID=l1.[F_CMBASETABLEID_SECTIONSTATUS]
|
||||
left join [Qavanin].[dbo].lwLawChange l2 on l1.F_LWLAWCHANGEID=l2.id
|
||||
left join [Qavanin].[dbo].lwLaw l3 on l2.F_LWLAWID_EFFECTIVE=l3.id
|
||||
left join [Qavanin].[dbo].lwSectionChange l4 on l1.id=l4.F_LWSECTIONID_EFFECTED
|
||||
where
|
||||
l3.ISLAW = 1
|
||||
and l4.ID is null --یعنی قبلا از طریق دیگر این اطلاعات برایش پر نشده باشد
|
||||
and l2.F_LWLAWID_EFFECTED is not null -- یعنی اطلاعات جدید اثرگذاری وجود داشته باشد
|
||||
|
||||
'''
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
file = open(file_log, 'a+', encoding='utf8')
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
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)
|
||||
|
||||
|
||||
effect_type = ''
|
||||
# effect_type = text_normal.normalize_qanon(row.effect_section_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
|
||||
|
||||
prev_ref_state = []
|
||||
item = {}
|
||||
try:
|
||||
item = elastic.get_doctument(index_name_o, eid)
|
||||
if 'ref_state' in item['_source'] :
|
||||
if len(item['_source']['ref_state']) > 0:
|
||||
prev_ref_state = item['_source']['ref_state']
|
||||
prev_ref_state1 = check_duplicate_ref_state(prev_ref_state)
|
||||
if len(prev_ref_state) != len(prev_ref_state1):
|
||||
print(' ==========> check_duplicate_ref_state OK : ', eid)
|
||||
file.write('==========> check_duplicate_ref_state OK : '+ eid + '\n')
|
||||
prev_ref_state = prev_ref_state1
|
||||
# continue
|
||||
|
||||
except Exception as e:
|
||||
# print(type(e).__name__)
|
||||
continue
|
||||
|
||||
ref_state = {}
|
||||
if row.effect_qanon_id :
|
||||
|
||||
result = [item for item in prev_ref_state if item['id'] == str(row.id)]
|
||||
if result : # این مورد قبلا در الاستیک اضافه شده است
|
||||
continue
|
||||
|
||||
efect_qanon_id= 'qq'+ str(row.effect_qanon_id)
|
||||
|
||||
ref_state = {
|
||||
"id" : str(row.id),
|
||||
"qanon_id": efect_qanon_id,
|
||||
"qanon_title" : text_normal.normalize_qanon(row.effect_qanon),
|
||||
"qanon_date": row.effect_Date,
|
||||
"section_id": '',
|
||||
"section_title": "",
|
||||
"ref_key": "qavanin",
|
||||
"effect_type" : effect_type,
|
||||
"new_text" : "",
|
||||
"prev_text" : "",
|
||||
"description" : ""
|
||||
}
|
||||
|
||||
prev_ref_state.insert(0 , ref_state)
|
||||
|
||||
data={
|
||||
'_id' : eid,
|
||||
'_source' : {
|
||||
'ref_state' : prev_ref_state
|
||||
}
|
||||
}
|
||||
|
||||
bulk_data.append(data)
|
||||
# print("-"*10, " bulk_data.append ", eid)
|
||||
prev_ref_state = []
|
||||
|
||||
|
||||
if len(bulk_data) >= 100:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' law_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
elastic.updateBulkList(bulk_data, index_name_o)
|
||||
bulk_data = []
|
||||
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' law_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
elastic.updateBulkList(bulk_data, index_name_o)
|
||||
|
||||
file.close()
|
||||
print('end success import_law_section_update_ref_state')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
|
||||
|
||||
|
||||
cursor, cnxn = create_cursor()
|
||||
|
||||
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)
|
||||
|
||||
|
||||
import_law_section_repair_ref_state(cursor, elastic, "mj_qa_section", "./output/log_s12.txt")
|
||||
|
||||
cursor.close()
|
||||
cnxn.close()
|
||||
@@ -0,0 +1,127 @@
|
||||
import requests
|
||||
import json
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
|
||||
# cursor, cnxn = create_cursor()
|
||||
|
||||
ADD_LIST_ROUTE = "project/add"
|
||||
ADD_ITEM_ROUTE = "subject/add"
|
||||
TITLE = "موضوعات درختی قانون"
|
||||
GET_H = lambda x: x["HIERARCHY"]
|
||||
|
||||
def insertProejct():
|
||||
# ایجاد فهرست جدید
|
||||
|
||||
ADD_LIST_QUERY = {
|
||||
"title": TITLE,
|
||||
"type": 3,
|
||||
"item_state": 1,
|
||||
"ispublic" : 1,
|
||||
}
|
||||
|
||||
# requests.post(BASE_URL + 'list/' + ADD_LIST_ROUTE, data=ADD_LIST_QUERY, headers = HEADERS)
|
||||
projectid = 6
|
||||
return projectid
|
||||
|
||||
#----------------------------------------------------------------
|
||||
|
||||
def insert(rows, projectid, IDS_DICT, childs ):
|
||||
remains =[]
|
||||
for row in rows:
|
||||
number = 1
|
||||
try:
|
||||
F_PARENTID = row["F_PARENTID"]
|
||||
except KeyError:
|
||||
F_PARENTID = -1
|
||||
print('*'*20)
|
||||
print(row)
|
||||
print('#'*20)
|
||||
continue
|
||||
|
||||
# try:
|
||||
if F_PARENTID == 0:
|
||||
parent = 0
|
||||
elif str(F_PARENTID) in IDS_DICT:
|
||||
parent = IDS_DICT[str(F_PARENTID)]['id']
|
||||
else:
|
||||
print(F_PARENTID)
|
||||
print(IDS_DICT)
|
||||
print(row)
|
||||
break
|
||||
remains.append(row)
|
||||
continue
|
||||
|
||||
# except KeyError:
|
||||
# print('error')
|
||||
# print(row)
|
||||
# continue
|
||||
|
||||
if parent in childs:
|
||||
number = childs[parent] + 1
|
||||
childs[parent] = number
|
||||
|
||||
ADD_ITEM_QUERY = {
|
||||
"title": row["CAPTION"],
|
||||
"projectid": projectid,
|
||||
"otherid": row["ID"],
|
||||
"meta": row["CODE"],
|
||||
"childorder": number,
|
||||
"listtype": 0,
|
||||
"parent": parent,
|
||||
}
|
||||
result = requests.post(BASE_URL + 'list/' + ADD_ITEM_ROUTE, data=ADD_ITEM_QUERY, headers=HEADERS)
|
||||
|
||||
New_ID = json.loads(result.text)["data"][0]["id"]
|
||||
print(str(row["ID"]) + '=' + str(New_ID))
|
||||
IDS_DICT[str(row["ID"])] = {"id" : int(New_ID), 'title': row["CAPTION"]}
|
||||
|
||||
return remains
|
||||
|
||||
|
||||
def insertProjectItems(cursor, projectid):
|
||||
childs = {}
|
||||
IDS_DICT = {}
|
||||
|
||||
query = """select * from dbo.lwtopic"""
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
result = []
|
||||
while True:
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
HIERARCHY = row.HIERARCHY
|
||||
HIERARCHY = HIERARCHY.split(".")[-2]
|
||||
HIERARCHY = HIERARCHY.rjust(3, "0")
|
||||
|
||||
result.append(
|
||||
{
|
||||
"ID": int(row.ID),
|
||||
"CODE": row.CODE,
|
||||
"CAPTION": text_normal.normalize_qanon(row.CAPTION),
|
||||
"F_PARENTID": int(row.F_PARENTID) if row.F_PARENTID else 0,
|
||||
"HIERARCHY": HIERARCHY,
|
||||
}
|
||||
)
|
||||
|
||||
result = sorted(result, key=GET_H)
|
||||
|
||||
remains = insert(result, projectid, IDS_DICT, childs )
|
||||
# print(IDS_DICT)
|
||||
|
||||
count = 1
|
||||
while remains.__len__() > 0 and count < 2:
|
||||
print('##################' + str(count))
|
||||
print( remains.__len__() )
|
||||
remains = insert(remains, projectid, IDS_DICT, childs )
|
||||
# print(IDS_DICT)
|
||||
count = count + 1
|
||||
|
||||
with open("list_LWTopic.json", 'w') as file:
|
||||
file.write(json.dumps(IDS_DICT))
|
||||
|
||||
print('** write list_LWTopic.json ')
|
||||
@@ -0,0 +1,277 @@
|
||||
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 app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
|
||||
# cursor, cnxn = create_cursor()
|
||||
|
||||
def import_law_section_to_elastic(cursor) :
|
||||
|
||||
query = '''
|
||||
select
|
||||
s.ID as sectionId
|
||||
,isnull(s.CAPTION,'') as title -- عنوان بخش: مثلا ماده 5
|
||||
,isnull(s.F_PARENTID,0) as parentId
|
||||
,isnull(lss.CAPTION,'') as sectionStatus -- lwLawSectionStatus_table: ... منسوخه، معتبر، اصلاحی، موقت و
|
||||
,isnull(lss2.CAPTION,'') as qanon_etebar -- برای کل قانون نه جزء یا ماده خاص : ... منسوخه، معتبر، اصلاحی، موقت و
|
||||
,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره
|
||||
,isnull(s.SECTIONLEVEL,0) as sectionLevel -- نسبت به عنوان قانون نامرتب و دارای مقدار تکراری هم هست ؟؟؟
|
||||
,isnull(nestedLawType.CAPTION,'') as lawType
|
||||
--,isnull(nestedLawStatus.CAPTION,'') as lawStatus
|
||||
,isnull(s.TEXTORDER,0) as textOrder -- ترتیب نمایش مواد و تبصره ها
|
||||
,s.STATENO as stateNo -- ???
|
||||
,isnull(s.SECTIONTYPENO,0) as sectionTypeNumber -- دوهزار رکورد با مقدار صفر دارد اما مقادیر دیگری نیز پذیرفته است ؟؟؟
|
||||
-- بیش از پنج هزار رکورد با مقدار بالاتر از 1500 دارد که چنین مقادیری در جدول سکشن_تایپ وجود ندارد پس با این جدول رابطه ندارد
|
||||
,isnull(l.CAPTION,'') as lawTitle -- عنوان قانون
|
||||
,isnull(l.ID,0) as lawId -- شناسه قانون
|
||||
,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
|
||||
,isnull(l.EXPIREDATE,'') as expireDate -- تاریخ انقضا
|
||||
--,isnull(s.F_LWPHASEID,0) as phaseId -- شناسه فاز
|
||||
,s.FULLPATH as sectionFullPath -- عنوان ماده یا تبصره
|
||||
,isnull(s.SECTIONTYPENOTEXT,'') as sectionType -- ??? استفساریه، کنوانسیون، موافقت نامه، اساسنامه، تفسیر، دوم ، سوم ، چهارم، دوازدهم، خالی، 1، 2، 3، 4
|
||||
,isnull(s.FIRSTSATENO,0) as firstStateNo -- ??? بازه 0 تا 169
|
||||
,isnull(s.LASTSTATENO,0) as lastStateNo -- ??? بازه 0 تا 112
|
||||
,isnull(s.HIERARCHY,'') as hierarchy
|
||||
,isnull(s.DISPLAYINCONTENTS,0) as displayInContents -- ??? صد و پنجاه و سه رکورد دارای مقدار یک و بقیه یک میلیون رکورد مقدار 0 دارد
|
||||
,isnull(s.ISINTERPRETATION,0) as isInterpretation -- ??? چهارصد و پنجاه و سه رکورد با مقدار یک دارد و بقیه مقادیر نال است
|
||||
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_TOPICID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM lwsectiontopic where [F_SECTIONID]=s.id) as topics
|
||||
,l.[ISLAW] -- قانون
|
||||
,l.[ISREGULATION] -- مقرره
|
||||
,l.[ISCORRECTIONLETTER] -- اصلاحیه
|
||||
,(
|
||||
SELECT top (1) p3.CAPTION
|
||||
FROM [lwPhase] p1
|
||||
left join [lwApprover] p2 on p1.ID=p2.F_LWPHASEID
|
||||
left join cmOrganization p3 on p2.F_CMORGANIZATIONID = p3.id
|
||||
where l.ID = p1.F_LWLAWID
|
||||
order by p2.APPROVEDATE asc
|
||||
) as ts_ref -- مرجع تصویب
|
||||
,(
|
||||
SELECT cbt.CAPTION
|
||||
FROM lwLaw l2
|
||||
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
|
||||
where l.ID = l2.id
|
||||
) as regulationType
|
||||
|
||||
|
||||
from lwSection s
|
||||
left join lwLawSectionStatus lss on s.F_CMBASETABLEID_SECTIONSTATUS = lss.ID
|
||||
left join lwLaw l on s.F_LWLAWID = l.ID
|
||||
left join lwLawSectionStatus lss2 on lss2.id= l.[F_CMBASETABLEID_LASTSTATUS]
|
||||
left JOIN (
|
||||
SELECT l2.F_LWBASETABLEID_LAWTYPE,l2.ID,cbt.CAPTION
|
||||
FROM lwLaw l2
|
||||
left JOIN cmBasetable cbt ON l2.F_LWBASETABLEID_LAWTYPE = cbt.ID
|
||||
) AS nestedLawType ON s.F_LWLAWID = nestedLawType.ID
|
||||
left JOIN (
|
||||
SELECT l2.[F_LWBASETABLEID_REGULATIONTYPE],l2.ID,cbt.CAPTION
|
||||
FROM lwLaw l2
|
||||
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
|
||||
) AS nestedRegulationType ON s.F_LWLAWID = nestedRegulationType.ID
|
||||
|
||||
where l.ISLAW = 1
|
||||
order by s.F_LWLAWID,textOrder
|
||||
'''
|
||||
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
url = BASE_URL + "repo/majles/section/multi/add"
|
||||
dict_topic = json.loads(open("list_LWTopic.json").read())
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
i = 0
|
||||
while 1:
|
||||
# print(i)
|
||||
i=i+1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
# if i > 1000:
|
||||
# break
|
||||
# print(row.sectionId)
|
||||
|
||||
html = ''
|
||||
if isNeedHtml(row.sectionText) :
|
||||
html = row.sectionText
|
||||
|
||||
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)
|
||||
content_len = text.__len__()
|
||||
|
||||
qanon_title = text_normal.normalize_qanon( row.lawTitle )
|
||||
title_type = getTitleType(qanon_title)
|
||||
|
||||
eid='qs'+ str(row.sectionId)
|
||||
|
||||
parentId = '0'
|
||||
if row.parentId != 0 :
|
||||
parentId = 'qs'+ str(row.parentId)
|
||||
lawId='qq'+ str(row.lawId)
|
||||
|
||||
main_type = ''
|
||||
if(row.ISLAW == 1):
|
||||
main_type = 'قانون'
|
||||
elif(row.ISREGULATION == 1):
|
||||
main_type = 'مقرره'
|
||||
|
||||
sub_type = ''
|
||||
if(row.ISLAW == 1):
|
||||
sub_type = row.lawType
|
||||
elif(row.ISREGULATION == 1):
|
||||
sub_type = row.regulationType
|
||||
sub_type = normalYehKe(sub_type)
|
||||
|
||||
# other_type = 'اصلی'
|
||||
# if(row.ISCORRECTIONLETTER == 1):
|
||||
# other_type = 'اصلاحی'
|
||||
|
||||
|
||||
ts_year = ''
|
||||
if row.aproveDate :
|
||||
items = row.aproveDate.split("/")
|
||||
if items.__len__() > 0:
|
||||
ts_year = items[0]
|
||||
|
||||
|
||||
tt = time.time()
|
||||
tt = int( round(tt) * 1000)
|
||||
version_ifo = {
|
||||
"timestamp": tt,
|
||||
"operation": "create",
|
||||
"number" : 1
|
||||
}
|
||||
|
||||
other_info = {
|
||||
"level": row.sectionLevel,
|
||||
"full_path": normalYehKe( row.sectionFullPath ),
|
||||
"number_text":row.sectionType ,
|
||||
"hierarchy" : row.hierarchy
|
||||
}
|
||||
|
||||
topics = []
|
||||
if row.topics:
|
||||
topic_ids = row.topics.split(",")
|
||||
topic_list = list(set(topic_ids))
|
||||
for item in topic_ids:
|
||||
if str(item) in dict_topic:
|
||||
topics.append(
|
||||
{'id': dict_topic[str(item)]['id'], 'title': normalYehKe(dict_topic[str(item)]['title'])}
|
||||
)
|
||||
|
||||
ts_ref = normalYehKe(row.ts_ref)
|
||||
|
||||
if ts_ref == 'مقام معظم رهبری ( فرماندهی کل قوا )' :
|
||||
ts_ref = 'مقام معظم رهبری'
|
||||
|
||||
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 # خطا یا خالی
|
||||
|
||||
expire_date = row.expireDate.strip()
|
||||
|
||||
# state_etebar = normalYehKe(row.lawStatus)
|
||||
state_etebar = normalYehKe(row.sectionStatus)
|
||||
|
||||
qanon_etebar = ''
|
||||
if row.qanon_etebar :
|
||||
qanon_etebar = normalYehKe(row.qanon_etebar)
|
||||
|
||||
|
||||
|
||||
data={
|
||||
'id':eid,
|
||||
'ref_id':row.sectionId,
|
||||
'ref_key':'m_qavanin',
|
||||
'main_type': main_type,
|
||||
'sub_type': sub_type,
|
||||
'content': text,
|
||||
'html' : html,
|
||||
# 'version_info': version_ifo,
|
||||
'qanon_title': qanon_title,
|
||||
'title_type': title_type,
|
||||
'expire_date': expire_date,
|
||||
'ts_date': row.aproveDate,
|
||||
'ts_year': ts_year,
|
||||
'ts_ref': ts_ref,
|
||||
'state_etebar': state_etebar,
|
||||
'qanon_id': lawId,
|
||||
'parent_id': parentId,
|
||||
'child_order': row.textOrder,
|
||||
'other_info': other_info,
|
||||
'content_len': content_len,
|
||||
'topics': topics,
|
||||
'qanon_etebar' : qanon_etebar,
|
||||
# 'ref_state' : ref_state,
|
||||
#'categories': row.oooo,
|
||||
#'tags': row.oooo,
|
||||
#'keywords': row.oooo,
|
||||
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
|
||||
}
|
||||
|
||||
if len(bulk_data) >= 200:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid , ' , lawid_current =' + lawId , ', lawid_first=' + bulk_data[0]['qanon_id'])
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
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 , ' , lawid_current =' + lawId , ', lawid_first=' + bulk_data[0]['qanon_id'])
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
|
||||
|
||||
print('end success import_law_section_to_elastic')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
@@ -0,0 +1,199 @@
|
||||
import json
|
||||
import requests
|
||||
import pyodbc
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import re
|
||||
import datetime
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
def import_opinion_to_elastic(cursor) :
|
||||
query = """
|
||||
SELECT
|
||||
isnull(o.[ID],0) as ref_id
|
||||
,isnull(l.CAPTION,'') as title
|
||||
,isnull([SUBJECT],'') as title_popular
|
||||
,isnull([OPINIONDATE],'') as ts_date
|
||||
,isnull(l.APPROVEDATE,'') as ts_date2
|
||||
,isnull(op_r.CAPTION,'') as sub_type
|
||||
,isnull(op_r.[F_CMBASETABLEID_OPINIONGROUP],0) as mainType -- 1419 : رای 1418:نظر
|
||||
--,isnull(F_OPOPINIONGIVERID,0) as ts_ref -- ts_ref
|
||||
--,isnull(bt.CAPTION,'') as classification -- عادی، ندارد مهم نیست
|
||||
,isnull(o.[F_LWLAWID],0) as qanon_id
|
||||
,isnull([DISTRIBUTENO],'') as eblagh_number -- ???????? شماره ابلاغ؟
|
||||
,isnull([DISTRIBUTEDATE],'') as eblagh_date -- ???????? تاریخ ابلاغ
|
||||
,isnull(d.DOCTEXT,'') as content -- !!!!!!!!!!!!!!!!!!!!!! داده های این فیلد حجم زیادی دارد
|
||||
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),[F_LWTOPICID]), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM opOpinionTopic where [F_OPOPINIONID]=o.id) as topics
|
||||
FROM [Qavanin].[dbo].[opOpinion] o
|
||||
left join opOpiniongiver op_r on o.F_OPOPINIONGIVERID = op_r.id
|
||||
left join [cmBasetable] bt on o.F_CMBASETABLEID_CLASSIFICATION = bt.ID
|
||||
left join lwLaw l on o.F_LWLAWID = l.ID
|
||||
left join prDoc d on o.F_PRDOCID = d.ID
|
||||
|
||||
"""
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
url = BASE_URL + "repo/majles/opinion/multi/add" # POST /repo/majles/opinion/multi/add
|
||||
dict_topic = json.loads(open("list_LWTopic.json").read())
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
|
||||
t1 = datetime.datetime.now()
|
||||
print(t1)
|
||||
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.content, "html.parser")
|
||||
text = soup.get_text("\n", strip=True)
|
||||
except Exception as e:
|
||||
text = row.content
|
||||
text = text_normal.normalize_qanon(text)
|
||||
content_len = text.__len__()
|
||||
|
||||
title = text_normal.normalize_qanon(row.title)
|
||||
|
||||
eid = "qo" + str(row.ref_id)
|
||||
|
||||
qanon_id = "qq" + str(row.qanon_id)
|
||||
|
||||
main_type = ""
|
||||
if row.mainType == 1418:
|
||||
main_type = "نظر"
|
||||
elif row.mainType == 1419:
|
||||
main_type = "رای"
|
||||
|
||||
ts_date = row.ts_date
|
||||
ts_date = ts_date.strip()
|
||||
if not ts_date :
|
||||
ts_date = row.ts_date2
|
||||
ts_date = ts_date.strip()
|
||||
|
||||
ts_year = ""
|
||||
if ts_date:
|
||||
items = ts_date.split("/")
|
||||
if items.__len__() > 1:
|
||||
ts_year = int(items[0].strip())
|
||||
|
||||
version_ifo = {
|
||||
"timestamp": datetime.datetime.now().timestamp(),
|
||||
"operation": "create",
|
||||
"number": 1,
|
||||
}
|
||||
|
||||
topics = []
|
||||
if row.topics:
|
||||
topic_ids = row.topics.split(",")
|
||||
topic_list = list(set(topic_ids))
|
||||
for item in topic_ids:
|
||||
if str(item) in dict_topic:
|
||||
topics.append(
|
||||
{
|
||||
"id": dict_topic[str(item)]["id"],
|
||||
"title": normalYehKe(dict_topic[str(item)]["title"]),
|
||||
}
|
||||
)
|
||||
|
||||
ts_ref = normalYehKe(row.sub_type)
|
||||
ts_ref = ts_ref.replace("رای وحدت رویه", "")
|
||||
ts_ref = ts_ref.replace("رای", "")
|
||||
ts_ref = ts_ref.replace("نظر", "")
|
||||
ts_ref = ts_ref.replace("- اصول 85 و 138", "")
|
||||
ts_ref = ts_ref.strip()
|
||||
|
||||
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
|
||||
try:
|
||||
sort_date_timestamp = getSortTimestamp(ts_date)
|
||||
except Exception as e:
|
||||
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
|
||||
|
||||
sub_type = normalYehKe(row.sub_type)
|
||||
title_popular = normalYehKe(row.title_popular)
|
||||
eblagh_number = normalYehKe(row.eblagh_number)
|
||||
eblagh_date = normalYehKe(row.eblagh_date)
|
||||
|
||||
# print(len(text.split()))
|
||||
# normalized_section_content, recognized_dates, recognized_numbers = normalizerDate2(text.strip())
|
||||
# print(len(normalized_section_content.split()))
|
||||
# recognized_numbers = find_number_indexes_in_string(normalized_section_content,recognized_numbers)
|
||||
# normalized_section_content = normalized_section_content.strip()
|
||||
# founded_patterns_array = regex_patterns_finder(normalized_section_content)
|
||||
|
||||
data = {
|
||||
"id": eid,
|
||||
"title": title,
|
||||
"ref_id": row.ref_id,
|
||||
"ref_key": "m_qavanin",
|
||||
"main_type": main_type,
|
||||
"sub_type": sub_type,
|
||||
"html": row.content,
|
||||
"content": text,
|
||||
# "version_info": version_ifo,
|
||||
"ts_date": ts_date,
|
||||
"ts_year": ts_year,
|
||||
"ts_ref": ts_ref,
|
||||
"qanon_id": qanon_id,
|
||||
"eblagh_number": eblagh_number,
|
||||
"eblagh_date": eblagh_date,
|
||||
"content_len": content_len,
|
||||
"title_popular": title_popular,
|
||||
"sort_date_timestamp": sort_date_timestamp,
|
||||
}
|
||||
|
||||
if len(bulk_data) >= 100:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, 'opinion_to_elastic , total='+str(total_count) , str(i)+ ', id=' + eid )
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' opinion_to_elastic , total='+str(total_count) )
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
|
||||
print("end success import_opinion_to_elastic")
|
||||
t2 = datetime.datetime.now()
|
||||
print(t2 - t1)
|
||||
@@ -0,0 +1,275 @@
|
||||
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
|
||||
import sys
|
||||
import traceback
|
||||
import re
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
def import_regulation_section_to_elastic(cursor):
|
||||
query = '''
|
||||
select
|
||||
s.ID as sectionId
|
||||
,isnull(s.CAPTION,'') as title -- عنوان بخش: مثلا ماده 5
|
||||
,isnull(s.F_PARENTID,0) as parentId
|
||||
,isnull(lss.CAPTION,'') as sectionStatus -- lwLawSectionStatus_table: ... منسوخه، معتبر، اصلاحی، موقت و
|
||||
,isnull(lss2.CAPTION,'') as qanon_etebar -- برای کل قانون نه جزء یا ماده خاص : ... منسوخه، معتبر، اصلاحی، موقت و
|
||||
,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره
|
||||
,isnull(s.SECTIONLEVEL,0) as sectionLevel -- نسبت به عنوان قانون نامرتب و دارای مقدار تکراری هم هست ؟؟؟
|
||||
,isnull(nestedLawType.CAPTION,'') as lawType
|
||||
--,isnull(nestedLawStatus.CAPTION,'') as lawStatus
|
||||
,isnull(s.TEXTORDER,0) as textOrder -- ترتیب نمایش مواد و تبصره ها
|
||||
,s.STATENO as stateNo -- ???
|
||||
,isnull(s.SECTIONTYPENO,0) as sectionTypeNumber -- دوهزار رکورد با مقدار صفر دارد اما مقادیر دیگری نیز پذیرفته است ؟؟؟
|
||||
-- بیش از پنج هزار رکورد با مقدار بالاتر از 1500 دارد که چنین مقادیری در جدول سکشن_تایپ وجود ندارد پس با این جدول رابطه ندارد
|
||||
,isnull(l.CAPTION,'') as lawTitle -- عنوان قانون
|
||||
,isnull(l.ID,0) as lawId -- شناسه قانون
|
||||
,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
|
||||
,isnull(l.EXPIREDATE,'') as expireDate -- تاریخ انقضا
|
||||
--,isnull(s.F_LWPHASEID,0) as phaseId -- شناسه فاز
|
||||
,s.FULLPATH as sectionFullPath -- عنوان ماده یا تبصره
|
||||
,isnull(s.SECTIONTYPENOTEXT,'') as sectionType -- ??? استفساریه، کنوانسیون، موافقت نامه، اساسنامه، تفسیر، دوم ، سوم ، چهارم، دوازدهم، خالی، 1، 2، 3، 4
|
||||
,isnull(s.FIRSTSATENO,0) as firstStateNo -- ??? بازه 0 تا 169
|
||||
,isnull(s.LASTSTATENO,0) as lastStateNo -- ??? بازه 0 تا 112
|
||||
,isnull(s.HIERARCHY,'') as hierarchy
|
||||
,isnull(s.DISPLAYINCONTENTS,0) as displayInContents -- ??? صد و پنجاه و سه رکورد دارای مقدار یک و بقیه یک میلیون رکورد مقدار 0 دارد
|
||||
,isnull(s.ISINTERPRETATION,0) as isInterpretation -- ??? چهارصد و پنجاه و سه رکورد با مقدار یک دارد و بقیه مقادیر نال است
|
||||
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_TOPICID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM lwsectiontopic where [F_SECTIONID]=s.id) as topics
|
||||
,l.[ISLAW] -- قانون
|
||||
,l.[ISREGULATION] -- مقرره
|
||||
,l.[ISCORRECTIONLETTER] -- اصلاحیه
|
||||
,(
|
||||
SELECT top (1) p3.CAPTION
|
||||
FROM [lwPhase] p1
|
||||
left join [lwApprover] p2 on p1.ID=p2.F_LWPHASEID
|
||||
left join cmOrganization p3 on p2.F_CMORGANIZATIONID = p3.id
|
||||
where l.ID = p1.F_LWLAWID
|
||||
order by p2.APPROVEDATE asc
|
||||
) as ts_ref -- مرجع تصویب
|
||||
,(
|
||||
SELECT cbt.CAPTION
|
||||
FROM lwLaw l2
|
||||
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
|
||||
where l.ID = l2.id
|
||||
) as regulationType
|
||||
|
||||
|
||||
from lwSection s
|
||||
left join lwLawSectionStatus lss on s.F_CMBASETABLEID_SECTIONSTATUS = lss.ID
|
||||
left join lwLaw l on s.F_LWLAWID = l.ID
|
||||
left join lwLawSectionStatus lss2 on lss2.id= l.[F_CMBASETABLEID_LASTSTATUS]
|
||||
left JOIN (
|
||||
SELECT l2.F_LWBASETABLEID_LAWTYPE,l2.ID,cbt.CAPTION
|
||||
FROM lwLaw l2
|
||||
left JOIN cmBasetable cbt ON l2.F_LWBASETABLEID_LAWTYPE = cbt.ID
|
||||
) AS nestedLawType ON s.F_LWLAWID = nestedLawType.ID
|
||||
left JOIN (
|
||||
SELECT l2.[F_LWBASETABLEID_REGULATIONTYPE],l2.ID,cbt.CAPTION
|
||||
FROM lwLaw l2
|
||||
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
|
||||
) AS nestedRegulationType ON s.F_LWLAWID = nestedRegulationType.ID
|
||||
|
||||
where l.[ISREGULATION] = 1
|
||||
order by s.F_LWLAWID,textOrder
|
||||
'''
|
||||
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
url = BASE_URL + "repo/majles/rgsection/multi/add"
|
||||
dict_topic = json.loads(open("list_LWTopic.json").read())
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
i = 0
|
||||
while 1:
|
||||
# print(i)
|
||||
i=i+1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
# if i > 1000:
|
||||
# break
|
||||
# print(row.sectionId)
|
||||
|
||||
html = ''
|
||||
if isNeedHtml(row.sectionText) :
|
||||
html = row.sectionText
|
||||
|
||||
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)
|
||||
content_len = text.__len__()
|
||||
|
||||
qanon_title = text_normal.normalize_qanon( row.lawTitle )
|
||||
title_type = getTitleType(qanon_title)
|
||||
|
||||
eid='qs'+ str(row.sectionId)
|
||||
|
||||
parentId = '0'
|
||||
if row.parentId != 0 :
|
||||
parentId = 'qs'+ str(row.parentId)
|
||||
lawId='qq'+ str(row.lawId)
|
||||
|
||||
main_type = ''
|
||||
if(row.ISLAW == 1):
|
||||
main_type = 'قانون'
|
||||
elif(row.ISREGULATION == 1):
|
||||
main_type = 'مقرره'
|
||||
|
||||
sub_type = ''
|
||||
if(row.ISLAW == 1):
|
||||
sub_type = row.lawType
|
||||
elif(row.ISREGULATION == 1):
|
||||
sub_type = row.regulationType
|
||||
sub_type = normalYehKe(sub_type)
|
||||
|
||||
# other_type = 'اصلی'
|
||||
# if(row.ISCORRECTIONLETTER == 1):
|
||||
# other_type = 'اصلاحی'
|
||||
|
||||
|
||||
ts_year = ''
|
||||
if row.aproveDate :
|
||||
items = row.aproveDate.split("/")
|
||||
if items.__len__() > 0:
|
||||
ts_year = items[0]
|
||||
|
||||
|
||||
tt = time.time()
|
||||
tt = int( round(tt) * 1000)
|
||||
version_ifo = {
|
||||
"timestamp": tt,
|
||||
"operation": "create",
|
||||
"number" : 1
|
||||
}
|
||||
|
||||
other_info = {
|
||||
"level": row.sectionLevel,
|
||||
"full_path": normalYehKe( row.sectionFullPath ),
|
||||
"number_text":row.sectionType ,
|
||||
"hierarchy" : row.hierarchy
|
||||
}
|
||||
|
||||
topics = []
|
||||
if row.topics:
|
||||
topic_ids = row.topics.split(",")
|
||||
topic_list = list(set(topic_ids))
|
||||
for item in topic_ids:
|
||||
if str(item) in dict_topic:
|
||||
topics.append(
|
||||
{'id': dict_topic[str(item)]['id'], 'title': normalYehKe(dict_topic[str(item)]['title'])}
|
||||
)
|
||||
|
||||
ts_ref = ''
|
||||
if(row.ts_ref):
|
||||
ts_ref = normalYehKe(row.ts_ref)
|
||||
|
||||
|
||||
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 # خطا یا خالی
|
||||
|
||||
expire_date = row.expireDate.strip()
|
||||
|
||||
# state_etebar = normalYehKe(row.lawStatus)
|
||||
state_etebar = normalYehKe(row.sectionStatus)
|
||||
qanon_etebar = ''
|
||||
if row.qanon_etebar :
|
||||
qanon_etebar = normalYehKe(row.qanon_etebar)
|
||||
|
||||
|
||||
|
||||
data={
|
||||
'id':eid,
|
||||
'ref_id':row.sectionId,
|
||||
'ref_key':'m_qavanin',
|
||||
'main_type': main_type,
|
||||
'sub_type': sub_type,
|
||||
'content': text,
|
||||
'html' : html,
|
||||
# 'version_info': version_ifo,
|
||||
'qanon_title': qanon_title,
|
||||
'title_type': title_type,
|
||||
'expire_date': expire_date,
|
||||
'ts_date': row.aproveDate,
|
||||
'ts_year': ts_year,
|
||||
'ts_ref': ts_ref,
|
||||
'state_etebar': state_etebar,
|
||||
'qanon_id': lawId,
|
||||
'parent_id': parentId,
|
||||
'child_order': row.textOrder,
|
||||
'other_info': other_info,
|
||||
'content_len': content_len,
|
||||
'topics': topics,
|
||||
'qanon_etebar' : qanon_etebar,
|
||||
#'categories': row.oooo,
|
||||
#'tags': row.oooo,
|
||||
#'keywords': row.oooo,
|
||||
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
|
||||
}
|
||||
|
||||
if len(bulk_data) >= 200:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' regulation_section , total='+str(total_count) , str(i)+ ', id=' + eid , ' , lawid_current =' + lawId , ', lawid_first=' + bulk_data[0]['qanon_id'])
|
||||
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' regulation_section , total='+str(total_count) , str(i)+ ', id=' + eid , ' , lawid_current =' + lawId , ', lawid_first=' + bulk_data[0]['qanon_id'])
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
|
||||
print('end success import_regulation_section_to_elastic')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
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 sys
|
||||
import traceback
|
||||
import re
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
# ضرورتا
|
||||
# این برنامه ضرورت دارد اجرا شود
|
||||
|
||||
def import_law_section_update_ref_state(cursor):
|
||||
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()
|
||||
|
||||
|
||||
url = BASE_URL + "repo/majles/section/multi/update"
|
||||
dict_topic = json.loads(open("list_LWTopic.json").read())
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
previd = ''
|
||||
prev_effect_type = ''
|
||||
prev_efect_section_id = ''
|
||||
ref_state_array = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
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
|
||||
|
||||
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,
|
||||
'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('=' * 10, ' law_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
|
||||
|
||||
|
||||
if ref_state_array.__len__() > 0 :
|
||||
data={
|
||||
'id' : previd,
|
||||
'ref_state' : ref_state_array
|
||||
}
|
||||
bulk_data.append(data)
|
||||
# print(bulk_data)
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' law_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
# print(response.text)
|
||||
|
||||
print('end success import_law_section_update_ref_state')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
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 sys
|
||||
import traceback
|
||||
import re
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
|
||||
# ضرورتا
|
||||
# این برنامه ضرورت دارد اجرا شود
|
||||
|
||||
|
||||
def import_regulation_section_update_ref_state(cursor):
|
||||
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.[ISREGULATION] = 1
|
||||
and gl1.[F_LWSECTIONID_EFFECTED] is not null
|
||||
|
||||
order by gl1.[F_LWSECTIONID_EFFECTED], gl4.APPROVEDATE
|
||||
|
||||
'''
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
|
||||
url = BASE_URL + "repo/majles/rgsection/multi/update"
|
||||
dict_topic = json.loads(open("list_LWTopic.json").read())
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
previd = ''
|
||||
prev_effect_type = ''
|
||||
prev_efect_section_id = ''
|
||||
ref_state_array = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
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
|
||||
|
||||
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,
|
||||
'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('=' * 10, ' regulation_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
|
||||
|
||||
if ref_state_array.__len__() > 0 :
|
||||
data={
|
||||
'id' : previd,
|
||||
'ref_state' : ref_state_array
|
||||
}
|
||||
bulk_data.append(data)
|
||||
# print(bulk_data)
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' regulation_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
# print(response.text)
|
||||
|
||||
print('end success import_regulation_section_update_ref_state')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import json
|
||||
import requests
|
||||
import pyodbc
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
def import_law_reg_qanon_to_elastic(cursor):
|
||||
|
||||
query = '''
|
||||
SELECT
|
||||
l1.[ID] as Id
|
||||
,l1.[CAPTION] as title
|
||||
--,[F_LWBASETABLEID_LAWTYPE]
|
||||
,l1.[ISLAW] -- قانون
|
||||
,l1.[ISREGULATION] -- مقرره
|
||||
,isnull(l1.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
|
||||
,isnull(l1.EXPIREDATE,'') as expireDate -- تاریخ انقضا
|
||||
--,[F_LWBASETABLEID_CLASSIFICATION]
|
||||
,[RULENO]
|
||||
,[LAWNO]
|
||||
--,[F_CMBASETABLEID_LASTSTATUS]
|
||||
,lss.CAPTION as qanon_etebar
|
||||
,cbt.CAPTION as lawType
|
||||
,(
|
||||
SELECT top (1) p3.CAPTION
|
||||
FROM [lwPhase] p1
|
||||
left join [lwApprover] p2 on p1.ID=p2.F_LWPHASEID
|
||||
left join cmOrganization p3 on p2.F_CMORGANIZATIONID = p3.id
|
||||
where l1.ID = p1.F_LWLAWID
|
||||
order by p2.APPROVEDATE asc
|
||||
) as ts_ref -- مرجع تصویب
|
||||
,(
|
||||
SELECT cbt.CAPTION
|
||||
FROM lwLaw l2
|
||||
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
|
||||
where l1.ID = l2.id
|
||||
) as regulationType
|
||||
|
||||
FROM [Qavanin].[dbo].[lwLaw] l1
|
||||
left JOIN cmBasetable cbt ON l1.F_LWBASETABLEID_LAWTYPE = cbt.ID
|
||||
left join lwLawSectionStatus lss on lss.id= l1.[F_CMBASETABLEID_LASTSTATUS]
|
||||
|
||||
where ( l1.ISLAW = 1 or l1.ISREGULATION = 1 )
|
||||
'''
|
||||
|
||||
|
||||
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
|
||||
url = BASE_URL + "repo/majles/qaqanon/multi/add"
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print(t1)
|
||||
i = 0
|
||||
while 1:
|
||||
# print(i)
|
||||
i=i+1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
# if i > 1000:
|
||||
# break
|
||||
# print(row.sectionId)
|
||||
|
||||
|
||||
title = text_normal.normalize_qanon( row.title )
|
||||
title_type = getTitleType(title)
|
||||
|
||||
eid='qq'+ str(row.Id)
|
||||
|
||||
main_type = ''
|
||||
if(row.ISLAW == 1):
|
||||
main_type = 'قانون'
|
||||
elif(row.ISREGULATION == 1):
|
||||
main_type = 'مقرره'
|
||||
|
||||
sub_type = ''
|
||||
if(row.ISLAW == 1):
|
||||
sub_type = row.lawType
|
||||
elif(row.ISREGULATION == 1):
|
||||
sub_type = row.regulationType
|
||||
sub_type = normalYehKe(sub_type)
|
||||
|
||||
qanon_number = ''
|
||||
if(row.ISLAW == 1):
|
||||
qanon_number = row.LAWNO
|
||||
elif(row.ISREGULATION == 1):
|
||||
qanon_number = row.RULENO
|
||||
|
||||
# other_type = 'اصلی' اصلاحی....
|
||||
# action_type ...
|
||||
|
||||
|
||||
|
||||
ts_year = ''
|
||||
if row.aproveDate :
|
||||
items = row.aproveDate.split("/")
|
||||
if items.__len__() > 0:
|
||||
ts_year = items[0]
|
||||
|
||||
ts_ref = normalYehKe(row.ts_ref)
|
||||
|
||||
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 # خطا یا خالی
|
||||
|
||||
expire_date = row.expireDate.strip()
|
||||
|
||||
qanon_etebar = ''
|
||||
if row.qanon_etebar :
|
||||
qanon_etebar = normalYehKe(row.qanon_etebar)
|
||||
|
||||
|
||||
data={
|
||||
'id':eid,
|
||||
'ref_id':row.Id,
|
||||
'main_type': main_type,
|
||||
'sub_type': sub_type,
|
||||
'title': title,
|
||||
'title_type': title_type,
|
||||
'expire_date': expire_date,
|
||||
'ts_date': row.aproveDate,
|
||||
'ts_year': ts_year,
|
||||
'ts_ref': ts_ref,
|
||||
'qanon_etebar' : qanon_etebar,
|
||||
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
|
||||
}
|
||||
|
||||
if len(bulk_data) >= 100:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' law_reg_qanon_to_elastic , total='+str(total_count) , str(i)+ ', id=' + eid )
|
||||
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
|
||||
|
||||
if len(bulk_data) > 0:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' law_reg_qanon_to_elastic , total='+str(total_count) , str(i)+ ', id=' + eid )
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
|
||||
print('end success law_reg_qanon_to_elastic ')
|
||||
t2= datetime.datetime.now()
|
||||
print(t2-t1)
|
||||
@@ -0,0 +1,215 @@
|
||||
import json
|
||||
import requests
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
|
||||
def import_relations_qanon_lwreg(cursor):
|
||||
# اجرای کوئری SQL و خواندن دادهها به یک DataFrame
|
||||
query = """
|
||||
SELECT
|
||||
l1.F_LWLAWID_LAW as id
|
||||
, l1.F_LWSECTIONID as section_id
|
||||
--, l2.CAPTION as from_title
|
||||
-- ,(select top(1) tt1.id from lwSection tt1 where tt1.F_LWLAWID=l1.F_LWLAWID_LAW and tt1.FULLPATH = 'عنوان') as section_id2
|
||||
, l3.[FULLPATH] as from_section_title
|
||||
, l1.ISREFERENCE
|
||||
, l1.F_LWLAWID_REGULATION as to_id
|
||||
, l4.CAPTION as to_title
|
||||
, 'مقرره' as to_type
|
||||
|
||||
|
||||
FROM [Qavanin].[dbo].[lwLawRegulation] l1
|
||||
left join lwLaw l2 on l1.F_LWLAWID_LAW=l2.id
|
||||
left join lwsection l3 on l1.F_LWSECTIONID=l3.id
|
||||
left join lwLaw l4 on l1.F_LWLAWID_REGULATION=l4.id
|
||||
|
||||
order by l1.F_lwlawid_law, l1.F_LWLAWID_REGULATION , l1.F_LWSECTIONID
|
||||
|
||||
"""
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
url = BASE_URL + "repo/majles/qaqanon/multi/update"
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
previd = ''
|
||||
ref_state_array = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print("start time: " + str(t1))
|
||||
i = 0
|
||||
all_data = []
|
||||
repeat_data = []
|
||||
|
||||
relations = []
|
||||
prev_eid = ''
|
||||
prev_sectionid = ''
|
||||
prev_to_id = ''
|
||||
|
||||
|
||||
# rows = cursor.fetchall()
|
||||
# for row in rows:
|
||||
|
||||
while 1:
|
||||
|
||||
i += 1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
eid='qq'+ str(row.id)
|
||||
to_id = 'qq'+ str(row.to_id)
|
||||
|
||||
sectionid = str(row.section_id)
|
||||
if sectionid != 'None' :
|
||||
sectionid = 'qs'+ str(row.section_id)
|
||||
else :
|
||||
sectionid = ''
|
||||
|
||||
if (i%100) == 0 :
|
||||
print('^' * 10, ' id=', eid, ' i=',i)
|
||||
|
||||
# ارتباط با خودش بی معنی است
|
||||
# چند مورد در دیتابیس بود
|
||||
if row.id == row.to_id :
|
||||
continue
|
||||
|
||||
if eid == prev_eid and to_id == prev_to_id :
|
||||
if prev_sectionid == sectionid :
|
||||
continue
|
||||
|
||||
prev_to_id = to_id
|
||||
prev_sectionid = sectionid
|
||||
|
||||
rel_type = 'عادی'
|
||||
if int(row.ISREFERENCE) == 1:
|
||||
rel_type = 'استناد'
|
||||
|
||||
from_type = "کل قانون"
|
||||
if row.section_id :
|
||||
from_type = "جزء قانون"
|
||||
|
||||
from_section_title = ''
|
||||
if row.from_section_title :
|
||||
from_section_title = text_normal.normalize_qanon(row.from_section_title)
|
||||
|
||||
to_title = text_normal.normalize_qanon( row.to_title )
|
||||
to_type = row.to_type
|
||||
|
||||
|
||||
relation = {
|
||||
"from_type": from_type,
|
||||
"from_section_id" : sectionid,
|
||||
"from_section_title" : from_section_title,
|
||||
"rel_type" : rel_type,
|
||||
"to_type" : to_type,
|
||||
"to_id" : to_id ,
|
||||
"to_title" : to_title,
|
||||
"wait" : 1,
|
||||
"rel_key" : 'qavanin',
|
||||
}
|
||||
|
||||
#print('%'*20, 'eid= ', eid, ' , ... prev_eid= ', prev_eid)
|
||||
#print('--------- relations' , len(relations) )
|
||||
#print(relation )
|
||||
|
||||
if prev_eid == '':
|
||||
prev_eid = eid
|
||||
continue
|
||||
elif prev_eid == eid :
|
||||
relations.append(relation)
|
||||
continue
|
||||
else :
|
||||
data={
|
||||
'id' : prev_eid,
|
||||
'qanon_relations' : relations
|
||||
}
|
||||
|
||||
total_count = total_count+1
|
||||
# if total_count < 2560 :
|
||||
# continue
|
||||
|
||||
bulk_data.append(data)
|
||||
|
||||
prev_eid = eid
|
||||
relations=[]
|
||||
relations.append(relation)
|
||||
|
||||
|
||||
if len(bulk_data) >= 10:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' relations_qanon_lwreg , total='+str(total_count) , str(i)+ ', id=' + eid )
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
|
||||
|
||||
if len(relations) :
|
||||
data={
|
||||
'id' : prev_eid,
|
||||
'qanon_relations' : relations
|
||||
}
|
||||
bulk_data.append(data)
|
||||
|
||||
|
||||
while len(bulk_data) > 0 :
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' relations_qanon_lwreg , total='+str(total_count))
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
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()
|
||||
print("finished time: " + str(t2))
|
||||
print("process time: " + str(t2-t1))
|
||||
print(' end success relations_qanon_lwreg ')
|
||||
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import json
|
||||
import requests
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from html import escape
|
||||
import json
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
def import_relations_qanon_opinion(cursor):
|
||||
# اجرای کوئری SQL و خواندن دادهها به یک DataFrame
|
||||
query = """
|
||||
SELECT
|
||||
l1.[F_LWLAWID] as id
|
||||
,[F_LWSECTIONID] as section_id
|
||||
, ls.[FULLPATH] as from_section_title
|
||||
,[ISRELATED]
|
||||
--,[F_CMBASETABLEID_OPBASEDOCTYPE]
|
||||
--,l4.CAPTION
|
||||
,[F_OPOPINIONID] as to_id
|
||||
,og.CAPTION as to_type
|
||||
,l3.CAPTION as to_title
|
||||
|
||||
FROM [Qavanin].[dbo].[opOpinionLaw] l1
|
||||
left join [opOpinion] l2 on l1.[F_OPOPINIONID] = l2.id
|
||||
left join opOpiniongiver og on l2.F_OPOPINIONGIVERID = og.id
|
||||
left join lwLaw l3 on l2.[F_LWLAWID] = l3.id
|
||||
left join lwsection ls on l1.F_LWSECTIONID=ls.id
|
||||
|
||||
--left join lwLaw l4 on l1.[F_LWLAWID] = l4.id
|
||||
|
||||
order by l1.[F_LWLAWID], [F_OPOPINIONID], [F_LWSECTIONID]
|
||||
|
||||
"""
|
||||
|
||||
cursor.execute(query)
|
||||
text_normal = TextNormalizer()
|
||||
|
||||
url = BASE_URL + "repo/majles/qaqanon/multi/update"
|
||||
|
||||
headers = HEADERS
|
||||
|
||||
|
||||
total_count = 0
|
||||
bulk_data = []
|
||||
previd = ''
|
||||
ref_state_array = []
|
||||
|
||||
t1= datetime.datetime.now()
|
||||
print("start time: " + str(t1))
|
||||
i = 0
|
||||
all_data = []
|
||||
repeat_data = []
|
||||
|
||||
relations = []
|
||||
prev_eid = ''
|
||||
prev_section_id = ''
|
||||
prev_to_id = ''
|
||||
|
||||
while 1:
|
||||
|
||||
i += 1
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
break
|
||||
|
||||
eid='qq'+ str(row.id)
|
||||
to_id = 'qo'+ str(row.to_id)
|
||||
|
||||
section_id = str(row.section_id)
|
||||
if section_id != 'None' :
|
||||
section_id = 'qs'+ str(row.section_id)
|
||||
else :
|
||||
section_id = ''
|
||||
|
||||
|
||||
if eid == prev_eid and to_id == prev_to_id :
|
||||
if prev_section_id == section_id :
|
||||
continue
|
||||
|
||||
prev_to_id = to_id
|
||||
prev_section_id = section_id
|
||||
|
||||
rel_type = 'عادی'
|
||||
if int(row.ISRELATED) == 1:
|
||||
rel_type = 'استناد'
|
||||
|
||||
from_type = "کل قانون"
|
||||
if section_id :
|
||||
from_type = "جزء قانون"
|
||||
|
||||
from_section_title = ''
|
||||
if row.from_section_title :
|
||||
from_section_title = text_normal.normalize_qanon(row.from_section_title)
|
||||
|
||||
to_title = text_normal.normalize_qanon( row.to_title )
|
||||
|
||||
|
||||
to_type = ''
|
||||
if row.to_type :
|
||||
to_type = row.to_type.strip()
|
||||
|
||||
if to_type == 'راي هيات عمومي ديوان عدالت اداري' :
|
||||
to_type = 'رای دیوان عدالت اداری'
|
||||
if to_type == 'راي وحدت رويه ديوان عالي كشور' :
|
||||
to_type = 'رای وحدت رویه'
|
||||
if to_type == 'اداره کل حقوقی قوه قضائیه' :
|
||||
to_type = 'نشست قضایی'
|
||||
if to_type == 'نظر رياست مجلس - اصول 85 و 138' :
|
||||
to_type = 'نظر ریاست مجلس'
|
||||
|
||||
relation = {
|
||||
"from_type": from_type,
|
||||
"from_section_id" : section_id,
|
||||
"from_section_title" : from_section_title,
|
||||
"rel_type" : rel_type,
|
||||
"to_type" : to_type,
|
||||
"to_id" : to_id ,
|
||||
"to_title" : to_title,
|
||||
"wait" : 1,
|
||||
"rel_key" : 'qavanin',
|
||||
}
|
||||
|
||||
#print('%'*20, 'eid= ', eid, ' , ... prev_eid= ', prev_eid)
|
||||
#print('--------- relations' , len(relations) )
|
||||
#print(relation )
|
||||
if (i%100) == 0 :
|
||||
print('^' * 10, ' id=', eid, ' i=',i)
|
||||
|
||||
if prev_eid == '':
|
||||
prev_eid = eid
|
||||
continue
|
||||
elif prev_eid == eid :
|
||||
relations.append(relation)
|
||||
continue
|
||||
else :
|
||||
data={
|
||||
'id' : prev_eid,
|
||||
'opinion_relations' : relations
|
||||
}
|
||||
bulk_data.append(data)
|
||||
|
||||
prev_eid = eid
|
||||
relations=[]
|
||||
relations.append(relation)
|
||||
|
||||
|
||||
if len(bulk_data) >= 10:
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' relations_qanon_opinion , total='+str(total_count) , str(i)+ ', id=' + eid )
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
# limit POST Content-Length 8388608
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
if response.status_code != 200 :
|
||||
print(bulk_data)
|
||||
print(response.text)
|
||||
bulk_data = []
|
||||
break
|
||||
|
||||
bulk_data = pops_data
|
||||
# print(response)
|
||||
# print(response.text)
|
||||
# print(row.txt)
|
||||
|
||||
|
||||
|
||||
if len(relations) > 0 :
|
||||
data={
|
||||
'id' : prev_eid,
|
||||
'opinion_relations' : relations
|
||||
}
|
||||
bulk_data.append(data)
|
||||
|
||||
while len(bulk_data) > 0 :
|
||||
total_count += len(bulk_data)
|
||||
print('=' * 10, ' relations_qanon_opinion , total='+str(total_count))
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
pops_data = []
|
||||
while len(payload) > 8388608 :
|
||||
el = bulk_data.pop()
|
||||
total_count -= 1
|
||||
pops_data.append(el)
|
||||
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
|
||||
|
||||
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()
|
||||
print("update rows count: " + str(len(all_data)))
|
||||
print("finished time: " + str(t2))
|
||||
print("process time: " + str(t2-t1))
|
||||
print(' end success relations_qanon_opinion')
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
این فایل در اولین فرصت پاک شود
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
|
||||
cursor, cnxn = create_cursor()
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
|
||||
|
||||
ADD_LIST_ROUTE = "project/add"
|
||||
ADD_ITEM_ROUTE = "subject/add"
|
||||
TITLE = "استانها و شهرهای ایران"
|
||||
TYPE = 2
|
||||
|
||||
ADD_LIST_QUERY = {
|
||||
"title": TITLE,
|
||||
"type": 2,
|
||||
"item_state": 0,
|
||||
"ispublic" : 1,
|
||||
"tags": "province",
|
||||
}
|
||||
|
||||
# result= requests.post(BASE_URL + 'list/' + ADD_LIST_ROUTE, data=ADD_LIST_QUERY, headers = HEADERS)
|
||||
# print(result)
|
||||
# print(result.text)
|
||||
# projectid = json.loads(result.text)["data"]["id"]
|
||||
# exit()
|
||||
|
||||
projectid = 1000
|
||||
|
||||
# EXAMPLE_ADD_ITEM_QUERY = {
|
||||
# "title": "",
|
||||
# "projectid": projectid,
|
||||
# "listtype": 0,
|
||||
# "parent": 0,
|
||||
# }
|
||||
|
||||
|
||||
file_path = './data/ostan.txt'
|
||||
lines = []
|
||||
with open(file_path, 'r', encoding='utf-8') as file:
|
||||
lines = file.readlines()
|
||||
|
||||
print(len(lines))
|
||||
|
||||
ostan_dic={}
|
||||
ostan_order = 0
|
||||
shahr_order = 0
|
||||
number = 0
|
||||
for line in lines:
|
||||
items = line.strip('\n').split('\t')
|
||||
# print(items)
|
||||
number +=1
|
||||
if len(items) != 2 :
|
||||
continue
|
||||
ostan=items[0]
|
||||
shahr=items[1]
|
||||
|
||||
if ostan not in ostan_dic:
|
||||
ostan_order= ostan_order+1
|
||||
payload = {
|
||||
"title": ostan,
|
||||
"projectid": projectid,
|
||||
"childorder": ostan_order,
|
||||
"listtype": 2,
|
||||
"parent": 0,
|
||||
}
|
||||
result = requests.post(BASE_URL + 'list/' + ADD_ITEM_ROUTE, data=payload, headers=HEADERS)
|
||||
# print(result.text)
|
||||
id = json.loads(result.text)["data"][0]["id"]
|
||||
ostan_dic[ostan]=id
|
||||
|
||||
ostan_id=ostan_dic[ostan]
|
||||
shahr_order = shahr_order + 1
|
||||
payload = {
|
||||
"title": shahr,
|
||||
"projectid": projectid,
|
||||
"childorder": shahr_order,
|
||||
"listtype": 2,
|
||||
"parent": ostan_id,
|
||||
}
|
||||
result = requests.post(BASE_URL + 'list/' + ADD_ITEM_ROUTE, data=payload, headers=HEADERS)
|
||||
id = json.loads(result.text)["data"][0]["id"]
|
||||
print('-'*10, id, ' ', shahr_order )
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import os
|
||||
import re
|
||||
import random
|
||||
from dotenv import load_dotenv
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
# from general import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
from create_relation_tags import *
|
||||
from temp_refactor_gn_dataset import *
|
||||
|
||||
load_dotenv(dotenv_path='config.env')
|
||||
|
||||
|
||||
host=os.getenv('HOST_160')
|
||||
password=os.getenv('HOST_160_PASS')
|
||||
|
||||
print(host)
|
||||
# print(password)
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
|
||||
|
||||
def import_synonym_virstaran_min(elastic, file_input, index_name_o):
|
||||
|
||||
lines = []
|
||||
with open(file_input, 'r', encoding='utf-8') as file:
|
||||
# نوشتن خطا در فایل
|
||||
lines = file.readlines()
|
||||
|
||||
row = 0
|
||||
for item in lines :
|
||||
item = item.strip()
|
||||
if not item :
|
||||
continue
|
||||
|
||||
|
||||
words = []
|
||||
for w in item.split(','):
|
||||
w = re.sub(r"\uFEFF|\u00AD|\u00AC", "\u200C", w)
|
||||
w = w.strip("\u200C").strip()
|
||||
words.append(w)
|
||||
|
||||
if len(words) == 0 :
|
||||
continue
|
||||
|
||||
row = row + 1
|
||||
|
||||
if ( row % 10 ) == 0 :
|
||||
print( 'row = ', row, '/', len(lines))
|
||||
#eid = 'syn_vr_' + random.randrange(10000)
|
||||
eid = 'syn_vr_' + str(10000+row)
|
||||
data = {
|
||||
'id' : eid,
|
||||
"main_type": "synonym",
|
||||
"ref_key": "virastaran",
|
||||
'words' : words
|
||||
}
|
||||
|
||||
try:
|
||||
resp = elastic.update_index_doc(False, index_name_o, eid, data)
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
|
||||
elastic.createIndex("gn_synonym", '', "gn_synonym" )
|
||||
|
||||
file_excel = './data/fa_virastarn_min.txt'
|
||||
import_synonym_virstaran_min(elastic, file_excel, "gn_synonym" )
|
||||
@@ -0,0 +1,402 @@
|
||||
[
|
||||
{
|
||||
"title": "آب",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 1,
|
||||
"listtype": 0,
|
||||
"id": 8007
|
||||
},
|
||||
{
|
||||
"title": "آمار، برنامه و بودجه",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 2,
|
||||
"listtype": 0,
|
||||
"id": 8008
|
||||
},
|
||||
{
|
||||
"title": "آموزش و پرورش",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 3,
|
||||
"listtype": 0,
|
||||
"id": 8009
|
||||
},
|
||||
{
|
||||
"title": "آموزش عالی، پژوهش و فناوری",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 4,
|
||||
"listtype": 0,
|
||||
"id": 8010
|
||||
},
|
||||
{
|
||||
"title": "آیین دادرسی مدنی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 5,
|
||||
"listtype": 0,
|
||||
"id": 8011
|
||||
},
|
||||
{
|
||||
"title": "آیین دادرسی اداری",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 6,
|
||||
"listtype": 0,
|
||||
"id": 8012
|
||||
},
|
||||
{
|
||||
"title": "آیین دادرسی کیفری",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 7,
|
||||
"listtype": 0,
|
||||
"id": 8013
|
||||
},
|
||||
{
|
||||
"title": "اداری و استخدامی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 8,
|
||||
"listtype": 0,
|
||||
"id": 8014
|
||||
},
|
||||
{
|
||||
"title": "اموال و معاملات دولتی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"(با زیرفصل اجرای سیاستهای کلی اصل44)\"}",
|
||||
"otherid": 9,
|
||||
"listtype": 0,
|
||||
"id": 8015
|
||||
},
|
||||
{
|
||||
"title": "اطلاعات، امنیت و نظامی، انتظامی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 10,
|
||||
"listtype": 0,
|
||||
"id": 8016
|
||||
},
|
||||
{
|
||||
"title": "امور زیربنایی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 11,
|
||||
"listtype": 0,
|
||||
"id": 8017
|
||||
},
|
||||
{
|
||||
"title": "انتخابات",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 12,
|
||||
"listtype": 0,
|
||||
"id": 8018
|
||||
},
|
||||
{
|
||||
"title": "اوقاف، اماکن دینی و امور مذهبی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 13,
|
||||
"listtype": 0,
|
||||
"id": 8019
|
||||
},
|
||||
{
|
||||
"title": "ایثارگران",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 14,
|
||||
"listtype": 0,
|
||||
"id": 8020
|
||||
},
|
||||
{
|
||||
"title": "بانکداری",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 15,
|
||||
"listtype": 0,
|
||||
"id": 8021
|
||||
},
|
||||
{
|
||||
"title": "برق و انرژیهای نوین",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 16,
|
||||
"listtype": 0,
|
||||
"id": 8022
|
||||
},
|
||||
{
|
||||
"title": "بیمه",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 17,
|
||||
"listtype": 0,
|
||||
"id": 8023
|
||||
},
|
||||
{
|
||||
"title": "پولی و مالی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\" (با زیرفصلهای سرمایه گذاری داخلی وخارجی ـ بازار سرمایه)\"}",
|
||||
"otherid": 18,
|
||||
"listtype": 0,
|
||||
"id": 8024
|
||||
},
|
||||
{
|
||||
"title": "تأمین اجتماعی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 19,
|
||||
"listtype": 0,
|
||||
"id": 8025
|
||||
},
|
||||
{
|
||||
"title": "تجارت",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"(اعم از تجارت داخلی و خارجی)\"}",
|
||||
"otherid": 20,
|
||||
"listtype": 0,
|
||||
"id": 8026
|
||||
},
|
||||
{
|
||||
"title": "تشکلهای مدنی و احزاب",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 21,
|
||||
"listtype": 0,
|
||||
"id": 8027
|
||||
},
|
||||
{
|
||||
"title": "تشکیلات و امور اداری قوه قضائیه",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 22,
|
||||
"listtype": 0,
|
||||
"id": 8028
|
||||
},
|
||||
{
|
||||
"title": "تعاون",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 23,
|
||||
"listtype": 0,
|
||||
"id": 8029
|
||||
},
|
||||
{
|
||||
"title": "تعزیرات حکومتی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"(مجازاتهای غیرقضایی)\"}",
|
||||
"otherid": 24,
|
||||
"listtype": 0,
|
||||
"id": 8030
|
||||
},
|
||||
{
|
||||
"title": "تقسیمات کشوری و مدیریت محلی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 25,
|
||||
"listtype": 0,
|
||||
"id": 8031
|
||||
},
|
||||
{
|
||||
"title": "ثبت اسناد و املاک",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 26,
|
||||
"listtype": 0,
|
||||
"id": 8032
|
||||
},
|
||||
{
|
||||
"title": "حمل و نقل",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 27,
|
||||
"listtype": 0,
|
||||
"id": 8033
|
||||
},
|
||||
{
|
||||
"title": "خانواده",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 28,
|
||||
"listtype": 0,
|
||||
"id": 8034
|
||||
},
|
||||
{
|
||||
"title": "رسانه",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 29,
|
||||
"listtype": 0,
|
||||
"id": 8035
|
||||
},
|
||||
{
|
||||
"title": "سلامت",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 30,
|
||||
"listtype": 0,
|
||||
"id": 8036
|
||||
},
|
||||
{
|
||||
"title": "صنعت",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 31,
|
||||
"listtype": 0,
|
||||
"id": 8037
|
||||
},
|
||||
{
|
||||
"title": "ارتباطات و فناوری اطلاعات",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 32,
|
||||
"listtype": 0,
|
||||
"id": 8038
|
||||
},
|
||||
{
|
||||
"title": "فرهنگ و هنر",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 33,
|
||||
"listtype": 0,
|
||||
"id": 8039
|
||||
},
|
||||
{
|
||||
"title": "کار",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 34,
|
||||
"listtype": 0,
|
||||
"id": 8040
|
||||
},
|
||||
{
|
||||
"title": "کشاورزی و دامپروری",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"(منابع طبیعی)\"}",
|
||||
"otherid": 35,
|
||||
"listtype": 0,
|
||||
"id": 8041
|
||||
},
|
||||
{
|
||||
"title": "کیفری",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 36,
|
||||
"listtype": 0,
|
||||
"id": 8042
|
||||
},
|
||||
{
|
||||
"title": "مالکیت فکری",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 37,
|
||||
"listtype": 0,
|
||||
"id": 8043
|
||||
},
|
||||
{
|
||||
"title": "مالیات",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 38,
|
||||
"listtype": 0,
|
||||
"id": 8044
|
||||
},
|
||||
{
|
||||
"title": "محاسبات عمومی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 39,
|
||||
"listtype": 0,
|
||||
"id": 8045
|
||||
},
|
||||
{
|
||||
"title": "محیط زیست",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"(اراضی مربوط به محیط زیست (خاک) زیر این کد قرار میگیرد)\"}",
|
||||
"otherid": 40,
|
||||
"listtype": 0,
|
||||
"id": 8046
|
||||
},
|
||||
{
|
||||
"title": "مدنی و امور حسبی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\" (ثبت احوال،تابعیت واتباع خارجی از سرفصلهای این کد است)\"}",
|
||||
"otherid": 41,
|
||||
"listtype": 0,
|
||||
"id": 8047
|
||||
},
|
||||
{
|
||||
"title": "مسکن و شهرسازی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\" (اراضی مربوط به مسکن و شهرسازی زیر این کد قرار میگیرد)\"}",
|
||||
"otherid": 42,
|
||||
"listtype": 0,
|
||||
"id": 8048
|
||||
},
|
||||
{
|
||||
"title": "مصرف",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\" (با زیرفصل قانون سازمان ملی استاندارد، سایر قوانین و مقررات استاندارد در زیر هر یک از کدهای مربوطه قرار می گیرد)\"}",
|
||||
"otherid": 43,
|
||||
"listtype": 0,
|
||||
"id": 8049
|
||||
},
|
||||
{
|
||||
"title": "معدن",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 44,
|
||||
"listtype": 0,
|
||||
"id": 8050
|
||||
},
|
||||
{
|
||||
"title": "مناطق آزاد و ویژه اقتصادی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 45,
|
||||
"listtype": 0,
|
||||
"id": 8051
|
||||
},
|
||||
{
|
||||
"title": "میراث فرهنگی، گردشگری و صنایع دستی",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 46,
|
||||
"listtype": 0,
|
||||
"id": 8052
|
||||
},
|
||||
{
|
||||
"title": "نظام قانونگذاری",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\" (که شامل سه سرفصل مجلس شورای اسلامی متشکل از (تقنین و نظارت)، شورای نگهبان، مجمع تشخیص مصلحت نظام)\"}",
|
||||
"otherid": 47,
|
||||
"listtype": 0,
|
||||
"id": 8053
|
||||
},
|
||||
{
|
||||
"title": "نظامهای صنفی و حرفهای",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 48,
|
||||
"listtype": 0,
|
||||
"id": 8054
|
||||
},
|
||||
{
|
||||
"title": "نفت و گاز",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 49,
|
||||
"listtype": 0,
|
||||
"id": 8055
|
||||
},
|
||||
{
|
||||
"title": "ورزش",
|
||||
"projectid": 8,
|
||||
"meta": "{\"description\":\"\"}",
|
||||
"otherid": 50,
|
||||
"listtype": 0,
|
||||
"id": 8056
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,161 @@
|
||||
لایحه قانونی راجع به آئین نامه اجرائی دفتر معاملات مسکن و تغییرنام=qq118694
|
||||
منتفی بودن لایحه قانونی تشکیل انجمنهای ده و اصلاح امور اجتماعی و عمرانی دهات=qq120753
|
||||
خریداری کلیه اراضی گودهای کوره پزخانه های سابق و فعلی واقع در جنوب تهران بین خیابانهای شوش و حد جنوبی جدید تهران و جاده آرامگاه و خیابان سپهبد رزم آرا توسط شهرداری تهرات برای رفع نیازمندی های عمومی شهر=0
|
||||
قانون راجع باجازه تحصیل مبلغ هفتاد و دو میلیون دلار وام از بانک بینالمللی ترمیم و توسعه=qq113980
|
||||
قانون راجع به احداث و توسعه معابر و خیابان ها=qq112239
|
||||
قانون بودجه 1385 کل کشور=qq87759
|
||||
قانون بودجه سال 1369کل کشور=qq84519
|
||||
قانون اصلاح مواد 4 و 6 قانون تغییر نام وزارت آبادانی و مسکن بوزارت مسکن و شهرسازی و تعیین وظایف آن=qq86848
|
||||
ائیننامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28ر12ر1345=qq115135
|
||||
قانون اعطای امتیاز نفط بشرکت نفط انگیس[انگلیس] و ایران محدود=qq85083
|
||||
آئین نامه اجرائی لایحه قانونی اصلاح لایحه قانونی واگذاری و احیاء اراضی در حکومت جمهوری اسلامی ایران مصوب 21/1/59=qq83760
|
||||
لایحه قانونی ملی کردن سهام شرکت سهامی انبارهای عمومی=qq83938
|
||||
لایحه قانونی الحاق سه تبصره به مواد 7 و 11 و 14 قانون تشکیل دادگاههای عمومی و یک تبصره بماده 17 قانون اصلاح قانون منع کشت خشخاش مصوب سال 1338 و اصلاح ماده 46 قانون اصول تشکیلات دادگستری=qq87062
|
||||
لایحه قانونی مالکیت و بهره برداری از اراضی واقع در آبخورسد دز و الغاء قردادهای کشت و صنعت=qq87024
|
||||
لایحه قانونی اصلاح قانون مربوط بسرسید سفته ها وتضمین نامه ها وبروات و چکها=qq86971
|
||||
تصمیم قانونی راجع به آئین نامه جلوگیری از آلودگی هوا=0
|
||||
قانون قراداد تشویق وحمایت متقابل سرمایه گذاری بین دولت ایران وجمهوری فدرال آلمان=qq85065
|
||||
قانون اجازه تحصیل مبلغ بیست و پنج میلیون دلار وام از صندوق وامهای عمرانی امریکا=qq85231
|
||||
رد لایحه راجع به تشکیل اداره دعاوی وزارت دارائی که در کمیسیون مشترک مجلسین رد شده است=qq114031
|
||||
آئین نامه اجرائی ماده 18 قانون اصلاح قانون مالیات بر درآمد=qq113975
|
||||
قانون مربوط بالحاق یک تبصره بماده 370 قانون امور حسبی و یک تبصره بماده 56 قانون شریع(تسریع) محاکمات=qq113534
|
||||
لایحه قانونی تصویب قرارداد بین المللی ارتباطات دوره منعقده در بوئنوس آیرس در سال 1331=qq113460
|
||||
قانون مربوط بموافقتنامه راجع به سرویسهای حمل و نقل بازرگانی منعقده بین دولت شاهنشاهی ایران و دولت هلند=qq114554
|
||||
تصمیم متخذه کمیسیون مشترک در مورد هزینه های دادگستری و ثبت و حق تمبر پروانه=qq113344
|
||||
قانون تصویب عهدنامه تسویه مسالمت آمیز اختلافات بین دولت شاهنشاهی ایران و دولت پادشاهی عراق=qq85019
|
||||
قانون راجع برشد متعاملین=qq112444
|
||||
قانون اصلاح مواد 13ر 41ر 43ر70ر111ر117قانون ثبت اسناد و املاک=qq112144
|
||||
قانون اجازه مبادله عهدنامه مودت منعقده بین دولتین ایران و افغانستان=qq84876
|
||||
قانون اصلاح جداول شماره (4) و (8) قانون برنامه چهارم توسعه اقتصادی، اجتماعی و فرهنگی جمهوری اسلامی ایران و قانون بودجه سال 1386 کل کشور به منظور تآمین کسری اعتبار گاز رسانی به روستاهای کشور=qq36662
|
||||
قانون الحاق دولت جمهوری اسلامی ایران به پروتکل 1992جهت اصلاح کنوانسیون بین المللی مسوولیت مدنی ناشی ازخسارت آلودگی نفتی ( 1969 ) و پروتکل 1992 جهت اصلاح کنوانسیون تاسیس یک صندوق بین المللی برای جبران خسارت آلودگی نفتی (1971)=qq116450
|
||||
قانون مربوط بقرداد فروش و خرید گاز طبیعی بین شرکت ملی ایران وشرکت متالیمکس (METALIMEX)چکسلواکی=qq86609
|
||||
قانون مربوط بقرداد فروش و خریدگازطبیعی بین شرکت ملی گاز ایران و شرکتهای روهرگاز Ruhrgaz گاز دوفرانس (Gaz de France)و نفت معدنی اطریش Oesterreichische Mineraloel Verwaltung Aktiengesellschaft=qq86601
|
||||
اجازه اعمال تغییرات در بودجه به وزارت دارائی به منظور تأمین کسری اعتبار بعضی از هزینه ها=qq235140
|
||||
اجازه پرداخت ده میلیون ریال جهت مبارزه با بیماری وبا در اختیار وزارت بهداری=qq289936
|
||||
اجازه پرداخت مبلغ یک میلیون و یکصد و بیست و پنج هزار ریال به وزارت کشاورزی جهت تأمین حقوق و هزینه های ضروری خرداد ماه سال 1341 سازمان اصلاحات ارضی=qq184583
|
||||
اجازه پرداخت نود و پنج میلیون ریال در حدود وصولی های درآمد کشور=qq289936
|
||||
اصلاح آئین نامه طرز تشخیص و وصول مالیات کسبه و پیشهوران=qq164518
|
||||
اصلاح بودجه تفضیلی سال 1340 و کسر مبلغ چهل میلیون ریال از بعضی مواد و افزودن به مواد دیگر=qq188606
|
||||
اصلاح بودجه سال 2536 (1356) شهربانی کشور=qq87031
|
||||
اصلاحیه قانون بودجه سال 1397 کل کشور=qq260944
|
||||
اصلاحیه قانون حداکثر استفاده از توان تولیدی و خدماتی در تأمین نیازهای کشور و تقویت آنها در امر صادرات و اصلاح ماده (104) قانون مالیاتهای مستقیم=qq192211
|
||||
اصلاحیه ماده 25 آیین نامه معاملات دولتی=qq118088
|
||||
الزام دولت به تقدیم لایحه توسط مجلس شورای اسلامی در خصوص برنامه زمان بندی ممنوعیت تدریجی کشت توتون، تولید و توزیع انواع سیگار و طرح انحلال شورای عالی پزشکی اعزام بیماران به خارج از کشور=0
|
||||
ائیننامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28 ر12 ر1345=qq115135
|
||||
آیین نامه اجرای[اجرایی] استفاده از اتومبیل های دولتی موضوع تبصره 68 قانون بودجه سال 1344 کل کشور=qq114484
|
||||
آئین نامه اجرائی لایحه قانونی اصلاح لایحه قانونی واگذاری و احیاء اراضی در حکومت جمهوری اسلامی ایران مصوب 21/1/59=qq83760
|
||||
آئین نامه اجرائی ماده 18 قانون اصلاح قانون مالیات بر درآمد=qq113975
|
||||
بودجه سازمان غله کشور در ششماهه دوم سال 1348 از محل درامد عمومی=qq289088
|
||||
بودجه سال 1332 سازمان برنامه (مصوب کمیسیون برنامه)=qq113255
|
||||
تصمیم قانونی راجع به آئین نامه جلوگیری از آلودگی هوا=qq120748
|
||||
تصمیم کمیسیون بودجه در خصوص اجازه پرداخت حق بیمه اشیاء عتیقه موزه ایران باستان=qq289520
|
||||
تصمیم کمیسیون بودجه درخصوص اصلاح اعتبار برنامه ها و اعتبار مواد هزینه و فصول بودجه سال 1345=qq289020
|
||||
تصمیم متخده کمیسیون بودجه مجلس شورای ملی دائر باصلاح بودجه سال 1348 وزارت کار و امور اجتماعی=qq289083
|
||||
تصمیم متخذه کمیسیون بودجه دائر به اجازه خرید یکدستگاه جیپ استیشن جهت وزارت صنایع و معادن [صنعت، معدن و تجارت]=qq113965
|
||||
تصمیم متخذه کمیسیون مشترک دارائی برنامه مجلسین دائر باصلاح تبصره 2 آئین نامه اجرایی قسمت اول تبصره 29 قانون بودجه سال 1344 کل کشور و حذف=qq114901
|
||||
تصمیم متخذه کمیسیون مشترک در مورد هزینه های دادگستری و ثبت و حق تمبر پروانه=qq113344
|
||||
تصویب نامه راجع به تمدید تعهد اعتبار وزارت بهداری=qq184596
|
||||
تصویب نامه شماره 3588 ـ5/3/1342 دولت راجع به وام شماره 017/ه/265 از سازمان عمران بین المللی آمریکا برای تأمین هزینه پروژههای بندر عباس=qq121069
|
||||
تصویب نامه شماره 3626 ـ6/3/1342 راجع به وام شماره 016/ه/265 از سازمان عمران بین المللی آمریکا برای تأمین هزینه پروژههای اصلی برق ایران=qq184693
|
||||
تصویب نامه قانونی لغو معافیت ورود و صدور اشیاء عتیقه و آثار فرهنگی هنری اصیل=qq118279
|
||||
تصویبنامه شماره 12/26202 مورخ 1339/9/26 هیأت وزیران راجع باجازه پرداخت مبلغ ده میلیون ریال از محل درآمد عمومی کشور در سال 1339 بوزارت بهداری جهت مبارزه با وبا=qq121087
|
||||
تصویبنامه شماره 20942 مورخ 1339/7/26 هیأت وزیران راجع بپرداخت مبلغ ده میلیون ریال از درآمد عمومی سال 1339 بوزارت بهداری برای جلوگیری از مرض وبا =qq121087
|
||||
تصویبنامه شماره 22842 مورخ 22 ر8ر1339 هیأت وزیران راجع به اجازه مصرف مبلغ چهار میلیون ریال از محل مازاد درآمد اختصاصی بنگاه دامپروری برای توسعه و پیشرفت امور موسسه دامپروری=qq121075
|
||||
تصویبنامه شماره 9878 مورخ 26 ر3ر1339 هیأت وزیران راجع به اجازه پرداخت مبلغ هفتصد و پنجاه میلیون ریال وام به سازمان برنامه از محل درآمدهای دولت در سال 1339 =qq121055
|
||||
دادن اختیار به وزارت کشاورزی در خصوص معاملات مربوط به دهات ششدانک=0
|
||||
رد تصویب نامه شماره 3588 ـ5/3/1342 دولت راجع بهوام شماره 017/ه/265 از سازمان عمران بین المللی آمریکا برای تأمین هزینه پروژههای بندر عباس=qq165841
|
||||
رد تصویب نامه شماره 3626 - 1342/3/6 راجع به وام شماره 016/ه/265 از سازمان عمران بین المللی آمریکا برای تأمین هزینه پروژههای اصلی برق ایران=qq184693
|
||||
رد تصویب نامه شماره 8028/ت ـ 25/3/1340 دولت راجع به تحصیل اعتبار از بانک صادرات و واردات آمریکا جهت خرید کالاهای تولیدی از آمریکا=qq165859
|
||||
رد لایحه راجع به تشکیل اداره دعاوی وزارت دارائی که در کمیسیون مشترک مجلسین رد شده است=qq114031
|
||||
قانون اجازه استقراض دو ملیون ریال از بانک ملی برای شهرداری رشت=qq112541
|
||||
قانون اجازه تجدید قرارداد استخدامی آقای ویلهلم مایر تبعه دولت آلمان=qq112556
|
||||
قانون اجازه تحصیل مبلغ بیست و پنج میلیون دلار وام از صندوق وامهای عمرانی امریکا=qq85231
|
||||
قانون اجازه ساختمان راهآهن مابین خورموسی و بندر محمره و بندر جز=qq115835
|
||||
قانون اجازه مبادله عهدنامه مودت منعقده بین دولتین ایران و افغانستان=qq84876
|
||||
قانون اجازه مبادله قراداد بازرگانی ایران و آلمان=qq114422
|
||||
قانون استخدام جانبازان ،اسراوافرادخانواده های شهدا،جانبازان ازکارافتاده ،اسراومفقودالاثرهای انقلاب اسلامی وجنگ تحمیلی وهمچنین افرادی که حداقل 9 ماه متوالی یایکسال متناوب داوطلبانه درجبهه خدمت نموده اند=qq83370
|
||||
قانون استخدام نیروهای مسلح شاهنشاهی ایران [قانون ارتش جمهوری اسلامی ایران]=qq113595
|
||||
قانون اصلاح بند (و) ماده (1) قانون برنامه چهارم توسعه اقتصادی‘ اجتماعی و فرهنگی جمهوری اسلامی ایران و جداول مربوط و اختصاص معادل تا دویست و پنجاه میلیون (250/000/000) دلار برای ماهواره سازمان صدا و سیمای جمهوری اسلامی ایران=qq121771
|
||||
قانون اصلاح بند«ج»ماده 15 قانون استخدام نیروهای مسلح شاهنشاهی=qq111882
|
||||
قانون اصلاح پاره ای از مقررات مربوط به پایه حقوق اعضای رسمی هیات علمی ( آموزشی و پژوهشی ) شاغل و بازنشسته دانشگاهها و موسسات آموزش عالی=qq120722
|
||||
قانون اصلاح تبصره یک مصوب 1364/06/28 ماده 9 قانون روابط موجر و مستاجر مصوب 1362/02/13 مجلس شورای اسلامی=qq111747
|
||||
قانون اصلاح جداول شماره (4) و (8) قانون برنامه چهارم توسعه اقتصادی، اجتماعی و فرهنگی جمهوری اسلامی ایران و قانون بودجه سال 1386 کل کشور به منظور تآمین کسری اعتبار گاز رسانی به روستاهای کشور=qq36662
|
||||
قانون اصلاح فصل دوم و پنجم قانون ترفیعات ارتش شاهنشاهی=qq112640
|
||||
قانون اصلاح قانون طبقه بندی مشاغل و برقراری کمک هزینه مسکن کارگری مصوب 1359/01/27 شورای انقلاب جمهوری اسلامی ایران=qq83726
|
||||
قانون اصلاح قانون معادن مصوب 62/3/1 [1362] مجلس شورای اسلامی=qq85625
|
||||
قانون اصلاح قانون معافیت یک نفر از فرزندان خانواده های شهداء، معلولین، اسرا، مفقودالاثرها از خدمت نظام وظیفه عمومی مصوب 1366=qq84464
|
||||
قانون اصلاح قانون نحوه جبران زحمات و خسارات کارکنان سازمان حفاظت محیط زیست در ارتباط جرائم زیست محیطی=qq87760
|
||||
قانون اصلاح قانون نظام هماهنگ پرداخت کارکنان دولت مصوب 1370/6/13=qq83577
|
||||
قانون اصلاح ماده (56) قانون الحاق موادی به قانون تنظیم بخشی از مقررات مالی دولت =qq121967
|
||||
قانون اصلاح ماده 113 قانون اصلاح قانون استخدام نیروهای مسلح شاهنشاهی=qq86913
|
||||
قانون اصلاح ماده 4 قانون شمول قانون استخدام نیروهای مسلح شاهنشاهی بافسران و درجه داران و افراد شهربانی کل کشور=qq115007
|
||||
قانون اصلاح ماده 70 قانون استخدام نیروهای مسلح شاهنشاهی=qq237979
|
||||
قانون اصلاح ماده 85 قانون استخدام نیروهای مسلح شاهنشاهی=qq114509
|
||||
قانون اصلاح مواد 13 ر 41 ر 43 ر70 ر111 ر117 قانون ثبت اسناد و املاک=qq112144
|
||||
قانون اصلاح مواد 13ر 41ر 43ر70ر111ر117قانون ثبت اسناد و املاک=qq112144
|
||||
قانون اصلاح موادی از قانون برنامه چهارم توسعه اقتصادی، اجتماعی و فرهنگی جمهوری اسلامی ایران و اجراء سیاستهای کلی اصل چهل و چهارم (44) قانون اساسی [قانون اجرای سیاستهای کلی اصل چهل و چهارم (44) قانون اساسی]=qq178058
|
||||
قانون اصلاح موادی از قانون شکار و صید - مصوب 1346 – و اصلاحیه بعدی آن=qq83519
|
||||
قانون الحاق تبصره (6) به ماده (31) قانون خدمت وظیفه عمومی=qq86843
|
||||
قانون الحاق دو تبصره به ماده (617) قانون مجازات اسلامی (کتاب پنجم ـ تعزیرات و مجازات های بازدارنده)=qq260019
|
||||
قانون الحاق دولت جمهوری اسلامی ایران به پروتکل 1992جهت اصلاح کنوانسیون بین المللی مسوولیت مدنی ناشی ازخسارت آلودگی نفتی ( 1969 ) و پروتکل 1992 جهت اصلاح کنوانسیون تاسیس یک صندوق بین المللی برای جبران خسارت آلودگی نفتی (1971)=qq116450
|
||||
قانون الحاق موادی به قانون نحوه حفظ آثار و یاد حضرت امام خمینی رضوان ا...تعالی علیه=0
|
||||
قانون الحاق یک بند بماده 15 قانون استخدام نیروهای مسلح شاهنشاهی=qq86939
|
||||
قانون الحاق یک بند به عنوان بند ج و دو تبصره به ماده 2 قانون روابط موجر و مستأجرمصوب 1362=qq83421
|
||||
قانون الحاق یک تبصره بعنوان تبصره یک به ماده 9 قانون روابط موجر ومستاجر مصوب 1362/2/13=qq111600
|
||||
قانون الحاق یک تبصره به ماده (182) قانون ایین نامه داخلی مجلس شورای اسلامی=0
|
||||
قانون الحاق یک تبصره به ماده 40 قانون نظام پزشکی جمهوری اسلامی ایران=qq185059
|
||||
قانون برقراری حقوق وظیفه یا مستمری بازماندگان آن دسته از مهاجران وکسانی که به مناطق جنگی مراجعت نموده و بعلت برخورد با مواد منفجره معلول یا فوت میشوند=qq83692
|
||||
قانون تجدید کنترات دکتر کراندل تبعه دولت فرانسه برای ریاست قسمت فنی و اداری موسسه پاستور به مدت سه سال=qq289936
|
||||
قانون تشکیل میراث فرهنگی و گردشگری=qq86061
|
||||
قانون تشکیلات و آیین دادرسی دیوان عدالت اداری=qq302246
|
||||
قانون تصویب عهدنامه تسویه مسالمت آمیز اختلافات بین دولت شاهنشاهی ایران و دولت پادشاهی عراق=qq85019
|
||||
قانون تفسیر جزء (1 ـ 5) قوانین بودجه سالهای 1391 و 1392 کل کشور=qq220596
|
||||
قانون تفسیر قانون الحاق یک ماده به قانون تعیین تکلیف استخدامی معلمین حق التدریسی و آموزشیاران نهضت سواد آموزی مصوب 13 /6 /1397=qq286515
|
||||
قانون تفسیرتبصره 2 ماده 22 قانون تشکیل سازمان نظام پزشکی جمهوری اسلامی ایران=qq83795
|
||||
قانون حدود و قصاص و مقررات آن از ماده 196 تا 218=qq87694
|
||||
قانون راجع باجازه پرداخت تفاوت اضافات سال 34 کارمندان دون پایه و خدمتگذاران جزء وزارتخانه ها و ادارات دولتی=qq113724
|
||||
قانون راجع باصلاح تبصره ماده 3 قانون استخدام پرستار و ماما و کارمند فنی مصوب 12 ر12 ر38=qq114773
|
||||
قانون راجع برشد متعاملین=qq112444
|
||||
قانون راجع بقرارداد فرهنگی بین دولت شاهنشاهی ایران و دولت متحده بریتانیای کبیر و ایرلند شمالی=qq85085
|
||||
قانون راجع بلغو گذرنامه برای مسافرت عراق و مرز سوریه=qq114552
|
||||
قانون راجع به چرانیدن دام در منابع طبیعی=qq177315
|
||||
قانون راجع به قرداد منعقده بین دفتربرنامه ریزی و هدایت ترابری وزارت راه و ترابری جمهوری اسلامی ایران و اتحادیه کل انتفاعی و بازرگانی (سایوزترانزیت) شوروی درباره ترانزیت کالاهای تجاری با پروتکل و پیوست های چهارگانه=qq84998
|
||||
قانون راجع به موسسه اصلاح و تهیه نهال و بذر=qq113991
|
||||
قانون سرباز گیری=0
|
||||
قانون شمول تبصره 3 قانون نحوه بازنشستگی جانبازان انقلاب اسلامی و جنگ تحمیلی و معلولان عادی و شاغلین مشاغل سخت و زیان آور به کارکنان واحدهای صنعتی و تحقیقاتی وزارت دفاع و پشتیبانی نیروهای مسلح=qq84394
|
||||
قانون شمول قانون استخدام نیروهای مسلح شاهنشاهی بافسران و درجه داران و افراد شهربانی کل کشور=qq114356
|
||||
قانون فهرست قوانین و احکام منسوخ در حوزه محیط زیست=qq289668
|
||||
قانون قراداد تشویق وحمایت متقابل سرمایه گذاری بین دولت ایران وجمهوری فدرال آلمان=qq85065
|
||||
قانون لغو تبصره 70 قانون بودجه سال 1342 کل کشور و تبصره ماده 74 قانون استخدام نیروهای مسلح شاهنشاهی=qq86760
|
||||
قانون متمم بودجه سال 313 [1313]مملکتی=qq115907
|
||||
قانون مربوط باصلاح ماده 49 قانون ثبت احوال مصوب 13 اسفند ماه 1334=qq114576
|
||||
قانون مربوط بالحاق یک تبصره بماده 370 قانون امور حسبی و یک تبصره بماده 56 قانون شریع(تسریع) محاکمات=qq113534
|
||||
قانون مربوط بقرداد فروش و خرید گاز طبیعی بین شرکت ملی ایران وشرکت متالیمکس (METALIMEX)چکسلواکی=qq86609
|
||||
قانون مربوط بقرداد فروش و خریدگازطبیعی بین شرکت ملی گاز ایران و شرکتهای روهرگاز Ruhrgaz گاز دوفرانس (Gaz de France)و نفت معدنی اطریش Oesterreichische Mineraloel Verwaltung Aktiengesellschaft=qq86601
|
||||
قانون مربوط بموافقتنامه راجع به سرویسهای حمل و نقل بازرگانی منعقده بین دولت شاهنشاهی ایران و دولت هلند=qq114554
|
||||
قانون مربوط به اجازه پرداخت اجرت تعمیر الات [آلات] هواپیماهای سمپاش دفع آفات نباتی بدون رعایت تشریفات مناقصه به کمپانی جوناس ارکرافت نیویورک (jonas Airctaft)=qq114748
|
||||
قانون معافیت بهداشتکاران دهان و دندان و بهداران (تکنیسین های بهداشت و مبارزه با بیماریها) از انجام خدمات وظیفه عمومی=qq85375
|
||||
قانون موافقتنامه تشویق و حمایت متقابل از سرمایه گذاری بین دولت جمهوری اسلامی ایران و دولت جماهیری عربی مردمی سوسیالیستی=qq117914
|
||||
قرار دادن مبلغ 15000000 میلیون ریال از محل تنخواه گردان خزانه داری کل در اختیار اداره کل حسابداری نخست وزیری=qq234522
|
||||
کسر مبلغ دو میلیون ریال از اعتبار ماده 13 بودجه اختصاصی 3 ه سهمیه وزارت بهداری و افزودن به اعتبار ماده 14 همان بودجه=qq94273
|
||||
کمک به بهبود نحوه تولید و استانداردیزاسیون کالاهای صادراتی کشور=qq232936
|
||||
لایحه قانونی اصلاح بعضی از موارد مقررات استخدامی شرکتهای دولتی و الحاق مواد و تبصره هائی به آن=qq86734
|
||||
لایحه قانونی اصلاح قانون مربوط بسرسید سفته ها وتضمین نامه ها وبروات و چکها=qq86971
|
||||
لایحه قانونی اصلاح قانون مربوط بسرسید سفته ها وتضمین نامه ها وبروات و چکها=qq86971
|
||||
لایحه قانونی اصلاح ماده3 آئین نامه کمک خرج بکارمندان دولت=qq176339
|
||||
لایحه قانونی الحاق سه تبصره به مواد 7 و 11 و 14 قانون تشکیل دادگاههای عمومی و یک تبصره بماده 17 قانون اصلاح قانون منع کشت خشخاش مصوب سال 1338 و اصلاح ماده 46 قانون اصول تشکیلات دادگستری=qq87062
|
||||
لایحه قانونی الحاق سه تبصره به مواد 7 و 11 و 14 قانون تشکیل دادگاههای عمومی و یک تبصره بماده 17 قانون اصلاح قانون منع کشت خشخاش مصوب سال 1338 و اصلاح ماده 46 قانون اصول تشکیلات دادگستری=qq87062
|
||||
لایحه قانونی انتقال وجوه حاصله از فروش اراضی یوسف آباد ببانک ساختمانی=qq176113
|
||||
لایحه قانونی تصویب قرارداد بین المللی ارتباطات دوره منعقده در بوئنوس آیرس در سال 1331=qq113460
|
||||
لایحه قانونی تصویب قرارداد بین المللی ارتباطات دوره منعقده در بوئنوس آیرس در سال 1331=qq113460
|
||||
لایحه قانونی راجع به شمول مقررات قانون استخدام کشوری به سازمان ملی حفاظت آثار باستانی -تالار رودکی ـ مرکز اسناد فرهنگی آسیا ـ تأتر شهر=qq87513
|
||||
لایحه قانونی لغو تصویبنامه های مالیات اراضی شهر تهران و چندین شهر دیگر=qq175762
|
||||
لایحه قانونی مالکیت و بهره برداری از اراضی واقع در آبخورسد دز و الغاء قردادهای کشت و صنعت=qq87024
|
||||
لایحه قانونی مالکیت و بهره برداری از اراضی واقع در آبخورسد دز و الغاء قردادهای کشت و صنعت=qq87024
|
||||
لایحه قانونی ملی کردن سهام شرکت سهامی انبارهای عمومی=qq83938
|
||||
لایحه قانونی ملی کردن سهام شرکت سهامی انبارهای عمومی=qq83938
|
||||
لغو تصویب نامه شماره 22742 مورخ 20/6/1341 دولت راجع به مالیات پیشه وران=qq165988
|
||||
ماده واحده راجع به اخذ فارغالتحصیلان دیپلمه داوطلب خدمت و ارتش و شماره دانش=qq227748
|
||||
موافقتنامه فرهنگی بین دولت جمهوری اسلامی ایران و دولت جمهوری متحده تانزانیا=qq85196
|
||||
قانون استخدام نیروهای مسلح شاهنشاهی ایران [قانون ارتش جمهوری اسلامی ایران]=qq113595
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
لایحه قانونی راجع به آئین نامه اجرائی دفتر معاملات مسکن و تغییرنام=qq118694
|
||||
منتفی بودن لایحه قانونی تشکیل انجمنهای ده و اصلاح امور اجتماعی و عمرانی دهات=qq120753
|
||||
خریداری کلیه اراضی گودهای کوره پزخانه های سابق و فعلی واقع در جنوب تهران بین خیابانهای شوش و حد جنوبی جدید تهران و جاده آرامگاه و خیابان سپهبد رزم آرا توسط شهرداری تهرات برای رفع نیازمندی های عمومی شهر=0
|
||||
قانون راجع باجازه تحصیل مبلغ هفتاد و دو میلیون دلار وام از بانک بینالمللی ترمیم و توسعه=qq113980
|
||||
قانون راجع به احداث و توسعه معابر و خیابان ها=qq112239
|
||||
قانون بودجه 1385 کل کشور=qq87759
|
||||
قانون بودجه سال 1369کل کشور=qq84519
|
||||
قانون اصلاح مواد 4 و 6 قانون تغییر نام وزارت آبادانی و مسکن بوزارت مسکن و شهرسازی و تعیین وظایف آن=qq86848
|
||||
ائیننامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28ر12ر1345=qq115135
|
||||
قانون اعطای امتیاز نفط بشرکت نفط انگیس[انگلیس] و ایران محدود=qq85083
|
||||
آئین نامه اجرائی لایحه قانونی اصلاح لایحه قانونی واگذاری و احیاء اراضی در حکومت جمهوری اسلامی ایران مصوب 21/1/59=qq83760
|
||||
لایحه قانونی ملی کردن سهام شرکت سهامی انبارهای عمومی=qq83938
|
||||
لایحه قانونی الحاق سه تبصره به مواد 7 و 11 و 14 قانون تشکیل دادگاههای عمومی و یک تبصره بماده 17 قانون اصلاح قانون منع کشت خشخاش مصوب سال 1338 و اصلاح ماده 46 قانون اصول تشکیلات دادگستری=qq87062
|
||||
لایحه قانونی مالکیت و بهره برداری از اراضی واقع در آبخورسد دز و الغاء قردادهای کشت و صنعت=qq87024
|
||||
لایحه قانونی اصلاح قانون مربوط بسرسید سفته ها وتضمین نامه ها وبروات و چکها=qq86971
|
||||
تصمیم قانونی راجع به آئین نامه جلوگیری از آلودگی هوا=0
|
||||
قانون قراداد تشویق وحمایت متقابل سرمایه گذاری بین دولت ایران وجمهوری فدرال آلمان=qq85065
|
||||
قانون اجازه تحصیل مبلغ بیست و پنج میلیون دلار وام از صندوق وامهای عمرانی امریکا=qq85231
|
||||
رد لایحه راجع به تشکیل اداره دعاوی وزارت دارائی که در کمیسیون مشترک مجلسین رد شده است=qq114031
|
||||
آئین نامه اجرائی ماده 18 قانون اصلاح قانون مالیات بر درآمد=qq113975
|
||||
قانون مربوط بالحاق یک تبصره بماده 370 قانون امور حسبی و یک تبصره بماده 56 قانون شریع(تسریع) محاکمات=qq113534
|
||||
لایحه قانونی تصویب قرارداد بین المللی ارتباطات دوره منعقده در بوئنوس آیرس در سال 1331=qq113460
|
||||
قانون مربوط بموافقتنامه راجع به سرویسهای حمل و نقل بازرگانی منعقده بین دولت شاهنشاهی ایران و دولت هلند=qq114554
|
||||
تصمیم متخذه کمیسیون مشترک در مورد هزینه های دادگستری و ثبت و حق تمبر پروانه=qq113344
|
||||
قانون تصویب عهدنامه تسویه مسالمت آمیز اختلافات بین دولت شاهنشاهی ایران و دولت پادشاهی عراق=qq85019
|
||||
قانون راجع برشد متعاملین=qq112444
|
||||
قانون اصلاح مواد 13ر 41ر 43ر70ر111ر117قانون ثبت اسناد و املاک=qq112144
|
||||
قانون اجازه مبادله عهدنامه مودت منعقده بین دولتین ایران و افغانستان=qq84876
|
||||
قانون اصلاح جداول شماره (4) و (8) قانون برنامه چهارم توسعه اقتصادی، اجتماعی و فرهنگی جمهوری اسلامی ایران و قانون بودجه سال 1386 کل کشور به منظور تآمین کسری اعتبار گاز رسانی به روستاهای کشور=qq36662
|
||||
قانون الحاق دولت جمهوری اسلامی ایران به پروتکل 1992جهت اصلاح کنوانسیون بین المللی مسوولیت مدنی ناشی ازخسارت آلودگی نفتی ( 1969 ) و پروتکل 1992 جهت اصلاح کنوانسیون تاسیس یک صندوق بین المللی برای جبران خسارت آلودگی نفتی (1971)=qq116450
|
||||
قانون مربوط بقرداد فروش و خرید گاز طبیعی بین شرکت ملی ایران وشرکت متالیمکس (METALIMEX)چکسلواکی=qq86609
|
||||
قانون مربوط بقرداد فروش و خریدگازطبیعی بین شرکت ملی گاز ایران و شرکتهای روهرگاز Ruhrgaz گاز دوفرانس (Gaz de France)و نفت معدنی اطریش Oesterreichische Mineraloel Verwaltung Aktiengesellschaft=qq86601
|
||||
@@ -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 app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
from app.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")
|
||||
@@ -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 app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
from app.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")
|
||||
@@ -0,0 +1,712 @@
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
import json
|
||||
import pandas as pd
|
||||
from dotenv import load_dotenv
|
||||
# from app.common.general_functions import *
|
||||
from app.common.qanon_functions import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
from app.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) )
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import pandas as pd
|
||||
import requests
|
||||
import json
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
# from app.common.config_base import *
|
||||
from app.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
|
||||
@@ -0,0 +1,224 @@
|
||||
import pandas as pd
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
# from app.common.config_base import *
|
||||
from app.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)
|
||||
|
||||
|
||||
@@ -0,0 +1,538 @@
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
import pandas as pd
|
||||
import json
|
||||
from dotenv import load_dotenv
|
||||
from app.common.config_base import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
from app.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)
|
||||
@@ -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 app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
from app.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")
|
||||
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
# from general import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
|
||||
|
||||
|
||||
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_60')
|
||||
# password=os.getenv('HOST_60_PASS')
|
||||
|
||||
# host=os.getenv('HOST_80')
|
||||
# password=os.getenv('HOST_80_PASS')
|
||||
|
||||
|
||||
print(host)
|
||||
# print(password)
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
|
||||
|
||||
elastic.createIndex("gn_log_action", '', "gn_log_action" )
|
||||
|
||||
def meta_to_meta_action(elastic, index_name_i, index_name_o):
|
||||
try:
|
||||
try:
|
||||
body={}
|
||||
list_data = elastic.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
lst = list(list_data)
|
||||
index = 0
|
||||
percent_prev = 0
|
||||
# text_normal = TextNormalizer()
|
||||
prev_user_id = 0
|
||||
prev_content = ''
|
||||
prev_data={}
|
||||
update = False
|
||||
for mentry in lst:
|
||||
#print(mentry)
|
||||
|
||||
index += 1
|
||||
percent = int((index / len(lst)) * 100)
|
||||
if percent != percent_prev:
|
||||
print("progress -> %.2f %%" % percent)
|
||||
percent_prev = percent
|
||||
|
||||
|
||||
id = mentry["id"]
|
||||
entry = mentry["source"]
|
||||
|
||||
|
||||
meta = entry.get("meta", [])
|
||||
meta_action={}
|
||||
for m in meta:
|
||||
meta_action[m["key"]] = m["value"]
|
||||
|
||||
data = entry
|
||||
data["meta_action"]= meta_action
|
||||
|
||||
|
||||
eid = id
|
||||
try:
|
||||
resp = elastic.update_index_doc(update, index_name_o, eid, data)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
def refactorLogSearch(elastic, index_name_i, index_name_o):
|
||||
try:
|
||||
try:
|
||||
body={
|
||||
"sort":{
|
||||
"userid": {"order": "asc"},
|
||||
"query_String.keyword": {"order": "asc"},
|
||||
"time": {"order": "desc"}
|
||||
}
|
||||
}
|
||||
list_data = elastic.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
lst = list(list_data)
|
||||
index = 0
|
||||
percent_prev = 0
|
||||
# text_normal = TextNormalizer()
|
||||
prev_user_id = 0
|
||||
prev_content = ''
|
||||
prev_data={}
|
||||
update = False
|
||||
for mentry in lst:
|
||||
#print(mentry)
|
||||
|
||||
index += 1
|
||||
percent = int((index / len(lst)) * 100)
|
||||
if percent != percent_prev:
|
||||
print("progress -> %.2f %%" % percent)
|
||||
percent_prev = percent
|
||||
|
||||
|
||||
id = mentry["id"]
|
||||
entry = mentry["source"]
|
||||
|
||||
|
||||
user_id = entry.get("userid", "")
|
||||
content = entry.get("query_String", "").strip()
|
||||
if not content :
|
||||
continue
|
||||
content = content.strip("\", ")
|
||||
id_click = entry.get("id_click", "")
|
||||
time_edit = round(float(entry.get("time", ""))/1000)
|
||||
ip = entry.get("id", "")
|
||||
facet = entry.get("facet", "")
|
||||
os_version = entry.get("os_version", "")
|
||||
browser = entry.get("browser", "")
|
||||
action_key = "normal"
|
||||
ref_key="none"
|
||||
values=[]
|
||||
meta={}
|
||||
if id_click :
|
||||
value ={
|
||||
"id" : id_click,
|
||||
"type": "click",
|
||||
"value": 1
|
||||
}
|
||||
values.append(value)
|
||||
|
||||
meta["ip"] = ip
|
||||
|
||||
if facet :
|
||||
meta["filter"] = facet
|
||||
|
||||
if browser :
|
||||
meta["browser"] = browser
|
||||
|
||||
if os_version :
|
||||
meta["os"] = os_version
|
||||
|
||||
if prev_user_id == user_id and prev_content == content :
|
||||
values = prev_data["values"]
|
||||
if id_click :
|
||||
founded = False
|
||||
i = 0
|
||||
for value in values :
|
||||
if value["id"] == id_click :
|
||||
founded = True
|
||||
value["value"] = value["value"] + 1
|
||||
values[i] = value
|
||||
break
|
||||
i +=1
|
||||
if not founded :
|
||||
values.append(
|
||||
{
|
||||
"id" : id_click,
|
||||
"type": "click",
|
||||
"value": 1
|
||||
})
|
||||
|
||||
prev_data["values"] = values
|
||||
continue
|
||||
|
||||
elif prev_data and prev_data["id"] :
|
||||
eid = prev_data["id"]
|
||||
try:
|
||||
resp = elastic.update_index_doc(update, index_name_o, eid, prev_data)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
prev_data = {}
|
||||
|
||||
|
||||
data = {}
|
||||
data["id"]= id
|
||||
data["content"]= content
|
||||
data["user_id"]= user_id
|
||||
data["time_edit"]= time_edit
|
||||
data["action_key"]= action_key
|
||||
data["ref_key"]= ref_key
|
||||
data["values"]= values
|
||||
data["meta_action"]= meta
|
||||
|
||||
prev_data = data
|
||||
prev_user_id = user_id
|
||||
prev_content = content
|
||||
|
||||
|
||||
if prev_data :
|
||||
eid = prev_data["id"]
|
||||
try:
|
||||
resp = elastic.update_index_doc(update, index_name_o, eid, prev_data)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
def refactorLogSearch_0(elastic, index_name_i, index_name_o):
|
||||
try:
|
||||
try:
|
||||
body={
|
||||
"sort":{
|
||||
"userid": {"order": "asc"},
|
||||
"query_String.keyword": {"order": "asc"},
|
||||
"time": {"order": "desc"}
|
||||
}
|
||||
}
|
||||
list_data = elastic.es_iterate_all_documents(index_name_i, body)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
lst = list(list_data)
|
||||
index = 0
|
||||
percent_prev = 0
|
||||
# text_normal = TextNormalizer()
|
||||
prev_user_id = 0
|
||||
prev_content = ''
|
||||
prev_data={}
|
||||
update = False
|
||||
for mentry in lst:
|
||||
#print(mentry)
|
||||
|
||||
index += 1
|
||||
percent = int((index / len(lst)) * 100)
|
||||
if percent != percent_prev:
|
||||
print("progress -> %.2f %%" % percent)
|
||||
percent_prev = percent
|
||||
|
||||
|
||||
id = mentry["id"]
|
||||
entry = mentry["source"]
|
||||
|
||||
|
||||
user_id = entry.get("userid", "")
|
||||
content = entry.get("query_String", "").strip()
|
||||
if not content :
|
||||
continue
|
||||
content = content.strip("\", ")
|
||||
id_click = entry.get("id_click", "")
|
||||
time_edit = round(float(entry.get("time", ""))/1000)
|
||||
ip = entry.get("id", "")
|
||||
facet = entry.get("facet", "")
|
||||
os_version = entry.get("os_version", "")
|
||||
browser = entry.get("browser", "")
|
||||
action_key = "normal"
|
||||
ref_key="none"
|
||||
values=[]
|
||||
meta=[]
|
||||
if id_click :
|
||||
value ={
|
||||
"id" : id_click,
|
||||
"type": "click",
|
||||
"value": 1
|
||||
}
|
||||
values.append(value)
|
||||
|
||||
ip_obj ={
|
||||
"key" : "ip",
|
||||
"value": ip
|
||||
}
|
||||
meta.append(ip_obj)
|
||||
|
||||
if facet :
|
||||
m ={
|
||||
"key" : "filter",
|
||||
"value": facet
|
||||
}
|
||||
meta.append(m)
|
||||
|
||||
if browser :
|
||||
m ={
|
||||
"key" : "browser",
|
||||
"value": browser
|
||||
}
|
||||
meta.append(m)
|
||||
|
||||
if os_version :
|
||||
m ={
|
||||
"key" : "os",
|
||||
"value": os_version
|
||||
}
|
||||
meta.append(m)
|
||||
|
||||
|
||||
if prev_user_id == user_id and prev_content == content :
|
||||
values = prev_data["values"]
|
||||
if id_click :
|
||||
founded = False
|
||||
i = 0
|
||||
for value in values :
|
||||
if value["id"] == id_click :
|
||||
founded = True
|
||||
value["value"] = value["value"] + 1
|
||||
values[i] = value
|
||||
break
|
||||
i +=1
|
||||
if not founded :
|
||||
values.append(
|
||||
{
|
||||
"id" : id_click,
|
||||
"type": "click",
|
||||
"value": 1
|
||||
})
|
||||
|
||||
prev_data["values"] = values
|
||||
continue
|
||||
|
||||
elif prev_data and prev_data["id"] :
|
||||
eid = prev_data["id"]
|
||||
try:
|
||||
resp = elastic.update_index_doc(update, index_name_o, eid, prev_data)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
prev_data = {}
|
||||
|
||||
|
||||
data = {}
|
||||
data["id"]= id
|
||||
data["content"]= content
|
||||
data["user_id"]= user_id
|
||||
data["time_edit"]= time_edit
|
||||
data["action_key"]= action_key
|
||||
data["ref_key"]= ref_key
|
||||
data["values"]= values
|
||||
data["meta"]= meta
|
||||
|
||||
prev_data = data
|
||||
prev_user_id = user_id
|
||||
prev_content = content
|
||||
|
||||
|
||||
if prev_data :
|
||||
eid = prev_data["id"]
|
||||
try:
|
||||
resp = elastic.update_index_doc(update, index_name_o, eid, prev_data)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
|
||||
#refactorLogSearch(elastic, "gn_log_search", "gn_log_action")
|
||||
meta_to_meta_action(elastic, "gn_log_action", "gn_log_action")
|
||||
@@ -0,0 +1,74 @@
|
||||
بیخبر بیخبر
|
||||
بیتوجهی بیتوجهی
|
||||
بیطرفانه بیطرفانه
|
||||
گفتوگو گفتوگو
|
||||
آنها آنها
|
||||
پیشبرد پیشبرد
|
||||
روانشناختی روانشناختی
|
||||
میباشد میباشد
|
||||
لذتبخش لذتبخش
|
||||
میدادند میدادند
|
||||
مینویسد مینویسد
|
||||
میبخشد میبخشد
|
||||
بیقاعده بیقاعده
|
||||
میباشند میباشند
|
||||
موافقتنامه موافقتنامه
|
||||
تخمگذار تخمگذار
|
||||
پایینترین پایینترین
|
||||
گرمکن گرمکن
|
||||
پیشبینی پیشبینی
|
||||
برونگرا برونگرا
|
||||
میدهد میدهد
|
||||
فیلمبرداری فیلمبرداری
|
||||
آنسوی آنسوی
|
||||
خدمتدهی خدمتدهی
|
||||
اینگونه اینگونه
|
||||
کمکرسانی کمکرسانی
|
||||
کلانشهر کلانشهر
|
||||
سپردهگذار سپردهگذار
|
||||
بنیانگذار بنیانگذار
|
||||
رضایتبخش رضایتبخش
|
||||
اصلاحطلبان اصلاحطلبان
|
||||
استخوانبندی استخوانبندی
|
||||
درونگرا درونگرا
|
||||
میگردد میگردد
|
||||
اصلاحطلب اصلاحطلب
|
||||
میتوان میتوان
|
||||
عملکرد عملکرد
|
||||
میروم میروم
|
||||
بزرگنمایی بزرگنمایی
|
||||
همجنس همجنس
|
||||
همانطور همانطور
|
||||
بیشترین بیشترین
|
||||
انسانگرایی انسانگرایی
|
||||
نمیباشند نمیباشند
|
||||
جانبداری جانبداری
|
||||
نمیتوانی نمیتوانی
|
||||
قانونگذار قانونگذار
|
||||
میشدند میشدند
|
||||
تفاهمنامه تفاهمنامه
|
||||
آسیبپذیر آسیبپذیر
|
||||
برونگرایی برونگرایی
|
||||
جفتگیری جفتگیری
|
||||
گرانبها گرانبها
|
||||
میشوند میشوند
|
||||
کلاهبرداری کلاهبرداری
|
||||
جهتیابی جهتیابی
|
||||
چشمپوشی چشمپوشی
|
||||
بنیانگذاران بنیانگذاران
|
||||
میکند میکند
|
||||
الهامبخش الهامبخش
|
||||
وقتگیر وقتگیر
|
||||
پسلرزه پسلرزه
|
||||
میکنند میکنند
|
||||
میتواند میتواند
|
||||
آرامبخش آرامبخش
|
||||
بینام بینام
|
||||
غربزدگی غربزدگی
|
||||
بیتفاوت بیتفاوت
|
||||
بیثباتی بیثباتی
|
||||
پاسخگویی پاسخگویی
|
||||
میگیرد میگیرد
|
||||
جمعبندی جمعبندی
|
||||
میشود میشود
|
||||
میکنیم میکنیم
|
||||
@@ -0,0 +1,112 @@
|
||||
مهماننوازی مهماننوازی
|
||||
صلیالله صلیالله
|
||||
موافقتنامه موافقتنامه
|
||||
اعتراضآمیز اعتراضآمیز
|
||||
رییسجمهور رییسجمهور
|
||||
چشمپوشی چشمپوشی
|
||||
هیئتعلمی هیئتعلمی
|
||||
الزامآور الزامآور
|
||||
بیمهنامه بیمهنامه
|
||||
آییننامه آییننامه
|
||||
بتنریزی بتنریزی
|
||||
تشییعجنازه تشییعجنازه
|
||||
تامینکنندگان تامینکنندگان
|
||||
پرسشنامه پرسشنامه
|
||||
تحتالشعاع تحتالشعاع
|
||||
شگفتانگیز شگفتانگیز
|
||||
بزرگنمایی بزرگنمایی
|
||||
نیمههادی نیمههادی
|
||||
قابلکنترل قابلکنترل
|
||||
روانپزشکی روانپزشکی
|
||||
ضربالمثل ضربالمثل
|
||||
اضافهکاری اضافهکاری
|
||||
اختلافنظر اختلافنظر
|
||||
بینالملل بینالملل
|
||||
یکطرفه یکطرفه
|
||||
موجشکن موجشکن
|
||||
عزتنفس عزتنفس
|
||||
بیسیم بیسیم
|
||||
شیبدار شیبدار
|
||||
دستیابی دستیابی
|
||||
روانشناختی روانشناختی
|
||||
عقبنشینی عقبنشینی
|
||||
بهطور بهطور
|
||||
خطچین خطچین
|
||||
ادراکشده ادراکشده
|
||||
خزانهداری خزانهداری
|
||||
شیمیدرمانی شیمیدرمانی
|
||||
آنسوی آنسوی
|
||||
نقطهچین نقطهچین
|
||||
منحصربهفرد منحصربهفرد
|
||||
درحالتوسعه درحالتوسعه
|
||||
رضایتبخش رضایتبخش
|
||||
قرضالحسنه قرضالحسنه
|
||||
هرجومرج هرجومرج
|
||||
سیبزمینی سیبزمینی
|
||||
میلیگرم میلیگرم
|
||||
نخستوزیر نخستوزیر
|
||||
تعیینکنندهای تعیینکنندهای
|
||||
طاقتفرسا طاقتفرسا
|
||||
قابلمشاهده قابلمشاهده
|
||||
بهوسیله بهوسیله
|
||||
قابلدستیابی قابلدستیابی
|
||||
الهامبخش الهامبخش
|
||||
پیدرپی پیدرپی
|
||||
سرمایهداری سرمایهداری
|
||||
لذتبخش لذتبخش
|
||||
تخمگذار تخمگذار
|
||||
گرمکن گرمکن
|
||||
قابلتوجهی قابلتوجهی
|
||||
فیلمبرداری فیلمبرداری
|
||||
خدمتدهی خدمتدهی
|
||||
معنیدار معنیدار
|
||||
کلانشهری کلانشهری
|
||||
گواهینامه گواهینامه
|
||||
همجنس همجنس
|
||||
همانطور همانطور
|
||||
سیستمعامل سیستمعامل
|
||||
حملونقل حملونقل
|
||||
تفاهمنامه تفاهمنامه
|
||||
بینالمللی بینالمللی
|
||||
کلاهبرداری کلاهبرداری
|
||||
نرمافزار نرمافزار
|
||||
مضافالیه مضافالیه
|
||||
قطعنامهای قطعنامهای
|
||||
پاسخگویی پاسخگویی
|
||||
عکسبرداری عکسبرداری
|
||||
پسلرزه پسلرزه
|
||||
خردهفروشی خردهفروشی
|
||||
حقوقبشر حقوقبشر
|
||||
تحلیلگران تحلیلگران
|
||||
اینگونه اینگونه
|
||||
صرفهجویی صرفهجویی
|
||||
علیالخصوص علیالخصوص
|
||||
کلانشهرها کلانشهرها
|
||||
حاصلضرب حاصلضرب
|
||||
اطلاعرسانی اطلاعرسانی
|
||||
دندانپزشکی دندانپزشکی
|
||||
پیشبرد پیشبرد
|
||||
ایدهال ایدهال
|
||||
هیچگاه هیچگاه
|
||||
صنایعدستی صنایعدستی
|
||||
سانتیمتر سانتیمتر
|
||||
پیشبینی پیشبینی
|
||||
خلیجفارس خلیجفارس
|
||||
تاریخنگاری تاریخنگاری
|
||||
هیچگونه هیچگونه
|
||||
راهاندازی راهاندازی
|
||||
جستوجوی جستوجوی
|
||||
حاشیهنشینی حاشیهنشینی
|
||||
رنگآمیزی رنگآمیزی
|
||||
جمعآوری جمعآوری
|
||||
وقتگیر وقتگیر
|
||||
آرامبخش آرامبخش
|
||||
غربزدگی غربزدگی
|
||||
کلانشهر کلانشهر
|
||||
نرمافزاری نرمافزاری
|
||||
بدینوسیله بدینوسیله
|
||||
جمعبندی جمعبندی
|
||||
گفتوگو گفتوگو
|
||||
حملونقل حملونقل
|
||||
آیتالله آیتالله
|
||||
حجتالاسلام حجتالاسلام
|
||||
@@ -0,0 +1,5 @@
|
||||
حملونقل حملونقل
|
||||
حجتالاسلاموالمسلمین حجتالاسلاموالمسلمین
|
||||
آیتاللهالعظمی آیتاللهالعظمی
|
||||
گفتوگو گفتوگو
|
||||
حملونقل حملونقل
|
||||
@@ -0,0 +1,127 @@
|
||||
آداب ادب
|
||||
اطراف طرف
|
||||
حقایق حقیقت
|
||||
امواج موج
|
||||
ادبا ادیب
|
||||
اعماق عمق
|
||||
خزائن خزینه
|
||||
مراکز مرکز
|
||||
آثار اثر
|
||||
علما عالم
|
||||
اخبار خبر
|
||||
مواقع موقع
|
||||
اسرا سر
|
||||
علوم علم
|
||||
ادوار دور
|
||||
مصارف مصرف
|
||||
اسامی اسم
|
||||
علائم علامت
|
||||
ادیان دین
|
||||
معارف معرفت
|
||||
اساطیر اسطوره
|
||||
علل علت
|
||||
دفاتر دفتر
|
||||
مباحث مبحث
|
||||
امرا امیر
|
||||
عقائد عقیده
|
||||
ذخایر ذخیره
|
||||
مواد ماده
|
||||
اوامر امور
|
||||
اعمال عمل
|
||||
رفقا رفیق
|
||||
مذاهب مذهب
|
||||
ائمه امام
|
||||
اعیاد عید
|
||||
آرا رای
|
||||
مصائب مصیبت
|
||||
اصول اصل
|
||||
عناصر عنصر
|
||||
رسوم رسم
|
||||
معابد معبد
|
||||
آفاق افق
|
||||
عواطف عاطفه
|
||||
روابط رابطه
|
||||
مساجد مسجد
|
||||
ابیات بیت
|
||||
اعضا عضو
|
||||
رموز رمز
|
||||
معابر معبر
|
||||
تجار تاجر
|
||||
عبارات عبارت
|
||||
رجال رجل
|
||||
مظاهر مظهر
|
||||
تصاویر تصویر
|
||||
عجایب عجیبه
|
||||
ارقام رقم
|
||||
اجداد جد
|
||||
فقها فقیه
|
||||
زوایا زاویه
|
||||
امراض مرض
|
||||
جوانب جانب
|
||||
فنون فن
|
||||
زعما زعیم
|
||||
موارد موزد
|
||||
جزایر جزیره
|
||||
افکار فکر
|
||||
سوانح سانحه
|
||||
مراحل مرحله
|
||||
جبال جبل
|
||||
فرایض فریضه
|
||||
سلاطین سلطان
|
||||
مفاهیم مفهوم
|
||||
جرایم جریمه
|
||||
افعال فعل
|
||||
اشعار شعر
|
||||
منابع منبع
|
||||
حوادث حادثه
|
||||
فقرا فقیر
|
||||
شعرا شاعر
|
||||
اماکن مکان
|
||||
احشام حشم
|
||||
قواعد قاعده
|
||||
آثار اثر
|
||||
احوال حال
|
||||
اخلاق خلق
|
||||
ارکان رکن
|
||||
اسرار سر
|
||||
اشیا شی
|
||||
اصول اصل
|
||||
اعضا عضو
|
||||
افراد فرد
|
||||
افکار فکر
|
||||
اقوام قوم
|
||||
اوقات وقت
|
||||
تصاویر تصویر
|
||||
تعالیم تعلیم
|
||||
تماثیل تمثیل
|
||||
حقوق حق
|
||||
حواس حس
|
||||
خاطرات خاطره
|
||||
خرافات خارفه
|
||||
دلایل دلیل
|
||||
شمایل شمیله
|
||||
عناصر عنصر
|
||||
عوامل عامل
|
||||
فضایل فضیلت
|
||||
کلمات کلمه
|
||||
مجالس مجلس
|
||||
مطالب مطلب
|
||||
مظاهر مظهره
|
||||
مفاهیم مفهوم
|
||||
منابع منبع
|
||||
نشریات نشریه
|
||||
نیّات نیت
|
||||
وظایف وظیفه
|
||||
فلاسفه فلاس
|
||||
مذاکرات مذاکره
|
||||
معاملات معامله
|
||||
ادارات اداره
|
||||
ضربات ضربه
|
||||
حملات حمله
|
||||
جزِئیات جزء
|
||||
دخانیات دخان
|
||||
شایعات شایعه
|
||||
عنایات عنایت
|
||||
اموال مال
|
||||
مدارس مدرسه
|
||||
جوامع جامعه
|
||||
@@ -0,0 +1,31 @@
|
||||
نده
|
||||
گانه
|
||||
دان
|
||||
ستان
|
||||
چی
|
||||
زار
|
||||
گار
|
||||
ناک
|
||||
گین
|
||||
انه
|
||||
یار
|
||||
مند
|
||||
کده
|
||||
یت
|
||||
یش
|
||||
یمان
|
||||
یشان
|
||||
یتان
|
||||
گر
|
||||
باره
|
||||
آگین
|
||||
سان
|
||||
گون
|
||||
الو
|
||||
واره
|
||||
گی
|
||||
یی
|
||||
ای
|
||||
تر
|
||||
ترین
|
||||
ی
|
||||
@@ -0,0 +1,9 @@
|
||||
#پیشوند
|
||||
نا
|
||||
پاد
|
||||
باز
|
||||
وا
|
||||
فرا
|
||||
فرو
|
||||
پیش
|
||||
بی
|
||||
@@ -0,0 +1,103 @@
|
||||
آزمود آزما
|
||||
انداخت انداز
|
||||
آزرد آزار
|
||||
اندود اندا
|
||||
آسود آسا
|
||||
انگاشت انگار
|
||||
آشفت آشوب
|
||||
انگیخت انگیز
|
||||
آغشت آغار
|
||||
باخت باز
|
||||
آفرید آفرین
|
||||
بخشید بخش
|
||||
بخشود بخشا
|
||||
برد بر
|
||||
آمد آ
|
||||
بست بند
|
||||
آموخت آموز
|
||||
بود باش
|
||||
آمیخت آمیز
|
||||
بیخت بیز
|
||||
آورد آور
|
||||
پالود پالا
|
||||
آویخت آویز
|
||||
پخت پز
|
||||
پذیرفت پذیر
|
||||
پرداخت پرداز
|
||||
افراشت افراز
|
||||
پنداشت پندار
|
||||
افروخت افروز
|
||||
پیمود پیما
|
||||
افزود افزا
|
||||
پیوست پیوند
|
||||
افشرد افشار
|
||||
تاخت تاز
|
||||
انباشت انباز
|
||||
تافت تاب
|
||||
توخت توز
|
||||
ساخت ساز
|
||||
جست جه
|
||||
سپرد سپار
|
||||
چید چین
|
||||
ستاند ستان
|
||||
جست جو
|
||||
ستود ستا
|
||||
خاست خیز
|
||||
سرود سرا
|
||||
خفت خواب
|
||||
سفت سنب
|
||||
داد ده
|
||||
سوخت سوز
|
||||
داشت دار
|
||||
شتافت شتاب
|
||||
دانست دان
|
||||
شد شو
|
||||
دروید درو
|
||||
شست شوی
|
||||
دوخت دوز
|
||||
شكست شكن
|
||||
دوشید دوش
|
||||
شمرد شمر
|
||||
دید بین
|
||||
شناخت شناس
|
||||
ربود ربا
|
||||
رست ره
|
||||
شنید شنو
|
||||
رشت ریس
|
||||
فرمود فرما
|
||||
رفت روب
|
||||
رفت رو
|
||||
فروخت فروش
|
||||
فریفت فریب
|
||||
زد زن
|
||||
فشرد فشار
|
||||
زدود زدا
|
||||
كاست كاه
|
||||
كاشت كار
|
||||
گشت گرد
|
||||
كرد كن
|
||||
گشود گشا
|
||||
کشت کار
|
||||
گفت گو
|
||||
كوفت كوب
|
||||
گماشت گمار
|
||||
گداخت گداز
|
||||
مرد میر
|
||||
گذاشت گذار
|
||||
نگاشت نگار
|
||||
گرفت گیر
|
||||
نواخت نواز
|
||||
گریخت گریز
|
||||
نمود نما
|
||||
گزید گزین
|
||||
هشت هل
|
||||
گسست گسل
|
||||
یافت یاب
|
||||
گسیخت گسل
|
||||
کرد کن
|
||||
داشت دار
|
||||
چلاند چل
|
||||
خورد خور
|
||||
سپرد سپار
|
||||
گذشت گذر
|
||||
خیساند خیسان
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,343 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
# from general import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
from for_ai.create_relation_tags import *
|
||||
from temp_refactor_gn_dataset import *
|
||||
|
||||
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')
|
||||
|
||||
# host=os.getenv('HOST_118')
|
||||
# password=os.getenv('HOST_118_PASS')
|
||||
|
||||
# host=os.getenv('HOST_60')
|
||||
# password=os.getenv('HOST_60_PASS')
|
||||
|
||||
# host=os.getenv('HOST_161')
|
||||
# password=os.getenv('HOST_161_PASS')
|
||||
|
||||
# host=os.getenv('HOST_80')
|
||||
# password=os.getenv('HOST_80_PASS')
|
||||
|
||||
# host=os.getenv('HOST_133')
|
||||
# password=os.getenv('HOST_133_PASS')
|
||||
|
||||
|
||||
print(host)
|
||||
# print(password)
|
||||
|
||||
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
|
||||
elastic = ElasticHelper(host, password, "elastic", path_base_map)
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/haditha", "dh_volume")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/haditha", "dh_haditha")
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_domain")
|
||||
# elastic.createIndex( 'mj_qa_domain', 'majles', 'mj_domain')
|
||||
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_domain.zip', 'mj_qa_domain', 'majles', False, 'mj_domain')
|
||||
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section-m1")
|
||||
# elastic.createIndex( 'mj_qa_section-m1', 'majles', 'mj_qa_section')
|
||||
# elastic.restorFileToElastic2('G:/Project2/111/server112/mj_qa_section-m1.zip', 'mj_qa_section-m1', 'majles', False, 'mj_qa_section')
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_calendar")
|
||||
#elastic.createIndex( 'gn_calendar', 'general', 'gn_calendar')
|
||||
#elastic.restorFileToElastic2('G:/Project2/111/gn_calendar.zip', 'gn_calendar', 'general', False, 'gn_calendar')
|
||||
|
||||
# elastic.createIndex( 'gn_synonym', 'general', 'gn_synonym')
|
||||
# elastic.restorFileToElastic2('G:/Project2/111/server112/gn_synonym.zip', 'gn_synonym', 'general', False, 'gn_synonym')
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "mn_sanad")
|
||||
# elastic.createIndex( 'mn_sanad', 'monir', 'mn_sanad')
|
||||
# elastic.restorFileToElastic2('G:/Project2/111/mn_sanad.zip', 'mn_sanad', 'monir', False, 'mn_sanad')
|
||||
|
||||
|
||||
elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
|
||||
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section.zip', 'mj_qa_section', 'majles', False, 'mj_qa_section')
|
||||
# elastic.restorFileToElastic2('G:/Project2/111/gn_setting.zip', 'gn_setting', 'general', False, 'gn_setting')
|
||||
#-------------------------------------------------------
|
||||
##
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "dh_haditha")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "dh_parag_bge")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_dataset")
|
||||
#elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
|
||||
#elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section_ai")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "mn_crition")
|
||||
#moveDataset1(elastic, "G:/Project2/111/gn_dataset_14031125.zip", "gn_dataset2")
|
||||
|
||||
#-------------------------------------------------------
|
||||
## backup from hamfahmi.ir
|
||||
#-------------------------------------------------------
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_bayanat")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_synonym")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_log_search")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_log_change")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_calendar") # ???
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_entity")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_setting")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "gn_research") # ???
|
||||
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_jahat")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_crition")
|
||||
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_sanad") # ???
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_steps") # ???
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111/server3", "mn_nesha")
|
||||
|
||||
#-------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
#-------------------------------------------------------
|
||||
## backup from 160
|
||||
#-------------------------------------------------------
|
||||
path_back = 'G:/Project2/111/server112/'
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_log_change")
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_log_action")
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_log_search")
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_dataset")
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_setting")
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_bayanat")
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_entity")
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_research")
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_synonym")
|
||||
|
||||
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_mashruh")
|
||||
# elastic.backupIndexToZipfile(path_back, "qanonindex")
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_qa_section")
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_qa_opinion")
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_rg_section")
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_qa_qanon")
|
||||
############elastic.backupIndexToZipfile(path_back, "rrk_index")
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_df_qanon")
|
||||
######elastic.backupIndexToZipfile(path_back, "mj_qa_qanon_ai")
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_qa_section_ai")
|
||||
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_qa_section-m1")
|
||||
# elastic.backupIndexToZipfile(path_back, "gn_setting_help")
|
||||
|
||||
# gn_version
|
||||
# mj_tmp_qanon
|
||||
# gn_dataset2
|
||||
# gn_setting2
|
||||
|
||||
#-------------------------------------------------------
|
||||
|
||||
#-------------------------------------------------------
|
||||
##
|
||||
|
||||
# ## کد نمونه بازیابی از فایل
|
||||
# path_back = 'G:/Project2/111/mj_qa_section.zip'
|
||||
# elastic.createIndex('mj_qa_section', 'majles', 'mj_qa_section')
|
||||
# elastic.zipFileToElastic(path_back, 'mj_qa_section')
|
||||
|
||||
#selastic.backupIndexToZipfile("G:/Project2/111", "dh_haditha")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_calendar")
|
||||
|
||||
#elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section")
|
||||
# elastic.backupIndexToZipfile("G:/Project2/111", "dh_haditha")
|
||||
#elastic.backupIndexToZipfile("G:/Project2/111", "dh_volume_temp")
|
||||
#elastic.restorFileToElastic("G:/Project2/111", "mj_qa_section_ai", 'majles', True, "mj_qa_section")
|
||||
|
||||
#elastic.restorFileToElastic('G:/Project2/111', 'mj_model', 'majles', True, 'mj_model' )
|
||||
# elastic.restorFileToElastic2('G:/Project2/111/mj_model_20250512-003003.zip', 'mj_model', 'majles', True, 'mj_model')
|
||||
# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section_2_majles_repair.zip', 'mj_qa_section', 'majles', False, 'mj_qa_section')
|
||||
|
||||
|
||||
# body= {
|
||||
# "query": {
|
||||
# "terms": {
|
||||
# "qanon_id": [
|
||||
# "qq83354",
|
||||
# "qq83382",
|
||||
# "qq112748",
|
||||
# "qq112296",
|
||||
# "qq83435",
|
||||
# "qq114127",
|
||||
# "qq175888",
|
||||
# "qq85335",
|
||||
# "qq84208",
|
||||
# "qq114652",
|
||||
# "qq114640"
|
||||
# ]
|
||||
# }
|
||||
# },
|
||||
# "sort": [
|
||||
# {
|
||||
# "qanon_id": {
|
||||
# "order": "asc"
|
||||
# },
|
||||
# "child_order": {
|
||||
# "order": "asc"
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# }
|
||||
|
||||
#elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section", "mj_qa_section_Aab", body, False, ["content", "simplifies", "tcode_sub_old", "tcode_main_old", "code-ai", "ai_keywords"])
|
||||
|
||||
#-------------------------------------------------------
|
||||
#### فایده ای نداشت ....!!!
|
||||
## مسیر درختی مفید تولید نشد و عنوان قانون هم که فیلد مجزا داریم !
|
||||
# create_context_ai(elastic, "mj_qa_section" )
|
||||
|
||||
#-------------------------------------------------------
|
||||
##
|
||||
|
||||
#ai_url_chunk = os.getenv("ai_url_chunk")
|
||||
#fill_chunk_tags(elastic, ai_url_chunk, "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'])
|
||||
|
||||
#-------------------------------------------------------
|
||||
##
|
||||
|
||||
## پشتیبان گیری
|
||||
|
||||
# path_back = os.getcwd() + '/data_back'
|
||||
path_back = 'G:/Project2/111'
|
||||
# if not os.path.exists(path_back) :
|
||||
# os.makedirs(path_back)
|
||||
# print('---> path_back = ' + path_back)
|
||||
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_qa_qanon")
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_qa_section")
|
||||
# elastic.backupIndexToZipfile(path_back, "mj_qa_section", '', {}, True, [], ["pos_tags", "chunk_tags", "version_info"])
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_qa_section_ai")
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_rg_section")
|
||||
#elastic.backupIndexToZipfile(path_back, "mj_qa_opinion")
|
||||
|
||||
## کد نمونه بازیابی از فایل
|
||||
# path_back = 'G:/Project2/_back/back_data/data_majles/elastic/v1.0/full'
|
||||
# elastic.restorFileToElastic(path_back, 'mj_qa_section', 'majles')
|
||||
|
||||
# elastic.restorFileToElastic(path_back, 'gn_log_action')
|
||||
|
||||
|
||||
#-------------------------------------------------------
|
||||
##
|
||||
|
||||
#-------------------------------------------------------
|
||||
##
|
||||
|
||||
|
||||
#-------------------------------------------------------
|
||||
# -- جهت استخراج دیتاست بخشی از الاستیک برای استفاده در هوش مصنوعی
|
||||
body= {
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"bool": {
|
||||
"must_not": [
|
||||
{
|
||||
"terms": {
|
||||
"nlp_tags": [
|
||||
"concept_no"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"exists": {
|
||||
"field": "ai_keywords"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"bool": {
|
||||
"filter": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"terms": {
|
||||
"qanon_etebar": [
|
||||
"",
|
||||
"معتبر"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"terms": {
|
||||
"title_type": [
|
||||
"عادی",
|
||||
"اصلی",
|
||||
"موافقتنامه",
|
||||
"بودجه"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
# elastic.exportToJsonForAI("./data/", "mj_qa_section", "keywords_extract_40K", body, ["content"])
|
||||
|
||||
# body={
|
||||
# "query": {
|
||||
# "term": {
|
||||
# "main_type": {
|
||||
# "value": "قانون"
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
#elastic.exportToJsonForAI("./data/", "mj_qa_qanon", "qanon_title", body, ["title", "ts_date", "ts_year"])
|
||||
|
||||
# body={
|
||||
# "query": {
|
||||
# "term": {
|
||||
# "main_type": {
|
||||
# "value": "مقرره"
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
#elastic.exportToJsonForAI("./data/", "mj_qa_qanon", "regular_title", body, ["title", "ts_date", "ts_year"])
|
||||
|
||||
|
||||
#-------------------------------------------------------
|
||||
|
||||
print("finished")
|
||||
@@ -0,0 +1,102 @@
|
||||
import os
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
# from general import *
|
||||
from app.common.general_functions import *
|
||||
from app.common.elastic_helper import ElasticHelper
|
||||
|
||||
|
||||
|
||||
def moveDataset1(elastic, file, index_name_o):
|
||||
try:
|
||||
try:
|
||||
list_data = elastic.iterateJsonFile(file)
|
||||
except Exception as e:
|
||||
save_error(0, e)
|
||||
|
||||
lst = list(list_data)
|
||||
index = 0
|
||||
percent_prev = 0
|
||||
text_normal = TextNormalizer()
|
||||
dict_order={}
|
||||
for mentry in lst:
|
||||
#print(mentry)
|
||||
|
||||
index += 1
|
||||
percent = int((index / len(lst)) * 100)
|
||||
if percent != percent_prev:
|
||||
print("progress -> %.2f %%" % percent)
|
||||
percent_prev = percent
|
||||
|
||||
|
||||
entry = mentry["source"]
|
||||
id = entry.get("id", "")
|
||||
content = entry.get("content", "")
|
||||
domain = entry.get("domain", "")
|
||||
order = entry.get("order", "")
|
||||
time_edit = entry.get("timestamp", "")
|
||||
user_create = entry.get("user_create", "")
|
||||
users = entry.get("user_show", [])
|
||||
result_objects = entry.get("result_objects", [])
|
||||
meta = entry.get("meta", [])
|
||||
group_key=domain
|
||||
ref_info = {
|
||||
"url" : entry.get("ref_url", ""),
|
||||
"key" : entry.get("ref_key", ""),
|
||||
"id" : entry.get("ref_id", "")
|
||||
}
|
||||
|
||||
if domain == 'تغییرات قانون':
|
||||
continue
|
||||
# elif domain == "استخراج کلیدواژه 11 هزارتایی":
|
||||
# group_key = "پیکره 11 هزارتایی قانون برای کلیدواژه"
|
||||
elif domain == "AI استخراج کلیدواژه" :
|
||||
group_key = "پیکره 7 هزار قوانین برای کلیداوژه"
|
||||
elif domain == "پیکره قوانین 480":
|
||||
group_key = "پیکره 480 هزار توکن قوانین"
|
||||
# elif domain == "استخراج کلیدواژه 15 هزارتایی":
|
||||
# group_key = "پیکره 15 هزار قانون برای کلیدواژه"
|
||||
#"پیکره آرمان
|
||||
#"پیکره پیما",
|
||||
#,
|
||||
if not order :
|
||||
if group_key in dict_order :
|
||||
order = dict_order[group_key]+1
|
||||
dict_order[group_key] = order
|
||||
else:
|
||||
dict_order[group_key] = 1
|
||||
order = 1
|
||||
|
||||
|
||||
results = []
|
||||
for item in result_objects :
|
||||
item["user_id"] = user_create
|
||||
item["time_edit"] = time_edit
|
||||
results.append(item)
|
||||
|
||||
#print(id)
|
||||
|
||||
#if len(users) == 0 :
|
||||
users.append(0) ## یعنی عمومی هست و همه می توانند ببینند
|
||||
users.append(user_create)
|
||||
|
||||
data = {}
|
||||
data["id"]= id
|
||||
data["content"]= content
|
||||
data["group_key"]= group_key
|
||||
data["order"]= order
|
||||
data["ref_info"]= ref_info
|
||||
data["time_edit"]= time_edit
|
||||
data["user_create"]= user_create
|
||||
data["users"]= users
|
||||
data["meta"]= meta
|
||||
data["result_objects"]= results
|
||||
update = False
|
||||
eid = id
|
||||
try:
|
||||
resp = elastic.update_index_doc(update, index_name_o, eid, data)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
|
||||
except Exception as e:
|
||||
save_error(id, e)
|
||||
@@ -0,0 +1,215 @@
|
||||
import os
|
||||
import re
|
||||
import pandas as pd
|
||||
from arabic_reshaper import reshape
|
||||
from bidi.algorithm import get_display
|
||||
from app.common.text_normalizer import TextNormalizer
|
||||
|
||||
text_normalizer = TextNormalizer()
|
||||
|
||||
|
||||
class ExcelToJsonConverter:
|
||||
"""
|
||||
کلاس برای تبدیل فایلهای اکسل به JSON با پشتیبانی از فارسی
|
||||
"""
|
||||
|
||||
def __init__(self, input_folder="data/tetebar", output_folder="data/json_output"):
|
||||
"""
|
||||
مقداردهی اولیه با مسیرهای پیشفرض
|
||||
"""
|
||||
self.base_folder = "data"
|
||||
self.excel_folder = input_folder
|
||||
self.output_folder = output_folder
|
||||
self.excel_files = []
|
||||
|
||||
def _display_persian_text(self, text):
|
||||
"""
|
||||
نمایش متن فارسی با شکل صحیح
|
||||
"""
|
||||
return get_display(reshape(text))
|
||||
|
||||
def _ensure_folders_exist(self):
|
||||
"""
|
||||
اطمینان از وجود پوشههای ورودی و خروجی
|
||||
"""
|
||||
os.makedirs(self.excel_folder, exist_ok=True)
|
||||
os.makedirs(self.output_folder, exist_ok=True)
|
||||
|
||||
def _find_excel_files(self):
|
||||
"""
|
||||
یافتن تمام فایلهای اکسل در پوشه ورودی
|
||||
"""
|
||||
try:
|
||||
self.excel_files = [f for f in os.listdir(self.excel_folder) if f.endswith(".xlsx")and not f.startswith("~$")]
|
||||
if not self.excel_files:
|
||||
print(self._display_persian_text("❌ هیچ فایل اکسلی در پوشه مشخص شده وجود ندارد."))
|
||||
return False
|
||||
return True
|
||||
except FileNotFoundError:
|
||||
print(self._display_persian_text(f"❌ پوشه اکسل یافت نشد. مسیر زیر وجود ندارد: {self.excel_folder}"))
|
||||
return False
|
||||
|
||||
def _display_file_list(self):
|
||||
"""
|
||||
نمایش لیست فایلهای پیدا شده
|
||||
"""
|
||||
print("\n" + self._display_persian_text("📄 لیست فایلهای اکسل پیدا شده:"))
|
||||
for idx, fname in enumerate(self.excel_files):
|
||||
print(self._display_persian_text(f"{idx + 1}. {fname}"))
|
||||
|
||||
def _get_user_choice(self):
|
||||
"""
|
||||
دریافت انتخاب کاربر برای تبدیل فایلها
|
||||
"""
|
||||
choice = input("\n" + self._display_persian_text(
|
||||
"آیا میخواهید همه فایلها را تبدیل کنید؟ (y/n): ") + " ").strip().lower()
|
||||
|
||||
if choice == "y":
|
||||
return self.excel_files
|
||||
|
||||
try:
|
||||
index_input = input(self._display_persian_text(
|
||||
"🔢 شماره فایل مورد نظر را وارد کنید: ") + " ")
|
||||
index = int(index_input) - 1
|
||||
if 0 <= index < len(self.excel_files):
|
||||
return [self.excel_files[index]]
|
||||
print(self._display_persian_text("❌ شماره وارد شده نامعتبر است."))
|
||||
return []
|
||||
except ValueError:
|
||||
print(self._display_persian_text("❌ ورودی نامعتبر است."))
|
||||
return []
|
||||
|
||||
def _parse_law_title_date(self, text):
|
||||
"""
|
||||
تجزیه عنوان قانون و تاریخ به title، date و other
|
||||
"""
|
||||
if pd.isna(text) or not isinstance(text, str):
|
||||
return {"title": "", "date": "", "other": ""}
|
||||
|
||||
# پاکسازی اولیه
|
||||
text = text.strip()
|
||||
|
||||
# الگوی regex برای یافتن تاریخ بعد از "مصوب"
|
||||
pattern = r'^(.*?)\s*[#]*\s*مصوب\s+([۰-۹٠-٩0-9\/\s]+)$'
|
||||
match = re.search(pattern, text, re.IGNORECASE | re.UNICODE)
|
||||
|
||||
if match:
|
||||
title_part = match.group(1).strip()
|
||||
date_part = re.sub(r'\s+', '', match.group(2)) # حذف تمام فاصلهها
|
||||
remaining = text[match.end():].strip()
|
||||
|
||||
# نرمالسازی تاریخ با استفاده از TextNormalizer
|
||||
normalized_date = text_normalizer.date_correction(date_part)
|
||||
|
||||
return {
|
||||
"title": title_part,
|
||||
"date": normalized_date,
|
||||
"other": remaining
|
||||
}
|
||||
|
||||
# اگر "مصوب" وجود نداشت ولی تاریخ داشت
|
||||
date_pattern = r'(\d{1,2}\/\s*\d{1,2}\/\s*\d{4})'
|
||||
date_match = re.search(date_pattern, text)
|
||||
if date_match:
|
||||
date_part = re.sub(r'\s+', '', date_match.group(1))
|
||||
title_part = text[:date_match.start()].strip()
|
||||
remaining = text[date_match.end():].strip()
|
||||
|
||||
return {
|
||||
"title": title_part,
|
||||
"date": date_part,
|
||||
"other": remaining
|
||||
}
|
||||
|
||||
# اگر هیچ تاریخی پیدا نشد
|
||||
return {
|
||||
"title": text,
|
||||
"date": "",
|
||||
"other": ""
|
||||
}
|
||||
|
||||
def _convert_file(self, excel_filename):
|
||||
"""
|
||||
تبدیل یک فایل اکسل به JSON با اصلاح فرمت اعداد و حذف فاصلههای اضافی
|
||||
"""
|
||||
try:
|
||||
excel_path = os.path.join(self.excel_folder, excel_filename)
|
||||
df = pd.read_excel(excel_path, header=0)
|
||||
|
||||
# --- مرحله 1: پاکسازی نام ستونها ---
|
||||
df.columns = df.columns.str.replace(r'[\u00A0\s]+', ' ', regex=True).str.strip()
|
||||
|
||||
# --- مرحله 2: پردازش ستون "ردیف" ---
|
||||
if 'ردیف' in df.columns:
|
||||
df['ردیف'] = df['ردیف'].astype(str).str.replace(r'[.\s]+', '', regex=True)
|
||||
df['ردیف'] = pd.to_numeric(df['ردیف'], errors='coerce')
|
||||
df['ردیف'] = df['ردیف'].fillna(method='ffill').astype(int)
|
||||
|
||||
# --- مرحله 3: پر کردن ستون "عنوان قانون" ---
|
||||
if "عنوان قانون و تاریخ تصویب" in df.columns:
|
||||
df["عنوان قانون و تاریخ تصویب"] = df["عنوان قانون و تاریخ تصویب"].replace('', pd.NA)
|
||||
df["عنوان قانون و تاریخ تصویب"] = df["عنوان قانون و تاریخ تصویب"].fillna(method='ffill')
|
||||
|
||||
if "عنوان قانون و تاریخ تصویب" in df.columns:
|
||||
parsed_data = df["عنوان قانون و تاریخ تصویب"].apply(self._parse_law_title_date)
|
||||
df["title"] = parsed_data.apply(lambda x: x["title"])
|
||||
df["date"] = parsed_data.apply(lambda x: x["date"])
|
||||
df["other"] = parsed_data.apply(lambda x: x["other"])
|
||||
df.drop(columns=["عنوان قانون و تاریخ تصویب"], inplace=True)
|
||||
# --- مرحله 4: پاکسازی تمام ستونهای متنی ---
|
||||
for col in df.select_dtypes(include='object').columns:
|
||||
df[col] = df[col].str.strip()
|
||||
df[col] = df[col].str.replace(r'\s+/', '/', regex=True)
|
||||
df[col] = df[col].str.replace(r'\s+', ' ', regex=True)
|
||||
|
||||
# --- مرحله 5: حذف ردیفهای کاملاً خالی ---
|
||||
df.dropna(how='all', inplace=True)
|
||||
df.fillna("", inplace=True)
|
||||
|
||||
# --- مرحله 6: تبدیل به JSON ---
|
||||
json_data = df.to_json(orient="records", force_ascii=False, indent=4)
|
||||
json_data = json_data.replace("\\/", "/")
|
||||
json_name = os.path.splitext(excel_filename)[0] + ".json"
|
||||
output_path = os.path.join(self.output_folder, json_name)
|
||||
|
||||
with open(output_path, "w", encoding="utf-8") as f:
|
||||
f.write(json_data)
|
||||
|
||||
return True, json_name
|
||||
|
||||
except Exception as e:
|
||||
print(self._display_persian_text(f"❌ خطا در پردازش فایل {excel_filename}: {str(e)}"))
|
||||
return False, None
|
||||
|
||||
def convert(self):
|
||||
"""
|
||||
فرآیند اصلی تبدیل فایلها
|
||||
"""
|
||||
self._ensure_folders_exist()
|
||||
|
||||
if not self._find_excel_files():
|
||||
return
|
||||
|
||||
self._display_file_list()
|
||||
files_to_process = self._get_user_choice()
|
||||
|
||||
if not files_to_process:
|
||||
return
|
||||
|
||||
print("\n" + self._display_persian_text("🔄 در حال پردازش فایل(های) انتخابی..."))
|
||||
|
||||
success_count = 0
|
||||
for fname in files_to_process:
|
||||
success, json_name = self._convert_file(fname)
|
||||
if success:
|
||||
print(self._display_persian_text(f"✅ فایل {fname} به {json_name} تبدیل شد."))
|
||||
success_count += 1
|
||||
|
||||
if success_count > 0:
|
||||
print("\n" + self._display_persian_text("🎉 تمامی فرآیندها با موفقیت انجام شد."))
|
||||
print(self._display_persian_text(f"📁 فایل(های) JSON در این مسیر قرار دارند: {self.output_folder}"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
converter = ExcelToJsonConverter()
|
||||
converter.convert()
|
||||
@@ -0,0 +1,748 @@
|
||||
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 sys
|
||||
import traceback
|
||||
from thefuzz import fuzz
|
||||
import re
|
||||
from app.common.jalali import Persian
|
||||
from app.common.config_base import *
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,23 @@
|
||||
from app.common.config_base import *
|
||||
from app.common.general_functions import *
|
||||
import requests
|
||||
|
||||
|
||||
|
||||
url = " https://tavasi.ir/api/nlp/keywords?content="
|
||||
|
||||
headers = HEADERS
|
||||
text = '''
|
||||
|
||||
دیپلماسی اقتصادی: مجموعه اقدامات و فعالیت های اقتصادی خارجی (توسط دولت یا بخش خصوصی با هماهنگی وزارت امورخارجه) که با هدف توسعه روابط اقتصادی و تجاری با کشورهای خارجی، در جهت دستیابی به اهداف نظیر افزایش دسترسی به بازارهای بین المللی کالاها و خدمات، سرمایه گذاری خارجی، تبادل فناوری و برقراری روابط پایدار با سایر کشورها انجام می شود.
|
||||
'''
|
||||
url = url + text
|
||||
payload = {}
|
||||
response = requests.request("GET", url, headers=headers, data=payload)
|
||||
entities = ''
|
||||
i = len(response.text.strip())-3
|
||||
keywords = response.text[13:i].split(',')
|
||||
# for entity in keywords:
|
||||
# entities = entities + str(entity).strip('\"') +' ' + '\n'
|
||||
print(keywords)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import arabic_reshaper
|
||||
from bidi.algorithm import get_display
|
||||
text = "سلام دنیا"
|
||||
reshaped_text = arabic_reshaper.reshape(text)
|
||||
bidi_text = get_display(reshaped_text)
|
||||
print(bidi_text)
|
||||
Reference in New Issue
Block a user