htm-cli 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +11 -0
- data/COMMITS.md +196 -0
- data/LICENSE.txt +21 -0
- data/README.md +99 -0
- data/Rakefile +23 -0
- data/bin/htm +18 -0
- data/lib/htm/admin/database_commands.rb +489 -0
- data/lib/htm/admin/enrich_commands.rb +275 -0
- data/lib/htm/admin/entity_commands.rb +203 -0
- data/lib/htm/admin/entity_graph.rb +313 -0
- data/lib/htm/admin/file_commands.rb +323 -0
- data/lib/htm/admin/memory_commands/edit.rb +175 -0
- data/lib/htm/admin/memory_commands/entities.rb +189 -0
- data/lib/htm/admin/memory_commands/entity_lines.rb +111 -0
- data/lib/htm/admin/memory_commands/search.rb +205 -0
- data/lib/htm/admin/memory_commands/tag_search.rb +98 -0
- data/lib/htm/admin/memory_commands/text.rb +166 -0
- data/lib/htm/admin/memory_commands/working_memory.rb +71 -0
- data/lib/htm/admin/memory_commands.rb +196 -0
- data/lib/htm/admin/tag_commands.rb +352 -0
- data/lib/htm/admin/tag_graph.rb +345 -0
- data/lib/htm/admin/templates/tag_graph.html +319 -0
- data/lib/htm/admin.rb +266 -0
- data/lib/htm/cli/config_file.rb +73 -0
- data/lib/htm/cli/db.rb +80 -0
- data/lib/htm/cli/enrich.rb +52 -0
- data/lib/htm/cli/entities.rb +268 -0
- data/lib/htm/cli/environment.rb +74 -0
- data/lib/htm/cli/error_suggestion.rb +97 -0
- data/lib/htm/cli/files.rb +41 -0
- data/lib/htm/cli/group.rb +46 -0
- data/lib/htm/cli/memory.rb +410 -0
- data/lib/htm/cli/memory_command.rb +72 -0
- data/lib/htm/cli/robots.rb +82 -0
- data/lib/htm/cli/support.rb +46 -0
- data/lib/htm/cli/tags.rb +103 -0
- data/lib/htm/cli/version.rb +11 -0
- data/lib/htm/cli/working_memory.rb +41 -0
- data/lib/htm/cli.rb +96 -0
- data/lib/htm/mcp/entity_tools.rb +334 -0
- data/lib/htm/mcp/file_tools.rb +196 -0
- data/lib/htm/mcp/group_tools.rb +466 -0
- data/lib/htm/mcp/node_tools.rb +358 -0
- data/lib/htm/mcp/resources.rb +192 -0
- data/lib/htm/mcp/robot_team_tools.rb +129 -0
- data/lib/htm/mcp/server.rb +111 -0
- data/lib/htm/mcp/tag_tools.rb +130 -0
- data/lib/htm/mcp/tool.rb +40 -0
- data/lib/htm/mcp/tool_support.rb +108 -0
- data/lib/htm/mcp/tools.rb +461 -0
- metadata +181 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class HTM
|
|
4
|
+
module Admin
|
|
5
|
+
# The `htm enrich ...` commands: catch up on, inspect and redo the
|
|
6
|
+
# work HTM's background jobs do for each node (embeddings, tags,
|
|
7
|
+
# entities, propositions).
|
|
8
|
+
module EnrichCommands
|
|
9
|
+
# Nodes older than this without an embedding or tags count as failed
|
|
10
|
+
STALE_AFTER = 3600
|
|
11
|
+
|
|
12
|
+
# Existing tags offered to the tag extractor as ontology context
|
|
13
|
+
ONTOLOGY_SIZE = 100
|
|
14
|
+
|
|
15
|
+
# What process_all says instead of extracting entities while entity.enabled is off
|
|
16
|
+
ENTITIES_OFF = "Skipping entity extraction: entity.enabled is off " \
|
|
17
|
+
"(`htm enrich process_entities` extracts them anyway)"
|
|
18
|
+
|
|
19
|
+
module_function
|
|
20
|
+
|
|
21
|
+
# @return [Sequel::Dataset] active nodes with no embedding
|
|
22
|
+
def nodes_without_embeddings = HTM::Models::Node.where(embedding: nil)
|
|
23
|
+
|
|
24
|
+
# @return [Sequel::Dataset] active nodes with no active tag link
|
|
25
|
+
def nodes_without_tags
|
|
26
|
+
HTM::Models::Node.where(Sequel.~(HTM::Models::NodeTag.where(Sequel[:node_tags][:node_id] => Sequel[:nodes][:id]).select(1).exists))
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# @return [Array<Integer>] ids of nodes that already have proposition nodes
|
|
30
|
+
def proposition_source_ids = HTM::Models::Node.proposition_source_ids
|
|
31
|
+
|
|
32
|
+
# @return [Sequel::Dataset] non-proposition nodes no proposition points back to
|
|
33
|
+
def nodes_without_propositions(processed_ids = proposition_source_ids)
|
|
34
|
+
HTM::Models::Node.non_propositions.exclude(id: processed_ids)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# @return [Hash{Integer => Integer}] tag count per depth (colons in the name), by depth
|
|
38
|
+
def tag_depth_counts(names)
|
|
39
|
+
names.map { it.count(':') }.tally.sort.to_h
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Print node and tag coverage
|
|
43
|
+
def stats(out: $stdout)
|
|
44
|
+
Admin.connect!
|
|
45
|
+
total = HTM::Models::Node.count
|
|
46
|
+
with_embeddings = HTM::Models::Node.exclude(embedding: nil).count
|
|
47
|
+
with_tags = HTM::Models::Node.with_tags.count
|
|
48
|
+
|
|
49
|
+
out.puts "HTM Async Job Statistics"
|
|
50
|
+
out.puts "=" * 60
|
|
51
|
+
out.puts "Total nodes: #{total}"
|
|
52
|
+
coverage_shares(total, with_embeddings, with_tags).merge(entity_shares)
|
|
53
|
+
.each { |label, part| print_share(out, label, part, total) }
|
|
54
|
+
print_tag_breakdown(HTM::Models::Tag.select_map(:name), with_tags, out)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# @return [Hash{String => Integer}] node counts with and without embeddings and tags, by label
|
|
58
|
+
def coverage_shares(total, with_embeddings, with_tags)
|
|
59
|
+
{
|
|
60
|
+
"Nodes with embeddings" => with_embeddings,
|
|
61
|
+
"Nodes without embeddings" => total - with_embeddings,
|
|
62
|
+
"Nodes with tags" => with_tags,
|
|
63
|
+
"Nodes without tags" => total - with_tags
|
|
64
|
+
}
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# @return [Hash{String => Integer}] nodes that mention an entity, and nodes process_entities
|
|
68
|
+
# would extract from (no mention, not yet examined, not a proposition), by label
|
|
69
|
+
def entity_shares
|
|
70
|
+
{
|
|
71
|
+
"Nodes with entities" => EntityCommands.nodes_with_entities,
|
|
72
|
+
"Nodes awaiting entity extraction" => EntityCommands.nodes_awaiting_entities.count
|
|
73
|
+
}
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def print_share(out, label, part, whole)
|
|
77
|
+
out.puts "#{label}: #{part} (#{Admin.percentage(part, whole)}%)"
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def print_tag_breakdown(names, nodes_with_tags, out)
|
|
81
|
+
out.puts "\nTotal tags in ontology: #{names.size}"
|
|
82
|
+
unless names.empty?
|
|
83
|
+
out.puts "\nTag hierarchy breakdown:"
|
|
84
|
+
tag_depth_counts(names).each { |depth, count| out.puts " Depth #{depth}: #{count} tags" }
|
|
85
|
+
end
|
|
86
|
+
return unless nodes_with_tags.positive?
|
|
87
|
+
|
|
88
|
+
out.puts "\nAverage tags per node: #{(HTM::Models::NodeTag.count.to_f / nodes_with_tags).round(2)}"
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# Generate embeddings for nodes that have none
|
|
92
|
+
#
|
|
93
|
+
# @return [Hash, nil] { ok:, failed: }, nil when nothing was pending
|
|
94
|
+
#
|
|
95
|
+
def process_embeddings(out: $stdout)
|
|
96
|
+
prepare!
|
|
97
|
+
process(nodes_without_embeddings, 'Embeddings', "embedding", out) { |node, _bar| embed!(node) }
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Embed +node+ and link it to its nearest neighbors, as GenerateEmbeddingJob does
|
|
101
|
+
def embed!(node)
|
|
102
|
+
Admin.embed!(node)
|
|
103
|
+
HTM::Jobs::GenerateRelationshipsJob.relate(node.id)
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Extract tags for nodes that have none
|
|
107
|
+
#
|
|
108
|
+
# @return [Hash, nil] { ok:, failed: }, nil when nothing was pending
|
|
109
|
+
#
|
|
110
|
+
def process_tags(out: $stdout)
|
|
111
|
+
prepare!
|
|
112
|
+
process(nodes_without_tags, 'Tags', "tag extraction", out) { |node, _bar| tag!(node) }
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# Extract tags for +node+ (with recent tags as ontology context) and
|
|
116
|
+
# link them, as GenerateTagsJob does
|
|
117
|
+
def tag!(node)
|
|
118
|
+
ontology = HTM::Models::Tag.order(Sequel.desc(:created_at)).limit(ONTOLOGY_SIZE).select_map(:name)
|
|
119
|
+
node.add_tags(HTM::TagService.extract(node.content, existing_ontology: ontology))
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Extract entities for the nodes that mention none and have not been
|
|
123
|
+
# examined yet (propositions inherit theirs). A node found to name no
|
|
124
|
+
# entity is stamped as examined and is not tried again.
|
|
125
|
+
#
|
|
126
|
+
# It runs whether or not entity.enabled is on: asking for it by name is enough.
|
|
127
|
+
#
|
|
128
|
+
# @return [Hash, nil] { ok:, failed: }, nil when nothing was pending
|
|
129
|
+
#
|
|
130
|
+
def process_entities(out: $stdout)
|
|
131
|
+
prepare!
|
|
132
|
+
process(EntityCommands.nodes_awaiting_entities, 'Entities', "entity extraction", out) do |node, _bar|
|
|
133
|
+
EntityCommands.extract!(node)
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# process_entities as a step of process_all: skipped, with a line saying so, while entity.enabled is off
|
|
138
|
+
#
|
|
139
|
+
# @return [Hash, nil] { ok:, failed: }, nil when nothing was pending or the step was skipped
|
|
140
|
+
#
|
|
141
|
+
def process_enabled_entities(out: $stdout)
|
|
142
|
+
prepare!
|
|
143
|
+
HTM.config.extract_entities ? process_entities(out:) : Admin.say(out, ENTITIES_OFF)
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
# Extract propositions for nodes not yet processed
|
|
147
|
+
#
|
|
148
|
+
# @return [Hash, nil] { ok:, failed:, created: }, nil when nothing was pending
|
|
149
|
+
#
|
|
150
|
+
def process_propositions(out: $stdout)
|
|
151
|
+
prepare!
|
|
152
|
+
processed = proposition_source_ids
|
|
153
|
+
pending = nodes_without_propositions(processed)
|
|
154
|
+
return none_pending(out, "proposition extraction") if pending.none?
|
|
155
|
+
|
|
156
|
+
out.puts "Processing #{pending.count} nodes for proposition extraction..."
|
|
157
|
+
out.puts "(Nodes already processed: #{processed.size})\n"
|
|
158
|
+
counts = DatabaseCommands.extract_all_propositions(pending, Admin.proposition_robot('proposition_extractor'), out)
|
|
159
|
+
Admin.print_counts("\nCompleted:", {
|
|
160
|
+
'Nodes processed' => counts[:ok],
|
|
161
|
+
'Propositions created' => counts[:created],
|
|
162
|
+
'Failed' => counts[:failed]
|
|
163
|
+
}, out:)
|
|
164
|
+
counts
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
# Run every process_* command in turn
|
|
168
|
+
#
|
|
169
|
+
# @return [Array<Hash, nil>] each step's counts ({ ok:, failed: }; nil when it had nothing to do)
|
|
170
|
+
#
|
|
171
|
+
def process_all(out: $stdout)
|
|
172
|
+
steps = [process_embeddings(out:), process_tags(out:), process_enabled_entities(out:), process_propositions(out:)]
|
|
173
|
+
out.puts "\nAll pending jobs processed!"
|
|
174
|
+
steps
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# Runs the process command +name+ and checks what it did (see succeeded!)
|
|
178
|
+
#
|
|
179
|
+
# @param name [Symbol] :process_tags, :process_all, :reprocess_embeddings, ...
|
|
180
|
+
# @return [Hash, nil, Array<Hash, nil>] the command's counts
|
|
181
|
+
# @raise [HTM::Admin::Error] when it failed on every node
|
|
182
|
+
#
|
|
183
|
+
def checked(name) = succeeded!(public_send(name))
|
|
184
|
+
|
|
185
|
+
# Checks what process commands returned: one that processed no node
|
|
186
|
+
# and failed on at least one did not do its work
|
|
187
|
+
#
|
|
188
|
+
# @param results [Hash, nil, Array<Hash, nil>] a command's counts ({ ok:, failed: }), or several commands'
|
|
189
|
+
# @return [Hash, nil, Array<Hash, nil>] +results+
|
|
190
|
+
# @raise [HTM::Admin::Error] when a command failed on every node
|
|
191
|
+
#
|
|
192
|
+
def succeeded!(results)
|
|
193
|
+
fruitless = [results].flatten.grep(Hash).find { it[:ok].zero? && it[:failed].positive? }
|
|
194
|
+
return results unless fruitless
|
|
195
|
+
|
|
196
|
+
raise Admin::Error, "Error: nothing was processed: all #{fruitless[:failed]} nodes failed (see the errors above)"
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
# Regenerate the embedding of every node, after confirmation
|
|
200
|
+
#
|
|
201
|
+
# @return [Hash, nil] { ok:, failed: }, nil when cancelled or there are no nodes
|
|
202
|
+
#
|
|
203
|
+
def reprocess_embeddings(input: $stdin, out: $stdout)
|
|
204
|
+
prompt = "This will regenerate embeddings for ALL nodes. Are you sure? (yes/no): "
|
|
205
|
+
return Admin.cancelled(out) unless Admin.confirmed?(prompt, input:, out:)
|
|
206
|
+
|
|
207
|
+
prepare!
|
|
208
|
+
process(HTM::Models::Node.dataset, 'Embeddings', "embedding", out) { |node, _bar| Admin.embed!(node) }
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
# Print nodes older than STALE_AFTER still missing an embedding or tags
|
|
212
|
+
def failed(out: $stdout, now: Time.now)
|
|
213
|
+
Admin.connect!
|
|
214
|
+
cutoff = Sequel.lit('created_at < ?', now - STALE_AFTER)
|
|
215
|
+
out.puts "Nodes with Processing Issues"
|
|
216
|
+
out.puts "=" * 60
|
|
217
|
+
print_stale(nodes_without_embeddings.where(cutoff), "embeddings", out, now)
|
|
218
|
+
print_stale(nodes_without_tags.where(cutoff), "tags", out, now)
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
def print_stale(dataset, missing, out, now)
|
|
222
|
+
count = dataset.count
|
|
223
|
+
if count.zero?
|
|
224
|
+
out.puts "\n✓ No old nodes without #{missing}"
|
|
225
|
+
return
|
|
226
|
+
end
|
|
227
|
+
|
|
228
|
+
out.puts "\nNodes without #{missing} (>1 hour old):"
|
|
229
|
+
dataset.limit(10).each { out.puts " Node #{it.id}: created #{Admin.time_ago(it.created_at, now:)}" }
|
|
230
|
+
out.puts " ... and #{count - 10} more" if count > 10
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
# Clear every embedding and tag, after confirmation
|
|
234
|
+
#
|
|
235
|
+
# @return [Boolean, nil] true once cleared, nil when cancelled
|
|
236
|
+
#
|
|
237
|
+
def clear_all(input: $stdin, out: $stdout)
|
|
238
|
+
prompt = "This will clear ALL embeddings and tags. Are you sure? (yes/no): "
|
|
239
|
+
return Admin.cancelled(out) unless Admin.confirmed?(prompt, input:, out:)
|
|
240
|
+
|
|
241
|
+
Admin.connect!
|
|
242
|
+
out.puts "Clearing embeddings..."
|
|
243
|
+
HTM::Models::Node.dataset.update(embedding: nil)
|
|
244
|
+
out.puts "Clearing tags..."
|
|
245
|
+
HTM::Models::NodeTag.dataset.delete
|
|
246
|
+
HTM::Models::Tag.dataset.delete
|
|
247
|
+
out.puts "Done! All embeddings and tags cleared."
|
|
248
|
+
true
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
def prepare!
|
|
252
|
+
Admin.connect!
|
|
253
|
+
HTM.configure
|
|
254
|
+
end
|
|
255
|
+
|
|
256
|
+
# Run the block over +dataset+ under a progress bar and report the counts
|
|
257
|
+
def process(dataset, title, what, out, &)
|
|
258
|
+
return none_pending(out, what) if dataset.none?
|
|
259
|
+
|
|
260
|
+
out.puts "Processing #{dataset.count} pending #{what} jobs...\n"
|
|
261
|
+
counts = Admin.each_with_progress(dataset, title, out:, &)
|
|
262
|
+
Admin.print_counts("\nCompleted:", {
|
|
263
|
+
'Processed' => counts[:ok],
|
|
264
|
+
'Failed' => counts[:failed]
|
|
265
|
+
}, out:)
|
|
266
|
+
counts
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
def none_pending(out, what)
|
|
270
|
+
out.puts "No pending #{what} jobs"
|
|
271
|
+
nil
|
|
272
|
+
end
|
|
273
|
+
end
|
|
274
|
+
end
|
|
275
|
+
end
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class HTM
|
|
4
|
+
module Admin
|
|
5
|
+
# What the entity commands share (`htm entities ...`, `htm enrich
|
|
6
|
+
# process_entities`, the statistics): finding an entity from a command
|
|
7
|
+
# line, counting entities, extracting a node's entities, and the
|
|
8
|
+
# rebuild that asks first.
|
|
9
|
+
#
|
|
10
|
+
# The module functions print nothing; Console runs rebuild against a
|
|
11
|
+
# given terminal.
|
|
12
|
+
module EntityCommands
|
|
13
|
+
module_function
|
|
14
|
+
|
|
15
|
+
# The entity a command-line NAME stands for: a name, an alias or an id
|
|
16
|
+
#
|
|
17
|
+
# @param name [String]
|
|
18
|
+
# @param type [String, nil] entity type, for a name several types share
|
|
19
|
+
# @param option [String] the command's option that takes the type, for the error message
|
|
20
|
+
# @return [HTM::Models::Entity] the canonical entity
|
|
21
|
+
# @raise [HTM::NotFoundError] when memory knows no such entity
|
|
22
|
+
# @raise [HTM::Admin::Error] when the name stands for several entities, or no entity has the type
|
|
23
|
+
#
|
|
24
|
+
def find(name, type = nil, option: '--type')
|
|
25
|
+
HTM::EntityLookup.find!(name, type: known_type!(type))
|
|
26
|
+
rescue HTM::EntityError => e
|
|
27
|
+
raise Admin::Error, "#{e.message}#{", or pass #{option} TYPE" unless type}"
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# What names a merged entity for `htm entities unmerge`: its own name,
|
|
31
|
+
# or its id when +name+ is digits and no merged entity is called that
|
|
32
|
+
#
|
|
33
|
+
# @param name [String]
|
|
34
|
+
# @return [String, Integer]
|
|
35
|
+
#
|
|
36
|
+
def merged_reference(name)
|
|
37
|
+
name.match?(/\A\d+\z/) && HTM::Models::Entity.merged.named(name).empty? ? name.to_i : name
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Entities from NAME:TYPE arguments (`htm remember --entities`). The
|
|
41
|
+
# type follows the last colon, so a name may contain colons.
|
|
42
|
+
#
|
|
43
|
+
# @param pairs [Array<String>, nil] e.g. ["Alice Chen:person", "Globex:organization"]
|
|
44
|
+
# @return [Array<Hash>] [{ name:, type: }]
|
|
45
|
+
# @raise [HTM::Admin::Error] for an argument without a name or a type
|
|
46
|
+
#
|
|
47
|
+
def parse_known(pairs) = Array(pairs).map { known_entity(it) }
|
|
48
|
+
|
|
49
|
+
# @return [Hash] { name:, type: } from "NAME:TYPE"
|
|
50
|
+
# @raise [HTM::Admin::Error] unless both are there and the type is configured
|
|
51
|
+
def known_entity(pair)
|
|
52
|
+
name, _colon, type = pair.to_s.rpartition(':').map(&:strip)
|
|
53
|
+
raise Admin::Error, "Error: --entities takes NAME:TYPE (got #{pair.inspect})" if name.empty? || type.empty?
|
|
54
|
+
|
|
55
|
+
{ name:, type: type!(type) }
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# @param type [String] an entity type from the command line
|
|
59
|
+
# @param types [Array<String>] the configured types
|
|
60
|
+
# @return [String] +type+
|
|
61
|
+
# @raise [HTM::Admin::Error] naming the configured types, unless it is one of them
|
|
62
|
+
def type!(type, types = HTM.config.entity_types) = type_error { HTM::NodeView.configured_entity_type!(type, types) }
|
|
63
|
+
|
|
64
|
+
# @param type [String, nil] an entity type a command filters or looks up by; several separated by commas
|
|
65
|
+
# @return [String, nil] +type+
|
|
66
|
+
# @raise [HTM::Admin::Error] naming the known types (the configured ones and those stored
|
|
67
|
+
# entities have), unless it is one of them
|
|
68
|
+
def known_type!(type) = type_error { HTM::NodeView.entity_type!(type) }
|
|
69
|
+
|
|
70
|
+
# @param filters [Hash] search filters, maybe with entity_type:
|
|
71
|
+
# @return [Hash] +filters+
|
|
72
|
+
# @raise [HTM::Admin::Error] for an entity_type that is not known (see known_type!)
|
|
73
|
+
def typed(filters)
|
|
74
|
+
known_type!(filters[:entity_type])
|
|
75
|
+
filters
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Runs the block, which checks an entity type (HTM::NodeView)
|
|
79
|
+
#
|
|
80
|
+
# @raise [HTM::Admin::Error] with the check's message as the command line prints it
|
|
81
|
+
def type_error
|
|
82
|
+
yield
|
|
83
|
+
rescue HTM::EntityError => e
|
|
84
|
+
raise Admin::Error, "Error: #{e.message}"
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Entity counts across memory
|
|
88
|
+
#
|
|
89
|
+
# @return [Hash] { total:, merged:, aliases:, mentions:, by_type: } where total counts the
|
|
90
|
+
# entities standing for themselves, merged those merged into another, mentions the
|
|
91
|
+
# node_entities rows on active nodes, and by_type the total per type, largest first
|
|
92
|
+
#
|
|
93
|
+
def counts
|
|
94
|
+
standing = HTM::Models::Entity.canonical
|
|
95
|
+
{
|
|
96
|
+
total: standing.count, merged: HTM::Models::Entity.merged.count,
|
|
97
|
+
aliases: HTM::Models::EntityAlias.count, mentions: HTM::Models::NodeEntity.on_active_nodes.count,
|
|
98
|
+
by_type: by_type(standing.group_and_count(:entity_type).all)
|
|
99
|
+
}
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# @param rows [Array<#[]>] rows with :entity_type and :count
|
|
103
|
+
# @return [Hash{String => Integer}] count per type, largest first (ties by name)
|
|
104
|
+
def by_type(rows)
|
|
105
|
+
rows.to_h { [it[:entity_type], it[:count]] }.sort_by { |type, count| [-count, type] }.to_h
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# @return [String] "person 3, organization 2", or "none"
|
|
109
|
+
def type_list(by_type) = by_type.empty? ? 'none' : by_type.map { |type, count| "#{type} #{count}" }.join(', ')
|
|
110
|
+
|
|
111
|
+
# @return [Sequel::Dataset] active nodes with no entity mention that extraction has not
|
|
112
|
+
# examined yet, less the propositions the propositions job stored (they inherit theirs
|
|
113
|
+
# from their sources; a file chunk or a node remembered as extracted is extracted);
|
|
114
|
+
# an examined node carries HTM::EnrichmentStamp's entities stamp
|
|
115
|
+
def nodes_awaiting_entities
|
|
116
|
+
HTM::Models::Node.not_extracted_propositions
|
|
117
|
+
.exclude(HTM::Models::Node::ID => HTM::Models::NodeEntity.select(:node_id))
|
|
118
|
+
.exclude(HTM::EnrichmentStamp.stamped(HTM::Jobs::GenerateEntitiesJob::STAMP))
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# @return [Integer] active nodes that mention an entity
|
|
122
|
+
def nodes_with_entities
|
|
123
|
+
HTM::Models::Node.where(HTM::Models::Node::ID => HTM::Models::NodeEntity.select(:node_id)).count
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Extract +node+'s entities with the LLM and store them in place of
|
|
127
|
+
# the mentions it had; its propositions inherit them again
|
|
128
|
+
# (HTM::Jobs::GenerateEntitiesJob.rebuild)
|
|
129
|
+
#
|
|
130
|
+
# @param node [HTM::Models::Node]
|
|
131
|
+
# @return [Integer] mentions the node has afterwards
|
|
132
|
+
# @raise [HTM::Admin::Error] when extraction failed (the node's mentions are unchanged)
|
|
133
|
+
#
|
|
134
|
+
def extract!(node)
|
|
135
|
+
HTM::Jobs::GenerateEntitiesJob.rebuild(node_id: node.id) or
|
|
136
|
+
raise Admin::Error, 'entity extraction failed (the log says why)'
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# What rebuild will do, for the confirmation prompt
|
|
140
|
+
#
|
|
141
|
+
# @param node_count [Integer] nodes to extract from
|
|
142
|
+
# @param mentions [Integer] mentions stored now
|
|
143
|
+
# @return [Array<String>]
|
|
144
|
+
#
|
|
145
|
+
def rebuild_plan(node_count, mentions)
|
|
146
|
+
[
|
|
147
|
+
"This will:",
|
|
148
|
+
" - Extract entities again for #{node_count} nodes: one LLM call per node",
|
|
149
|
+
" - Replace the #{mentions} entity mentions stored now, propositions' included",
|
|
150
|
+
" - Delete hand-linked mentions too (htm entities add, htm remember --entities)",
|
|
151
|
+
"\nEntities, aliases and merges stay. A node whose extraction fails keeps its mentions.",
|
|
152
|
+
DatabaseCommands::Console::LONG_RUNNING
|
|
153
|
+
]
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# Extract every node's entities again, after confirmation (see Console#rebuild)
|
|
157
|
+
#
|
|
158
|
+
# @param confirm [Boolean, nil] skip the confirmation prompt (--yes)
|
|
159
|
+
# @return [Hash, nil] { ok:, failed: }, nil when aborted
|
|
160
|
+
#
|
|
161
|
+
def rebuild(confirm: nil) = Console.new(assume_yes: confirm).rebuild
|
|
162
|
+
|
|
163
|
+
# The entity commands that ask before they change anything
|
|
164
|
+
#
|
|
165
|
+
# @example
|
|
166
|
+
# HTM::Admin::EntityCommands::Console.new(input: StringIO.new("yes\n")).rebuild
|
|
167
|
+
#
|
|
168
|
+
class Console < Admin::Console
|
|
169
|
+
# Extract entities again for every non-proposition node, replacing
|
|
170
|
+
# the mentions stored now (hand-linked ones included); propositions
|
|
171
|
+
# inherit again from their sources
|
|
172
|
+
#
|
|
173
|
+
# @return [Hash, nil] { ok:, failed: }, nil when aborted
|
|
174
|
+
#
|
|
175
|
+
def rebuild
|
|
176
|
+
EnrichCommands.prepare!
|
|
177
|
+
sources = HTM::Models::Node.not_extracted_propositions
|
|
178
|
+
heading("HTM Entities Rebuild", 40)
|
|
179
|
+
out.puts EntityCommands.rebuild_plan(sources.count, HTM::Models::NodeEntity.count)
|
|
180
|
+
return aborted unless proceed?
|
|
181
|
+
|
|
182
|
+
reextract(sources)
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
private
|
|
186
|
+
|
|
187
|
+
# @return [Hash] { ok:, failed: }
|
|
188
|
+
def reextract(sources)
|
|
189
|
+
out.puts "\nExtracting entities..."
|
|
190
|
+
counts = each_with_progress(sources, 'Entities') { |node, _bar| EntityCommands.extract!(node) }
|
|
191
|
+
totals = EntityCommands.counts
|
|
192
|
+
print_counts("\nRebuild complete!", {
|
|
193
|
+
'Nodes processed' => counts[:ok],
|
|
194
|
+
'Errors' => counts[:failed],
|
|
195
|
+
'Entity mentions' => totals[:mentions],
|
|
196
|
+
'Entities' => "#{totals[:total]} (#{EntityCommands.type_list(totals[:by_type])})"
|
|
197
|
+
})
|
|
198
|
+
counts
|
|
199
|
+
end
|
|
200
|
+
end
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
end
|