import os import re import uuid import traceback import json import time 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 * from app.common.data_helper import DataHelper def recersive_sections( section, list_bulk, parent_id, parent_path, tcode_label, child_order, version_key = "D49_oss120", ): """ Recursive helper to process one section (and its subsections). """ title = section.get("title", "").strip() section_list = section.get("section_list", []) if not section_list : section_list = section.get("sections", []) description = section.get("definition", "").strip() tags = section.get("keywords", []) ai_section_ids = [] for item in section_list : if isinstance(item, str) : ai_section_ids.append(item) if not title: return # Generate node ID node_id = uuid.uuid4().hex[:8] full_path = parent_path + title + "/" # Append current section list_bulk.append({ "_id": node_id, "_source":{ "id": node_id, "title": title, "version_key": version_key, "full_path": full_path, "description": description, "tags": tags, "parent_id": parent_id, "child_order": child_order, "ai_section_ids": ai_section_ids, "tcode": tcode_label, "time_create": int(round(time.time() * 1000)) } }) # Process subsections (children) subsections = section.get("subsections", []) if not subsections : subsections = section.get("subnodes", []) if not subsections : subsections = section.get("sub_title", []) if subsections : for idx, subsec in enumerate(subsections, start=1): recersive_sections( section=subsec, list_bulk=list_bulk, parent_id=node_id, # ✅ important: parent is current node parent_path=full_path, # ✅ path extended child_order=idx, # ✅ order among child_order tcode_label=tcode_label, version_key=version_key ) def import_paln_json_to_elastic(all_codes, elastic, file_path, index_name, version_key= "D49_oss120"): 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}") print("-"*10, " ... import_paln_json_to_elastic ....", file_path) total = len(list(data)) list_bulk = [] batch_size = 20 processed_count = 0 total_update = 0 batch_size_number = 1 file_name = os.path.basename(file_path) _name = os.path.splitext(file_name)[0] code_name = _name tcode_label = data.get("law_title") item_found = [item for item in all_codes if item.get("title") == tcode_label] if not item_found : item_found = [item for item in all_codes if item.get("title") == code_name] if item_found : tcode_label = code_name else : print("################### error tcode_label , code_name ....", tcode_label, code_name, file_path) return # Step 1: Add root node (the law itself) root_id = uuid.uuid4().hex[:8] root_path = tcode_label + "/" # list_bulk.append({ # "_id": root_id, # "_source": { # "id": root_id, # "title": tcode_label, # "version_key": version_key, # "full_path": root_path, # "parent_id": 0, # or 0 if you prefer integer root parent # "child_order": 0, # "tcode": tcode_label, # "time_create": int(round(time.time() * 1000)) # } # }) # Step 2: Recursively process top-level sections for idx, section in enumerate(data.get("sections", []), start=1): # print("..start..", idx, section["title"]) recersive_sections( section=section, list_bulk=list_bulk, parent_id=0, parent_path=root_path, child_order=idx, tcode_label=tcode_label, version_key= version_key ) if len(list_bulk) >= batch_size : elastic.importBulkList(list_bulk, index_name) total_update += len(list_bulk) list_bulk = [] # print("updated batch : ", batch_size_number, f" {total_update}/{total} --->", file_path) batch_size_number += 1 if list_bulk: elastic.importBulkList(list_bulk, index_name) total_update += len(list_bulk) # print(" .... finish updated batch : ", batch_size_number, f" {total_update}/{total} --->", file_path) batch_size_number += 1 ########################## save manual for test # file_path = r'D:\\init_mahdi\project\dataParsers\data\plan_test\test1.json' # with open(file_path, 'w', encoding='utf-8') as f: # json.dump(list_bulk, f, ensure_ascii=False, indent=4) # print(':D') def list_json_files(directory): import os json_files = [] # مرور در دایرکتوری for root, _, files in os.walk(directory): for file in files: if file.endswith('.json'): # افزودن مسیر کامل فایل به لیست json_files.append(os.path.join(root, file)) return json_files def import_v1(elastic, all_codes, version_key= "D49_oss120"): index_name='mj_plan' # file_path=r'data/plans/gpt120b_49_1/data_1/آمار، برنامه و بودجه.json' file_path=r'data/plans/gpt120b_49_1/data_1/' for file in list_json_files(file_path): import_paln_json_to_elastic( all_codes=all_codes, elastic=elastic, file_path=file, index_name=index_name, version_key= version_key ) file_path=r'data/plans/gpt120b_49_1/data_2/' for file in list_json_files(file_path): import_paln_json_to_elastic( all_codes=all_codes, elastic=elastic, file_path=file, index_name=index_name, version_key= version_key ) # all_codes = [] # with open("./data/codes49.json", "r", encoding="utf8") as f: # codes_1 = json.load(f) # all_codes = codes_1 def import_v2_full_tree(elastic, all_codes, file_path, index_name="mj_plan", list_codes_jump = [], version_key= "D49_oss120_gemma"): data_all = DataHelper.load_orjson(file_path) list_bulk = [] total_update = 0 batch_size_number = 0 for key in data_all : node = data_all[key] code_name = key.replace("قانون ", "").strip() item_found = [item for item in all_codes if item.get("title") == code_name] if not item_found : print("* " * 10, " error in code_name ", key, code_name) continue #-- قبلا درخت همراه شناسه ماده های مرتبط افزوده شده است if code_name in list_codes_jump : continue # print("-"* 10, key) root_path = code_name + "/" idx = 0 for item in node : idx += 1 recersive_sections( section=item, list_bulk=list_bulk, parent_id=0, parent_path=root_path, child_order= idx, tcode_label=code_name, version_key= version_key, ) print("-" * 10, code_name, len(list_bulk)) if len(list_bulk) >= 0 : elastic.importBulkList(list_bulk, index_name) total_update += len(list_bulk) list_bulk = [] print("updated batch : ", batch_size_number, f" {total_update} --->", code_name) batch_size_number += 1 def import_v2_section_list(elastic, all_codes, folder_path, index_name="mj_plan",version_key= "D49_oss120_gemma_matched"): list_codes_imported = [] files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))] for file in files : file_name = os.path.basename(file) _name = os.path.splitext(file_name)[0] _name = _name.replace("_finall_tree", "") code_name = _name print('=========================== start code_name ===> ', code_name[::-1]) w1 = text_normalizer.split_words(code_name)[0] file_path = os.path.join(folder_path, file) data_tree = {} root_node = {} try: data_tree = DataHelper.load_orjson(file_path) if data_tree["title"] : code_name = data_tree["title"] code_name = code_name.replace("قانون جامع", "").strip() if "subsections" in data_tree : root_node = data_tree["subsections"] if "sub_title" in data_tree : root_node = data_tree["sub_title"] if "subnodes" in data_tree : root_node = data_tree["subnodes"] except Exception as e: print(output) continue item_found = [item for item in all_codes if item.get("title") == code_name] if not item_found : print("* " * 10, " error in code_name ", code_name) continue list_bulk = [] total_update = 0 batch_size_number = 0 root_path = code_name + "/" idx = 0 for item in root_node : idx += 1 recersive_sections( section=item, list_bulk=list_bulk, parent_id=0, parent_path=root_path, child_order= idx, tcode_label=code_name, version_key= version_key, ) print("-" * 10, code_name, len(list_bulk)) if len(list_bulk) >= 0 : elastic.importBulkList(list_bulk, index_name) total_update += len(list_bulk) list_bulk = [] print("updated batch : ", batch_size_number, f" {total_update} --->", code_name) batch_size_number += 1 list_codes_imported.append(code_name) return list_codes_imported load_dotenv(dotenv_path='config.env') # 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') print('.... codes_import_from_excel ......', host) path_base_map = "G:/Project2/gateway_php/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 ## --------------------------------------------------------- # #--- برای گلان خبره استفاده شد # D49_TgV1 # #--- D49_oss120 پلان ai - نسخه 1 # import_v1(elastic, all_codes, "D49_oss120") # list_codes_imported=[] # file_path = r"G:\Project2\102_gpu\match_plan\v2_0\plan_dict_def_keyword.json" # import_v2_full_tree(elastic, all_codes, file_path, "mj_plan", list_codes_imported, "D49_oss120_gemma") # folder_path = r"G:\Project2\102_gpu\match_plan\v3.0" # list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_oss120_gemma_matched") # folder_path = r"G:\Project2\102_gpu\match_plan\v3.01" # list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_oss120_gemma_matched_2") # folder_path = r"G:\Project2\102_gpu\match_plan\v3.02" # list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_oss120_gemma_matched_3") # folder_path = r"G:\Project2\102_gpu\match_plan\v4" # list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_oss120_matched_4") # folder_path = r"G:\Project2\102_gpu\match_plan\v4.1" # list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_oss120_matched_4-1") # folder_path = r"G:\Project2\102_gpu\match_plan\v4.2" # list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_oss120_matched_4-2") # folder_path = r"G:\Project2\102_gpu\match_plan\v4.3" # list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_oss120_matched_4-3") folder_path = r"G:\Project2\102_gpu\match_plan\v5" list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_gemma4_5") folder_path = r"G:\Project2\102_gpu\match_plan\v5.1_gemma" list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_gemma4_5_1") folder_path = r"G:\Project2\102_gpu\match_plan\v5.1_oss" list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_oss_5_1") folder_path = r"G:\Project2\102_gpu\match_plan\v5.1_yourmind" list_codes_imported = import_v2_section_list(elastic, all_codes, folder_path, "mj_plan", "D49_yourmind_5_1") ## --------------------------------------------------------- ## --------------------------------------------------------- # .\.env\Scripts\activate # python -m app.majles.majles_plans_import