33from ..data_generator import FakeTextDataGenerator
44from ..utils import load_dict , load_fonts
55
6+ # support RTL
7+ from arabic_reshaper import ArabicReshaper
8+ from bidi .algorithm import get_display
69
710class GeneratorFromStrings :
811 """Generator that uses a given list of strings"""
@@ -13,6 +16,7 @@ def __init__(
1316 count = - 1 ,
1417 fonts = [],
1518 language = "en" ,
19+ rtl = False ,
1620 size = 32 ,
1721 skewing_angle = 0 ,
1822 random_skew = False ,
@@ -44,6 +48,14 @@ def __init__(
4448 self .fonts = fonts
4549 if len (fonts ) == 0 :
4650 self .fonts = load_fonts (language )
51+ self .rtl = rtl
52+ self .orig_strings = []
53+ if self .rtl :
54+ self .rtl_shaper = ArabicReshaper (configuration = {"delete_harakat" :False })
55+ # save a backup of the original strings before arabic-reshaping
56+ self .orig_strings = self .strings
57+ # reshape the strings
58+ self .strings = self .reshape_rtl (self .strings , self .rtl_shaper )
4759 self .language = language
4860 self .size = size
4961 self .skewing_angle = skewing_angle
@@ -112,5 +124,15 @@ def next(self):
112124 self .stroke_fill ,
113125 self .image_mode ,
114126 ),
115- self .strings [(self .generated_count - 1 ) % len (self .strings )],
127+ self .orig_strings [( self . generated_count - 1 ) % len ( self . orig_strings )] if self . rtl else self . strings [(self .generated_count - 1 ) % len (self .strings )],
116128 )
129+
130+ def reshape_rtl (self , strings : list , rtl_shaper : ArabicReshaper ):
131+ # reshape RTL characters before generating any image
132+ rtl_strings = []
133+ for string in strings :
134+ reshaped_string = rtl_shaper .reshape (string )
135+ rtl_strings .append (get_display (reshaped_string ))
136+ return rtl_strings
137+
138+
0 commit comments