diff --git a/app/temp_codes.py b/app/temp_codes.py index dce2dc5..a3a0eff 100644 --- a/app/temp_codes.py +++ b/app/temp_codes.py @@ -4,20 +4,20 @@ from app.common.text_normalizer import TextNormalizer # from general import * from app.common.general_functions import * from app.common.elastic_helper import ElasticHelper -from for_ai.create_relation_tags import * -from temp_refactor_gn_dataset import * +from app.for_ai.create_relation_tags import * +from app.temp_refactor_gn_dataset import * load_dotenv(dotenv_path='config.env') -# host=os.getenv('HOST_160') -# password=os.getenv('HOST_160_PASS') +host=os.getenv('HOST_160') +password=os.getenv('HOST_160_PASS') # host=os.getenv('HOST_112') # password=os.getenv('HOST_112_PASS') -host=os.getenv('HOST_113') -password=os.getenv('HOST_113_PASS') +# host=os.getenv('HOST_113') +# password=os.getenv('HOST_113_PASS') # host=os.getenv('HOST_118') # password=os.getenv('HOST_118_PASS') diff --git a/app/test_import_excel_tcodes.py b/app/test_import_excel_tcodes.py deleted file mode 100644 index 921a3ca..0000000 --- a/app/test_import_excel_tcodes.py +++ /dev/null @@ -1,215 +0,0 @@ -import os -import re -import pandas as pd -from arabic_reshaper import reshape -from bidi.algorithm import get_display -from app.common.text_normalizer import TextNormalizer - -text_normalizer = TextNormalizer() - - -class ExcelToJsonConverter: - """ - کلاس برای تبدیل فایل‌های اکسل به JSON با پشتیبانی از فارسی - """ - - def __init__(self, input_folder="data/tetebar", output_folder="data/json_output"): - """ - مقداردهی اولیه با مسیرهای پیش‌فرض - """ - self.base_folder = "data" - self.excel_folder = input_folder - self.output_folder = output_folder - self.excel_files = [] - - def _display_persian_text(self, text): - """ - نمایش متن فارسی با شکل صحیح - """ - return get_display(reshape(text)) - - def _ensure_folders_exist(self): - """ - اطمینان از وجود پوشه‌های ورودی و خروجی - """ - os.makedirs(self.excel_folder, exist_ok=True) - os.makedirs(self.output_folder, exist_ok=True) - - def _find_excel_files(self): - """ - یافتن تمام فایل‌های اکسل در پوشه ورودی - """ - try: - self.excel_files = [f for f in os.listdir(self.excel_folder) if f.endswith(".xlsx")and not f.startswith("~$")] - if not self.excel_files: - print(self._display_persian_text("❌ هیچ فایل اکسلی در پوشه مشخص شده وجود ندارد.")) - return False - return True - except FileNotFoundError: - print(self._display_persian_text(f"❌ پوشه اکسل یافت نشد. مسیر زیر وجود ندارد: {self.excel_folder}")) - return False - - def _display_file_list(self): - """ - نمایش لیست فایل‌های پیدا شده - """ - print("\n" + self._display_persian_text("📄 لیست فایل‌های اکسل پیدا شده:")) - for idx, fname in enumerate(self.excel_files): - print(self._display_persian_text(f"{idx + 1}. {fname}")) - - def _get_user_choice(self): - """ - دریافت انتخاب کاربر برای تبدیل فایل‌ها - """ - choice = input("\n" + self._display_persian_text( - "آیا می‌خواهید همه فایل‌ها را تبدیل کنید؟ (y/n): ") + " ").strip().lower() - - if choice == "y": - return self.excel_files - - try: - index_input = input(self._display_persian_text( - "🔢 شماره فایل مورد نظر را وارد کنید: ") + " ") - index = int(index_input) - 1 - if 0 <= index < len(self.excel_files): - return [self.excel_files[index]] - print(self._display_persian_text("❌ شماره وارد شده نامعتبر است.")) - return [] - except ValueError: - print(self._display_persian_text("❌ ورودی نامعتبر است.")) - return [] - - def _parse_law_title_date(self, text): - """ - تجزیه عنوان قانون و تاریخ به title، date و other - """ - if pd.isna(text) or not isinstance(text, str): - return {"title": "", "date": "", "other": ""} - - # پاک‌سازی اولیه - text = text.strip() - - # الگوی regex برای یافتن تاریخ بعد از "مصوب" - pattern = r'^(.*?)\s*[#]*\s*مصوب\s+([۰-۹٠-٩0-9\/\s]+)$' - match = re.search(pattern, text, re.IGNORECASE | re.UNICODE) - - if match: - title_part = match.group(1).strip() - date_part = re.sub(r'\s+', '', match.group(2)) # حذف تمام فاصله‌ها - remaining = text[match.end():].strip() - - # نرمال‌سازی تاریخ با استفاده از TextNormalizer - normalized_date = text_normalizer.date_correction(date_part) - - return { - "title": title_part, - "date": normalized_date, - "other": remaining - } - - # اگر "مصوب" وجود نداشت ولی تاریخ داشت - date_pattern = r'(\d{1,2}\/\s*\d{1,2}\/\s*\d{4})' - date_match = re.search(date_pattern, text) - if date_match: - date_part = re.sub(r'\s+', '', date_match.group(1)) - title_part = text[:date_match.start()].strip() - remaining = text[date_match.end():].strip() - - return { - "title": title_part, - "date": date_part, - "other": remaining - } - - # اگر هیچ تاریخی پیدا نشد - return { - "title": text, - "date": "", - "other": "" - } - - def _convert_file(self, excel_filename): - """ - تبدیل یک فایل اکسل به JSON با اصلاح فرمت اعداد و حذف فاصله‌های اضافی - """ - try: - excel_path = os.path.join(self.excel_folder, excel_filename) - df = pd.read_excel(excel_path, header=0) - - # --- مرحله 1: پاک‌سازی نام ستون‌ها --- - df.columns = df.columns.str.replace(r'[\u00A0\s]+', ' ', regex=True).str.strip() - - # --- مرحله 2: پردازش ستون "ردیف" --- - if 'ردیف' in df.columns: - df['ردیف'] = df['ردیف'].astype(str).str.replace(r'[.\s]+', '', regex=True) - df['ردیف'] = pd.to_numeric(df['ردیف'], errors='coerce') - df['ردیف'] = df['ردیف'].fillna(method='ffill').astype(int) - - # --- مرحله 3: پر کردن ستون "عنوان قانون" --- - if "عنوان قانون و تاریخ تصویب" in df.columns: - df["عنوان قانون و تاریخ تصویب"] = df["عنوان قانون و تاریخ تصویب"].replace('', pd.NA) - df["عنوان قانون و تاریخ تصویب"] = df["عنوان قانون و تاریخ تصویب"].fillna(method='ffill') - - if "عنوان قانون و تاریخ تصویب" in df.columns: - parsed_data = df["عنوان قانون و تاریخ تصویب"].apply(self._parse_law_title_date) - df["title"] = parsed_data.apply(lambda x: x["title"]) - df["date"] = parsed_data.apply(lambda x: x["date"]) - df["other"] = parsed_data.apply(lambda x: x["other"]) - df.drop(columns=["عنوان قانون و تاریخ تصویب"], inplace=True) - # --- مرحله 4: پاک‌سازی تمام ستون‌های متنی --- - for col in df.select_dtypes(include='object').columns: - df[col] = df[col].str.strip() - df[col] = df[col].str.replace(r'\s+/', '/', regex=True) - df[col] = df[col].str.replace(r'\s+', ' ', regex=True) - - # --- مرحله 5: حذف ردیف‌های کاملاً خالی --- - df.dropna(how='all', inplace=True) - df.fillna("", inplace=True) - - # --- مرحله 6: تبدیل به JSON --- - json_data = df.to_json(orient="records", force_ascii=False, indent=4) - json_data = json_data.replace("\\/", "/") - json_name = os.path.splitext(excel_filename)[0] + ".json" - output_path = os.path.join(self.output_folder, json_name) - - with open(output_path, "w", encoding="utf-8") as f: - f.write(json_data) - - return True, json_name - - except Exception as e: - print(self._display_persian_text(f"❌ خطا در پردازش فایل {excel_filename}: {str(e)}")) - return False, None - - def convert(self): - """ - فرآیند اصلی تبدیل فایل‌ها - """ - self._ensure_folders_exist() - - if not self._find_excel_files(): - return - - self._display_file_list() - files_to_process = self._get_user_choice() - - if not files_to_process: - return - - print("\n" + self._display_persian_text("🔄 در حال پردازش فایل(های) انتخابی...")) - - success_count = 0 - for fname in files_to_process: - success, json_name = self._convert_file(fname) - if success: - print(self._display_persian_text(f"✅ فایل {fname} به {json_name} تبدیل شد.")) - success_count += 1 - - if success_count > 0: - print("\n" + self._display_persian_text("🎉 تمامی فرآیندها با موفقیت انجام شد.")) - print(self._display_persian_text(f"📁 فایل(های) JSON در این مسیر قرار دارند: {self.output_folder}")) - - -if __name__ == "__main__": - converter = ExcelToJsonConverter() - converter.convert() \ No newline at end of file diff --git a/app/test_script.py b/app/test_script.py deleted file mode 100644 index 113d9be..0000000 --- a/app/test_script.py +++ /dev/null @@ -1,6 +0,0 @@ -import arabic_reshaper -from bidi.algorithm import get_display -text = "سلام دنیا" -reshaped_text = arabic_reshaper.reshape(text) -bidi_text = get_display(reshaped_text) -print(bidi_text) \ No newline at end of file