import textwrap from typing import List from faker import Faker from funcy import iterate, take, last from cv_analysis.logging import debug_log from cv_analysis.utils import star from cv_analysis.utils.rectangle import Rectangle from synthesis.random import rnd from synthesis.text.line_formatter.identity import IdentityLineFormatter from synthesis.text.line_formatter.line_formatter import LineFormatter from synthesis.text.line_formatter.paragraph import ParagraphLineFormatter from synthesis.text.text_block_generator.text_block_generator import TextBlockGenerator class ParagraphGenerator(TextBlockGenerator): def __init__(self): self.line_formatter = ParagraphLineFormatter(blank_line_percentage=rnd.uniform(0, 0.5)) @debug_log(exits=False) def __call__(self, rectangle, n_sentences=None): return self.generate_paragraph(rectangle, n_sentences) @debug_log(exits=False) def generate_paragraph(self, rectangle, n_sentences=None): lines = generate_random_text_lines(rectangle, self.line_formatter, n_sentences) return lines @debug_log(exits=False) def generate_random_text_lines( rectangle: Rectangle, line_formatter: LineFormatter = None, n_sentences=None, ) -> List[str]: n_sentences = n_sentences or 3000 # TODO: De-hardcode. line_formatter = line_formatter or IdentityLineFormatter() text = Faker().paragraph(nb_sentences=n_sentences, variable_nb_sentences=False, ext_word_list=None) unformatted_lines = textwrap.wrap( text, width=rectangle.width // rnd.uniform(4, 5), # TODO: De-hardcode. break_long_words=True, ) # 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