Files
init_dataParser/app/monir_gn_tree.py
T
2026-02-02 19:25:35 +03:30

542 lines
14 KiB
Python

import mariadb
from dotenv import load_dotenv
import os
import datetime
import json
import uuid
import pandas as pd
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 *
from app.common.text_normalizer import TextNormalizer
from app.monir_options import (
get_public_options,
get_monir_options
)
load_dotenv(dotenv_path="config.env")
# host = os.getenv("HOST_160")
# host = os.getenv("HOST_160_LOCAL")
# password = os.getenv("HOST_160_PASS")
host = os.getenv("HOST_60")
password = os.getenv("HOST_60_PASS")
# host = os.getenv("HOST_133")
# password = os.getenv("HOST_133_PASS")
# print(host)
# print(password)
path_base_map = (
"G:\Project2\gateaway_py\elastic_backend/elastic_backend/app/schemas/mappings/"
)
# path_base_map = (
# "G:\Project2\tavasi_60\src\repo\_other/"
# )
elastic = ElasticHelper(host, password, "elastic", path_base_map)
text_normalize = TextNormalizer()
def import_simple_list_to_elastic(
elastic,
items,
prefix_id,
tree_label,
tree_key,
group_key="",
index_name_o="gn_tree",
):
bulk_data = []
total_count = 0
t1 = datetime.datetime.now()
print(t1)
i = 0
for item in items:
# print(i)
i = i + 1
row = cursor.fetchone()
if not item:
break
id = prefix_id + str(i).zfill(5)
# eid = uuid.uuid4().hex[:8]
eid = id
title = item.strip()
title = text_normalize.normalize_qanon(title)
parent_id = "0"
child_order = i
data = {
"id": eid,
"version_key": "base_1",
"tree_key": tree_key,
"tree_label": tree_label,
"main_type": "list",
"group_key": group_key,
"title": title,
"parent_id": parent_id,
"child_order": child_order,
}
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print(
"=" * 10,
"to_elastic , total=" + str(total_count),
str(i) + ", id=" + eid,
)
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
bulk_data.append({"_id": eid, "_source": data})
if len(bulk_data) > 0:
total_count += len(bulk_data)
print("=" * 10, " to_elastic , total=" + str(total_count))
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
print("end success import_to_elastic")
t2 = datetime.datetime.now()
print(t2 - t1)
def import_project_to_elastic(
cursor, elastic, project_id, project_title, index_name_o="gn_tree"
):
query = f"""
SELECT id, title, parent, child_order, meta, tags from tlist.tl_subjects
where project_id={project_id}
ORDER BY parent, child_order
"""
# print('-'*10)
# print(query)
# print('-'*10)
cursor.execute(query)
parent_nodes = {}
bulk_data = []
total_count = 0
t1 = datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i = i + 1
row = cursor.fetchone()
if not row:
break
id = row[0]
# eid = uuid.uuid4().hex[:8]
eid = "gnt" + str(id).zfill(5)
title = row[1]
if title is None: # داده های خراب
continue
title = row[1].strip()
title = text_normalize.normalize_qanon(title)
parent = row[2]
parent_id = 0
if parent != 0:
parent_id = "gnt" + str(parent).zfill(5)
child_order = row[3]
meta = row[4]
tags = row[5]
meta_info = {}
if meta:
meta_info["id1"] = str(meta)
tags_list = []
if tags:
for tt in tags.strip().split(","):
if tt and not tt in tags_list:
tags_list.append(tt)
main_type_key = "tree" + str(project_id)
data = {
"id": eid,
"version_key": "base_1",
"tree_key": main_type_key,
"tree_label": project_title,
"main_type": "tree",
"group_key" : "موضوعی",
"title": title,
"parent_id": parent_id,
"child_order": child_order,
"tags": tags_list,
"meta_info": meta_info,
}
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print(
"=" * 10,
"to_elastic , total=" + str(total_count),
str(i) + ", id=" + eid,
)
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
bulk_data.append({"_id": eid, "_source": data})
if len(bulk_data) > 0:
total_count += len(bulk_data)
print("=" * 10, " to_elastic , total=" + str(total_count))
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
print("end success import_to_elastic")
t2 = datetime.datetime.now()
print(t2 - t1)
def import_tlist_projects(index_name_o="gn_tree"):
config_env = load_dotenv(dotenv_path="./config.env")
MYSQL_username = os.getenv("MYSQL_username")
MYSQL_root_password = os.getenv("MYSQL_root_password")
MYSQL_port = os.getenv("MYSQL_port")
# MYSQL_host = os.getenv("MYSQL_import_host")
MYSQL_host = os.getenv("MYSQL_import_host_60")
# MYSQL_host = os.getenv("MYSQL_import_host_160")
cnx = mariadb.connect(user="root", password=MYSQL_root_password, host=MYSQL_host)
cursor = cnx.cursor()
query = "select id, title from tlist.tl_projects"
cursor.execute(query)
list_projects = []
while 1:
row = cursor.fetchone()
if not row:
break
pid = row[0] # "id"
title = row[1] # "title"
title = text_normalize.normalize_qanon(title)
# print(title)
# فهرست های تستی همفهمی
if pid == 4 or pid == 5 or pid == 6:
continue
# فهرستهای موضوعی استاد حسینی و استاد میرباقری که قرار شد از اکسل پورتال ارسال شود
if pid == 2 or pid == 3:
continue
# استانها و شهرها که در ایندکس دیگر ذخیره می شود
if pid == 1000:
continue
list_projects.append({"id": pid, "title": title})
for item in list_projects:
print("*" * 100)
print(item)
import_project_to_elastic(cursor, elastic, item["id"], item["title"], index_name_o)
cursor.close()
def import_option_to_elastic(
elastic,
main_key,
main_label,
group_key="عناوین انتخابی برنامه",
eid="",
index_name_o="gn_option",
):
res = get_public_options(main_key)
if not res :
res = get_monir_options(main_key)
titles = [item["value"] for item in res]
if not eid:
eid = uuid.uuid4().hex[:8]
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"main_type": "list_simple",
"titles": titles,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
def import_option_base_list(elastic, index_name_o="gn_option"):
op_list = [
{
"main_key": "calendar_main_type",
"main_label": "تقویم- نوع اصلی",
},
{
"main_key": "calendar_media",
"main_label": "تقویم - رسانه دارد؟",
},
{
"main_key": "calendar_domain",
"main_label": "تقویم - حوزه درخواست",
},
{
"main_key": "calendar_audience",
"main_label": "تقویم - نوع مخاطبان",
},
{
"main_key": "calendar_format",
"main_label": "تقویم - قالب جلسه",
},
{
"main_key": "calendar_exec",
"main_label": "تقویم - وضعیت برگزاری",
},
{
"main_key": "calendar_accept",
"main_label": "تقویم - وضعیت پذیرش",
},
{
"main_key": "sanad_steps",
"main_label": "مراحل نگارش سند",
},
{
"main_key": "search_amplify",
"main_label": "انواع جستجوی تقویتی",
},
{
"main_key": "sanad_meta-permit",
"main_label": "سطوح دسترسی داده",
},
{
"main_key": "sanad_format",
"main_label": "قالب های جلسه",
},
{
"main_key": "fish_take_type",
"main_label": "فیش - نوع برداشت",
},
{
"main_key": "fish_text_verb",
"main_label": "فیش - نوع فعل",
},
{
"main_key": "note_take_type",
"main_label": "یادداشت - نوع برداشت",
},
]
number = 0
for op in op_list:
number = number + 1
print(op["main_key"])
eid = "mn_op_" + str(number)
group_key = "عناوین انتخابی برنامه"
if "group_key" in op:
group_key = op["group_key"]
import_option_to_elastic(
elastic, op["main_key"], op["main_label"], group_key, eid, index_name_o
)
def import_option_ostan_shahr(elastic, index_name_o="gn_option"):
file_path = './data/ostan.txt'
lines = []
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
print(len(lines))
ostan_dic={}
ostan_list = []
number = 0
for line in lines:
items = line.strip('\n').split('\t')
# print(items)
number +=1
if len(items) != 2 :
continue
ostan=items[0]
ostan = text_normalize.normalize_qanon(ostan)
shahr=items[1]
shahr = text_normalize.normalize_qanon(shahr)
if ostan not in ostan_dic:
ostan_list.append(ostan)
ostan_dic[ostan] = []
ostan_dic[ostan].append(shahr)
eid = 'iros_0'
main_key = "ir_ostan"
main_label = "استانهای ایران"
group_key = "استان و شهرهای ایران"
main_type = "list_simple"
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"titles": ostan_list,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
number = 0
for key, value in ostan_dic.items():
number = number + 1
ostan = key
shahrs = value
eid = 'iros_' + str(number)
main_key = str(ostan)
main_label = "شهرهای استان " + ostan
group_key = "استان و شهرهای ایران"
main_type = "list_simple"
data = {
"id": eid,
"version_key": "b1",
"main_key": main_key,
"main_label": main_label,
"group_key": group_key,
"titles": shahrs,
}
elastic.es.index(index=index_name_o, id=eid, document=data)
##### -------------------------------------------------------------
def convert_excel_data_to_json(item):
_id = "gnp" + str(item["id"])
tree_label = item["person_title"]
person_id = item["person_id"]
title = item["title"]
group_key = ""
if person_id == 1103 :
group_key = "استاد حسینی"
tree_label = "فهرست موضوعی جلسات استاد حسینی"
elif person_id == 1128 :
group_key = "استاد میرباقری"
tree_label = "فهرست موضوعی جلسات استاد میرباقری"
papa_id = item["papa_id"]
if papa_id == 0:
parent_id = str(0)
else:
parent_id = "gnp" + str(papa_id)
child_order = item["order"]
return {
"id": _id, # "gnt01741"
"version_key": "portal_2",
"tree_key": "tree" + str(person_id),
"tree_label": tree_label, # "فهرست موضوعات مسائل و پاسخها",
"group_key": group_key,
"main_type": "tree",
"title": title, # "پیامدهای روبنایی",
"parent_id": parent_id,
"child_order": child_order,
"tags": [],
"meta_info": {},
}
def import_excel_tree_monir(elastic, file_path, index_name_o = "gn_tree"):
data_excel = extract_excel_fields(file_path, sheet_name="Sheet1")
print(f'data_excel {len(data_excel)}')
try:
f_data = []
for i in data_excel:
f_data.append(convert_excel_data_to_json(i))
except Exception as e:
print(
f"*************",
)
traceback.print_exc()
bulk_data=[]
total_count = 0
data_list = f_data
i = 0
for data in data_list :
eid = data["id"]
i = i + 1
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print('=' * 10, 'to_elastic , total='+str(total_count) , str(i)+ ', id=' + eid )
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
bulk_data.append(
{
'_id' : eid,
'_source' : data
}
)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 10, ' to_elastic , total='+str(total_count) )
elastic.importBulkList(bulk_data, index_name_o)
bulk_data = []
print("end success import_to_elastic")
##### -------------------------------------------------------------
if __name__ == "__main__":
###### -------------- gn_tree -----------------------------
# import_tlist_projects("gn_tree")
# file_path = r"app/../data/monir/041106_لیست تمام موضوعات.xlsx"
# import_excel_tree_monir(elastic, file_path, "gn_tree")
###### -------------- gn_option -----------------------------
# import_option_base_list(elastic, "gn_option")
# import_option_ostan_shahr(elastic, "gn_option")
###### -------------- -----------------------------
# elastic.backupIndexToZipfile("G:/Project2/111", "mn_sanad_temp", "mn_sanad")
# elastic.backupIndexToZipfile("G:/Project2/111", "mn_steps_temp", "mn_steps")
# elastic.backupIndexToZipfile("G:/Project2/111", "gn_calendar", "gn_calendar")