【语言与知识主题月】自动创作之智能春联
让天涯 发布于2020-07 浏览:4371 回复:2
0
收藏
最后编辑于2022-04

一、功能介绍

根据用户输入的命题关键词自动生成一副春联,包括上联、下联和横批。

二、应用场景

可以通过智能春联功能,获取一些朗朗上口、富有内涵的春联,提升自己的文化品位。

三、使用攻略

说明:本文采用C# 语言,开发环境为.Net Core 3.1,采用在线API接口方式实现。

(1)平台接入
登陆 百度智能云-管理中心 创建 “智能创作平台 ”应用,获取 “API Key ”和 “Secret Key”:https://console.bce.baidu.com/ai/?_=1595858433940&fromai=1#/ai/intelligentwriting/overview/index

(2)接口文档

文档地址:https://ai.baidu.com/ai-doc/NLP/Ok53wb6dh

接口描述:根据用户输入的命题关键词自动生成一副春联,包括上联、下联和横批。

Body请求示例:

{ 
"text": "百度",
"index": 0
}

返回示例:

{	
	"couplets" : {
	   "first": "喜气千年千里新",
	   "second": "清风百度百花艳",
	   "center": "千云祥集"
	}
}

 具体关于输入参数、输出参数、错误码等说明,请参考开发文档,这里不再罗列。

(3)源码共享

(3-1)根据 API Key 和 Secret Key 获取 AccessToken

/// 
/// 获取百度access_token
/// 
/// API Key
/// Secret Key
/// 
public static string GetAccessToken(string clientId, string clientSecret)
{
    string authHost = "https://aip.baidubce.com/oauth/2.0/token";
    HttpClient client = new HttpClient();
    List> paraList = new List>();
    paraList.Add(new KeyValuePair("grant_type", "client_credentials"));
    paraList.Add(new KeyValuePair("client_id", clientId));
    paraList.Add(new KeyValuePair("client_secret", clientSecret));

    HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
    string result = response.Content.ReadAsStringAsync().Result;
    JObject jo = (JObject)JsonConvert.DeserializeObject(result);

    string token = jo["access_token"].ToString();
    return token;
}

(3-2)调用API接口获取识别结果

(3-2-1) 建立Index.cshtml文件

(3-2-1-1)前台代码:

    由于html代码无法原生显示,只能简单说明一下:

    主要是一个form表单,需要设置属性enctype="multipart/form-data",否则无法上传图片;

    form表单里面有几个控件:

一个Input:type="text",asp-for="Text" ,输入创作主题;

一个Input:asp-for="Index" ,value="@Model.Index",记录请求提交次数;

一个Input:type="submit",asp-page-handler="Couplets" ,提交请求。

(3-2-1-2) 后台代码: 

主程序代码:

[BindProperty]
public string Text { get; set; }
[BindProperty]
public int Index { get; set; }
public List msg = new List();

string Create_API_KEY="你的API KEY";
string Create_SECRET_KEY="你的SECRET KEY";

public OnGet()
{
}

public async Task OnPostCoupletsAsync()
{
    if (string.IsNullOrEmpty(Text))
    {
        ModelState.AddModelError(string.Empty, "请输入创作主题!");
    }
    if (!ModelState.IsValid)
    {
        return Page();
    }
    msg = new List();

    DateTime startTime = DateTime.Now;

    string result = GetCreateJson(Text, Index, Create_API_KEY, Create_SECRET_KEY);

    DateTime endTime = DateTime.Now;

    TimeSpan ts = endTime - startTime;

    JObject jo = (JObject)JsonStringToObj(result);

    try
    {
        msg.Add("智能春联(" + (++Index) + ")(耗时" + ts.TotalSeconds + "秒):\n");
        msg.Add("横批:" + jo["couplets"]["center"].ToString());
        msg.Add("上联:" + jo["couplets"]["first"].ToString());
        msg.Add("下联:" + jo["couplets"]["second"].ToString());
    }
    catch (Exception e)
    {
        msg.Add(result);
    }
    return Page();
}

其他相关函数:

/// 
/// 智能创作Json字符串
/// 
/// 主题
/// 第几首
/// API Key
/// Secret Key
/// 
public static string GetCreateJson(string text, int index, string clientId, string clientSecret)
{
    string token = GetAccessToken(clientId, clientSecret);
    string host = "https://aip.baidubce.com/rpc/2.0/creation/v1/couplets?access_token=" + token;
    Encoding encoding = Encoding.Default;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
    request.Method = "post";
    request.ContentType = "application/json";
    request.KeepAlive = true;
    string str = "{\"text\":\"" + text;
    str += "\",\"index\":" + index;
    str += "}";
    byte[] buffer = encoding.GetBytes(str);
    request.ContentLength = buffer.Length;
    request.GetRequestStream().Write(buffer, 0, buffer.Length);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
    string result = reader.ReadToEnd();
    return result;
}

/// 
/// 获取百度access_token
/// 
/// API Key
/// Secret Key
/// 
public static string GetAccessToken(string clientId, string clientSecret)
{
    string authHost = "https://aip.baidubce.com/oauth/2.0/token";
    HttpClient client = new HttpClient();
    List> paraList = new List>();
    paraList.Add(new KeyValuePair("grant_type", "client_credentials"));
    paraList.Add(new KeyValuePair("client_id", clientId));
    paraList.Add(new KeyValuePair("client_secret", clientSecret));

    HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
    string result = response.Content.ReadAsStringAsync().Result;
    JObject jo = (JObject)JsonConvert.DeserializeObject(result);

    string token = jo["access_token"].ToString();
    return token;
}

/// 
/// json转为对象
/// 
/// Json字符串
/// 
public static Object JsonStringToObj(string jsonString)
{
    Object s = JsonConvert.DeserializeObject(jsonString);
    return s;
}

四、效果测试

1、页面:

2、识别结果:

2.1

2.2

2.3

2.4

2.5

2.6

2.7

五、测试结果及建议

从测试结果来看,除了第一次生成智能春联时,耗费了3秒多时间,后来就差不多0.6左右时间,总体生成时间还是比较快的。

生成的春联语句通顺,读起来也有一定的文化内涵。

但是有一个问题,就是生成一定数量的春联后(这里是10条),后的的就是重复之前的春联了,所以对于同一个主题,生成春联的总体数量还是太少了,所以如果能够增加同一主题春联的总体生成数量的话(加到100级别),那么效果会更好的。不然,想想如果有10-20个好友相聚,然后大家都用百度生成智能春联,第11个人之后,发现都是已经讲过的。。。

收藏
点赞
0
个赞
共2条回复 最后由用户已被禁言回复于2022-04
#3189******30回复于2020-07

比曹植快多了。。。

0
#2189******30回复于2020-07

很有意思~~

0
TOP
切换版块