66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
|
# File 'lib/huginn_naive_bayes_agent/naive_bayes_agent.rb', line 66
def receive(incoming_events)
incoming_events.each do |event|
nbayes = load(memory['data'])
if !event.payload['nb_cats']
error("Missing `nb_cats` field in the event payload. #{event.payload.to_s}")
raise 'Missing `nb_cats` field in the event payload.'
end
if !event.payload['nb_content']
error("Missing `nb_content` field in the event payload. #{event.payload.to_s}")
raise 'Missing `nb_content` field in the event payload.'
end
if event.payload['nb_cats'].length > 0 and not event.payload['nb_cats'].include?("=class")
cats = event.payload['nb_cats'].split(/\s+/)
if cats[0] == "=loadYML"
memory['data'] = event.payload['nb_content']
elsif cats[0] == "=delCat"
ca = event.payload['nb_content'].split(/\s+/)
ca.each do |c|
nbayes.delete_category(c)
end
memory['data'] = YAML.dump(nbayes)
elsif cats[0] == "=purgeTokens"
nbayes.purge_less_than(event.payload['nb_content'].to_i)
memory['data'] = YAML.dump(nbayes)
else
nb_content = event.payload['nb_content']
if interpolated['strip_punctuation'] == "true"
nb_content = nb_content.gsub(/[^[:word:]\s]/, '') end
if interpolated['stem'] == "true"
nb_content = nb_content.split(/\s+/).map{|word| word.stem}.join(" ")
end
cats.each do |c|
c.starts_with?('-') ? nbayes.untrain(nb_content.split(/\s+/), c[1..-1]) : nbayes.train(nb_content.split(/\s+/), c)
end
memory['data'] = YAML.dump(nbayes)
if interpolated['propagate_training_events'] == "true"
create_event payload: event.payload
end
end
else
nb_content = event.payload['nb_content']
if interpolated['strip_punctuation'] == "true"
nb_content = nb_content.gsub(/[^[:word:]\s]/, '') end
if interpolated['stem'] == "true"
nb_content = nb_content.split(/\s+/).map{|word| word.stem}.join(" ")
end
result = nbayes.classify(nb_content.split(/\s+/))
if interpolated['min_value'].to_f == 1
event.payload['nb_cats'] << (event.payload['nb_cats'].length == 0 ? result.max_class : " "+result.max_class)
else
result.each do |cat, val|
if val > interpolated['min_value'].to_f
event.payload['nb_cats'] << (event.payload['nb_cats'].length == 0 ? cat : " "+cat)
end
end
end
create_event payload: event.payload
end
end
end
|