Valentine’s day isn’t my favorite holiday, mostly because I never seem to get my act together before the big day. But even though the holiday leaves me confused and clueless, the thought of adding a little more love into the world never does. So this year, instead of planning a wonderful night (like maybe I should have done?), I instead opened my laptop and decided to resurrect a 400 year-old poet who had a lot to say on the subject of love― Billy H. Shakespeare.

The thinking was simple, since I’m notoriously bad at writing romantic cards, maybe Shakespeare could do some of the heavy lifting for me. In short I wanted to create an artificially intelligent Shakespeare bot that would:

Tell me if my romantic prose was good or awful Create a custom sonnet for me on demand

Worst-case scenario was that it would give me a good excuse to play with the Twilio-IBM Watson integration ; best-case scenario was that it would save my Valentine’s day!

You can try out the finished product now by texting “Help Me Shakespeare!” to (501) 712-4613 .


Resurrecting Shakespeare using Node, Express, Twilio Add-Ons, IBM Watson and Lov ...
#HelpMeShakespeare

You can see the full code on github , but let’s walk through some of the challenges of resurrecting Shakespeare.

Writing a sonnet from scratch

The first custom piece we need to figure out is how to generate Shakespeare poetry. Luckily there is an awesome API called PoetryDB which allows us to search and filter by poet. Right in the documentation there was an example that searched for Shakespeare sonnets by filtering the results to only poems that were exactly 14 lines long.

varsonnetGenerator = {}; sonnetGenerator.randomSonnet = function(user) { varclient = newClient(); varpoem = [], sonnet = ''; // Search poetryDB for all Shakespeare sonnets. client.get("http://poetrydb.org/author,linecount/Shakespeare;14/lines", function(data, response) { for(vari = 0; i < 14; i ) { varline = data[getRandomInt(data.length)].lines[i]; poem.push(line); } // Generate an image of the sonnet to make it easily shareable. sonnet = createImage(poem, user); return; }); } But since these sonnets would make for fairly long text messages, which would be pretty hard to send to a special someone, we should try and generate an image of the poem. So to do that let’s use node - gd ');">[crayon-58a207540c3b0951025791-i/] and generate a simple gif of our new rad poem. varcreateImage = function(poemArray, user) { varbaseY = 336, leading = 50, pid = getRandomString(), path = `./public/shakes/shake${pid}.gif`, publicUrl = `http://45.55.136.193/shakes/shake${pid}.gif`, poemString = poemArray.join("rn"); // Use a template gif as the starting point gd.openFile('./public/shakespeare.gif', function(err, img) { if(err) { throwerr; } // set text colors vartxtColor = img.colorAllocate(13, 18, 43); vartxtColor2 = img.colorAllocate(241, 47, 70); // Setup fonts and signature varfontPath = './public/fonts/whitney-book.otf'; varsignature = ` - Love ${user.firstName}`; // Since we can't set a leading value for the type, let's insert // the poem lines, line by line at the specific distance for(vari = 0; i < poemArray.length; i ) { // calculate the y position using our leading value varnewY = baseY (leading * i); // insert line onto image canvas // (color, fontPath, fontSize, fontAngle, x, y, string) img.stringFT(txtColor, fontPath, 21, 0, 77, newY, poemArray[i]); } // insert signature after the poem img.stringFT(txtColor2, fontPath, 28, 0, 120, 1096, signature); img.saveFile(path, function(err) { // once the image actually exists on our server, // then we can send it user.sendImage(publicUrl); // save it to the users profile user.sonnets.push({ url: publicUrl, text: poemString }) user.save(); // destroy it in memory img.destroy(); if(err) { throwerr; } }); }); return; } Artificial Intelligence

To embed some artificial intelligence into this bot I needed to use Watson’s sentiment analysis to determine whether a phrase or sentence was positive or not. So let’s add the ability for our Shakespeare-bot to check the positivity of a message. Depending on whether or not it’s positive, we either send an uplifting message or we send a discouraging note with a new custom sonnet.

romanceMeter.check = function(user, req) { varresults = JSON.parse(req.body.AddOns), sentiment = results.results.ibm_watson_sentiment.result.docSentiment, positive = messages[getRandomInt(messages.length)], snark = snarky[getRandomInt(snarky.length)], message = '', media = ''; if(sentiment.score > 0.4) { message = `Well done ${user.firstName}, youcherub! Thouhastcreatedquitetheromanticmessage. ${positive}`; } else{ message = `Oof ${user.firstName}. ${snark} May I recommendthouuses a sonnetofmineown... writingitnow.`; sonnetGenerator.randomSonnet(user); } return{ 'message': message, 'media': media } };

It turns out there is a fairly high correlation between a positive message and a generally nice message so it seems to work fairly consistently.

Notice that to grab the sentiment data in node, we first needed to JSON.parse() the string that was returned inside of req.body.AddOnswe had to do this because even with body-parser extended, express still does not create javascript objects for the nested objects in the Twilio response.

So let’s recap, we have an AI-driven bot that analyzes my romantic dexterity, generates custom Shakespeare poems and creates shareable images of those poems. Now all we need to put a bow on this is a user database, some routing in express and some logic to switch responses based on user input. To see how the code that handles all of this and more, go to github .

Otherwise enjoy your weekend, and if you have any questions about this app, how my valentine’s day ended up going, or you just want to dream up the next weird Twilio app shoot me a note on twitter I’m always happy to jam.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: IBM
分页:12
转载请注明
本文标题:Resurrecting Shakespeare using Node, Express, Twilio Add-Ons, IBM Watson and Lov ...
本站链接:http://www.codesec.net/view/533382.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(47)