Write me a python script that parses a CSV file, columns limited by pipes, extracts the text column (the third one, or the last one), makes the lines uniques without sorting, keeps the original sort and writes to a text file, here is the example of the content of the csv file: 1|1|بسم الله الرحمن الرحيم 1|2|الحمد لله رب العالمين 1|3|الرحمن الرحيم 1|4|مالك يوم الدين 1|5|إياك نعبد وإياك نستعين 1|6|اهدنا الصراط المستقيم 1|7|صراط الذين أنعمت عليهم غير المغضوب عليهم ولا الضالين 2|1|بسم الله الرحمن الرحيم الم 2|2|ذلك الكتاب لا ريب فيه هدى للمتقين 2|3|الذين يؤمنون بالغيب ويقيمون الصلاة ومما رزقناهم ينفقون
Assistant
Here’s a Python script that parses a CSV file with columns delimited by pipes (|), extracts unique lines from the third column (or the last column), maintains their original order, and writes them to a text file.
python
import csv
def parse_csv_and_extract_unique_text(input_csv_file, output_text_file):
# Using a set to maintain uniqueness and a list to maintain order
seen = set()
unique_lines = []
# Open the CSV file and read it
with open(input_csv_file, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter='|')
for row in reader:
# Extract the third column (index 2) or the last one
text = row[2] if len(row) >= 3 else row[-1]
# Check if we have seen this text before
if text not in seen:
seen.add(text)
unique_lines.append(text)
# Write the unique lines to the output text file
with open(output_text_file, 'w', encoding='utf-8') as outputfile:
for line in unique_lines:
outputfile.write(line + '\n')
# Example usage
input_csv_file = 'input.csv' # Replace with your CSV file path
output_text_file = 'output.txt' # Replace with your desired output file path
parse_csv_and_extract_unique_text(input_csv_file, output_text_file)
How to Use This Script
Save the Script: Copy the script into a Python file, e.g., extract_unique_text.py.
Update File Paths: Make sure to update the input_csv_file and output_text_file variables with the appropriate paths of your input CSV file and desired output text file.
Run the Script: Execute the script using Python:
bash
python extract_unique_text.py
Explanation
The script uses the csv module to read the CSV file, specifying | as the delimiter.
It then iterates through each row, extracts the third column text (or the last column), and checks for uniqueness using a set.
Unique entries are stored in a list while maintaining their original order.
Finally, it writes the unique lines to a specified text file, each on a new line.
User
Please put the input and output files ar arguments to the script
Assistant
Certainly! Below is the modified Python script that takes the input and output file paths as command-line arguments.
python
import csv
import sys
def parse_csv_and_extract_unique_text(input_csv_file, output_text_file):
seen = set()
unique_lines = []
# Open the CSV file and read it
with open(input_csv_file, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter='|')
for row in reader:
# Extract the third column (index 2) or the last one
text = row[2] if len(row) >= 3 else row[-1]
# Check if we have seen this text before
if text not in seen:
seen.add(text)
unique_lines.append(text)
# Write the unique lines to the output text file
with open(output_text_file, 'w', encoding='utf-8') as outputfile:
for line in unique_lines:
outputfile.write(line + '\n')
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python extract_unique_text.py <input_csv_file> <output_text_file>")
sys.exit(1)
input_csv_file = sys.argv[1]
output_text_file = sys.argv[2]
parse_csv_and_extract_unique_text(input_csv_file, output_text_file)
How to Use This Script
Save the Script: Copy the updated script into a Python file, e.g., extract_unique_text.py.
Run the Script with Command-Line Arguments:
Open your terminal or command prompt and run the script with the input and output file paths as arguments:
Replace input.csv with the path to your input CSV file and output.txt with the desired path for your output text file.
Note
Make sure that you have Python installed on your system.
Ensure the input CSV file exists at the specified location before running the script.
User
Traceback (most recent call last):
File "/home/incognito/dataset2image/csv_unique.py", line 34, in
parse_csv_and_extract_unique_text(input_csv_file, output_text_file)
File "/home/incognito/dataset2image/csv_unique.py", line 14, in parse_csv_and_extract_unique_text
text = row[2] if len(row) >= 3 else row[-1]
IndexError: list index out of range
Assistant
The IndexError: list index out of range indicates that the script is attempting to access an index in the row list that doesn't exist. This can happen if a line in your CSV file is empty or has fewer columns than expected.
To handle this situation more gracefully, we can add a check to ensure that the row has enough columns before trying to access them. Below is the modified version of the script with added error handling:
python
import csv
import sys
def parse_csv_and_extract_unique_text(input_csv_file, output_text_file):
seen = set()
unique_lines = []
# Open the CSV file and read it
with open(input_csv_file, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter='|')
for row in reader:
# Check if the row is not empty and has enough columns
if len(row) == 0:
continue # Skip empty rows
elif len(row) >= 3:
text = row[2] # Third column
else:
text = row[-1] # Last column (in case there are less than 3 columns)
# Check if we have seen this text before
if text not in seen:
seen.add(text)
unique_lines.append(text)
# Write the unique lines to the output text file
with open(output_text_file, 'w', encoding='utf-8') as outputfile:
for line in unique_lines:
outputfile.write(line + '\n')
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python extract_unique_text.py <input_csv_file> <output_text_file>")
sys.exit(1)
input_csv_file = sys.argv[1]
output_text_file = sys.argv[2]
parse_csv_and_extract_unique_text(input_csv_file, output_text_file)
Changes Made
Empty Row Check: Before accessing the elements of row, we check if the row is empty. If it is, we simply skip that iteration using continue.
Length Check: If the row has fewer than 3 columns but is not empty, it uses the last column instead.
How to Use the Updated Script
You can still run the script the same way you did before. Make sure to provide proper input and output file paths, and the script will now handle empty lines more robustly without crashing.
User
From a string like this"fonts/tahomabd.ttf" how can I get the file's basename in Python?
Assistant
You can use the os.path module in Python to easily extract the basename of a file from a given file path. The os.path.basename() function will return the last part of the path, which is the filename itself.
os.path.basename(file_path): This function extracts the base name (the last component of the path) from the given file path, which in this case would be tahomabd.ttf.
Alternative: Using pathlib
If you're using Python 3.4 or above, you might also consider using the pathlib module, which offers an object-oriented approach to filesystem paths. Here’s how you can use it:
In this case, Path(file_path).name retrieves the filename from the path while making the code more readable and versatile. Both methods will achieve the desired result of obtaining the file's basename.
User
I want the basename not filename, without extension ".ttf"
Assistant
To extract the basename of a file (without the extension) from a given file path in Python, you can use either the os.path module or the pathlib module and combine it with the os.path.splitext() function or the Path.stem property.
Using os.path
Here’s how you can do it:
python
import os
file_path = "fonts/tahomabd.ttf"
# Get the filename without the extension
file_basename = os.path.splitext(os.path.basename(file_path))[0]
print(file_basename) # Output: tahomabd
Using pathlib
Alternatively, you can use pathlib which allows for a more modern approach:
python
from pathlib import Path
file_path = "fonts/tahomabd.ttf"
# Get the stem (basename without the extension)
file_basename = Path(file_path).stem
print(file_basename) # Output: tahomabd
Explanation
Using os.path:
os.path.basename(file_path) retrieves the filename (tahomabd.ttf).
os.path.splitext(...)[0] separates the filename from its extension, returning only tahomabd.
Using pathlib:
Path(file_path).stem gives you the filename without the extension directly.
Both approaches will yield the basename (the filename without its extension).
User
Please change the following Python script, keep in mind the "font_size" and calculate the text line so it will fit in a line of A4 page, if the text line is longer split it to fit and write more images for that line, "line_1.png" would be for a normal line and if split you go with "line_1_1.png" "line_1_2.png" and so on. Otherwise please keep the script as much as you can like the original one. Here is the script: ```import os
import random
import argparse
import unicodedata
import numpy as np
from PIL import Image, ImageFont, ImageDraw
from scipy.ndimage import gaussian_filter, affine_transform
from PIL import ImageOps
Function to degrade text, can be modified or disabled as per input flag
def distort_line(image):
return image # Placeholder for custom distortion
def generate_image(text, font, background, pad=0, normalize=None, degradation=True):
if normalize:
text = unicodedata.normalize(normalize, text)
code
# Load background image and resize to fit the text size
bg_image = Image.open(background).convert("RGBA")
draw = ImageDraw.Draw(bg_image)
# Select random font size
font_size = random.randint(20, 40)
font = ImageFont.truetype(font, font_size)
# Create text image
text_bbox = draw.textbbox((0, 0), text, font=font)
text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
# Add padding to text image size
text_image = Image.new("RGBA", (text_width + 2 * pad, text_height + 2 * pad), (255, 255, 255, 0))
draw = ImageDraw.Draw(text_image)
draw.text((pad, pad), text, font=font, fill=(0, 0, 0))
# Resize or crop background to fit the text size with padding
bg_image = bg_image.resize((text_width + 2 * pad, text_height + 2 * pad), Image.LANCZOS)
bg_image.paste(text_image, (0, 0), text_image)
# Apply degradation if enabled
if degradation:
bg_image = Image.fromarray(ocropy_degrade(np.array(bg_image)))
return bg_image
Assistant
To modify the provided Python script so that it handles long text lines by splitting them into multiple images while considering the font size and making them fit within the dimensions of an A4 page, we will update the main logic of the script.
An A4 paper has dimensions of approximately 210mm x 297mm, which translates to about 8.27 inches x 11.69 inches. Assuming a resolution of 300 DPI (dots per inch), this gives us:
Width: 2480 pixels (8.27 in * 300 DPI)
Height: 3508 pixels (11.69 in * 300 DPI)
Here is the modified script:
python
User
Please keep in mind the language and script, if is RTL the string is split from right-to-left, if is LTR from left-to-right
Assistant
To consider the text direction based on the language (right-to-left for languages like Arabic and Hebrew, and left-to-right for languages like English and most others), we need to modify the text splitting logic. Here's how we can change the function to split the text appropriately:
Check the language direction based on the RFC-3066 language tag provided.
Adjust the text splitting logic to respect this direction.
Here's the updated code that includes this behavior:
python
User
This script has a problem. With a RTL script, Hebrew or Arabic, the words are right-to-left but the phrase itself is left-to-right.
Assistant
Thank you for your clarification. In RTL languages like Arabic and Hebrew, while the text flows from right to left, the order of the words itself can appear as a singular phrase. To account for this, we need to implement a mechanism that respects the orientation of both the characters and the overall sentence structure.
Here's the revised version of the script that handles the text direction properly. The main challenge is ensuring that while we split the text into lines, we still respect the overall left-to-right arrangement of the lines themselves for rendering.
Updated Script
python
User
Can you change the script and instead the argument "--language" to have "--text-dirrection" so we can choose between "LTR" and "RTL" and the default to be "LTR"? And if selected, to be considered what I said earlier about text dirrection.
Assistant
Certainly! We can modify the script to use the --text-direction argument instead of --language, allowing you to specify whether the text direction is "LTR" (left-to-right) or "RTL" (right-to-left). The default will be set to "LTR".
def main(args):
# Read text lines from file
with open(args.text_file, 'r', encoding="utf-8") as file:
lines = file.readlines()
code
# Retrieve fonts and background images
fonts = [os.path.join(args.fonts_dir, f) for f in os.listdir(args.fonts_dir) if f.endswith('.ttf')]
backgrounds = [os.path.join(args.backgrounds_dir, bg) for bg in os.listdir(args.backgrounds_dir) if bg.endswith(('.png', '.jpg'))]
# Ensure output directory exists
os.makedirs(args.output_dir, exist_ok=True)
for i, line in enumerate(lines):
line = line.strip()
if not line:
continue
# Select random font and background for each line
font = random.choice(fonts)
background = random.choice(backgrounds)
# Generate and save image for each line
image = generate_image(
text=line,
font=font,
background=background,
pad=args.pad, # Use the pad argument
normalize=args.normalization,
degradation=not args.disable_degradation
)
# Save image
image_path = os.path.join(args.output_dir, f"line_{i+1}.png")
image.save(image_path)
print(f"Saved: {image_path}")
if name == "main":
parser = argparse.ArgumentParser(description="Generate images from text lines.")
parser.add_argument("--text_file", "-t", type=str, required=True, help="Path to the text file containing lines of text.")
parser.add_argument("--fonts_dir", "-f", type=str, required=True, help="Directory containing font files.")
parser.add_argument("--backgrounds_dir", "-b", type=str, required=True, help="Directory containing background images.")
parser.add_argument("--output_dir", "-o", type=str, required=True, help="Directory to save the generated images.")
parser.add_argument("--language", "-l", type=str, required=True, help="RFC-3066 language tag to determine text direction.")
parser.add_argument("--normalization", "-n", type=str, choices=["NFD", "NFKD", "NFC", "NFKC"], help="Normalization form.")
parser.add_argument("--disable-degradation", "-D", action="store_true", help="Disable text degradation.")
parser.add_argument("--pad", "-p", type=int, default=0, help="Padding around text (default: 0).")
code
args = parser.parse_args()
main(args)```
import os
import random
import argparse
import unicodedata
import numpy as np
from PIL import Image, ImageFont, ImageDraw
from scipy.ndimage import gaussian_filter, affine_transform
# Function to degrade text, can be modified or disabled as per input flag
def ocropy_degrade(image):
degraded_image = gaussian_filter(image, sigma=1.0)
return degraded_image
def degrade_line(image):
image = affine_transform(image, matrix=[[-1, 0], [0, 1]])
return image
def distort_line(image):
return image # Placeholder for custom distortion
def generate_image(text, font, background, pad=0, normalize=None, degradation=True):
if normalize:
text = unicodedata.normalize(normalize, text)
# Load background image and resize to fit the text size
bg_image = Image.open(background).convert("RGBA")
draw = ImageDraw.Draw(bg_image)
# Create text image with specified font
text_image = create_text_image(text, font, pad)
# Resize or crop background to fit the text size with padding
bg_image = bg_image.resize(text_image.size, Image.LANCZOS)
bg_image.paste(text_image, (0, 0), text_image)
# Apply degradation if enabled
if degradation:
bg_image = Image.fromarray(ocropy_degrade(np.array(bg_image)))
return bg_image
def create_text_image(text, font, pad):
# Draw text to calculate size and create text image
draw = ImageDraw.Draw(Image.new("RGBA", (1, 1)))
text_bbox = draw.textbbox((0, 0), text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
# Create the text image
text_image = Image.new("RGBA", (text_width + 2 * pad, text_height + 2 * pad), (255, 255, 255, 0))
draw = ImageDraw.Draw(text_image)
draw.text((pad, pad), text, font=font, fill=(0, 0, 0))
return text_image
def split_text(line, font, max_width, pad):
# Split text if it exceeds the max width
words = line.split()
split_lines = []
current_line = ""
for word in words:
# Check if adding this word exceeds max_width
test_line = f"{current_line} {word}".strip()
text_image = create_text_image(test_line, font, pad)
if text_image.size[0] > max_width:
split_lines.append(current_line.strip())
current_line = word # Start a new line with the current word
else:
current_line = test_line
if current_line:
split_lines.append(current_line.strip()) # Add any remaining text
return split_lines
def main(args):
# Read text lines from file
with open(args.text_file, 'r', encoding="utf-8") as file:
lines = file.readlines()
# Retrieve fonts and background images
fonts = [os.path.join(args.fonts_dir, f) for f in os.listdir(args.fonts_dir) if f.endswith('.ttf')]
backgrounds = [os.path.join(args.backgrounds_dir, bg) for bg in os.listdir(args.backgrounds_dir) if bg.endswith(('.png', '.jpg'))]
# A4 dimensions at 300 DPI in pixels
a4_width = 2480 # Width in pixels
a4_height = 3508 # Height in pixels
# Ensure output directory exists
os.makedirs(args.output_dir, exist_ok=True)
for i, line in enumerate(lines):
line = line.strip()
if not line:
continue
# Select random font and background for each line
font = random.choice(fonts)
font_size = random.randint(20, 40) # Random font size
font = ImageFont.truetype(font, font_size)
background = random.choice(backgrounds)
# Split line if necessary
split_lines = split_text(line, font, a4_width, args.pad)
for j, split_line in enumerate(split_lines):
# Generate and save image for each split line
image = generate_image(
text=split_line,
font=font,
background=background,
pad=args.pad,
normalize=args.normalization,
degradation=not args.disable_degradation
)
# Save image with appropriate naming
suffix = f"_{j + 1}" if len(split_lines) > 1 else ""
image_path = os.path.join(args.output_dir, f"line_{i + 1}{suffix}.png")
image.save(image_path)
print(f"Saved: {image_path}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate images from text lines.")
parser.add_argument("--text_file", "-t", type=str, required=True, help="Path to the text file containing lines of text.")
parser.add_argument("--fonts_dir", "-f", type=str, required=True, help="Directory containing font files.")
parser.add_argument("--backgrounds_dir", "-b", type=str, required=True, help="Directory containing background images.")
parser.add_argument("--output_dir", "-o", type=str, required=True, help="Directory to save the generated images.")
parser.add_argument("--language", "-l", type=str, required=True, help="RFC-3066 language tag to determine text direction.")
parser.add_argument("--normalization", "-n", type=str, choices=["NFD", "NFKD", "NFC", "NFKC"], help="Normalization form.")
parser.add_argument("--disable-degradation", "-D", action="store_true", help="Disable text degradation.")
parser.add_argument("--pad", "-p", type=int, default=0, help="Padding around text (default: 0).")
args = parser.parse_args()
main(args)
Modifications Explained:
Text Splitting: A new function split_text is created to check if a line exceeds the available width for an A4 page and to split it accordingly.
Calculate A4 Size: The dimensions of an A4 page at 300 DPI are defined (a4_width and a4_height).
Dynamic Image Generation: The image generation now considers the possibility of multiple lines for a single text line, creating separate images for each segment.
Image Naming Convention: The image naming has been updated to use the format line_{i+1}.png for the first segment and line_{i+1}_{j+1}.png for subsequent segments.
This script will properly handle long text lines by splitting them and generating appropriate images, maintaining as much of the original functionality as possible.
import os
import random
import argparse
import unicodedata
import numpy as np
from PIL import Image, ImageFont, ImageDraw
from scipy.ndimage import gaussian_filter, affine_transform
# Function to degrade text, can be modified or disabled as per input flag
def ocropy_degrade(image):
degraded_image = gaussian_filter(image, sigma=1.0)
return degraded_image
def degrade_line(image):
image = affine_transform(image, matrix=[[-1, 0], [0, 1]])
return image
def distort_line(image):
return image # Placeholder for custom distortion
def generate_image(text, font, background, pad=0, normalize=None, degradation=True):
if normalize:
text = unicodedata.normalize(normalize, text)
# Load background image and resize to fit the text size
bg_image = Image.open(background).convert("RGBA")
draw = ImageDraw.Draw(bg_image)
# Create text image with specified font
text_image = create_text_image(text, font, pad)
# Resize or crop background to fit the text size with padding
bg_image = bg_image.resize(text_image.size, Image.LANCZOS)
bg_image.paste(text_image, (0, 0), text_image)
# Apply degradation if enabled
if degradation:
bg_image = Image.fromarray(ocropy_degrade(np.array(bg_image)))
return bg_image
def create_text_image(text, font, pad):
# Draw text to calculate size and create text image
draw = ImageDraw.Draw(Image.new("RGBA", (1, 1)))
text_bbox = draw.textbbox((0, 0), text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
# Create the text image
text_image = Image.new("RGBA", (text_width + 2 * pad, text_height + 2 * pad), (255, 255, 255, 0))
draw = ImageDraw.Draw(text_image)
draw.text((pad, pad), text, font=font, fill=(0, 0, 0))
return text_image
def split_text(line, font, max_width, pad, rtl):
# Split text if it exceeds the max width
words = line.split()
split_lines = []
current_line = ""
if rtl:
# For RTL languages, we build the line from the end to the beginning
for word in reversed(words):
test_line = f"{current_line} {word}".strip()
text_image = create_text_image(test_line, font, pad)
if text_image.size[0] > max_width:
split_lines.append(current_line.strip())
current_line = word # Start a new line with the current word
else:
current_line = test_line
else:
# For LTR languages, we build the line from the beginning to the end
for word in words:
test_line = f"{current_line} {word}".strip()
text_image = create_text_image(test_line, font, pad)
if text_image.size[0] > max_width:
split_lines.append(current_line.strip())
current_line = word # Start a new line with the current word
else:
current_line = test_line
if current_line:
split_lines.append(current_line.strip()) # Add any remaining text
return split_lines
def determine_direction(language):
# A simple check for RTL languages
rtl_languages = {"ar", "he", "fa", "ur"} # Add more as needed
# Extract the primary language code (the first part of the RFC-3066 tag)
lang_code = language.split("-")[0]
return lang_code in rtl_languages
def main(args):
# Read text lines from file
with open(args.text_file, 'r', encoding="utf-8") as file:
lines = file.readlines()
# Retrieve fonts and background images
fonts = [os.path.join(args.fonts_dir, f) for f in os.listdir(args.fonts_dir) if f.endswith('.ttf')]
backgrounds = [os.path.join(args.backgrounds_dir, bg) for bg in os.listdir(args.backgrounds_dir) if bg.endswith(('.png', '.jpg'))]
# A4 dimensions at 300 DPI in pixels
a4_width = 2480 # Width in pixels
a4_height = 3508 # Height in pixels
# Determine if the text direction is RTL or LTR
rtl = determine_direction(args.language)
# Ensure output directory exists
os.makedirs(args.output_dir, exist_ok=True)
for i, line in enumerate(lines):
line = line.strip()
if not line:
continue
# Select random font and background for each line
font = random.choice(fonts)
font_size = random.randint(20, 40) # Random font size
font = ImageFont.truetype(font, font_size)
background = random.choice(backgrounds)
# Split line if necessary
split_lines = split_text(line, font, a4_width, args.pad, rtl)
for j, split_line in enumerate(split_lines):
# Generate and save image for each split line
image = generate_image(
text=split_line,
font=font,
background=background,
pad=args.pad,
normalize=args.normalization,
degradation=not args.disable_degradation
)
# Save image with appropriate naming
suffix = f"_{j + 1}" if len(split_lines) > 1 else ""
image_path = os.path.join(args.output_dir, f"line_{i + 1}{suffix}.png")
image.save(image_path)
print(f"Saved: {image_path}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate images from text lines.")
parser.add_argument("--text_file", "-t", type=str, required=True, help="Path to the text file containing lines of text.")
parser.add_argument("--fonts_dir", "-f", type=str, required=True, help="Directory containing font files.")
parser.add_argument("--backgrounds_dir", "-b", type=str, required=True, help="Directory containing background images.")
parser.add_argument("--output_dir", "-o", type=str, required=True, help="Directory to save the generated images.")
parser.add_argument("--language", "-l", type=str, required=True, help="RFC-3066 language tag to determine text direction.")
parser.add_argument("--normalization", "-n", type=str, choices=["NFD", "NFKD", "NFC", "NFKC"], help="Normalization form.")
parser.add_argument("--disable-degradation", "-D", action="store_true", help="Disable text degradation.")
parser.add_argument("--pad", "-p", type=int, default=0, help="Padding around text (default: 0).")
args = parser.parse_args()
main(args)
Key Changes
Determine Direction: A new function, determine_direction, checks if the provided language is an RTL language (based on the language code).
Split Text According to Direction: The split_text function now takes the direction into account. It splits words for RTL languages from right to left and for LTR languages from left to right.
Incorporate Language Parameter: The script reads the language from the command line and determines if the text should be processed as RTL or LTR.
Usage
You can run the script as before, providing the necessary command-line arguments, including the language tag. The script will now correctly handle the text split direction based on the specified language.
import os
import random
import argparse
import unicodedata
import numpy as np
from PIL import Image, ImageFont, ImageDraw
from scipy.ndimage import gaussian_filter
# Function to degrade text, can be modified or disabled as per input flag
def ocropy_degrade(image):
degraded_image = gaussian_filter(image, sigma=1.0)
return degraded_image
def generate_image(text, font, background, pad=0, normalize=None, degradation=True):
if normalize:
text = unicodedata.normalize(normalize, text)
# Load background image and resize to fit the text size
bg_image = Image.open(background).convert("RGBA")
draw = ImageDraw.Draw(bg_image)
# Create text image with specified font
text_image = create_text_image(text, font, pad)
# Resize or crop background to fit the text size with padding
bg_image = bg_image.resize(text_image.size, Image.LANCZOS)
bg_image.paste(text_image, (0, 0), text_image)
# Apply degradation if enabled
if degradation:
bg_image = Image.fromarray(ocropy_degrade(np.array(bg_image)))
return bg_image
def create_text_image(text, font, pad):
# Draw text to calculate size and create text image
draw = ImageDraw.Draw(Image.new("RGBA", (1, 1)))
text_bbox = draw.textbbox((0, 0), text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
# Create the text image
text_image = Image.new("RGBA", (text_width + 2 * pad, text_height + 2 * pad), (255, 255, 255, 0))
draw = ImageDraw.Draw(text_image)
draw.text((pad, pad), text, font=font, fill=(0, 0, 0))
return text_image
def split_text(line, font, max_width, pad, rtl):
# Split text if it exceeds the max width
words = line.split()
split_lines = []
current_line = ""
if rtl:
# For RTL languages, we preserve overall left-to-right ordering of lines
for word in words:
test_line = f"{current_line} {word}".strip()
text_image = create_text_image(test_line, font, pad)
if text_image.size[0] > max_width:
split_lines.append(current_line.strip())
current_line = word # Start a new line with the current word
else:
current_line = test_line
else:
# For LTR languages, we build the line from the beginning to the end
for word in words:
test_line = f"{current_line} {word}".strip()
text_image = create_text_image(test_line, font, pad)
if text_image.size[0] > max_width:
split_lines.append(current_line.strip())
current_line = word # Start a new line with the current word
else:
current_line = test_line
if current_line:
split_lines.append(current_line.strip()) # Add any remaining text
return split_lines
def determine_direction(language):
# A simple check for RTL languages
rtl_languages = {"ar", "he", "fa", "ur"} # Add more as needed
# Extract the primary language code (the first part of the RFC-3066 tag)
lang_code = language.split("-")[0]
return lang_code in rtl_languages
def main(args):
# Read text lines from file
with open(args.text_file, 'r', encoding="utf-8") as file:
lines = file.readlines()
# Retrieve fonts and background images
fonts = [os.path.join(args.fonts_dir, f) for f in os.listdir(args.fonts_dir) if f.endswith('.ttf')]
backgrounds = [os.path.join(args.backgrounds_dir, bg) for bg in os.listdir(args.backgrounds_dir) if bg.endswith(('.png', '.jpg'))]
# A4 dimensions at 300 DPI in pixels
a4_width = 2480 # Width in pixels
a4_height = 3508 # Height in pixels
# Determine if the text direction is RTL or LTR
rtl = determine_direction(args.language)
# Ensure output directory exists
os.makedirs(args.output_dir, exist_ok=True)
for i, line in enumerate(lines):
line = line.strip()
if not line:
continue
# Select random font and background for each line
font = random.choice(fonts)
font_size = random.randint(20, 40) # Random font size
font = ImageFont.truetype(font, font_size)
background = random.choice(backgrounds)
# Split line if necessary
split_lines = split_text(line, font, a4_width, args.pad, rtl)
for j, split_line in enumerate(split_lines):
# Generate and save image for each split line
image = generate_image(
text=split_line,
font=font,
background=background,
pad=args.pad,
normalize=args.normalization,
degradation=not args.disable_degradation
)
# Save image with appropriate naming
suffix = f"_{j + 1}" if len(split_lines) > 1 else ""
image_path = os.path.join(args.output_dir, f"line_{i + 1}{suffix}.png")
image.save(image_path)
print(f"Saved: {image_path}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate images from text lines.")
parser.add_argument("--text_file", "-t", type=str, required=True, help="Path to the text file containing lines of text.")
parser.add_argument("--fonts_dir", "-f", type=str, required=True, help="Directory containing font files.")
parser.add_argument("--backgrounds_dir", "-b", type=str, required=True, help="Directory containing background images.")
parser.add_argument("--output_dir", "-o", type=str, required=True, help="Directory to save the generated images.")
parser.add_argument("--language", "-l", type=str, required=True, help="RFC-3066 language tag to determine text direction.")
parser.add_argument("--normalization", "-n", type=str, choices=["NFD", "NFKD", "NFC", "NFKC"], help="Normalization form.")
parser.add_argument("--disable-degradation", "-D", action="store_true", help="Disable text degradation.")
parser.add_argument("--pad", "-p", type=int, default=0, help="Padding around text (default: 0).")
args = parser.parse_args()
main(args)
Key Changes Explained:
Split Logic Adjustment: The splitting logic for RTL has been modified so that it keeps the left-to-right sequence of lines while preserving the right-to-left order of the characters within each line.
Text Drawing: The text remains visually correct, with words ordered according to their respective writing direction, allowingfor proper rendering in images.
Usage:
You can run this script in the same way as before, specifying the necessary command-line arguments, including the language. The script now respects the appropriate handling of text for RTL languages while ensuring the overall output is correct visually.
import os
import random
import argparse
import unicodedata
import numpy as np
from PIL import Image, ImageFont, ImageDraw
from scipy.ndimage import gaussian_filter
# Function to degrade text, can be modified or disabled as per input flag
def ocropy_degrade(image):
degraded_image = gaussian_filter(image, sigma=1.0)
return degraded_image
def generate_image(text, font, background, pad=0, normalize=None, degradation=True):
if normalize:
text = unicodedata.normalize(normalize, text)
# Load background image and resize to fit the text size
bg_image = Image.open(background).convert("RGBA")
draw = ImageDraw.Draw(bg_image)
# Create text image with specified font
text_image = create_text_image(text, font, pad)
# Resize or crop background to fit the text size with padding
bg_image = bg_image.resize(text_image.size, Image.LANCZOS)
bg_image.paste(text_image, (0, 0), text_image)
# Apply degradation if enabled
if degradation:
bg_image = Image.fromarray(ocropy_degrade(np.array(bg_image)))
return bg_image
def create_text_image(text, font, pad):
# Draw text to calculate size and create text image
draw = ImageDraw.Draw(Image.new("RGBA", (1, 1)))
text_bbox = draw.textbbox((0, 0), text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
# Create the text image
text_image = Image.new("RGBA", (text_width + 2 * pad, text_height + 2 * pad), (255, 255, 255, 0))
draw = ImageDraw.Draw(text_image)
draw.text((pad, pad), text, font=font, fill=(0, 0, 0))
return text_image
def split_text(line, font, max_width, pad, rtl):
# Split text if it exceeds the max width
words = line.split()
split_lines = []
current_line = ""
if rtl:
# For RTL languages, we preserve overall left-to-right ordering of lines
for word in words:
test_line = f"{current_line} {word}".strip()
text_image = create_text_image(test_line, font, pad)
if text_image.size[0] > max_width:
split_lines.append(current_line.strip())
current_line = word # Start a new line with the current word
else:
current_line = test_line
else:
# For LTR languages, we build the line from the beginning to the end
for word in words:
test_line = f"{current_line} {word}".strip()
text_image = create_text_image(test_line, font, pad)
if text_image.size[0] > max_width:
split_lines.append(current_line.strip())
current_line = word # Start a new line with the current word
else:
current_line = test_line
if current_line:
split_lines.append(current_line.strip()) # Add any remaining text
return split_lines
def main(args):
# Read text lines from file
with open(args.text_file, 'r', encoding="utf-8") as file:
lines = file.readlines()
# Retrieve fonts and background images
fonts = [os.path.join(args.fonts_dir, f) for f in os.listdir(args.fonts_dir) if f.endswith('.ttf')]
backgrounds = [os.path.join(args.backgrounds_dir, bg) for bg in os.listdir(args.backgrounds_dir) if bg.endswith(('.png', '.jpg'))]
# A4 dimensions at 300 DPI in pixels
a4_width = 2480 # Width in pixels
a4_height = 3508 # Height in pixels
# Determine if the text direction is RTL or LTR
rtl = args.text_direction.upper() == "RTL"
# Ensure output directory exists
os.makedirs(args.output_dir, exist_ok=True)
for i, line in enumerate(lines):
line = line.strip()
if not line:
continue
# Select random font and background for each line
font = random.choice(fonts)
font_size = random.randint(20, 40) # Random font size
font = ImageFont.truetype(font, font_size)
background = random.choice(backgrounds)
# Split line if necessary
split_lines = split_text(line, font, a4_width, args.pad, rtl)
for j, split_line in enumerate(split_lines):
# Generate and save image for each split line
image = generate_image(
text=split_line,
font=font,
background=background,
pad=args.pad,
normalize=args.normalization,
degradation=not args.disable_degradation
)
# Save image with appropriate naming
suffix = f"_{j + 1}" if len(split_lines) > 1 else ""
image_path = os.path.join(args.output_dir, f"line_{i + 1}{suffix}.png")
image.save(image_path)
print(f"Saved: {image_path}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate images from text lines.")
parser.add_argument("--text_file", "-t", type=str, required=True, help="Path to the text file containing lines of text.")
parser.add_argument("--fonts_dir", "-f", type=str, required=True, help="Directory containing font files.")
parser.add_argument("--backgrounds_dir", "-b", type=str, required=True, help="Directory containing background images.")
parser.add_argument("--output_dir", "-o", type=str, required=True, help="Directory to save the generated images.")
parser.add_argument("--text_direction", "-d", type=str, choices=["LTR", "RTL"], default="LTR", help="Text direction (default: LTR).")
parser.add_argument("--normalization", "-n", type=str, choices=["NFD", "NFKD", "NFC", "NFKC"], help="Normalization form.")
parser.add_argument("--disable-degradation", "-D", action="store_true", help="Disable text degradation.")
parser.add_argument("--pad", "-p", type=int, default=0, help="Padding around text (default: 0).")
args = parser.parse_args()
main(args)
Key Changes
Argument Modification: The --language argument was replaced with --text-direction, accepting values "LTR" and "RTL". The default is set to "LTR".
Direction Check: The check for RTL is now based directly on the value of args.text_direction (after converting to uppercase for consistency).
Removal of Language Functionality: The language detection functionality has been removed since it's no longer necessary with the new argument.