@[TOC]

“This is the third day of my participation in the First Challenge 2022, for more details: First Challenge 2022”.

preface

Oh, that was a sunny afternoon, as a master of fishing in troubled waters I accidentally skimmed, suddenly found such an article.Writing Spring Festival Couplets in Python: Express the most sincere wishes and best wishes This is not hit my gun, anyway idle is idle, it is better to do something. So I enjoyed a cup of teaGo to look look. Good guy, the original is to generate a couplet of pictures, so the question comes is there a way to automatically generate couplets, and then regenerate into pictures?

And deploy it locally.

So I had a bold idea

Generate couplets based on RNN (Seq2Seq + Attention)

Yes, I have a bold idea. Let’s generate couplets based on Seq2Seq + Attention. However,Well, I guess we’re gonna have to think differently.Whew, I found it.

Environment to prepare

So without further ado, let’s get started quickly. We need to prepare our environment before we do that. I’m using Python 3.8 here

pip install paddlepaddle
pip install paddlehub
This can be used if the paddleHub installation fails
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --default-timeout=100 paddlehub

pip install pillow 

Copy the code

Functional analysis

Couplet generated

Thanks to the PaddleHub that the fly pulp provides for us, we can quickly implement the functions we need. So we can encapsulate our code like this.

There’s really nothing to say about that.

import paddlehub as hub

class HubUtils(object) :
    def __init__(self) :
        self.hub = hub
        Load the model when initializing. It takes time to load the model. It is convenient to call it later, but it is special for the title
        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) :
        By default, five words are returned. This is passed to 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, 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 the key sentence, the word can generate poetry, default one
        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 top line to give the bottom line, default to 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("Heifer on a plane"))
    print(Hub.GetCouplet("The wind blows clouds and the sky tears."))

Copy the code

Here I’ve also encapsulated a few more interesting trained models.

Images generated

Now that we have our couplet, all we need to do is generate our image.

This is actually very simple, we just use pillow to write on a background image, like a watermark.

But first we need to pick a nice font. Here I use or Windows system (no way, a lot of environment configuration in Windows system, in addition to the peacetime office play basic did not play, and now also put the winter vacation….. Used to play Kali.)

Open up this folder C:\Windows\Fonts Let’s pick a nice one.

So let’s take a look at what this produces

We’re going to beautify it a little bit, and we’re going to have to make our letters stand up.And then we’re going to draw some more points and make it puff puff.

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)
        # beautification
        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)
        # beautification
        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()

Copy the code

call

And then we call it.

from utils import ImgUtils,HubUtils


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

    up_couplet = "Pretty 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()
Copy the code

The effect

Looks like it flipped over

conclusion

This is also my first time to write a popular science type (difficulty) article, if there is not enough advice (just kidding, this content is very simple, just adjust the trained model)And happy New Year to you all in advance