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()