From cec03b7d3b0bcc89865b469fc9c3a8f9284f690e Mon Sep 17 00:00:00 2001 From: hsafaei Date: Wed, 18 Jun 2025 15:46:57 +0330 Subject: [PATCH] 1 --- ai_json_move_to_index.py | 22 +- elastic_helper_async.py | 400 ++++++++++++++++++ excel_helper.py | 24 -- import_elastic_async.py | 116 +++++ mmm1.json | 250 ++++++----- r3_import_excel_tcodes.py | 15 +- ...mport_50_codes.py => r4_import_50_codes.py | 15 +- ...t_plan_excel.py => r5_import_plan_excel.py | 14 +- sql_helper.py | 46 ++ temp_codes.py | 12 +- version_util.py | 92 ++++ 11 files changed, 856 insertions(+), 150 deletions(-) create mode 100644 elastic_helper_async.py delete mode 100644 excel_helper.py create mode 100644 import_elastic_async.py rename r5_import_50_codes.py => r4_import_50_codes.py (71%) rename r4_import_plan_excel.py => r5_import_plan_excel.py (82%) create mode 100644 sql_helper.py create mode 100644 version_util.py diff --git a/ai_json_move_to_index.py b/ai_json_move_to_index.py index d0dff88..dbb0b90 100644 --- a/ai_json_move_to_index.py +++ b/ai_json_move_to_index.py @@ -140,10 +140,10 @@ def moveClassifierAiCodes(elastic, index_name_o, data): list_bulk=[] for item in data: index += 1 - # percent = int((index / len(data)) * 100) - # if percent != percent_prev: - # print("progress -> %.2f %%" % percent) - # percent_prev = percent + percent = int((index / len(data)) * 100) + if percent != percent_prev: + print("progress -> %.2f %%" % percent) + percent_prev = percent id = item best_code = data[item]['best-class'] @@ -164,12 +164,12 @@ def moveClassifierAiCodes(elastic, index_name_o, data): if len(list_bulk) > 200 : elastic.updateBulkList(list_bulk, index_name_o) list_bulk = [] - print(f"send_round -> {send_round}") + # print(f"send_round -> {send_round}") send_round += 1 if len(list_bulk) : elastic.updateBulkList(list_bulk, index_name_o) - print(f"last ::: send_round -> {send_round}") + # print(f"last ::: send_round -> {send_round}") @@ -185,12 +185,15 @@ def moveClassifierAiCodes(elastic, index_name_o, data): 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_60') # password=os.getenv('HOST_60_PASS') @@ -198,8 +201,7 @@ password=os.getenv('HOST_160_PASS') print(host) # print(password) -# path_base_map = "G:/Project2/gateway2_main/repo/_other/" -path_base_map = "" +path_base_map = "G:/Project2/gateway2_main/repo/_other/" elastic = ElasticHelper(host, password, "elastic", path_base_map) diff --git a/elastic_helper_async.py b/elastic_helper_async.py new file mode 100644 index 0000000..1329caf --- /dev/null +++ b/elastic_helper_async.py @@ -0,0 +1,400 @@ +from elasticsearch import AsyncElasticsearch +from elasticsearch.helpers import async_bulk +import sys +import os +import asyncio +import aiofiles +import json +from dotenv import load_dotenv +from zipfile import ZipFile +from time import sleep +import gc + + + +class elastic_helper_async: + + def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mapping = ""): + + # self.limit_data = os.getenv("ELASTIC_LIMIT_IMPORT") + # self.app_key = os.getenv("APP_KEY") + + if path_mapping : + self.path_mapping = path_mapping + + if es_pass == '' : + self.aes = AsyncElasticsearch(es_url, timeout=100000000) + else: + self.aes = AsyncElasticsearch(es_url, basic_auth=(es_user, es_pass),timeout=100000000) + + print(es_url) + print(self.aes) + + self.success_connect = False + for a in range(0,10): + try : + if not self.es.ping(): + print('elastic not ping, sleep 30 s : ', a) + sleep(5) + continue + else: + self.success_connect = True + break + + except Exception as e: + break + + if not self.success_connect : + print('******','not access to elastic service') + return + + + self.counter = 0 + self.total = 0 + self.id = "" + + + + + + async def test_file(self,array: list, name_s): + for a in array: + if a == name_s: + return True + + return False + + + async def name_file(self,array: list, namber_claer:str): + data = [] + for a in array: + data.append(a[:-namber_claer]) + + print(data) + return data + + async def read_file_json_mapping(self, name_map_general ): + async with aiofiles.open(f"{self.path_mapping}/general/" + name_map_general + ".json", mode="r", encoding="utf8") as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + return data_mapping_josn + + + async def create_general_indexes(self): + mapping_general = f"{self.path_mapping}/general/" + list_general=['gn_setting','gn_calendar' ,'gn_dataset','gn_entity','gn_log_action','gn_log_change','gn_log_search','gn_research' ] + + for seed_general in list_general: + print("mapping "+seed_general) + data_json_mapping = await self.read_file_json_mapping(seed_general) + try: + await self.aes.indices.create(index=seed_general, body=data_json_mapping) + except: + print("This file has already been created, and I cannot create it again.") + + + async def create_mapping_delete(self,location_file_zip:str, app_key="majles"): + locations_data_ok = [] + location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/") + location_mapping_general = os.listdir(f"{self.path_mapping}/general/") + location_filezip = os.listdir(location_file_zip) + name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5) + name_locations_mapping_general = await self.name_file(location_mapping_general, 5) + name_locations_filezip = await self.name_file(location_filezip, 4) + + for a in name_locations_filezip: + if await self.test_file(name_locations_mapping_majles, a): + print(a) + async with aiofiles.open(f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8") as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") + await self.delete_index(a) + await asyncio.sleep(10) + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + elif await self.test_file(name_locations_mapping_general, a): + print(a) + async with aiofiles.open( + f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8" + ) as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") + await self.delete_index(a) + await asyncio.sleep(10) + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + else: + if a == "mj_rg_section" or a == "semantic_search": + mapping_read = "mj_qa_section" + async with aiofiles.open( + f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8" + ) as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") + await self.delete_index(a) + await asyncio.sleep(10) + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + elif a[-3:] == "_ai": + mapping_read = a[:-3] + try: + + async with aiofiles.open( + f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8" + ) as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") + await self.delete_index(a) + await asyncio.sleep(10) + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + except: + async with aiofiles.open( + f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8" + ) as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") + await self.delete_index(a) + await asyncio.sleep(10) + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + else: + print(f"not funds map {a}") + + return locations_data_ok + ## error for to for + + + async def create_mapping(self,location_file_zip:str, app_key="majles"): + locations_data_ok = [] + location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/") + location_mapping_general = os.listdir(f"{self.path_mapping}/general/") + location_filezip = os.listdir(location_file_zip) + name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5) + name_locations_mapping_general = await self.name_file(location_mapping_general, 5) + name_locations_filezip = await self.name_file(location_filezip, 4) + + for a in name_locations_filezip: + if await self.test_file(name_locations_mapping_majles, a): + print(a) + async with aiofiles.open( + f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8" + ) as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + elif await self.test_file(name_locations_mapping_general, a): + print(a) + async with aiofiles.open( + f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8" + ) as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + else: + if a == "mj_rg_section" or a == "semantic_search": + mapping_read = "mj_qa_section" + async with aiofiles.open( + f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8" + ) as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + elif a[-3:] == "_ai": + mapping_read = a[:-3] + try: + + async with aiofiles.open( + f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8" + ) as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + except: + async with aiofiles.open( + f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8" + ) as file_json: + data_mapping_josn = await file_json.read() + data_mapping_josn = json.loads(data_mapping_josn) + locations_data_ok.append(a) + try: + await self.aes.indices.create(index=a, body=data_mapping_josn) + await self.aes.indices.refresh(index=a) + + except: + print( + f" ******************* There is a mapping {a} ***********************" + ) + + else: + print(f"not funds map {a}") + + return locations_data_ok + ## error for to for + + + async def data_unzip(self,location_file_zip:str,namefile: str): + + current_directory = os.getcwd() + file_name = f"{location_file_zip}/{namefile}.zip" + sleep(10) + print(" -----> start to unzip ... ",file_name) + data1 = [] + os.system(f"del /q /S .\\data\\tmp\\edb\\{namefile}") + os.system(f"mkdir .\\data\\tmp\\edb\\{namefile}") + # os.system(f"del -rf /q .\\data\\tmp\\edb\\{namefile}\\*") + os.system(f"tar -xf {file_name} -C .\\data\\tmp\\edb\\{namefile}\\") + #await asyncio.sleep(1) + list_file_json = os.listdir(f".\\data\\tmp\\edb\\{namefile}\\") + await asyncio.sleep(10) + for a in list_file_json: + try: + with open(f"{current_directory}\\data\\tmp\\edb\\{namefile}\\{a}", "r", encoding="utf8") as file_json: + data = file_json.read() + data = json.loads(data) + for a1 in data: + #await asyncio.sleep(0.001) + try: + yield ( + { + "_op_type": "index", + "_index": namefile, + "_id": a1["_id"], + "_source": a1["_source"], + } + ) + except: + print("error type document") + + except Exception as e: + print(f"read file {current_directory}\\data\\tmp\\edb\\{namefile}\\{a}" + " " + {e}) + + + + async def go_to_data(list_data: list, namefile: str): + with open(f"T:{namefile}.json", "a") as a: + a.write(str(list_data)) + a.close() + + + async def run_elastic_import(self,loc:str): + locations_data = await self.create_mapping(loc) + print(locations_data) + await self.create_general_indexes() + #await asyncio.sleep(5) + for file_list in locations_data: + # try : + await async_bulk(self.aes, self.data_unzip(loc,file_list), True) + gc.collect() + # except: + # await asyncio.sleep(10) + # await async_bulk(self.aes, self.data_unzip(file_list), True) + + print("finash") + #await asyncio.sleep(10) + + + async def run_elastic_import_delete(self,loc:str): + locations_data = await self.create_mapping_delete(loc) + #await asyncio.sleep(1000) + print(locations_data) + await self.create_general_indexes() + #await asyncio.sleep(5) + + for file_list in locations_data: + # try : + await async_bulk(self.aes, self.data_unzip(loc,file_list), True) + gc.collect() + # except: + # await asyncio.sleep(10) + # await async_bulk(self.aes, self.data_unzip(file_list), True) + + print("finash") + #await asyncio.sleep(10) + + async def delete_index(self,name_index:str): + await self.aes.indices.delete(index=name_index, ignore=[400, 404]) # await go_to_data( data2,"gn_dataset") + + + diff --git a/excel_helper.py b/excel_helper.py deleted file mode 100644 index c8abf60..0000000 --- a/excel_helper.py +++ /dev/null @@ -1,24 +0,0 @@ -import pandas as pd - - -class ExcelHelper: - def __init__(self): - self.pd = null - self.data_dict = [] - - - - def load_data(self, file_path, sheet_name=0): - df = pd.read_excel(file_path, sheet_name=sheet_name) - return df - - - # def load_data(self, file_path, sheet_name): - # df = pd.read_excel(file_path, sheet_name=sheet_name) - # selected_columns = df[[self.fltxt_column_name]] - # self.data_dict = selected_columns.to_dict(orient='records') - - # for record in self.data_dict: - # record['_id'] = " " - - # print("✅ داده‌ها با موفقیت از فایل اکسل خوانده شدند.") diff --git a/import_elastic_async.py b/import_elastic_async.py new file mode 100644 index 0000000..3d29532 --- /dev/null +++ b/import_elastic_async.py @@ -0,0 +1,116 @@ +import os +import sys +from dotenv import load_dotenv +from elastic_helper_async import elastic_helper_async +import asyncio +from sql_helper import sql_helper +from time import sleep +# from docker import docker_import +# from version_util import VersionUtil + +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_60') +# password=os.getenv('HOST_60_PASS') + +# host=os.getenv('HOST_161') +# password=os.getenv('HOST_161_PASS') + +# host=os.getenv('HOST_80') +# password=os.getenv('HOST_80_PASS') + +# host=os.getenv('HOST_133') +# password=os.getenv('HOST_133_PASS') + + +current_directory = os.getcwd() +data_t_location = current_directory + "\\data\\" +default_location_data= current_directory + "\\data" + +path_base_map = "G:/Project2/gateway2_main/repo/_other/" +elasticImport = elastic_helper_async(host, password, "elastic", path_base_map) + +name_zip_file = "data_back_0322.zip" + +# versionUtil = VersionUtil(data_t_location) + + +def download_file(): + pass + + +def update_elastic(): + pass + + +def update_mysql(): + pass + +def update_dist(): + pass + + + +# async def elastic(dict_version_info): +# elasticImport = elastic_helper_async() +# if versionUtil.chack_version(dict_version_info["ver_local"],dict_version_info["ver_new"],"elastic"): +# location_elastic=versionUtil.find_location_folder_version(dict_version_info["ver_local"]["elastic"],dict_version_info["ver_new"]["elastic"],"elastic") +# for loc in location_elastic: +# await elasticImport.run_elastic_import(loc) + + + +# async def mariadb(dict_version_info:dict): +# sqlImport = sql_helper() +# sqlImport.create_users() +# if versionUtil.chack_version(dict_version_info["ver_local"],dict_version_info["ver_new"],"db"): +# location_db=versionUtil.find_location_folder_version(dict_version_info["ver_local"]["db"],dict_version_info["ver_new"]["db"],"db") +# for loc in location_db: +# list_file_sql = os.listdir(loc) +# for file in list_file_sql: +# print(f"----> create_database ... {file[:-4]}") +# sqlImport.create_database(file[:-4]) +# print(f"----> read_file_import ... {loc}/{file}") +# sqlImport.read_file_import(f"{loc}/{file}",file[:-4]) + + + +async def main(): + + + + # name_zip_file_arry = sys.argv[1:] + # name_zip_file = name_zip_file_arry[0] + + # arg2 = sys.argv[2:] + # print(arg2) + + # mode = 'normal' + # if len(arg2) : + # mode = arg2[0]y + # print('mode', mode) + + + sub_folder=name_zip_file[:-4] + + # os.system(f"mkdir {default_location_data}\\elastic") + # os.system(f"mkdir {default_location_data}\\elastic\\{sub_folder}") + # os.system(f"copy {default_location_data}\\{name_zip_file} {default_location_data}\\elastic\\{sub_folder}") + # # ؟؟؟؟؟ ??? اگر پوشه ای بود ... + # os.system(f"Expand-Archive -Path {default_location_data}\\elastic\\{sub_folder}\\{name_zip_file} && del {name_zip_file}") + + loc=f"{default_location_data}\\elastic\\{sub_folder}" + os.system("del /f /q /S data\\tmp\\edb\\*") + await elasticImport.run_elastic_import_delete(loc) + os.system("del /f /q /S data\\tmp\\edb\\*") + + ##docker_import(data_t_location) +loop = asyncio.get_event_loop() +loop.run_until_complete(main()) \ No newline at end of file diff --git a/mmm1.json b/mmm1.json index 52f6d08..a37e6ef 100644 --- a/mmm1.json +++ b/mmm1.json @@ -2,351 +2,401 @@ { "title": "آب", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 1, - "listtype": 0 + "listtype": 0, + "id": 8007 }, { "title": "آمار، برنامه و بودجه", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 2, - "listtype": 0 + "listtype": 0, + "id": 8008 }, { "title": "آموزش و پرورش", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 3, - "listtype": 0 + "listtype": 0, + "id": 8009 }, { "title": "آموزش عالی، پژوهش و فناوری", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 4, - "listtype": 0 + "listtype": 0, + "id": 8010 }, { "title": "آیین دادرسی مدنی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 5, - "listtype": 0 + "listtype": 0, + "id": 8011 }, { "title": "آیین دادرسی اداری", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 6, - "listtype": 0 + "listtype": 0, + "id": 8012 }, { "title": "آیین دادرسی کیفری", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 7, - "listtype": 0 + "listtype": 0, + "id": 8013 }, { "title": "اداری و استخدامی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 8, - "listtype": 0 + "listtype": 0, + "id": 8014 }, { "title": "اموال و معاملات دولتی", "projectid": 8, - "meta": "(با زیرفصل اجرای سیاستهای کلی اصل44)", + "meta": "{\"description\":\"(با زیرفصل اجرای سیاستهای کلی اصل44)\"}", "otherid": 9, - "listtype": 0 + "listtype": 0, + "id": 8015 }, { "title": "اطلاعات، امنیت و نظامی، انتظامی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 10, - "listtype": 0 + "listtype": 0, + "id": 8016 }, { "title": "امور زیربنایی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 11, - "listtype": 0 + "listtype": 0, + "id": 8017 }, { "title": "انتخابات", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 12, - "listtype": 0 + "listtype": 0, + "id": 8018 }, { "title": "اوقاف، اماکن دینی و امور مذهبی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 13, - "listtype": 0 + "listtype": 0, + "id": 8019 }, { "title": "ایثارگران", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 14, - "listtype": 0 + "listtype": 0, + "id": 8020 }, { "title": "بانکداری", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 15, - "listtype": 0 + "listtype": 0, + "id": 8021 }, { "title": "برق و انرژی‌های نوین", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 16, - "listtype": 0 + "listtype": 0, + "id": 8022 }, { "title": "بیمه", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 17, - "listtype": 0 + "listtype": 0, + "id": 8023 }, { "title": "پولی و مالی", "projectid": 8, - "meta": " (با زیرفصل‌های سرمایه گذاری داخلی وخارجی ـ بازار سرمایه)", + "meta": "{\"description\":\" (با زیرفصل‌های سرمایه گذاری داخلی وخارجی ـ بازار سرمایه)\"}", "otherid": 18, - "listtype": 0 + "listtype": 0, + "id": 8024 }, { "title": "تأمین اجتماعی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 19, - "listtype": 0 + "listtype": 0, + "id": 8025 }, { "title": "تجارت", "projectid": 8, - "meta": "(اعم از تجارت داخلی و خارجی)", + "meta": "{\"description\":\"(اعم از تجارت داخلی و خارجی)\"}", "otherid": 20, - "listtype": 0 + "listtype": 0, + "id": 8026 }, { "title": "تشکل‌های مدنی و احزاب", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 21, - "listtype": 0 + "listtype": 0, + "id": 8027 }, { "title": "تشکیلات و امور اداری قوه قضائیه", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 22, - "listtype": 0 + "listtype": 0, + "id": 8028 }, { "title": "تعاون", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 23, - "listtype": 0 + "listtype": 0, + "id": 8029 }, { "title": "تعزیرات حکومتی", "projectid": 8, - "meta": "(مجازات‌های غیرقضایی)", + "meta": "{\"description\":\"(مجازات‌های غیرقضایی)\"}", "otherid": 24, - "listtype": 0 + "listtype": 0, + "id": 8030 }, { "title": "تقسیمات کشوری و مدیریت محلی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 25, - "listtype": 0 + "listtype": 0, + "id": 8031 }, { "title": "ثبت اسناد و املاک", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 26, - "listtype": 0 + "listtype": 0, + "id": 8032 }, { "title": "حمل و نقل", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 27, - "listtype": 0 + "listtype": 0, + "id": 8033 }, { "title": "خانواده", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 28, - "listtype": 0 + "listtype": 0, + "id": 8034 }, { "title": "رسانه", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 29, - "listtype": 0 + "listtype": 0, + "id": 8035 }, { "title": "سلامت", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 30, - "listtype": 0 + "listtype": 0, + "id": 8036 }, { "title": "صنعت", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 31, - "listtype": 0 + "listtype": 0, + "id": 8037 }, { "title": "ارتباطات و فناوری اطلاعات", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 32, - "listtype": 0 + "listtype": 0, + "id": 8038 }, { "title": "فرهنگ و هنر", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 33, - "listtype": 0 + "listtype": 0, + "id": 8039 }, { "title": "کار", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 34, - "listtype": 0 + "listtype": 0, + "id": 8040 }, { "title": "کشاورزی و دامپروری", "projectid": 8, - "meta": "(منابع طبیعی)", + "meta": "{\"description\":\"(منابع طبیعی)\"}", "otherid": 35, - "listtype": 0 + "listtype": 0, + "id": 8041 }, { "title": "کیفری", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 36, - "listtype": 0 + "listtype": 0, + "id": 8042 }, { "title": "مالکیت فکری", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 37, - "listtype": 0 + "listtype": 0, + "id": 8043 }, { "title": "مالیات", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 38, - "listtype": 0 + "listtype": 0, + "id": 8044 }, { "title": "محاسبات عمومی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 39, - "listtype": 0 + "listtype": 0, + "id": 8045 }, { "title": "محیط زیست", "projectid": 8, - "meta": "(اراضی مربوط به محیط زیست (خاک) زیر این کد قرار میگیرد)", + "meta": "{\"description\":\"(اراضی مربوط به محیط زیست (خاک) زیر این کد قرار میگیرد)\"}", "otherid": 40, - "listtype": 0 + "listtype": 0, + "id": 8046 }, { "title": "مدنی و امور حسبی", "projectid": 8, - "meta": " (ثبت احوال،تابعیت واتباع خارجی از سرفصل‌های این کد است)", + "meta": "{\"description\":\" (ثبت احوال،تابعیت واتباع خارجی از سرفصل‌های این کد است)\"}", "otherid": 41, - "listtype": 0 + "listtype": 0, + "id": 8047 }, { "title": "مسکن و شهرسازی", "projectid": 8, - "meta": " (اراضی مربوط به مسکن و شهرسازی زیر این کد قرار میگیرد)", + "meta": "{\"description\":\" (اراضی مربوط به مسکن و شهرسازی زیر این کد قرار میگیرد)\"}", "otherid": 42, - "listtype": 0 + "listtype": 0, + "id": 8048 }, { "title": "مصرف", "projectid": 8, - "meta": " (با زیرفصل قانون سازمان ملی استاندارد، سایر قوانین و مقررات استاندارد در زیر هر یک از کدهای مربوطه قرار می گیرد)", + "meta": "{\"description\":\" (با زیرفصل قانون سازمان ملی استاندارد، سایر قوانین و مقررات استاندارد در زیر هر یک از کدهای مربوطه قرار می گیرد)\"}", "otherid": 43, - "listtype": 0 + "listtype": 0, + "id": 8049 }, { "title": "معدن", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 44, - "listtype": 0 + "listtype": 0, + "id": 8050 }, { "title": "مناطق آزاد و ویژه اقتصادی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 45, - "listtype": 0 + "listtype": 0, + "id": 8051 }, { "title": "میراث فرهنگی، گردشگری و صنایع دستی", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 46, - "listtype": 0 + "listtype": 0, + "id": 8052 }, { "title": "نظام قانونگذاری", "projectid": 8, - "meta": " (که شامل سه سرفصل مجلس شورای اسلامی متشکل از (تقنین و نظارت)، شورای نگهبان، مجمع تشخیص مصلحت نظام)", + "meta": "{\"description\":\" (که شامل سه سرفصل مجلس شورای اسلامی متشکل از (تقنین و نظارت)، شورای نگهبان، مجمع تشخیص مصلحت نظام)\"}", "otherid": 47, - "listtype": 0 + "listtype": 0, + "id": 8053 }, { "title": "نظامهای صنفی و حرفهای", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 48, - "listtype": 0 + "listtype": 0, + "id": 8054 }, { "title": "نفت و گاز", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 49, - "listtype": 0 + "listtype": 0, + "id": 8055 }, { "title": "ورزش", "projectid": 8, - "meta": "", + "meta": "{\"description\":\"\"}", "otherid": 50, - "listtype": 0 + "listtype": 0, + "id": 8056 } ] \ No newline at end of file diff --git a/r3_import_excel_tcodes.py b/r3_import_excel_tcodes.py index 398e92a..de760ef 100644 --- a/r3_import_excel_tcodes.py +++ b/r3_import_excel_tcodes.py @@ -661,7 +661,7 @@ def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_ 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') + # new_df.to_excel(file_excel2, index=False, engine='openpyxl') except Exception as e: @@ -836,7 +836,7 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_i 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') + # new_df.to_excel(file_excel2, index=False, engine='openpyxl') except Exception as e: @@ -935,21 +935,24 @@ def run_Etebar_directory(elastic, directory, output): 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') + print(password) 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") +#run_Codes_directory(elastic, "./data/tcodes", "./data/tcodes/result") -# run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result") +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") diff --git a/r5_import_50_codes.py b/r4_import_50_codes.py similarity index 71% rename from r5_import_50_codes.py rename to r4_import_50_codes.py index 52738fc..3693794 100644 --- a/r5_import_50_codes.py +++ b/r4_import_50_codes.py @@ -2,12 +2,19 @@ import pandas as pd import requests import json from text_normalizer import TextNormalizer -from config_base import * +# from config_base import * from general_functions import * ADD_ITEM_ROUTE = "subject/add" +# TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDgyNTY3MTYsImp0aSI6IlZWejlWRDFGMUx5UkEyd01EaW5od3M3cTJRRkVqYW9kIiwiaXNzIjpudWxsLCJleHAiOjE3NDk1NTY3MTUsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDY0NVx1MDYyZlx1MDZjY1x1MDYzMSBcdTA2NDFcdTA2NDZcdTA2Y2MiLCJsYXN0X25hbWUiOiJcdTA2MzNcdTA2MjdcdTA2NDVcdTA2MjdcdTA2NDZcdTA2NDciLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.QljFs4f0HFT7S8qrib6q54kMWg7z381v2uqoiSFDfR4' +TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDk1NjU0NDksImp0aSI6IlwvODBxR2pEUHlleFZVRFErTkhKcGl0ejd6TmdvaDdHSiIsImlzcyI6bnVsbCwiZXhwIjoxNzUwODY1NDQ4LCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjIsImZpcnN0X25hbWUiOiJcdTA2MmRcdTA2NDVcdTA2Y2NcdTA2MmYiLCJsYXN0X25hbWUiOiJcdTA2MzVcdTA2NDFcdTA2MjdcdTA2Y2NcdTA2Y2MiLCJlbWFpbCI6InNhZmFlaS5oYW1pZEBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImhzYWZhZWkiLCJ1c2VyX2xldmVsIjoyfX0.XmEEA_DhVbUQe76guQxuNrEoTUxPRMYd5Zbi7l7m5M4' +ACCEPT = "application/json" +HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT} +# BASE_URL = "http://192.168.23.160/api/" +BASE_URL = "http://192.168.23.113/api/" # TITLE = "" + def read_excel_data(file_path ): df = pd.read_excel(file_path ) df.fillna("", inplace=True) @@ -57,7 +64,8 @@ def insertProejct(title, id=''): def process_excel_data(file_path, send_to_server=True): data = read_excel_data(file_path) data = sorted(data, key=lambda x: x["ID"]) - projectid = insert_project('کدهای تنقیح 50 باب', 8) + # projectid = insert_project('کدهای تنقیح 50 باب', 8) + projectid = insertProejct('کدهای تنقیح 50 باب', 8) id_counter = 1 # برای fake_id local_id_map = {} # برای نگه‌داشتن ID ساختگی در حالت تست output_data = [] # لیستی برای ذخیره خروجی نهایی @@ -65,6 +73,7 @@ def process_excel_data(file_path, send_to_server=True): caption = row["CAPTION"] row_id = row["ID"] meta = row.get("META", "") + meta = '{"description":"'+meta+'"}' insertProejct('پلان ' + caption, 100+row_id) @@ -108,4 +117,4 @@ def process_excel_data(file_path, send_to_server=True): if __name__ == "__main__": file_path = "data/کدهای 50 گانه.xlsx" - process_excel_data(file_path ,send_to_server=False ) # False for test \ No newline at end of file + process_excel_data(file_path ,send_to_server=True ) # False for test \ No newline at end of file diff --git a/r4_import_plan_excel.py b/r5_import_plan_excel.py similarity index 82% rename from r4_import_plan_excel.py rename to r5_import_plan_excel.py index 8f0eb18..72fd45b 100644 --- a/r4_import_plan_excel.py +++ b/r5_import_plan_excel.py @@ -3,11 +3,17 @@ import requests import json import os from text_normalizer import TextNormalizer -from config_base import * +# from config_base import * from general_functions import * ADD_ITEM_ROUTE = "subject/add" +# TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDgyNTY3MTYsImp0aSI6IlZWejlWRDFGMUx5UkEyd01EaW5od3M3cTJRRkVqYW9kIiwiaXNzIjpudWxsLCJleHAiOjE3NDk1NTY3MTUsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDY0NVx1MDYyZlx1MDZjY1x1MDYzMSBcdTA2NDFcdTA2NDZcdTA2Y2MiLCJsYXN0X25hbWUiOiJcdTA2MzNcdTA2MjdcdTA2NDVcdTA2MjdcdTA2NDZcdTA2NDciLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.QljFs4f0HFT7S8qrib6q54kMWg7z381v2uqoiSFDfR4' +TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDk1NjU0NDksImp0aSI6IlwvODBxR2pEUHlleFZVRFErTkhKcGl0ejd6TmdvaDdHSiIsImlzcyI6bnVsbCwiZXhwIjoxNzUwODY1NDQ4LCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjIsImZpcnN0X25hbWUiOiJcdTA2MmRcdTA2NDVcdTA2Y2NcdTA2MmYiLCJsYXN0X25hbWUiOiJcdTA2MzVcdTA2NDFcdTA2MjdcdTA2Y2NcdTA2Y2MiLCJlbWFpbCI6InNhZmFlaS5oYW1pZEBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImhzYWZhZWkiLCJ1c2VyX2xldmVsIjoyfX0.XmEEA_DhVbUQe76guQxuNrEoTUxPRMYd5Zbi7l7m5M4' +ACCEPT = "application/json" +HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT} +# BASE_URL = "http://192.168.23.160/api/" +BASE_URL = "http://192.168.23.113/api/" # TITLE = "" def read_excel_data(file_path ,sheet_name): @@ -208,8 +214,10 @@ def process_excel_data(file_path , sheet_name): if __name__ == "__main__": file_path = "data/Plan.xlsx" - # sheet_name = 'آموزش و پرورش' - # sheet_name = 'مناطق آزاد و ویژه اقتصادی' + sheet_name = 'آموزش و پرورش' + process_excel_data(file_path , sheet_name) + sheet_name = 'مناطق آزاد و ویژه اقتصادی' + process_excel_data(file_path , sheet_name) sheet_name = 'فرهنگ و هنر' process_excel_data(file_path , sheet_name) diff --git a/sql_helper.py b/sql_helper.py new file mode 100644 index 0000000..aef3f69 --- /dev/null +++ b/sql_helper.py @@ -0,0 +1,46 @@ +import mariadb +from dotenv import load_dotenv +import os + +class sql_helper: + def __init__(self): + 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") + self.cnx = mariadb.connect(user="root", password=MYSQL_root_password, host=MYSQL_host) + self.cursor = self.cnx.cursor() + def create_users(self): + password = os.getenv("MYSQL_password") + users = os.getenv("MYSQL_username") + try: + self.cursor.execute(f"CREATE USER '{users}'@'%' IDENTIFIED BY '{password}'") + self.cursor.execute(f" GRANT ALL PRIVILEGES ON *.* to '{users}'@'%'") + print("create user") + except: + print("not create user") + + + def read_file_import(self,filename,name_database): + self.cursor.execute(f"use {name_database}") + with open(filename, 'r') as file: + sqlFile = file.read() + file.close() + + sqlCommands = sqlFile.split(';\n') + + for command in sqlCommands: + try: + if command.rstrip() != '': + self.cursor.execute(command) + self.cnx.commit() + except ValueError as msg: + print ("Command skipped: ", msg) + def create_database(self,name_database): + try: + self.cursor.execute(f"CREATE DATABASE {name_database};") + self.cnx.commit() + print(f"create database {name_database}") + except: + print(f"not create database {name_database}") diff --git a/temp_codes.py b/temp_codes.py index 63534a4..710036a 100644 --- a/temp_codes.py +++ b/temp_codes.py @@ -19,8 +19,6 @@ 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') @@ -33,6 +31,9 @@ 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') + print(host) # print(password) @@ -43,11 +44,14 @@ 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-m1") +#elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section-m1") # elastic.createIndex( 'mj_qa_section-m1', 'majles', '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') +#elastic.restorFileToElastic2('G:/Project2/111/gn_calendar.zip', 'gn_calendar', 'general', False, 'gn_calendar') + #elastic.backupIndexToZipfile("G:/Project2/111", "mj_qa_section") # elastic.restorFileToElastic2('G:/Project2/111/gn_setting.zip', 'gn_setting', 'general', False, 'gn_setting') diff --git a/version_util.py b/version_util.py new file mode 100644 index 0000000..20b627a --- /dev/null +++ b/version_util.py @@ -0,0 +1,92 @@ + +import os +import yaml + + +class VersionUtil(): + + data_t_location = "./data/" + def __init__(self, data_t_location): + self.data_t_location = data_t_location + + def chack_folder_full(self, list_folder: list): + for a in list_folder: + if a == "full": + return True + if a == "update": + return False + + + + + + def chack_version(self, version_old : dict, version_new : dict, name_part : str): + if version_old[name_part] < version_new[name_part]: + return True + + + + + + def find_version(self): + data_file_version_local = {} + try: + with open(f"{self.data_t_location}VERSION_local", "r") as file_yaml_version_local: + data_file_version_local = yaml.safe_load(file_yaml_version_local) + + except: + print("not fund file version local") + + if data_file_version_local == {} or data_file_version_local == None: + print("None data for local") + data_file_version_local = {"version": {"db": 0.0, "elastic": 0.0, "dist": 0.0}} + + try: + with open(f"{self.data_t_location}VERSION", "r") as file_yaml_version_new: + data_file_version_new = yaml.safe_load(file_yaml_version_new) + + except: + print("not fund file yaml new VERSION") + exit(1) + try: + return {"ver_new":data_file_version_new["version"],"ver_local":data_file_version_local["version"]} + except: + print("file yaml local empety") + data_file_version_local = {"version": {"db": 0.0, "elastic": 0.0, "dist": 0.0}} + return {"ver_new":data_file_version_new["version"],"ver_local":data_file_version_local["version"]} + + + def find_location_folder_version(self, version_local:str,version_new:str,name_service:str): + + version_local = str(version_local).split(".") + version_new = str(version_new).split(".") + version_local_full_namber = int(version_local[0]) + version_local_update_namber = int(version_local[1]) + version_new_full_namber = int(version_new[0]) + version_new_update_namber = int(version_new[1]) + list_location = [] + if version_local_full_namber == version_new_full_namber : + for versions in range(version_local_update_namber,version_new_update_namber): + list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{versions+1}/update") + if version_local_update_namber == version_new_update_namber : + list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{version_new_update_namber}/update") + print(list_location) + else : + list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{0}/full") + for versions in range(0,version_new_update_namber): + list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{versions+1}/update") + if version_local_update_namber == version_new_update_namber : + list_location.append(f"{self.data_t_location}{name_service}/v{version_new_full_namber}.{version_new_update_namber}/full") + print(list_location) + + return list_location + + + def version_local_write(self, data_version_file:dict): + try: + os.remove(f"{self.data_t_location}VERSION_local") + except: + print("not fund file local") + with open(f"{self.data_t_location}VERSION_local","w") as file_local: + yaml.dump(data_version_file,file_local) +