37 lines
1.6 KiB
Python
37 lines
1.6 KiB
Python
import textwrap
|
|
from typing import List
|
|
|
|
from faker import Faker
|
|
from funcy import identity, iterate, take, last
|
|
|
|
from cv_analysis.utils import star
|
|
from cv_analysis.utils.rectangle import Rectangle
|
|
from synthesis.random import rnd
|
|
from synthesis.text.text_block_generator.text_block_generator import TextBlockGenerator
|
|
from synthesis.text.line_formatter.paragraph import ParagraphLineFormatter
|
|
|
|
|
|
class ParagraphGenerator(TextBlockGenerator):
|
|
def __init__(self):
|
|
self.line_formatter = ParagraphLineFormatter(blank_line_percentage=rnd.uniform(0, 0.5))
|
|
|
|
def __call__(self, rectangle, n_sentences):
|
|
return self.generate_paragraph(rectangle, n_sentences)
|
|
|
|
def generate_paragraph(self, rectangle, n_sentences):
|
|
lines = generate_random_text_lines(rectangle, self.line_formatter, n_sentences)
|
|
return lines
|
|
|
|
|
|
def generate_random_text_lines(rectangle: Rectangle, line_formatter=identity, n_sentences=3000) -> List[str]:
|
|
text = Faker().paragraph(nb_sentences=n_sentences, variable_nb_sentences=False, ext_word_list=None)
|
|
unformatted_lines = textwrap.wrap(text, width=rectangle.width, break_long_words=False)
|
|
# each iteration of the line formatter function formats one more line and adds it to the back of the list
|
|
formatted_lines_generator = iterate(star(line_formatter), (unformatted_lines, True))
|
|
# hence do as many iterations as there are lines in the rectangle
|
|
lines_per_iteration = take(len(unformatted_lines), formatted_lines_generator)
|
|
# and then take the lines from the last iteration of the function
|
|
formatted_lines, _ = last(lines_per_iteration)
|
|
|
|
return formatted_lines
|