you misunderstood. make a global and universal and just one folder for all extracted images and put all of them in the folder(don't make an image folder for every docx file. make just one folder for all the images). also don't put converted markdown files each in separate folders put them beside each other(outside of any folder)
Assistant
User
images are not shown in converted markdown files. the link to them is broken(due to images folder change). fix the images linking
Assistant
User
give me the entire fixed code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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, output_folder):
# Create target folder for the current docx conversion
os.makedirs(output_folder, exist_ok=True)
code
# base name for the markdown file
base_name = os.path.splitext(os.path.basename(docx_path))[0]
safe_base_name = base_name.replace(' ', '_') # If needed
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(output_folder, 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 = image_name # Image is in the same folder as markdown
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)
# Save markdown file inside output_folder
md_path = os.path.join(output_folder, safe_base_name + ".md")
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')
code
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)
# Create folder for docx
output_folder = os.path.join(cwd, safe_base_name)
success = convert_docx_to_md_with_mammoth(docx_path, output_folder)
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 the code so that it saves all the extracted images from docx files in a folder and all the converted markdown files should be outside of that images folder.
Certainly! To achieve this, you need to:
Create a dedicated images folder inside the output folder (e.g., output_folder/images).
Save all extracted images in that images folder.
Save the markdown file inside the output folder but not inside the images folder.
I updated your code accordingly. The changes are marked with comments # MODIFIED for clarity.
Here's your updated code with the required modifications:
python
import os
import mammoth
import sys
import re
from tqdm import tqdm
def convert_docx_to_md_with_mammoth(docx_path, output_folder):
# Create target folder for the current docx conversion
os.makedirs(output_folder, exist_ok=True)
# Create images subfolder inside output_folder
images_folder = os.path.join(output_folder, "images")
os.makedirs(images_folder, exist_ok=True) # MODIFIED
# base name for the markdown file
base_name = os.path.splitext(os.path.basename(docx_path))[0]
safe_base_name = base_name.replace(' ', '_') # If needed
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_folder, image_name) # MODIFIED: save inside images_folder
with image.open() as image_stream:
image_bytes = image_stream.read()
with open(image_path, "wb") as f:
f.write(image_bytes)
# Return path relative to markdown file location: images/image_x.ext
relative_path = os.path.join("images", image_name) # MODIFIED
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)
# Save markdown file inside output_folder (not inside images folder)
md_path = os.path.join(output_folder, safe_base_name + ".md") # MODIFIED
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)
# Create folder for docx
output_folder = os.path.join(cwd, safe_base_name)
success = convert_docx_to_md_with_mammoth(docx_path, output_folder)
if not success:
print(f"Failed to convert {docx_file}", file=sys.stderr)
pbar.update(1)
print("\nAll conversions done.")
if __name__ == "__main__":
main()
Summary of the key changes:
Created an "images" subfolder inside the output folder.
The images extracted are saved inside this "images" folder.
The Markdown image references point to "images/image_x.ext" relative to the Markdown file.
The Markdown file is saved directly inside the output folder, not inside the images folder.
Let me know if you need help testing this or want additional features!
Got it! You want:
One global images folder for all extracted images from any DOCX file (e.g., extracted_images).
All converted Markdown files saved directly in your working directory (no subfolders).
The images folder stays separate and all images from multiple DOCX files coexist there.
Image filenames should be unique globally to avoid clashes across docx files.
Here is the updated version of your code reflecting those changes.
python
import os
import mammoth
import sys
import re
from tqdm import tqdm
def convert_docx_to_md_with_mammoth(docx_path, images_folder):
base_name = os.path.splitext(os.path.basename(docx_path))[0]
safe_base_name = base_name.replace(' ', '_') # sanitize
# We will keep a counter for images for unique names globally, using a prefix based on the filename
image_counter = [0]
def image_converter(image):
image_counter[0] += 1
extension = image.content_type.split('/')[1]
# Image filename prefixed with doc basename to avoid name clashes from different documents
image_name = f"{safe_base_name}_image_{image_counter[0]}.{extension}"
image_path = os.path.join(images_folder, image_name)
with image.open() as image_stream:
image_bytes = image_stream.read()
with open(image_path, "wb") as f:
f.write(image_bytes)
# Return relative path to markdown file, which is in cwd, so just 'extracted_images/imagename'
relative_path = os.path.join(os.path.basename(images_folder), image_name)
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
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)
# Save markdown directly in the current working directory, named with sanitized base_name
md_filename = safe_base_name + ".md"
md_path = os.path.join(os.getcwd(), md_filename)
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
# Create a single global images folder in cwd
images_folder = os.path.join(cwd, "extracted_images")
os.makedirs(images_folder, exist_ok=True)
print(f"Found {total_files} .docx file(s) to convert.\n")
print(f"All images will be saved to folder: {images_folder}")
with tqdm(total=total_files, unit="file", ncols=80) as pbar:
for docx_file in docx_files:
docx_path = os.path.join(cwd, docx_file)
success = convert_docx_to_md_with_mammoth(docx_path, images_folder)
if not success:
print(f"Failed to convert {docx_file}", file=sys.stderr)
pbar.update(1)
print("\nAll conversions done.")
if __name__ == "__main__":
main()
Explanation of the changes:
One global folder for images: Created once in main() as extracted_images inside the current working directory.
Image saving:
Every image from any DOCX is saved inside that folder.
Image filenames are prefixed with the DOCX filename to be unique (e.g. mydoc_image_1.png).
Markdown files:
Saved directly in the cwd (no subfolders).
Named after DOCX filename, spaces replaced with underscores.
Let me know if you'd like me to add more features or error handling!
Thanks for the info! The broken image links issue is because the relative path from the markdown file to the images folder is probably incorrect.
Since your markdown files are saved directly in the current directory (cwd), and your images are inside the extracted_images folder also in the cwd, the relative links inside the markdown should be something like:
code
extracted_images/image_name.ext
If those links are broken, likely the src values returned in the image_converter function are either absolute paths or incorrect.
Try this fix and let me know if images show up correctly in your markdown files!
Certainly! Here's the entire fixed code with the image links corrected to use forward slashes, ensuring that image paths in the Markdown files are valid and relative to the location of the markdown files (which are saved directly in the current working directory).
python
import os
import mammoth
import sys
import re
from tqdm import tqdm
def convert_docx_to_md_with_mammoth(docx_path, images_folder):
base_name = os.path.splitext(os.path.basename(docx_path))[0]
safe_base_name = base_name.replace(' ', '_') # sanitize
image_counter = [0]
def image_converter(image):
image_counter[0] += 1
extension = image.content_type.split('/')[1]
image_name = f"{safe_base_name}_image_{image_counter[0]}.{extension}"
image_path = os.path.join(images_folder, image_name)
with image.open() as image_stream:
image_bytes = image_stream.read()
with open(image_path, "wb") as f:
f.write(image_bytes)
# Fix image path for markdown (forward slashes even on Windows)
relative_path = os.path.join(os.path.basename(images_folder), image_name).replace(os.sep, '/')
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
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)
md_filename = safe_base_name + ".md"
md_path = os.path.join(os.getcwd(), md_filename)
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
images_folder = os.path.join(cwd, "extracted_images")
os.makedirs(images_folder, exist_ok=True)
print(f"Found {total_files} .docx file(s) to convert.\n")
print(f"All images will be saved to folder: {images_folder}")
with tqdm(total=total_files, unit="file", ncols=80) as pbar:
for docx_file in docx_files:
docx_path = os.path.join(cwd, docx_file)
success = convert_docx_to_md_with_mammoth(docx_path, images_folder)
if not success:
print(f"Failed to convert {docx_file}", file=sys.stderr)
pbar.update(1)
print("\nAll conversions done.")
if __name__ == "__main__":
main()
Summary of the fix:
The image URLs inside markdown use forward slashes / regardless of OS.
Images are saved into a single extracted_images folder.
Markdown files are saved directly in the cwd, referencing images like extracted_images/<image_name>.
This will resolve broken image links in your markdown files.
Feel free to ask if you want me to help with anything else!