refactor codes and names

This commit is contained in:
hsafaei
2026-02-12 11:19:58 +03:30
parent 56084b0c8e
commit 9c99d816db
25 changed files with 395 additions and 2360 deletions
+748
View File
@@ -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)