refactor 2

This commit is contained in:
hsafaei
2025-09-02 12:15:47 +03:30
parent cfe3cff77c
commit 5a6647bbf2
62 changed files with 151 additions and 160 deletions
+2
View File
@@ -0,0 +1,2 @@
+53
View File
@@ -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
+152
View File
@@ -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
+677
View File
@@ -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)
File diff suppressed because it is too large Load Diff
+367
View File
@@ -0,0 +1,367 @@
import os
import re
import traceback
import json
from dotenv import load_dotenv
from common.config_base import *
# from common.general_functions import *
from common.text_normalizer import TextNormalizer
from 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)
+87
View File
@@ -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)
+410
View File
@@ -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)
+59
View File
@@ -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