Skip to content

Instantly share code, notes, and snippets.

@derveloper
Last active August 28, 2016 22:10
Show Gist options
  • Save derveloper/74ad1a94600e17d0c5042cd1b88e6745 to your computer and use it in GitHub Desktop.
Save derveloper/74ad1a94600e17d0c5042cd1b88e6745 to your computer and use it in GitHub Desktop.
Hubot script for training hubot with facebook's fastText neural network - https://github.com/facebookresearch/fastText
fs = require 'fs'
execSync = require('child_process').execSync
tmp = require('tmp')
execSync('wget -c https://github.com/facebookresearch/fastText/archive/master.tar.gz')
execSync('tar xvfz master.tar.gz && cd fastText-master && make && cp fasttext ../')
module.exports = (robot) ->
robot.respond /train \"(.+)\" (.+)/i, (res) ->
action = res.match[1]
sentence = res.match[2]
trainLine = "#{sentence} __label__#{action.replace(' ', '_')}\n"
fs.appendFileSync('./train-data.txt', trainLine)
execSync('{ rm train-data.txt && uniq > train-data.txt; } < train-data.txt')
execSync('./fasttext supervised -input train-data.txt -output model')
res.reply "Trained action \"#{action}\" with \"#{sentence}\""
robot.catchAll (msg) ->
if msg.message.match /// #{robot.name}.* ///i
query = msg.message
tmpObj = tmp.fileSync()
fs.appendFileSync(tmpObj.name, query)
action = execSync("./fasttext predict model.bin #{tmpObj.name}")
execSync("rm #{tmpObj.name}")
action = "#{action}".replace("\n", '').replace('__label__', '').replace('_', ' ')
if action is "n/a"
msg.reply "Sorry, I did not understand you"
else
msg.reply "I understand! I'll do \"#{action}\""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment