excel codes tanghih

This commit is contained in:
hsafaei
2025-05-26 09:11:22 +03:30
parent b77a7fe703
commit cbb98723d8
10 changed files with 578 additions and 14 deletions
+24
View File
@@ -0,0 +1,24 @@
import pandas as pd
class ExcelHelper:
def __init__(self):
self.pd = null
self.data_dict = []
def load_data(self, file_path, sheet_name=0):
df = pd.read_excel(file_path, sheet_name=sheet_name)
return df
# def load_data(self, file_path, sheet_name):
# df = pd.read_excel(file_path, sheet_name=sheet_name)
# selected_columns = df[[self.fltxt_column_name]]
# self.data_dict = selected_columns.to_dict(orient='records')
# for record in self.data_dict:
# record['_id'] = " "
# print("✅ داده‌ها با موفقیت از فایل اکسل خوانده شدند.")
+12
View File
@@ -12,6 +12,7 @@ from decimal import Decimal
import traceback
# from lxml import etree
import datetime
from datetime import timedelta
#enumerate(token_list):
_normalizer = Normalizer(date_normalizing_needed=True)
@@ -1083,6 +1084,17 @@ def separated_date_format_finder(date_ner):
return result
def myTimestamp(days=0):
dt = datetime.datetime.now()
# tt = round(time.time() * 1000)
if days != 0 :
dt = (dt - timedelta(days))
tt = dt.timestamp()
return round(tt)
#////////////////////////////////////////////////////////////
#////////////////////////////////////////////////////////////
+10
View File
@@ -0,0 +1,10 @@
لایحه قانونی راجع به آئین نامه اجرائی دفتر معاملات مسکن و تغییرنام=qq118694
منتفی بودن لایحه قانونی تشکیل انجمنهای ده و اصلاح امور اجتماعی و عمرانی دهات=qq120753
خریداری کلیه اراضی گودهای کوره پزخانه های سابق و فعلی واقع در جنوب تهران بین خیابانهای شوش و حد جنوبی جدید تهران و جاده آرامگاه و خیابان سپهبد رزم آرا توسط شهرداری تهرات برای رفع نیازمندی های عمومی شهر=0
قانون راجع باجازه تحصیل مبلغ هفتاد و دو میلیون دلار وام از بانک بین‌المللی ترمیم و توسعه=qq113980
قانون راجع به احداث و توسعه معابر و خیابان ها=qq112239
قانون بودجه 1385 کل کشور=qq87759
قانون بودجه سال 1369کل کشور=qq84519
قانون اصلاح مواد 4 و 6 قانون تغییر نام وزارت آبادانی و مسکن بوزارت مسکن و شهرسازی و تعیین وظایف آن=qq86848
ائین‌نامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28ر12ر1345=qq115135
قانون اعطای امتیاز نفط بشرکت نفط انگیس[انگلیس] و ایران محدود=qq85083
+106
View File
@@ -0,0 +1,106 @@
import os
from dotenv import load_dotenv
import json
import requests
from config_base import *
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import time
from config_base import *
from general_functions import *
from text_normalizer import TextNormalizer
from elastic_helper import ElasticHelper
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")
+350
View File
@@ -0,0 +1,350 @@
import os
from dotenv import load_dotenv
from config_base import *
from general_functions import *
from text_normalizer import TextNormalizer
from 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):
spell_list = [
"ائین‌نامه[آئین نامه]=آئین نامه",
"انگیس[انگلیس]=انگلیس",
"انگیس=انگلیس",
"ائین‌نامه=آئین نامه",
"بوزارت=به وزارت"
"تهرات=تهران"
]
text = text_normalizer.date_correction(text)
text = text_normalizer.word_digit_correction(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 = re.sub(r"( |\u200C|\>|\<)+", "", section_title)
for item in s_res["hits"]["hits"]:
other_info = item['_source']['other_info']
title = other_info['full_path']
# حذف اضافات
title = re.sub(r"( |\u200C|\>|\<|-|ـ)+", "", 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 searchQanonId(elastic, index_name, qanon_title, ts_data=""):
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 = 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["_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 = 90
item = list_equal[0]
return item["_id"], score, item
return 0, 0, {}
def importDataToElastic(elastic, file_excel, index_name_o, tcode, 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 = []
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, "mj_qa_qanon", qanon_title, ts_date)
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)
# 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/"
try:
os.makedirs(result_path, exist_ok=True)
except Exception as e:
print(result_path)
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_in_directory(elastic, directory, output):
# 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]
log_file = output + "/log_r_"+code_name+".txt"
file_path = os.path.join(directory, file)
# importDataToElastic(elastic, file_path, "mj_qa_section", code_name, log_file)
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)
# run_in_directory(elastic, "./data/tcodes", "./data/tcodes/result")
importDataToElastic(elastic, "./data/tcodes/مسکن و شهرسازی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r3.txt")
# importDataToElastic(elastic, "./data/tcodes/آمار، برنامه و بودجه.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_آمار.txt")
# importDataToElastic(elastic, "./data/tcodes/آیین دادرسی مدنی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_دادرسی.txt")
# importDataToElastic(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 = 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, "mj_qa_qanon", text) )
+2
View File
@@ -3,3 +3,5 @@ python-dotenv
pyodbc
bs4
elasticsearch
pandas
openpyxl
+1 -1
View File
@@ -215,7 +215,7 @@ def import_law_section_to_elastic(cursor) :
'sub_type': sub_type,
'content': text,
'html' : html,
'version_info': version_ifo,
# 'version_info': version_ifo,
'qanon_title': qanon_title,
'title_type': title_type,
'expire_date': expire_date,
+1 -1
View File
@@ -149,7 +149,7 @@ def import_opinion_to_elastic(cursor) :
"sub_type": sub_type,
"html": row.content,
"content": text,
"version_info": version_ifo,
# "version_info": version_ifo,
"ts_date": ts_date,
"ts_year": ts_year,
"ts_ref": ts_ref,
+1 -1
View File
@@ -213,7 +213,7 @@ def import_regulation_section_to_elastic(cursor):
'sub_type': sub_type,
'content': text,
'html' : html,
'version_info': version_ifo,
# 'version_info': version_ifo,
'qanon_title': qanon_title,
'title_type': title_type,
'expire_date': expire_date,
+70 -10
View File
@@ -21,6 +21,34 @@ class TextNormalizer:
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 ""
@@ -68,7 +96,6 @@ class TextNormalizer:
return text
def normalize_text(self, text):
if not text :
return ""
@@ -89,14 +116,11 @@ class TextNormalizer:
text = re.sub(r"(\n)+", "\n", text)
# نرمال کردن حروف اختلافی عربی و فارسی
if self.options.get("charArNormal", True):
text = text.replace("ي", "ی")
text = text.replace("ك", "ک")
text = self.yeke_normal(text)
# پرش از اختلافات همزه‌ا
if self.options.get("hamzehNormal", False):
text = re.sub(r"ئ|ﺋ", "ی", text)
text = re.sub(r"ؤ|ﺅ", "و", text)
text = re.sub(r"ﺔ|ۀ|ة", "ه", text)
text = re.sub(r"إ|أ", "ا", text)
text = self.hamzah_normal(text)
# اصلاح فاصله‌ها در ترکیب کلمات
if self.options.get("spaceCorrection", False):
text = self.space_correction(text)
@@ -106,6 +130,23 @@ class TextNormalizer:
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 ""
@@ -242,11 +283,21 @@ class TextNormalizer:
def date_correction(self, 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)
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{1,2})[\/\-](\d{1,2})[\/\-](\d{4})', r'\3/\2/\1', text)
text = re.sub(r'(\d{4})[\/\-](\d{2})[\/\-](\d{2})', r'\3/\2/\1', text)
text = re.sub(r'(\d{1})[\/\-](\d{1})[\/\-](\d{4})', r'0\1/0\2/\3', text)
return text
def space_correction(self, text):
@@ -280,6 +331,8 @@ class TextNormalizer:
# ### 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)
# ر54ر44ر135
text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1\/\2\/\3", text)
@@ -300,6 +353,13 @@ class TextNormalizer:
return text
def pad_left(self, s, length, char=' '):
if len(s) >= length:
return s
else:
return char * (length - len(s)) + s
# # تست برنامه
# options = {