from docx import Document
from bs4 import BeautifulSoup
import re

tableTag=["table","tr", "th", "tc"]
mark1 = r'#\[#'
mark2 = r'#\]#'
hTag1 = r'<'
hTag2 = r'>'
strTable = ''
for tag in tableTag:
    if strTable != '':
        strTable += '|'     
    strTable += '('+tag+')'
regTable = r'<(?P<slash>/)*(?P<tag>'+strTable+')(?P<class>[^>]+)*>'
regTableReplace = r'#[#\g<slash>\g<tag>\g<class>#]#'

def removeHtmlNoTableTag(html):
    html = re.sub(regTable, regTableReplace, html)
    soup = BeautifulSoup(html, "html.parser")
    text = soup.get_text("\n", strip=True)
    text = re.sub(mark1, hTag1, text)
    text = re.sub(mark2, hTag2, text)
    return text

def removeHtmlTags(html, exceptionTags=[]):
    if len(exceptionTags):
        exceptTags = ''
        for tag in exceptionTags:
            if exceptTags != '':
                exceptTags += '|'
            exceptTags += '(' + tag + ')'
        reg1 = r'<(?P<slash>/)*(?P<tag>' + exceptTags + ')(?P<class>[^>]+)*>'
        html = re.sub(reg1, regTableReplace, html)

    soup = BeautifulSoup(html, "html.parser")
    text = soup.get_text("\n", strip=True)

    if len(exceptionTags):
        text = re.sub(mark1, hTag1, text)
        text = re.sub(mark2, hTag2, text)

    return text

def read_docx(file_path):
    doc = Document(file_path)
    full_text = []
    for para in doc.paragraphs:
        full_text.append(para.text)
    return '\n'.join(full_text)

def write_docx(text, output_path):
    doc = Document()
    for line in text.split('\n'):
        doc.add_paragraph(line)
    doc.save(output_path)

input_path = 'qavanin.docx'
output_path = 'output.docx'

html_content = read_docx(input_path)

clean_text = removeHtmlTags(html_content, exceptionTags=[])

write_docx(clean_text, output_path)

print("تگ‌های HTML با موفقیت حذف شدند و نتیجه در فایل جدید ذخیره شد.")
