i have this code for docx to markdown conversion:
import os
import mammoth
import sys
import re
from tqdm import tqdm


def convert_docx_to_md_with_mammoth(docx_path, md_path):
    md_dir = os.path.dirname(os.path.abspath(md_path))
    if md_dir == '':
        md_dir = '.'

    base_name = os.path.splitext(os.path.basename(md_path))[0]
    safe_base_name = base_name.replace(' ', '_')  # Replace spaces with underscores

    images_dir_name = f"{safe_base_name}_images"
    images_dir = os.path.join(md_dir, images_dir_name)
    os.makedirs(images_dir, exist_ok=True)

    image_counter = [0]  # To ensure images are numbered sequentially

    def image_converter(image):
        image_counter[0] += 1
        extension = image.content_type.split('/')[1]
        image_name = f"image_{image_counter[0]}.{extension}"
        image_path = os.path.join(images_dir, image_name)
        with image.open() as image_stream:
            image_bytes = image_stream.read()
        with open(image_path, "wb") as f:
            f.write(image_bytes)
        relative_path = os.path.join(images_dir_name, image_name).replace('\\', '/')
        alt_text = image.alt_text or ""
        return {
            "src": relative_path,
            "alt_text": alt_text,
        }

    style_map = """
    heading1 => h1
    heading2 => h2
    heading3 => h3
    """

    if not os.path.isfile(docx_path):
        print(f"Error: Input DOCX file does not exist: {docx_path}", file=sys.stderr)
        return False

    try:
        with open(docx_path, "rb") as docx_file:
            result = mammoth.convert_to_markdown(
                docx_file,
                convert_image=mammoth.images.img_element(image_converter),
                style_map=style_map
            )
    except Exception as e:
        print(f"Error during DOCX conversion of '{docx_path}': {e}", file=sys.stderr)
        return False

    # Optional: print Mammoth messages
    if result.messages:
        for message in result.messages:
            print(f"Mammoth message for '{docx_path}': {message}")

    markdown = result.value

    def remove_emphasis_in_headers(markdown_text):
        def fix_line(line):
            m = re.match(r'^(#+) (_)(.*)(_)\s*$', line)
            if m:
                return f"{m.group(1)} {m.group(3)}"
            return line
        return '\n'.join(fix_line(l) for l in markdown_text.splitlines())

    def isolate_images_on_lines(markdown_text):
        img_pattern = re.compile(r'!\[.*?\]\(.*?\)')

        new_lines = []
        for line in markdown_text.split('\n'):
            matches = list(img_pattern.finditer(line))
            if not matches:
                new_lines.append(line)
                continue

            if len(matches) == 1 and matches[0].start() == 0 and matches[0].end() == len(line):
                new_lines.append(line)
                continue

            last_idx = 0
            parts = []
            for m in matches:
                prefix = line[last_idx:m.start()]
                if prefix.strip():
                    parts.append(prefix.strip())
                parts.append(m.group())
                last_idx = m.end()
            suffix = line[last_idx:]
            if suffix.strip():
                parts.append(suffix.strip())

            new_lines.extend(parts)

        return '\n'.join(new_lines)

    markdown = remove_emphasis_in_headers(markdown)
    markdown = isolate_images_on_lines(markdown)

    def is_persian_line(line):
        for ch in line:
            if '\u0600' <= ch <= '\u06FF' or '\u0750' <= ch <= '\u077F':
                return True
        return False

    lines = markdown.split('\n')
    for i, line in enumerate(lines):
        if line.strip() and is_persian_line(line):
            lines[i] = '\u200f' + line

    markdown = '\n'.join(lines)

    try:
        with open(md_path, "w", encoding="utf-8") as f_md:
            f_md.write(markdown)
    except Exception as e:
        print(f"Error saving Markdown file '{md_path}': {e}", file=sys.stderr)
        return False

    return True


def main():
    if hasattr(sys.stdin, 'reconfigure'):
        sys.stdin.reconfigure(encoding='utf-8')
    if hasattr(sys.stdout, 'reconfigure'):
        sys.stdout.reconfigure(encoding='utf-8')

    cwd = os.getcwd()
    docx_files = [f for f in os.listdir(cwd) if f.lower().endswith(".docx")]
    total_files = len(docx_files)

    if total_files == 0:
        print("No .docx files found in the current directory.")
        return

    print(f"Found {total_files} .docx file(s) to convert.\n")

    with tqdm(total=total_files, unit="file", ncols=80) as pbar:
        for docx_file in docx_files:
            base_name = os.path.splitext(docx_file)[0]
            safe_base_name = base_name.replace(' ', '_')
            docx_path = os.path.join(cwd, docx_file)
            md_file = safe_base_name + ".md"
            md_path = os.path.join(cwd, md_file)
            success = convert_docx_to_md_with_mammoth(docx_path, md_path)
            if not success:
                print(f"Failed to convert {docx_file}", file=sys.stderr)
            pbar.update(1)

    print("\nAll conversions done.")


if __name__ == "__main__":
    main()

change it so that for each docx file a folder with the name of docx file is created and inside of that folder there should be the converted markdown file and the image files extracted from the docx file.