From 75928e8c651964e53d8e0c62f6d5a537ad252c4b Mon Sep 17 00:00:00 2001 From: Mehdi104797 <92753457+Mehdi104797@users.noreply.github.com> Date: Tue, 27 May 2025 17:02:47 +0330 Subject: [PATCH 1/2] =?UTF-8?q?=D8=AA=D8=BA=DB=8C=DB=8C=D8=B1=D8=A7=D8=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- script.py | 6 + test_import_excel_tcodes.py | 215 ++++++++++++++++++++++++++++++++++++ 2 files changed, 221 insertions(+) create mode 100644 script.py create mode 100644 test_import_excel_tcodes.py diff --git a/script.py b/script.py new file mode 100644 index 0000000..113d9be --- /dev/null +++ b/script.py @@ -0,0 +1,6 @@ +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 diff --git a/test_import_excel_tcodes.py b/test_import_excel_tcodes.py new file mode 100644 index 0000000..b440510 --- /dev/null +++ b/test_import_excel_tcodes.py @@ -0,0 +1,215 @@ +import os +import re +import pandas as pd +from arabic_reshaper import reshape +from bidi.algorithm import get_display +from 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 From ab0a567ce324e7857d7b85446e945b0f964328b6 Mon Sep 17 00:00:00 2001 From: hsafaei Date: Sun, 1 Jun 2025 17:08:17 +0330 Subject: [PATCH 2/2] tetebar --- elastic_helper.py | 6 +- qanon_title_ids.txt | 2 + r3_import_excel_tcodes.py | 436 +++++++++++++++++++++++++++++++++++++- 3 files changed, 432 insertions(+), 12 deletions(-) diff --git a/elastic_helper.py b/elastic_helper.py index df133f5..f206a43 100644 --- a/elastic_helper.py +++ b/elastic_helper.py @@ -3,7 +3,7 @@ import sys import os import json from time import sleep -from elasticsearch import Elasticsearch,helpers +from elasticsearch8 import Elasticsearch,helpers class ElasticHelper(): @@ -25,8 +25,8 @@ class ElasticHelper(): http_auth=(es_user, es_pass), ) - # print(es_url) - # print(self.es) + print(es_url) + print(self.es) self.success_connect = False for a in range(0,10): diff --git a/qanon_title_ids.txt b/qanon_title_ids.txt index 4827be9..5d5083c 100644 --- a/qanon_title_ids.txt +++ b/qanon_title_ids.txt @@ -157,3 +157,5 @@ لغو تصویب نامه شماره 22742 مورخ 20/6/1341 دولت راجع به مالیات پیشه وران=qq165988 ماده واحده راجع به اخذ فارغ‌التحصیلان دیپلمه داوطلب خدمت و ارتش و شماره دانش=qq227748 موافقتنامه فرهنگی بین دولت جمهوری اسلامی ایران و دولت جمهوری متحده تانزانیا=qq85196 +قانون استخدام نیروهای مسلح شاهنشاهی ایران [قانون ارتش جمهوری اسلامی ایران]=qq113595 + diff --git a/r3_import_excel_tcodes.py b/r3_import_excel_tcodes.py index 65e7bfa..72df9e3 100644 --- a/r3_import_excel_tcodes.py +++ b/r3_import_excel_tcodes.py @@ -1,7 +1,8 @@ import os +import re from dotenv import load_dotenv from config_base import * -from general_functions import * +# from general_functions import * from text_normalizer import TextNormalizer from elastic_helper import ElasticHelper # from excel_helper import ExcelHelper @@ -179,7 +180,382 @@ def searchQanonId(elastic, index_name, qanon_title, ts_data=""): return 0, 0, {} -def importDataToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""): +def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , 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 = [] + bulk_data = [] + total_count=0 + 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]] + if code_state : + print ( 'ddddddddddddddcode_state' , code_state) + else : + print ( 'ccccccccccccccode_state' , code_state) + 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) + + data={} + # ذخیره کد در الاستیک برای شناسه های یافت شده + if section_id and section_id != 0: + item = elastic.get_doctument(index_name_o,section_id) + tcode_mains = [] + tcode_subs = [] + if "tcode_mains" in item['_source'] : + tcode_mains= item['_source']["tcode_mains"] + if "tcode_subs" in item['_source'] : + tcode_subs= item['_source']["tcode_subs"] + + code = { + "label" : tcode_label, + "id" : tcode_id + } + if code_state : + tcode_mains.append(code) + else: + tcode_subs.append(code) + data={ + '_id':section_id, + '_source' : { + 'tcode_mains': tcode_mains, + 'tcode_subs': tcode_subs, + } + } + bulk_data.append(data) + + + # انتقال دسته جمعی کدها به الاستیک + if len(bulk_data) >= 200: + total_count += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count)) + elastic.updateBulkList(bulk_data, index_name_o) + bulk_data = [] + + + + if len(bulk_data) > 0: + total_count += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) ) + elastic.updateBulkList(bulk_data, index_name_o) + + + # 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/" + + 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 get_qanon_date(title): + regex = r"مصوب(\s*\d{1,4}/\d{1,4}/\d{1,4})\s*$" + regex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*$" + ts_ref = '' + qanon_title = '' + ts_date = '' + items = title.split('#') + if len(items) == 1: + qanon_title = items[0] + else: + last = items[-1].strip() + if 'مصوب' in last : + ts_date = last.replace('مصوب').strip() + elif last : + ts_ref=last + + qanon_title= ' '.join(items[:-1]) + print('qanon_title', qanon_title) + + + if ts_date == '' : + # قانون كار مصوب 26/12/1337 + match = re.search(regex, qanon_title) + if match : + print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}") + ts_date = match.group(1).strip() + qanon_title = qanon_title[0:match.start()] + + + return qanon_title, ts_date, ts_ref + +def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""): + + df = pd.read_excel(file_excel, sheet_name=0) + + count = 0 + rows_list = df.to_dict(orient='records') + + column_names = df.columns.tolist() + # print(column_names) + + total = len(df[column_names[0]]) + print('total : ', total) + + 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 = [] + bulk_data = [] + total_count=0 + prevRow = None + try: + for row in rows_list: + row_number = row[column_names[0]] + title = row[column_names[1]] + section_title = row[column_names[2]] + ts_date = "" + code_state = "" + if title is None or is_nan_or_none_or_empty(title) or title is None or is_nan_or_none_or_empty(title) : + title = prevRow[column_names[1]] + + + 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)) + + + title = text_normalizer.normalize_search_qanon(title) + + qanon_title, ts_date, ts_ref = get_qanon_date(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_title = text_normalizer.normalize_search_qanon(str(section_title)) + # 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) + + data={} + # # ذخیره کد در الاستیک برای شناسه های یافت شده + # if section_id and section_id != 0: + # item = elastic.get_doctument(index_name_o,section_id) + # tcode_mains = [] + # tcode_subs = [] + # if "tcode_mains" in item['_source'] : + # tcode_mains= item['_source']["tcode_mains"] + # if "tcode_subs" in item['_source'] : + # tcode_subs= item['_source']["tcode_subs"] + + # code = { + # "label" : tcode_label, + # "id" : tcode_id + # } + # if code_state : + # tcode_mains.append(code) + # else: + # tcode_subs.append(code) + # data={ + # '_id':section_id, + # '_source' : { + # 'tcode_mains': tcode_mains, + # 'tcode_subs': tcode_subs, + # } + # } + # bulk_data.append(data) + + + # # انتقال دسته جمعی کدها به الاستیک + # if len(bulk_data) >= 200: + # total_count += len(bulk_data) + # print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count)) + # elastic.updateBulkList(bulk_data, index_name_o) + # bulk_data = [] + + + + # if len(bulk_data) > 0: + # total_count += len(bulk_data) + # print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) ) + # elastic.updateBulkList(bulk_data, index_name_o) + + + # 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/" + + 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: + print(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 importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""): # excel_helper = ExcelHelper() # df = excel_helper.load_data(file) @@ -354,7 +730,7 @@ def importDataToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id -def run_in_directory(elastic, directory, output): +def run_Codes_directory(elastic, directory, output): dic_code_id={ "آب" : 1, "آمار، برنامه و بودجه" : 2, @@ -382,11 +758,50 @@ def run_in_directory(elastic, directory, output): code_id = 0 if code_name in dic_code_id : code_id = dic_code_id[code_name] - importDataToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file) + importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file) else : print('00000 error 000000 ', code_name) + +def run_Etebar_directory(elastic, directory, output): + dic_code_id={ + "آب" : 1, + "آمار، برنامه و بودجه" : 2, + "آموزش و پرورش" : 3, + "آیین دادرسی مدنی" : 5, + "سلامت" : 30, + "فرهنگ و هنر" : 33, + "مسکن و شهرسازی" : 42, + "مناطق آزاد و ویژه اقتصادی" : 45, + "نفت و گاز" : 49, + } + # 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) + if '~$' in file_name : + continue + code_name = os.path.splitext(file_name)[0] + code_name = code_name.replace("نامعتبر-", "").strip() + w1 = text_normalizer.split_words(code_name)[0] + log_file = output + "/log_r_"+w1+".txt" + file_path = os.path.join(directory, file) + try: + os.makedirs(output, exist_ok=True) + except Exception as e: + print(output) + + code_id = 0 + importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file) + + # if code_name in dic_code_id : + # code_id = dic_code_id[code_name] + # importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file) + # else : + # print('00000 error 000000 ', code_name) + + @@ -398,17 +813,20 @@ password=os.getenv('HOST_160_PASS') # host=os.getenv('HOST_112') # password=os.getenv('HOST_112_PASS') +print(password) 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") +# run_Codes_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") +run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result") + +# importCodesToElastic(elastic, "./data/tcodes/مسکن و شهرسازی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r3.txt") +# importCodesToElastic(elastic, "./data/tcodes/آمار، برنامه و بودجه.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_آمار.txt") +# importCodesToElastic(elastic, "./data/tcodes/آیین دادرسی مدنی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_دادرسی.txt") +# importCodesToElastic(elastic, "./data/tcodes/نفت و گاز.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_نفت.txt") # text="قانون  بلدیه" #text = text.replace("\u00a0", " ") # No Break space