all_sql_steps , repair qa_qanon

This commit is contained in:
hsafaei
2025-11-26 18:14:47 +03:30
parent 02b359c66b
commit e616d748c5
28 changed files with 2545 additions and 415 deletions
+463
View File
@@ -0,0 +1,463 @@
import pandas as pd
import os
import re
from tqdm import tqdm
import unicodedata
import logging
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
base_folder = r"E:\pdf advar"
# بعد انقلاب
col_shomare_parvande_after = "شماره پرونده"
col_doreh_after = "دوره قانونگذاری"
col_ts_ref = "مرجع تصویب"
# قبل انقلاب
col_shomare_koli_before = "شماره کلی"
col_shomare_parvande_before = "شماره پرونده و ردیف "
col_tarikh_before = "تاريخ‌تصويب 1"
col_doreh_before = "دوره قانونگذاری"
col_lib_folder_before = "شماره فولدر کتابخانه"
error_descriptions = {
"پوشه دوره پیدا نشد": "دوره قانونی در مسیر مشخص وجود ندارد، پوشه متناظر با دوره پیدا نشد.",
"مسیر دوره وجود ندارد": "مسیر دوره در سیستم وجود ندارد (احتمالاً مسیر اصلی اشتباه است).",
"پوشه پیدا نشد": "پوشه با شماره پرونده مشخص در مسیر دوره وجود ندارد.",
"نبود فایل": "هیچ فایل PDF یا عکس در پوشه یا زیرپوشه پیدا نشد.",
"بدون خطا": "پوشه و فایل‌ها موجود هستند و تطابق لازم برقرار است.",
"عدم تطابق با شماره فولدر کتابخانه": "فایل عکس موجود است اما نام آن با شماره فولدر کتابخانه تطابق ندارد.",
"خطای زیر پوشه": "پوشه شامل زیرپوشه است، بررسی فایل‌ها طبق قوانین انجام می‌شود.",
"خطای زیر پوشه / وجود فایل / بدون خطا": "زیرپوشه دارد و فایل PDF یا عکس مطابق شماره فولدر موجود است، بدون خطا ثبت می‌شود.",
"خطای زیر پوشه / وجود فایل / عدم تطابق با شماره فولدر کتابخانه": "زیرپوشه دارد و فایل عکس موجود است اما نام فایل مطابق شماره فولدر نیست.",
"دوره نامعتبر": "دوره قانونگذاری به صورت متنی است و عدد آن قابل استخراج نیست.",
"دوره نامعتبر (عدد X خارج از محدوده 1-12)": "عدد استخراج‌شده از دوره خارج از محدوده مجاز است.",
"فایل یا پوشه ای با این شماره پرونده پیدا نشد": "در مسیر مربوطه، هیچ فایل یا پوشه‌ای با این نام وجود ندارد.",
"مطابق با الگو نبود": "شماره پرونده با الگوی تعریف‌شده مطابقت ندارد.",
"دوره (مجلس تشخیص)": "مصوبه مجلس تشخیص",
}
doreh_to_folder_after = {str(i): f"d.{i}" for i in range(1, 13)} # d.1 تا d.12
doreh_to_folder_before = {
"اول": "d1-ok",
"دوم": "d2-ok",
"سوم": "d3-ok",
"چهارم": "d4-ok",
"پنجم": "d5-ok",
"ششم": "d6-ok",
"هفتم": "d7-ok",
"هشتم": "d8-ok",
"نهم": "d9-ok",
"دهم": "d10-ok",
"یازدهم": "d11-ok",
"دوازدهم": "d12-ok",
"سیزدهم": "d13-ok",
"چهاردهم": "d14-ok",
"پانزدهم": "d15-ok",
"شانزدهم": "d16-ok",
"هفدهم": "d17-ok",
"هجدهم": "d18-ok",
"نوزدهم": "d19-ok",
"بیستم": "d20-ok",
"بیست و یکم": "d21-ok",
"بیست و دوم": "d22-ok",
"بیست و سوم": "d23-ok",
"بیست و چهارم": "d24-ok",
}
# الگوی شماره پرونده بعد انقلاب
pattern_after = r"^\d+(?:\s*مکرر)?(?:/|\s*)?ش?\s*(?:مکرر)?\d*$"
# الگوی قبل انقلاب
pattern_before = r"^\d+$|^\d+\s*مکرر\d*$"
# نرمال‌سازی برای مقایسه دقیق
def normalize_str(s):
if not isinstance(s, str):
return ""
return unicodedata.normalize("NFKC", s).replace(" ", "").casefold()
# استخراج عدد
def extract_period_number(text):
if not isinstance(text, str):
return None
text = text.strip().lower()
num_match = re.match(r"^(\d+)", text)
if num_match:
return int(num_match.group(1))
number_map = {
"اول": 1,
"دوم": 2,
"سوم": 3,
"چهارم": 4,
"پنجم": 5,
"ششم": 6,
"هفتم": 7,
"هشتم": 8,
"نهم": 9,
"دهم": 10,
"یازدهم": 11,
"دوازدهم": 12,
}
for word, num in number_map.items():
if word in text:
return num
return None
def normalize_file_number(s):
if not isinstance(s, str):
return ""
s = s.translate(str.maketrans("۰۱۲۳۴۵۶۷۸۹", "0123456789"))
s = unicodedata.normalize("NFKC", s)
s = s.replace(" ", "").replace("/", "").casefold()
return s
# --- پردازش بعد انقلاب ---
def process_after_simple(df, period_map, base_subfolder_name):
df = df.copy()
df["وجود فایل"] = ""
df["تطابق با الگو"] = ""
df["مدیریت خطا"] = ""
df["مسیر"] = ""
df["فایلها"] = ""
folder_cache = {}
for idx, row in tqdm(df.iterrows(), total=len(df), desc="پردازش بعد انقلاب"):
try:
full_path=''
name_files=''
ts_ref_val = (
str(row[col_ts_ref]).strip()
if not pd.isna(row[col_ts_ref])
else ""
)
shomare_parvande_val = (
str(row[col_shomare_parvande_after]).strip()
if not pd.isna(row[col_shomare_parvande_after])
else ""
)
doreh_val = (
str(row[col_doreh_after]).strip()
if not pd.isna(row[col_doreh_after])
else ""
)
if doreh_val=='اول':
doreh_val='1'
elif doreh_val=='دوم':
doreh_val='2'
elif doreh_val=='سوم':
doreh_val='3'
elif doreh_val=='چهارم':
doreh_val='4'
elif doreh_val=='پنجم':
doreh_val='5'
elif doreh_val=='ششم':
doreh_val='6'
elif doreh_val=='هفتم':
doreh_val='7'
elif doreh_val=='هشتم':
doreh_val='8'
elif doreh_val=='نهم':
doreh_val='9'
elif doreh_val=='دهم':
doreh_val='10'
elif doreh_val=='یازدهم':
doreh_val='11'
elif doreh_val=='دوازدهم':
doreh_val='12'
elif doreh_val=='سیزدهم':
doreh_val='13'
elif doreh_val in ["...", "…", "........."]:
if ts_ref_val == 'شوراي انقلاب جمهوري اسلامي ايران' :
doreh_val='شورای انقلاب'
elif ts_ref_val == 'مجمع تشخيص مصلحت نظام' :
df.at[idx, "وجود فایل"] = "ندارد"
df.at[idx, "تطابق با الگو"] = "غیر مطابق"
df.at[idx, "مدیریت خطا"] = "دوره نامعتبر"
continue
else :
df.at[idx, "وجود فایل"] = "ندارد"
df.at[idx, "تطابق با الگو"] = "غیر مطابق"
df.at[idx, "مدیریت خطا"] = "دوره نامعتبر"
continue
full_path = ''
if doreh_val == 'شورای انقلاب':
shomare_parvande_val = shomare_parvande_val.replace("/", "")
search_name = shomare_parvande_val
norm_search = normalize_file_number(search_name)
full_path = os.path.join(
base_folder,
base_subfolder_name,
"shorayeh enghelab",
"مصوبات به تفکیک شمار پرونده"
)
else :
search_name=shomare_parvande_val
shomare_parvande_val=shomare_parvande_val.replace(".", "/")
# parts = shomare_parvande_val.split("/", 1)
parts = shomare_parvande_val.split("/")
if len(parts) == 2 :
search_name = parts[1].strip()
if doreh_val=='':
doreh_val = parts[0].strip()
else:
search_name = parts[0].strip()
norm_search = normalize_file_number(search_name)
period_num = doreh_val
period_folder = period_map.get(str(period_num))
if not period_folder:
df.at[idx, "وجود فایل"] = "ندارد"
df.at[idx, "تطابق با الگو"] = "غیر مطابق"
df.at[idx, "مدیریت خطا"] = "دوره نامعتبر"
continue
full_path = os.path.join(
base_folder, base_subfolder_name, period_folder
)
if full_path not in folder_cache:
folder_cache[full_path] = (
set(os.listdir(full_path))
if os.path.exists(full_path) and os.path.isdir(full_path)
else set()
)
if not folder_cache[full_path]:
logging.warning(f"پوشه وجود ندارد یا خالی: {full_path}")
folder_contents = folder_cache[full_path]
found_file_name = None
for f in folder_contents:
root, ext = os.path.splitext(f)
if normalize_file_number(root).startswith(norm_search):
found_file_name = f
break
# df.at[idx, "وجود فایل"] = "دارد" if found_file_name else "ندارد"
# df.at[idx, "مسیر"] = (full_path +"/" + norm_search).replace(base_folder,'')
if not found_file_name :
df.at[idx, "مسیر"] = full_path.replace(base_folder,'')
df.at[idx, "وجود فایل"] = "ندارد"
df.at[idx, "تطابق با الگو"] = "غیر مطابق"
df.at[idx, "مدیریت خطا"] = (
"فایل یا پوشه ای با این شماره پرونده پیدا نشد"
)
else :
df.at[idx, "وجود فایل"] = "دارد"
df.at[idx, "مسیر"] = full_path.replace(base_folder,'')
name_files = os.path.basename(found_file_name) + ','
df.at[idx, "فایلها"] = name_files
if re.match(pattern_after, normalize_file_number(shomare_parvande_val)):
df.at[idx, "تطابق با الگو"] = "مطابق"
df.at[idx, "مدیریت خطا"] = "بدون خطا"
else:
df.at[idx, "تطابق با الگو"] = "غیر مطابق"
df.at[idx, "مدیریت خطا"] = "مطابق با الگو نبود"
except Exception as e:
df.at[idx, "وجود فایل"] = "نامشخص"
df.at[idx, "تطابق با الگو"] = "نامشخص"
df.at[idx, "مدیریت خطا"] = f"خطا در ردیف {idx}: {str(e)}"
return df
# --- پردازش قبل انقلاب ---
def process_dataframe_before(df, period_map, base_subfolder):
df = df.copy()
df["وضعیت وجود پوشه"] = ""
df["تطابق با الگو"] = ""
df["بررسی زیر پوشه"] = ""
df["وجود فایل"] = ""
df["مدیریت خطا"] = ""
df["مسیر"] = ""
df["فایلها"] = ""
for idx, row in tqdm(df.iterrows(), total=len(df), desc=f"پردازش {base_subfolder}"):
try:
shomare_parvande_val = str(row[col_shomare_parvande_before]).strip()
doreh_val = str(row[col_doreh_before]).strip()
lib_folder_val = str(row[col_lib_folder_before]).strip()
period_folder = period_map.get(doreh_val)
if not period_folder:
df.at[idx, "وضعیت وجود پوشه"] = "ندارد"
df.at[idx, "تطابق با الگو"] = "غیر مطابق"
df.at[idx, "مدیریت خطا"] = "پوشه دوره پیدا نشد"
continue
target_folder_name_clean = shomare_parvande_val.replace(" ", "").strip()
full_path = os.path.join(base_folder, base_subfolder, period_folder, target_folder_name_clean)
df.at[idx, "مسیر"] = full_path.replace(base_folder,'')
found_folders = []
# print(full_path)
if not os.path.exists(full_path):
df.at[idx, "وضعیت وجود پوشه"] = "ندارد"
df.at[idx, "تطابق با الگو"] = "غیر مطابق"
df.at[idx, "مدیریت خطا"] = "پوشه پیدا نشد"
continue
# for d in os.listdir(full_path):
# folder_path = os.path.join(full_path, d)
# if (
# os.path.isdir(folder_path)
# and d.replace(" ", "").strip() == target_folder_name_clean
# ):
# found_folders.append(folder_path)
# if not found_folders:
# df.at[idx, "وضعیت وجود پوشه"] = "ندارد"
# df.at[idx, "تطابق با الگو"] = "غیر مطابق"
# df.at[idx, "مدیریت خطا"] = "پوشه پیدا نشد"
# continue
df.at[idx, "وضعیت وجود پوشه"] = "دارد"
df.at[idx, "تطابق با الگو"] = (
"مطابق"
if re.match(pattern_before, shomare_parvande_val.replace(" ", ""))
else "غیر مطابق"
)
has_file = False
pdf_found = False
subfolder_error = ""
matched_file = False
name_files= ''
for root, dirs, files in os.walk(full_path):
df.at[idx, "بررسی زیر پوشه"] = "دارد" if dirs else "ندارد"
if dirs:
subfolder_error = "خطای زیر پوشه"
for f in files:
f_lower = f.lower()
name_files += os.path.basename(f_lower) + ','
if f_lower.endswith(".pdf"):
pdf_found = True
has_file = True
elif f_lower.endswith(
(".jpg", ".jpeg", ".png", ".tif", ".bmp")
):
has_file = True
if (
lib_folder_val
and lib_folder_val.lower() != "nan"
and lib_folder_val.replace(" ", "").strip()
in os.path.splitext(f)[0].replace(" ", "").strip()
):
matched_file = True
if not has_file:
df.at[idx, "وجود فایل"] = "ندارد"
df.at[idx, "مدیریت خطا"] = (
subfolder_error if subfolder_error else "نبود فایل"
)
else:
df.at[idx, "وجود فایل"] = "دارد"
if subfolder_error:
if pdf_found or matched_file:
df.at[idx, "مدیریت خطا"] = (
f"{subfolder_error} / وجود فایل / بدون خطا"
)
else:
df.at[idx, "مدیریت خطا"] = (
f"{subfolder_error} / وجود فایل / عدم تطابق با شماره فولدر کتابخانه"
)
else:
if pdf_found or matched_file:
df.at[idx, "مدیریت خطا"] = "بدون خطا"
else:
df.at[idx, "مدیریت خطا"] = "عدم تطابق با شماره فولدر کتابخانه"
df.at[idx, "فایلها"] = name_files
except Exception as e:
df.at[idx, "وضعیت وجود پوشه"] = "نامشخص"
df.at[idx, "تطابق با الگو"] = "نامشخص"
df.at[idx, "مدیریت خطا"] = str(e)
return df
def prepare_error_report(result_df, sheet_name):
df = result_df.copy()
counts = df["مدیریت خطا"].value_counts().reset_index()
counts.columns = ["خطا", "تعداد"]
counts["زمان"] = sheet_name
counts["توضیح"] = counts["خطا"].map(error_descriptions)
return counts[["خطا", "زمان", "توضیح", "تعداد"]]
def main_proccess():
# excel_file = "data/qavanin_files/qavanin.xlsx"
# output_file = "data/qavanin_files/qavanin_output2.xlsx"
# df_before = pd.read_excel(excel_file, sheet_name=0)
# df_after = pd.read_excel(excel_file, sheet_name=1)
excel_file1 = "data/qavanin_files/فهرست تمام قوانین_1_ 1 الی2378-رشیدزاده.xlsx"
excel_file2 = "data/qavanin_files/فهرست تمام قوانین_2_تکمیل شده.xlsx"
output_file = "data/qavanin_files/qavanin_output4.xlsx"
df_before = pd.read_excel(excel_file1, sheet_name=0)
df_after = pd.read_excel(excel_file2, sheet_name=0)
result_before = process_dataframe_before(
df_before,
doreh_to_folder_before,
os.path.join("ghabl az enghelab", "majlis shorayeh melli"),
)
result_after = process_after_simple(
df_after, doreh_to_folder_after, "baed az enghelab eslami"
)
errors_before = prepare_error_report(result_before, "قبل انقلاب")
errors_after = prepare_error_report(result_after, "بعد انقلاب")
errors_combined = pd.concat([errors_before, errors_after], ignore_index=True)
os.makedirs("files", exist_ok=True)
with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
result_before.to_excel(writer, index=False, sheet_name="قبل انقلاب")
result_after.to_excel(writer, index=False, sheet_name="بعد انقلاب")
errors_combined.to_excel(writer, index=False, sheet_name="گزارش کلی")
print(f"✅ خروجی نهایی ذخیره شد در: {output_file}")
if __name__ == "__main__":
main_proccess()
@@ -0,0 +1,558 @@
import pandas as pd
import os
import re
from tqdm import tqdm
import unicodedata
import logging
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from ..common.text_normalizer import TextNormalizer
# from general import *
from ..common.general_functions import *
from ..common.elastic_helper import ElasticHelper
# ---------------------------------------------
# قبل انقلاب
# خواندن اطلاعات اکسل و درج در qaqanon
# ....... تصمیمات قانونی داخل اکسل فیلد نوع دارند
# ---------------------------------------------
# ---------------------------------------------
# بعد انقلاب
# خواندن اطلاعات اکسل و درج در qaqanon
# برای تصمیمات قانونی، خواندن اکسل مخصوص و درج در qaqanon
# ---------------------------------------------
def import_excel_before_to_elastic(elastic, path_file, index_name_o):
bulk_data_import=[]
bulk_data_update=[]
total_count = 0
count = 0
id = ""
try:
data = excel_to_json(path_file, None, 0)
print('*' * 20 , ' count=', len(data))
cols = [
"شماره کلی",
"شماره ردیف با احتساب مکرر",
"شماره پرونده و ردیف ",
"دوره قانونگذاری",
"عنوان",
"تاریخ تصویب در dotic ",
"تاريخ‌تصويب 1",
"مرجع تصويب ",
"تاریخ تصویب 2",
"مرجع تصویب 2",
"نوع",
"شماره پرونده های مرتبط",
"وضعيت",
"اصلی/تبعی",
"بررسی کننده",
"تایید نهایی",
"شماره فولدر کتابخانه",
"توضیحات",
"شماره پرونده سنا",
"_id",
# "error",
# "Unnamed: 21",
# "Unnamed: 22",
# "Unnamed: 23",
# "Unnamed: 24",
# "وضعیت وجود پوشه",
# "تطابق با الگو",
# "بررسی زیر پوشه",
# "وجود فایل",
"مدیریت خطا",
"مسیر",
"فایلها"
]
text_normalizer = TextNormalizer()
for item in data:
count += 1
error_files_state = item.get("مدیریت خطا", "")
title = item.get("عنوان", "")
title = text_normalizer.normalize_qanon(title)
sub_type = item.get("نوع", "")
sub_type = text_normalizer.normalize_qanon(sub_type)
_id = item.get("_id", "")
davam_type = ''
eid = _id
number_all = item.get("شماره کلی", "")
number_row_duplicate = item.get("شماره ردیف با احتساب مکرر", "")
number_row_duplicate = number_row_duplicate if not '..' in number_row_duplicate else ''
number_row = item.get("شماره پرونده و ردیف ", "")
number_row = number_row if not '..' in number_row else ''
number_lib_folder = item.get("شماره فولدر کتابخانه", "")
number_lib_folder = number_lib_folder if not '..' in number_lib_folder else ''
number_sena = item.get("شماره پرونده سنا", "")
number_sena = number_sena if not '..' in number_sena else ''
description = item.get("توضیحات", "")
description = text_normalizer.normalize_qanon(description)
term = item.get("دوره قانونگذاری", "") # ???? term
term = text_normalizer.normalize_qanon(term)
term = term if not '..' in term else ''
ts_date_dotic = item.get("تاریخ تصویب در dotic ", "")
if not is_match_persian_date_format(ts_date_dotic):
ts_date_dotic = ''
ts_date1 = item.get("تاريخ‌تصويب 1", "")
if not is_match_persian_date_format(ts_date1):
ts_date1 = ''
ts_ref1 = item.get("مرجع تصويب ", "") # ????? ts_ref
ts_ref1 = text_normalizer.normalize_qanon(ts_ref1)
ts_ref1 = ts_ref1 if not '..' in ts_ref1 else ''
ts_date2 = item.get("تاریخ تصویب 2", "")
if not is_match_persian_date_format(ts_date2):
ts_date2 = ''
ts_ref2 = item.get("مرجع تصویب 2", "")
ts_ref2 = text_normalizer.normalize_qanon(ts_ref2)
ts_ref2 = ts_ref2 if not '..' in ts_ref2 else ''
qanon_etebar = item.get("وضعيت", "")
qanon_etebar = text_normalizer.normalize_qanon(qanon_etebar)
qanon_etebar = qanon_etebar if not '..' in qanon_etebar else ''
path_folder = item.get("مسیر", "")
name_files = item.get("فایلها", "")
# title = item.get("شماره پرونده های مرتبط", "") # فیلد معادل ندارد
# title = item.get("اصلی/تبعی", "") # فیلد معادل ندارد
# title = item.get("بررسی کننده", "") # فیلد معادل ندارد
# title = item.get("تایید نهایی", "") # فیلد معادل ندارد
main_type='قانون'
if sub_type == 'تصمیم قانونی' :
main_type = 'تصمیم قانونی'
sub_type=''
elif sub_type == 'علدی' :
sub_type='عادی'
elif sub_type == '...' :
if title.startswith('تصمیم قانونی') or title.startswith('تصویب نامه قانونی') :
sub_type=''
main_type = 'تصمیم قانونی'
else :
sub_type='بودجه'
else:
print('.#'*10,'error subtype , ', count)
is_update = True
if not _id.startswith('qq') :
eid = 0
is_update= False
if sub_type =='تصمیم قانونی' :
eid='qt_'+ uuid.uuid4().hex[:8]
else :
eid='qe_'+ uuid.uuid4().hex[:8]
sub_type='نامشخص'
if _id=='قانون جدید - موقت' :
davam_type='موقت'
sub_type='عادی'
files_info=[]
for name in name_files.split(','):
if not name :
continue
file_type = ''
if name.endswith(".pdf"):
file_type="pdf"
elif name.endswith(
(".jpg", ".jpeg", ".png", ".tif", ".bmp")
):
file_type="img"
else :
file_type=""
files_info.append({
"path": os.path.join(path_folder, name),
"file_name": name,
"title": name,
"type": file_type
})
data = {
"id": eid,
"title": title,
"main_type": main_type,
"sub_type": sub_type,
"term": term,
"qanon_etebar": qanon_etebar,
"davam_type": davam_type,
"ts_date_dotic": ts_date_dotic,
"ts_date1": ts_date1,
"ts_ref1": ts_ref1,
"ts_date2": ts_date2,
"ts_ref2": ts_ref2,
"description": description,
"files": files_info,
"number" :{
"all" : number_all,
"row_duplicate" : number_row_duplicate,
"row" : number_row,
"lib_folder" : number_lib_folder,
"sena" : number_sena
}
}
if is_update :
bulk_data_update.append({
"_id": id,
"_source": data
})
else :
bulk_data_import.append({
"_id": id,
"_source": data
})
if len(bulk_data_update) >= 100:
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data_update, index_name_o)
bulk_data_update = []
if len(bulk_data_import) >= 100:
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
bulk_data_import = []
if len(bulk_data_update):
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data_update, index_name_o)
bulk_data_update = []
if len(bulk_data_import):
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
bulk_data_import = []
except Exception as e:
print("Exception: " + str(e))
def import_excel_after_to_elastic(elastic, path_file, index_name_o):
bulk_data_import=[]
bulk_data_update=[]
total_count = 0
count = 0
id = ""
try:
data = excel_to_json(path_file, None, 0)
print('*' * 20 , ' count=', len(data))
cols = [
"شماره عمومی",
"شماره رديف",
"شماره پرونده",
"دوره قانونگذاری",
"عنوان",
"تاریخ تصویب",
"مرجع تصویب",
"تاریخ تایید",
"وضعيت",
"شماره روزنامه رسمی کشور",
"تاریخ انتشار روزنامه رسمی کشور",
"شماره شناسه قانون",
"شماره پرونده های مرتبط",
"اصلی/تبعی",
"مستندات",
" تصدیق کنندگان فایل word قانون با pdf",
"توضیحات تصدیق",
"تاریخ لازم الاجرا شدن",
" تطبیق کنندگان فایلpdf با روزنامه رسمی",
"توضیحات تطبیق فایلpdf با روزنامه رسمی",
"_id",
"error",
"وجود فایل",
"تطابق با الگو",
"مدیریت خطا",
"مسیر",
"فایلها"
]
text_normalizer = TextNormalizer()
for item in data:
count += 1
error_files_state = item.get("مدیریت خطا", "")
title = item.get("عنوان", "")
title = text_normalizer.normalize_qanon(tile)
_id = item.get("_id", "")
davam_type = ''
eid = _id
number_all = item.get("شماره عمومی", "")
number_row_duplicate = item.get("شماره ردیف", "")
number_row = item.get("شماره پرونده ", "")
ts_date = item.get("تاريخ‌تصويب", "")
if not is_match_persian_date_format(ts_date):
ts_date = ''
ts_ref = item.get("مرجع تصويب", "") # ????? ts_ref
ts_ref = text_normalizer.normalize_qanon(ts_ref)
shora_date = item.get("تاریخ تایید", "")
if not is_match_persian_date_format(shora_date):
shora_date = ''
exec_date = item.get("تاریخ لازم الاجرا شدن", "")
if not is_match_persian_date_format(exec_date):
exec_date = ''
rrk_number = item.get("شماره روزنامه رسمی کشور", "")
rrk_number = rrk_number if not '..' in rrk_number else ''
rrk_date = item.get("تاریخ انتشار روزنامه رسمی کشور", "")
if not is_match_persian_date_format(rrk_date):
rrk_date = ''
number_qanon = item.get("شماره شناسه قانون", "")
description = item.get("مستندات", "")
description = text_normalizer.normalize_qanon(description)
term = item.get("دوره قانونگذاری", "") # ???? term
term = text_normalizer.normalize_qanon(term)
term = term if not '..' in term else ''
qanon_etebar = item.get("وضعيت", "")
qanon_etebar = text_normalizer.normalize_qanon(qanon_etebar)
path_folder = item.get("مسیر", "")
name_files = item.get("فایلها", "")
# title = item.get("شماره پرونده های مرتبط", "") # فیلد معادل ندارد - تبعی های مرتبط و مثل این منظورهست که خودکار پر میشود یا سامانه می دهد
# title = item.get("اصلی/تبعی", "") # فیلد معادل ندارد
# title = item.get("بررسی کننده", "") # فیلد معادل ندارد
# title = item.get("تایید نهایی", "") # فیلد معادل ندارد
main_type='قانون'
sub_type = 'عادی'
letters = []
if shora_date :
letters.append({
"type" : "تایید شورای نگهبان",
"date" : shora_date
})
if rrk_number or rrk_date :
letters.append({
"type" : "انتشار در روزنامه رسمی",
"number" : rrk_number,
"date" : rrk_date
})
is_update = True
if not _id.startswith('qq') :
eid = 0
is_update= False
eid='qe_'+ uuid.uuid4().hex[:8]
sub_type='نامشخص'
files_info=[]
for name in name_files.split(','):
if not name :
continue
file_type = ''
if name.endswith(".pdf"):
file_type="pdf"
elif name.endswith(
(".jpg", ".jpeg", ".png", ".tif", ".bmp")
):
file_type="img"
else :
file_type=""
files_info.append({
"path": os.path.join(path_folder, name),
"file_name": name,
"title": name,
"type": file_type
})
data = {
"id": eid,
"title": title,
"main_type": main_type,
"sub_type": sub_type,
"term": term,
"qanon_etebar": qanon_etebar,
"davam_type": davam_type,
"ts_date_dotic": ts_date_dotic,
"ts_date1": ts_date1,
"ts_ref1": ts_ref1,
"ts_date2": ts_date2,
"ts_ref2": ts_ref2,
"description": description,
"files": files_info,
"number" :{
"all" : number_all,
"row_duplicate" : number_row_duplicate,
"row" : number_row,
"lib_folder" : number_lib_folder,
"sena" : number_sena
}
}
if is_update :
bulk_data_update.append({
"_id": id,
"_source": data
})
else :
bulk_data_import.append({
"_id": id,
"_source": data
})
if len(bulk_data_update) >= 100:
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data_update, index_name_o)
bulk_data_update = []
if len(bulk_data_import) >= 100:
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
bulk_data_import = []
if len(bulk_data_update):
total_count += len(bulk_data_update)
print('=' * 10, ' update , total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data_update, index_name_o)
bulk_data_update = []
if len(bulk_data_import):
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
bulk_data_import = []
except Exception as e:
print("Exception: " + str(e))
def import_excel_tasmimat_to_elastic(elastic, path_file, index_name_o):
bulk_data_import=[]
total_count = 0
count = 0
id = ""
try:
data = excel_to_json(path_file, None, 0)
print('*' * 20 , ' count=', len(data))
cols = [
"ردیف",
"مستند قانونی",
"موضوع",
"نتیجه",
"جلسه",
"تاریخ",
]
text_normalizer = TextNormalizer()
for item in data:
count += 1
row = item.get("ردیف", "")
description = item.get("مستند قانونی", "")
description = text_normalizer.normalize_qanon(description)
subject = item.get("موضوع", "")
subject = text_normalizer.normalize_qanon(subject)
content = item.get("نتیجه", "")
content = text_normalizer.normalize_qanon(content)
number = item.get("جلسه", "")
ts_date = item.get("تاریخ", "")
if not is_match_persian_date_format(ts_date):
ts_date = ''
print('.*'*10, ' error ts_date in ', row)
continue
title = subject + ' - جلسه ' + number + ' تاریخ ' + ts_date
main_type='تصمیم قانونی'
ts_ref='مجلس شورای اسلامی'
sub_type = ''
term = ''
is_update = False
eid ='qt_'+ uuid.uuid4().hex[:8]
data = {
"id": eid,
"title": title,
"main_type": main_type,
"sub_type": sub_type,
"term": term,
"ts_date": ts_date,
"ts_ref": ts_ref,
"description": description,
"content": content
}
bulk_data_import.append({
"_id": id,
"_source": data
})
if len(bulk_data_import) >= 100:
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
bulk_data_import = []
if len(bulk_data_import):
total_count += len(bulk_data_import)
print('=' * 10, ' import , total='+str(total_count) , str(count))
elastic.importBulkList(bulk_data_import, index_name_o)
bulk_data_import = []
except Exception as e:
print("Exception: " + str(e))
+794
View File
@@ -0,0 +1,794 @@
{
"mappings": {
"date_detection": false,
"properties": {
"id": {
"type": "keyword"
},
"title": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_fa",
"search_analyzer": "normal_analyzer_fa",
"search_quote_analyzer": "phrase_analyzer_fa"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_fa",
"search_analyzer": "phrase_analyzer_fa",
"search_quote_analyzer": "phrase_analyzer_fa"
},
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title_popular": {
"type": "text",
"analyzer": "normal_analyzer_fa",
"search_analyzer": "normal_analyzer_fa",
"search_quote_analyzer": "phrase_analyzer_fa"
},
"content": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_fa",
"search_analyzer": "normal_analyzer_fa",
"search_quote_analyzer": "phrase_analyzer_fa"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_fa",
"search_analyzer": "phrase_analyzer_fa",
"search_quote_analyzer": "phrase_analyzer_fa"
}
}
},
"embeddings": {
"type": "dense_vector",
"dims": 768,
"index": true,
"similarity": "cosine"
},
"initial": {
"properties": {
"title": {
"type": "text"
},
"content": {
"type": "text"
},
"approuve_type": {
"type": "keyword"
},
"creators": {
"type": "keyword"
},
"signers": {
"type": "keyword"
},
"approuve_number": {
"type": "text"
},
"approuve_date": {
"type": "date"
},
"letter_number": {
"type": "text"
},
"letter_date": {
"type": "date"
},
"letter_signer": {
"type": "keyword"
},
"ministers": {
"type": "keyword"
},
"files": {
"properties": {
"path": {
"type": "text"
},
"file_name": {
"type": "text"
},
"title": {
"type": "text"
}
}
}
}
},
"receive": {
"properties": {
"term_number": {
"type": "text"
},
"ref_law": {
"type": "keyword"
},
"meet_number": {
"type": "text"
},
"meet_date": {
"type": "date"
},
"register_number": {
"type": "text"
},
"publish_number": {
"type": "text"
},
"handle_type": {
"type": "keyword"
},
"handle_method": {
"type": "keyword"
}
}
},
"refer": {
"properties": {
"refer_date": {
"type": "date"
},
"commission_type": {
"type": "keyword"
},
"commission_main": {
"type": "keyword"
},
"commission_mirrors": {
"type": "keyword"
},
"commission_common": {
"properties": {
"name": {
"type": "keyword"
},
"member_count": {
"type": "integer"
},
"member_names": {
"type": "keyword"
}
}
},
"handle_85": {
"type": "keyword"
}
}
},
"commission_report": {
"properties": {
"agendas": {
"properties": {
"number": {
"type": "text"
},
"date": {
"type": "date"
}
}
},
"meets": {
"properties": {
"number": {
"type": "text"
},
"date": {
"type": "date"
}
}
},
"report_first": {
"properties": {
"approve_type": {
"type": "keyword"
},
"number": {
"type": "text"
},
"date": {
"type": "date"
}
}
},
"report_nexts": {
"properties": {
"type": {
"type": "keyword"
},
"number": {
"type": "text"
},
"date": {
"type": "date"
},
"duration_85": {
"type": "date"
},
"date_85": {
"type": "date"
}
}
}
}
},
"parl_handle": {
"properties": {
"agendas": {
"properties": {
"number": {
"type": "text"
},
"date": {
"type": "date"
}
}
},
"meets": {
"properties": {
"number": {
"type": "text"
},
"date": {
"type": "date"
}
}
},
"agree_names": {
"type": "keyword"
},
"against_names": {
"type": "keyword"
},
"demands": {
"type": "keyword"
},
"demand85_names": {
"type": "keyword"
},
"handle_infos": {
"properties": {
"type": {
"type": "keyword"
},
"number": {
"type": "text"
},
"date": {
"type": "date"
},
"duration_85": {
"type": "date"
},
"date_85": {
"type": "date"
}
}
}
}
},
"before_info": {
"properties": {
"ref_id": {
"type": "keyword"
},
"plan_type": {
"type": "keyword"
},
"discuss_type": {
"type": "keyword"
},
"ministers": {
"type": "keyword"
},
"creators": {
"type": "text"
},
"register_number": {
"type": "text"
},
"prev_number": {
"type": "text"
},
"receipt_date": {
"type": "date"
},
"discuss_date1": {
"type": "date"
},
"discuss_date2": {
"type": "date"
},
"description": {
"type": "text"
},
"commission_type": {
"type": "keyword"
},
"commission_main": {
"type": "keyword"
},
"commission_mirrors": {
"type": "keyword"
},
"content": {
"type": "text"
}
}
},
"letters": {
"properties": {
"type": {
"type": "keyword"
},
"sub_type": {
"type": "keyword"
},
"order": {
"type": "float"
},
"number": {
"type": "text"
},
"date": {
"type": "date"
},
"description": {
"type": "text"
},
"content": {
"type": "text"
},
"delay_time": {
"type": "text"
},
"expire_date": {
"type": "date"
},
"files": {
"properties": {
"path": {
"type": "text"
},
"file_name": {
"type": "text"
},
"title": {
"type": "text"
}
}
}
}
},
"counts": {
"properties": {
"key": {
"type": "keyword"
},
"value": {
"type": "text"
}
}
},
"davam_type": {
"type": "keyword"
},
"number": {
"properties": {
"row_duplicate": {
"type": "text"
},
"lib_folder": {
"type": "text"
},
"row": {
"type": "text"
},
"all": {
"type": "text"
},
"sena": {
"type": "text"
}
}
},
"archive_info": {
"properties": {
"type": {
"type": "keyword"
},
"number": {
"type": "text"
},
"description": {
"type": "text"
}
}
},
"ts_date_dotic": {
"type": "date"
},
"ts_date1": {
"type": "date"
},
"ts_ref1": {
"type": "keyword"
},
"ts_date2": {
"type": "date"
},
"ts_ref2": {
"type": "keyword"
},
"description": {
"type": "text"
},
"conformity_rrk": {
"type": "keyword"
},
"conformity_qanonyar": {
"type": "keyword"
},
"content_ocr": {
"type": "text"
},
"qanon_etebar": {
"type": "keyword"
},
"expire_date": {
"type": "date"
},
"exec_date": {
"type": "date"
},
"ref_key": {
"type": "keyword"
},
"ts_date": {
"type": "date"
},
"ts_year": {
"type": "integer"
},
"ts_ref": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"term": {
"type": "keyword"
},
"term_number": {
"type": "integer"
},
"ranking_weight": {
"type": "integer"
},
"main_type": {
"type": "keyword"
},
"sub_type": {
"type": "keyword"
},
"title_type": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"action_type": {
"type": "keyword"
},
"section_len": {
"type": "integer"
},
"eblagh": {
"properties": {
"number": {
"type": "text"
},
"date": {
"type": "date"
},
"from": {
"type": "keyword"
}
}
},
"rrk": {
"properties": {
"number": {
"type": "text"
},
"date": {
"type": "date"
}
}
},
"exceuter_organs": {
"properties": {
"id": {
"type": "integer"
},
"title": {
"type": "keyword"
}
}
},
"receiver_organs": {
"properties": {
"id": {
"type": "integer"
},
"title": {
"type": "keyword"
}
}
},
"sort_date_timestamp": {
"type": "long"
},
"qanon_relations": {
"properties": {
"from_type": {
"type": "keyword"
},
"from_section_id": {
"type": "keyword"
},
"from_section_title": {
"type": "keyword"
},
"rel_type": {
"type": "keyword"
},
"to_type": {
"type": "keyword"
},
"to_id": {
"type": "keyword"
},
"to_title": {
"type": "keyword"
},
"wait": {
"type": "integer"
},
"rel_key": {
"type": "keyword"
}
}
},
"opinion_relations": {
"properties": {
"from_type": {
"type": "keyword"
},
"from_section_id": {
"type": "keyword"
},
"from_section_title": {
"type": "keyword"
},
"rel_type": {
"type": "keyword"
},
"to_type": {
"type": "keyword"
},
"to_id": {
"type": "keyword"
},
"to_title": {
"type": "keyword"
},
"wait": {
"type": "integer"
},
"rel_key": {
"type": "keyword"
}
}
},
"fixed_date": {
"type": "date"
},
"renewal_date": {
"type": "date"
},
"exec_duration": {
"type": "text"
},
"effective_date": {
"type": "date"
},
"relation_organs": {
"type": "keyword"
},
"files": {
"properties": {
"path": {
"type": "text"
},
"file_name": {
"type": "text"
},
"title": {
"type": "text"
},
"type": {
"type": "keyword"
}
}
},
"is_delete": {
"type": "integer"
},
"time_edit": {
"type": "date"
},
"doc_tags": {
"type": "keyword"
},
"doc_states": {
"type": "keyword"
}
}
},
"settings": {
"index.max_result_window": 15000,
"index": {
"analysis": {
"analyzer": {
"phrase_analyzer_fa": {
"type": "custom",
"tokenizer": "standard",
"char_filter": [
"fa_char_filter"
],
"filter": []
},
"normal_analyzer_fa": {
"type": "custom",
"tokenizer": "standard",
"char_filter": [
"fa_char_filter"
],
"filter": [
"fa_stop"
]
}
},
"filter": {
"fa_stop": {
"type": "stop",
"stopwords": [
"یا",
"را",
"این",
"با",
"آن",
"و",
"در",
"به",
"که",
"از",
"طی",
"پس",
"چه",
"اگر",
"نه",
"آنها",
"هر",
"او",
"ما",
"من",
"تا",
"نیز",
"اما",
"یک",
"بر",
"هم",
"برای",
"کن",
"کرد",
"کردن",
"باش",
"بود",
"بودن",
"شو",
"شد",
"شدن",
"‏دار",
"داشت",
"داشتن",
"‏خواه",
"خواست",
"خواستن",
"‏گوی",
"گفت",
"گفتن",
"‏گیر",
"گرفت",
"گرفتن",
"‏آی",
"آمد",
"آمدن",
"‏توان",
"توانستن",
"‏یاب",
"یافتن",
"‏آور",
"آورد",
"آوردن",
"1",
"2",
"3",
"ص",
"4",
"و",
"5",
"ج",
"6",
"a",
"top",
"href",
"pageno"
],
"char_filter": []
}
},
"char_filter": {
"fa_char_filter": {
"type": "mapping",
"mappings": [
"٠ => 0",
"١ => 1",
"٢ => 2",
"٣ => 3",
"٤ => 4",
"٥ => 5",
"٦ => 6",
"٧ => 7",
"٨ => 8",
"٩ => 9",
"ک => ك",
"ی => ي",
"ة => ه",
"إ => ا",
"أ => ا",
"آ => ا",
"ء => ا",
"َ => ",
"ُ => ",
"ِ => ",
"ّ => ",
"ً => ",
"ٌ => ",
"ٍ => ",
"ْ => "
]
}
}
},
"number_of_shards": "1",
"number_of_replicas": "0"
}
}
}
-1
View File
@@ -1 +0,0 @@
این فایل در اولین فرصت پاک شود
@@ -0,0 +1,156 @@
import numbers
import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch, helpers
import json
import re
import zipfile
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from ..common.text_normalizer import TextNormalizer
# from general import *
from ..common.general_functions import *
from ..common.elastic_helper import ElasticHelper
# text_normal = TextNormalizer()
def repair_persian_date(item, key, id, error_list, key2=''):
res = ''
path_key = key2+'.'+key if key2 else key
if key in item :
_date = item[key]
if not _date or _date == '' :
del item[key]
return item
if _date and not is_match_persian_date_format(_date):
error_list.append({'id':id, 'key': path_key, "value":_date, "message": "match_persian_date_format" })
del item[key]
return item
if _date :
try :
res = jdate2Gregorian(_date)
except Exception as e:
error_list.append({'id':id, 'key': path_key, "value":_date, "message": "convert persian_date" })
del item[key]
return item
if res :
item[key] = res
return item
def correct_qanono_data_json( data, error_list ) :
data_new = []
for item in data :
id = item['_id']
item['_source'] = repair_persian_date(item['_source'], 'ts_date', id, error_list, '')
item['_source'] = repair_persian_date(item['_source'], 'exec_date', id, error_list, '')
item['_source'] = repair_persian_date(item['_source'], 'expire_date', id, error_list, '')
item['_source'] = repair_persian_date(item['_source'], 'fixed_date', id, error_list, '')
item['_source'] = repair_persian_date(item['_source'], 'renewal_date', id, error_list, '')
if 'eblagh' in item['_source'] :
item['_source']['eblagh'] = repair_persian_date(item['_source']['eblagh'], 'date', id, error_list, 'eblagh')
if 'rrk' in item['_source'] :
item['_source']['rrk'] = repair_persian_date(item['_source']['rrk'], 'date', id, error_list, 'rrk')
data_new.append(item)
return data_new
def restore_correct_data_to_elastic(elastic, file_path, index_name ) :
error_list = []
fileNo = 0
with zipfile.ZipFile(file_path, "r") as zObject:
fileNo += 1
packNo = 0
counter = 0
for filename in zObject.namelist():
packNo += 1
# print("index:", index_name, "=>", filename)
data = []
with zObject.open(filename) as file:
data = json.loads(file.read())
data_new = correct_qanono_data_json(data, error_list)
elastic.importJsonDataToElastic(data_new, index_name, [], True)
counter += len(data)
# print('-'*10, 'len()', str(counter) + '/ ' + str(len(data)) + ' , ' +str(len(data_new)) )
elastic.es.indices.refresh(index=index_name)
print(elastic.es.cat.count(index=index_name, format="json"))
file_log_error = 'G:/Project2/160_dotic/date_log_error.txt'
with open(file_log_error, 'w', encoding='utf8') as f :
json.dump(error_list, f, ensure_ascii=False, indent=4)
def import_data_new_qaqanon(elastic, path_file):
jsonData=[]
count = 0
id = ""
try:
try:
list_ = elastic.iterateJsonFile(path_file, True)
except Exception as e:
print("Exception es_iterate_all_documents : " + str(e))
print('*' * 20 , ' count=', elastic.total)
for mentry in list(list_):
count += 1
entry = mentry["source"]
id = entry.get("id", "")
main_type = entry.get("main_type", "")
# قانونها را نباید بروزرسانی کنیم ...چون از طرف مجلس تغییرات شناسانامه در ایندکس داشته است
if(main_type == 'قانون') :
continue
jsonData.append({
"_id": id,
"_source": entry
})
except Exception as e:
print("Exception: " + str(e))
error_list = []
jsonData_new = correct_qanono_data_json(jsonData, error_list)
pack_size = 1000
bulk = []
total = len(jsonData_new)
count = 0
for item in jsonData_new:
bulk.append(item)
if len(bulk) >= pack_size :
count += len(bulk)
elastic.importJsonDataToElastic(bulk, "mj_qa_qanon")
print( ' count update ', str(count), '/', str(total))
bulk = []
if len(bulk):
count += len(bulk)
elastic.importJsonDataToElastic(bulk, "mj_qa_qanon")
print( ' count update ', str(count), '/', str(total))
bulk = []