From 372251aff73bf9319972e65ec55d39d9a09bcd23 Mon Sep 17 00:00:00 2001 From: hsafaei Date: Tue, 30 Sep 2025 16:40:11 +0330 Subject: [PATCH 1/4] llm_codes_import_to_es --- app/common/general_functions.py | 16 + app/for_ai/ai_json_move_to_index.py | 102 ++++++- app/for_ai/ai_repair_data.py | 16 - ...odes_tokens.py => extract_codes_tokens.py} | 0 ...se_spell.py => extract_sections_tokens.py} | 0 app/for_ai/history_excel_update_to_es.py | 143 --------- app/for_ai/llm_codes_import_to_es.py | 276 ++++++++++++++++++ ...e_llm.py => llm_france_codes_translate.py} | 0 app/temp_codes.py | 19 +- 9 files changed, 402 insertions(+), 170 deletions(-) rename app/for_ai/{codes_tokens.py => extract_codes_tokens.py} (100%) rename app/for_ai/{extract_tokens_parse_spell.py => extract_sections_tokens.py} (100%) delete mode 100644 app/for_ai/history_excel_update_to_es.py create mode 100644 app/for_ai/llm_codes_import_to_es.py rename app/for_ai/{translate_llm.py => llm_france_codes_translate.py} (100%) diff --git a/app/common/general_functions.py b/app/common/general_functions.py index dc43eaa..c2595a6 100644 --- a/app/common/general_functions.py +++ b/app/common/general_functions.py @@ -40,6 +40,22 @@ class JSONEncoder(json.JSONEncoder): return json.JSONEncoder.default(self, obj) +##-------------------------------- +# لازم است این فیلد پرشود تا مجلس بتواند دسترسی تغییر داشته باشد +##------------------------------------ +def is_section_empty(section_path): + filtered_keys = ['فصل','موخره','امضاء','عنوان'] + if '>' in section_path: + path_parts = section_path.split('>') + for key in filtered_keys: + if key in path_parts[-1]: + return True + else: + for key in filtered_keys: + if key in section_path: + return True + return False + def isNeedHtml(html): if " {len(list_bulk)}") +def moveClassifierAiCodes2( elastic, data_codes, version_key, index_name_i, index_name_o) : + body = {} + + try: + list = elastic.es_iterate_all_documents(index_name_i, body) + except Exception as e: + save_error(0, e) + + text_normal = TextNormalizer() + + t1= datetime.datetime.now() + print(t1) + + send_round = 1 + list_bulk=[] + best_code = {} + other_codes = [] + eid = 0 + + try: + for mentry in list: + + entry = mentry["source"] + id = entry.get("id", "") + other_info = entry.get("other_info", {}) + history_codes = entry.get("history_codes", []) + eid = id + + if other_info and is_section_empty(other_info['full_path']) : + continue + + if not eid in data_codes : + continue + + best_code = data_codes[eid]['best-class'] + other_codes = data_codes[eid]['other-classes'] + if not best_code and not other_codes : + continue + + ai_code = best_code + ai_codes = other_codes + # print(ai_code) + #---------------------------------------------- + for label_doc in ai_codes: + label = text_normal.normalize_qanon(label_doc["label"]) + label_doc["label"] = label + if label_doc["score"] >= 1 : + label_doc["score"] = label_doc["score"] / 100 + + history_codes.append({ + "version_key": version_key, + "sub_key": "sub", + "label": text_normal.normalize_qanon(label_doc['label']), + "score": label_doc['score'], + }) + + if ai_code : + if ai_code["score"] >= 1 : + ai_code["score"] = ai_code["score"] / 100 + + label = ai_code["label"] + label = text_normal.normalize_qanon(ai_code["label"]) + ai_code["label"] = label + history_codes.append({ + "version_key": version_key, + "sub_key": "main", + "label": text_normal.normalize_qanon(ai_code['label']), + "score": ai_code['score'], + }) + #---------------------------------------------- + + list_bulk.append({ + '_id': eid, + '_source': { + "ai_code" : ai_code, + "ai_codes" : ai_codes, + "history_codes": history_codes + } + }) + + if len(list_bulk) > 200 : + elastic.updateBulkList(list_bulk, index_name_o) + list_bulk = [] + # print(f"send_round -> {send_round}") + send_round += 1 + except Exception as e: + print("error ---> id ", eid, " message: ", str(e)) + + if len(list_bulk) : + elastic.updateBulkList(list_bulk, index_name_o) + print(f"last ::: send_round -> {len(list_bulk)}") + + + + + + + + load_dotenv(dotenv_path='config.env') @@ -281,6 +380,7 @@ with open("./data/all_sections_classes_full_140407.json", "r", encoding="utf-8") classes = json.load(f) -moveClassifierAiCodes(elastic,"mj_qa_section", classes, "D49_v1") +# moveClassifierAiCodes(elastic,"mj_qa_section", classes, "D49_v1") +moveClassifierAiCodes2(elastic, classes, "D49_v1","mj_qa_section", "mj_qa_section") print('finished!') diff --git a/app/for_ai/ai_repair_data.py b/app/for_ai/ai_repair_data.py index 9d6036e..0540e4f 100644 --- a/app/for_ai/ai_repair_data.py +++ b/app/for_ai/ai_repair_data.py @@ -15,22 +15,6 @@ from app.common.general_functions import * from app.common.text_normalizer import TextNormalizer from app.common.elastic_helper import ElasticHelper -##-------------------------------- -# لازم است این فیلد پرشود تا مجلس بتواند دسترسی تغییر داشته باشد -##------------------------------------ -def is_section_empty(section_path): - filtered_keys = ['فصل','موخره','امضاء','عنوان'] - if '>' in section_path: - path_parts = section_path.split('>') - for key in filtered_keys: - if key in path_parts[-1]: - return True - else: - for key in filtered_keys: - if key in section_path: - return True - return False - def repair_ai_codes( elastic, index_name_i, index_name_o, file_log) : body = {} diff --git a/app/for_ai/codes_tokens.py b/app/for_ai/extract_codes_tokens.py similarity index 100% rename from app/for_ai/codes_tokens.py rename to app/for_ai/extract_codes_tokens.py diff --git a/app/for_ai/extract_tokens_parse_spell.py b/app/for_ai/extract_sections_tokens.py similarity index 100% rename from app/for_ai/extract_tokens_parse_spell.py rename to app/for_ai/extract_sections_tokens.py diff --git a/app/for_ai/history_excel_update_to_es.py b/app/for_ai/history_excel_update_to_es.py deleted file mode 100644 index a0ef61d..0000000 --- a/app/for_ai/history_excel_update_to_es.py +++ /dev/null @@ -1,143 +0,0 @@ -from pydantic import BaseModel -from typing import List, Optional -import io -import os -import json -import orjson -from collections import defaultdict -from dotenv import load_dotenv -from app.common.text_normalizer import TextNormalizer -from app.common.elastic_helper import ElasticHelper -import pandas as pd -import json -from pathlib import Path -from openpyxl import Workbook - -def excel_to_json(excel_file, required_columns=None, sheet_name=0): - """ - خواندن یک sheet از فایل اکسل و تبدیل به لیست دیکشنری. - - Args: - sheet_name: نام sheet (رشته) یا شماره آن (عدد). پیش‌فرض: 0 (اولین sheet) - """ - sheet_names = pd.ExcelFile(excel_file).sheet_names - - print("all sheet") - for i, name in enumerate(sheet_names, start=1): - print(f" {i}. {name}") - - df = pd.read_excel(excel_file, sheet_name=sheet_name) - - if required_columns is None: - selected_columns = df.columns.tolist() - else: - missing = [col for col in required_columns if col not in df.columns] - if missing: - raise ValueError(f"ستون‌های مفقوده در sheet '{sheet_name}': {missing}") - selected_columns = required_columns - - return df[selected_columns].to_dict(orient='records') - - -def update_history_code(data, index_name, elastic=None, sub_key='', qanon_name='' ): - - - # Base-Model - class DataHistoryIn(BaseModel): - id: str - content: str - path: str - qanon: str - reason: str - confidence: float - - class DataHistoryOut(BaseModel): - label: str - score: float - version_key: str = 'llm_cg5m_v1' - sub_key: Optional[List[str]] = ['positve', 'negative'] - description: str - - - version_key= "llm_cg5m_v1" - domain_type = "D51_v1" - text_normalizer = TextNormalizer() - with open("data/ai/domains_list.json", "r", encoding="utf-8") as file: - domains_list = json.load(file) - dict_domain_id = {} - labels_list = [] - for item in domains_list[domain_type] : - item["domain_name"] = text_normalizer.normalize_qanon(item["domain_name"]) - labels_list.append(item["domain_name"]) - dict_domain_id[item["domain_name"]] = str(item["id"]) - - for i in data : - id = i['id'] - res = elastic.get_doctument(index_name, id) - h_data = res['_source']['history_codes'] - print( - '='*25, - f'before {type(h_data)} -> {h_data}', - F'id {id}', - sep='\n', - ) - new_data = { - "label": text_normalizer.normalize_qanon(qanon_name), # normalize - "score": i['confidence'], - "sub_key": sub_key, - "description": i['reason'], - "version_key": version_key - } - h_data.append(new_data) - for qq in h_data: - if "description" not in qq.keys(): - qq['description'] = '' - - - print( - '='*25, - f'after {type(h_data)} -> {h_data}', - F'id {id}', - sep='\n', - ) - try: - resp = elastic.update_index_doc(True, index_name, id, h_data) - except Exception as e: - import traceback - print(traceback.print_exc()) - print(f'data NOT saved in es') - break - - -####################################################################################################### -# exel_path1 = r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\insurance_result_score.xlsx" -# qanon_name1 = 'بیمـه‌' -# # p sheet insurance -# # n sheet Non_insurance -# # exel2_path = r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\international_trade_result_4.xlsx" -# # p sheet International_Trade -# # n sheet Non_International_Trade -# exel_path3 = r"C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\water_result.xlsx" -# qanon_name3 = 'آب' -# # p sheet water -# # n sheet Non_water - - -# 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') - -# path_base_map = "G:/Project2/gateway2_main/repo/_other/" -# elastic = ElasticHelper(host, password, "elastic", path_base_map) - -# # positve -# # negative -# result = excel_to_json(excel_file=exel_path1, sheet_name='insurance') -# result_f = update_history_code(data=result,elastic=elastic,index_name='mj_qa_section', sub_key='positve', qanon_name=qanon_name1) - -# o1= r'C:\Users\TAVASI-3\Desktop\init_mahdi\project\dataParsers\data\ai\test1_excel.json' \ No newline at end of file diff --git a/app/for_ai/llm_codes_import_to_es.py b/app/for_ai/llm_codes_import_to_es.py new file mode 100644 index 0000000..9907ba7 --- /dev/null +++ b/app/for_ai/llm_codes_import_to_es.py @@ -0,0 +1,276 @@ +# from pydantic import BaseModel +from typing import List, Optional +import io +import os +import json +from collections import defaultdict +from dotenv import load_dotenv +from app.common.text_normalizer import TextNormalizer +from app.common.elastic_helper import ElasticHelper +import pandas as pd +import json +from pathlib import Path +from openpyxl import Workbook + + +# # Base-Model +# class DataHistoryIn(BaseModel): +# id: str +# content: str +# path: str +# qanon: str +# reason: str +# confidence: float + +# class DataHistoryOut(BaseModel): +# label: str +# score: float +# version_key: str = "llm_cg5m_v1" +# sub_key: Optional[List[str]] = ["positve", "negative"] +# description: str +text_normalizer = TextNormalizer() + + +def excel_to_json(excel_file, required_columns=None, sheet_name=0): + """ + خواندن یک sheet از فایل اکسل و تبدیل به لیست دیکشنری. + + Args: + sheet_name: نام sheet (رشته) یا شماره آن (عدد). پیش‌فرض: 0 (اولین sheet) + """ + sheet_names = pd.ExcelFile(excel_file).sheet_names + + print("all sheet") + for i, name in enumerate(sheet_names, start=1): + print(f" {i}. {name}") + + df = pd.read_excel(excel_file, sheet_name=sheet_name) + + if required_columns is None: + selected_columns = df.columns.tolist() + else: + missing = [col for col in required_columns if col not in df.columns] + if missing: + raise ValueError(f"ستون‌های مفقوده در sheet '{sheet_name}': {missing}") + selected_columns = required_columns + + return df[selected_columns].to_dict(orient="records") + + +def update_history_code(elastic, data, index_name_o, sub_key, label_name, version_key): + + send_round = 1 + index = 1 + list_bulk=[] + total = len(data) + percent = 0 + eid = 0 + try: + for item in data: + id = item["id"] + index += 1 + # if id in ["qs1002289", "qs1002290"] : + # continue + eid = id + res = elastic.get_doctument(index_name_o, eid) + history_codes = res["_source"]["history_codes"] + + new_data = { + "label": text_normalizer.normalize_qanon(label_name), # normalize + "sub_key": sub_key, + "description": item["reason"], + "version_key": version_key, + } + if "confidence" in item: + new_data["score"] = item["confidence"] + + history_codes.append(new_data) + # for qq in h_data: + # if "description" not in qq.keys(): + # qq['description'] = '' + + list_bulk.append( + { + "_id": eid, + "_source": { + "history_codes": history_codes, + }, + } + ) + + if len(list_bulk) > 200: + _percent = int ( (index * 100) / total) + print(f" --> {_percent}% index {index}/{total} id {eid}", sep="\n") + + elastic.updateBulkList(list_bulk, index_name_o) + list_bulk = [] + # print(f"send_round -> {send_round}") + send_round += 1 + except Exception as e: + print("error ---> id ", eid, " message: ", str(e)) + + if len(list_bulk): + elastic.updateBulkList(list_bulk, index_name_o) + print(f"last ::: send_round -> {len(list_bulk)}") + + +def run_all_excels_codes(elastic, excel_path_base, list_excel, version_key ): + for item in list_excel : + result = excel_to_json(excel_path_base + item["file"], sheet_name=0) + print( "########## positve ########### ended file to json ", len(result) , item["label"] ) + update_history_code( elastic, result, "mj_qa_section", "positve", item["label"], version_key) + + result = excel_to_json(excel_path_base + item["file"], sheet_name=1) + print( "########## negative ########### ended file to json ", len(result) , item["label"] ) + update_history_code( elastic, result, "mj_qa_section", "negative", item["label"], version_key) + + +def run_all_json_codes(elastic, path_base, index_name_o, version_key): + + path = Path(path_base) + # به‌دست آوردن لیست فایل‌های JSON + json_files = list(path.glob('*.json')) + + # jump = True + # jump_id = True + for file in json_files : + file_path = Path(file) + label_name = file_path.stem.replace("_batch_result", "").strip() + + if "log" in label_name : + print( " !!!!!!!-------jumped---------> is log ... ", file_path.stem) + continue + + label_name = text_normalizer.normalize_qanon(label_name) + + ###--- بخاطر خطای خاص در اجرای اول و نیاز به پرش در ادامه + # if label_name == "نظام‌های صنفی و حرفه‌ای" : + # jump = False + # jump_id = True + + # if jump : + # print( "jump ", label_name ) + # continue + + if label_name in ["تجارت خارجی", "آب", "بیمه"] : + print( " !!!!!!!----------------> duplicate by excel ... ", label_name) + continue + + data = {} + with open(file, 'r', encoding='utf-8') as json_file: + data = json.load(json_file) + + + send_round = 1 + index = 1 + list_bulk=[] + total = len(data.items()) + eid = 0 + try: + print( "########## start ########### json to es ", total , label_name ) + for id, item in data.items() : + index += 1 + eid = id + + # if id == "qs876345" : + # jump_id = False + + # if jump_id : + # print( "jump_id ", eid ) + # continue + + if "error" in item : + continue + + if not "rel" in item : + continue + + res = elastic.get_doctument(index_name_o, eid) + history_codes = res["_source"]["history_codes"] + + sub_key = "positive" + if not item["rel"] : + sub_key = "negative" + + new_data = { + "label": label_name, + "sub_key": sub_key, + "description": item["reason"], + "version_key": version_key, + } + if "confidence" in item: + new_data["score"] = item["confidence"] + + history_codes.append(new_data) + + + list_bulk.append( + { + "_id": eid, + "_source": { + "history_codes": history_codes, + }, + } + ) + + if len(list_bulk) > 200: + _percent = int ( (index * 100) / total) + print(f" --> {_percent}% index {index}/{total} id {eid}", sep="\n") + + elastic.updateBulkList(list_bulk, index_name_o) + list_bulk = [] + # print(f"send_round -> {send_round}") + send_round += 1 + except Exception as e: + print("error ---> id ", eid, " message: ", str(e)) + + if len(list_bulk): + elastic.updateBulkList(list_bulk, index_name_o) + print(f"last ::: send_round -> {len(list_bulk)}") + + + +####################################################################################################### + + +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') + +path_base_map = "G:/Project2/gateway2_main/repo/_other/" +elastic = ElasticHelper(host, password, "elastic", path_base_map) + +#---------------------------------------------------------------- +#------یکبار اجرا شد و نباید تکرار شود +excel_path_base = "data/ai/llm_codes/" +list_excel = [ + # { + # "file" : "insurance_result_score.xlsx", + # "label" : "بیمه" + # }, + # { + # "file" : "international_trade_result_4.xlsx", + # "label" : "تجارت خارجی" + # }, + # { + # "file" : "water_result.xlsx", + # "label" : "آب" + # } +] + +# run_all_excels_codes(elastic, excel_path_base, list_excel, "llm_cg5m_v1") + +#---------------------------------------------------------------- +#------یکبار اجرا شد و نباید تکرار شود +# path_base = "data/ai/llm_codes/batch_entity_result/" +# run_all_json_codes(elastic, path_base, "mj_qa_section", "llm_cg5m_v1") +#---------------------------------------------------------------- + + + + diff --git a/app/for_ai/translate_llm.py b/app/for_ai/llm_france_codes_translate.py similarity index 100% rename from app/for_ai/translate_llm.py rename to app/for_ai/llm_france_codes_translate.py diff --git a/app/temp_codes.py b/app/temp_codes.py index 05b777c..42571d4 100644 --- a/app/temp_codes.py +++ b/app/temp_codes.py @@ -11,8 +11,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') @@ -23,8 +23,8 @@ load_dotenv(dotenv_path="config.env") # host=os.getenv('HOST_118') # password=os.getenv('HOST_118_PASS') -host=os.getenv('HOST_60') -password=os.getenv('HOST_60_PASS') +# host=os.getenv('HOST_60') +# password=os.getenv('HOST_60_PASS') # host=os.getenv('HOST_161') # password=os.getenv('HOST_161_PASS') @@ -42,12 +42,14 @@ print(host) path_base_map = "G:/Project2/gateway2_main/repo/_other/" elastic = ElasticHelper(host, password, "elastic", path_base_map) -# elastic.backupIndexToZipfile("G:/Project2/111/haditha", "dh_volume") -# elastic.backupIndexToZipfile("G:/Project2/111/haditha", "dh_haditha") +# elastic.backupIndexToZipfile("G:/Project2/111", "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') + # elastic.backupIndexToZipfile("G:/Project2/111", "mn_spr_sanad") # elastic.createIndex( 'mn_spr_sanad', 'monir', 'mn_spr_sanad') -elastic.restorFileToElastic2('G:/Project2/111/mn_spr_sanad.zip', 'mn_spr_sanad', 'monir', False, 'mn_spr_sanad') +# elastic.restorFileToElastic2('G:/Project2/111/mn_spr_sanad.zip', 'mn_spr_sanad', 'monir', False, 'mn_spr_sanad') # elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_domain") # elastic.createIndex( 'mj_qa_domain', 'majles', 'mj_domain') @@ -70,9 +72,6 @@ elastic.restorFileToElastic2('G:/Project2/111/mn_spr_sanad.zip', 'mn_spr_sanad', # elastic.restorFileToElastic2('G:/Project2/111/mn_sanad.zip', 'mn_sanad', 'monir', False, 'mn_sanad') -# elastic.backupIndexToZipfile("G:/Project2/111", "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') # ------------------------------------------------------- ## # elastic.backupIndexToZipfile("G:/Project2/111", "dh_haditha") From c80813aaa8bed2d311930acd3e9b01b82823880f Mon Sep 17 00:00:00 2001 From: hsafaei Date: Sun, 12 Oct 2025 11:11:44 +0330 Subject: [PATCH 2/4] ai hostorycode --- ...epair_data.py => ai_base_history_codes.py} | 12 +-- app/for_ai/ai_json_move_to_index.py | 79 +++++++++++++++---- app/temp_codes.py | 9 ++- 3 files changed, 74 insertions(+), 26 deletions(-) rename app/for_ai/{ai_repair_data.py => ai_base_history_codes.py} (94%) diff --git a/app/for_ai/ai_repair_data.py b/app/for_ai/ai_base_history_codes.py similarity index 94% rename from app/for_ai/ai_repair_data.py rename to app/for_ai/ai_base_history_codes.py index 0540e4f..7d6d329 100644 --- a/app/for_ai/ai_repair_data.py +++ b/app/for_ai/ai_base_history_codes.py @@ -16,7 +16,7 @@ from app.common.text_normalizer import TextNormalizer from app.common.elastic_helper import ElasticHelper -def repair_ai_codes( elastic, index_name_i, index_name_o, file_log) : +def ai_fill_history_codes( elastic, index_name_i, index_name_o, file_log) : body = {} try: @@ -172,16 +172,16 @@ def repair_ai_codes( elastic, index_name_i, index_name_o, file_log) : 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_113') -password=os.getenv('HOST_113_PASS') +# host=os.getenv('HOST_113') +# password=os.getenv('HOST_113_PASS') path_base_map = "G:/Project2/gateway2_main/repo/_other/" elastic = ElasticHelper(host, password, "elastic", path_base_map) -repair_ai_codes( elastic, "mj_qa_section", "mj_qa_section", "./output/log__ai_r1.txt") +ai_fill_history_codes( elastic, "mj_qa_section", "mj_qa_section", "./output/log__ai_r1.txt") diff --git a/app/for_ai/ai_json_move_to_index.py b/app/for_ai/ai_json_move_to_index.py index 2ae4372..834ea64 100644 --- a/app/for_ai/ai_json_move_to_index.py +++ b/app/for_ai/ai_json_move_to_index.py @@ -134,7 +134,7 @@ def moveSimplifies(elastic, index_name_o, data): -def moveClassifierAiCodes(elastic, index_name_o, data, version_key = "D51_v1"): +def copyToAiCodesHistoryCodes(elastic, index_name_o, data, version_key = "D51_v1"): text_normal = TextNormalizer() index = 0 percent_prev = 0 @@ -217,7 +217,7 @@ def moveClassifierAiCodes(elastic, index_name_o, data, version_key = "D51_v1"): print(f"last ::: send_round -> {len(list_bulk)}") -def moveClassifierAiCodes2( elastic, data_codes, version_key, index_name_i, index_name_o) : +def copyToAiCodesHistoryCodes2( elastic, data_codes, version_key, index_name_i, index_name_o) : body = {} try: @@ -320,14 +320,14 @@ def moveClassifierAiCodes2( elastic, data_codes, version_key, index_name_i, inde load_dotenv(dotenv_path='config.env') -host=os.getenv('HOST_160') -password=os.getenv('HOST_160_PASS') +# host=os.getenv('HOST_160') +# password=os.getenv('HOST_160_PASS') # host=os.getenv('HOST_112') # password=os.getenv('HOST_112_PASS') -# host=os.getenv('HOST_113') -# password=os.getenv('HOST_113_PASS') +host=os.getenv('HOST_113') +password=os.getenv('HOST_113_PASS') # host=os.getenv('HOST_60') # password=os.getenv('HOST_60_PASS') @@ -365,22 +365,69 @@ elastic = ElasticHelper(host, password, "elastic", path_base_map) # classes = json.load(f) -#---#-----داده های جدید نسخه -#with open("./data/all_sections_classes_new_140406.json", "r", encoding="utf-8") as f: +# #---#-----داده های جدید نسخه +# with open("./data/all_sections_classes_new_140406.json", "r", encoding="utf-8") as f: # classes = json.load(f) -# moveClassifierAiCodes(elastic,"mj_qa_section", classes, "D51_v1") - -#--------------------------- +# copyToAiCodesHistoryCodes(elastic,"mj_qa_section", classes, "D51_v1") #--------------------------- # کدهای 49 گانه آموزش دیده با دیتاست خوب حدود15 الی 20 هزارتایی که با کمک فایلهای تبیین مفهومی و مدلهای زبانی به دست آمد -with open("./data/all_sections_classes_full_140407.json", "r", encoding="utf-8") as f: - classes = json.load(f) +# with open("./data/all_sections_classes_full_140407.json", "r", encoding="utf-8") as f: +# classes = json.load(f) -# moveClassifierAiCodes(elastic,"mj_qa_section", classes, "D49_v1") -moveClassifierAiCodes2(elastic, classes, "D49_v1","mj_qa_section", "mj_qa_section") -print('finished!') +# copyToAiCodesHistoryCodes(elastic,"mj_qa_section", classes, "D49_v1") +#--برای سرعت بیشتر ، که چندان اثری نداشت +# copyToAiCodesHistoryCodes2(elastic, classes, "D49_v1","mj_qa_section", "mj_qa_section") +# print('finished!') + + + +#-------------------------------------- +#-- دستی این مورد اجرا شد، تا اجزاءی که در مرحله جدید کدگذاری نشدند، و از قبل مواردی داشتند پاک شوند +# POST mj_qa_section/_update_by_query +# { +# "query": { +# "bool": { +# "should": [ +# { +# "terms": { +# "ai_code.label": [ +# "امور زیربنایی", +# "نظامی و انتظامی" , +# "کشاورزی و دامپروری", +# "منابع طبیعی", +# "آیین دادرسی مدنی و اداری", +# "اطلاعات و امنیت" +# ] +# } +# }, +# { +# "terms": { +# "ai_codes.label": [ +# "امور زیربنایی", +# "نظامی و انتظامی" , +# "کشاورزی و دامپروری", +# "منابع طبیعی", +# "آیین دادرسی مدنی و اداری", +# "اطلاعات و امنیت" +# ] +# } +# } +# ] +# } +# } +# ,"script": { +# "source": """ +# ctx._source.remove("ai_code"); +# ctx._source.remove("ai_codes"); +# """, +# "lang": "painless" +# } +# } + + +#-------------------------------------- diff --git a/app/temp_codes.py b/app/temp_codes.py index 42571d4..bd14f02 100644 --- a/app/temp_codes.py +++ b/app/temp_codes.py @@ -42,18 +42,19 @@ print(host) path_base_map = "G:/Project2/gateway2_main/repo/_other/" elastic = ElasticHelper(host, password, "elastic", path_base_map) -# elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section") +# elastic.backupIndexToZipfile("G:/Project2/111", "mj_mashruh") +#elastic.backupIndexToZipfile("G:/Project2/111", "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') # elastic.backupIndexToZipfile("G:/Project2/111", "mn_spr_sanad") -# elastic.createIndex( 'mn_spr_sanad', 'monir', 'mn_spr_sanad') +#elastic.createIndex( 'mn_spr_sanad', 'monir', 'mn_spr_sanad') # elastic.restorFileToElastic2('G:/Project2/111/mn_spr_sanad.zip', 'mn_spr_sanad', 'monir', False, 'mn_spr_sanad') # elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_domain") -# elastic.createIndex( 'mj_qa_domain', 'majles', 'mj_domain') -# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_domain_base1.zip', 'mj_qa_domain', 'majles', False, 'mj_qa_domain') +# elastic.createIndex( 'mj_qa_domain', 'majles', 'mj_qa_domain') +# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_domain.zip', 'mj_qa_domain', 'majles', False, 'mj_qa_domain') # elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section-m1") From 498c3c4bd1f97630496961b37135a24748dacf2b Mon Sep 17 00:00:00 2001 From: hsafaei Date: Mon, 27 Oct 2025 12:54:04 +0330 Subject: [PATCH 3/4] procces refactor majles --- app/common/elastic_helper.py | 65 +- app/common/qanon_functions.py | 202 +++++- .../codes_import_from_excel.py} | 460 +++++-------- app/for_ai/codes_llm_update_to_elastic.py | 621 ++++++++++++++++++ app/for_ai/extract_json_to_ai.py | 117 ++++ app/for_ai/repiar_ids.py | 63 ++ app/repair_data/r8_remove_fileds.py | 170 +++++ app/temp_codes.py | 9 +- 8 files changed, 1395 insertions(+), 312 deletions(-) rename app/{repair_data/r3_import_excel_tcodes.py => for_ai/codes_import_from_excel.py} (61%) create mode 100644 app/for_ai/codes_llm_update_to_elastic.py create mode 100644 app/for_ai/extract_json_to_ai.py create mode 100644 app/for_ai/repiar_ids.py create mode 100644 app/repair_data/r8_remove_fileds.py diff --git a/app/common/elastic_helper.py b/app/common/elastic_helper.py index 3425cf9..7691bd6 100644 --- a/app/common/elastic_helper.py +++ b/app/common/elastic_helper.py @@ -68,7 +68,7 @@ class ElasticHelper(): return resp - def exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[]) : + def exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[], mode='normal', collapse_field = '') : print('*' * 50, ' start backup -->', index_name) self.counter = 0 sid = None @@ -77,8 +77,6 @@ class ElasticHelper(): if out_name == '' : out = index_name - fout = open( path_back + "/"+ out + '.json', 'a+' , encoding='utf-8') - s_res = self.es.search( index=index_name, scroll='5m', @@ -92,28 +90,69 @@ class ElasticHelper(): sid = s_res['_scroll_id'] scroll_size = len(s_res['hits']['hits']) - file_count = 1 + pack_count = 1 out_json = [] + if mode == 'dict' or collapse_field: + out_json = {} + + prev_collapse_value = '' + pack_collapse = [] while scroll_size > 0: "Scrolling..." self.counter += scroll_size print("progress -> %.2f %%" % ((self.counter / self.total)*100)) + + #### for test + # if pack_count > 2 : + # break + pack_count += 1 ############################# for item in s_res['hits']['hits']: - - if fields : - item2={} - item2['id']=item['_id'] + id = item['_id'] + item2=None + if mode =='id' : # فقط شناسه ها نیاز هست + item2=id + elif fields : + item2={} + item2['id']= id for kf in fields : #print(kf) if kf in item['_source'] : # print(item['_source'][kf]) item2[kf] = item['_source'][kf] + elif '.' in kf : + cols = kf.split('.') + subsource = item['_source'] + for sub in cols : + if sub in subsource : + subsource = subsource[sub] + continue + else: + break + key = kf.replace(".", "__") + item2[key] = subsource + #exit() else : + item2={} item2=item - out_json.append(item2) + if collapse_field and collapse_field in item['_source']: + collapse_value = item['_source'][collapse_field] + if not prev_collapse_value : + prev_collapse_value = collapse_value + + if not collapse_value == prev_collapse_value : + out_json[prev_collapse_value] = pack_collapse + pack_collapse = [] + prev_collapse_value = collapse_value + + pack_collapse.append(item2) + + elif mode == 'dict': + out_json[id]=item2 + else : + out_json.append(item2) s_res = self.es.scroll(scroll_id=sid, scroll='2m', request_timeout=100000) @@ -121,8 +160,12 @@ class ElasticHelper(): scroll_size = len(s_res['hits']['hits']) sid = None - text = json.dumps(out_json, ensure_ascii=False) - fout.write(text) + + if collapse_field and prev_collapse_value and pack_collapse : + out_json[prev_collapse_value] = pack_collapse + + with open(path_back + "/"+ out, "w", encoding="utf-8") as fout: + json.dump(out_json, fout, ensure_ascii=False, indent=4) ############################## diff --git a/app/common/qanon_functions.py b/app/common/qanon_functions.py index 1abafdf..e0cf936 100644 --- a/app/common/qanon_functions.py +++ b/app/common/qanon_functions.py @@ -71,8 +71,21 @@ def get_section_title_sample(text): text = re.sub(r"( |\u200C|\>|\<|-|ـ)+", "", text) return text -def searchSectionId(elastic, index_name, qanon_id, section_title): +def searchSectionIdContent(elastic, index_name, qanon_id, section_title, content): score = 100 + should = [] + should.append( { + "match": { + "other_info.full_path": section_title + } + }) + + should.append( { + "match": { + "content": content + } + }) + body = { "query": { "bool": { @@ -86,8 +99,61 @@ def searchSectionId(elastic, index_name, qanon_id, section_title): }, { - "match": { - "other_info.full_path": section_title + "bool" : { + "should" : should + } + } + ] + } + } + } + + s_res = elastic.es.search(index=index_name, body=body) + content = get_section_title_sample(content) + for item in s_res["hits"]["hits"]: + content = item['_source']['content'] + + # حذف اضافات + content_sample = get_section_title_sample(content) + + if content == content : + return item["_id"], 100, item + + return 0, 0, {} + + +def searchSectionId(elastic, index_name, qanon_id, section_title, other_title=[]): + score = 100 + should = [] + should.append( { + "match": { + "other_info.full_path": section_title + } + }) + + for title in other_title : + if title and title != section_title : + should.append( { + "match": { + "other_info.full_path": title + } + }) + + body = { + "query": { + "bool": { + "must": [ + { + "term": { + "qanon_id": { + "value": qanon_id + } + } + + }, + { + "bool" : { + "should" : should } } ] @@ -100,10 +166,29 @@ def searchSectionId(elastic, index_name, qanon_id, section_title): other_info = item['_source']['other_info'] title = other_info['full_path'] # حذف اضافات - title = get_section_title_sample(title) + title_sample = get_section_title_sample(title) - if title == section_title : + if title_sample == section_title : return item["_id"], 100, item + + title_sample2 = title + title_sample2 = re.sub(r'^(فصل|کتاب|قسمت|بخش)\s*?(اول|دوم|سوم|چهارم|پنجم|ششم|هفتم|هشتم|نهم|دهم|یازدهم|دوازدهم|سیزدهم|هفدهم|هجدهم|نوزدهم|بیستم)', '', title_sample2) + title_sample2 = title_sample2.replace('ماده واحده', '') + title_sample2 = title_sample2.replace('متن', '') + title_sample2 = title_sample2.replace('پیوست', '') + title_sample2 = title_sample2.replace('ضمیمه', '') + title_sample2 = title_sample2.strip(' ><') + title_sample2 = title_sample2.lstrip(' ><') + title_sample2 = get_section_title_sample(title_sample2) + + # if title_sample2 != title_sample : + # print('searchSectionId : ', title_sample, title_sample2) + + if title_sample2 == section_title : + return item["_id"], 100, item + + if title_sample2 in other_title or title in other_title : + return item["_id"], 95, item return 0, 0, {} @@ -186,7 +271,7 @@ def searchQanonTitleOfContent(elastic, qanon_title, ts_data="", index_name="mj_q return 0, 0, {} -def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"): +def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon", ts_ref=""): score = 100 body = { "query": { @@ -226,6 +311,10 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"): total = s_res["hits"]["total"]['value'] qanon_title_sample = re.sub(r"( |\u200C)+", "", qanon_title) + qanon_title_sample2 = re.sub(r"^(.+?)(\(.+\))$", r"\1", qanon_title_sample) + qanon_title_sample = get_qanon_title_sample(qanon_title_sample) + qanon_title_sample2 = get_qanon_title_sample(qanon_title_sample2) + list_equal = [] for item in s_res["hits"]["hits"]: title = item['_source']['title'] @@ -233,14 +322,14 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"): title_sample = get_qanon_title_sample(title) title_sample = re.sub(r"( |\u200C)+", "", title_sample) - if title_sample == qanon_title_sample : + if title_sample == qanon_title_sample or title_sample == qanon_title_sample2: list_equal.append(item) else : qanon_title_sample = get_qanon_title_sample(qanon_title) title_sample = get_qanon_title_sample(title) - if title_sample == qanon_title_sample : + if title_sample == qanon_title_sample or title_sample == qanon_title_sample2: list_equal.append(item) if len(list_equal) == 1 : @@ -251,7 +340,11 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"): return item["_id"], score, item for item in list_equal : - if ts_data == item['_source']['ts_date'] : + if ts_data and ts_data == item['_source']['ts_date'] : + score = 100 + return item["_id"], score, item + + if ts_ref and ts_ref == item['_source']['ts_ref'] : score = 100 return item["_id"], score, item @@ -263,17 +356,21 @@ def searchQanonId(elastic, qanon_title, ts_data="", index_name="mj_qa_qanon"): return 0, 0, {} -def get_qanon_date(title): +def get_qanon_date(title, byDateCorrection = True): # 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*$" - regex_ex = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*((مجلس|کمیسیون|کمیسیونهای|هیات|شورای).{1,50})$" + regex1 = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*$" + regex2 = r"مصوب\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*((مجلس|کمیسیون|نخست وزیر|کمیسیونهای|هیات|شورای).{1,50})$" + regex3 = r"تاریخ تصویب\s*:*\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*مرجع تصویب\s*:*\s*((مجلس|کمیسیون|نخست وزیر|کمیسیونهای|هیات|شورای).{1,50})$" + regex4 = r"مرجع تصویب\s*:*\s*((مجلس|کمیسیون|نخست وزیر|کمیسیونهای|هیات|شورای).{1,50})\s*تاریخ تصویب\s*:*\s*(\d{1,4}/\s*\d{1,4}/\s*\d{1,4})\s*$" ts_ref = '' qanon_title = '' ts_date = '' title=title.strip().strip(' #=').strip() + title=title.replace("\r", " ").replace("\n", " ").replace(" ", " ").replace(" ", " ") title=title.replace("=", "#") title=title.replace("#مصوب#", "#مصوب ") title=title.replace("#مصوب #", "#مصوب ") + items = title.split('#') if len(items) == 1: qanon_title = items[0] @@ -294,28 +391,89 @@ def get_qanon_date(title): if ts_date == '' : # قانون كار مصوب 26/12/1337 - match = re.search(regex, qanon_title) + match = re.search(regex1, 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()] if ts_date == '': - match = re.search(regex_ex, qanon_title) + match = re.search(regex2, qanon_title) if match : #print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}") ts_date = match.group(1).strip() ts_ref = match.group(2).strip() qanon_title = qanon_title[0:match.start()] + if ts_date == '': + match = re.search(regex3, qanon_title) + if match : + #print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}") + ts_date = match.group(1).strip() + ts_ref = match.group(2).strip() + qanon_title = qanon_title[0:match.start()] + + if ts_date == '': + match = re.search(regex4, qanon_title) + if match : + #print(f"Match found: {match.group(1)} at position {match.start()}-{match.end()}") + ts_ref = match.group(1).strip() + ts_date = match.group(3).strip() + qanon_title = qanon_title[0:match.start()] + + if byDateCorrection and ts_date == '': + title = text_normalizer.date_correction(title) + return get_qanon_date(title, False) return qanon_title, ts_date, ts_ref + +# ماده 1 -> ماده یک +# ماده دوم -> ماده دیم +# ماده دوم -> ماده دویم +def get_section_title2(title): + + regex1 = r"^(جزء|بند|ماده|فصل|مبحث|ردیف|جدول|تبصره|پیوست|قسمت)(\s*)(\d+?)$" + title=title.strip() + title2 = '' + title3 = '' + match = re.search(regex1, title) + if match : + try: + number = int(match.group(3).strip()) + s_number1, s_number2 = number_to_persian(number) + if s_number1 : + title2 = match.group(1) + match.group(2) + s_number1 + title3 = match.group(1) + match.group(2) + s_number2 + except : + title2 = '' + title3 = '' + + if title2 == '' : + title2 = title.replace('دیم', 'دوم') + title2 = title.replace('دویم', 'دوم') + + return [title2, title3] + +def number_to_persian(num): + ones = ["صفر", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه"] + ones2 = ["صفر", "اول", "دوم", "سوم", "چهارم", "پنجم", "ششم", "هفتم", "هشتم", "نهم"] + if 0 <= num < 10: + return ones[num], ones2[num] + else: + return "" + def get_section_correct(title): title=title.strip().strip(' #=').strip() - if title == 'کل قانون' or title == 'متن قانون' or title == 'متن' or title == 'تمام قانون' or title == 'کل مصوبه': + all_titles = ['تمام ماده ها','همه ماده ها','تمام مواد','همه مواد','کل قانون','متن قانون','متن','تمام قانون','کل مصوبه'] + if title in all_titles : return ['all'] + + if re.match(r'^(.+)\(.*\)$', title) : + title_1 = re.sub(r'^(.+)\(.*\)$', r'\1', title) + if title_1 in all_titles : + return ['all'] title=title.replace('"', '') title=title.replace('اصلاحی', '') @@ -323,10 +481,13 @@ def get_section_correct(title): subs = title.split('،') result = [] - for item in subs : - item=re.sub(r"(جزء|بند|ماده|فصل|مبحث|ردیف|جدول|تبصره|پیوست|قسمت)", r"#\1", item) + for item in subs : + if not item : + continue + item=re.sub(r"(جزء|بند|ماده|فصل|مبحث|ردیف|جدول|تبصره|باب|کتاب|پیوست|ضمیمه|قسمت)", r"#\1", item) items = item.split('#') - items.reverse() + if re.match(r"(فصل|مبحث|ردیف|جدول|باب|کتاب|پیوست|ضمیمه|قسمت)", items[-1]) : + items.reverse() item = '> '.join(items).strip(' >').replace(' ', '') item = text_normalizer.word_digit_correction(item) result.append(item) @@ -364,4 +525,7 @@ def get__all_section_qanon(elastic, index_name, qanon_id): # print(qanon_title) # qanon_title="قانون الحاق دو تبصره بعنوان تبصره‌ های 3 و 4 به ماده 9 قانون روابط موجر و مستأجر مصوب 13 /2 /1362" # qanon_title = get_qanon_title_sample(qanon_title) -# print(qanon_title) \ No newline at end of file +# print(qanon_title) + +# print( get_section_number_correct('ماده 1') ) + diff --git a/app/repair_data/r3_import_excel_tcodes.py b/app/for_ai/codes_import_from_excel.py similarity index 61% rename from app/repair_data/r3_import_excel_tcodes.py rename to app/for_ai/codes_import_from_excel.py index dc80e23..f7f4a5a 100644 --- a/app/repair_data/r3_import_excel_tcodes.py +++ b/app/for_ai/codes_import_from_excel.py @@ -4,187 +4,18 @@ import traceback import json import pandas as pd from dotenv import load_dotenv + +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))) + + # from app.common.general_functions import * from app.common.qanon_functions import * from app.common.elastic_helper import ElasticHelper from app.common.config_base import * -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, qanon_title, ts_date, "mj_qa_qanon") - # اگر قابل اطمینان نبود، خطا ثبت کند - 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 == True : - 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 importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""): +def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = "", update_elastic = False, genrate_excel = True): df = pd.read_excel(file_excel, sheet_name=0) @@ -198,9 +29,17 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ total = len(df[column_names[0]]) print('total : ', total) - file = open(file_log, 'w+', encoding='utf8') + if result_path == '' : + directory_path = os.path.dirname(file_excel) + result_path = directory_path + "/result/" + try: + os.makedirs(result_path, exist_ok=True) + except Exception as e: + print(result_path) + + file = open(result_path + file_log, 'w+', encoding='utf8') - dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt") + dict_qanon_id = get_dict_qanon_title("app/repair_data/qanon_title_ids.txt") # Print the list of rows dic_error_qanon_title={} dic_error_section_title={} @@ -209,17 +48,52 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ 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 = "" + for row in rows_list: + row_number = row[column_names[0]] # ردیف + # if row_number == 152: + # print(row_number) + + c_name = 'عنوان و تاریخ تصویب قانون' + if not c_name in column_names : + c_name = 'عنوان' + if not c_name in column_names : + print("!!!!!!!!!!!! error column in title ", c_name) + continue + title = row[c_name] + 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]] else: prevRow = row + + ts_date = "" + c_name = 'تاریخ تصویب' + if c_name in column_names : + ts_date = row[c_name] + + ts_ref = "" + c_name = 'مرجع تصویب' + if c_name in column_names : + ts_ref = row[c_name] + + content = "" + c_name = 'متن قانون' + if c_name in column_names : + content = row[c_name] + if content is None or is_nan_or_none_or_empty(content) : + content = '' + + c_name = 'مواد مرتبط' + if not c_name in column_names : + print("!!!!!!!!!!!! error column in ", c_name) + continue + section_title = row[c_name] + + code_state = "" + c_name = 'نوع ارتباط' + if c_name in column_names : + code_state = row[c_name] qanon_id = 0 section_id = 0 @@ -231,8 +105,12 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ title = text_normalizer.normalize_search_qanon(title) - qanon_title, ts_date, ts_ref = get_qanon_date(title) - + qanon_title, ts_date_1, ts_ref_1 = get_qanon_date(title) + if not ts_date and ts_date_1: + ts_date = ts_date_1 + if not ts_ref and ts_ref_1: + ts_ref = ts_ref_1 + qanon_title = text_normalizer.normalize_search_qanon(qanon_title) # جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل @@ -253,7 +131,7 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ # اگر پیدا نشد، از الاستیک جستجو کند if qanon_id == 0 : - qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon") + qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon", ts_ref) # اگر قابل اطمینان نبود، خطا ثبت کند if score < 90 : dic_error_qanon_title[qanon_title]=count @@ -261,14 +139,26 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n') qanon_id = 0 state = 'خطا-قانون' + if qanon_title=='قانون مالياتهاي مستقيم': + print(ts_date) + print(ts_ref) + break + + else: state = 'قانون-جستجو' # اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ... - section_title = text_normalizer.normalize_search_qanon(str(section_title)) - result_section_title = get_section_correct(section_title) result_section_id = [] - if qanon_id != 0 : + result_section_title=[] + if qanon_id != 0 : + + section_title = str(section_title).replace('\n', '،') + if qanon_id == 'qq83655' : + #if 'ماده 188> فصل سوم> باب دویم' in section_title: + print(qanon_id) + section_title = text_normalizer.normalize_search_qanon(str(section_title)) + result_section_title = get_section_correct(section_title) for section_title in result_section_title: if section_title == 'all' : @@ -276,7 +166,9 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ result_section_id.append('all') continue - section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title) + other_title2 = get_section_title2(section_title) + section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title, other_title2) + # - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود if score < 90 : dic_error_section_title[str(qanon_id)+'=='+section_title]=count @@ -288,12 +180,28 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ state = 'صحیح' result_section_id.append(section_id) + + if content and state == 'خطا-جزء' : + section_id, score, section_item = searchSectionIdContent(elastic, "mj_qa_section", qanon_id , section_title, content) + # - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود + 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 = 'خطا-جزء' + elif state == '': + state = 'صحیح' # ذخیره شناسه ها و وضعیت برای اکسل جدید row[column_count+1]=qanon_id - row[column_count+2]= '#'.join(str(item) for item in result_section_id) + row[column_count+2]= '' + if result_section_id : + rrr = '#'.join(str(item) for item in result_section_id) + row[column_count+2]= rrr row[column_count+3]=state - row[column_count+4]=qanon_title +'#'+ ts_date +'#'+ ts_ref + ttt = f'{qanon_title}#{ts_date}#{ts_ref}' + row[column_count+4]= ttt row[column_count+5]='#'.join(result_section_title) rows_list_new.append(row) @@ -301,20 +209,25 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ tstate = 'نامعتبر' c_name = 'وضعیت اعتبار' + if not c_name in column_names : + c_name = 'وضعیت تنقيحي' + if c_name in column_names : - tstate = row[c_name].replace('#', '').replace('=', '') + tstate = str(row[c_name]).replace('#', '').replace('=', '') if tstate.startswith('نامعتبر') : tstate = 'نامعتبر-' + tstate treason = '' c_name = 'مستند عدم اعتبار' + if not c_name in column_names : + c_name = 'مستندات و دلايل' if c_name in column_names : - treason = row[c_name].replace('#','\n').replace('=','\n') + treason = str(row[c_name]).replace('#','\n').replace('=','\n') description = '' c_name = 'توضیحات' if c_name in column_names : - description = row[c_name].replace('*', '') + description = str(row[c_name]).replace('*', '') # ذخیره کد در الاستیک برای شناسه های یافت شده for section_id in result_section_id : @@ -362,7 +275,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)) - elastic.updateBulkList(bulk_data, index_name_o) + if update_elastic : + elastic.updateBulkList(bulk_data, index_name_o) bulk_data = [] @@ -370,7 +284,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) ) - elastic.updateBulkList(bulk_data, index_name_o) + if update_elastic : + elastic.updateBulkList(bulk_data, index_name_o) # columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش'] @@ -381,15 +296,14 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ column_names.append(column_count+5) columns= column_names 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') + 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('################# create excel file : ', file_excel2) except Exception as e: @@ -410,18 +324,9 @@ 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 = ""): - # 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) +def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = "", update_elastic = False, genrate_excel = True): + 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]) @@ -432,7 +337,7 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i file = open(file_log, 'w+', encoding='utf8') - dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt") + dict_qanon_id = get_dict_qanon_title("app/repair_data/qanon_title_ids.txt") # Print the list of rows dic_error_qanon_title={} dic_error_section_title={} @@ -542,7 +447,8 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i 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) + if update_elastic : + elastic.updateBulkList(bulk_data, index_name_o) bulk_data = [] @@ -550,7 +456,8 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i 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) + if update_elastic : + elastic.updateBulkList(bulk_data, index_name_o) # columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش'] @@ -563,8 +470,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') - print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2) - # new_df.to_excel(file_excel2, index=False, engine='openpyxl') + if genrate_excel : + 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: @@ -582,18 +490,19 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i -def run_Codes_directory(elastic, directory, output): - dic_code_id={ - "آب" : 1, - "آمار، برنامه و بودجه" : 2, - "آموزش و پرورش" : 3, - "آیین دادرسی مدنی" : 5, - "سلامت" : 30, - "فرهنگ و هنر" : 33, - "مسکن و شهرسازی" : 42, - "مناطق آزاد و ویژه اقتصادی" : 45, - "نفت و گاز" : 49 - } +def run_Codes_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 : @@ -608,26 +517,27 @@ def run_Codes_directory(elastic, directory, output): print(output) code_id = 0 - if code_name in dic_code_id : - code_id = dic_code_id[code_name] - importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file) - else : - print('00000 error 000000 ', code_name) + # 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) -def run_Etebar_directory(elastic, directory, output): - dic_code_id={ - "آب" : 1, - "آمار، برنامه و بودجه" : 2, - "آموزش و پرورش" : 3, - "آیین دادرسی مدنی" : 5, - "سلامت" : 30, - "فرهنگ و هنر" : 33, - "مسکن و شهرسازی" : 42, - "مناطق آزاد و ویژه اقتصادی" : 45, - "نفت و گاز" : 49, - } +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 : @@ -648,18 +558,14 @@ def run_Etebar_directory(elastic, directory, output): 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) + 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) + else : + print('00000 error 000000 ', code_name) - - load_dotenv(dotenv_path='config.env') @@ -678,35 +584,29 @@ path_base_map = "G:/Project2/gateway2_main/repo/_other/" elastic = ElasticHelper(host, password, "elastic", path_base_map) -#run_Codes_directory(elastic, "./data/tcodes", "./data/tcodes/result") +all_codes = [] +with open("./data/codes49.json", "r", encoding="utf8") as f: + codes_1 = json.load(f) + all_codes = codes_1 -run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result") +run_Codes_directory(elastic, "./data/tcodes", "./data/tcodes/result", all_codes, False, True) + +# 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 -# text="قانون تشکیلات، وظایف و انتخابات شوراهای اسلامی کشور و انتخاب شهرداران مصوب 1 /3 /1375 و اصلاحات بعدی آن" -# text="ائین‌نامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28ر12ر1345" -# text="قانون بودجه سال 1369کل کشور" - -# text="قانون تشکیلات، وظایف و انتخابات شوراهای اسلامی کشور و انتخاب شهرداران مصوب 1/3/1375 و اصلاحات بعدی آن" -text="قانون بودجه سال 1369کل کشور" - -text="پیوست 3>متن >ضمیمه 1>قسمت الف>فصل پنجم>جدول الف-1-1-1 /5" -# searchSectionId(elastic, "mj_qa_section", "qq240970", text ) - -# text = text_normalizer.date_correction(text) -# text = re.sub(r"(\d+?) /(\d+?) /(\d+?)", r"\1/\2/\3", text) -# text = re.sub(r"(\d)/(\d)/(\d{4})", r"0\1/0\2/\3", text) -# print(text.split('/')) -# text1 = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", text) -# print(text) -# print(text1) -# print(text1==text) -# print( searchQanonId(elastic, text) ) +file_path="data/tcodes2/فایل سند پشتیبان کد ارتباطات 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) diff --git a/app/for_ai/codes_llm_update_to_elastic.py b/app/for_ai/codes_llm_update_to_elastic.py new file mode 100644 index 0000000..b1ebe6c --- /dev/null +++ b/app/for_ai/codes_llm_update_to_elastic.py @@ -0,0 +1,621 @@ +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 + + +def get_files(directory): + # Pattern to match filenames like out_1.json, out_25.json, etc. + pattern = re.compile(r"output_(\d+)\.json$") + + max_num = 0 + list_file = [] + + for filename in os.listdir(directory): + match = pattern.match(filename) + if match: + list_file.append(directory+"/"+filename) + return list_file + + +def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", update_to_elastic=False, by_ai_code = False): + try: + # Read JSON file + with open(file_path, 'r', encoding="utf8") as f: + data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"Failed to parse JSON file: {str(e)}") + except FileNotFoundError: + raise FileNotFoundError(f"File not found: {file_path}") + + + list_bulk = [] + batch_size = 200 + processed_count = 0 + total = len(data) + batch_size_number = 1 + + + list_section_id_notfound = [] + list_prccessed_negative_file = [] + for item in data: + + section_id = item["id"] + + reaseon_code_item = item["history_codes"] + + #آخرین مورد برداشته میشود، برای هر دو حالت ذخیره کامل از الاستیک و فقط جدید نیز جواب میده + history_codes_new = reaseon_code_item[-1] + + history_codes = [] + ai_code = {} + ai_codes = [] + + res = None + try : + if elastic : + res = elastic.get_doctument(index_name_o, section_id) + except: + list_section_id_notfound.append(section_id) + continue + + if res : + if "history_codes" in res["_source"] : + history_codes = res["_source"]["history_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_new["sub_key"] == "negative" : + list_prccessed_negative_file.append(section_id) + + source = {} + # تکراری هست بخاطر اجراهای تکراری روی یک داده + 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 not by_ai_code : + continue # دیگه چیزی برای بروز رسانی الاستیک نیست + else : + history_codes.append(history_codes_new) + source["history_codes"] = history_codes + + if by_ai_code and history_codes_new["sub_key"] == 'positive': + + ai_code_new = { + "label": history_codes_new["label"], + "score": history_codes_new["score"] + } + 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) + + source["ai_codes"] = ai_codes_new + + + + if not update_to_elastic : + continue + + list_bulk.append({ + "_id" : section_id, + "_source": source + } + ) + if len(list_bulk) >= batch_size : + elastic.updateBulkList(list_bulk, index_name_o) + list_bulk = [] + print("updated batch : ", batch_size_number, f"/{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) + batch_size_number += 1 + + return list_prccessed_negative_file + +def parse_and_update_multi_code(file_path, elastic, all_codes, index_name_o, update_to_elastic=False, by_ai_code = False): + try: + # Read JSON file + with open(file_path, 'r', encoding="utf8") as f: + data = json.load(f) + except json.JSONDecodeError as e: + raise ValueError(f"Failed to parse JSON file: {str(e)}") + except FileNotFoundError: + raise FileNotFoundError(f"File not found: {file_path}") + + + list_bulk = [] + batch_size = 200 + processed_count = 0 + total = len(data) + batch_size_number = 1 + + + list_section_id_notfound = [] + list_prccessed_negative_file = [] + for item in data: + + section_id = item["id"] + + reaseon_code_item = item["history_codes"][0] + + + if reaseon_code_item["sub_key"] == "negative" : + print('==!!!!!!!!!!=== warning .... negative is ', section_id, ' ' , file_path) + list_prccessed_negative_file.append(section_id) + continue + + ##---------------------------------------- + ### بررسی معتربر بودن کد مدل + label = reaseon_code_item["label_ai"] + label = label.strip() + + try: + number = int(label) # or int(value) for integers + if all_codes and number > 0 and number <= 49 : + label = all_codes[number-1] + except ValueError: + label = label.strip('0123456789. ') + label = label.lstrip('0123456789. ') + + if all_codes and not label in all_codes : + list_prccessed_negative_file.append(section_id) + continue + ##---------------------------------------- + + history_codes = [] + ai_code = {} + ai_codes = [] + + res = None + try : + if elastic : + res = elastic.get_doctument(index_name_o, section_id) + except: + list_section_id_notfound.append(section_id) + continue + + if res : + if "history_codes" in res["_source"] : + history_codes = res["_source"]["history_codes"] + # print(history_codes) + + source = {} + + history_last = history_codes[-1] + # تکراری هست بخاطر اجراهای تکراری روی یک داده + if history_codes and reaseon_code_item["version_key"] == history_last["version_key"] : + + if not "sub_key" in history_last : + history_last["sub_key"] = "positive" # موقتا بخاطر خطایی در وسط کار + + if reaseon_code_item["sub_key"] == history_last["sub_key"] : + continue # دیگه چیزی برای بروز رسانی الاستیک نیست + + history_code_new = { + "score" : reaseon_code_item["score"], + "label" : label, + "sub_key" : reaseon_code_item["sub_key"], + "version_key" : reaseon_code_item["version_key"], + "description" : reaseon_code_item["description"] + } + history_codes.append(history_code_new) + + source["history_codes"] = history_codes + + if by_ai_code and reaseon_code_item["sub_key"] == 'positive': + + ai_code = { + "score" : reaseon_code_item["score"], + "label" : label, + } + + for code in reaseon_code_item["secondary_labels"] : + 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 + #-------------------------------- + + + if not label1 == ai_code["label"] : + ai_codes.append({ + "score" : code["confidence"], + "label" : code["label"], + }) + + + source["ai_code"] = ai_code + source["ai_codes"] = ai_codes + + + if not update_to_elastic : + continue + + list_bulk.append({ + "_id" : section_id, + "_source": source + } + ) + if len(list_bulk) >= batch_size : + elastic.updateBulkList(list_bulk, index_name_o) + list_bulk = [] + print("updated batch : ", batch_size_number, f"/{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) + batch_size_number += 1 + + return list_prccessed_negative_file + + + +def get_proccesed_count(): + + #////بررسی آمار اولیه + all_ids_list = [] + try: + with open("data/codes_reaseon_oss/all_ids_list.json", "r", encoding="utf8") as f: + all_ids_list = json.load(f) + except : + all_ids_list = [] + print("len candids ", len(all_ids_list), len(set(all_ids_list))) + + + list_proccess = [] + with open("data/codes_reaseon_oss/process_id_final_1.json", "r", encoding="utf8") as f: + list_proccess1 = json.load(f) + list_proccess.extend(list_proccess1) + with open("data/codes_reaseon_oss/process_id_final_2.json", "r", encoding="utf8") as f: + list_proccess1 = json.load(f) + list_proccess.extend(list_proccess1) + with open("data/codes_reaseon_oss/process_id_final_3.json", "r", encoding="utf8") as f: + list_proccess1 = json.load(f) + list_proccess.extend(list_proccess1) + + print("len proccessed ", len(list_proccess), len(set(list_proccess))) + return list_proccess + + +def extract_list_week_sections(elastic, index_name="mj_qa_section"): + body = { + "query": { + "bool": { + "must": [ + { + "range": { + "content_len": { + "lte": 50 + } + } + } + ] + } + } + } + + list_weeks = [] + try: + list = elastic.es_iterate_all_documents(index_name, body) + except Exception as e: + print("extract_list_week_sections --> ", str(e)) + return [] + + for mentry in list: + entry = mentry["source"] + id = entry.get("id", "") + list_weeks.append(id) + + return list_weeks + +def genrate_list_negative(paths=[],list_minues=[]): + + elastic = None + 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) + except : + list_prccessed_negative = [] + + for path in paths : + print('*', 100) + print('******** ', path) + for file in get_files(path): + print(file) + list_prccessed_negative_file = parse_and_update_code(file, elastic, "mj_qa_section", False) + list_prccessed_negative.extend(list_prccessed_negative_file) + + if list_minues : + print("start list minues ..... wait several minutes .... ") + list_prccessed_negative = [x for x in list_prccessed_negative if x not in 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) + + +def import_codes_to_elastic(elastic, all_codes, by_ai_code, paths=[], list_minues=[]): + + list_prccessed_negative = [] + try: + with open("data/codes_reaseon_oss/processed_id_negative.json", "r", encoding="utf8") as f: + list_prccessed_negative = json.load(f) + except : + list_prccessed_negative = [] + + for path in paths : + print('*', 100) + print('******** ', path) + for file in get_files(path): + print(file) + if 'data_h100_full' in path : # data_h100_full_1 , ..., data_h100_full_4 + list_prccessed_negative_file = parse_and_update_multi_code(file, elastic, all_codes, "mj_qa_section", True, by_ai_code) + else: + list_prccessed_negative_file = parse_and_update_code(file, elastic, "mj_qa_section", True, by_ai_code) + list_prccessed_negative.extend(list_prccessed_negative_file) + + if list_minues : + print("start list minues ..... wait several minutes .... ") + list_prccessed_negative = [x for x in list_prccessed_negative if x not in 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) + + +def parse_notvalid_multi_codes(paths, all_codes=[], file_not_valid="processed_id_notvalid"): + json_no_valids = {} + list_prccessed_negative = [] + total = 0 + 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) + for item in data: + section_id = item["id"] + reaseon_code_item = item["history_codes"][0] + label = reaseon_code_item["label_ai"] + label = label.strip() + + try: + number = int(label) # or int(value) for integers + if number > 0 and number <= 49 : + label = all_codes[number-1] + except ValueError: + label = label.strip('0123456789. ') + label = label.lstrip('0123456789. ') + + if not label in all_codes : + if not label in json_no_valids : + json_no_valids[label] = [] + json_no_valids[label].append(item) + list_prccessed_negative.append(section_id) + total +=1 + + 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) + + 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) + + +def extract_sectionid_in_files(paths, sections=[], file_result="section_id_files"): + json_no_valids = {} + list_prccessed_negative = [] + total = 0 + result=[] + 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) + for item in data: + section_id = item["id"] + if section_id in sections : + result.append({ + "id": section_id, + "file": file, + "history_codes": item["history_codes"] + }) + + + 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) + + + +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') + +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([]) + + + +#------------------------------------------------ +#------ درج در الاستیک - بخش ا +# 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_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") + + + +#------------------------------------- +#--- مرحله پاکسازی- بخش 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" +# } +# } + + +# POST mj_qa_section/_update_by_query +# { +# "query": { +# "bool": { +# "must": [ +# { +# "exists": { +# "field": "code-ai" +# } +# } +# ] +# } +# } +# ,"script": { +# "source": """ +# ctx._source.remove("code-ai"); +# """, +# "lang": "painless" +# } +# } +#------------------------------------- diff --git a/app/for_ai/extract_json_to_ai.py b/app/for_ai/extract_json_to_ai.py new file mode 100644 index 0000000..0277738 --- /dev/null +++ b/app/for_ai/extract_json_to_ai.py @@ -0,0 +1,117 @@ +import io +import os +import json +from dotenv import load_dotenv + +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))) + + +from app.common.text_normalizer import TextNormalizer +from app.common.elastic_helper import ElasticHelper + + +# def get_custom_fileds(elastci, index_name, fields=[]) + + + + + +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) + +# elastic.exportToJsonForAI("output","mj_qa_section", "mj_qa_section.json", {}, ["content", "qanon_title", "ts_date", "other_info.full_path"]) + +##### qanon_id !! +# elastic.exportToJsonForAI("output","mj_qa_section", "mj_qa_section_childs.json", {}, ["content", "qanon_title", "ts_date", "other_info.full_path", "parent_id", "child_order", "nlp_childs"]) + + +body = { + "query": { + "bool": { + "must": [ + { + "bool" :{ + "must_not":[ + { + "terms": { + "title_type": [ + "موافقتنامه" + ] + } + } + ] + } + }, + { + "term":{ + "ai_code.label":"فناوری اطلاعات و ارتباطات" + } + } + ] + } + } +} + +# body = { +# "query":{ +# "term":{ +# "ai_code.label":"فناوری اطلاعات و ارتباطات" +# } +# } +# } +elastic.exportToJsonForAI("output","mj_qa_section", "section_codes_ertabatat.json", body, ["ai_codes", "ai_code", "content", "qanon_title", "qanon_id", "other_info.full_path"], "normal") + +body = { + "sort": [ + {"qanon_id": {"order": "asc"} }, + { "child_order":{ "order": "asc" } } + ] +} +# elastic.exportToJsonForAI("output","mj_qa_section", "mj_qa_section_qanon.json", body, ["other_info.full_path"], 'normal', 'qanon_id') + + +###--- مناسب برای پرش در تسک کدگذاری +body = { + "query": { + "bool": { + "must": [ + { + "bool": { + "should": [ + { + "terms": { + "title_type": [ + "موافقتنامه" + ] + } + }, + { + "match": { + "other_info.full_path": "عنوان" + } + }, + { + "match": { + "other_info.full_path": "امضاء" + } + }, + { + "match": { + "other_info.full_path": "موخره" + } + } + ] + } + } + ] + } + } +} +# elastic.exportToJsonForAI("output","mj_qa_section", "ignore_sections_code.json", body, [], 'id', '') diff --git a/app/for_ai/repiar_ids.py b/app/for_ai/repiar_ids.py new file mode 100644 index 0000000..febf5d4 --- /dev/null +++ b/app/for_ai/repiar_ids.py @@ -0,0 +1,63 @@ +import os +from dotenv import load_dotenv +from elasticsearch import Elasticsearch, helpers +import json +import re + +load_dotenv() + +def run_folder(dir): + pattern = re.compile(r"output_(\d+)\.json$") + process_ids = [] + filename = '' + processed_id = [] + # processed_id_set = set(processed_id) + + try: + for filename in os.listdir(dir): + + # match = pattern.match(filename) + # if match: + # # Read JSON file + # data = {} + print(filename) + with open(dir + filename, 'r', encoding="utf-8") as f: + data = json.load(f) + for item in data : + processed_id.append(item["id"]) + + except json.JSONDecodeError as e: + print(f"File not found: {filename}") + raise ValueError(f"Failed to parse JSON file: {str(e)}") + except FileNotFoundError: + raise FileNotFoundError(f"File not found: {filename}") + + + return processed_id + + + +processed_id_1 = run_folder("data/codes_reaseon_oss/data_g3090/") +print("processed_id 1 ", len(processed_id_1)) +processed_id_2 = run_folder("data/codes_reaseon_oss/data_h100/") +print("processed_id 2 ", len(processed_id_2)) + + +processed_id_1.extend(processed_id_2) +print("total ", len(processed_id_1)) + +processed_id_set1 = set(processed_id_1) +print("total set ", len(processed_id_set1)) + +with open("data/codes_reaseon_oss/process_tt_id.json", "w") as f: + json.dump(list(processed_id_set1), f) + + + +# with open("data/codes_reaseon_oss/section_codes.json", 'r', encoding="utf-8") as f: +# data = json.load(f) +# print("section_codes ", len(data.items())) + +# with open("data/codes_reaseon_oss/mj_qa_section.json", 'r', encoding="utf-8") as f: +# data = json.load(f) +# print("mj_qa_section ", len(data)) diff --git a/app/repair_data/r8_remove_fileds.py b/app/repair_data/r8_remove_fileds.py new file mode 100644 index 0000000..6e02156 --- /dev/null +++ b/app/repair_data/r8_remove_fileds.py @@ -0,0 +1,170 @@ +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 bd14f02..a5c80fe 100644 --- a/app/temp_codes.py +++ b/app/temp_codes.py @@ -1,5 +1,10 @@ import os from dotenv import load_dotenv + + +import sys +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + from app.common.text_normalizer import TextNormalizer # from general import * @@ -43,7 +48,7 @@ path_base_map = "G:/Project2/gateway2_main/repo/_other/" elastic = ElasticHelper(host, password, "elastic", path_base_map) # elastic.backupIndexToZipfile("G:/Project2/111", "mj_mashruh") -#elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section") +elastic.backupIndexToZipfile("G:/Project2/111", "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') @@ -59,7 +64,7 @@ elastic = ElasticHelper(host, password, "elastic", path_base_map) # elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section-m1") # elastic.createIndex( 'mj_qa_section-m1', 'majles', 'mj_qa_section') -# elastic.restorFileToElastic2('G:/Project2/111/server112/mj_qa_section-m1.zip', 'mj_qa_section-m1', 'majles', False, 'mj_qa_section') +# elastic.restorFileToElastic2('G:/Project2/111/mj_qa_section-m1.zip', 'mj_qa_section-m1', 'majles', False, 'mj_qa_section') # elastic.backupIndexToZipfile("G:/Project2/111", "gn_calendar") # elastic.createIndex( 'gn_calendar', 'general', 'gn_calendar') From aa47259860922d29c80c5ef8242bd7273563e78e Mon Sep 17 00:00:00 2001 From: hsafaei Date: Thu, 6 Nov 2025 11:41:24 +0330 Subject: [PATCH 4/4] 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