Flair TextGenerator-Based Sentence Creation

  • Share this:

Code introduction


This function uses the TextGenerator model from the Flair library to generate a random sentence of specified length based on a given seed text.


Technology Stack : Flair, TextGenerator

Code Type : Text generation

Code Difficulty : Intermediate


                
                    
def random_sentence_generator(seed, length):
    import random
    from flair.models import TextGenerator
    from flair.data import Sentence

    # Initialize the text generator with a pre-trained model
    generator = TextGenerator('text-generation-fast')

    # Create a sentence with the given seed
    sentence = Sentence(seed)
    generator.predict(sentence, length)

    return ' '.join(sentencewords for sentencewords in sentence)