This commit is contained in:
hsafaei
2025-12-06 12:03:01 +03:30
parent 1c6d446110
commit 9bb61a60b2
22 changed files with 3384 additions and 4008 deletions
+4
View File
@@ -0,0 +1,4 @@
ES_URL = 'http://192.168.23.60:6900'
ES_USER_NAME = 'elastic'
ES_PASSWORD = '1234'
LLM_URL = 'http://2.188.15.102:8001/v1/'
View File
+304 -129
View File
@@ -1,32 +1,196 @@
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from typing import Optional, List, Dict from typing import Optional, List, Dict, Union, Any
from datetime import datetime
# فیلد اجباری: # فیلد اجباری:
# str = Field(..., description="") # str = Field(..., description=)
# فیلد اختیاری: # فیلد اختیاری:
# Optional[str] = Field(None, description="") # Optional[str] = Field("", description=)
class Properties(BaseModel): class Properties(BaseModel):
""" """
Standard Form Of Foreign Key To Other Index Standard Form Of Foreign Key To Other Index
""" """
id: str = Field(..., description="شناسه یکتا") id: str = Field(..., description="شناسه یکتا")
title: str = Field(..., description="عنوان") title: Optional[str] = Field("", description="عنوان")
author: str = Field(..., description="سازنده") author: Optional[str] = Field("", description="سازنده")
sub_type: str = Field(..., description="نوع دوم") sub_type: Optional[str] = Field("", description="نوع دوم")
class TreeInfo(BaseModel): class TreeInfo(BaseModel):
title: str title: str
parent_id: str = Field(..., description="") parent_id: str = Field(..., description="")
child_order: int
level: int
full_path: Optional[str] = Field("", description="")
path_headings: str
class NlpParses(BaseModel):
main_type: str
nlp_type: str
begin: int
end: int
text: str
referes: str
dependency_infos: str # nested
class Embeddings(BaseModel):
type: Optional[str] = (Field("", description=""),)
dims: Optional[int] = (Field(1024, description=""),)
index: Optional[bool] = (Field(True, description=""),)
similarity: Optional[str] = Field("", description="")
class FileLinks(BaseModel):
title: str
link: str
type: str
description: str
class UserLogs(BaseModel):
id: str
user_id: int
username: str
time_edit: int
property: str
class MnSection(BaseModel):
id: str
old_id: str
main_type: str
html: str
content: str
meet_info: Properties
term_info: Properties
tree_info: TreeInfo
content_len: int
word_len: int
tags: str
keywords: str
sort_date_timestamp: int
nlp_parses: NlpParses
embeddings: Embeddings
file_links: FileLinks
time_edit: int
user_edit: int
user_logs: UserLogs
class MnTerm(BaseModel):
id: str
author: str
sub_type: Optional[str] = ""
title: Optional[str] = ""
begin_date: Optional[int] = ""
end_date: Optional[int] = ""
begin_year: Optional[int] = ""
main_type: Optional[str] = ""
content: Optional[str] = ""
tags: Optional[str] = ""
keywords: Optional[str] = ""
class MnMeetEntity(BaseModel):
id: str
main_type: str
sub_type: str
title: str
content: str
permit_tags: str
search_state: str
user_create: str
time_create: int
time_edit: int
file_links: FileLinks
meet_info: Properties
term_info: Properties
class Subjects(BaseModel):
id: int
title: str
class ReportInfo(BaseModel):
films: int
sounds: int
photos: int
class MnMeet(BaseModel):
"""
Monir Meet Standard fields foramt
"""
id: str
sanad_id: str
main_type: str
sub_type: Optional[str] = ""
person_code: Optional[str] = ""
research_code: str
meet_code: str
old_meet_id: int
title: str
meet_no: int
author: str
term_info: Optional[Properties] = Field("", description="کلید اتصال به جدول ترم")
subtitle: str
subjects: Optional[List[Subjects]] = []
allwords: str
tags: Optional[List[str]] = []
keywords: str
verb: str
sanad_year: Optional[int] = ""
sanad_date: Optional[int] = ""
amplify: str
ralation: str
city: str
place: str
address: str
audience: str
attendees: str
report_info: ReportInfo
mindex: Optional[str] = Field("", description="mindex index فهرست")
mintro: Optional[str] = Field("", description="mintro خلاصه ")
content: str
completion: Optional[str] = Field("", description="type: completion")
sort_date_timestamp: int
permit_tags: str
resource_info: str
class MnSanadLink(BaseModel):
text: Optional[str] = ""
link: str
in_search: bool
title: str
class Properties(BaseModel):
"""
Standard Form Of Foreign Key To Other Index
"""
id: str = Field(..., description="شناسه یکتا")
title: Optional[str] = Field("", description="عنوان")
author: Optional[str] = Field("", description="سازنده")
sub_type: Optional[str] = Field("", description="نوع دوم")
class TreeProperties(BaseModel):
parent_id :str
child_order: int child_order: int
level: int level: int
full_path: Optional[str] = Field(None, description="") full_path: str
title: str
path_headings: str path_headings: str
class NlpParses(BaseModel): class NlpParses(BaseModel):
main_type: str main_type: str
nlp_type: str nlp_type: str
@@ -34,131 +198,142 @@ class NlpParses(BaseModel):
end: int end: int
text: str text: str
referes: str referes: str
dependency_infos:str # nested dependency_infos: Dict
class Embeddings(BaseModel):
type: Optional[str] = Field(None, description=""),
dims: Optional[int] = Field(1024, description=""),
index: Optional[bool] = Field(True, description=""),
similarity: Optional[str] = Field(None, description="")
class FileLinks(BaseModel):
title: str
link: str
type: str
description: str
class UserLogs(BaseModel): class UserLogs(BaseModel):
id: str id:str
user_id: int user_id:int
username: str username:str
time_edit: datetime time_edit:int
property: str property:str
class MNSection(BaseModel):
class MnSection(BaseModel): main_type : str
id: str id : str
main_type: str html : str
html: str content : str
content: str meet_info: Properties
meet_info: Properties term_info: Properties
term_info: Properties tree_info: TreeProperties
tree_info: TreeInfo content_len: int
content_len: int word_len: int
word_len: int
tags: str
keywords: str
sort_date_timestamp: int
nlp_parses: NlpParses
embeddings: Embeddings
file_links: FileLinks
time_edit: datetime
user_edit: int
user_logs: UserLogs
class MnTerm(BaseModel):
id: str
main_type: str
sub_type: str
title: str
content: str
author: str
begin_date: datetime
end_date: datetime
begin_year: int
tags: str tags: str
keywords: str keywords: str
sort_date_timestamp: int
nlp_parses: NlpParses
embeddings: Embeddings
file_links:FileLinks
time_edit: int
user_edit: int
user_logs: UserLogs
class MnMeetEntity(BaseModel): class MnSanadVersionInfo(BaseModel):
id: str timestamp: int
main_type: str number: int
sub_type: str title: str
title: str
content: str
permit_tags: str
search_state: str
user_create: str
time_create: datetime
time_edit: datetime
file_links: FileLinks
meet_info: Properties
term_info: Properties
class Subjects(BaseModel):
id: int
title: str
class ReportInfo(BaseModel): class SoundLinks(BaseModel):
film_count: int link: str
sound_count: int title: str
photo_count: int
file_count: int
is_address: int
is_mindex: int
is_mintro: int
is_sanad_data1: int
is_sanad_data2: int
class MnMeet(BaseModel):
""" class MnSanad(BaseModel):
Monir Meet Standard fields foramt id: Optional[str] = ""
""" sort_date_timestamp: Optional[int] = ""
id: str title: Optional[str] = ""
main_type: str subtitle: Optional[str] = ""
sub_type: str research_code: Optional[int] = ""
person_code: str content: Optional[str] = ""
research_code: str version_info: Optional[MnSanadVersionInfo] = ""
meet_code: str meet_lid: Optional[int] = ""
old_meet_id: int meet_id: Optional[int] = ""
title: str meet_no: Optional[int] = ""
meet_no: int meet_code: Optional[int] = ""
author: str allwords: Optional[str] = ""
term_info: Properties keywords: Optional[str] = ""
subtitle: str person_code: Optional[str] = ""
subjects: Subjects subject: Optional[List] = ""
allwords: str city: Optional[str] = ""
tags: str author: str
keywords: str begin_year: Optional[int] = ""
verb: str begin_date: Optional[int] = ""
sanad_year: int end_date: Optional[int] = ""
sanad_date: datetime branch: Optional[str] = ""
amplify: str ralation: Optional[str] = ""
ralation: str research_id: Optional[int] = ""
city: str mintro: Optional[str] = ""
place: str mindex: Optional[str] = ""
address: str RowNum: Optional[int] = ""
audience: str resource_info: Optional[str] = ""
attendees: str in_tadvin: Optional[bool] = ""
report_info: ReportInfo format: Optional[str] = ""
mindex: str verb: Optional[str] = ""
mintro: str address: Optional[str] = ""
content: str attendees: Optional[str] = ""
completion: Optional[str] = Field(None, description="type: completion") amplify: Optional[str] = ""
sort_date_timestamp: int audience: Optional[str] = ""
permit_tags: str place: Optional[str] = ""
resource_info: str permit_tags: Optional[str] = ""
photos: Optional[int] = ""
tags: Optional[List[str]] = ""
films: Optional[int] = ""
sounds: Optional[int] = ""
file_links: Optional[List[MnSanadLink]] = ""
sound_links: Optional[List[SoundLinks]] = ""
video_links: Optional[List[SoundLinks]] = ""
photo_links: Optional[List[SoundLinks]] = ""
model_config = {"exclude_" "": True}
class MnSanad2Meet(BaseModel):
id: str
sort_date_timestamp: Optional[int] = ""
title: str
subtitle: str
research_code: str
format: str
content: str
# version_info: Optional[List|dict] = ""
meet_lid: Optional[str] = ""
meet_id: Optional[int] = ""
meet_no: Optional[int] = ""
meet_code: Optional[str] = ""
allwords: Optional[str] = ""
keywords: Optional[str] = ""
person_code: Optional[str] = ""
subject: Optional[List] = []
city: Optional[str] = ""
author: str
begin_year: Optional[int] = ""
begin_date: Optional[str] = ""
end_date: Optional[str] = ""
branch: str
ralation: Optional[str] = ""
research_id: int
mintro: Optional[str] = ""
mindex: Optional[str] = ""
# RowNum: Optional[int]= ""
resource_info: Optional[str] = ""
# in_tadvin: Optional[bool] = ""
verb: Optional[str] = ""
address: Optional[str] = ""
attendees: Optional[str] = ""
amplify: Optional[str] = ""
audience: Optional[str] = ""
place: Optional[str] = ""
permit_tags: Optional[str] = ""
photos: Optional[int] = 0
tags: Optional[List[str]] = []
films: Optional[int] = 0
sounds: Optional[int] = 0
file_links: Optional[List[MnSanadLink]] = ""
sound_links: Optional[List[SoundLinks]] = ""
video_links: Optional[List[SoundLinks]] = ""
photo_links: Optional[List[SoundLinks]] = ""
# model_config = {
# "exclude_""": True
# }
+349
View File
@@ -0,0 +1,349 @@
type_count = [
{
"key": "جلسه علمی",
"doc_count": 7332
},
{
"key": "منبر",
"doc_count": 3970
},
{
"key": "درس خارج",
"doc_count": 2450
},
{
"key": "تدریس",
"doc_count": 1401
},
{
"key": "سخنرانی",
"doc_count": 1221
},
{
"key": "-",
"doc_count": 992
},
{
"key": "مشاوره",
"doc_count": 858
},
{
"key": "مدیریت",
"doc_count": 652
},
{
"key": "مصاحبه",
"doc_count": 628
},
{
"key": "مباحثه و گفتگو",
"doc_count": 587
},
{
"key": "جزوه",
"doc_count": 583
},
{
"key": "مناظره و گفتگو",
"doc_count": 496
},
{
"key": "گزارش",
"doc_count": 395
},
{
"key": "--",
"doc_count": 250
},
{
"key": "جدول",
"doc_count": 208
},
{
"key": "کتاب",
"doc_count": 173
},
{
"key": "صورت جلسه",
"doc_count": 126
},
{
"key": "فهرست",
"doc_count": 124
},
{
"key": "ارائه",
"doc_count": 90
},
{
"key": "بازدید (دیدار)",
"doc_count": 83
},
{
"key": "مقاله",
"doc_count": 81
},
{
"key": "طرح",
"doc_count": 74
},
{
"key": "کلیپ",
"doc_count": 68
},
{
"key": "گزارش رصد",
"doc_count": 64
},
{
"key": "نامه",
"doc_count": 48
},
{
"key": "نمودار",
"doc_count": 45
},
{
"key": "آیین نامه",
"doc_count": 36
},
{
"key": "تقریر",
"doc_count": 35
},
{
"key": "خلاصه",
"doc_count": 25
},
{
"key": "پیش نویس",
"doc_count": 25
},
{
"key": "نقد",
"doc_count": 23
},
{
"key": "چکیده",
"doc_count": 16
},
{
"key": "یادبود",
"doc_count": 13
},
{
"key": "فرم",
"doc_count": 12
},
{
"key": "فرم فیش",
"doc_count": 11
},
{
"key": "مناجات",
"doc_count": 10
},
{
"key": "دعا و مناجات",
"doc_count": 8
},
{
"key": "فیش",
"doc_count": 6
},
{
"key": "پرسش و پاسخ",
"doc_count": 6
},
{
"key": "بیانیه",
"doc_count": 5
},
{
"key": "اجلاسیه",
"doc_count": 4
},
{
"key": "پایان نامه",
"doc_count": 4
},
{
"key": "",
"doc_count": 3
},
{
"key": "آئین نامه",
"doc_count": 3
},
{
"key": "رزومه",
"doc_count": 3
},
{
"key": "قرارداد",
"doc_count": 3
},
{
"key": "مصوبه",
"doc_count": 3
},
{
"key": "نمونه سوال",
"doc_count": 3
},
{
"key": "همایش",
"doc_count": 3
},
{
"key": "پژوهش",
"doc_count": 3
},
{
"key": "چارت",
"doc_count": 3
},
{
"key": "کنفرانس",
"doc_count": 3
},
{
"key": "تلخیص",
"doc_count": 2
},
{
"key": "قرائت زیارت",
"doc_count": 2
},
{
"key": "لیست",
"doc_count": 2
},{
"key": "متن جلسه",
"doc_count": 2
},
{
"key": "مستند تلوزیونی",
"doc_count": 2
},
{
"key": "نشست علمی",
"doc_count": 2
},
{
"key": "کتاب داخلی",
"doc_count": 2
},
{
"key": "گزارش جلسه",
"doc_count": 2
},
{
"key": "برنامه",
"doc_count": 1
},
{
"key": "بروشور",
"doc_count": 1
},
{
"key": "بزرگداشت",
"doc_count": 1
},
{
"key": "جزو",
"doc_count": 1
},
{
"key": "خطبه عقد(دائم)",
"doc_count": 1
},
{
"key": "روضه",
"doc_count": 1
},
{
"key": "زندگی نامه",
"doc_count": 1
},
{
"key": "زیارتنامه",
"doc_count": 1
},
{
"key": "سائر",
"doc_count": 1
},
{
"key": "سالگرد",
"doc_count": 1
},
{
"key": "سایر",
"doc_count": 1
},
{
"key": "طرج",
"doc_count": 1
},
{
"key": "عقد",
"doc_count": 1
},
{
"key": "ماتریس",
"doc_count": 1
},
{
"key": "مدل",
"doc_count": 1
},
{
"key": "مراحل دستیابی و به کارگیری الگوی پیشرفت اسلامی ـ ",
"doc_count": 1
},
{
"key": "مقالات",
"doc_count": 1
},
{
"key": "مقاله و ارائه",
"doc_count": 1
},
{
"key": "نماه",
"doc_count": 1
},
{
"key": "نمایه",
"doc_count": 1
},
{
"key": "هرم",
"doc_count": 1
},
{
"key": "پرسشنامه",
"doc_count": 1
},
{
"key": "پروژه",
"doc_count": 1
},
{
"key": "پیش نشست",
"doc_count": 1
},
{
"key": "کاربرگ",
"doc_count": 1
},
{
"key": "کتاب سایت",
"doc_count": 1
},
{
"key": "کمیسیون خبرگان",
"doc_count": 1
}
]
+128
View File
@@ -0,0 +1,128 @@
from pathlib import Path
import orjson
PER = set("ضصثقفغعهخحجچپشسیبلاتنمکگظطزرذدئو.1234567890()!؟آۀًٌٍَُِّريالةيژؤإأء")
PER.update(
[
"\t",
"\n",
"\f",
"\r",
" ",
"!",
"(",
")",
"-",
".",
"/",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
":",
"[",
"]",
"«",
"»",
]
)
Unvalid = set([
"\u0000","\u0001","\u0002","\u0007","\u001e","\u001f",
"„",""," ","¢","£","¤","¨","«","¬","­","°","´","·","»",
"¼","½","¾","Ã","É","Í","Ï","Û","à","á","ã","ä","ç","è",
"é","ê","í","ï","ñ","ó","õ","ö","ø","ú","ü","þ","ÿ",
"ā","Ă","Ĉ","Ĥ","Ŋ","ˆ","ˇ","˜","΄","μ","π","Щ","؀",
"ऀ","ऌ","ऎ","ऐ","द","ऴ","ू","ॄ","ॆ","ग़","ड़",
"চ","জ","৤","০","৪","৮","ਢ","ਤ","ੋ","੒","ੜ","ઈ","଀",
"଎","஘","௚","ా","౔","ೂ","ඊ","ฃ","ด","ฮ","โ","ไ","๒",
"ༀ","ᆖ","ᆘ","ᆦ","ᐨ","ᑪ","ᒂ","ᒶ","ᔟ","ᔢ","ᔧ","ᔪ","ᘀ",
"ᘂ","ᨾ","ᰀ","᱊","Ḩ","ḭ","Ḿ","Ṏ","Ἂ","Ῥ",
" ","‌","‍","‎","‏","‐","⍤","␂","␃","⒢","◮","⚚","⚜","⛾",
"⡯","⤦","⤨","ⱆ","ⱶ","ま","㈬","㈮","㈺","㈼","㛸","㝶",
"㩴","㪐","㵹","㸐","㸒","䂨","䌀","䐀","䑶","䑸","䗜",
"䠨","䡟","䢪","䩞","䩡","䭨","䭪","䳸","䴮","䴰",
"伀","偦","偨","儀","凄","刐","刚","唃","唎","唢","唤",
"喈","喡","娀","宜","屨","恨","惄","愀","愔","掋","摧",
"撆","桨","汊","汌","淄","皆","稀","笺","筠","筨","箜",
"篃","絘","脈","茊","茌","菈","蕞","蚞","譨","軺","輒",
"輔","辜","酠","鉦","鉼","鉾","銨","镖","闎","餸","馼",
"髄","魰","鶊","ꅨ","ꉣ","ꍀ","ꡨ","꡻","ꢆ","ꢘ","꣜","넣",
"뫜","뺨","뻪","쌀","쫮","쵕","케","퓪","","","","",
"","","","","","","","","","","","","",
"","","","","","","","","","","","","",
"","","","","","","","","","","","","",
"","","","","","","","","﴾","﴿","ﺓ","ﺔ","ﻫ",
"ﻻ","�"
]
)
UNVALID_CHAR_LIST = [
'pm147111', 'pm154520'
]
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())
_path = (
r"D:\init_mahdi\project\dataParsers\app\monir\informations\unique_char_sanad.json"
)
data = load_orjson(_path)
all_char_set = load_orjson(
r"D:\init_mahdi\project\dataParsers\app\monir\informations\all_char_set.json"
)
all_char_set = set(all_char_set)
empty_content = []
unvalid_content = []
all_char_set_now = set()
for i in data:
if i['id'] in UNVALID_CHAR_LIST:
continue
# if len(i["char"]) == 0:
# empty_content.append(i["id"])
else:
set_i = set(i["char"])
all_char_set_now.update(set_i)
if set_i & Unvalid: # اگر تقاطع غیرخالی بود
unvalid_content.append(i)
# delta = set_i - PER
# if delta:
# unvalid_content.append(i)
all_char_set_now = sorted(all_char_set_now, key=lambda ch: ord(ch))
save_orjson(
data=all_char_set_now,
path=r"D:\init_mahdi\project\dataParsers\app\monir\informations\all_invalid_char_set_now.json",
)
save_orjson(
data=unvalid_content,
path=r"D:\init_mahdi\project\dataParsers\app\monir\informations\unvalid_content_ids.json",
)
# save_orjson(
# data=list(empty_content),
# path=r"D:\init_mahdi\project\dataParsers\app\monir\informations\empty_content_ids.json",
# )
# python -m app.monir.informations.main
+413
View File
@@ -0,0 +1,413 @@
from dotenv import load_dotenv
import os
from .base_model import MnMeet
import time, traceback, uuid, orjson, re, asyncio
from collections import OrderedDict
from idataparser import (
count_tokens,
save_orjson,
load_orjson,
ElasticHelper,
html_to_clean_text,
json_to_excel,AsyncCore
)
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 pydantic import BaseModel
load_dotenv()
ES_URL = os.getenv("ES_URL")
ES_USER_NAME = os.getenv("ES_USER_NAME")
ES_PASSWORD = os.getenv("ES_PASSWORD")
LLM_URL = os.getenv("LLM_URL")
# --------------------------- flow
# term_index_name = "mn_term"
# meet_index_name = "mn_meet"
# ment_index_name = "mn_meet_entity"
# sections_index_name = ""
# dash = "-" * 25
# es_helper = ElasticHelper(
# es_url=ES_URL,
# es_user=ES_USER_NAME,
# es_pass=ES_PASSWORD,
# )
# ########### 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)
# es = es_helper.es
# # fields = list(MnMeet.model_fields.keys())
# fields = [
# "id",
# "sanad_id",
# "main_type",
# "title",
# "author",
# "content",
# "sanad_id"
# ]
# # 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=meet_index_name,
# query={
# "_source": fields,
# "query":
# { "term":
# {
# "main_type.keyword": "مناظره و گفتگو" # "جلسه علمی"
# }},
# # {"match_all": {}},
# },
# )
# )
# save_orjson(
# data=old_data,
# path=r'D:\init_mahdi\project\dataParsers\idataparser\task\monir\data_content_2.json'
# )
#######################################################################################################
# data = load_orjson(r'D:\init_mahdi\project\dataParsers\idataparser\task\monir\data_content_2.json')
# f_data = {}
# for i in data :
# id = i['_source']['sanad_id']
# content = i['_source']['content']
# if 90000 > len(content) > 10000:
# f_data[id] = content
# break
# save_orjson(
# data=f_data,
# path=r'D:\init_mahdi\project\dataParsers\temps\mn\t2.json'
# )
#######################################################################################################
# html_data = load_orjson(
# r"D:\init_mahdi\project\dataParsers\idataparser\task\monir\informations\finall_result_sanads.json"
# )
# html_data = {item["id"]: item for item in html_data}
# # print(f' html_data {html_data}')
# t1_data = load_orjson(
# r"D:\init_mahdi\project\dataParsers\idataparser\task\monir\data_content_1.json"
# )
# print(f"--- t1_data {len(t1_data)}")
# t1_data = sorted(t1_data, key=lambda x: len(x["_source"]["content"]), reverse=True)
# final_data = {}
# for item in t1_data:
# sanad_id = item["_source"]["sanad_id"]
# # print(f'sanad_id {sanad_id}')
# h_data = html_data[sanad_id]
# # print(f'h_data {h_data}')
# if html_data[sanad_id]["is_html"] is False and item["_source"]["content"] != "":
# final_data[item["_id"]] = item["_source"]["content"]
# print(f"--- final_data {len(final_data)}")
# for k, v in final_data.items():
# # v = html_to_clean_text(v)
# c = count_tokens(model_name="gpt-oss-120b", system_prompt="", user_prompt=v)
# print(f"most == {c}")
# print(f"k == {k}")
# save_orjson(data=v, path="./temps/mn/test1.json")
# break
#####################################################
class ScientificMeeting(BaseModel):
"""جلسه علمی"""
class Output(BaseModel):
heading: str
level: int
content: str
start_idx: int
end_idx: int
output: List[Output]
from pydantic import BaseModel
from typing import List, Optional, Dict
# class IDDocument(BaseModel):
# title : str # عنوان پژوهش
# code : int
# meet_number : int
# meet_code : int
# meet_date : str
# meet_duration : str
# meet_total: int
class IdDocument(BaseModel):
id_document : str
class IdTadvin(BaseModel):
id_tadvin : str
class Paragraph(BaseModel):
paragraph : str
class BlockParagraph(BaseModel):
level: int # شناسه یکتا خط، مثل ln_1, ln_2, ...
heading:str
paragraph: List[str] # متن خط دقیقاً بدون تغییر
class QuestionAnswer(BaseModel):
question : str
answer : str
class BlockQuestionAnswer(BaseModel):
level: int # شناسه یکتا خط، مثل ln_1, ln_2, ...
heading:str
List[QuestionAnswer]
SYSTEM_PROMPT_LINE = """شما یک مدل بخش‌بندی هستید. وظیفه شما گروه‌بندی خطوط بر اساس نزدیکی معنایی و نزدیکی محتوایی است.
قوانین بسیار سختگیرانه:
1. فقط خطوطی را می‌توان در یک بلاک قرار داد که:
- به صورت متوالی آمده باشند (ln_5 کنار ln_6 باشد)
- و از نظر ساختاری و نقش زبانی بسیار نزدیک باشند
- باید خطوط با بهم پیوستن به یکدیگر ساختار را بسازند مثل: جدول، پاراگراف، شعر و ...
**اگر کوچک‌ترین تفاوت ساختاری وجود داشت، باید بلاک جدید بسازید.**
2. ادغام خطوط غیرمرتبط (حتی اگر هر دو درباره‌ی یک موضوع کلی باشند) کاملاً ممنوع است.
مثال: اطلاعات سند ≠ متن سخنرانی ≠ گفتگو ≠ فهرست
هر کدام بلاک جدا هستند.
3. شما باید همیشه چند بلاک بسازید.
ساخت فقط یک بلاک از تمام خطوط **ممنوع** است.
4. خروجی برای هر بلاک:
- level: سطح موضوع (۰ برای بخش‌های اصلی، ۱ برای زیر موضوعات)
- heading: یک عنوان بسیار کوتاه (۲–۵ کلمه)
- lines: فقط ID خطوط
اگر فقط 1 بلاک تولید کنید → خروجی باطل است.
اگر دو خط از نظر موضوعی دقیقاً یکسان نیستند → باید جدا شوند.
"""
ASSISST_PROMPT_LINE = """
input :
{
"ln_0": "مصاحبه شماره 114"
"ln_1": "\n",
"ln_2": "شناسنامه سند",
"ln_3": "عنوان دوره: سمت خدا",
"ln_4": "کد داخلی: 002261110",
"ln_5": "تاریخ جلسه: 11/07/1394",
"ln_6": "شماره جلسه: 002261110",
"ln_7": "مدت جلسه: 51 دقیقه ",
"ln_8": "تعداد جلسات: 124",
"ln_9": "تعداد کلمات: 6875 کلمه",
}
output:
[
{
"lines": ["ln_0"],
"type": "عنوان اصلی",
"level": 0
}
{
"lines": ["ln_2", "ln_3", "ln_4", "ln_5", "ln_6", "ln_7", "ln_8", "ln_9"],
"type": "شناسنامه سند",
"level": 0
}
]
"""
S_PROMPT_TAG_LINE = '''شما یک مدل "تشخیص ساختار + بخش‌بندی خطوط" هستید.
مرحله ۱ → هر خط باید یکی از این نوع‌ها باشد:
- id_document
- id_tadvin
- title
- paragraph
- question
- answer
- other
مرحله ۲ → خطوط هم‌نوع و متوالی باید تبدیل شوند به یک بلاک.
قوانین ساخت بلاک:
1. بلاک‌ها فقط بر اساس "نوع ساختار" ساخته می‌شوند، نه موضوع.
مثال:
question → answer (بلاک پرسش‌پاسخ)
paragraph → paragraph → paragraph (بلاک پاراگراف)
2. هیچ خطی نباید حذف شود.
3. هیچ بلاکی نباید خطوط غیرمتوالی داشته باشد.
4. هیچ بلاکی نباید بیش از 6 خط داشته باشد (به جز QA که هر جفت سؤال/جواب یک آیتم جداست).
5. تعداد بلاک‌ها باید حداقل 2 باشد.
خروجی فقط باید JSON زیر باشد:
{
"blocks": [
{
"type": "...",
"level": 0 یا 1,
"heading": "۲ تا ۵ کلمه",
"lines": ["ln_x", ...] ← فقط برای paragraph/title/ids
},
{
"type": "qa",
"level": 0,
"heading": "...",
"items": [
{"question": "ln_x", "answer": "ln_y"},
...
]
}
]
}
هیچ توضیح اضافی ندهید.
'''
class Tag(BaseModel):
id: str
tag: str
class TagLLMOutput(BaseModel):
output:List[Tag]
S_PROMPT_TAG_LINE_LV1 = '''
شما یک مدل تخصصی در «تشخیص ساختار خطوط» هستید.
وظیفه شما فقط این است که برای هر خط ورودی، یک تگ ساختاری بسازید.
هر خط باید دقیقاً یکی از این تگ‌ها باشد:
- id_document
- id_tadvin
- title
- paragraph
- question
- answer
- other
قوانین:
1. تگ را فقط بر اساس "ساختار زبانی و فرمت نوشتار" تعیین کنید، توجه ویژه ای به خط در ساختار داشته باشید!
مثال: اگر خط فرمتی شبیه سؤال دارد (؟، پرسش:، سؤال:)، پس question است حتی اگر محتوا چیز دیگری باشد.
2. هیچ خطی نباید حذف شود، در گفتگو ها همیشه یادت باشه اگر دو نفر بودند فرد اولی
3. اگر خط ساختار پرسشی دارد → question
اگر خط ساختار پاسخ دارد → answer
(نشانه‌ها: «پاسخ:»، «جواب:»، «در پاسخ به»، شروع با فعل توضیحی)
4. خطوط عنوان کوتاه در ابتدای سند → title
5. خطوط شامل کد، شماره سند، تاریخ، متادیتا → id_document یا id_tadvin
- اگر شامل کلیدواژه‌های تولیدی/تدوین باشد → id_tadvin
- در غیر این صورت → id_document
6. خروجی باید حتماً یک آرایه JSON از آبجکت‌ها باشد.
ساختار خروجی دقیقاً این است:
[
{"id": "ln_0", "tag": "title"},
{"id": "ln_1", "tag": "paragraph"},
{"id": "ln_2", "tag": "question"},
...
]
هیچ نوع متن اضافی، توضیح، دلیل، یا توضیح خط تولید نکنید.
فقط JSON خالص بدهید.
'''
ASSIST_TAG = """
input:
{
}
"""
def to_line(text:str, o_path=None):
lines = text.split('\n')
line_dict = { str('ln_' +str(i)):index for i, index in enumerate(lines) }
save_orjson(
data=line_dict,
path =r'D:\init_mahdi\project\dataParsers\temps\mn\test_line1.json'
)
line_dict_valid = { i:index for i, index in line_dict.items() if index != ""}
return line_dict_valid
_dict = load_orjson("./temps/mn/t2.json")
for k ,v in _dict.items():
raw_text_here = str(v)
line = to_line(raw_text_here)
print(f'line {len(line)}')
# print(raw_text_here)
user_p = f''' این داده های ورودی هستند، هیچ کدام از خطوط را جا ننداز و همه را تگ بزن:
{line}
'''
# لطفاً با قوانین Locked-Parser بخش‌بندی معنایی انجام بده.
item = {
"system_prompt":S_PROMPT_TAG_LINE_LV1,
# "assistant_prompt":ASSISST_PROMPT_LINE,
"user_prompt":user_p
}
c1_ = count_tokens(model_name='oss-gpt', system_prompt='', user_prompt=user_p)
c2_ = count_tokens(model_name='oss-gpt', system_prompt=SYSTEM_PROMPT_LINE, user_prompt=user_p+ASSISST_PROMPT_LINE)
print(f'user_prompt {c1_}, user+system prompt {c2_}')
runner = AsyncCore(
model_name='gpt-oss-120b',
data_path=None,
output_path=r"D:\init_mahdi\project\dataParsers\temps\mn\t1",
api_url="http://2.188.15.102:8001/v1/",
task_name='mn-t1-sm-oss-120b-med',
output_schema=TagLLMOutput, # ScientificMeeting,
reasoning_effort='medium',
ai_code_version='oss120b_med',
request_timeout=60,
save_number=2,
max_token=128000,
top_p= 1.0,
temperature=0.0,
)
s = time.time()
res, _ = asyncio.run(runner.single_simple_async_proccess_item(item))
o1_ = count_tokens(model_name='oss-gpt', system_prompt='', user_prompt=res)
print(f'Model Output token {o1_}')
save_orjson(
data=res,
path=r"D:\init_mahdi\project\dataParsers\temps\mn\tline1_model.json"
)
e = time.time()
print(
f"Time => {e-s:.2f}'s "
)
# python -m idataparser.task.monir.main_cleaning
+458
View File
@@ -0,0 +1,458 @@
from idataparser import InitTextNormalizer, DataHelper, save_orjson, load_orjson
normalizer = InitTextNormalizer(
options={
"alphabetsNormal": True,
"emptylinesNormal": True,
"hamzehNormal": True,
"removeInvalidChar": True,
}
)
mapping_sanad = {
"„",
"",
" ",
"¢",
"£",
"¤",
"¨",
"¬",
"­",
"°",
"´",
"·",
"¼",
"½",
"¾",
"Ã",
"É",
"Í",
"Ï",
"×",
"Û",
"à",
"á",
"ã",
"ä",
"ç",
"è",
"é",
"ê",
"í",
"ï",
"ñ",
"ó",
"õ",
"ö",
"÷",
"ø",
"ú",
"ü",
"þ",
"ÿ",
"ā",
"Ă",
"Ĉ",
"Ĥ",
"Ŋ",
"ˆ",
"ˇ",
"˜",
"΄",
"μ",
"π",
"Щ",
"؀",
"،",
"؛",
"؟",
"ء",
"آ",
"أ",
"ؤ",
"إ",
"ئ",
"ا",
"ب",
"ة",
"ت",
"ث",
"ج",
"ح",
"خ",
"د",
"ذ",
"ر",
"ز",
"س",
"ش",
"ص",
"ض",
"ط",
"ظ",
"ع",
"غ",
"ـ",
"ف",
"ق",
"ك",
"ل",
"م",
"ن",
"ه",
"و",
"ى",
"ي",
"ً",
"ٌ",
"ٍ",
"َ",
"ُ",
"ِ",
"ّ",
"ْ",
"ٓ",
"ٔ",
"ٖ",
"ٞ",
"٠",
"١",
"٢",
"٣",
"٤",
"٥",
"٨",
"٩",
"٪",
"٬",
"٭",
"ٰ",
"ٱ",
"ٲ",
"ٶ",
"پ",
"چ",
"ژ",
"ک",
"گ",
"ۀ",
"ۃ",
"ی",
"ۖ",
"ۗ",
"ۚ",
"ۡ",
"ۥ",
"ۭ",
"۰",
"۱",
"۲",
"۳",
"۴",
"۵",
"۶",
"۷",
"۸",
"۹",
"ࠤ",
"࠮",
"ࡸ",
"ࢆ",
"ࢲ",
"ࢴ",
"ࣨ",
"ࣴ",
"ࣾ",
"ऀ",
"ऌ",
"ऎ",
"ऐ",
"द",
"ऴ",
"ू",
"ॄ",
"ॆ",
"ग़",
"ड़",
"চ",
"জ",
"৤",
"০",
"৪",
"৮",
"ਢ",
"ਤ",
"ੋ",
"੒",
"ੜ",
"ઈ",
"଀",
"଎",
"஘",
"௚",
"ా",
"౔",
"ೂ",
"ඊ",
"ฃ",
"ด",
"ฮ",
"โ",
"ไ",
"๒",
"ༀ",
"ᆖ",
"ᆘ",
"ᆦ",
"ᐨ",
"ᑪ",
"ᒂ",
"ᒶ",
"ᔟ",
"ᔢ",
"ᔧ",
"ᔪ",
"ᘀ",
"ᘂ",
"ᨾ",
"ᰀ",
"᱊",
"Ḩ",
"ḭ",
"Ḿ",
"Ṏ",
"Ἂ",
"Ῥ",
" ",
"‌",
"‍",
"‎",
"‏",
"‑",
"–",
"—",
"‘",
"’",
"‚",
"“",
"”",
"•",
"…",
"‪",
"‬",
"″",
"‹",
"›",
"⁋",
"",
"™",
"↓",
"−",
"≥",
"⍤",
"␂",
"␃",
"⒢",
"◮",
"⚚",
"⚜",
"⛾",
"⡯",
"⤦",
"⤨",
"ⱆ",
"ⱶ",
"ま",
"㈬",
"㈮",
"㈺",
"㈼",
"㛸",
"㝶",
"㩴",
"㪐",
"㵹",
"㸐",
"㸒",
"䂨",
"䌀",
"䐀",
"䑶",
"䑸",
"䗜",
"䠨",
"䡟",
"䢪",
"䩞",
"䩡",
"䭨",
"䭪",
"䳸",
"䴮",
"䴰",
"伀",
"偦",
"偨",
"儀",
"凄",
"刐",
"刚",
"唃",
"唎",
"唢",
"唤",
"喈",
"喡",
"娀",
"宜",
"屨",
"恨",
"惄",
"愀",
"愔",
"掋",
"摧",
"撆",
"桨",
"汊",
"汌",
"淄",
"皆",
"稀",
"笺",
"筠",
"筨",
"箜",
"篃",
"絘",
"脈",
"茊",
"茌",
"菈",
"蕞",
"蚞",
"譨",
"軺",
"輒",
"輔",
"辜",
"酠",
"鉦",
"鉼",
"鉾",
"銨",
"镖",
"闎",
"餸",
"馼",
"髄",
"魰",
"鶊",
"ꅨ",
"ꉣ",
"ꍀ",
"ꡨ",
"꡻",
"ꢆ",
"ꢘ",
"꣜",
"넣",
"뫜",
"뺨",
"뻪",
"쌀",
"쫮",
"쵕",
"케",
"퓪",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"﴾",
"﴿",
"ﺓ",
"ﺔ",
"ﻫ",
"ﻻ",
"�",
}
# --- تست ---
text = "".join(sorted(mapping_sanad)) # مرتب‌سازی برای قابلیت خواندن
new_text = normalizer.normalize_text_monir(text)
remaining_chars = set(new_text)
removed_chars = mapping_sanad - remaining_chars
print(f"Input Char {len(mapping_sanad)}")
print(f"Now Char{len(remaining_chars)}")
print(f"Remove Char {len(removed_chars)}")
save_orjson(
path=r"D:\init_mahdi\project\dataParsers\idataparser\task\monir\informations\temp_char_test_normalization.json",
data=sorted(list(remaining_chars)),
)
unvalid_string = {
" ",
"&shy",
"",
"",
}
# python -m idataparser.task.monir.mapping_char
unvalid_id = {
"pm146812",
"pm146821",
"",
}
File diff suppressed because it is too large Load Diff
-284
View File
@@ -1,284 +0,0 @@
{
"main_type": {
"type": "keyword"
},
"sub_type": {
"type": "keyword"
},
"id": {
"type": "keyword"
},
"person_code": {
"type": "keyword"
},
"research_code": {
"type": "keyword"
},
"meet_code": {
"type": "keyword"
},
"old_meet_id": {
"type": "integer"
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"meet_no": {
"type": "integer"
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"term_info": {
"properties": {
"id": {
"type": "keyword"
},
"sub_type": {
"type": "keyword"
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"subtitle": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"subjects": {
"properties": {
"id": {
"type": "integer"
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"allwords": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"keywords": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"verb": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"sanad_year": {
"type": "integer"
},
"sanad_date": {
"type": "date"
},
"amplify": {
"type": "text"
},
"ralation": {
"type": "keyword"
},
"city": {
"type": "keyword"
},
"place": {
"type": "keyword"
},
"address": {
"type": "text"
},
"audience": {
"type": "text"
},
"attendees": {
"type": "text"
},
"report_info": {
"properties": {
"film_count": {
"type": "integer"
},
"sound_count": {
"type": "integer"
},
"photo_count": {
"type": "integer"
},
"file_count": {
"type": "integer"
},
"is_address": {
"type": "integer"
},
"is_mindex": {
"type": "integer"
},
"is_mintro": {
"type": "integer"
},
"is_sanad_data1": {
"type": "integer"
},
"is_sanad_data2": {
"type": "integer"
}
}
},
"mindex": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian",
"search_analyzer": "phrase_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
},
"mintro": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian",
"search_analyzer": "phrase_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
},
"content": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian",
"search_analyzer": "phrase_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
},
"completion": {
"type": "completion",
"analyzer": "simple",
"preserve_separators": true,
"preserve_position_increments": true,
"max_input_length": 50
},
"sort_date_timestamp": {
"type": "long"
},
"permit_tags": {
"type": "keyword"
},
"resource_info": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
}
}
-130
View File
@@ -1,130 +0,0 @@
{
"main_type": {
"type": "keyword"
},
"sub_type": {
"type": "keyword"
},
"id": {
"type": "keyword"
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"content": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian",
"search_analyzer": "phrase_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
},
"permit_tags": {
"type": "keyword"
},
"search_state": {
"type": "keyword"
},
"user_create": {
"type": "keyword"
},
"time_create": {
"type": "date"
},
"time_edit": {
"type": "date"
},
"file_links": {
"properties": {
"title": {
"type": "keyword"
},
"link": {
"type": "text"
},
"type": {
"type": "text"
},
"description": {
"type": "text"
}
}
},
"meet_info": {
"properties": {
"id": {
"type": "keyword"
},
"sub_type": {
"type": "keyword"
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"term_info": {
"properties": {
"id": {
"type": "keyword"
},
"sub_type": {
"type": "keyword"
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
-209
View File
@@ -1,209 +0,0 @@
{
"main_type": {
"type": "keyword"
},
"id": {
"type": "keyword"
},
"html": {
"type": "text"
},
"content": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_fa",
"search_analyzer": "normal_analyzer_fa",
"search_quote_analyzer": "phrase_analyzer_fa"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_fa",
"search_analyzer": "phrase_analyzer_fa",
"search_quote_analyzer": "phrase_analyzer_fa"
}
}
},
"meet_info": {
"properties": {
"id": {
"type": "keyword"
},
"format": {
"type": "keyword"
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"term_info": {
"properties": {
"id": {
"type": "keyword"
},
"format": {
"type": "keyword"
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"tree_info": {
"properties": {
"parent_id": {
"type": "keyword"
},
"child_order": {
"type": "double"
},
"level": {
"type": "integer"
},
"full_path": {
"type": "text"
},
"title": {
"type": "text"
},
"path_headings": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"content_len": {
"type": "integer"
},
"word_len": {
"type": "integer"
},
"tags": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"keywords": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"sort_date_timestamp": {
"type": "long"
},
"nlp_parses": {
"properties": {
"main_type": {
"type": "keyword"
},
"nlp_type": {
"type": "keyword"
},
"begin": {
"type": "integer"
},
"end": {
"type": "integer"
},
"text": {
"type": "text"
},
"referes": {
"type": "keyword"
},
"dependency_infos": {
"type": "nested"
}
}
},
"embeddings": {
"type": "dense_vector",
"dims": 768,
"index": true,
"similarity": "cosine"
},
"file_links": {
"properties": {
"title": {"type": "keyword"},
"link": {"type": "text"},
"type": {"type": "text"}
}
},
"time_edit": {
"type": "date"
},
"user_edit": {
"type": "integer"
},
"user_logs": {
"properties": {
"id": {
"type": "keyword"
},
"user_id": {
"type": "integer"
},
"username": {
"type": "keyword"
},
"time_edit": {
"type": "date"
},
"property": {
"type": "keyword"
}
}
}
}
-79
View File
@@ -1,79 +0,0 @@
{
"id": {
"type": "keyword"
},
"main_type": {
"type": "keyword"
},
"sub_type": {
"type": "keyword"
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"content": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian",
"search_analyzer": "phrase_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"begin_date": {
"type": "date"
},
"end_date": {
"type": "date"
},
"begin_year": {
"type": "integer"
},
"tags": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"keywords": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
-363
View File
@@ -1,363 +0,0 @@
{
"id": {
"type": "keyword"
},
"person_code": {
"type": "keyword"
},
"research_code": {
"type": "keyword"
},
"meet_code": {
"type": "keyword"
},
"old_meet_id": {
"type": "integer"
},
"Allwords": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
--"branch": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"meet_no": {
"type": "integer"
},
"subject": {
"properties": {
"id": {
"type": "integer"
},
"title": {
"type": "text",
"fielddata": true,
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"subtitle": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"keywords": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"verb": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"format": {
"type": "text",
"fielddata": true,
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"begin_year": {
"type": "integer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 20
}
}
},
"begin_date": {
"type": "date"
},
"end_date": {
"type": "date"
},
"amplify": {
"type": "text"
},
"ralation": {
"type": "keyword"
},
"city": {
"type": "keyword"
},
"place": {
"type": "keyword"
},
"address": {
"type": "text"
},
"films": {
"type": "integer"
},
"sounds": {
"type": "integer"
},
"photos": {
"type": "integer"
},
"in_tadvin": {
"type": "boolean"
},
"video_links": {
"properties": {
"title": {
"type": "keyword"
},
"link": {
"type": "text"
}
}
},
"sound_links": {
"properties": {
"title": {
"type": "keyword"
},
"link": {
"type": "text"
}
}
},
"photo_links": {
"properties": {
"title": {
"type": "keyword"
},
"link": {
"type": "text"
}
}
},
"file_links": {
"properties": {
"title": {
"type": "keyword"
},
"link": {
"type": "text"
},
"text": {
"type": "text"
},
"date": {
"type": "date"
},
"in_search": {
"type": "boolean"
}
}
},
"audience": {
"type": "text",
"fielddata": true
},
"attendees": {
"type": "text"
},
"report_tmp": {
"properties": {
"address": {
"type": "integer"
},
"mindex": {
"type": "integer"
},
"mintro": {
"type": "integer"
},
"sanad_data1": {
"type": "integer"
},
"sanad_data2": {
"type": "integer"
}
}
},
"mindex": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian",
"search_analyzer": "phrase_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
},
"mintro": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian",
"search_analyzer": "phrase_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
},
"content": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian",
"search_analyzer": "phrase_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
},
"version_info": {
"properties": {
"number": {
"type": "integer"
},
"title": {
"type": "keyword"
},
"timestamp": {
"type": "long"
}
}
},
"next_page": {
"type": "integer"
},
"completion": {
"type": "completion",
"analyzer": "simple",
"preserve_separators": true,
"preserve_position_increments": true,
"max_input_length": 50
},
"sort_date_timestamp": {
"type": "long"
},
"permit_tags": {
"type": "keyword"
},
"resource_info": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian",
"search_analyzer": "phrase_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
}
}
},
"user_owner": {
"type": "integer"
},
"draft_step": {
"type": "keyword"
}
}
-16
View File
@@ -1,16 +0,0 @@
https://dbdiagram.io/home
project-name: normalize-db-Farhangestan
project STEPS:
----- start sanad
1- create-flowchart-normalize-db
2- check- any conflict in merge and unmerge
3- create new es.index
4- test data with example
5- put all data to new es.index
6- check merge and unmerge
----- end sanad
7- start for steps
+704
View File
@@ -0,0 +1,704 @@
# --------------------------- 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
# --------------------------- 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 == "":
return MnTerm(
id=get_unique_id(prfix="mn_tr_"), # each record gets its own ID
old_sanad_id=[sanad_data.id],
author=sanad_data.author,
title=None,
begin_date=sanad_data.begin_date,
begin_year=sanad_data.begin_year,
end_date=sanad_data.end_date,
)
# ===============================
# 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
term_index_name = "mn_term"
meet_index_name = "mn_meet"
ment_index_name = "mn_meet_entity"
dash = "-" * 25
es_helper = ElasticHelper(
es_url="http://192.168.23.60:6900",
es_user="elastic",
es_pass="1234",
# 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
+698
View File
@@ -0,0 +1,698 @@
# --------------------------- 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
+336
View File
@@ -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
-71
View File
@@ -1,71 +0,0 @@
{
"_index": "mn_sanad",
"_id": "pm145554",
"_score": 1,
"_source": {
"sort_date_timestamp": 530928000,
"subtitle": "گروه اقتصاد(تشریح نمودار فلسفه منطق)",
"file_links": [
{
"text": "... string ...\n\n ...",
"link": "/Quick/Download/107434",
"in_search": true,
"title": "سند اولیه (ت. منسومی)"
}
],
"begin_year": 1365,
"research_code": "001104",
"version_info": {
"timestamp": 1714988336,
"number": 1,
"title": "سند اولیه (بازخوانی)"
},
"meet_lid": "001104004",
"allwords": "",
"keywords": "",
"permit_tags": "p5",
"person_code": "001",
"id": 5455,
"subject": [],
"city": "نامشخص",
"begin_date": "1986-10-29T00:00:00",
"author": "سید منیر الدین حسینی الهاشمی(ره)",
"ralation": "",
"research_id": 7548,
"mintro": "",
"content": "... string ...\n\n ...",
"branch": "بررسی کلیات روش دسته بندی و تنظیم امور (دوره اول)",
"sound_links": [
{
"link": "/Quick/Download/276920",
"title": "ضبط ریاست"
},
{
"link": "/Quick/Download/276921",
"title": "ضبط ریاست"
}
],
"RowNum": 4679,
"resource_info": "",
"in_tadvin": true,
"end_date": "1986-10-29T00:00:00",
"format": "جلسه علمی",
"mindex": "",
"video_links": [],
"meet_id": 145554,
"films": 0,
"verb": "",
"address": "",
"attendees": "",
"tags": [],
"amplify": "",
"sounds": 2,
"photos": 0,
"meet_no": 4,
"title": "گروه اقتصاد(تشریح نمودار فلسفه منطق)",
"audience": "",
"place": "",
"meet_code": "1365080701",
"photo_links": []
}
}
-71
View File
@@ -1,71 +0,0 @@
{
"_index": "mn_sanad",
"_id": "pm145552",
"_score": 1,
"_source": {
"sort_date_timestamp": 529718400,
"subtitle": "گروه اقتصاد",
"file_links": [
{
"text": "... string ...\n\n ...",
"link": "/Quick/Download/107429",
"in_search": true,
"title": "سند اولیه (ت. منسومی)"
}
],
"begin_year": 1365,
"research_code": "001104",
"version_info": {
"timestamp": 1714988321,
"number": 1,
"title": "سند اولیه (بازخوانی)"
},
"meet_lid": "001104002",
"allwords": "",
"keywords": "",
"permit_tags": "p5",
"person_code": "001",
"id": 5453,
"subject": [],
"city": "نامشخص",
"begin_date": "1986-10-15T00:00:00",
"author": "سید منیر الدین حسینی الهاشمی(ره)",
"ralation": "",
"research_id": 7548,
"mintro": "",
"content": "... string ...\n\n ...",
"branch": "بررسی کلیات روش دسته بندی و تنظیم امور (دوره اول)",
"sound_links": [
{
"link": "/Quick/Download/276917",
"title": "ضبط ریاست"
},
{
"link": "/Quick/Download/276916",
"title": "ضبط ریاست"
}
],
"RowNum": 4677,
"resource_info": "",
"in_tadvin": true,
"end_date": "1986-10-15T00:00:00",
"format": "جلسه علمی",
"mindex": "",
"video_links": [],
"meet_id": 145552,
"films": 0,
"verb": "",
"address": "",
"attendees": "",
"tags": [],
"amplify": "",
"sounds": 2,
"photos": 0,
"meet_no": 2,
"title": "گروه اقتصاد",
"audience": "",
"place": "",
"meet_code": "1365072301",
"photo_links": []
}
}
-462
View File
@@ -1,462 +0,0 @@
{
"date_detection": false,
"properties": {
"Allwords": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"RowNum": {
"type": "long"
},
"address": {
"type": "text"
},
"allwords": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"amplify": {
"type": "text"
},
"attendees": {
"type": "text"
},
"audience": {
"type": "text",
"fielddata": true
},
"audio_links": {
"properties": {
"link": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"begin_date": {
"type": "date"
},
"begin_year": {
"type": "integer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 20
}
}
},
"branch": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"city": {
"type": "keyword"
},
"completion": {
"type": "completion",
"analyzer": "simple",
"preserve_separators": true,
"preserve_position_increments": true,
"max_input_length": 50
},
"content": {
"type": "text",
"fields": {
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian"
}
}
},
"date_edit": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"draft_step": {
"type": "keyword"
},
"end_date": {
"type": "date"
},
"file_links": {
"properties": {
"date": {
"type": "date"
},
"in_search": {
"type": "boolean"
},
"link": {
"type": "text"
},
"text": {
"type": "text"
},
"title": {
"type": "keyword"
}
}
},
"films": {
"type": "integer"
},
"format": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"fielddata": true
},
"id": {
"type": "keyword"
},
"in_tadvin": {
"type": "boolean"
},
"keywords": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"meet_code": {
"type": "keyword"
},
"meet_id": {
"type": "long"
},
"meet_lid": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"meet_no": {
"type": "integer"
},
"mindex": {
"type": "text",
"fields": {
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian"
}
}
},
"mintro": {
"type": "text",
"fields": {
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian"
}
}
},
"next_page": {
"type": "integer"
},
"old_meet_id": {
"type": "integer"
},
"permit_tags": {
"type": "keyword"
},
"person_code": {
"type": "keyword"
},
"photo_links": {
"properties": {
"link": {
"type": "text"
},
"title": {
"type": "keyword"
}
}
},
"photos": {
"type": "integer"
},
"place": {
"type": "keyword"
},
"province": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"ralation": {
"type": "keyword"
},
"report_tmp": {
"properties": {
"address": {
"type": "integer"
},
"mindex": {
"type": "integer"
},
"mintro": {
"type": "integer"
},
"sanad_data1": {
"type": "integer"
},
"sanad_data2": {
"type": "integer"
}
}
},
"research_code": {
"type": "keyword"
},
"research_id": {
"type": "long"
},
"resource_info": {
"type": "text",
"fields": {
"ar": {
"type": "text",
"analyzer": "normal_analyzer_arabic",
"search_analyzer": "normal_analyzer_arabic",
"search_quote_analyzer": "phrase_analyzer_arabic"
},
"fa": {
"type": "text",
"analyzer": "normal_analyzer_persian",
"search_analyzer": "normal_analyzer_persian",
"search_quote_analyzer": "phrase_analyzer_persian"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_persian"
}
}
},
"sort_date_timestamp": {
"type": "long"
},
"sound_links": {
"properties": {
"link": {
"type": "text"
},
"title": {
"type": "keyword"
}
}
},
"sounds": {
"type": "integer"
},
"subject": {
"properties": {
"id": {
"type": "integer"
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"fielddata": true
}
}
},
"subtitle": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"time_edit": {
"type": "long"
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"user_edit": {
"type": "long"
},
"user_log": {
"properties": {
"property": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"time_edit": {
"type": "long"
},
"user_id": {
"type": "long"
},
"username": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"user_owner": {
"type": "integer"
},
"verb": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"version_info": {
"properties": {
"number": {
"type": "integer"
},
"timestamp": {
"type": "long"
},
"title": {
"type": "keyword"
}
}
},
"version_number": {
"type": "long"
},
"video_links": {
"properties": {
"link": {
"type": "text"
},
"title": {
"type": "keyword"
}
}
}
}
}
-50
View File
@@ -1,50 +0,0 @@
# --------------------------- modularity
from app.common.elastic_helper import ElasticHelper
from base_model import MnTerm
# --------------------------- global-params
input_es_index_name = ''
base_index_name = 'monir_test_term'
id_data = None
_data = None
# --------------------------- function
def conver_mn_term(old_data) -> MnTerm:
new_data = {
id: str
main_type: str
sub_type: str
title: str
content: str
author: str
begin_date: datetime
end_date: datetime
begin_year: int
tags: str
keywords: str
}
# --------------------------- flow
es_helper = ElasticHelper(
es_url="http://127.0.0.1:6900",
es_user="elastic",
# es_pass="",
# path_mappings = ""
)
es_helper.update_index_doc(
is_update_state=False,
index_name_o=base_index_name,
eid=id_data,
data=_data
)
# --------------------------- RUN
# ------ command
# --liunx
# python3 -m app.monir.sanad_stuff.py
# --windows
# python -m app.monir.sanad_stuff.py
-78
View File
@@ -1,78 +0,0 @@
{
"date_detection": false,
"properties": {
"attachment": {
"properties": {
"description": {
"type": "text"
},
"link": {
"type": "keyword"
},
"type": {
"type": "keyword"
}
}
},
"data": {
"type": "text",
"fields": {
"fa": {
"type": "text",
"analyzer": "normal_analyzer_fa",
"search_analyzer": "normal_analyzer_fa",
"search_quote_analyzer": "phrase_analyzer_fa"
},
"ph": {
"type": "text",
"analyzer": "phrase_analyzer_fa"
}
}
},
"data_type": {
"type": "keyword"
},
"description": {
"type": "text"
},
"entity_type": {
"type": "keyword"
},
"history_number": {
"type": "integer"
},
"ref_id": {
"type": "keyword"
},
"ref_key": {
"type": "keyword"
},
"ref_property": {
"type": "keyword"
},
"second_id": {
"type": "keyword"
},
"time_edit": {
"type": "date"
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"user_id": {
"type": "integer"
},
"username": {
"type": "keyword"
},
"version_number": {
"type": "long"
}
}
}