Files
init_dataParser/app/for_ai/plans_import.py
T
2025-11-08 09:43:05 +03:30

163 lines
4.8 KiB
Python

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 *
def recersive_sections(
section,
list_bulk,
parent_id,
parent_path,
tcode_label,
child_order,
):
"""
Recursive helper to process one section (and its subsections).
"""
title = section.get("title", "").strip()
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,
"title": title,
"version_key": "D49_oss120",
"full_path": full_path,
"parent_id": parent_id,
"child_order": child_order,
"tcode": tcode_label,
"time_create": time.time()
})
# Process subsections (children)
subsections = section.get("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
)
def import_paln_json_to_elastic(elastic, file_path, index_name):
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}")
total = len(data)
list_bulk = []
batch_size = 200
processed_count = 0
total_update = 0
tcode_label = data.get("law_title")
if not tcode_label :
print(" error tcode_label", file_path)
return
# Step 1: Add root node (the law itself)
root_id = uuid.uuid4().hex[:8]
root_path = data.get("law_title") + "/"
list_bulk.append({
"id": root_id,
"title": data.get("law_title"),
"version_key": "D49_oss120",
"full_path": root_path,
"parent_id": 0, # or 0 if you prefer integer root parent
"child_order": 0,
"tcode": tcode_label,
"time_create": time.time()
})
# Step 2: Recursively process top-level sections
for idx, section in enumerate(data.get("sections", []), start=1):
recersive_sections(
section=section,
list_bulk=list_bulk,
parent_id=root_id,
parent_path=root_path,
child_order=idx,
tcode_label=tcode_label
)
if len(list_bulk) >= batch_size :
elastic.updateBulkList(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.updateBulkList(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')
# -------------------------------------------------------------------- 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_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/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
file_path=r'D:\init_mahdi\project\dataParsers\data\plan_آمار_برنامه_و_بودجه.json'
index_name='mj'
import_paln_json_to_elastic(
elastic=elastic,
file_path=file_path,
index_name=index_name
)
# all_codes = []
# with open("./data/codes49.json", "r", encoding="utf8") as f:
# codes_1 = json.load(f)
# all_codes = codes_1