From aa47259860922d29c80c5ef8242bd7273563e78e Mon Sep 17 00:00:00 2001 From: hsafaei Date: Thu, 6 Nov 2025 11:41:24 +0330 Subject: [PATCH] majles_codes_update --- app/common/elastic_helper.py | 381 +++++++++- app/common/general_functions.py | 10 +- app/common/text_normalizer.py | 37 +- app/for_ai/codes_import_from_excel.py | 384 ++++++---- app/for_ai/codes_llm_update_to_elastic.py | 667 +++++++++++++----- ..._es.py => llm_excel_codes_import_to_es.py} | 0 app/for_ai/majles_codes_update_steps.py | 192 +++++ app/repair_data/r8_remove_fileds.py | 170 ----- app/temp_codes.py | 13 +- task.json | 191 +++++ 10 files changed, 1569 insertions(+), 476 deletions(-) rename app/for_ai/{llm_codes_import_to_es.py => llm_excel_codes_import_to_es.py} (100%) create mode 100644 app/for_ai/majles_codes_update_steps.py delete mode 100644 app/repair_data/r8_remove_fileds.py create mode 100644 task.json diff --git a/app/common/elastic_helper.py b/app/common/elastic_helper.py index 7691bd6..db48107 100644 --- a/app/common/elastic_helper.py +++ b/app/common/elastic_helper.py @@ -6,12 +6,34 @@ from time import sleep from elasticsearch import Elasticsearch,helpers class ElasticHelper(): + # ----------------------------start--------------------------- + # کلاس ElasticHelper: + # نوع ورودی: بدون ورودی مستقیم در تعریف کلاس + # نوع خروجی: شیء از نوع ElasticHelper + # عملیات: + # - متغیرهای کلاسی برای شمارش و مدیریت عملیات تعریف می‌کند + # - مسیر پیش‌فرض مپینگ‌ها را تنظیم می‌کند + # -----------------------------end---------------------------- counter = 0 total = 0 id = "" path_mappings = os.getcwd() + '/repo/_other/' + # ----------------------------start--------------------------- + # متد __init__: + # نوع ورودی: + # - es_url: آدرس Elasticsearch (str) - پیش‌فرض "http://127.0.0.1:6900" + # - es_pass: رمز عبور (str) - پیش‌فرض خالی + # - es_user: نام کاربری (str) - پیش‌فرض "elastic" + # - path_mappings: مسیر مپینگ‌ها (str) - پیش‌فرض خالی + # نوع خروجی: شیء ElasticHelper + # عملیات: + # - اتصال به Elasticsearch را برقرار می‌کند + # - در صورت وجود رمز عبور، از احراز هویت استفاده می‌کند + # - تا 10 بار برای اتصال مجدد تلاش می‌کند (هر بار 5 ثانیه انتظار) + # - در صورت عدم موفقیت، پیام خطا نمایش داده می‌شود + # -----------------------------end---------------------------- def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mappings = ""): if path_mappings : @@ -25,8 +47,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): @@ -50,7 +72,13 @@ class ElasticHelper(): self.total = 0 self.id = "" - + def search(self, **params): + try: + res = self.es.search(**params) + except: + return {'hits':{'hits':[]}} + return res + def get_doctument(self, index_name, id): res = self.es.get(index=index_name, id=id) return res @@ -59,6 +87,19 @@ class ElasticHelper(): res = self.es.exists(index=index_name, id=id) return res + + # ----------------------------start--------------------------- + # متد update_index_doc: + # نوع ورودی: + # - is_update_state: تعیین عملیات (update یا index) (bool) + # - index_name_o: نام اندیس (str) + # - eid: شناسه سند (str) + # - data: داده‌های سند (dict) + # نوع خروجی: پاسخ Elasticsearch (dict) + # عملیات: + # - اگر is_update_state=True باشد: سند را آپدیت می‌کند + # - در غیر این صورت: سند جدید ایجاد می‌کند + # -----------------------------end---------------------------- def update_index_doc(self, is_update_state, index_name_o, eid, data): if is_update_state: resp = self.es.update(index=index_name_o, id=eid, doc=data) @@ -68,6 +109,21 @@ class ElasticHelper(): return resp + # ----------------------------start--------------------------- + # متد exportToJsonForAI: + # نوع ورودی: + # - path_back: مسیر ذخیره فایل (str) + # - index_name: نام اندیس (str) + # - out_name: نام فایل خروجی (str) - پیش‌فرض خالی + # - body: بدنه جستجو (dict) - پیش‌فرض خالی + # - fields: لیست فیلدهای مورد نیاز (list) - پیش‌فرض خالی + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - داده‌های اندیس را با استفاده از scroll API دریافت می‌کند + # - پیشرفت عملیات را نمایش می‌دهد + # - داده‌ها را در فایل JSON ذخیره می‌کند + # - اگر fields مشخص شده باشد، فقط فیلدهای مورد نظر را استخراج می‌کند + # -----------------------------end---------------------------- def exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[], mode='normal', collapse_field = '') : print('*' * 50, ' start backup -->', index_name) self.counter = 0 @@ -169,14 +225,33 @@ class ElasticHelper(): ############################## - def backupIndexToZipfile(self, path_back, index_name, out_name= '', body={}, byzip = True, fields=[], noFields=[]) : + # ----------------------------start--------------------------- + # متد backupIndexToZipfile: + # نوع ورودی: + # - path_back: مسیر ذخیره فایل (str) + # - index_name: نام اندیس (str) + # - out_name: نام فایل خروجی (str) - پیش‌فرض خالی + # - body: بدنه جستجو (dict) - پیش‌فرض {"size":1000} + # - byzip: تعیین فرمت خروجی (bool) - پیش‌فرض True + # - fields: لیست فیلدهای مورد نیاز (list) - پیش‌فرض خالی + # - noFields: لیست فیلدهای مورد حذف (list) - پیش‌فرض خالی + # نوع خروجی: bool (True اگر داده وجود داشته باشد) + # عملیات: + # - داده‌های اندیس را با استفاده از scroll API دریافت می‌کند + # - پیشرفت عملیات را نمایش می‌دهد + # - داده‌ها را در فایل ZIP یا JSON ذخیره می‌کند + # - اگر fields مشخص شده باشد، فقط فیلدهای مورد نظر را استخراج می‌کند + # - اگر noFields مشخص شده باشد، فیلدهای مورد نظر را حذف می‌کند + # -----------------------------end---------------------------- + def backupIndexToZipfile(self, path_back, index_name, file_name= '', body={"size":1000}, byzip = True, fields=[], noFields=[]) : print('*' * 50, ' start backup -->', index_name) self.counter = 0 sid = None - out = out_name - if out_name == '' : - out = index_name + out = index_name + + if file_name == '' : + file_name = index_name if body == {} : @@ -189,19 +264,17 @@ class ElasticHelper(): s_res = self.es.search( index=index_name, scroll='5m', - size=1000, body=body ) - self.total = s_res["hits"]["total"]['value'] if self.total == 0 : print('total index_name by query = %d' % self.total) return False if byzip: - fout = zipfile.ZipFile(path_back + "/"+ out + '.zip', 'w') + fout = zipfile.ZipFile(path_back + "/"+ file_name + '.zip', 'w') else: - fout = open( path_back + "/"+ out + '.json', 'a+' , encoding='utf-8') + fout = open( path_back + "/"+ file_name + '.json', 'a+' , encoding='utf-8') print('start index = %s' % index_name) @@ -210,10 +283,14 @@ class ElasticHelper(): sid = s_res['_scroll_id'] scroll_size = len(s_res['hits']['hits']) file_count = 1 + prev_percent = 0 while scroll_size > 0: "Scrolling..." self.counter += scroll_size - print("progress -> %.2f %%" % ((self.counter / self.total)*100)) + percent = int((self.counter / self.total)*100) + if percent != prev_percent : + print("progress -> %.2f %%" % percent) + prev_percent = percent ############################# out_json = [] for item in s_res['hits']['hits']: @@ -253,6 +330,21 @@ class ElasticHelper(): fout.close() + # ----------------------------start--------------------------- + # متد restorFileToElastic: + # نوع ورودی: + # - path_back: مسیر فایل (str) + # - index_name: نام اندیس (str) + # - app_key: کلید برنامه برای مپینگ (str) - پیش‌فرض خالی + # - queryDelete: تعیین حذف اندیس قبل از بازیابی (bool) - پیش‌فرض True + # - map_name: نام فایل مپینگ (str) - پیش‌فرض خالی + # نوع خروجی: bool + # عملیات: + # - وجود فایل ZIP را بررسی می‌کند + # - اگر queryDelete=True باشد، از کاربر تأیید حذف را می‌گیرد + # - اندیس را ایجاد می‌کند + # - داده‌ها را از فایل ZIP به Elasticsearch بازیابی می‌کند + # -----------------------------end---------------------------- def restorFileToElastic(self, path_back, index_name, app_key = '', queryDelete = True, map_name='') : if not os.path.exists(path_back) : print(' **** error *** path not exist: ', path_back) @@ -290,6 +382,19 @@ class ElasticHelper(): self.zipFileToElastic(file_path, index_name) + # ----------------------------start--------------------------- + # متد renameElasticIndex: + # نوع ورودی: + # - index_name_i: نام اندیس منبع (str) + # - index_name_o: نام اندیس مقصد (str) + # - app_key: کلید برنامه برای مپینگ (str) - پیش‌فرض خالی + # - map_name: نام فایل مپینگ (str) - پیش‌فرض خالی + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - اندیس مقصد را ایجاد می‌کند + # - با استفاده از reindex API، داده‌ها را از اندیس منبع به مقصد منتقل می‌کند + # - پیشرفت عملیات را نمایش می‌دهد + # -----------------------------end---------------------------- def renameElasticIndex(self, index_name_i, index_name_o, app_key = '', map_name='') : if self.createIndex(index_name_o, app_key, map_name) : @@ -317,6 +422,16 @@ class ElasticHelper(): print( '----', index_name_o, ' complated') + # ----------------------------start--------------------------- + # متد deleteIndex: + # نوع ورودی: + # - index_name: نام اندیس (str) + # نوع خروجی: bool + # عملیات: + # - وجود اندیس را بررسی می‌کند + # - از کاربر تأیید حذف را می‌گیرد + # - در صورت تأیید، اندیس را حذف می‌کند + # -----------------------------end---------------------------- def deleteIndex(self, index_name) : if not self.es.indices.exists(index=index_name) : print(' ' * 10, " for delete NOT exist index :", index_name ) @@ -330,6 +445,17 @@ class ElasticHelper(): else : return False + # ----------------------------start--------------------------- + # متد query_yes_no: + # نوع ورودی: + # - question: سوال نمایش داده شده (str) + # - default: پاسخ پیش‌فرض (str) - پیش‌فرض "no" + # نوع خروجی: bool + # عملیات: + # - سوال را به کاربر نمایش می‌دهد + # - پاسخ کاربر را دریافت و اعتبارسنجی می‌کند + # - True برای 'yes'/'y' و False برای 'no'/'n' برمی‌گرداند + # -----------------------------end---------------------------- def query_yes_no(self, question, default="no"): valid = { "yes": True, "y": True, "ye": True, "no": False, "n": False } if default is None: @@ -352,6 +478,16 @@ class ElasticHelper(): else: sys.stdout.write("لطفا یکی از موارد روبرو را وارد کنید : 'yes' or 'no' " "(or 'y' or 'n').\n") + # ----------------------------start--------------------------- + # متد createIndexIfNotExist: + # نوع ورودی: + # - index_name_o: نام اندیس (str) + # - mapping_o: مپینگ اندیس (str) - پیش‌فرض خالی + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - وجود اندیس را بررسی می‌کند + # - در صورت عدم وجود، اندیس را با مپینگ مشخص شده ایجاد می‌کند + # -----------------------------end---------------------------- def createIndexIfNotExist(self, index_name_o, mapping_o=""): try: if not self.es.indices.exists(index=index_name_o): @@ -362,6 +498,19 @@ class ElasticHelper(): print("....... index exist ! ... not created") + # ----------------------------start--------------------------- + # متد createIndex: + # نوع ورودی: + # - index_name: نام اندیس (str) + # - app_key: کلید برنامه برای مپینگ (str) - پیش‌فرض خالی + # - map_name: نام فایل مپینگ (str) - پیش‌فرض خالی + # نوع خروجی: bool + # عملیات: + # - وجود اندیس را بررسی می‌کند + # - مسیر فایل مپینگ را تعیین می‌کند + # - فایل مپینگ را خوانده و اندیس را ایجاد می‌کند + # - در صورت عدم یافت فایل مپینگ، خطا نمایش داده می‌شود + # -----------------------------end---------------------------- def createIndex(self, index_name, app_key='', map_name=''): path_base = self.path_mappings @@ -408,8 +557,18 @@ class ElasticHelper(): return False + # ----------------------------start--------------------------- + # متد updateBulkList: + # نوع ورودی: + # - listData: لیست داده‌ها (list) + # - index_name: نام اندیس (str) + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - داده‌ها را به صورت bulk آپدیت می‌کند + # - از helpers.bulk Elasticsearch استفاده می‌کند + # -----------------------------end---------------------------- def updateBulkList(self, listData, index_name): - chunk_size=1000 + chunk_size=100000 raise_on_error=False raise_on_exception=False stats_only=True @@ -426,6 +585,16 @@ class ElasticHelper(): ) helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) + # ----------------------------start--------------------------- + # متد importBulkList: + # نوع ورودی: + # - listData: لیست داده‌ها (list) + # - index_name: نام اندیس (str) + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - داده‌ها را به صورت bulk وارد می‌کند + # - از helpers.bulk Elasticsearch استفاده می‌کند + # -----------------------------end---------------------------- def importBulkList(self, listData, index_name): chunk_size=100000 raise_on_error=False @@ -444,8 +613,18 @@ class ElasticHelper(): helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) + # ----------------------------start--------------------------- + # متد importJsonDataToElastic: + # نوع ورودی: + # - jsonData: داده‌های JSON (list) + # - index_name: نام اندیس (str) + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - داده‌ها را به صورت bulk وارد می‌کند + # - از helpers.bulk Elasticsearch استفاده می‌کند + # -----------------------------end---------------------------- def importJsonDataToElastic(self, jsonData, index_name, fields=[]): - chunk_size=1000 + chunk_size=100000 raise_on_error=False raise_on_exception=False stats_only=True @@ -472,6 +651,18 @@ class ElasticHelper(): helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) + # ----------------------------start--------------------------- + # متد fileToElastic: + # نوع ورودی: + # - file_path: مسیر فایل (str) + # - index_name: نام اندیس (str) + # - limit_pack: محدودیت تعداد بسته‌ها (int) - پیش‌فرض -1 + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - فایل JSON را خوانده و داده‌ها را به Elasticsearch وارد می‌کند + # - اندیس را refresh می‌کند + # - تعداد اسناد را نمایش می‌دهد + # -----------------------------end---------------------------- def fileToElastic(self, file_path, index_name, limit_pack = -1, fields=[]): if not os.path.exists(file_path): print("file zip:" , file_path , " not exist") @@ -485,6 +676,19 @@ class ElasticHelper(): self.es.indices.refresh(index=index_name) print(self.es.cat.count(index=index_name, format="json")) + # ----------------------------start--------------------------- + # متد zipFileToElastic: + # نوع ورودی: + # - file_path: مسیر فایل ZIP (str) + # - index_name: نام اندیس (str) + # - limit_pack: محدودیت تعداد فایل‌ها (int) - پیش‌فرض -1 + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - فایل ZIP را باز کرده و هر فایل JSON داخل آن را پردازش می‌کند + # - داده‌ها را به Elasticsearch وارد می‌کند + # - اندیس را refresh می‌کند + # - تعداد اسناد را نمایش می‌دهد + # -----------------------------end---------------------------- def zipFileToElastic(self, file_path, index_name, limit_pack = -1, fields=[]): if not os.path.exists(file_path): print("file zip:" , file_path , " not exist for imort to elastic : ", index_name ) @@ -514,6 +718,18 @@ class ElasticHelper(): print(" END Of Import to elastic ", index_name ,"\n") + # ----------------------------start--------------------------- + # متد iterateJsonFile: + # نوع ورودی: + # - file_path: مسیر فایل (str) + # - isZip: تعیین نوع فایل (ZIP یا JSON) (bool) - پیش‌فرض True + # - limit_pack: محدودیت تعداد فایل‌ها (int) - پیش‌فرض -1 + # نوع خروجی: ژنراتور + # عملیات: + # - اگر isZip=True باشد: فایل ZIP را پردازش می‌کند + # - اگر isZip=False باشد: فایل JSON را پردازش می‌کند + # - داده‌ها را به صورت ژنراتور برمی‌گرداند + # -----------------------------end---------------------------- def iterateJsonFile(self, file_path, isZip=True, limit_pack = -1): if not os.path.exists(file_path): print("file zip:" , file_path , " not exist iterateJsonFile " ) @@ -549,6 +765,20 @@ class ElasticHelper(): yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in data) + # ----------------------------start--------------------------- + # متد es_iterate_all_documents: + # نوع ورودی: + # - index: نام اندیس (str) + # - body: بدنه جستجو (dict) - پیش‌فرض خالی + # - pagesize: اندازه صفحه (int) - پیش‌فرض 250 + # - scroll_timeout: زمان اسکرول (str) - پیش‌فرض "25m" + # - **kwargs: پارامترهای اضافی + # نوع خروجی: ژنراتور + # عملیات: + # - تمام اسناد اندیس را با استفاده از scroll API دریافت می‌کند + # - پیشرفت عملیات را نمایش می‌دهد + # - داده‌ها را به صورت ژنراتور برمی‌گرداند + # -----------------------------end---------------------------- def es_iterate_all_documents(self, index, body="", pagesize=250, scroll_timeout="25m", **kwargs): """ Helper to iterate ALL values from a single index @@ -600,6 +830,89 @@ class ElasticHelper(): yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in hits) + def removeCustomFileds(self, index_name_i, fields=[], renameFileds={}, body={}, bulk_update_size=200): + try: + _list = [] + try: + _list = self.es_iterate_all_documents(index_name_i, body) + except Exception as e: + print(e) + + bulk_data = [] + count = 0 + total_count = 0 + for mentry in _list: + count += 1 + + entry = mentry["source"] + id = mentry["id"] + # print(id) + eid = id + + # if (count % 100) == 0 : + # print("%s -> %.2f " % (id , (count / self.total) if self.total > 0 else 0)) + + data_filled = False + data = entry + for col in fields: + if col in data : + del data[col] + + elif '.' in col : + cols = col.split('.') + subsource = entry + for sub in cols : + dCol = subsource.get(sub, None) + if dCol : + subsource = dCol + else : + break + + for col in renameFileds.items(): + if col in data : + dCol = data[col] + data[renameFileds[col]] = dCol + del data[col] + + bulk_data.append({ + '_id': eid, + '_source' : data + }) + + # انتقال دسته جمعی کدها به الاستیک + if len(bulk_data) >= bulk_update_size: + total_count += len(bulk_data) + print('=' * 5, ' update bulk --> ' , 'total='+ str(total_count) , str(count)) + self.importBulkList(bulk_data, index_name_i) + bulk_data = [] + + + if len(bulk_data) >= 0: + total_count += len(bulk_data) + print('=' * 5, ' update bulk --> ' , 'total='+ str(total_count) , str(count)) + self.importBulkList(bulk_data, index_name_i) + bulk_data = [] + + except Exception as e: + # print("1111") + print(e) + + # save_error(id, e) + + + # ----------------------------start--------------------------- + # متد moveCustomFileds: + # نوع ورودی: + # - index_name_i: نام اندیس منبع (str) + # - index_name_o: نام اندیس مقصد (str) + # - fields: لیست فیلدهای مورد انتقال (list) - پیش‌فرض خالی + # - renameFileds: دیکشنری تغییر نام فیلدها (dict) - پیش‌فرض خالی + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - تمام اسناد اندیس منبع را دریافت می‌کند + # - فیلدهای مشخص شده را استخراج و به اندیس مقصد انتقال می‌دهد + # - اگر renameFileds وجود داشته باشد، نام فیلدها را تغییر می‌دهد + # -----------------------------end---------------------------- def moveCustomFileds(self, index_name_i, index_name_o, fields=[], renameFileds={}): try: body = {} @@ -662,6 +975,15 @@ class ElasticHelper(): # save_error(id, e) + # ----------------------------start--------------------------- + # متد mappingIndex: + # نوع ورودی: + # - index_name_i: نام اندیس (str) + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - توضیح می‌دهد که تغییر مپینگ از طریق پایتون امکان‌پذیر نیست + # - باید اندیس جدیدی با مپینگ مطلوب ایجاد و رایندکس شود + # -----------------------------end---------------------------- def mappingIndex(self, index_name_i): # فقط از طریق کیبانا میشه تغییر مپ داد @@ -669,6 +991,16 @@ class ElasticHelper(): # باید ایندکس جدیدی با مپ مطلوب ایجاد کرد و رایندکس کرد pass + # ----------------------------start--------------------------- + # متد updateByQueryIndex: + # نوع ورودی: + # - index_name_i: نام اندیس (str) + # - body: بدنه آپدیت (dict) + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - اسناد را با استفاده از update_by_query API آپدیت می‌کند + # - در صورت خطا، پیام خطا نمایش داده می‌شود + # -----------------------------end---------------------------- def updateByQueryIndex(self, index_name_i, body): ## sample # body = { @@ -690,6 +1022,16 @@ class ElasticHelper(): # save_error(id, e) + # ----------------------------start--------------------------- + # متد deleteByQueryIndex: + # نوع ورودی: + # - index_name_i: نام اندیس (str) + # - body: بدنه حذف (dict) + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - اسناد را با استفاده از delete_by_query API حذف می‌کند + # - در صورت خطا، پیام خطا نمایش داده می‌شود + # -----------------------------end---------------------------- def deleteByQueryIndex(self, index_name_i, body): ## sample # body = { @@ -706,6 +1048,16 @@ class ElasticHelper(): print(e) # save_error(id, e) + # ----------------------------start--------------------------- + # متد delete_by_ids: + # نوع ورودی: + # - index_name_i: نام اندیس (str) + # - ids: لیست شناسه‌ها (list) + # نوع خروجی: بدون خروجی مستقیم + # عملیات: + # - اسناد با شناسه‌های مشخص شده را حذف می‌کند + # - در صورت خطا، پیام خطا نمایش داده می‌شود + # -----------------------------end---------------------------- def delete_by_ids(self, index_name_i, ids): try: # ids = ['test1', 'test2', 'test3'] @@ -717,4 +1069,3 @@ class ElasticHelper(): except Exception as e: print(e) # save_error(id, e) - diff --git a/app/common/general_functions.py b/app/common/general_functions.py index c2595a6..d7ca6d0 100644 --- a/app/common/general_functions.py +++ b/app/common/general_functions.py @@ -935,7 +935,13 @@ def getTitleType(caption: str) -> str: caption = re.sub(r'\s+', ' ', caption.strip()) # حذف فاصله‌های اضافی caption = caption.replace('\u200c', ' ') # جایگزینی نیم‌فاصله‌ها با فاصله کامل - if caption.startswith("الحاق ") or caption.startswith("قانون الحاق ") or caption.startswith("قانون الحاقیه "): + if "موافقتنامه" in caption or "موافقت نامه" in caption or "کنوانسیون" in caption or \ + "قرارداد بین المللی" in caption or "مقررات بین المللی" in caption or "الحاق دولت" in caption or \ + "الحاق ایران" in caption or "قرارداد بین المللی" in caption or \ + caption.startswith("قانون عضویت دولت") or caption.startswith("قانون عضویت ایران") or caption.startswith("قانون اجازه عضویت"): + + return "موافقتنامه" + elif caption.startswith("الحاق ") or caption.startswith("قانون الحاق ") or caption.startswith("قانون الحاقیه "): return "الحاقی" elif re.match(r"^قانون اضافه.*قانون", caption): return "الحاقی" @@ -986,8 +992,6 @@ def getTitleType(caption: str) -> str: elif caption.startswith("قانون موقتی ") or caption.startswith("قانون موقت "): return "موقتی" - elif "موافقتنامه" in caption or "موافقت نامه" in caption: - return "موافقتنامه" else: return "اصلی" diff --git a/app/common/text_normalizer.py b/app/common/text_normalizer.py index 5215785..ccdcc98 100644 --- a/app/common/text_normalizer.py +++ b/app/common/text_normalizer.py @@ -289,6 +289,32 @@ class TextNormalizer: text = text.strip("\u200c").strip() return text + + def repair_qanon_html(self, html): + if not html : + return "" + + text = html + text = re.sub(r'(\t)+', ' ', text) + text = re.sub(r'( )+', ' ', text) + + text = text.replace("\\n", "") + text = text.replace("\\r", "") + text = re.sub(r"(\r\n)+", "", text) + text = text.replace("\r", "") + + + text = re.sub(r"(\d+?) /(\d+?) /(\d+?)", r"\1/\2/\3", text) + text = re.sub(r"(\d+?)/ (\d+?)/ (\d+?)", r"\1/\2/\3", text) + + # جابجا کردن اعداد تاریخ + # text = re.sub(r"(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})", r"\3/\2/\1", text) + + text = re.sub(r"(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})", r"\3/\2/\1", text) + + return text + + def date_correction(self, text): text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1/\2/\3", text) @@ -451,6 +477,7 @@ class TextNormalizer: return text + def full_hamzah_normal(self, text): text = re.sub(r"ئ|ﺌ|ﺋ", "ی", text) text = re.sub(r"ؤ|ﺅ", "و", text) @@ -484,7 +511,7 @@ class TextNormalizer: # "trimLine": True # حذف فضای خالی اضافی در ابتدا و انتهای متن # } -# normalizer = TextNormalizer() +normalizer = TextNormalizer() # text = """ # سلام -- ـ ـ خوبی # دادی ییی بی داد @@ -511,3 +538,11 @@ class TextNormalizer: # # text="46- متون زیر به عنوان تبصره‌ های ( 3 ) و ( 4 ) به ماده (-187-) قانون الحاق می ‌شود:" # normalized_text = normalizer.normalize_qanon(text) # print(normalized_text) + +# html= ' قانون متمم بودجه سال 1321 كشور مصوب 05/ 09/ 1321 ' +# html = ''' + +#
3
قانون بودجه كل سال 1316 كشور مصوب 23/ 12/ 1315 +# ''' +# print(html) +# print( normalizer.repair_qanon_html(html) ) \ No newline at end of file diff --git a/app/for_ai/codes_import_from_excel.py b/app/for_ai/codes_import_from_excel.py index f7f4a5a..830dec3 100644 --- a/app/for_ai/codes_import_from_excel.py +++ b/app/for_ai/codes_import_from_excel.py @@ -15,7 +15,7 @@ from app.common.elastic_helper import ElasticHelper from app.common.config_base import * -def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = "", update_elastic = False, genrate_excel = True): +def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, file_log, result_path = "", update_elastic = False, genrate_excel = True): df = pd.read_excel(file_excel, sheet_name=0) @@ -45,7 +45,7 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ dic_error_section_title={} rows_list_new = [] bulk_data = [] - total_count=0 + total_update=0 prevRow = None try: for row in rows_list: @@ -273,8 +273,8 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ # انتقال دسته جمعی کدها به الاستیک if len(bulk_data) >= 200: - total_count += len(bulk_data) - print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count)) + total_update += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_update) , str(count)) if update_elastic : elastic.updateBulkList(bulk_data, index_name_o) bulk_data = [] @@ -282,8 +282,8 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ if len(bulk_data) > 0: - total_count += len(bulk_data) - print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) ) + total_update += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_update) , str(count) ) if update_elastic : elastic.updateBulkList(bulk_data, index_name_o) @@ -324,7 +324,7 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ # 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 = "", update_elastic = False, genrate_excel = True): +def parseCodesToExcel(elastic, file_excel, index_name_o, tcode_label, file_log, result_path = ""): df = pd.read_excel(file_excel, sheet_name=0, header=None) count = 0 @@ -343,7 +343,7 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i dic_error_section_title={} rows_list_new = [] bulk_data = [] - total_count=0 + total_update=0 try: for row in rows_list: section_title = row[column_names[0]] @@ -414,51 +414,6 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i 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)) - if update_elastic : - 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) ) - if update_elastic : - elastic.updateBulkList(bulk_data, index_name_o) - # columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش'] columns=[0, 1, 2, 3, 4, 5, 6, 7] @@ -469,10 +424,9 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i file_name = os.path.basename(file_excel) file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx') - - if genrate_excel : - print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2) - new_df.to_excel(file_excel2, index=False, engine='openpyxl') + + 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: @@ -489,25 +443,185 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4)) +def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, file_log): + + df = pd.read_excel(file_excel, sheet_name=0) + count = 0 + rows_list = df.to_dict(orient='records') + total = len(df[0]) + print('total : ', total) -def run_Codes_directory(elastic, directory, output, all_codes, update_elastic = False, genrate_excel = True): + column_names = df.columns.tolist() + print(column_names) + + file = open(file_log, 'w+', encoding='utf8') + + bulk_data = [] + total_update=0 + row_number = 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]] + qanon_id = row[column_names[5]] + section_id = row[column_names[6]] + state_match = row[column_names[7]] + + section_id_new = 0 + c_name = 'حکم' # بعضی فایلهای اصلاحی، شناسه اینجا ذخیره شده بود + if c_name in column_names : + section_id_new = row[c_name] + + if not is_nan_or_none_or_empty(section_id_new) and section_id_new != 0 : + section_id = section_id_new - # dic_code_id={ - # "آب" : 1, - # "آمار، برنامه و بودجه" : 2, - # "آموزش و پرورش" : 3, - # "آیین دادرسی مدنی" : 5, - # "سلامت" : 30, - # "فرهنگ و هنر" : 33, - # "مسکن و شهرسازی" : 42, - # "مناطق آزاد و ویژه اقتصادی" : 45, - # "نفت و گاز" : 49 - # } + count = count + 1 + if (count % 10) == 0 : + print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0)) + + + data={} + # ذخیره کد در الاستیک برای شناسه های یافت شده + if section_id and section_id != 0: + try : + item = elastic.get_doctument(index_name_o,section_id) + except Exception as e: + print('-------------Exception as e section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n') + file.write('----section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n') + continue + + if not item['found'] : + print('------------------------------ section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n') + file.write('----section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n') + continue + + 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"] + + nead_to_update = False + if code_state : + item_found = [item for item in tcode_mains if item == tcode_label] + if not item_found : + tcode_mains.append(tcode_label) + nead_to_update = True + else: + item_found = [item for item in tcode_subs if item == tcode_label] + if not item_found : + tcode_subs.append(tcode_label) + nead_to_update = True + + if nead_to_update : + data={ + '_id':section_id, + '_source' : { + 'tcode_mains': tcode_mains, + 'tcode_subs': tcode_subs, + } + } + bulk_data.append(data) + # else: + # print(" ------------ section_id not valid row_number=", row_number, " -->", section_id) + + + # انتقال دسته جمعی کدها به الاستیک + if nead_to_update and len(bulk_data) >= 200: + total_update += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_update) , str(count)) + elastic.updateBulkList(bulk_data, index_name_o) + bulk_data = [] + + + + if len(bulk_data) > 0: + total_update += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_update) , str(count) ) + elastic.updateBulkList(bulk_data, index_name_o) + + + except Exception as e: + print('######################## Exception error ---' + str(count) + ' ***' + str(e) + '\n') + file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n') + + file.close() + +def extract_codes_to_json( file_excel, tcode_label, file_json): + + df = pd.read_excel(file_excel, sheet_name=0) + count = 0 + rows_list = df.to_dict(orient='records') + total = len(df[0]) + print('total : ', total) + + column_names = df.columns.tolist() + print(column_names) + + bulk_data = [] + total_update=0 + row_number = 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]] + # qanon_id = row[column_names[5]] + section_id = row[column_names[6]] + # state_match = row[column_names[7]] + + section_id_new = 0 + # c_name = 'حکم' # بعضی فایلهای اصلاحی، شناسه اینجا ذخیره شده بود + # if c_name in column_names : + # section_id_new = row[c_name] + + if not is_nan_or_none_or_empty(section_id_new) and section_id_new != 0 : + section_id = section_id_new + + count = count + 1 + if (count % 10) == 0 : + print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0)) + + + data={} + # ذخیره کد در الاستیک برای شناسه های یافت شده + if section_id and section_id != 0: + + tcode_mains = [] + tcode_subs = [] + + data={ + 'id':section_id, + 'label': tcode_label, + 'is_main': int(code_state), + } + bulk_data.append(data) + + with open(file_json, "w", encoding="utf8") as f: + json.dump(bulk_data, f, ensure_ascii=False, indent=4) + + except Exception as e: + print('######################## Exception error ---' + str(count) + ' ***' + str(e) + '\n') + file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n') + + +def run_codes_to_elastic_directory(elastic, directory, output, all_codes, update_elastic = False, genrate_excel = True): + # 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) - code_name = os.path.splitext(file_name)[0] + _name = os.path.splitext(file_name)[0] + code_name = _name.split('_')[0] + print('=========================== start code_name ===> ', code_name) w1 = text_normalizer.split_words(code_name)[0] log_file = output + "/log_r_"+w1+".txt" file_path = os.path.join(directory, file) @@ -515,30 +629,23 @@ def run_Codes_directory(elastic, directory, output, all_codes, update_elastic = os.makedirs(output, exist_ok=True) except Exception as e: print(output) + + # if not code_name in ['پولی و مالی' ,'اداری و استخدامی'] : + # continue - code_id = 0 - # item_found = [item for item in all_codes if item.get("label") == code_name] - # if item_found : - # code_id = item_found.get("id") - importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file, "", update_elastic, genrate_excel) - # else : - # print('00000 error 000000 ', code_name) + item_found = [item for item in all_codes if item.get("title") == code_name] + if item_found : + if genrate_excel : + parseCodesToExcel(elastic, file_path, "mj_qa_section", code_name, log_file, "") + if update_elastic : + importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, log_file) + else : + print('00000 error 000000 ', code_name) def run_Etebar_directory(elastic, directory, output, all_codes, update_elastic = False, genrate_excel = True): - # 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) @@ -557,56 +664,87 @@ def run_Etebar_directory(elastic, directory, output, all_codes, update_elastic = except Exception as e: print(output) - code_id = 0 item_found = [item for item in all_codes if item.get("label") == code_name] if item_found : - code_id = item_found.get("id") - importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file, "", update_elastic, genrate_excel) + importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, log_file, "", update_elastic, genrate_excel) + else : + print('00000 error 000000 ', code_name) + + +def run_codes_extract_directory(directory, output, all_codes): + + # 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) + _name = os.path.splitext(file_name)[0] + code_name = _name.split('_')[0] + print('=========================== start code_name ===> ', code_name) + 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) + + # if not code_name in ['پولی و مالی' ,'اداری و استخدامی'] : + # continue + + item_found = [item for item in all_codes if item.get("title") == code_name] + if item_found : + extract_codes_to_json(file_path, code_name, output + f"/{code_name}.json") else : print('00000 error 000000 ', code_name) +# -------------------------------------------------------------------- Run +if __name__ == "__main__": + + load_dotenv(dotenv_path='config.env') -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_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') + print('.... codes_import_from_excel ......', host) -print(password) - -path_base_map = "G:/Project2/gateway2_main/repo/_other/" -elastic = ElasticHelper(host, password, "elastic", path_base_map) + path_base_map = "G:/Project2/gateway2_main/repo/_other/" + elastic = ElasticHelper(host, password, "elastic", path_base_map) -all_codes = [] -with open("./data/codes49.json", "r", encoding="utf8") as f: - codes_1 = json.load(f) - all_codes = codes_1 + # all_codes = [] + # with open("./data/codes49.json", "r", encoding="utf8") as f: + # codes_1 = json.load(f) + # all_codes = codes_1 -run_Codes_directory(elastic, "./data/tcodes", "./data/tcodes/result", all_codes, False, True) + #------------------------------------- + #----- انتقال مرحله اول اکسل خطایابی شده مجلس برای کدگذاری ها + # run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_1", "./data/tcodes/result", all_codes, True, False) -# run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result") + #------------------------------------- + #----- انتقال مرحله دوم اکسل خطایابی شده مجلس برای کدگذاری ها + # run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_2", "./data/tcodes/result", all_codes, True, False) -# 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") + #------------------------------------- + #----- انتقال مرحله سوم اکسل خطایابی شده مجلس برای کدگذاری ها + # run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_3", "./data/tcodes/result", all_codes, True, False) + # run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result") -file_path="data/tcodes2/فایل سند پشتیبان کد ارتباطات 27 مهر 1404.xlsx" -log_file = "/log_r_"+"ارتباطات"+".txt" -#importEtebarToElastic(elastic, file_path, "mj_qa_section", "فناوری ارتباطات", "1", log_file) + file_path="data/tcodes/tcodes_llm/فایل سند پشتیبان کد ارتباطات 27 مهر 1404.xlsx" + log_file = "/log_r_"+"ارتباطات"+".txt" + #importEtebarToElastic(elastic, file_path, "mj_qa_section", "فناوری ارتباطات", "1", log_file) -# qanon_title= 'قانون مالياتهاي مستقيم' -# qanon_title = text_normalizer.normalize_search_qanon(qanon_title) -# qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title) -# qanon_title = qanon_title.replace("–", "-") -# ts_date = '1366/12/03' -# qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon") -# print(qanon_id, score) + # qanon_title= 'قانون مالياتهاي مستقيم' + # qanon_title = text_normalizer.normalize_search_qanon(qanon_title) + # qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title) + # qanon_title = qanon_title.replace("–", "-") + # ts_date = '1366/12/03' + # qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon") + # print(qanon_id, score) diff --git a/app/for_ai/codes_llm_update_to_elastic.py b/app/for_ai/codes_llm_update_to_elastic.py index b1ebe6c..6c370cf 100644 --- a/app/for_ai/codes_llm_update_to_elastic.py +++ b/app/for_ai/codes_llm_update_to_elastic.py @@ -9,19 +9,28 @@ import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))) from app.common.elastic_helper import ElasticHelper +from app.common.general_functions import getTitleType +from app.common.text_normalizer import TextNormalizer +text_normal = TextNormalizer() -def get_files(directory): - # Pattern to match filenames like out_1.json, out_25.json, etc. - pattern = re.compile(r"output_(\d+)\.json$") +def get_files(directory, pattern_file=r"output_(\d+)\.json$"): + + pattern = None + if pattern_file : + pattern = re.compile(pattern_file) max_num = 0 list_file = [] for filename in os.listdir(directory): - match = pattern.match(filename) - if match: - list_file.append(directory+"/"+filename) + if pattern : + match = pattern.match(filename) + if match: + list_file.append(directory+"/"+filename) + else: + list_file.append(directory+"/"+filename) + return list_file @@ -41,6 +50,7 @@ def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", up processed_count = 0 total = len(data) batch_size_number = 1 + total_update = 0 list_section_id_notfound = [] @@ -78,8 +88,13 @@ def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", up list_prccessed_negative_file.append(section_id) source = {} + + history_code_last = {} + + if history_codes: + history_code_last = history_codes[-1] # تکراری هست بخاطر اجراهای تکراری روی یک داده - if history_codes and history_codes_new["sub_key"] == history_codes[-1]["sub_key"] and history_codes_new["version_key"] == history_codes[-1]["version_key"] : + if history_code_last and history_codes_new["sub_key"] == history_code_last["sub_key"] and history_codes_new["version_key"] == history_code_last["version_key"] and history_codes_new["label"] == history_code_last["label"] : if not by_ai_code : continue # دیگه چیزی برای بروز رسانی الاستیک نیست else : @@ -94,16 +109,24 @@ def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", up } source["ai_code"] = ai_code_new - # اگر کدگذاری جدید مدل با موجود مخالف بود، قبلی به کدهای فرعی اضافه شود - if not ai_code["label"] == ai_code_new["label"] : - ai_codes_new = [] - ai_code_found = False - for code in ai_codes : - if ai_code_new["score"] == code["score"] and ai_code_new["label"] == code["label"] : - ai_code_found = True - ai_codes.append(code) + ##------------------------------------------ + #### ترمیم کدهای فرعی + ai_codes_new = [] + + # حذف کد اصلی جدید از کدهای فرعی قبلی + ai_code_found = False + for code in ai_codes : + if ai_code_new["score"] == code["score"] and ai_code_new["label"] == code["label"] : + ai_code_found = True + ai_codes_new.append(code) + - source["ai_codes"] = ai_codes_new + # اگر کدگذاری جدید مدل با موجود مخالف بود، قبلی به کدهای فرعی اضافه شود + if ai_code and "label" in ai_code and not ai_code["label"] == ai_code_new["label"] : + ai_codes_new.append(ai_code) + + source["ai_codes"] = ai_codes_new + ##------------------------------------------ @@ -117,13 +140,15 @@ def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", up ) if len(list_bulk) >= batch_size : elastic.updateBulkList(list_bulk, index_name_o) + total_update += len(list_bulk) list_bulk = [] - print("updated batch : ", batch_size_number, f"/{total} --->", file_path) + print("updated batch : ", batch_size_number, f" {total_update}/{total} --->", file_path) batch_size_number += 1 if list_bulk: elastic.updateBulkList(list_bulk, index_name_o) - print("updated batch : ", batch_size_number, " --->", file_path) + total_update += len(list_bulk) + print(" .... finish updated batch : ", batch_size_number, f" {total_update}/{total} --->", file_path) batch_size_number += 1 return list_prccessed_negative_file @@ -225,6 +250,8 @@ def parse_and_update_multi_code(file_path, elastic, all_codes, index_name_o, upd "label" : label, } + + ### fill ai_codes for code in reaseon_code_item["secondary_labels"] : label1 = code["label"] label1 = label1.strip() @@ -341,7 +368,7 @@ def genrate_list_negative(paths=[],list_minues=[]): list_prccessed_negative = [] try: with open("data/codes_reaseon_oss/processed_id_negative.json", "w", encoding="utf8") as f: - json.dump(list_prccessed_negative, f) + json.dump(list_prccessed_negative, f, ensure_ascii=False, indent=4) except : list_prccessed_negative = [] @@ -360,7 +387,7 @@ def genrate_list_negative(paths=[],list_minues=[]): with open("data/codes_reaseon_oss/processed_id_negative.json", "w", encoding="utf8") as f: l_set = set(list_prccessed_negative) print("total negative len is : " , len(l_set)) - json.dump(list(l_set), f) + json.dump(list(l_set), f, ensure_ascii=False, indent=4) def import_codes_to_elastic(elastic, all_codes, by_ai_code, paths=[], list_minues=[]): @@ -390,7 +417,7 @@ def import_codes_to_elastic(elastic, all_codes, by_ai_code, paths=[], list_minue with open("data/codes_reaseon_oss/processed_id_negative.json", "w", encoding="utf8") as f: l_set = set(list_prccessed_negative) print("total negative len is : " , len(l_set)) - json.dump(list(l_set), f) + json.dump(list(l_set), f, ensure_ascii=False, indent=4) def parse_notvalid_multi_codes(paths, all_codes=[], file_not_valid="processed_id_notvalid"): @@ -428,12 +455,12 @@ def parse_notvalid_multi_codes(paths, all_codes=[], file_not_valid="processed_id with open("data/codes_reaseon_oss/code_no_valids.json", "w", encoding="utf8") as f: print("total not valid len is : " , total, len(json_no_valids.items())) - json.dump(json_no_valids, f) + json.dump(json_no_valids, f, ensure_ascii=False, indent=4) with open(f"data/codes_reaseon_oss/{file_not_valid}.json", "w", encoding="utf8") as f: l_set = set(list_prccessed_negative) print("total negative len is : " , len(l_set)) - json.dump(list(l_set), f) + json.dump(list(l_set), f, ensure_ascii=False, indent=4) def extract_sectionid_in_files(paths, sections=[], file_result="section_id_files"): @@ -461,161 +488,483 @@ def extract_sectionid_in_files(paths, sections=[], file_result="section_id_files with open(f"data/codes_reaseon_oss/{file_result}.json", "w", encoding="utf8") as f: print("total negative len is : " , len(result)) - json.dump(result, f) + json.dump(result, f, ensure_ascii=False, indent=4) -load_dotenv(dotenv_path='config.env') -host=os.getenv('HOST_160') -password=os.getenv('HOST_160_PASS') -print( "---------------->>>>>>>>>>>>>>>", host ) +def repair_notvalid_number_ai_codes( elastic, all_codes, index_name, update_to_elastic=False, body={}): + + try: + data = elastic.es_iterate_all_documents(index_name, body) + except Exception as e: + save_error(0, e) + + + list_bulk = [] + batch_size = 200 + processed_count = 0 + total = elastic.total + batch_size_number = 1 + count = 0 + for mentry in data: + count += 1 + entry = mentry["source"] + eid = entry.get("id", "") -# host=os.getenv('HOST_113') -# password=os.getenv('HOST_113_PASS') + # if (count % 100) == 0 : + # print("%s -> %.2f " % (id , (count / elastic.total) if elastic.total > 0 else 0)) -path_base_map = "G:/Project2/gateway2_main/repo/_other/" -elastic = ElasticHelper(host, password, "elastic", path_base_map) - - -#------------------------------------------------ -#---- بررسی آمار اولیه -# get_proccesed_count() - -#------------------------------------------------ -#------ استخراج موارد منفی - مرحله 1 ، بعد از انتقال به سرور جدید -# list_week_sections = extract_list_week_sections(elastic,) -# print(" list_week_sections --> ", len(list_week_sections)) - -# paths= [ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2' ] -# genrate_list_negative(paths, list_week_sections) - -#------------------------------------------------ -#------ استخراج موارد منفی مرحله 2 ، بعد از اتمام یک دور کامل -# paths= [ 'data/codes_reaseon_oss/data_h100_3' ] -# genrate_list_negative([]) + ai_codes = entry.get("ai_codes", {}) + if not ai_codes : + continue + + ai_codes_new = [] + for code in ai_codes : + label1 = code["label"] + label1 = label1.strip() + #-------------------------------- + #--- بررسی تکراری + try: + number = int(label1) # or int(value) for integers + if all_codes and number > 0 and number <= 49 : + label1 = all_codes[number-1] + except ValueError: + label1 = label1.strip('0123456789. ') + label1 = label1.lstrip('0123456789. ') + + if all_codes and not label1 in all_codes : + continue + + ai_codes_new.append({ + "label": label1, + "score" : code["score"] + }) + + ##---------------------------------------- + + source = { + "ai_codes" : ai_codes_new + } + + if not update_to_elastic : + continue + + list_bulk.append({ + "_id" : eid, + "_source": source + } + ) + + if len(list_bulk) >= batch_size : + elastic.updateBulkList(list_bulk, index_name) + list_bulk = [] + print("updated batch : ", batch_size_number, f"/{total} --->") + batch_size_number += 1 + + if list_bulk: + elastic.updateBulkList(list_bulk, index_name) + print("updated batch : ", batch_size_number) + batch_size_number += 1 + +def repair_html_title_type( elastic, index_name, update_to_elastic=False, body={}): + + try: + data = elastic.es_iterate_all_documents(index_name, body) + except Exception as e: + save_error(0, e) + + + list_bulk = [] + batch_size = 200 + processed_count = 0 + total = elastic.total + batch_size_number = 1 + count = 0 + for mentry in data: + count += 1 + entry = mentry["source"] + eid = entry.get("id", "") + + + qanon_title = entry.get("qanon_title", "") + title_type = getTitleType(qanon_title) + # if title_type == 'موافقتنامه' : + # print(title_type[::-1]) # reverce -#------------------------------------------------ -#------ درج در الاستیک - بخش ا -# list_week_sections = [] -# # list_week_sections = extract_list_week_sections(elastic,) -# paths=[ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2', 'data/codes_reaseon_oss/data_h100_3' ] -# import_codes_to_elastic(elastic, [], True, paths, list_week_sections) - + source = { + "title_type" : title_type + } + # if (count % 100) == 0 : + # print("%s -> %.2f " % (id , (count / elastic.total) if elastic.total > 0 else 0)) + ##---------------------------------------- + html = entry.get("html", {}) + if html : + html = text_normal.repair_qanon_html(html) + source['html'] = html -#------------------------------------------------ -#------ درج در الاستیک - بخش 2 -# all_codes = [] -# with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: -# codes_1 = json.load(f) -# all_codes = codes_1 + + ##---------------------------------------- + + if not update_to_elastic : + continue + + list_bulk.append({ + "_id" : eid, + "_source": source + } + ) -# paths=[ 'data/codes_reaseon_oss/data_h100_full_1', 'data/codes_reaseon_oss/data_h100_full_2', 'data/codes_reaseon_oss/data_h100_full_3', 'data/codes_reaseon_oss/data_h100_full_4' ] -# paths=[ 'data/codes_reaseon_oss/data_h100_full_test1' ] -# print(all_codes) -# import_codes_to_elastic(elastic, all_codes, False, paths) + if len(list_bulk) >= batch_size : + elastic.updateBulkList(list_bulk, index_name) + list_bulk = [] + print("updated batch : ", batch_size_number, f"/{total} --->") + batch_size_number += 1 + + if list_bulk: + elastic.updateBulkList(list_bulk, index_name) + print("updated batch : ", batch_size_number) + batch_size_number += 1 + -# #------------------------------------------------ -# ##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند -# all_codes = [] -# with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: -# codes_1 = json.load(f) -# all_codes = codes_1 -# paths=[ 'data/codes_reaseon_oss/data_h100_full_1' ] -# parse_notvalid_multi_codes(paths, all_codes, "processed_id_notvalid_step_1") -####---- count = 3080 + +def extract_codes_diff_llm_tanghih( elastic, index_name, file_result, list_ignore=[], body={}): + + try: + data = elastic.es_iterate_all_documents(index_name, body) + except Exception as e: + save_error(0, e) -# #------------------------------------------------ -# ##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند -# all_codes = [] -# with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: -# codes_1 = json.load(f) -# all_codes = codes_1 -# paths=[ 'data/codes_reaseon_oss/data_h100_full_2' ] -# parse_notvalid_multi_codes(paths, all_codes, "processed_id_notvalid_step_2") -####---- count = 1110 + + list_data = [] + batch_size = 200 + processed_count = 0 + total = elastic.total + batch_size_number = 1 + count = 0 + for mentry in data: + count += 1 + entry = mentry["source"] + eid = entry.get("id", "") -#------------------------------------------------ -##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند -# all_codes = [] -# with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: -# codes_1 = json.load(f) -# all_codes = codes_1 -# paths=[ 'data/codes_reaseon_oss/data_h100_full_3' ] -# parse_notvalid_multi_codes(paths, all_codes, "processed_id_notvalid_step_3") -####---- count = 600 + if eid in list_ignore : + continue + + # if (count % 100) == 0 : + # print("%s -> %.2f " % (id , (count / elastic.total) if elastic.total > 0 else 0)) - -#------------------------------------------------ -##---- بررسی وضعیت بعضی کدها در خروجی فایلهای مدل -# paths=[ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2', 'data/codes_reaseon_oss/data_h100_full_1', 'data/codes_reaseon_oss/data_h100_full_2', 'data/codes_reaseon_oss/data_h100_full_3', 'data/codes_reaseon_oss/data_h100_full_4' ] -# extract_sectionid_in_files(paths, sections=["qs688df5c54ea9f_017", "qs3353621", "qs3026464"], "section_id_files_1") + + ai_code = entry.get("ai_code", {}) + ai_codes = entry.get("ai_codes", []) + + tcode_mains = entry.get("tcode_mains", []) + tcode_subs = entry.get("tcode_subs", []) + + if not ai_code or not tcode_mains : + continue + + #آیا اختلاف بین دو کد هوش مصنوعی و تنقیح هست ؟ + label1 = ai_code['label'] + found = False + for code in tcode_mains : + if label1 == code : + found = True + break + + # اختلافی نیست + if found : + continue + + source = {} + history_last = {} + history_codes = entry.get("history_codes", []) + if history_codes : + history_last = history_codes[-1] + + # محتوای توضیحی هوش + if history_last and history_last["version_key"] == "D49_v2" and history_last["sub_key"] == "positive" : + source["history_codes"] = [] + source["history_codes"].append(history_last) + + source["tcode_mains"] = tcode_mains + source["tcode_subs"] = tcode_subs + source["ai_code"] = ai_code + source["ai_codes"] = ai_codes + source["id"] = eid + source["content"] = entry.get("content", "") + source["qanon_title"] = entry.get("qanon_title", "") + + list_data.append(source) + + with open(f"data/codes_reaseon_oss/{file_result}.json", "w", encoding="utf-8") as f: + print("total diffffffffffff len is : " , len(list_data)) + json.dump(list_data, f, ensure_ascii=False, indent=4) -#------------------------------------- -#--- مرحله پاکسازی- بخش 1 -# POST mj_qa_section/_update_by_query -# { -# "query": { -# "bool": { -# "must": [ -# { -# "exists": { -# "field": "ai_code.label" -# } -# }, -# { -# "bool": { -# "should": [ -# { -# "match": { -# "other_info.full_path": "امضاء" -# } -# }, -# { -# "match": { -# "other_info.full_path": "موخره" -# } -# } -# ] -# } -# } -# ] -# } -# } -# ,"script": { -# "source": """ -# ctx._source.remove("ai_code"); -# ctx._source.remove("ai_codes"); -# """, -# "lang": "painless" -# } -# } + +def repair_diff_codes_llm(elastic, paths, index_name, file_result="diff_section_ids"): + + json_no_valids = {} + list_prccessed_negative = [] + total = 0 + result=[] + bulk_data=[] + total_update = 0 + list_section_id_notfound = [] + for path in paths : + print('*', 100) + print('******** ', path) + for file in get_files(path, ""): + print(file) + data = [] + with open(file, 'r', encoding="utf8") as f: + data = json.load(f) + + print(" ...start data ", len(data)) + for item in data: + section_id = item["id"] + if not "diff_ai" in item or not "ai_result" in item["diff_ai"] : + continue + diff_ai = item["diff_ai"]["ai_result"] + label_new = diff_ai["correct_domain"] + description_new = diff_ai["correct_description"] + + if label_new == "null": + list_section_id_notfound.append(section_id) + continue + + res = None + try : + res = elastic.get_doctument(index_name, section_id) + except: + list_section_id_notfound.append(section_id) + continue + + if not res : + continue + + + history_codes = [] + ai_code = {} + ai_codes = [] + + if "ai_code" in res["_source"] : + ai_code = res["_source"]["ai_code"] + + if "ai_codes" in res["_source"] : + ai_codes = res["_source"]["ai_codes"] + + if "history_codes" in res["_source"] : + history_codes = res["_source"]["history_codes"] + + source = {} + history_last = {} + if history_codes : + history_last = history_codes[-1] + + #حذف آخرین مورد تکراری + if history_last and history_last["version_key"] == "D49_v2" and history_last["sub_key"] == "positive" : + history_codes = history_codes[:-1] + + history_code_new = { + "score" : ai_code["score"], + "label" : label_new, + "sub_key" : "positive", + "version_key" : "D49_v2", + "description" : description_new + } + history_codes.append(history_code_new) + source["history_codes"] = history_codes + + # if label_new != ai_code["label"] : + ai_code_new = { + "score" : ai_code["score"], + "label" : label_new + } + + # کد اصلی قبلی ، اگر با کد جدید همنام نباشد و در کدهای فرعی نباشد به کدهای فرعی اضافه شود + item_found = [item for item in ai_codes if item.get("label") == ai_code["label"]] + if not item_found and ai_code["label"] != label_new: + ai_code["score"] = ai_code["score"]/2 + ai_codes.append(ai_code) + source["ai_codes"] = ai_codes + + source["ai_code"] = ai_code_new + data={ + '_id':section_id, + '_source' : source + } + + bulk_data.append(data) + + # انتقال دسته جمعی کدها به الاستیک + if len(bulk_data) >= 200: + total_update += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_update)) + elastic.updateBulkList(bulk_data, index_name) + bulk_data = [] + + if len(bulk_data) > 0: + total_update += len(bulk_data) + print('=' * 5, 'law_section ===', ', total='+str(total_update) ) + elastic.updateBulkList(bulk_data, index_name) + bulk_data=[] + + # with open(f"data/codes_reaseon_oss/{file_result}.json", "w", encoding="utf8") as f: + # print("total negative len is : " , len(result)) + # json.dump(result, f, ensure_ascii=False, indent=4) + -# POST mj_qa_section/_update_by_query -# { -# "query": { -# "bool": { -# "must": [ -# { -# "exists": { -# "field": "code-ai" -# } -# } -# ] -# } -# } -# ,"script": { -# "source": """ -# ctx._source.remove("code-ai"); -# """, -# "lang": "painless" -# } -# } -#------------------------------------- +# -------------------------------------------------------------------- Run +if __name__ == "__main__": + + load_dotenv(dotenv_path='config.env') + + host=os.getenv('HOST_160') + password=os.getenv('HOST_160_PASS') + + # host=os.getenv('HOST_113') + # password=os.getenv('HOST_113_PASS') + + print( "---------------->>>>>>>>>>>>>>>", host ) + + + path_base_map = "G:/Project2/gateway2_main/repo/_other/" + elastic = ElasticHelper(host, password, "elastic", path_base_map) + + # extract_codes_diff_llm_tanghih( elastic, "mj_qa_section", "diff_llm_tanghih_2", body={}) + + #------------------------------------------------ + #---- بررسی آمار اولیه + # get_proccesed_count() + + #------------------------------------------------ + #------ استخراج موارد منفی - مرحله 1 ، بعد از انتقال به سرور جدید + # list_week_sections = extract_list_week_sections(elastic,) + # print(" list_week_sections --> ", len(list_week_sections)) + + # paths= [ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2' ] + # genrate_list_negative(paths, list_week_sections) + + #------------------------------------------------ + #------ استخراج موارد منفی مرحله 2 ، بعد از اتمام یک دور کامل + # paths= [ 'data/codes_reaseon_oss/data_h100_3' ] + # genrate_list_negative([]) + + + #------------------------------------------------ + #------ درج در الاستیک - بخش ا + # list_week_sections = [] + # # list_week_sections = extract_list_week_sections(elastic,) + # paths=[ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2', 'data/codes_reaseon_oss/data_h100_3' ] + # import_codes_to_elastic(elastic, [], True, paths, list_week_sections) + + + + #------------------------------------------------ + #------ درج در الاستیک - بخش 2 + # all_codes = [] + # with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: + # codes_1 = json.load(f) + # all_codes = codes_1 + + # paths=[ 'data/codes_reaseon_oss/data_h100_full_1', 'data/codes_reaseon_oss/data_h100_full_2', 'data/codes_reaseon_oss/data_h100_full_3', 'data/codes_reaseon_oss/data_h100_full_4' ] + # paths=[ 'data/codes_reaseon_oss/data_h100_full_test1' ] + # print(all_codes) + # import_codes_to_elastic(elastic, all_codes, False, paths) + + + # #------------------------------------------------ + # ##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند + # all_codes = [] + # with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: + # codes_1 = json.load(f) + # all_codes = codes_1 + # paths=[ 'data/codes_reaseon_oss/data_h100_full_1' ] + # parse_notvalid_multi_codes(paths, all_codes, "processed_id_notvalid_step_1") + ####---- count = 3080 + + # #------------------------------------------------ + # ##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند + # all_codes = [] + # with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: + # codes_1 = json.load(f) + # all_codes = codes_1 + # paths=[ 'data/codes_reaseon_oss/data_h100_full_2' ] + # parse_notvalid_multi_codes(paths, all_codes, "processed_id_notvalid_step_2") + ####---- count = 1110 + + #------------------------------------------------ + ##---- نام کدهای غیر معتبر ثبت شده با هوش مصنوعی را فهرست می کند + # all_codes = [] + # with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: + # codes_1 = json.load(f) + # all_codes = codes_1 + # paths=[ 'data/codes_reaseon_oss/data_h100_full_3' ] + # parse_notvalid_multi_codes(paths, all_codes, "processed_id_notvalid_step_3") + ####---- count = 600 + + + #------------------------------------------------ + ##---- بررسی وضعیت بعضی کدها در خروجی فایلهای مدل + paths=[ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2', 'data/codes_reaseon_oss/data_h100_3', 'data/codes_reaseon_oss/data_h100_full_1', 'data/codes_reaseon_oss/data_h100_full_2', 'data/codes_reaseon_oss/data_h100_full_3', 'data/codes_reaseon_oss/data_h100_full_4' ] + # extract_sectionid_in_files(paths, sections=["qs2138157"], file_result="section_id_files_2") + + + + #------------------------------------------------ + ##---- تصحیح خطای کدگذاری مدل زبانی - برای مواردی که شماره کد را ثبت کرده بود + all_codes = [] + with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: + codes_1 = json.load(f) + all_codes = codes_1 + + body={} + #repair_notvalid_number_ai_codes(elastic, all_codes, "mj_qa_section", True, body) + + #------------------------------------- + #--- مرحله پاکسازی- بخش 1 + # POST mj_qa_section/_update_by_query + # { + # "query": { + # "bool": { + # "must": [ + # { + # "exists": { + # "field": "ai_code.label" + # } + # }, + # { + # "bool": { + # "should": [ + # { + # "match": { + # "other_info.full_path": "امضاء" + # } + # }, + # { + # "match": { + # "other_info.full_path": "موخره" + # } + # } + # ] + # } + # } + # ] + # } + # } + # ,"script": { + # "source": """ + # ctx._source.remove("ai_code"); + # ctx._source.remove("ai_codes"); + # """, + # "lang": "painless" + # } + # } + diff --git a/app/for_ai/llm_codes_import_to_es.py b/app/for_ai/llm_excel_codes_import_to_es.py similarity index 100% rename from app/for_ai/llm_codes_import_to_es.py rename to app/for_ai/llm_excel_codes_import_to_es.py diff --git a/app/for_ai/majles_codes_update_steps.py b/app/for_ai/majles_codes_update_steps.py new file mode 100644 index 0000000..f739437 --- /dev/null +++ b/app/for_ai/majles_codes_update_steps.py @@ -0,0 +1,192 @@ +import numbers +import os +from dotenv import load_dotenv +from elasticsearch import Elasticsearch, helpers +import json +import re + +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))) + +from app.common.elastic_helper import ElasticHelper +from app.common.general_functions import getTitleType +from app.common.text_normalizer import TextNormalizer + +from app.for_ai.codes_llm_update_to_elastic import repair_html_title_type, import_codes_to_elastic, extract_codes_diff_llm_tanghih, repair_diff_codes_llm +from app.for_ai.codes_import_from_excel import run_codes_to_elastic_directory, run_codes_extract_directory + +text_normal = TextNormalizer() + + +load_dotenv(dotenv_path='config.env') + +# host=os.getenv('HOST_160') +# password=os.getenv('HOST_160_PASS') +# print( "---------------->>>>>>>>>>>>>>>", host ) + +host=os.getenv('HOST_113') +password=os.getenv('HOST_113_PASS') + + +print('.... majles_codes_update_steps ......', host) + +path_base_map = "G:/Project2/gateway2_main/repo/_other/" +elastic = ElasticHelper(host, password, "elastic", path_base_map) + +#------------------------------------------------ +#-- مرحله 1 : حذف فیلدهای اضافی +# body = { +# "query": { +# "bool": { +# "should": [ +# { +# "exists": {"field": "tcode"} +# }, +# { +# "exists": {"field": "nlp_parser"} +# }, +# { +# "exists": {"field": "content_normal"} +# }, +# { +# "exists": {"field": "tcode_mains"} +# }, +# { +# "exists": {"field": "tcode_subs"} +# }, +# { +# "exists": {"field": "ners_v1"} +# }, +# { +# "exists": {"field": "level"} +# }, +# { +# "exists": {"field": "code-ai"} +# }, +# ] +# } +# } +# } + +# elastic.removeCustomFileds("mj_qa_section", ["tcode","nlp_parser","content_normal","tcode_mains","tcode_subs", "ners_v1", "level", "code-ai"], {}, body ) +# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_1_remove_fileds") + +#------------------------------------- +#---- مرحله دوم، اصلاح تاریخ فیلد html و اصلاح فیلد title_type +# body={} +# repair_html_title_type( elastic, "mj_qa_section", True, body) +# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_2_html_title_type") + +#------------------------------------- +#--- مرحله پاکسازی +# POST mj_qa_section/_update_by_query +# { +# "query": { +# "bool": { +# "must": [ +# { +# "exists": { +# "field": "ai_code.label" +# } +# }, +# { +# "bool": { +# "should": [ +# { +# "match": { +# "other_info.full_path": "امضاء" +# } +# }, +# { +# "match": { +# "other_info.full_path": "موخره" +# } +# } +# ] +# } +# } +# ] +# } +# } +# ,"script": {1 +# "source": """ +# ctx._source.remove("ai_code"); +# ctx._source.remove("ai_codes"); +# """, +# "lang": "painless" +# } +# } + + +#------------------------------------------------ +#------ درج در الاستیک - بخش ا +# list_week_sections = [] +# # list_week_sections = extract_list_week_sections(elastic) +# paths=[ 'data/codes_reaseon_oss/data_g3090', 'data/codes_reaseon_oss/data_h100_1', 'data/codes_reaseon_oss/data_h100_2', 'data/codes_reaseon_oss/data_h100_3' ] +# import_codes_to_elastic(elastic, [], True, paths, list_week_sections) +# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_3_1_h100_codes") + +# #------------------------------------------------ +# # #------ درج در الاستیک - بخش 2 +# all_codes = [] +# with open("data/codes_reaseon_oss/code49_sort_prompt.json", "r", encoding="utf8") as f: +# codes_1 = json.load(f) +# all_codes = codes_1 + +# paths=[ 'data/codes_reaseon_oss/data_h100_full_1', 'data/codes_reaseon_oss/data_h100_full_2', 'data/codes_reaseon_oss/data_h100_full_3', 'data/codes_reaseon_oss/data_h100_full_4' ] +# import_codes_to_elastic(elastic, all_codes, True, paths) +# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_3_2_h100_full") + + +#------------------------------------- +#------------------------------------- +#------------------------------------- + +#----- انتقال مرحله اول اکسل خطایابی شده مجلس برای کدگذاری ها + +all_codes = [] +with open("./data/codes49.json", "r", encoding="utf8") as f: + codes_1 = json.load(f) + all_codes = codes_1 + +# run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_1", "./data/tcodes/corrected_majles/edit_1/result", all_codes, True, False) + +#------------------------------------- +#----- انتقال مرحله دوم اکسل خطایابی شده مجلس برای کدگذاری ها +# run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_2", "./data/tcodes/corrected_majles/edit_2/result", all_codes, True, False) + +#------------------------------------- +#----- انتقال مرحله سوم اکسل خطایابی شده مجلس برای کدگذاری ها +# run_codes_to_elastic_directory(elastic, "./data/tcodes/corrected_majles/edit_3", "./data/tcodes/corrected_majles/edit_3/result", all_codes, True, False) + +# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_4_edit_1_3") + +#------------------------------------- +#------ برای بررسی و خطایابی استفاده شد +#----- مواردی که کدگذاری ما مشکوک بود کشف شد و دوباره با +#----- llm +# ----- مورد ارزیابی و تولید نتیجه جدید شد که در مرحله بعد درج شد + +# list_ignore = [] +# with open("data/codes_reaseon_oss/diff_llm_tanghih_1_3_step1.json", "r", encoding="utf8") as f: +# codes_1 = json.load(f) +# for item in codes_1 : +# list_ignore.append(item["id"]) +# print(' list_ignore len ', len(list_ignore)) + +# extract_codes_diff_llm_tanghih( elastic, "mj_qa_section", "diff_llm_tanghih_1_3_step2", list_ignore, body={}) + +#------------------------------------- +#------ درج کدهای اختلافی مرحله قبل که کدگذاری مجدد انجام شد + +# paths=[ 'data/codes_reaseon_oss/data_llm_diff' ] +# repair_diff_codes_llm( elastic, paths, "mj_qa_section", "diff_section_ids_1") + +# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section", "mj_qa_section_5_diff_1") + + +#------------------------------------- +#------ استخراج برخی کدهای باقیمانده که اکسل آنها از قبل موجود هست و تولید فایل مناسب برای درج فایل محور در بانک مجلس + + +run_codes_extract_directory( "./data/tcodes/corrected_majles/not_edit", "./data/tcodes/corrected_majles/not_edit/result_json", all_codes) diff --git a/app/repair_data/r8_remove_fileds.py b/app/repair_data/r8_remove_fileds.py deleted file mode 100644 index 6e02156..0000000 --- a/app/repair_data/r8_remove_fileds.py +++ /dev/null @@ -1,170 +0,0 @@ -import os -from dotenv import load_dotenv -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 time -from app.common.config_base import * -from app.common.general_functions import * -from app.common.text_normalizer import TextNormalizer -from app.common.elastic_helper import ElasticHelper - -##-------------------------------- -# لازم است این فیلد پرشود تا مجلس بتواند دسترسی تغییر داشته باشد -##------------------------------------ - -def fill_doc_state( elastic, index_name_i, index_name_o, file_log) : - body = { - "sort": [ - {"qanon_id": {"order": "asc"}}, - {"child_order": {"order": "asc"}} - ] - } - - try: - list = elastic.es_iterate_all_documents(index_name_i, body) - except Exception as e: - save_error(0, e) - count = 0 - text_normal = TextNormalizer() - result = {} - result_new = {} - total_count = 0 - bulk_data = [] - bulk_data_section = [] - - t1= datetime.datetime.now() - print(t1) - - file = open(file_log, 'a+', encoding='utf8') - i = 0 - doc_tags=[] - qanon_id=0 - prev_qanon_id = 0 - siyasatha_list = ["qq85859", "qq260090", "qq121403", "qq222873", "qq198729", "qq121413", "qq118359", "qq305009", "qq118373", "qq286578"] - for mentry in list: - - entry = mentry["source"] - id = entry.get("id", "") - qanon_id = entry.get("qanon_id", "") - qanon_title = entry.get("qanon_title", "") - nlp_tags = entry.get("nlp_tags", []) - - ref_state = entry.get("ref_state", []) - # title_type = entry.get("title_type", "عادی") - title_type = getTitleType(qanon_title) - - if prev_qanon_id == 0 : - prev_qanon_id = qanon_id - elif prev_qanon_id != qanon_id : - data={ - '_id':prev_qanon_id, - '_source' : { - 'doc_tags': doc_tags - } - } - body = { - "script": { - "source": "ctx._source.doc_tags=params.doc_tags", - "lang": "painless", - "params" : { 'doc_tags' : doc_tags } - }, - "query": { - "term": { - "qanon_id": { "value" : prev_qanon_id } - } - } - } - elastic.updateByQueryIndex(index_name_i, body) - bulk_data.append(data) - doc_tags=[] - - if len(ref_state) > 0 : - if "مهذب" not in doc_tags : - doc_tags.append("مهذب") - elif title_type not in ["عادی", "اصلی", "موافقتنامه", "بودجه"] : - if "تبعی" not in doc_tags : - doc_tags.append("تبعی") - elif title_type in ["عادی", "اصلی", "موافقتنامه", "بودجه"] : - if "اصلی" not in doc_tags : - doc_tags.append("اصلی") - - - if qanon_id in siyasatha_list : - if "سیاستهای کلی" not in doc_tags : - doc_tags.append("سیاستهای کلی") - - if "qanon_usefull" in nlp_tags : - if "پرکاربرد" not in doc_tags : - doc_tags.append("پرکاربرد") - - prev_qanon_id = qanon_id - i=i+1 - - - if len(bulk_data) >= 10: - total_count += len(bulk_data) - print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + qanon_id) - elastic.updateBulkList(bulk_data, index_name_o) - bulk_data = [] - - if prev_qanon_id != 0: - data={ - '_id':prev_qanon_id, - '_source' : { - 'doc_tags': doc_tags - } - } - body = { - "script": { - "source": "ctx._source.doc_tags=params.doc_tags", - "lang": "painless", - "params" : { 'doc_tags' : doc_tags } - }, - "query": { - "term": { - "qanon_id": { "value" : prev_qanon_id } - } - } - } - elastic.updateByQueryIndex(index_name_i, body) - bulk_data.append(data) - - if len(bulk_data) > 0: - total_count += len(bulk_data) - print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + qanon_id ) - elastic.updateBulkList(bulk_data, index_name_o) - - file.close() - print('end success import_law_section_to_elastic') - t2= datetime.datetime.now() - print(t2-t1) - - -load_dotenv(dotenv_path='config.env') - -host=os.getenv('HOST_160') -password=os.getenv('HOST_160_PASS') - -path_base_map = "G:/Project2/gateway2_main/repo/_other/" -elastic = ElasticHelper(host, password, "elastic", path_base_map) - - -# print(dict_effected_sections) - -# try: -# item = elastic.get_doctument("mj_qa_section", "3223423") -# except Exception as e: -# print(e) -# print(type(e).__name__) -# print(str(e)) - -fill_doc_state( elastic, "mj_qa_section", "mj_qa_qanon", "./output/log_r1.txt") - - diff --git a/app/temp_codes.py b/app/temp_codes.py index a5c80fe..cd9b87a 100644 --- a/app/temp_codes.py +++ b/app/temp_codes.py @@ -16,8 +16,8 @@ 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') @@ -37,8 +37,8 @@ password = os.getenv("HOST_160_PASS") # host=os.getenv('HOST_80') # password=os.getenv('HOST_80_PASS') -# host=os.getenv('HOST_133') -# password=os.getenv('HOST_133_PASS') +host=os.getenv('HOST_133') +password=os.getenv('HOST_133_PASS') print(host) @@ -47,8 +47,11 @@ print(host) path_base_map = "G:/Project2/gateway2_main/repo/_other/" elastic = ElasticHelper(host, password, "elastic", path_base_map) + +# elastic.removeCustomFileds("mj_qa_section", ["tcode","nlp_parser","content_normal","tcode_mains","tcode_subs", "ners_v1", "level", "code-ai"]) + # elastic.backupIndexToZipfile("G:/Project2/111", "mj_mashruh") -elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section") +# elastic.backupIndexToZipfile("G:/Project2/113", "mj_qa_section") # elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section.zip', 'mj_qa_section', 'majles', False, 'mj_qa_section') # elastic.restorFileToElastic2('G:/Project2/111/gn_setting.zip', 'gn_setting', 'general', False, 'gn_setting') diff --git a/task.json b/task.json new file mode 100644 index 0000000..cdb0f57 --- /dev/null +++ b/task.json @@ -0,0 +1,191 @@ +{ + "1-H101": [ + { + "tag": "plan", + "llm": "gpt-oss-120", + "reasoning_effort": "medium", + "domain": "49", + "description": "تولید پلن کدهای 49 تا با توجه به پلن تطبیقی کدهای فرانسه", + "description2": "منتظر نظر کارشناسی مجلس برای فناوری اطلاعات هم هستیم", + "state": "end", + "users": [""] + }, + { + "tag": "match_plan_pilot", + "llm": "gpt-oss-120 ? gpt-oss-20", + "reasoning_effort": "medium", + "domain": "1 سلامت", + "description": "تطبیق هوشمند کد سلامت به پلن سلامت", + "state": "wait", + "users": [""] + }, + { + "tag": "match_plan_pilot", + "llm": "gpt-oss-120", + "reasoning_effort": "medium", + "domain": "1 یک کد", + "description": "تطبیق هوشمند کد خاص به پلن کد", + "state": "wait", + "users": [""] + }, + { + "tag": "match_plan", + "llm": "gpt-oss-120 ? gpt-oss-20", + "reasoning_effort": "medium", + "domain": "49 ? 30??", + "description": "تطبیق مادههای هر کد از 49 تا به پلان پیشنهادی هوشمند خودمان", + "state": "wait", + "users": [""] + } + ], + "1-H102": [ + { + "tag": "context", + "llm": "gpt-oss-120", + "reasoning_effort": "medium", + "domain": "12550", + "description": "سیاق نگاری کل قوانین", + "state": "wait", + "users": [ + "گیوه چی" + ] + }, + { + "tag": "semantic_chunk", + "llm": "gpt-oss-120", + "reasoning_effort": "medium", + "domain": "12550", + "description": "جزء نگاری معنایی قانون به اجزاء مناسب جهت فعالیتهای معنایی ai", + "state": "wait", + "users": [ + "گیوه چی" + ] + }, + { + "tag": "rule", + "llm": "gpt-oss-120", + "reasoning_effort": "medium", + "domain": "286000", + "description": "", + "state": "wait", + "users": [ + "گیوه چی" + ] + }, + { + "tag": "subject_full", + "llm": "gpt-oss-120", + "reasoning_effort": "medium", + "domain": "1000000", + "description": "احکام استخراجی از ماده ها", + "state": "wait", + "users": [ + "گیوه چی : موضوع و حکم" + ] + } + ], + "1": [ + { + "tag": "keyword", + "llm": "gpt-oss-20", + "reasoning_effort": "medium", + "domain": "700", + "description": "برای داده ارزیابی ", + "state": "end" + }, + { + "tag": "simpilify", + "llm": "gpt-oss-20", + "reasoning_effort": "medium", + "domain": "700", + "description": "برای داده ارزیابی ", + "state": "end" + }, + { + "tag": "NER", + "llm": "gpt-oss-20 ? gpt-oss-120", + "reasoning_effort": "medium", + "domain": "400000", + "description": "برای استخراج موجودیتها حقوقی مثل عنوان قانون، سازمان، موضوع قانون، حکم قانون، .... ", + "state": "wait", + "users": [ + "جوکار", + "گیوه چی : موضوع و حکم" + ] + } + ], + "2": [ + { + "tag": "synonym", + "lang": "fa ? ar", + "llm": "gpt-oss-20 ? gpt-oss-120", + "reasoning_effort": "medium", + "domain": "200000", + "description": "برای تصحیح بانک مترادفات عمومی و حقوقی با اسکور تطبیق معنا", + "state": "end" + }, + { + "tag": "synonym_regular", + "lang": "fa ? ar", + "llm": "gpt-oss-120", + "reasoning_effort": "medium", + "domain": "25000", + "description": "بانک کلمات حقوقی مترادف", + "state": "wait" + }, + { + "tag": "word", + "llm": "gpt-oss-20 ? gpt-oss-120", + "reasoning_effort": "medium", + "domain": "1200000", + "description": "برای بانک کلمات صحیح با اطلاعات جانبی", + "state": "wait" + } + ], + "3": [ + { + "tag": "keyword", + "llm": "gpt-oss-120 ?", + "reasoning_effort": "medium ?", + "domain": "280000" + }, + { + "tag": "stemm", + "llm": "gpt-oss-20 ? gpt-oss-120", + "reasoning_effort": "medium", + "domain": "1200000", + "description": "با کمک خروجی بانک کلمات word ، باید بررسی و طراحی شود", + "state": "wait" + }, + { + "tag": "ocr train", + "llm": "مدلهای بزرگ", + "reasoning_effort": "lora", + "domain": "10000000", + "description": "", + "state": "wait" + }, + { + "tag": "pos", + "llm": "gpt-oss-20 ? gpt-oss-120", + "reasoning_effort": "medium", + "domain": "??? bijan , 4000 nor, ...", + "description": "برای تحلیل گرامری متن فارسی", + "state": "wait", + "users": [ + "منتظر" + ] + }, + { + "tag": "summiry", + "llm": "gpt-oss-20 ? gpt-oss-120", + "reasoning_effort": "medium", + "domain": "hamfahmi ? hadith ? ", + "description": "برای بانک کلمات صحیح با اطلاعات جانبی", + "state": "wait", + "users": [ + "جوکار" + ] + } + ] +} \ No newline at end of file