refactor folders py 3

This commit is contained in:
hsafaei
2025-09-02 13:04:48 +03:30
parent 5a6647bbf2
commit 4b449268d3
13 changed files with 21 additions and 11 deletions
+400
View File
@@ -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")
+4 -4
View File
@@ -1,6 +1,6 @@
from normalizer import Normalizer
from common.normalizer import Normalizer
from common.tokenizer import *
import jalali
from common.jalali import Gregorian,Persian
import re
import sys
from re import sub
@@ -376,7 +376,7 @@ def jdate2timestamp_old(dt):
ndt = dt.replace("y", "")
ndt = ndt.replace("m", "/")
ndt = ndt.replace("d", "/")
gd = jalali.Persian(ndt).gregorian_datetime()
gd = Persian(ndt).gregorian_datetime()
# print(gd)
ztime = datetime.time(0, 0, 0, 0)
gdt = datetime.datetime.combine(gd, ztime)
@@ -389,7 +389,7 @@ def jdate2timestamp(dt):
ndt = dt.replace("y", "")
ndt = ndt.replace("m", "/")
ndt = ndt.replace("d", "/")
gd = jalali.Persian(ndt).gregorian_datetime()
gd = Persian(ndt).gregorian_datetime()
base = datetime.date(1970, 1, 1)
rr = (gd-base).total_seconds()
tst = int( round(rr) * 1000)
+192
View File
@@ -0,0 +1,192 @@
# In The Name Of Allah
#
# Jalali date converter
# 2014 07 25
# Ported from PHP (http://jdf.scr.ir/) to Python (2&3) by Mohammad Javad Naderi <mjnaderi@gmail.com>
#
# As mentioned in http://jdf.scr.ir/, the original code is free and open source,
# and you are not allowed to sell it. You can read more in http://jdf.scr.ir/.
#
# Original License Notes:
#
# /** Software Hijri_Shamsi , Solar(Jalali) Date and Time
# Copyright(C)2011, Reza Gholampanahi , http://jdf.scr.ir
# version 2.55 :: 1391/08/24 = 1433/12/18 = 2012/11/15 */
#
# /** Convertor from and to Gregorian and Jalali (Hijri_Shamsi,Solar) Functions
# Copyright(C)2011, Reza Gholampanahi [ http://jdf.scr.ir/jdf ] version 2.50 */
#
# Example Usage:
#
# >>> import jalali
#
# >>> jalali.Persian('1393-1-11').gregorian_string()
# '2014-3-31'
# >>> jalali.Persian(1393, 1, 11).gregorian_datetime()
# datetime.date(2014, 3, 31)
# >>> jalali.Persian('1393/1/11').gregorian_string("{}/{}/{}")
# '2014/3/31'
# >>> jalali.Persian((1393, 1, 11)).gregorian_tuple()
# (2014, 3, 31)
#
# >>> jalali.Gregorian('2014-3-31').persian_string()
# '1393-1-11'
# >>> jalali.Gregorian('2014,03,31').persian_tuple()
# (1393, 1, 11)
# >>> jalali.Gregorian(2014, 3, 31).persian_year
# 1393
import re
import datetime
class Gregorian:
def __init__(self, *date):
# Parse date
if len(date) == 1:
date = date[0]
if type(date) is str:
m = re.match(r'^(\d{4})\D(\d{1,2})\D(\d{1,2})$', date)
if m:
[year, month, day] = [int(m.group(1)), int(m.group(2)), int(m.group(3))]
else:
raise Exception("Invalid Input String")
elif type(date) is datetime.date:
[year, month, day] = [date.year, date.month, date.day]
elif type(date) is tuple:
year, month, day = date
year = int(year)
month = int(month)
day = int(day)
else:
raise Exception("Invalid Input Type")
elif len(date) == 3:
year = int(date[0])
month = int(date[1])
day = int(date[2])
else:
raise Exception("Invalid Input")
# Check the validity of input date
try:
datetime.datetime(year, month, day)
except:
raise Exception("Invalid Date")
self.gregorian_year = year
self.gregorian_month = month
self.gregorian_day = day
# Convert date to Jalali
d_4 = year % 4
g_a = [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
doy_g = g_a[month] + day
if d_4 == 0 and month > 2:
doy_g += 1
d_33 = int(((year - 16) % 132) * .0305)
a = 286 if (d_33 == 3 or d_33 < (d_4 - 1) or d_4 == 0) else 287
if (d_33 == 1 or d_33 == 2) and (d_33 == d_4 or d_4 == 1):
b = 78
else:
b = 80 if (d_33 == 3 and d_4 == 0) else 79
if int((year - 10) / 63) == 30:
a -= 1
b += 1
if doy_g > b:
jy = year - 621
doy_j = doy_g - b
else:
jy = year - 622
doy_j = doy_g + a
if doy_j < 187:
jm = int((doy_j - 1) / 31)
jd = doy_j - (31 * jm)
jm += 1
else:
jm = int((doy_j - 187) / 30)
jd = doy_j - 186 - (jm * 30)
jm += 7
self.persian_year = jy
self.persian_month = jm
self.persian_day = jd
def persian_tuple(self):
return self.persian_year, self.persian_month, self.persian_day
def persian_string(self, date_format="{}-{}-{}"):
return date_format.format(self.persian_year, self.persian_month, self.persian_day)
class Persian:
def __init__(self, *date):
# Parse date
if len(date) == 1:
date = date[0]
if type(date) is str:
m = re.match(r'^(\d{4})\D(\d{1,2})\D(\d{1,2})$', date)
if m:
[year, month, day] = [int(m.group(1)), int(m.group(2)), int(m.group(3))]
else:
raise Exception("Invalid Input String")
elif type(date) is tuple:
year, month, day = date
year = int(year)
month = int(month)
day = int(day)
else:
raise Exception("Invalid Input Type")
elif len(date) == 3:
year = int(date[0])
month = int(date[1])
day = int(date[2])
else:
raise Exception("Invalid Input")
# Check validity of date. TODO better check (leap years)
if year < 1 or month < 1 or month > 12 or day < 1 or day > 31 or (month > 6 and day == 31):
raise Exception("Incorrect Date")
self.persian_year = year
self.persian_month = month
self.persian_day = day
# Convert date
d_4 = (year + 1) % 4
if month < 7:
doy_j = ((month - 1) * 31) + day
else:
doy_j = ((month - 7) * 30) + day + 186
d_33 = int(((year - 55) % 132) * .0305)
a = 287 if (d_33 != 3 and d_4 <= d_33) else 286
if (d_33 == 1 or d_33 == 2) and (d_33 == d_4 or d_4 == 1):
b = 78
else:
b = 80 if (d_33 == 3 and d_4 == 0) else 79
if int((year - 19) / 63) == 20:
a -= 1
b += 1
if doy_j <= a:
gy = year + 621
gd = doy_j + b
else:
gy = year + 622
gd = doy_j - a
for gm, v in enumerate([0, 31, 29 if (gy % 4 == 0) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]):
if gd <= v:
break
gd -= v
self.gregorian_year = gy
self.gregorian_month = gm
self.gregorian_day = gd
def gregorian_tuple(self):
return self.gregorian_year, self.gregorian_month, self.gregorian_day
def gregorian_string(self, date_format="{}-{}-{}"):
return date_format.format(self.gregorian_year, self.gregorian_month, self.gregorian_day)
def gregorian_datetime(self):
return datetime.date(self.gregorian_year, self.gregorian_month, self.gregorian_day)
+1403
View File
File diff suppressed because it is too large Load Diff
+92
View File
@@ -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)