Files
init_dataParser/app/monir/sanad_2_new_safa.py
T
2025-12-06 12:03:01 +03:30

699 lines
21 KiB
Python

# --------------------------- modularity
from idataparser import (
DataHelper,
ElasticHelper,
InitTextNormalizer,
DataHelper,
save_orjson,
load_orjson,
)
from .base_model import (
MnTerm,
MnMeetEntity,
MnMeet,
List,
MnSanad2Meet,
Properties,
Subjects,
ReportInfo,
FileLinks,
)
import time, traceback, uuid, orjson, jdatetime, re
from datetime import datetime, timezone
from elasticsearch.helpers import scan
from typing import Union
from pathlib import Path
from collections import defaultdict
from typing import List
from dotenv import load_dotenv
# --------------------------- global-params
input_es_index_name = ""
new_index_name = "mn_meet"
old_index_name = "mn_sanad"
NORMALIZER = InitTextNormalizer(
options={
"alphabetsNormal": True,
"emptylinesNormal": True,
"hamzehNormal": True,
"removeInvalidChar": True,
}
)
UNVALID_DATA = {}
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",
}
UNVALID_CONTENT_IDS = [
"749684487110e6f6",
"333684e85d0cbd52",
"941684e86749c382",
"896683eb6527aab1",
"8986846ce56b9561",
"9046848108a8bc5c",
]
ALL_TITLE = set()
BRANCH_TO_ID = defaultdict(list)
BEGIN_DATAS = {}
END_DATAS = {}
BRANCH_TO_AUTHERS = {}
BRANCH_TO_TERM_ID = {}
ORIGIN_OF_TIME = datetime(1970, 1, 1, tzinfo=timezone.utc)
URL_REGEX = re.compile(
r"""
(?i) # case-insensitive
(?:
# گزینه ۱: لینک با پروتکل (http/https/ftp)
https?://
(?:[a-z0-9\-]+\.)+[a-z]{2,}
(?:/[^\s<>"{}|\\^`[\]]*)?
|
# گزینه ۲: دامنه‌های معروف بدون پروتکل (فقط اگر دامنه‌ای معتبر داشته باشند)
# نکته: فقط زمانی معتبر است که دامنه یک TLD رایج داشته باشد
(?<![\w@]) # اطمینان از اینکه قبل از آن کاراکتر کلمه یا @ نباشد (مثلاً جلوی user@example.com را نگیرد)
(?:[a-z0-9\-]+\.)+
(?:com|org|net|edu|gov|mil|io|co|ir|tv|xyz|me|info|biz|online|site|tech)
(?:/[^\s<>"{}|\\^`[\]]*)?
)
""",
re.VERBOSE,
)
# --------------------------- function
VALID_CHAR = set(NORMALIZER.valid_charset)
FINALL_STAT_SANADS = []
def result_content_validation(text: str, valid_chars: set = VALID_CHAR):
is_html = False
is_unvalid_char = False
for ch in text:
# فقط یک بار روی داده loop می‌زنیم
if ch == "<" or ch == ">":
is_html = True
if ch not in valid_chars:
is_unvalid_char = True
# اگر هر دو تشخیص داده شدند ادامه لازم نیست
if is_html and is_unvalid_char:
break
return is_html, is_unvalid_char
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
def datetime_to_int(dt):
try:
if dt is None:
return None
if isinstance(dt, str) and dt in UNVALID_DATA:
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 get_mn_sanad(data: dict) -> MnSanad2Meet:
return MnSanad2Meet.model_validate(data)
def get_term_info(term_data: MnTerm) -> Properties:
data = Properties(
author=term_data.author,
id=term_data.id,
sub_type=term_data.sub_type,
title=term_data.title,
)
return data
def get_mn_meet_info(meet_data: MnMeet) -> Properties:
data = Properties(
author=meet_data.author,
id=meet_data.id,
sub_type=meet_data.sub_type,
title=meet_data.title,
)
return data
def get_report_info(data: MnSanad2Meet) -> ReportInfo:
data = ReportInfo(photos=data.photos, sounds=data.sounds, films=data.films)
return data
def normalize_field(data: MnSanad2Meet) -> MnSanad2Meet:
form_ = {}
# data_old = data.model_copy()
if data.begin_date in UNVALID_TIME:
data.begin_date = None
else:
data.begin_date = datetime_to_int(data.begin_date)
if data.end_date in UNVALID_TIME:
data.end_date = None
else:
data.end_date = datetime_to_int(data.end_date)
is_html, is_unvalid_char = result_content_validation(data.content)
data.content = NORMALIZER.normalize_text_monir(data.content)
if data.branch == "--":
data.branch = None
if data.begin_date is None:
data.begin_year = None
else:
data.begin_year = timestamp_to_shamsi(data.begin_date)
form_["id"] = data.id
form_["is_html"] = is_html
form_["is_unvalid_char"] = is_unvalid_char
FINALL_STAT_SANADS.append(form_)
return data
def get_mn_meet_entity(
sanad_data: MnSanad2Meet,
meet_info: Properties,
term_info: Properties,
dict_return=True,
) -> List[MnMeetEntity]:
# content
meet_entity_data: List[MnMeetEntity] = []
# نگاشت نوع‌ها به مقادیر
link_types = {
"file": sanad_data.file_links,
"sound": sanad_data.sound_links,
"video": sanad_data.video_links,
"photo": sanad_data.photo_links,
}
for main_type, links in link_types.items():
if not links:
continue # اگر None یا خالی بود رد کن
for link in links:
# اگر کلاس‌ها مختلفند، ممکن است نیاز به تبدیل داشته باشی
file_obj = FileLinks(
title=getattr(link, "title", ""),
link=getattr(link, "link", ""),
type=main_type,
description=getattr(link, "description", ""),
)
meet_entity = MnMeetEntity(
id=get_unique_id(prfix="mn_ment_"), # تابع تولید ID
main_type=main_type,
sub_type=getattr(link, "sub_type", ""), # اگر وجود دارد
title=getattr(link, "title", ""),
content=getattr(sanad_data, "content", ""),
permit_tags="",
search_state="",
user_create="",
time_create=int(time.time()),
time_edit=int(time.time()),
file_links=file_obj,
meet_info=meet_info, # بسته به نیاز
term_info=term_info, # بسته به نیاز
)
if dict_return:
meet_entity_data.append(meet_entity.model_dump())
else:
meet_entity_data.append(meet_entity)
return meet_entity_data
def get_mn_meet(
sanad_data: MnSanad2Meet,
term_info: Properties,
subjects: Subjects,
report_info: ReportInfo,
) -> MnMeet:
new_data = MnMeet(
id=get_unique_id(prfix="mn_meet_"),
sanad_id=sanad_data.id,
main_type=sanad_data.format,
author=sanad_data.author,
title=sanad_data.title,
research_code=sanad_data.research_code,
meet_code=sanad_data.meet_code,
old_meet_id=sanad_data.meet_id,
meet_no=sanad_data.meet_no,
term_info=term_info,
report_info=report_info,
subjects=subjects,
subtitle=sanad_data.subtitle,
allwords=sanad_data.allwords,
tags=sanad_data.tags,
keywords=sanad_data.keywords,
verb=sanad_data.verb,
sanad_year=sanad_data.begin_year,
sanad_date=sanad_data.begin_date,
amplify=sanad_data.amplify,
ralation=sanad_data.ralation,
city=sanad_data.city,
place=sanad_data.place,
address=sanad_data.address,
audience=sanad_data.audience,
attendees=sanad_data.attendees,
content=sanad_data.content,
sort_date_timestamp=sanad_data.sort_date_timestamp,
permit_tags=sanad_data.permit_tags,
resource_info=sanad_data.resource_info,
)
return new_data
def get_term_data(sanad_data: MnSanad2Meet) -> MnTerm:
title = sanad_data.branch
# ===============================
# 1) Case: branch is None → NO MERGE
# ===============================
if title is None or title == "" or title == "--":
return None
# ===============================
# 2) Case: normal branch → use grouping logic
# ===============================
# first time seeing this title
elif title not in BRANCH_TO_TERM_ID:
# create ID and store
term_id = get_unique_id(prfix="mn_tr_")
BRANCH_TO_TERM_ID[title] = term_id
# init structures
ALL_TITLE.add(title)
BRANCH_TO_ID[title].append(sanad_data.id)
BRANCH_TO_AUTHERS[title] = sanad_data.author
BEGIN_DATAS[title] = sanad_data.begin_date
END_DATAS[title] = sanad_data.end_date
return MnTerm(
id=term_id,
old_sanad_id=[sanad_data.id],
author=sanad_data.author,
title=title,
begin_date=sanad_data.begin_date,
begin_year=sanad_data.begin_year,
end_date=sanad_data.end_date,
)
# ---------------------------------------
# Already seen this branch → reuse ID
# ---------------------------------------
term_id = BRANCH_TO_TERM_ID[title]
BRANCH_TO_ID[title].append(sanad_data.id)
BRANCH_TO_AUTHERS[title] = sanad_data.author
BEGIN_DATAS[title] = safe_min(BEGIN_DATAS[title], sanad_data.begin_date)
END_DATAS[title] = safe_max(END_DATAS[title], sanad_data.end_date)
return MnTerm(
id=term_id, # reuse the SAME ID!
old_sanad_id=[sanad_data.id],
author=sanad_data.author,
title=title,
begin_date=BEGIN_DATAS[title],
begin_year=sanad_data.begin_year,
end_date=END_DATAS[title],
)
def get_subjects(sanad: MnSanad2Meet) -> List[Subjects]:
raw = sanad.subject
# هیچ مقدار یا مقدار خالی
if not raw:
return []
# اگر لیست بود → تک تک تبدیل کنیم
if isinstance(raw, list):
return [Subjects(**item) for item in raw]
# اگر اشتباهاً فقط یک dict بود
if isinstance(raw, dict):
return [Subjects(**raw)]
# اگر هیچ‌کدام نبود → خطا
raise ValueError(f"Invalid subjects format: {raw}")
def convert_mn(
old_data: list, es_helper, term_index_name, meet_index_name, ment_index_name
):
start = time.time()
try:
#### -------- prepare data
phase_1 = []
total = len(old_data)
start_t = start
for i, sanad_dict in enumerate(old_data, start=1):
try:
if sanad_dict["id"] in UNVALID_CONTENT_IDS:
continue
sanad_data = get_mn_sanad(sanad_dict)
normal_sanad_data = normalize_field(sanad_data)
# save_orjson(
# path=r"D:\init_mahdi\project\dataParsers\app\monir\unvalid-data\test_normalize.json",
# data=normal_sanad_data.model_dump(),
# )
# build-term
term_data = get_term_data(normal_sanad_data)
# build-term-info
term_info = get_term_info(term_data)
# build-report-info
report_info = get_report_info(normal_sanad_data)
# build-subjects
subjects = get_subjects(normal_sanad_data)
# build-meet
meet_data = get_mn_meet(
normal_sanad_data, term_info, subjects, report_info
)
# build-meet-info
meet_info = get_mn_meet_info(meet_data)
# build-meet_entity
meet_entity_lists = get_mn_meet_entity(
normal_sanad_data, meet_info, term_info
)
# save-term
# save_orjson(data=term_data.model_dump(), path="./term_1.json")
term_data = term_data.model_dump()
es_helper.update_index_doc(
is_update_state=False,
index_name_o=term_index_name,
eid=term_data.get("id"),
data=term_data,
)
# save-meet
# save_orjson(data=meet_data.model_dump(), path="./meet_1.json")
meet_data = meet_data.model_dump()
es_helper.update_index_doc(
is_update_state=False,
index_name_o=meet_index_name,
eid=meet_data.get("id"),
data=meet_data,
)
# save-meet_entity
# save_orjson(data=meet_entity_lists, path="./meet_entity_1.json")
for ment in meet_entity_lists:
es_helper.update_index_doc(
is_update_state=False,
index_name_o=ment_index_name,
eid=ment.get("id"),
data=ment,
)
# print("##########################################")
if i % 1000 == 0:
end_t = time.time()
delta = end_t - start_t
print(
f"--- {i}/{total} ({delta:.2f}'s) total-time = ({end_t-start:.2f}'s)---"
)
start_t = time.time()
except Exception as e:
print(f"Problem -> {sanad_dict}") # ['id']
traceback.print_exc()
break
save_orjson(data=phase_1, path="./meet_test_1_data.json")
print(
"✅ Data-Created",
" - saved-> mn_meet",
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
host = os.getenv("HOST_60")
password = os.getenv("HOST_60_PASS")
term_index_name = "mn_term"
meet_index_name = "mn_meet"
ment_index_name = "mn_meet_entity"
dash = "-" * 25
es_helper = ElasticHelper(
es_url=host,
es_user="elastic",
es_pass=password,
# path_mappings = ""
)
############ DELETE INDEXES
# es_helper.deleteIndex(index_name=term_index_name)
# es_helper.deleteIndex(index_name=meet_index_name)
# es_helper.deleteIndex(index_name=ment_index_name)
############ CREATE INDEXES
es_helper.createIndexIfNotExist(index_name_o=term_index_name)
es_helper.createIndexIfNotExist(index_name_o=meet_index_name)
es_helper.createIndexIfNotExist(index_name_o=ment_index_name)
print(dash, " es_helper-loaded ", dash)
### fields = list(MnSanad2Meet.model_fields.keys())
fields = [
"id",
"sort_date_timestamp",
"title",
"subtitle",
"research_code",
"format",
"content",
"meet_lid",
"meet_id",
"meet_no",
"meet_code",
"allwords",
"keywords",
"person_code",
"subject",
"city",
"author",
"begin_year",
"begin_date",
"end_date",
"branch",
"ralation",
"research_id",
"mintro",
"mindex",
"resource_info",
"verb",
"address",
"attendees",
"amplify",
"audience",
"place",
"permit_tags",
"photos",
"tags",
"films",
"sounds",
"sound_links",
"video_links",
"photo_links",
]
# fields = ["id", "content"]
print(f"fields {fields}")
# fields ['id', 'sort_date_timestamp', 'title', 'subtitle', 'research_code', 'content', 'version_info', 'meet_lid', 'meet_id', 'meet_no', 'meet_code', 'allwords', 'keywords', 'person_code', 'subject', 'city', 'author', 'begin_year', 'begin_date', 'end_date', 'branch', 'ralation', 'research_id', 'mintro', 'mindex', 'RowNum', 'resource_info', 'in_tadvin', 'format', 'verb', 'address', 'attendees', 'amplify', 'audience', 'place', 'permit_tags', 'photos', 'tags', 'films', 'sounds', 'file_links', 'sound_links', 'video_links', 'photo_links']
es = es_helper.es
# old_data = es_helper.search(
# index=old_index_name, _source=fields, query={"match_all": {}}, size=3
# )
# old_data = old_data["hits"]["hits"] # don't use in scan
################### for all data
old_data = list(
scan(
es,
index=old_index_name,
query={
"_source": fields,
"query":
# {"ids": {"values": ["pm146821"]}},
{"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, index in enumerate(old_data):
valid_i = index["_source"]
id = index["_id"]
valid_i["id"] = id
# if id not in UNVALID_CONTENT_IDS:
# valid_list.append(valid_i)
valid_list.append(valid_i)
print(f"total-data = {len(valid_list)} ")
convert_mn(
old_data=valid_list,
es_helper=es_helper,
term_index_name=term_index_name,
meet_index_name=meet_index_name,
ment_index_name=ment_index_name,
)
save_orjson(
path=r"D:\init_mahdi\project\dataParsers\idataparser\task\monir\informations\finall_result_sanads.json",
data=FINALL_STAT_SANADS,
)
# # --------------------------- RUN
# ------ command
# --liunx
# python3 -m app.monir.sanad_2_meet.py
# --windows
# python -m app.monir.sanad_2_meet