first commit

This commit is contained in:
init_mahdi
2026-11-23 20:06:18 +03:30
parent 179d37336b
commit 69d8af4b18
17 changed files with 2185 additions and 27 deletions
+64
View File
@@ -0,0 +1,64 @@
from app.common.elastic_helper import ElasticHelper
import os
import orjson
from pathlib import Path
from dotenv import load_dotenv
def load_orjson(path: str | Path):
path = Path(path)
with path.open("rb") as f: # باید باینری باز بشه برای orjson
return orjson.loads(f.read())
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)
)
meet_index_name = "mn_meet"
dash = "-" * 25
load_dotenv()
url = os.getenv("ES_URL")
user_name = os.getenv("ES_USER_NAME")
password = os.getenv("ES_PASSWORD")
new_data = load_orjson(r"D:\init_mahdi\project\dataParsers\app\monir\p1_changed_id_item.json")
print(f'new_data {len(new_data)}')
es_helper = ElasticHelper(
es_url=url,
es_user=user_name,
es_pass=password,
# path_mappings = ""
)
sussecfull = 0
failed = 0
for id, item in new_data.items():
db_data = es_helper.get_document(index_name=meet_index_name, id=id)
# print(f'db_data {db_data}')
db_data = db_data['_source']
if db_data['content'] == item["meet_content"]:
failed += 1
continue
elif item["meet_content"] == "":
failed += 1
continue
else:
sussecfull +=1
db_data['html'] = db_data['content']
db_data['content'] = item["meet_content"]
es_helper.update_index_doc(is_update_state=True, index_name_o=meet_index_name, eid=id, data=db_data)
print(f'id {id}')
# break
# print(db_data)
print(
f'sussecfull {sussecfull}',
f'failed {failed}',
)
# python -m app.monir.change_content_html_meet
# 6235
# sussecfull 139 failed 6096
+373
View File
@@ -0,0 +1,373 @@
from bs4 import BeautifulSoup
import orjson
from pathlib import Path
import re, os, traceback, html
def load_orjson(path: str | Path):
path = Path(path)
with path.open("rb") as f: # باید باینری باز بشه برای orjson
return orjson.loads(f.read())
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 html_to_clean_text(html: str) -> str:
"""
Parse HTML 2 PLAIN TEXT
"""
soup = BeautifulSoup(html, "html.parser")
# تبدیل تگ‌های ساختاری به newline
for tag in soup.find_all(["br", "p", "h1", "h2", "h3", "h4", "h5", "h6"]):
tag.append("\n")
# حذف همه‌ی استایل‌ها و تگ‌های اضافی
for tag in soup():
if tag.name not in ["a"]:
tag.attrs = {} # remove style, class, dir, etc.
# استخراج متن خام
text = soup.get_text("\n")
# حذف newline های اضافی
text = re.sub(r"\n{2,}", "\n", text)
# حذف فاصله‌های خاص HTML
text = text.replace("\xa0", " ").strip()
return text
HTML_TO_NEWLINE = [
r"<\s*br\s*/?>",
r"<\s*p[^>]*>",
r"<\s*/\s*p\s*>",
r"<\s*h[1-6][^>]*>",
r"<\s*/\s*h[1-6]\s*>",
r"<\s*div[^>]*>",
r"<\s*/\s*div\s*>",
]
HTML_TO_SPACE = [
r"&nbsp;",
r"<\s*span[^>]*>",
r"<\s*/\s*span\s*>",
r"\u00A0",
]
def clean_remaining_markup_junk(text: str) -> str:
# 1 orphan closing VML tags </v:...>
text = re.sub(r"</\s*v:[^>]+>", "", text, flags=re.IGNORECASE)
# 2 orphan closing Office tags </o:...>
text = re.sub(r"</\s*o:[^>]+>", "", text, flags=re.IGNORECASE)
# 3 broken SUP tag: SUP>1</SUP>
text = re.sub(r"\bSUP>\s*\d+\s*</\s*SUP\s*>", "", text, flags=re.IGNORECASE)
# 4 FONT tag با محتوای فقط whitespace
text = re.sub(r"<\s*font[^>]*>\s*</\s*font\s*>", "", text, flags=re.IGNORECASE)
return text
def clean_broken_formatting_tags(text: str) -> str:
# 1 fragment های شکسته مثل <STRON ، <B ، <U
text = re.sub(
r"<\s*(strong|stron|b|u|i)\b[^\>]*$",
"",
text,
flags=re.IGNORECASE | re.MULTILINE,
)
# 2 تگ های فرمت‌دهی که باز شده‌اند ولی فقط newline/space بعدش آمده
text = re.sub(r"<\s*(strong|b|u|i)[^>]*>\s*(?=\n)", "", text, flags=re.IGNORECASE)
# 3 orphan opening formatting tags
text = re.sub(r"<\s*(strong|b|u|i)[^>]*>", "", text, flags=re.IGNORECASE)
# 4 <BR> با هر attribute → newline
text = re.sub(r"<\s*br\b[^>]*>", "\n", text, flags=re.IGNORECASE)
return text
def clean_word_office_tag(text: str) -> str:
# 1 XML namespace
text = re.sub(r"<\?xml:namespace[^>]*?>", "", text, flags=re.IGNORECASE)
# 2 Office tags
text = re.sub(r"<\s*o:[^>]+>|<\s*/\s*o:[^>]+>", "", text, flags=re.IGNORECASE)
# 3 VML
text = re.sub(
r"<\s*v:[^>]+>.*?<\s*/\s*v:[^>]+>", "", text, flags=re.IGNORECASE | re.DOTALL
)
text = re.sub(r"<\s*v:[^>]*/\s*>", "", text, flags=re.IGNORECASE)
# 4 حذف کامل لینک‌های فهرست Word (کلیدی)
text = re.sub(
r"<\s*a[^>]*_Toc[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
# 5 حذف تگ‌های فرمت‌دهی خالی
text = re.sub(r"<(strong|b|u|i)[^>]*>\s*</\1>", "", text, flags=re.IGNORECASE)
# orphan closing tags
text = re.sub(r"</\s*(strong|b|u|i|a)\s*>", "", text, flags=re.IGNORECASE)
return text
def clean_text(text: str) -> str:
# 1 فقط entity ها (بدون حذف هیچ تگی)
text = html.unescape(text)
# 2 تگ‌های newline
for pattern in HTML_TO_NEWLINE:
text = re.sub(pattern, "\n", text, flags=re.IGNORECASE)
# 3 موارد فاصله‌ای
for pattern in HTML_TO_SPACE:
text = re.sub(pattern, " ", text, flags=re.IGNORECASE)
# 4 نرمال‌سازی فاصله‌های اطراف newline
# " \n" , "\n " , " \n "
text = re.sub(r"[ \t]+\n", "\n", text)
text = re.sub(r"\n[ \t]+", "\n", text)
# 5 نرمال‌سازی فاصله‌های پشت سرهم
# فاصله‌ها (space) پشت هم ≥2 → یک space
text = re.sub(r" {2,}", " ", text)
# tab پشت سر هم ≥1 → یک tab
text = re.sub(r"\t+", "\t", text)
# 6 جمع کردن newline های پشت‌سرهم
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def clean_inline_font_and_footnote(text: str) -> str:
# 1 پاورقی‌های Word (mso-footnote)
text = re.sub(
r"<\s*a[^>]*mso-footnote-id[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
# 2 FONT هایی که فقط whitespace دارند
text = re.sub(r"<\s*font[^>]*>\s*</\s*font\s*>", "", text, flags=re.IGNORECASE)
# 3 FONT با متن واقعی → نگه‌داشتن متن
text = re.sub(
r"<\s*font[^>]*>([^<]+)</\s*font\s*>", r"\1", text, flags=re.IGNORECASE
)
# 4 SUP های تو در تو (inline reference)
text = re.sub(
r"<\s*sup[^>]*>\s*(?:<\s*sup[^>]*>)?\s*\[?\s*\d+\s*\]?\s*(?:</\s*sup\s*>)?\s*</\s*sup\s*>",
"",
text,
flags=re.IGNORECASE,
)
# 5 tab / shift-space / NBSP
text = text.replace("\t", " ")
text = re.sub(r"\u00A0+", " ", text)
return text
def clean_xml_noise(text: str) -> str:
# 1 حذف namespace های XML ورد
text = re.sub(r"<\?xml:namespace[^>]*?>", "", text, flags=re.IGNORECASE)
# 2 حذف تگ های o:p
text = re.sub(r"<\s*o:p\s*>|<\s*/\s*o:p\s*>", "", text, flags=re.IGNORECASE)
# 3 تبدیل NBSP واقعی به space معمولی
for pattern in HTML_TO_SPACE:
text = re.sub(pattern, " ", text, flags=re.IGNORECASE)
# 4 جمع کردن NBSP + newline های پشت سرهم
text = re.sub(r"( \n)+", "\n", text)
text = re.sub(r"\n( \n)+", "\n\n", text)
return text
def clean_final_word_junk(text: str) -> str:
# حذف همه <A> های پاورقی یا anchor Word حتی بدون محتوای قابل نمایش
text = re.sub(
r"<\s*a[^>]*(mso-footnote-id|msocomanchor)[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
# orphan <A ...> که بسته نشده یا فقط فضا دارند
text = re.sub(
r"<\s*a[^>]*(mso-footnote-id|msocomanchor)[^>]*\s*/?>",
"",
text,
flags=re.IGNORECASE,
)
# 3 حذف <A style="mso-comment-..."> (comment anchor)
text = re.sub(
r"<\s*a[^>]*mso-comment-[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(r"<\s*a[^>]*mso-comment-[^>]*/\s*>", "", text, flags=re.IGNORECASE)
# 4 حذف DEL (متن حذف‌شده Track Changes)
text = re.sub(
r"<\s*del[^>]*>.*?<\s*/\s*del\s*>", "", text, flags=re.IGNORECASE | re.DOTALL
)
# 5 حذف wrapهای Word
text = re.sub(
r"<\s*w:wrap[^>]*>.*?<\s*/\s*w:wrap\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(r"<\s*w:wrap[^>]*/\s*>", "", text, flags=re.IGNORECASE)
# 6 حذف HR ها
text = re.sub(r"<\s*hr\b[^>]*>", "", text, flags=re.IGNORECASE)
# 7 حذف تگ‌های قالب‌بندی جدول
text = re.sub(r"<\s*(table|tbody|tr|td)[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*(table|tbody|tr|td)\s*>", "", text, flags=re.IGNORECASE)
# 8 حذف orphan / fragment تگ‌های VML و Office
text = re.sub(r"<\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE)
return text
def clean_final2_word_junk(text: str) -> str:
# 1 حذف تمام <A> های Word (footnote, anchor, endnote)
text = re.sub(
r"<\s*a[^>]*(mso-footnote-id|msocomanchor|mso-endnote-id)[^>]*>.*?<\s*/\s*a\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(
r"<\s*a[^>]*(mso-footnote-id|msocomanchor|mso-endnote-id)[^>]*/?\s*>",
"",
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"<\s*(del|ins)[^>]*>.*?<\s*/\s*\1\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(
r"<\s*(em|strong|b|u|i)[^>]*>\s*</\s*\1\s*>", "", text, flags=re.IGNORECASE
)
text = re.sub(r"<\s*font[^>]*>\s*</\s*font\s*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"<\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(
r"<\s*w:wrap[^>]*>.*?<\s*/\s*w:wrap\s*>",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(r"<\s*w:wrap[^>]*/\s*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"<\s*hr\b[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"<\s*(table|tbody|tr|td)[^>]*>", "", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*(table|tbody|tr|td)\s*>", "", text, flags=re.IGNORECASE)
return text
def clean_final_stage(text: str) -> str:
"""
"""
def has_fa_ar(text_chunk: str) -> bool:
# Unicode فارسی: \u0600-\u06FF, عربی: \u0750-\u077F, \u08A0-\u08FF
return bool(re.search(r"[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF]", text_chunk))
# <tag ...>...</tag>
def replace_tag(match):
inner = match.group(2) # متن داخل تگ
if has_fa_ar(inner):
return f"({inner.strip()})" # متن فارسی/عربی → داخل پرانتز
else:
return "" # تگ بدون متن فارسی/عربی → حذف کامل
# تگ‌های باز و بسته
text = re.sub(
r"(<([a-zA-Z0-9:_-]+)[^>]*>)(.*?)(</\2>)", replace_tag, text, flags=re.DOTALL
)
text = re.sub(r"<[a-zA-Z0-9:_-]+[^>]*/>", "", text)
text = re.sub(r"<[^>]+>", "", text)
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
if __name__ == "__main__":
######################################################################## p1
in_data = load_orjson(
"/home1/ava3/init_mahdi/project/aiDataParser/task/mn_section/p0_data_dict_id_item.json"
)
unwanted_char = set("&<>")
new_dict = {}
for k, v in in_data.items():
content = v["meet_content"]
if content == "": continue
content = clean_broken_formatting_tags(content)
content = clean_word_office_tag(content)
content = clean_xml_noise(content)
content = clean_remaining_markup_junk(content)
content = clean_inline_font_and_footnote(content)
content = clean_final_word_junk(content)
content = clean_final2_word_junk(content)
content = clean_final_stage(content)
content = clean_text(content)
v["meet_content"] = content
new_dict[k] = v
print(f'new_dict {len(new_dict)}')
save_orjson(
data=new_dict,
path="/home1/ava3/init_mahdi/project/aiDataParser/task/mn_section/p1_data_dict_id_item.json",
)
+59
View File
@@ -0,0 +1,59 @@
from app.common.elastic_helper import ElasticHelper
from app.common.data_helper import DataHelper
import os
import time, traceback, uuid, orjson
from elasticsearch.helpers import scan
from dotenv import load_dotenv
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)
)
load_dotenv()
url = os.getenv("ES_URL")
user_name = os.getenv("ES_USER_NAME")
password = os.getenv("ES_PASSWORD")
term_index_name = "mn_term"
meet_index_name = "mn_meet"
ment_index_name = "mn_meet_entity"
dash = "-" * 25
es_helper = ElasticHelper(
es_url=url,
es_user="elastic",
es_pass=password,
# path_mappings = ""
)
fields = [ "content", "subtitle", "title", "sanad_id", "id", "main_type", "sub_type"]
es_helper
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="mn_meet",
query={
"_source": fields,
"query":
# {"ids": {"values": ["pm146821"]}},
{"match_all": {}},
},
)
)
print(f'old_data {len(old_data)}')
save_orjson(
data=old_data,
path=r"./mn_meet_for_section.json"
)
# python -m dataParsers.app.monir.test