Markov chains appear to be training correctly

* Markov chains record words correctly from a single line to the end of
  their line with a couple of exceptions.
* Start working on using ETS for storing markov chains, and saving it as
  a DETS periodically

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
2020-07-08 17:25:26 -07:00
parent 1a73a62a2c
commit 9c69ca7b72
4 changed files with 43 additions and 24 deletions

View File

@@ -3,20 +3,44 @@ defmodule Omnibot.Contrib.Markov do
alias Omnibot.Contrib.Markov.Chain
@default_config path: :"wordbot.ets", order: 2
@default_config path: "markov", order: 2
@impl true
def on_init(cfg) do
# Create the markov database
path = if is_atom(cfg[:path]),
do: cfg[:path],
else: String.to_atom(cfg[:path])
{:ok, db} = :dets.open_file(path)
db
path = String.to_atom(cfg[:path])
:ets.new(path, [:public])
end
@impl true
def on_channel_msg(_irc, _channel, _nick, msg) do
_words = String.split(msg, ~r/\s+/)
def on_channel_msg(_irc, channel, nick, msg) do
train(channel, nick, msg)
end
def train(channel, user, msg) do
chain = (user_chain(channel, user) || create_user_chain(channel, user))
|> Chain.train(msg)
true = update_user_chain(channel, user, chain)
end
def user_chain(channel, user) do
db = state()
case :ets.lookup(db, {channel, user}) do
[] -> nil
[{{^channel, ^user}, chains}] -> chains
end
end
def update_user_chain(channel, user, chain) do
db = state()
case user_chain(channel, user) do
nil -> :ets.insert_new(db, {{channel, user}, chain})
chain -> :ets.insert(db, {{channel, user}, chain})
end
end
defp create_user_chain(channel, user) do
true = update_user_chain(channel, user, %Chain{order: cfg()[:order]})
user_chain(channel, user)
end
end