2022 pairs of Spring Festival couplets (generation of Spring Festival couplets -- hand-in-hand teaching with python (difficulty of Popular Science))

preface

Oh, it was a sunny afternoon. As a master of fishing in troubled waters, I accidentally found such an article.
Write Spring Festival couplets in Python: express the most sincere blessings and best wishes

This is not hitting my gun. Anyway, I'm idle. It's better to do something. So I happily drank a cup of tea

Go look look. Good guy, it turned out that the pictures of couplets were generated. Then the problem came. Is there a way to automatically generate couplets and then generate pictures?

And deploy locally.

So I have a bold idea

Generate couplets (farts) based on RNN (Seq2Seq + Attention)

Yes, I have a bold idea, that is, let's generate couplets based on Seq2Seq + Attention. however

Well, it looks like we have to change our mind.

Ah hoo, I really found it.

Environmental preparation

Well, stop talking nonsense. Let's start quickly.
Before that, we have to prepare our environment.
I use python 3.8 here

pip install paddlepaddle
pip install paddlehub
#If the paddlehub installation fails, you can use the
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --default-timeout=100 paddlehub

pip install pillow 

functional analysis

Couplet generation

Thanks to the support provided by flying slurry PaddleHub We can quickly realize the functions we need. So we can encapsulate our code like this.

There's really nothing to say about this.

import paddlehub as hub

class HubUtils(object):
    def __init__(self):
        self.hub = hub
        #The model needs to be loaded during initialization. It takes time. Load it for later calls, but the title is special
        self.module_love_words = self.hub.Module(name="ernie_gen_lover_words")
        self.module_poetry = self.hub.Module(name="ernie_gen_poetry")
        self.module_couplets = self.hub.Module(name="ernie_gen_couplet")
    def GetLoveWords(self,curx,size=5):
        # Generate love words. Five love words are returned by default. This is passed into the list
        results = self.module_love_words.generate(texts=curx, use_gpu=True, beam_width=size)
        return results[0]

    def GetAcrostic(self,title,line=4,word=7,size=1):
        #By default, one song is returned, and you can enter the title
        self.module_acrostic = self.hub.module = hub.Module(name="ernie_gen_acrostic_poetry", line=4, word=7)
        results = self.module_acrostic.generate(texts=[title], use_gpu=True, beam_width=size)
        return results[0]

    def GetPoetry(self,curx,size=1):
        #Enter key sentences and words to generate a poem, which is one by default
        results = self.module_poetry.generate(texts=[curx], use_gpu=True, beam_width=size)
        return results[0]

    def GetCouplet(self,up_couplet,size=1):
        #Enter the upper link and give the lower link. The default is one
        results = self.module_couplets.generate(texts=[up_couplet], use_gpu=True, beam_width=size)
        return results[0]


if __name__=="__main__":
    Hub = HubUtils()
    print(Hub.GetCouplet("The heifer flew"))
    print(Hub.GetCouplet("The wind blows the clouds and tears the sky"))

Here, I also encapsulated several interesting trained models.

Image generation

Now that we have our couplet, the next thing to do is to generate our pictures.

This is actually very simple. We can directly use the pilot to write on a background picture, just like a watermark.

But before that, we have to choose a nice font.
I still use the Windows system here (I can't help it. Many environment configurations are in the Windows system. I haven't played it except in the office, and now it's winter vacation... I used to play kali before)

Open this folder
C:\Windows\Fonts

Let's choose a nice one.


Let's first look at the effect of this generation


Let's beautify him again. At the same time, we need to make our words stand up.

Then we draw some more points and let it shine.

class ImgUtils(object):

    def Set_Color(self):
        return random.randrange(255)
    def Pretty(self,dr,width,height):
        for i in range(800):
            # Draw interference points
            dr.point(xy=(random.randrange((width)), random.randrange(height)),
                            fill=(self.Set_Color(), self.Set_Color(), self.Set_Color()))

    def CreateImg(self,text,output_path="output.png",
                  fontPath = r"C:\Windows\Fonts\STXINGKA.TTF",show=True,
                  fontSize = 55,pretty=True):
        #Normal text
        lens = len(text)
        # Canvas Color 
        im = Image.new("RGB", (fontSize * lens + 20, (fontSize + 20)), (255, 0, 0))
        dr = ImageDraw.Draw(im)
        font = ImageFont.truetype(fontPath, fontSize)
        #beautify
        if(pretty):
            self.Pretty(dr,fontSize * lens + 20,(fontSize + 20))

        # Text color
        dr.text((10, 10), text, font=font, fill="black")
        im.save(output_path)
        if(show):
            im.show()

    def CoupletImg(self,text,output_path="output.png",
                   fontPath = r"C:\Windows\Fonts\STXINGKA.TTF",show=True,
                   fontSize = 55,pretty=True):

        lens = len(text)
        words = list(text)
        # Canvas Color 
        im = Image.new("RGB", ((fontSize + 20),fontSize * (lens+1) + 20), (255, 0, 0))
        dr = ImageDraw.Draw(im)

        font = ImageFont.truetype(fontPath, fontSize)
        #beautify
        if(pretty):
            self.Pretty(dr,(fontSize + 20),fontSize * lens + 20)
        # Text color
        step = 10
        for word in words:
            dr.text((10, step), word, font=font, fill="black")
            step +=10+fontSize
        im.save(output_path)
        if (show):
            im.show()

call

Then we call it.

from utils import ImgUtils,HubUtils


def main():
    Hub = HubUtils()
    imgUtils = ImgUtils()

    up_couplet = "Beautiful little sister"
    down_couplet = Hub.GetCouplet(up_couplet)[0]
    imgUtils.CoupletImg(up_couplet,output_path="up_couplet.png")
    imgUtils.CoupletImg(down_couplet, output_path="down_couplet.png")

if __name__ == '__main__':
    main()

effect



Looks like the car overturned

summary

This is also my first time to write popular science type (difficulty) articles. If there are deficiencies, please give me more advice
In addition, I wish you a happy New Year~

Keywords: Python AI

Added by blyz on Sat, 22 Jan 2022 19:37:00 +0200