monir
This commit is contained in:
@@ -0,0 +1,336 @@
|
||||
# --------------------------- modularity
|
||||
from idataparser.common.elastic_helper import ElasticHelper
|
||||
from idataparser.monir.base_model import MnTerm, MnSanad, MnMeetEntity, MnMeet
|
||||
import time, traceback, uuid, orjson
|
||||
from datetime import datetime, timezone
|
||||
from elasticsearch.helpers import scan
|
||||
from typing import Union
|
||||
import jdatetime
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
|
||||
# --------------------------- global-params
|
||||
input_es_index_name = ""
|
||||
new_index_name = "mn_term"
|
||||
old_index_name = "mn_sanad"
|
||||
UNVALID_TIME = {
|
||||
"1800-01-01T00:00:00",
|
||||
"1900-01-28T00:00:00",
|
||||
"1900-01-18T00:00:00",
|
||||
"1900-01-25T00:00:00",
|
||||
"1900-01-04T00:00:00",
|
||||
"1900-01-05T00:00:00",
|
||||
"1900-02-05T00:00:00",
|
||||
"1900-01-17T00:00:00",
|
||||
"1900-01-31T00:00:00",
|
||||
"1900-01-29T00:00:00",
|
||||
"1900-01-26T00:00:00",
|
||||
"1900-01-07T00:00:00",
|
||||
"1900-01-12T00:00:00",
|
||||
"1900-01-11T00:00:00",
|
||||
"1900-02-04T00:00:00",
|
||||
"1900-01-22T00:00:00",
|
||||
"1900-02-03T00:00:00",
|
||||
"1900-01-16T00:00:00",
|
||||
"1900-01-27T00:00:00",
|
||||
"1900-01-06T00:00:00",
|
||||
"1900-01-03T00:00:00",
|
||||
"1900-01-20T00:00:00",
|
||||
"1900-01-30T00:00:00",
|
||||
"1900-01-10T00:00:00",
|
||||
"1900-02-01T00:00:00",
|
||||
"1900-01-15T00:00:00",
|
||||
"1900-01-23T00:00:00",
|
||||
"1900-01-02T00:00:00",
|
||||
"1900-01-24T00:00:00",
|
||||
"1900-01-13T00:00:00",
|
||||
"1900-01-19T00:00:00",
|
||||
"1900-01-14T00:00:00",
|
||||
"1900-01-21T00:00:00",
|
||||
"1900-01-01T00:00:00",
|
||||
"1900-01-09T00:00:00",
|
||||
"1900-02-02T00:00:00",
|
||||
"1900-01-08T00:00:00",
|
||||
}
|
||||
# --------------------------- function
|
||||
|
||||
|
||||
def save_orjson(path, data):
|
||||
with open(path, "wb") as f:
|
||||
f.write(
|
||||
orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS)
|
||||
)
|
||||
|
||||
|
||||
def load_orjson(path: str | Path):
|
||||
path = Path(path)
|
||||
with path.open("rb") as f: # باید باینری باز بشه برای orjson
|
||||
return orjson.loads(f.read())
|
||||
|
||||
|
||||
def timestamp_to_shamsi(
|
||||
timestamp: int, fmt: str = "%Y/%m/%d %H:%M:%S", year_only: bool = True
|
||||
) -> Union[str, int]:
|
||||
dt_jalali = jdatetime.datetime.fromtimestamp(timestamp)
|
||||
if year_only:
|
||||
return dt_jalali.year # int, e.g. 1404
|
||||
return dt_jalali.strftime(fmt)
|
||||
|
||||
|
||||
def year_from_timestamp(ts: int | float):
|
||||
"""
|
||||
Convert a UNIX timestamp to its Gregorian year.
|
||||
Returns None if input is invalid.
|
||||
"""
|
||||
try:
|
||||
dt = datetime.fromtimestamp(ts)
|
||||
return int(dt.year)
|
||||
except (ValueError, OSError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
ORIGIN_OF_TIME = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def datetime_to_int(dt):
|
||||
try:
|
||||
if dt is None:
|
||||
return None
|
||||
|
||||
if isinstance(dt, str) and dt in UNVALID_TIME:
|
||||
return None
|
||||
|
||||
# Already int/float timestamp
|
||||
if isinstance(dt, (int, float)):
|
||||
return int(dt)
|
||||
|
||||
# Convert string → datetime
|
||||
if isinstance(dt, str):
|
||||
dt = dt.strip()
|
||||
# if dt.endswith("Z"): # handle UTC Zulu suffix
|
||||
# dt = dt.replace("Z", "+00:00")
|
||||
try:
|
||||
dt = datetime.fromisoformat(dt)
|
||||
except Exception:
|
||||
# fallback: try simple date format
|
||||
try:
|
||||
dt = datetime.strptime(dt, "%Y-%m-%d")
|
||||
except Exception as e:
|
||||
print("❌ could not parse date:", dt, e)
|
||||
return None
|
||||
|
||||
if isinstance(dt, datetime):
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
else:
|
||||
dt = dt.astimezone(timezone.utc)
|
||||
return int(dt.timestamp())
|
||||
|
||||
if not isinstance(dt, datetime):
|
||||
print("❌ not a datetime after conversion:", dt, type(dt))
|
||||
return None
|
||||
|
||||
# Ensure UTC awareness
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
else:
|
||||
dt = dt.astimezone(timezone.utc)
|
||||
|
||||
return int(dt)
|
||||
|
||||
except Exception as e:
|
||||
print("❌ Exception in datetime_to_int:", e)
|
||||
return None
|
||||
|
||||
|
||||
def get_unique_id(prfix="mn_tr_"):
|
||||
return str(prfix + uuid.uuid4().hex[:8])
|
||||
|
||||
|
||||
def safe_min(a, b):
|
||||
if a is None:
|
||||
return b
|
||||
if b is None:
|
||||
return a
|
||||
return min(a, b)
|
||||
|
||||
def safe_max(a, b):
|
||||
if a is None:
|
||||
return b
|
||||
if b is None:
|
||||
return a
|
||||
return max(a, b)
|
||||
|
||||
def conver_mn_term(old_data: list, es_helper, index_name_o):
|
||||
try:
|
||||
|
||||
all_title = set()
|
||||
branch_to_authors = {}
|
||||
branch_to_id = defaultdict(list)
|
||||
valid_time_data = []
|
||||
#### -------- prepare data
|
||||
############# -------- prepare time and year begin
|
||||
phase_1 = []
|
||||
for i in old_data:
|
||||
try:
|
||||
i_old = i.copy()
|
||||
i["begin_date"] = datetime_to_int(i["begin_date"])
|
||||
i["end_date"] = datetime_to_int(i["end_date"])
|
||||
|
||||
if i["begin_date"] is None:
|
||||
i["begin_year"] = None
|
||||
else:
|
||||
i["begin_year"] = timestamp_to_shamsi(i["begin_date"])
|
||||
|
||||
sanad_data = MnSanad.model_validate(i)
|
||||
phase_1.append(sanad_data)
|
||||
except Exception as e:
|
||||
print(f'i_old {i_old}')
|
||||
traceback.print_exc()
|
||||
return 0
|
||||
|
||||
|
||||
begin_datas = {}
|
||||
end_datas = {}
|
||||
for sanad_data in phase_1:
|
||||
try:
|
||||
branch = sanad_data.branch
|
||||
begin_date = sanad_data.begin_date
|
||||
end_date = sanad_data.end_date
|
||||
|
||||
if branch == "--":
|
||||
term_data = MnTerm(
|
||||
id=get_unique_id(),
|
||||
old_sanad_id = [sanad_data.id],
|
||||
author=sanad_data.author,
|
||||
begin_date=begin_date,
|
||||
begin_year=sanad_data.begin_year,
|
||||
end_date=end_date,
|
||||
title=None,
|
||||
)
|
||||
valid_time_data.append(term_data.model_dump())
|
||||
else:
|
||||
title = sanad_data.branch
|
||||
if title != None:
|
||||
if title not in all_title:
|
||||
all_title.add(branch)
|
||||
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
return 0
|
||||
|
||||
print(f'all_title {len(all_title)}')
|
||||
for sanad_data in phase_1:
|
||||
title = sanad_data.branch
|
||||
if title == "--" or not title:
|
||||
continue # اینها رو جداگانه مدیریت کردی
|
||||
|
||||
begin_date = sanad_data.begin_date
|
||||
end_date = sanad_data.end_date
|
||||
author = sanad_data.author
|
||||
|
||||
if title not in begin_datas:
|
||||
begin_datas[title] = begin_date
|
||||
end_datas[title] = end_date
|
||||
branch_to_authors[title] = author
|
||||
branch_to_id[title].append(sanad_data.id)
|
||||
else:
|
||||
begin_datas[title] = safe_min(begin_datas[title], begin_date)
|
||||
end_datas[title] = safe_max(end_datas[title], end_date)
|
||||
|
||||
|
||||
for title in begin_datas:
|
||||
term_data = MnTerm(
|
||||
id=get_unique_id(),
|
||||
old_sanad_id=branch_to_id[title], # یا مثلاً اولین id مرتبط — اگر نیاز داری
|
||||
author=branch_to_authors[title],
|
||||
begin_date=begin_datas[title],
|
||||
begin_year=timestamp_to_shamsi(begin_datas[title], year_only=True) if begin_datas[title] else None,
|
||||
end_date=end_datas[title],
|
||||
title=title,
|
||||
)
|
||||
valid_time_data.append(term_data.model_dump())
|
||||
|
||||
print(f"valid_time_data {len(valid_time_data)}")
|
||||
######## save in json if u want
|
||||
# save_orjson(data=unvalid_time_data, path="./unvalid_time_data.json")
|
||||
# save_orjson(data=valid_time_data, path="./valid_time_data.json")
|
||||
|
||||
#### -------- insert to es
|
||||
for term_data in valid_time_data:
|
||||
es_helper.update_index_doc(
|
||||
is_update_state=False,
|
||||
index_name_o=index_name_o,
|
||||
eid=term_data.get('id'),
|
||||
data=term_data
|
||||
)
|
||||
|
||||
print(
|
||||
'✅ Data-Created',
|
||||
' - saved-> MnTerm',
|
||||
sep='\n',
|
||||
)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
raise ValueError("❌ Problem in the Validation data Sanad")
|
||||
|
||||
|
||||
def get_old_sanads(hits_list):
|
||||
result = []
|
||||
for hit in hits_list:
|
||||
begin_date = hit["_source"].get("begin_date")
|
||||
if begin_date:
|
||||
try:
|
||||
# فرض: begin_date یک رشته با فرمت ISO مثل "1945-03-12T00:00:00"
|
||||
year = int(begin_date[:4])
|
||||
if year < 1950:
|
||||
result.append({"_id": hit["_id"], "begin_date": begin_date})
|
||||
except (ValueError, IndexError, TypeError):
|
||||
# اگر فرمت تاریخ مشکل داشت، نادیده بگیر (یا لاگ کن)
|
||||
continue
|
||||
return result
|
||||
|
||||
|
||||
# --------------------------- flow
|
||||
dash = "-" * 25
|
||||
es_helper = ElasticHelper(
|
||||
es_url="http://192.168.23.60:6900",
|
||||
es_user="elastic",
|
||||
es_pass="1234",
|
||||
# path_mappings = ""
|
||||
)
|
||||
# es_helper.deleteIndex(index_name=new_index_name)
|
||||
|
||||
print(dash, " es_helper-Loaded ", dash)
|
||||
fields = ["id", "begin_date", "end_date", "branch", "author"] # 'begin_year'
|
||||
es = es_helper.es
|
||||
old_data = list(
|
||||
scan(es, index="mn_sanad", query={"_source": fields, "query": {"match_all": {}}})
|
||||
)
|
||||
#################### --- for find unvalid time data
|
||||
# data = get_old_sanads(old_data)
|
||||
# save_orjson(data=data, path='./unvalid_time_list.json')
|
||||
# time_data = load_orjson("./unvalid_time_list.json")
|
||||
##################### --- for find unvalid time data
|
||||
####### old_data = old_data['hits']['hits'] # don't use in scan
|
||||
valid_list = []
|
||||
for i in old_data:
|
||||
valid_i = i["_source"]
|
||||
valid_i["id"] = i["_id"]
|
||||
# if i['_source']['branch'] is None:
|
||||
# print(f'branch {i}')
|
||||
# continue
|
||||
valid_list.append(valid_i)
|
||||
|
||||
print(f"old_data {len(valid_list)} ")
|
||||
conver_mn_term(old_data=valid_list, es_helper=es_helper, index_name_o=new_index_name)
|
||||
|
||||
print(dash, " FinishEd ", dash)
|
||||
|
||||
# --------------------------- RUN
|
||||
# ------ command
|
||||
# --liunx
|
||||
# python3 -m app.monir.sanad_stuff.py
|
||||
# --windows
|
||||
# python -m app.monir.sanad_stuff.py
|
||||
# python -m app.monir.sanad_stuff
|
||||
Reference in New Issue
Block a user