ruby-spacy 0.6.0 → 0.8.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 +4 -4
- data/CHANGELOG.md +75 -92
- data/Gemfile +7 -0
- data/README.md +68 -15
- data/Rakefile +6 -0
- data/docs/syntax_trees.md +59 -0
- data/examples/llm/anthropic_chat.rb +1 -1
- data/examples/openai_integration/openai_completion.rb +2 -3
- data/examples/openai_integration/openai_query_1.rb +2 -3
- data/examples/openai_integration/openai_query_2.rb +2 -3
- data/examples/openai_integration/openai_query_3.rb +2 -3
- data/examples/openai_integration/openai_query_4.rb +2 -3
- data/examples/rsyntaxtree/outputs/tree_ar_projection.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_de_projection.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_en_chunks.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_en_morphology.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_en_path.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_en_projection.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_ja_chunks.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_ja_projection.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_ru_morphology.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_ru_projection.png +0 -0
- data/examples/rsyntaxtree/outputs/tree_zh_projection.png +0 -0
- data/examples/rsyntaxtree/syntax_tree_ar.rb +36 -0
- data/examples/rsyntaxtree/syntax_tree_de.rb +19 -0
- data/examples/rsyntaxtree/syntax_tree_en.rb +30 -0
- data/examples/rsyntaxtree/syntax_tree_ja.rb +21 -0
- data/examples/rsyntaxtree/syntax_tree_ru.rb +23 -0
- data/examples/rsyntaxtree/syntax_tree_zh.rb +21 -0
- data/lib/ruby-spacy/anthropic_client.rb +8 -7
- data/lib/ruby-spacy/anthropic_helper.rb +15 -7
- data/lib/ruby-spacy/llm_client_base.rb +69 -12
- data/lib/ruby-spacy/openai_client.rb +27 -16
- data/lib/ruby-spacy/openai_helper.rb +12 -7
- data/lib/ruby-spacy/syntax_tree.rb +349 -0
- data/lib/ruby-spacy/version.rb +1 -1
- data/lib/ruby-spacy.rb +138 -34
- data/ruby-spacy.gemspec +8 -1
- metadata +24 -4
- data/.github/FUNDING.yml +0 -6
- data/.github/workflows/ci.yml +0 -74
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Spacy
|
|
4
|
+
# Converts spaCy parse results into rsyntaxtree bracket notation and renders
|
|
5
|
+
# them with the rsyntaxtree gem. This is an internal implementation module;
|
|
6
|
+
# the public API is {Doc#syntax_tree} and {Span#syntax_tree}.
|
|
7
|
+
#
|
|
8
|
+
# rsyntaxtree is a soft dependency: it is required (>= MIN_RSYNTAXTREE) on
|
|
9
|
+
# the first call, not at load time.
|
|
10
|
+
module SyntaxTree
|
|
11
|
+
FORMATS = %i[bracket svg png pdf tikz json].freeze
|
|
12
|
+
STYLES = %i[projection chunks].freeze
|
|
13
|
+
|
|
14
|
+
# Oldest rsyntaxtree with everything used here: RSyntaxTree.escape,
|
|
15
|
+
# OPTION_KEYS, leaf_align, leafstyle "dashed", and highlighted paths (+=)
|
|
16
|
+
MIN_RSYNTAXTREE = "2.10.0"
|
|
17
|
+
|
|
18
|
+
# rsyntaxtree drawing defaults chosen for the wide, shallow trees produced
|
|
19
|
+
# here: the words line up on the bottom row so the sentence reads straight
|
|
20
|
+
# across, with a dashed line down to each from its tag. User-supplied
|
|
21
|
+
# options take precedence (except hyphen, which the escaping depends on).
|
|
22
|
+
RENDER_DEFAULTS = {
|
|
23
|
+
hyphen: "literal",
|
|
24
|
+
polyline: "on",
|
|
25
|
+
tidy: "medium",
|
|
26
|
+
leafstyle: "dashed",
|
|
27
|
+
leaf_align: "words",
|
|
28
|
+
color: "modern"
|
|
29
|
+
}.freeze
|
|
30
|
+
|
|
31
|
+
# Marks the two ends of a highlighted path (`path:`) on their leaf labels
|
|
32
|
+
PATH_MARKER = "+=1"
|
|
33
|
+
|
|
34
|
+
# Phrase label mapping from the head's POS tag
|
|
35
|
+
PHRASE_LABEL = {
|
|
36
|
+
"NOUN" => "NP", "PROPN" => "NP", "PRON" => "NP", "NUM" => "NP",
|
|
37
|
+
"VERB" => "VP", "AUX" => "VP", "ADP" => "PP", "ADJ" => "AdjP",
|
|
38
|
+
"ADV" => "AdvP", "DET" => "DP", "SCONJ" => "CP", "CCONJ" => "ConjP"
|
|
39
|
+
}.freeze
|
|
40
|
+
|
|
41
|
+
ENT_BACKGROUND = "orange"
|
|
42
|
+
|
|
43
|
+
class << self
|
|
44
|
+
# @param source [Doc, Span] the document or span to convert
|
|
45
|
+
# @return [String] the bracket notation (format: :bracket), the rendered
|
|
46
|
+
# output (SVG/TikZ/JSON text, or PNG/PDF binary), depending on format
|
|
47
|
+
def generate(source, format: :bracket, style: :projection, morphology: false,
|
|
48
|
+
entities: true, punctuation: false, path: nil, **render_opts)
|
|
49
|
+
ensure_rsyntaxtree!
|
|
50
|
+
format = format.to_sym
|
|
51
|
+
style = style.to_sym
|
|
52
|
+
render_opts = render_opts.transform_keys(&:to_sym)
|
|
53
|
+
validate_options!(format, style, render_opts)
|
|
54
|
+
|
|
55
|
+
bracket = bracket_for(source, style: style, morphology: morphology,
|
|
56
|
+
entities: entities, punctuation: punctuation, path: path)
|
|
57
|
+
return bracket if format == :bracket
|
|
58
|
+
|
|
59
|
+
# Right-to-left scripts are drawn mirrored (leaves run right to left)
|
|
60
|
+
# unless the caller says otherwise. A tree laid out left to right
|
|
61
|
+
# stacks the leaves down the page, where the script's direction plays
|
|
62
|
+
# no part. The notation itself is unaffected
|
|
63
|
+
if rtl?(source) && render_opts[:direction].to_s != "ltr"
|
|
64
|
+
render_opts = { mirror: "on" }.merge(render_opts)
|
|
65
|
+
end
|
|
66
|
+
render(bracket, format, render_opts)
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
private
|
|
70
|
+
|
|
71
|
+
# True when the source's language writes right-to-left. Asked from the
|
|
72
|
+
# pipeline itself (`Defaults.writing_system`) rather than a hardcoded
|
|
73
|
+
# language list, so external pipelines (spacy-stanza, spacy-udpipe) work
|
|
74
|
+
# too. Any failure (e.g. no `Defaults`) falls back to left-to-right;
|
|
75
|
+
# note this also swallows a genuine detection failure, so if an RTL
|
|
76
|
+
# tree ever renders unmirrored, this fallback is the first place to check
|
|
77
|
+
def rtl?(source)
|
|
78
|
+
py_nlp = source.is_a?(Spacy::Span) ? source.doc.py_nlp : source.py_nlp
|
|
79
|
+
direction = Spacy::Builtins.getattr(py_nlp.Defaults, "writing_system")["direction"]
|
|
80
|
+
direction.to_s == "rtl"
|
|
81
|
+
rescue StandardError
|
|
82
|
+
false
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def ensure_rsyntaxtree!
|
|
86
|
+
return if @loaded
|
|
87
|
+
|
|
88
|
+
begin
|
|
89
|
+
require "rsyntaxtree"
|
|
90
|
+
rescue LoadError
|
|
91
|
+
raise LoadError, "syntax_tree requires the rsyntaxtree gem (>= #{MIN_RSYNTAXTREE}): gem install rsyntaxtree"
|
|
92
|
+
end
|
|
93
|
+
if Gem::Version.new(RSyntaxTree::VERSION) < Gem::Version.new(MIN_RSYNTAXTREE)
|
|
94
|
+
raise LoadError, "syntax_tree requires rsyntaxtree >= #{MIN_RSYNTAXTREE} (found #{RSyntaxTree::VERSION})"
|
|
95
|
+
end
|
|
96
|
+
@loaded = true
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def validate_options!(format, style, render_opts)
|
|
100
|
+
unless FORMATS.include?(format)
|
|
101
|
+
raise ArgumentError, "unknown format: #{format.inspect} (expected one of: #{FORMATS.join(', ')})"
|
|
102
|
+
end
|
|
103
|
+
unless STYLES.include?(style)
|
|
104
|
+
raise ArgumentError, "unknown style: #{style.inspect} (expected one of: #{STYLES.join(', ')})"
|
|
105
|
+
end
|
|
106
|
+
if render_opts.key?(:hyphen)
|
|
107
|
+
raise ArgumentError, "hyphen: cannot be overridden (the notation is escaped for hyphen: :literal)"
|
|
108
|
+
end
|
|
109
|
+
unknown = render_opts.keys - ::OPTION_KEYS
|
|
110
|
+
unless unknown.empty?
|
|
111
|
+
raise ArgumentError,
|
|
112
|
+
"unknown rsyntaxtree option(s): #{unknown.join(', ')} (valid: #{::OPTION_KEYS.join(', ')})"
|
|
113
|
+
end
|
|
114
|
+
if format == :bracket && !render_opts.empty?
|
|
115
|
+
raise ArgumentError,
|
|
116
|
+
"drawing options (#{render_opts.keys.join(', ')}) have no effect with format: :bracket"
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def render(bracket, format, render_opts)
|
|
121
|
+
params = RENDER_DEFAULTS.merge(render_opts).merge(data: bracket)
|
|
122
|
+
gen = RSyntaxTree::RSGenerator.new(params)
|
|
123
|
+
case format
|
|
124
|
+
when :svg then gen.draw_svg
|
|
125
|
+
when :json then gen.draw_json
|
|
126
|
+
when :tikz then gen.draw_tikz
|
|
127
|
+
when :png then gen.draw_png.force_encoding(Encoding::BINARY)
|
|
128
|
+
when :pdf then gen.draw_pdf.force_encoding(Encoding::BINARY)
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
# Escapes a string for the bracket notation. `as:` follows
|
|
133
|
+
# `RSyntaxTree.escape` (:word for leaf words, :label for entity labels,
|
|
134
|
+
# :cell for AVM cells).
|
|
135
|
+
def escape(text, as:, context: nil)
|
|
136
|
+
RSyntaxTree.escape(text, as: as, hyphen: :literal, apostrophe: :keep)
|
|
137
|
+
rescue ArgumentError => e
|
|
138
|
+
where = context ? " (#{context})" : ""
|
|
139
|
+
raise ArgumentError, "syntax_tree: cannot escape#{where}: #{e.message}"
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def bracket_for(source, style:, morphology:, entities:, punctuation:, path:)
|
|
143
|
+
tokens, root, root_label = tree_scope(source)
|
|
144
|
+
marks = path_marks(source, tokens, path)
|
|
145
|
+
chunks = chunk_spans(source)
|
|
146
|
+
if chunks.nil? && style == :chunks
|
|
147
|
+
raise ArgumentError,
|
|
148
|
+
"noun chunks are not available for this language/model, so style: :chunks cannot be used"
|
|
149
|
+
end
|
|
150
|
+
chunks ||= []
|
|
151
|
+
ents = entities ? ent_map(source) : {}
|
|
152
|
+
|
|
153
|
+
bracket = case style
|
|
154
|
+
when :chunks
|
|
155
|
+
chunks_bracket(tokens, chunks, ents, morphology: morphology,
|
|
156
|
+
punctuation: punctuation, marks: marks)
|
|
157
|
+
else
|
|
158
|
+
projection_bracket(root, chunks, ents, root_label: root_label,
|
|
159
|
+
morphology: morphology, punctuation: punctuation, marks: marks)
|
|
160
|
+
end
|
|
161
|
+
# Escaping turns any "+=" in the text into "\+\=", so every marker
|
|
162
|
+
# found is one placed on a leaf
|
|
163
|
+
if bracket.scan(PATH_MARKER).size != marks.size
|
|
164
|
+
raise ArgumentError,
|
|
165
|
+
"path: a token is not drawn in the tree (punctuation is left out unless punctuation: true)"
|
|
166
|
+
end
|
|
167
|
+
bracket
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# Doc-based indices of the two tokens that `path:` connects, or [] when
|
|
171
|
+
# no path is asked for
|
|
172
|
+
def path_marks(source, tokens, path)
|
|
173
|
+
return [] if path.nil?
|
|
174
|
+
|
|
175
|
+
unless path.is_a?(Array) && path.size == 2 && path.all?(Spacy::Token)
|
|
176
|
+
raise ArgumentError, "path: takes two tokens, e.g. path: [doc[1], doc[4]]"
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
py_doc = source.is_a?(Spacy::Span) ? source.py_span.doc : source.py_doc
|
|
180
|
+
range = tokens.first.i..tokens.last.i
|
|
181
|
+
path.each do |token|
|
|
182
|
+
next if Spacy::Builtins.id(token.py_token.doc) == Spacy::Builtins.id(py_doc) && range.cover?(token.i)
|
|
183
|
+
|
|
184
|
+
raise ArgumentError, "path: #{token.text.inspect} is not a token of this #{source.class.name.split('::').last.downcase}"
|
|
185
|
+
end
|
|
186
|
+
raise ArgumentError, "path: the two tokens must differ" if path[0].i == path[1].i
|
|
187
|
+
|
|
188
|
+
path.map(&:i)
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# Returns [tokens, root_token, root_label]. All positions are doc-based
|
|
192
|
+
# (Span#tokens / Token#i are doc-based, which matches chunk and entity
|
|
193
|
+
# offsets).
|
|
194
|
+
def tree_scope(source)
|
|
195
|
+
case source
|
|
196
|
+
when Spacy::Doc
|
|
197
|
+
py_doc = source.py_doc
|
|
198
|
+
unless py_doc.has_annotation("DEP")
|
|
199
|
+
raise ArgumentError, "syntax_tree requires a dependency parse (the pipeline has no parser)"
|
|
200
|
+
end
|
|
201
|
+
if py_doc.has_annotation("SENT_START") && source.sents.size > 1
|
|
202
|
+
raise ArgumentError,
|
|
203
|
+
"syntax_tree requires a single sentence; " \
|
|
204
|
+
"use doc.sents.map { |s| s.syntax_tree } for a multi-sentence doc"
|
|
205
|
+
end
|
|
206
|
+
tokens = source.tokens
|
|
207
|
+
# The root is the token that is its own head. Comparing dep strings
|
|
208
|
+
# would tie this to an annotation scheme (spaCy's trained pipelines
|
|
209
|
+
# use "ROOT" while UD-style pipelines such as Stanza use "root")
|
|
210
|
+
root = tokens.find { |t| t.head.i == t.i }
|
|
211
|
+
raise ArgumentError, "syntax_tree: no root token found (no dependency parse)" unless root
|
|
212
|
+
|
|
213
|
+
[tokens, root, "S"]
|
|
214
|
+
when Spacy::Span
|
|
215
|
+
unless source.py_span.doc.has_annotation("DEP")
|
|
216
|
+
raise ArgumentError, "syntax_tree requires a dependency parse (the pipeline has no parser)"
|
|
217
|
+
end
|
|
218
|
+
tokens = source.tokens
|
|
219
|
+
raise ArgumentError, "syntax_tree: empty span" if tokens.empty?
|
|
220
|
+
|
|
221
|
+
first_i = tokens.first.i
|
|
222
|
+
last_i = tokens.last.i
|
|
223
|
+
roots = tokens.select { |t| t.head.i == t.i || t.head.i < first_i || t.head.i > last_i }
|
|
224
|
+
unless roots.size == 1
|
|
225
|
+
raise ArgumentError,
|
|
226
|
+
"syntax_tree requires a span with a single root (e.g. a sentence from doc.sents)"
|
|
227
|
+
end
|
|
228
|
+
root = roots.first
|
|
229
|
+
unless root.left_edge.i == first_i && root.right_edge.i == last_i
|
|
230
|
+
raise ArgumentError,
|
|
231
|
+
"syntax_tree requires a span that is a complete subtree " \
|
|
232
|
+
"(e.g. a sentence from doc.sents or a noun chunk)"
|
|
233
|
+
end
|
|
234
|
+
is_sentence = source.py_span.sent.start == source.py_span.start &&
|
|
235
|
+
source.py_span.sent.end == source.py_span.end
|
|
236
|
+
[tokens, root, is_sentence ? "S" : PHRASE_LABEL.fetch(root.pos, "XP")]
|
|
237
|
+
else
|
|
238
|
+
raise ArgumentError, "syntax_tree expects a Spacy::Doc or Spacy::Span"
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
# Noun chunk spans as doc-based [start, end) pairs, or nil when the
|
|
243
|
+
# language/model has no noun chunk iterator (spaCy error E894).
|
|
244
|
+
def chunk_spans(source)
|
|
245
|
+
source.noun_chunks.map { |c| [c.py_span.start, c.py_span.end] }
|
|
246
|
+
rescue PyCall::PyError => e
|
|
247
|
+
raise unless e.message.include?("E894")
|
|
248
|
+
|
|
249
|
+
nil
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
# Entity spans as a doc-based [start, end) => label map
|
|
253
|
+
def ent_map(source)
|
|
254
|
+
source.ents.to_h { |e| [[e.py_span.start, e.py_span.end], e.label] }
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
def leaf(token, morphology:, marks:)
|
|
258
|
+
word = escape(token.text, as: :word, context: "token #{token.text.inspect}")
|
|
259
|
+
mark = marks.include?(token.i) ? PATH_MARKER : ""
|
|
260
|
+
return "[#{token.pos}#{mark} #{word}]" unless morphology
|
|
261
|
+
|
|
262
|
+
rows = ["pos\\t#{escape(token.pos, as: :cell)}"]
|
|
263
|
+
morph = token.morphology(hash: false)
|
|
264
|
+
unless morph.empty?
|
|
265
|
+
morph.split("|").each do |kv|
|
|
266
|
+
k, v = kv.split("=", 2)
|
|
267
|
+
rows << "#{escape(k, as: :cell)}\\t#{escape(v, as: :cell)}"
|
|
268
|
+
end
|
|
269
|
+
end
|
|
270
|
+
"[#(#{rows.join('\n')}#)#{mark} #{word}]"
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
# "%NP" for a bare chunk; "%@orange:NP\nLABEL" for one matching an entity
|
|
274
|
+
def chunk_label(base, ent_label)
|
|
275
|
+
return "%#{base}" unless ent_label
|
|
276
|
+
|
|
277
|
+
"%@#{ENT_BACKGROUND}:#{base}\\n#{escape(ent_label, as: :label, context: 'entity label')}"
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
# A shallow tree: [S ...] with chunks as [%NP [POS w] ...] and other
|
|
281
|
+
# tokens as plain leaves. Chunks matching an entity get a colored
|
|
282
|
+
# background and a second label line.
|
|
283
|
+
def chunks_bracket(tokens, chunks, ents, morphology:, punctuation:, marks:)
|
|
284
|
+
i = 0
|
|
285
|
+
parts = []
|
|
286
|
+
while i < tokens.size
|
|
287
|
+
token = tokens[i]
|
|
288
|
+
chunk = chunks.find { |s, _e| s == token.i }
|
|
289
|
+
if chunk
|
|
290
|
+
s, e = chunk
|
|
291
|
+
chunk_tokens = tokens.select { |t| t.i >= s && t.i < e }
|
|
292
|
+
label = chunk_label("NP", ents[[s, e]])
|
|
293
|
+
parts << "[#{label} #{chunk_tokens.map { |t| leaf(t, morphology: morphology, marks: marks) }.join(' ')}]"
|
|
294
|
+
i += chunk_tokens.size
|
|
295
|
+
else
|
|
296
|
+
parts << leaf(token, morphology: morphology, marks: marks) unless token.pos == "PUNCT" && !punctuation
|
|
297
|
+
i += 1
|
|
298
|
+
end
|
|
299
|
+
end
|
|
300
|
+
"[S #{parts.join(' ')}]"
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
# Head projection: each head projects a phrase node over its dependents
|
|
304
|
+
# and itself in word order. A phrase whose span coincides with a noun
|
|
305
|
+
# chunk gets a background; when the chunk containing the head is
|
|
306
|
+
# narrower than the projection (NP -> NP PP), the chunk's tokens are
|
|
307
|
+
# wrapped in an inner [%NP ...]. A single-token chunk (a frequent case
|
|
308
|
+
# for named entities) is wrapped as [%NP leaf] so that the background
|
|
309
|
+
# and entity label are not lost.
|
|
310
|
+
def projection_bracket(token, chunks, ents, root_label:, morphology:, punctuation:, marks:)
|
|
311
|
+
kids = token.children.to_a
|
|
312
|
+
kids = kids.reject { |k| k.pos == "PUNCT" } unless punctuation
|
|
313
|
+
if kids.empty?
|
|
314
|
+
node = leaf(token, morphology: morphology, marks: marks)
|
|
315
|
+
single = [token.i, token.i + 1]
|
|
316
|
+
return node unless chunks.include?(single)
|
|
317
|
+
|
|
318
|
+
return "[#{chunk_label('NP', ents[single])} #{node}]"
|
|
319
|
+
end
|
|
320
|
+
|
|
321
|
+
label = root_label || PHRASE_LABEL.fetch(token.pos, "XP")
|
|
322
|
+
span = [token.left_edge.i, token.right_edge.i + 1]
|
|
323
|
+
label = chunk_label(label, ents[span]) if chunks.include?(span)
|
|
324
|
+
|
|
325
|
+
ordered = (kids + [token]).sort_by(&:i)
|
|
326
|
+
render_node = lambda do |t|
|
|
327
|
+
if t.i == token.i
|
|
328
|
+
leaf(t, morphology: morphology, marks: marks)
|
|
329
|
+
else
|
|
330
|
+
projection_bracket(t, chunks, ents, root_label: nil,
|
|
331
|
+
morphology: morphology, punctuation: punctuation, marks: marks)
|
|
332
|
+
end
|
|
333
|
+
end
|
|
334
|
+
|
|
335
|
+
inner = chunks.find { |s, e| (s...e).cover?(token.i) && [s, e] != span }
|
|
336
|
+
if inner
|
|
337
|
+
s, e = inner
|
|
338
|
+
inside, = ordered.partition { |t| (s...e).cover?(t.i) }
|
|
339
|
+
inner_node = "[#{chunk_label('NP', ents[inner])} #{inside.map(&render_node).join(' ')}]"
|
|
340
|
+
parts = ordered.map { |t| inside.include?(t) ? (t.equal?(inside.first) ? inner_node : nil) : render_node.call(t) }
|
|
341
|
+
parts = parts.compact
|
|
342
|
+
else
|
|
343
|
+
parts = ordered.map(&render_node)
|
|
344
|
+
end
|
|
345
|
+
"[#{label} #{parts.join(' ')}]"
|
|
346
|
+
end
|
|
347
|
+
end
|
|
348
|
+
end
|
|
349
|
+
end
|
data/lib/ruby-spacy/version.rb
CHANGED
data/lib/ruby-spacy.rb
CHANGED
|
@@ -6,6 +6,7 @@ require_relative "ruby-spacy/openai_client"
|
|
|
6
6
|
require_relative "ruby-spacy/anthropic_client"
|
|
7
7
|
require_relative "ruby-spacy/openai_helper"
|
|
8
8
|
require_relative "ruby-spacy/anthropic_helper"
|
|
9
|
+
require_relative "ruby-spacy/syntax_tree"
|
|
9
10
|
require "pycall"
|
|
10
11
|
require "json"
|
|
11
12
|
require "base64"
|
|
@@ -344,6 +345,44 @@ module Spacy
|
|
|
344
345
|
PyDisplacy.render(py_doc, style: style, options: { compact: compact }, jupyter: false)
|
|
345
346
|
end
|
|
346
347
|
|
|
348
|
+
# Generates a syntax tree in rsyntaxtree bracket notation, or renders it
|
|
349
|
+
# with the rsyntaxtree gem.
|
|
350
|
+
#
|
|
351
|
+
# Requires the rsyntaxtree gem (>= 2.10.0) at call time (it is a soft
|
|
352
|
+
# dependency; install it with `gem install rsyntaxtree`). The doc must
|
|
353
|
+
# contain a single sentence; for a multi-sentence doc, use
|
|
354
|
+
# `doc.sents.map { |s| s.syntax_tree }`.
|
|
355
|
+
#
|
|
356
|
+
# Note that the bracket notation is rsyntaxtree-flavored: it may contain
|
|
357
|
+
# rsyntaxtree-specific markup such as AVMs (`#(...#)`), region backgrounds
|
|
358
|
+
# (`%`), and in-word space joins (`<>`).
|
|
359
|
+
#
|
|
360
|
+
# @param format [Symbol] `:bracket` (default; the notation string),
|
|
361
|
+
# `:svg`, `:png`, `:pdf`, `:tikz`, or `:json`. `:png` and `:pdf` return
|
|
362
|
+
# a binary string
|
|
363
|
+
# @param style [Symbol] `:projection` (default; head-projection
|
|
364
|
+
# phrase-structure-like tree) or `:chunks` (shallow tree with noun chunks)
|
|
365
|
+
# @param morphology [Boolean] attach a morphology AVM to each leaf
|
|
366
|
+
# @param entities [Boolean] mark chunks that match a named entity with a
|
|
367
|
+
# colored background and the entity label
|
|
368
|
+
# @param punctuation [Boolean] keep punctuation tokens
|
|
369
|
+
# @param path [Array<Token>, nil] two tokens whose connecting path through
|
|
370
|
+
# the tree is drawn highlighted; in a projection tree, this is the
|
|
371
|
+
# dependency path between them
|
|
372
|
+
# @param render_opts [Hash] rsyntaxtree drawing options (e.g. `fontsize:`).
|
|
373
|
+
# `hyphen:` cannot be overridden
|
|
374
|
+
# @return [String] the bracket notation or the rendered output
|
|
375
|
+
# @example
|
|
376
|
+
# doc.syntax_tree # => "[S [%NP [DET The] ...] ...]"
|
|
377
|
+
# doc.syntax_tree(format: :svg) # => "<svg ..."
|
|
378
|
+
# doc.syntax_tree(format: :png, fontsize: 12)
|
|
379
|
+
# doc.syntax_tree(format: :svg, path: [doc[3], doc[11]])
|
|
380
|
+
def syntax_tree(format: :bracket, style: :projection, morphology: false,
|
|
381
|
+
entities: true, punctuation: false, path: nil, **render_opts)
|
|
382
|
+
SyntaxTree.generate(self, format: format, style: style, morphology: morphology,
|
|
383
|
+
entities: entities, punctuation: punctuation, path: path, **render_opts)
|
|
384
|
+
end
|
|
385
|
+
|
|
347
386
|
# Generates a JSON string summarizing the linguistic analysis of the document.
|
|
348
387
|
# Designed to be passed as context to an LLM (e.g., via {OpenAIHelper#chat}).
|
|
349
388
|
#
|
|
@@ -409,7 +448,10 @@ module Spacy
|
|
|
409
448
|
# @param max_tokens [Integer] Alias for max_completion_tokens (deprecated, for backward compatibility)
|
|
410
449
|
# @param temperature [Float, nil] Sampling temperature (omitted from requests
|
|
411
450
|
# when nil; models that reject it are retried without it)
|
|
412
|
-
# @param model [String] The model to use (default: gpt-
|
|
451
|
+
# @param model [String] The model to use (default: gpt-6-luna)
|
|
452
|
+
# @param reasoning_effort [String, nil] Reasoning effort; "none" by
|
|
453
|
+
# default, since models such as gpt-6-luna call tools on Chat
|
|
454
|
+
# Completions only without reasoning. nil leaves it out of the request
|
|
413
455
|
# @param messages [Array<Hash>] Conversation history (for recursive tool calls). Note: this array is modified in place when tool calls occur.
|
|
414
456
|
# @param prompt [String, nil] System prompt for the query
|
|
415
457
|
# @return [String, nil] The model's response content
|
|
@@ -418,13 +460,14 @@ module Spacy
|
|
|
418
460
|
max_tokens: nil,
|
|
419
461
|
temperature: nil,
|
|
420
462
|
model: OpenAIClient::DEFAULT_MODEL,
|
|
463
|
+
reasoning_effort: "none",
|
|
421
464
|
messages: [],
|
|
422
465
|
prompt: nil,
|
|
423
466
|
response_format: nil,
|
|
424
467
|
max_tool_call_depth: 5,
|
|
425
468
|
_tool_call_depth: 0)
|
|
426
469
|
# Support both max_completion_tokens and max_tokens for backward compatibility
|
|
427
|
-
max_completion_tokens ||= max_tokens ||
|
|
470
|
+
max_completion_tokens ||= max_tokens || LLMClientBase::DEFAULT_MAX_TOKENS
|
|
428
471
|
if messages.empty?
|
|
429
472
|
messages = [
|
|
430
473
|
{ role: "system", content: prompt },
|
|
@@ -465,41 +508,26 @@ module Spacy
|
|
|
465
508
|
messages: messages,
|
|
466
509
|
max_completion_tokens: max_completion_tokens,
|
|
467
510
|
temperature: temperature,
|
|
511
|
+
reasoning_effort: reasoning_effort,
|
|
468
512
|
tools: tools,
|
|
469
513
|
tool_choice: tool_choice,
|
|
470
514
|
response_format: response_format
|
|
471
515
|
)
|
|
472
516
|
|
|
473
517
|
message = response.dig("choices", 0, "message")
|
|
518
|
+
return nil unless message
|
|
474
519
|
|
|
475
|
-
# Handle tool calls (GPT-5 format)
|
|
476
|
-
if message["tool_calls"] && !message["tool_calls"].empty?
|
|
520
|
+
# Handle tool calls (GPT-5 format), only while tools are offered
|
|
521
|
+
if tools && message["tool_calls"] && !message["tool_calls"].empty?
|
|
477
522
|
messages << message
|
|
478
523
|
|
|
524
|
+
# Every tool call needs an answer, or the next request is rejected
|
|
479
525
|
message["tool_calls"].each do |tool_call|
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
result = tokens.map do |t|
|
|
486
|
-
{
|
|
487
|
-
surface: t.text,
|
|
488
|
-
lemma: t.lemma,
|
|
489
|
-
pos: t.pos,
|
|
490
|
-
tag: t.tag,
|
|
491
|
-
dep: t.dep,
|
|
492
|
-
ent_type: t.ent_type,
|
|
493
|
-
morphology: t.morphology
|
|
494
|
-
}
|
|
495
|
-
end.to_json
|
|
496
|
-
|
|
497
|
-
messages << {
|
|
498
|
-
role: "tool",
|
|
499
|
-
tool_call_id: tool_call_id,
|
|
500
|
-
content: result
|
|
501
|
-
}
|
|
502
|
-
end
|
|
526
|
+
messages << {
|
|
527
|
+
role: "tool",
|
|
528
|
+
tool_call_id: tool_call["id"],
|
|
529
|
+
content: tool_result(tool_call["function"] || {})
|
|
530
|
+
}
|
|
503
531
|
end
|
|
504
532
|
|
|
505
533
|
# Recursive call to get final response after tool execution
|
|
@@ -508,6 +536,7 @@ module Spacy
|
|
|
508
536
|
max_completion_tokens: max_completion_tokens,
|
|
509
537
|
temperature: temperature,
|
|
510
538
|
model: model,
|
|
539
|
+
reasoning_effort: reasoning_effort,
|
|
511
540
|
messages: messages,
|
|
512
541
|
prompt: prompt,
|
|
513
542
|
response_format: response_format,
|
|
@@ -529,11 +558,11 @@ module Spacy
|
|
|
529
558
|
# @param max_tokens [Integer] Alias for max_completion_tokens (deprecated, for backward compatibility)
|
|
530
559
|
# @param temperature [Float, nil] Sampling temperature (omitted from requests
|
|
531
560
|
# when nil; models that reject it are retried without it)
|
|
532
|
-
# @param model [String] The model to use (default: gpt-
|
|
561
|
+
# @param model [String] The model to use (default: gpt-6-luna)
|
|
533
562
|
# @return [String, nil] The completed text
|
|
534
563
|
def openai_completion(access_token: nil, max_completion_tokens: nil, max_tokens: nil, temperature: nil, model: OpenAIClient::DEFAULT_MODEL)
|
|
535
564
|
# Support both max_completion_tokens and max_tokens for backward compatibility
|
|
536
|
-
max_completion_tokens ||= max_tokens ||
|
|
565
|
+
max_completion_tokens ||= max_tokens || LLMClientBase::DEFAULT_MAX_TOKENS
|
|
537
566
|
|
|
538
567
|
messages = [
|
|
539
568
|
{ role: "system", content: "Complete the text input by the user." },
|
|
@@ -574,8 +603,40 @@ module Spacy
|
|
|
574
603
|
access_token ||= ENV["OPENAI_API_KEY"]
|
|
575
604
|
raise "Error: OPENAI_API_KEY is not set" unless access_token
|
|
576
605
|
|
|
577
|
-
|
|
578
|
-
|
|
606
|
+
OpenAIClient.new(access_token: access_token)
|
|
607
|
+
end
|
|
608
|
+
|
|
609
|
+
# The content answering one tool call of openai_query (a JSON string)
|
|
610
|
+
def tool_result(function)
|
|
611
|
+
unless function["name"] == "get_tokens"
|
|
612
|
+
return { error: "unknown tool: #{function['name']}" }.to_json
|
|
613
|
+
end
|
|
614
|
+
|
|
615
|
+
args = begin
|
|
616
|
+
JSON.parse(function["arguments"])
|
|
617
|
+
rescue JSON::ParserError, TypeError
|
|
618
|
+
nil
|
|
619
|
+
end
|
|
620
|
+
# text may be left out (the whole document), but not given as a non-string
|
|
621
|
+
unless args.is_a?(Hash) && (!args.key?("text") || args["text"].is_a?(String))
|
|
622
|
+
return { error: "get_tokens takes a JSON object with a text string" }.to_json
|
|
623
|
+
end
|
|
624
|
+
|
|
625
|
+
# The model may ask about part of the document or a rewording of it
|
|
626
|
+
text = args["text"].to_s
|
|
627
|
+
doc = if text.strip.empty? || text == @text
|
|
628
|
+
self
|
|
629
|
+
else
|
|
630
|
+
begin
|
|
631
|
+
Doc.new(@py_nlp, text: text, max_retrial: 0)
|
|
632
|
+
rescue StandardError
|
|
633
|
+
return { error: "the text could not be analyzed" }.to_json
|
|
634
|
+
end
|
|
635
|
+
end
|
|
636
|
+
doc.tokens.map do |t|
|
|
637
|
+
{ surface: t.text, lemma: t.lemma, pos: t.pos, tag: t.tag, dep: t.dep,
|
|
638
|
+
ent_type: t.ent_type, morphology: t.morphology }
|
|
639
|
+
end.to_json
|
|
579
640
|
end
|
|
580
641
|
|
|
581
642
|
public
|
|
@@ -614,6 +675,12 @@ module Spacy
|
|
|
614
675
|
end
|
|
615
676
|
end
|
|
616
677
|
|
|
678
|
+
# Sentinel for "the caller gave no model argument". Distinct from nil so
|
|
679
|
+
# that an explicit nil (e.g. an unset ENV var passed straight through)
|
|
680
|
+
# still fails validation instead of silently loading the default model
|
|
681
|
+
NO_MODEL = Object.new.freeze
|
|
682
|
+
private_constant :NO_MODEL
|
|
683
|
+
|
|
617
684
|
# Creates a language model instance, which is conventionally referred to by a variable named `nlp`.
|
|
618
685
|
# @param model [String] A language model installed in the system
|
|
619
686
|
# @param timeout [Numeric, nil] Seconds to wait for the model to load before
|
|
@@ -622,7 +689,31 @@ module Spacy
|
|
|
622
689
|
# because Ruby's `Timeout` cannot fire while PyCall holds the GVL. When it
|
|
623
690
|
# fires, the loading thread is left running as a daemon until the process
|
|
624
691
|
# exits (accepted: timeouts are an abnormal path).
|
|
625
|
-
|
|
692
|
+
# @param py_nlp [Object, nil] an existing Python `Language` pipeline to wrap
|
|
693
|
+
# instead of loading a model. For languages spaCy ships no trained
|
|
694
|
+
# pipeline for (e.g. Arabic and other right-to-left languages) or for
|
|
695
|
+
# self-built pipelines, create one with a third-party package such as
|
|
696
|
+
# spacy-stanza or spacy-udpipe and pass it here. Mutually exclusive with
|
|
697
|
+
# `model`; model name validation, timeout, and retries are skipped
|
|
698
|
+
# @example Load an installed spaCy model
|
|
699
|
+
# nlp = Spacy::Language.new("en_core_web_sm")
|
|
700
|
+
# @example Wrap an external pipeline (requires: pip install spacy-stanza)
|
|
701
|
+
# py_nlp = PyCall.import_module("spacy_stanza").load_pipeline("ar")
|
|
702
|
+
# nlp = Spacy::Language.new(py_nlp: py_nlp)
|
|
703
|
+
def initialize(model = NO_MODEL, max_retrial: MAX_RETRIAL, timeout: 60, py_nlp: nil)
|
|
704
|
+
if py_nlp
|
|
705
|
+
raise ArgumentError, "model and py_nlp: are mutually exclusive" unless model.equal?(NO_MODEL)
|
|
706
|
+
unless Builtins.isinstance(py_nlp, PyLanguage)
|
|
707
|
+
raise ArgumentError,
|
|
708
|
+
"py_nlp: must be a spaCy Language pipeline " \
|
|
709
|
+
"(e.g. from spacy.load or spacy_stanza.load_pipeline)"
|
|
710
|
+
end
|
|
711
|
+
|
|
712
|
+
@py_nlp = py_nlp
|
|
713
|
+
return
|
|
714
|
+
end
|
|
715
|
+
|
|
716
|
+
model = "en_core_web_sm" if model.equal?(NO_MODEL)
|
|
626
717
|
unless model.to_s.match?(/\A[a-zA-Z0-9_\-\.\/]+\z/)
|
|
627
718
|
raise ArgumentError, "Invalid model name: #{model.inspect}"
|
|
628
719
|
end
|
|
@@ -780,22 +871,26 @@ module Spacy
|
|
|
780
871
|
# @param max_completion_tokens [Integer] default maximum tokens in responses
|
|
781
872
|
# @param temperature [Float, nil] default sampling temperature (omitted from
|
|
782
873
|
# requests when nil)
|
|
874
|
+
# @param reasoning_effort [String, nil] default reasoning effort (omitted
|
|
875
|
+
# from requests when nil)
|
|
783
876
|
# @param base_url [String, nil] OpenAI-compatible API endpoint override
|
|
784
877
|
# @yield [OpenAIHelper] the helper instance for making API calls
|
|
785
878
|
# @return [Object] the block's return value
|
|
786
879
|
# @example Batch processing with pipe
|
|
787
|
-
# nlp.with_openai(model: "gpt-
|
|
880
|
+
# nlp.with_openai(model: "gpt-6-luna") do |ai|
|
|
788
881
|
# nlp.pipe(texts).map do |doc|
|
|
789
882
|
# ai.chat(system: "Analyze.", user: doc.linguistic_summary)
|
|
790
883
|
# end
|
|
791
884
|
# end
|
|
792
885
|
def with_openai(access_token: nil, model: OpenAIClient::DEFAULT_MODEL,
|
|
793
|
-
max_completion_tokens:
|
|
886
|
+
max_completion_tokens: LLMClientBase::DEFAULT_MAX_TOKENS, temperature: nil,
|
|
887
|
+
reasoning_effort: nil, base_url: nil)
|
|
794
888
|
helper = OpenAIHelper.new(
|
|
795
889
|
access_token: access_token,
|
|
796
890
|
model: model,
|
|
797
891
|
max_completion_tokens: max_completion_tokens,
|
|
798
892
|
temperature: temperature,
|
|
893
|
+
reasoning_effort: reasoning_effort,
|
|
799
894
|
base_url: base_url
|
|
800
895
|
)
|
|
801
896
|
yield helper
|
|
@@ -1003,6 +1098,15 @@ module Spacy
|
|
|
1003
1098
|
Doc.new(@doc.py_nlp, text: text)
|
|
1004
1099
|
end
|
|
1005
1100
|
|
|
1101
|
+
# Generates a syntax tree for the span in rsyntaxtree bracket notation, or
|
|
1102
|
+
# renders it with the rsyntaxtree gem. The span must have a single root
|
|
1103
|
+
# (e.g. a sentence from {Doc#sents}). See {Doc#syntax_tree} for the
|
|
1104
|
+
# available options.
|
|
1105
|
+
# @return [String] the bracket notation or the rendered output
|
|
1106
|
+
def syntax_tree(**options)
|
|
1107
|
+
SyntaxTree.generate(self, **options)
|
|
1108
|
+
end
|
|
1109
|
+
|
|
1006
1110
|
# Returns tokens conjugated to the root of the span.
|
|
1007
1111
|
# @return [Array<Token>] an array of tokens
|
|
1008
1112
|
def conjuncts
|
data/ruby-spacy.gemspec
CHANGED
|
@@ -17,10 +17,17 @@ Gem::Specification.new do |spec|
|
|
|
17
17
|
spec.license = "MIT"
|
|
18
18
|
spec.required_ruby_version = Gem::Requirement.new(">= 3.2")
|
|
19
19
|
|
|
20
|
+
spec.metadata["source_code_uri"] = spec.homepage
|
|
21
|
+
spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md"
|
|
22
|
+
spec.metadata["rubygems_mfa_required"] = "true"
|
|
23
|
+
|
|
20
24
|
# Specify which files should be added to the gem when it is released.
|
|
21
25
|
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
|
26
|
+
# `scripts/` holds release-time tooling that inspects the built gem; excluding it
|
|
27
|
+
# keeps that tooling out of the package it checks. `.github/` configures the
|
|
28
|
+
# repository on GitHub and is of no use once installed.
|
|
22
29
|
spec.files = Dir.chdir(File.expand_path(__dir__)) do
|
|
23
|
-
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
|
|
30
|
+
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features|scripts|\.github)/}) }
|
|
24
31
|
end
|
|
25
32
|
# spec.bindir = "exe"
|
|
26
33
|
# spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|