from bs4 import BeautifulSoup from aiDataParser.core.data_normalizer import load_orjson, save_orjson import re, os, traceback, html 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" ", r"<\s*span[^>]*>", r"<\s*/\s*span\s*>", r"\u00A0", ] def clean_remaining_markup_junk(text: str) -> str: # 1️⃣ orphan closing VML tags text = re.sub(r"]+>", "", text, flags=re.IGNORECASE) # 2️⃣ orphan closing Office tags text = re.sub(r"]+>", "", text, flags=re.IGNORECASE) # 3️⃣ broken SUP tag: SUP>1 text = re.sub(r"\bSUP>\s*\d+\s*", "", text, flags=re.IGNORECASE) # 4️⃣ FONT tag با محتوای فقط whitespace text = re.sub(r"<\s*font[^>]*>\s*", "", text, flags=re.IGNORECASE) return text def clean_broken_formatting_tags(text: str) -> str: # 1️⃣ fragment های شکسته مثل ]*$", "", 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️⃣
با هر 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*", "", text, flags=re.IGNORECASE) # 6️⃣ orphan closing tags text = re.sub(r"", "", 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*", "", text, flags=re.IGNORECASE) # 3️⃣ FONT با متن واقعی → نگه‌داشتن متن text = re.sub( r"<\s*font[^>]*>([^<]+)", 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*", "", 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: # 1️⃣ حذف همه های پاورقی یا anchor Word حتی بدون محتوای قابل نمایش text = re.sub( r"<\s*a[^>]*(mso-footnote-id|msocomanchor)[^>]*>.*?<\s*/\s*a\s*>", "", text, flags=re.IGNORECASE | re.DOTALL, ) # 2️⃣ orphan که بسته نشده یا فقط فضا دارند text = re.sub( r"<\s*a[^>]*(mso-footnote-id|msocomanchor)[^>]*\s*/?>", "", text, flags=re.IGNORECASE, ) # 3️⃣ حذف (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"", "", text, flags=re.IGNORECASE) # 8️⃣ حذف orphan / fragment تگ‌های VML و Office text = re.sub(r"<\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE) text = re.sub(r"]*>", "", text, flags=re.IGNORECASE) return text def clean_final2_word_junk(text: str) -> str: # 1️⃣ حذف تمام های 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, ) # 2️⃣ حذف DEL و INS (Track Changes) text = re.sub( r"<\s*(del|ins)[^>]*>.*?<\s*/\s*\1\s*>", "", text, flags=re.IGNORECASE | re.DOTALL, ) # 3️⃣ حذف EM, STRONG, B, U, I خالی یا فقط whitespace text = re.sub( r"<\s*(em|strong|b|u|i)[^>]*>\s*", "", text, flags=re.IGNORECASE ) # 4️⃣ حذف FONT خالی یا فقط whitespace text = re.sub(r"<\s*font[^>]*>\s*", "", text, flags=re.IGNORECASE) # 5️⃣ حذف orphan / fragment تگ‌های VML و Office text = re.sub(r"<\s*(v|o):[^>]*>", "", text, flags=re.IGNORECASE) text = re.sub(r"]*>", "", text, flags=re.IGNORECASE) # 6️⃣ حذف 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) # 7️⃣ حذف HR ها text = re.sub(r"<\s*hr\b[^>]*>", "", text, flags=re.IGNORECASE) # 8️⃣ حذف تگ‌های قالب‌بندی جدول text = re.sub(r"<\s*(table|tbody|tr|td)[^>]*>", "", text, flags=re.IGNORECASE) text = re.sub(r"", "", text, flags=re.IGNORECASE) return text def clean_final_stage(text: str) -> str: """ 1️⃣ حذف آخرین junk های Word/HTML 2️⃣ متن فارسی/عربی داخل تگ حفظ شود، بقیه حذف 3️⃣ تگ‌های بدون متن یا غیر فارسی/عربی → جایگزین () """ # 1️⃣ تابع کمکی: بررسی وجود کاراکتر فارسی/عربی 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)) # 2️⃣ حذف همه تگ‌ها اما متن فارسی/عربی را نگه دار # ... 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:_-]+)[^>]*>)(.*?)()", replace_tag, text, flags=re.DOTALL ) # 3️⃣ حذف تگ‌های self-closing بدون متن text = re.sub(r"<[a-zA-Z0-9:_-]+[^>]*/>", "", text) # 4️⃣ حذف تگ‌های باقی‌مانده بدون محتوا text = re.sub(r"<[^>]+>", "", text) # 5️⃣ cleanup فاصله و newline اضافی text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip() from bs4 import BeautifulSoup, NavigableString import re from bs4 import BeautifulSoup, NavigableString import re from bs4 import BeautifulSoup, NavigableString, Tag import re def safe_clean_html(text: str) -> str: if not text or not text.strip(): return "" soup = BeautifulSoup(text, "html.parser") # ▼ 1. تگ‌های بلوکی: اضافه کردن \n قبل/بعد + unwrap block_tags = {"p", "h1", "h2", "h3", "h4", "h5", "h6", "div"} for tag in soup.find_all(block_tags): if tag.parent is not None: try: tag.insert_before("\n") tag.insert_after("\n") tag.unwrap() except Exception: # fallback: فقط unwrap کن if tag.parent is not None: tag.unwrap() else: tag.decompose() # ▼ 2. تگ‌های inline: فقط unwrap (بدون \n) inline_tags = {"span", "font", "b", "strong", "i", "em", "u"} for tag in soup.find_all(inline_tags): if tag.parent is not None: tag.unwrap() else: tag.decompose() # ▼ 3. حذف تگ‌های namespace (v:, o:, w:) و غیرضروری for tag in soup.find_all(True): if isinstance(tag, Tag): name = tag.name if name and ( name.startswith(("o:", "v:", "w:")) or name in {"br", "hr", "del", "ins", "sup", "sub"} ): tag.decompose() # ▼ 4. حذف لینک‌های Word-specific (footnote, TOC, comment) for a in soup.find_all("a"): # جمع‌آوری تمام ویژگی‌ها به صورت متن برای جستجوی راحت‌تر tag_str = str(a).lower() if ( "_toc" in tag_str or "mso-footnote-id" in tag_str or "msocomanchor" in tag_str or "mso-endnote-id" in tag_str or "mso-comment" in tag_str ): a.decompose() # ▼ 5. تبدیل
به \n — اگر هنوز باقی مانده باشد for br in soup.find_all("br"): br.replace_with("\n") # ▼ 6. حذف تگ‌های خالی for tag in soup.find_all(True): if isinstance(tag, Tag) and tag.parent and not tag.get_text(strip=True): tag.decompose() # ▼ 7. استخراج متن و پاک‌سازی cleaned = soup.get_text() # نرمال‌سازی whitespace cleaned = re.sub(r"[ \t]+", " ", cleaned) cleaned = re.sub(r"\n\s*\n", "\n\n", cleaned) cleaned = re.sub(r"^\s+|\s+$", " ", cleaned, flags=re.MULTILINE) cleaned = re.sub(r"\n{3,}", "\n\n", cleaned) return cleaned.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("&<>") changed = {} not_changed = {} for k, v in in_data.items(): content = v["meet_content"] if content == "": continue elif not any(char in set(content) for char in unwanted_char): not_changed[k] = v else: # 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) ############## content = safe_clean_html(content) v["meet_content"] = content changed[k] = v print(f'changed {len(changed)} not_changed {len(not_changed)}') save_orjson( data=changed, path="/home1/ava3/init_mahdi/project/aiDataParser/task/mn_section/p1_changed_id_item.json", ) save_orjson( data=not_changed, path="/home1/ava3/init_mahdi/project/aiDataParser/task/mn_section/p1_not_changed_id_item.json", ) ######################################################################## p0 # main_data = load_orjson('/home1/ava3/init_mahdi/data/mn_meet_for_section.json') # f_data = {} # for i in main_data: # if i['_source']['content'] == "": continue # else: # f_data[i['_id']]={ # 'meet_id':i['_id'], # 'sanad_id':i['_source']['sanad_id'], # 'meet_content':i['_source']['content'], # "meet_main_type":i['_source']['main_type'], # } # print(f'main_data {len(main_data)}') # print(f'f_data {len(f_data.keys())}') # # 23311 # save_orjson( # data=f_data, # path='/home1/ava3/init_mahdi/project/aiDataParser/task/mn_section/p0_data_dict_id_item.json' # ) # python3 -m aiDataParser.task.mn_section.dev_test.data_ready