Skip to content

Instantly share code, notes, and snippets.

@mootoh
Created September 16, 2014 07:33
Show Gist options
  • Select an option

  • Save mootoh/677ea06446be36203273 to your computer and use it in GitHub Desktop.

Select an option

Save mootoh/677ea06446be36203273 to your computer and use it in GitHub Desktop.
HTTPD that classifies word to noun/other
require 'classifier'
require 'stemmer'
require 'webrick'
require 'json'
# load the previous state if exists
bayes = nil
fh = open('classifier.dump')
if fh
puts 'load'
bayes = Marshal.load(fh)
else
bayes = Classifier::Bayes.new 'noun', 'other'
end
def save(bayes)
out = open('classifier.dump', 'w')
Marshal.dump(bayes, out)
out.flush
end
server = WEBrick::HTTPServer.new :Port => 1979
server.mount_proc '/upload' do |req, res|
nouns = JSON.parse(req.body)
nouns.each do |noun|
puts noun + ': maybe ' + bayes.classify(noun)
input = gets
if input == "\n"
bayes.train_other noun
else
bayes.train_noun noun
end
p bayes
# m.take_snapshot
save(bayes)
end
res.body = bayes
end
server.mount_proc '/noun' do |req, res|
word = req.body
puts 'setting ' + word + ' to noun'
puts word
bayes.train_noun word
save(bayes)
end
server.mount_proc '/other' do |req, res|
word = req.body
# word = req.path.split(/\//)[2]
puts 'setting ' + word + ' to other'
puts word
bayes.train_other word
save(bayes)
end
server.mount_proc '/classify' do |req, res|
word = req.body
p word
result = bayes.classify(word)
res.body = result
end
server.start
def test(bayes)
nouns = JSON.parse(open('a.json').read)
nouns.each do |noun|
puts noun + ': maybe ' + bayes.classify(noun)
input = gets
if input == "\n"
bayes.train_other noun
else
bayes.train_noun noun
end
p bayes
save(bayes)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment