PK creative Spring Festival, I am participating in the “Spring Festival creative submission contest”, please see: Spring Festival creative submission Contest

1. Introduction

The Spring Festival is the most solemn traditional festival in China. Every family must paste Spring Festival couplets on the Spring Festival. On the eve of the Spring Festival, they will use red paper and thick ink to write blessing words, which are pasted on both sides of the door frame on the day of the Spring Festival, implying good luck for the year. They will also invert the word “fu” and paste it on the door, meaning “blessing to the door”. In order to conveniently find the appropriate sentence of Spring Festival couplets, I use the ready-made natural language processing interface to achieve an automatic generation of Spring Festival couplets software, input prompt words can complete the generation of Spring Festival couplets, convenient to write Spring Festival couplets reference.

Here’s what it looks like:

When I was a child the most looking forward to the day is the Chinese New Year, can wear new clothes, eat usually can not eat delicious, after the New Year’s Eve dinner to watch the Spring Festival Gala, set off firecrackers; Now the living standard is gradually improving, the clothes and food we usually wear are not bad, and we are not looking forward to it. Now after the Chinese New Year dinner, everyone is staring at the mobile phone to play, and the feeling is not the same as when I was a child.

2. Implementation principle

Software is designed using Qt framework, call Baidu brain intelligent Couplets interface to complete the generation of Spring Festival couplets.

Official website: ai.baidu.com/tech/nlp_ap…

HTTP request method: POST address: https://aip.baidubce.com/rpc/2.0/creation/v1/couplets URL parameters: access_token through the API Key and Secret Key to obtain the access_token request Header Header: Content-type Application /json Request Parameter Text Prompt character of the Spring Festival couplet index Index of the Spring Festival couplet. The default is 0, the same prompt, multiple times when the index +1 can access the following Spring Festival couplets. Returned Parameter Description First Spring Festival couplet top: 7-9 characters top second Spring Festival couplet bottom: generates 7-9 characters Bottom Center Spring Festival couplet Horizontal batch: generates 4-character Spring Festival couplet horizontal batchCopy the code

Example request:

{"text": "new water ", "index": 0}Copy the code

Examples of data returned:

{" couplets ": {" first" : "New Year new qianshan mountain green water", "second" : "spring spring breeze wanhu red", "center" : "celebrate the New Year"}}Copy the code

3. sample code

The main core code listed below can be directly pasted into their own projects can be used.

3.1 Obtaining the Spring Festival Couplets Interface

// Get Spring Festival couplets
void Widget::get_CoupletText(QString terms,int index)
{
    function_select=1;
    QString requestUrl;
    QNetworkRequest request;
​
    // Store the image BASE64 encoding
    QString imgData;
​
    // Package request parameter assignment
    QJsonObject post_data;
    QJsonDocument document;
​
    // Set the request address
    QUrl url;
    QByteArray post_param;
​
    // Request an address
    requestUrl = "https://aip.baidubce.com/rpc/2.0/creation/v1/couplets";
​
    // Set the data submission format
    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
​
    // Set request parameters:
    post_data.insert("text",terms); // The string (no more than 5 characters) is the theme of the Spring Festival couplets
    post_data.insert("index",index);  //int Integer default value is 0, that is, the first Spring Festival couplet. Each change, the value can be increased by 1, after a certain number will return the previous Spring Festival couplets results.
​
    // Construct the request
    url.setUrl(requestUrl + "? access_token=" + Token);
    request.setUrl(url);
​
    document.setObject(post_data);
    post_param = document.toJson(QJsonDocument::Compact);
​
    // Send the request
    manager->post(request, post_param);
}
Copy the code

3.2 Data parsing code

// Parse the feedback
void Widget::replyFinished(QNetworkReply *reply)
{
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(a);// Read all data
    QByteArray replyData = reply->readAll(a);qDebug() < <"Status code:<<statusCode;
    qDebug() < <"Feedback data:<<QString(replyData);
​
    // Determine the status code
    if(200! = statusCode) {return;
    }
​
    / * feedback data: "{" couplets" : {" center ":" everything is spring ", "first" : "the year of dragon QianQiuYe dragon", "second" : "snake, snake Wan Lichun room"}, "log_id" : 1484407725829006888} "top allied: "In the Year of the Dragon, the Dragon Dances in a thousand years of history", second line: "In the year of the Dragon, the snake ascends thousands of miles of spring", second line: "Everything is in spring", first line: "Tiger leaps forward thousands of miles of tiger", second line: "Tiger leaps forward thousands of dragons", second line: "Tiger leaps forward thousands of dragons", second line: "Tiger leaps forward thousands of dragons" */
    if(function_select==1) // Spring Festival couplets are generated
    {
        // Parse the data
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
            // Determine if it is an object and start parsing the data
            if(document.isObject())
            {
                QJsonObject obj = document.object(a);// Parse the error code
                if(obj.contains("error_code"))
                {
                    int error_code=obj.take("error_code").toInt(a);switch (error_code)
                    {
                    case 0: / / success
                        break;
                    case 110:
                    case 111:
                        QMessageBox::information(this."Tip"."Working on updating the key. Try again.,
                        QMessageBox::Ok,QMessageBox::Ok);
​
                        // Update the key
                        QTimer::singleShot(200.this.SLOT(updateCaption()));
                        return;
​
                    default:
                        if(obj.contains("error_msg"))
                        {
                            QString text=obj.take("error_msg").toString(a); QMessageBox::information(this."Tip",text,
                            QMessageBox::Ok,QMessageBox::Ok);
                            return; }}}else if(obj.contains("couplets"))
                {
                    QJsonObject obj2=obj.take("couplets").toObject(a); QString center;/ / horizontal batch
                    QString first;  // First
                    QString second; // Second in the league
​
                    if(obj2.contains("center"))
                    {
                        center=obj2.take("center").toString(a); }if(obj2.contains("first"))
                    {
                        first=obj2.take("first").toString(a); }if(obj2.contains("second"))
                    {
                        second=obj2.take("second").toString(a); } ui->label_0->setText(center);
​
                    QString first_1="\n";
                    for(int i=0; i<first.size(a); i++) { first_1+=first.at(i);
                        first_1+="\n";
                    }
​
                    QString second_1="\n";
                    for(int i=0; i<second.size(a); i++) { second_1+=second.at(i);
                        second_1+="\n";
                    }
​
                    ui->label_1->setText(first_1);
                    ui->label_2->setText(second_1);
​
                    qDebug() < <"Part."<<first;
                    qDebug() < <Allied: ""<<second;
                    qDebug() < <"Guangpi:"<<center; }}}}/ / update the token
    else if(function_select==4)
    {
        // Parse the data
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
            // Determine if it is an object and start parsing the data
            if(document.isObject())
            {
                QJsonObject obj = document.object(a);//解析token
                if(obj.contains("access_token"))
                {
                     QString data_token=obj.take("access_token").toString(a); Token=data_token.toUtf8(a);qDebug() < <"Updated Token:"<<data_token;
                     // Save to file
                     SaveDataToFile(Token);
                     QMessageBox::information(this."Tip"."Key updated successfully.", QMessageBox::Ok,QMessageBox::Ok); }}}return; }}Copy the code

3.2 Token Data Storage

/* Save data to file */
void Widget::SaveDataToFile(QString text)
{
    /* Save data to a file for next loading */
    QString file;
    file=QCoreApplication::applicationDirPath() +"/"+ConfigFile;
    QFile filesrc(file);
    filesrc.open(QIODevice::WriteOnly);
    QDataStream out(&filesrc);
    out << text;  // serialize write string
    filesrc.flush(a); filesrc.close(a); }/* Function: read data from a file */
QString Widget::ReadDataFile(void)
{
    // Read the configuration file
    QString text,data;
    text=QCoreApplication::applicationDirPath() +"/"+ConfigFile;
​
    // Check whether the file exists
    if(QFile::exists(text))
    {
        QFile filenew(text);
        filenew.open(QIODevice::ReadOnly);
        QDataStream in(&filenew); // Read serialized data from a file
        in >> data; // Extract the written data
        filenew.close(a); }return data; // Return value The value read
}
Copy the code