Files
2026-11-23 20:06:18 +03:30

373 lines
11 KiB
Python

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",
)