yuno-proofreader 0.1.0 → 0.1.2

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.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +16 -0
  3. data/README.md +169 -58
  4. data/lib/yuno/proofreader/audit/attempt.rb +11 -4
  5. data/lib/yuno/proofreader/audit/batch.rb +5 -3
  6. data/lib/yuno/proofreader/audit/report.rb +6 -1
  7. data/lib/yuno/proofreader/audit/runner.rb +28 -14
  8. data/lib/yuno/proofreader/audit/schemas.rb +51 -0
  9. data/lib/yuno/proofreader/cli/audit_commands.rb +9 -5
  10. data/lib/yuno/proofreader/cli/command_log.rb +4 -0
  11. data/lib/yuno/proofreader/cli/generate_commands.rb +133 -0
  12. data/lib/yuno/proofreader/cli/init_command.rb +24 -10
  13. data/lib/yuno/proofreader/cli/model_commands.rb +10 -2
  14. data/lib/yuno/proofreader/cli/queue_commands.rb +11 -1
  15. data/lib/yuno/proofreader/cli/sheet_commands.rb +4 -1
  16. data/lib/yuno/proofreader/cli.rb +28 -11
  17. data/lib/yuno/proofreader/config.rb +3 -3
  18. data/lib/yuno/proofreader/generate/cache.rb +77 -0
  19. data/lib/yuno/proofreader/generate/collector.rb +115 -0
  20. data/lib/yuno/proofreader/generate/describe.rb +29 -0
  21. data/lib/yuno/proofreader/generate/llm/prompt.rb +62 -0
  22. data/lib/yuno/proofreader/generate/llm/reader.rb +114 -0
  23. data/lib/yuno/proofreader/generate/llm/rules.yml +14 -0
  24. data/lib/yuno/proofreader/generate/llm/wording.rb +20 -0
  25. data/lib/yuno/proofreader/generate/llms_builder.rb +50 -0
  26. data/lib/yuno/proofreader/generate/llms_report.rb +112 -0
  27. data/lib/yuno/proofreader/generate/llms_txt.rb +107 -0
  28. data/lib/yuno/proofreader/generate/llms_writer.rb +54 -0
  29. data/lib/yuno/proofreader/generate/outline.rb +91 -0
  30. data/lib/yuno/proofreader/generate/passage.rb +54 -0
  31. data/lib/yuno/proofreader/generate/saved_answer.rb +50 -0
  32. data/lib/yuno/proofreader/llm/client.rb +18 -11
  33. data/lib/yuno/proofreader/llm/defaults.yml +3 -0
  34. data/lib/yuno/proofreader/llm/errors.rb +2 -0
  35. data/lib/yuno/proofreader/llm/factory.rb +9 -6
  36. data/lib/yuno/proofreader/llm/handoff.rb +114 -0
  37. data/lib/yuno/proofreader/llm/provider.rb +5 -2
  38. data/lib/yuno/proofreader/llm/providers/gemini.rb +7 -5
  39. data/lib/yuno/proofreader/llm/providers/manual.rb +44 -0
  40. data/lib/yuno/proofreader/llm/providers.rb +4 -10
  41. data/lib/yuno/proofreader/site.rb +2 -1
  42. data/lib/yuno/proofreader/site_reader.rb +29 -3
  43. data/lib/yuno/proofreader/store/cells.rb +13 -3
  44. data/lib/yuno/proofreader/store/gateways/csv.rb +79 -0
  45. data/lib/yuno/proofreader/store/sheets.rb +8 -4
  46. data/lib/yuno/proofreader/version.rb +1 -1
  47. data/lib/yuno/proofreader.rb +18 -0
  48. data/proofreader.example.yml +39 -10
  49. metadata +42 -7
  50. data/lib/yuno/proofreader/llm/model_commands.rb +0 -34
  51. /data/lib/yuno/proofreader/store/{google_gateway.rb → gateways/google.rb} +0 -0
@@ -3,21 +3,29 @@
3
3
  module Yuno
4
4
  module Proofreader
5
5
  module Audit
6
- # Audits one page from start to finish: fetches it, asks the model, asks a second model for an independent
7
- # review, merges the answers, compares them with the suggestions already in the store and writes the changes.
8
- # Everything it needs is passed in, so it runs with fakes in tests. A page that has not changed since its
9
- # last complete audit is skipped without calling a model.
6
+ # Audits one page from start to finish: fetches it, asks the model, optionally asks a second model for an
7
+ # independent review, merges the answers, compares them with the suggestions already in the store and writes
8
+ # the changes.
10
9
  class Runner
10
+ # review_requested: whether a second review was asked for, so the report can leave out one that was never
11
+ # meant to run.
11
12
  Result = Data.define(:status, :page, :fetched, :plan, :calls, :audit_count, :review_count, :missing_steps,
12
- :discarded, :notes, :complete, :dry_run, :skipped_since)
13
+ :discarded, :notes, :complete, :dry_run, :skipped_since, :review_requested) do
14
+ def initialize(review_requested: true, **fields) = super
15
+ end
16
+
17
+ # REVIEW: whether to ask for the second review. It needs a review_client, which is ignored otherwise.
18
+ def initialize(site:, store:, fetcher:, audit_client:, review_client: nil, review: true,
19
+ prompt: Prompt.new(site), clock: -> { Time.now.utc }, progress: ->(_message) {},
20
+ log: Log.null)
21
+ raise ArgumentError, "A review needs a review_client" if review && review_client.nil?
13
22
 
14
- def initialize(site:, store:, fetcher:, audit_client:, review_client:, prompt: Prompt.new(site),
15
- clock: -> { Time.now.utc }, progress: ->(_message) {}, log: Log.null)
16
23
  @site = site
17
24
  @store = store
18
25
  @fetcher = fetcher
19
26
  @audit_client = audit_client
20
27
  @review_client = review_client
28
+ @review = review
21
29
  @prompt = prompt
22
30
  @clock = clock
23
31
  @progress = progress
@@ -69,7 +77,7 @@ module Yuno
69
77
  @store.record_audit(record, fingerprint: record.fingerprint.to_s.strip, at: now) unless dry_run
70
78
  Result.new(status: :skipped, page: record.name, fetched:, plan: nil, calls: [], audit_count: 0,
71
79
  review_count: 0, missing_steps: [], discarded: [], notes: [], complete: true, dry_run:,
72
- skipped_since: record.last_audited)
80
+ skipped_since: record.last_audited, review_requested: @review)
73
81
  end
74
82
 
75
83
  # ---- an audit ----
@@ -85,14 +93,14 @@ module Yuno
85
93
  def attempt_for(fetched)
86
94
  user = @prompt.user_message(fetched)
87
95
  first = ask(:audit, @audit_client, @prompt.audit_system, user)
88
- review = try_review(user, first.call.model)
96
+ review = @review ? try_review(user, first.call.model) : nil
89
97
  audit_read = Answers.audit(first.answer.data, steps: @prompt.steps, languages: @site.languages)
90
98
  Attempt.new(first:, review:, audit_read:, review_read: read_review(review))
91
99
  end
92
100
 
93
101
  def ask(role, client, system, user, avoid: [])
94
102
  say("Asking the #{role} model (this can take a minute or two)...")
95
- answer = client.generate(system:, user:, avoid:)
103
+ answer = client.generate(system:, user:, avoid:, schema: Schemas.for_role(role))
96
104
  say("The #{role} model answered: #{answer.model}, #{answer.seconds.round} s.")
97
105
  Asked.new(answer:, call: Call.new(role:, model: answer.model, seconds: answer.seconds,
98
106
  input_tokens: answer.input_tokens, output_tokens: answer.output_tokens,
@@ -109,8 +117,11 @@ module Yuno
109
117
  Review.new(asked: nil, error: e.message)
110
118
  end
111
119
 
120
+ # Nothing to read when no review was asked for, when it failed, or when its answer has the wrong shape.
112
121
  def read_review(review)
113
- data = review.asked&.answer&.data
122
+ return unless review&.asked
123
+
124
+ data = review.asked.answer.data
114
125
  return unless data.is_a?(Hash) && data["issues"].is_a?(Array)
115
126
 
116
127
  Answers.review(data, languages: @site.languages)
@@ -122,9 +133,11 @@ module Yuno
122
133
  ignore_terms: @site.context.ignore_terms, now:)
123
134
  end
124
135
 
125
- # Only a complete audit records the page's fingerprint, because that is what lets the next run skip it.
136
+ # Only a complete audit records the page's fingerprint, because that is what lets the next run skip it. A
137
+ # review that was not asked for does not hold it back, but one that was asked for and failed does.
126
138
  def complete?(fetched, attempt)
127
- fetched.ok? && fetched.snapshots.none?(&:truncated) && attempt.missing_steps.empty? && attempt.reviewed?
139
+ fetched.ok? && fetched.snapshots.none?(&:truncated) && attempt.missing_steps.empty? &&
140
+ attempt.review_done?
128
141
  end
129
142
 
130
143
  def write(record, fetched, plan, complete, now)
@@ -136,7 +149,8 @@ module Yuno
136
149
  Result.new(status: :audited, page: record.name, fetched:, plan:, calls: attempt.calls,
137
150
  audit_count: attempt.audit_read.findings.size, review_count: attempt.review_read&.findings&.size,
138
151
  missing_steps: attempt.missing_steps, discarded: attempt.discarded,
139
- notes: attempt.notes(fetched), complete:, dry_run:, skipped_since: nil)
152
+ notes: attempt.notes(fetched), complete:, dry_run:, skipped_since: nil,
153
+ review_requested: @review)
140
154
  end
141
155
  end
142
156
  end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yuno
4
+ module Proofreader
5
+ module Audit
6
+ # What the models are asked to answer with, as JSON Schemas. They only fix the shape, so that an answer is
7
+ # valid JSON. Findings::Finding still decides which items are usable.
8
+ module Schemas
9
+ ISSUE = {
10
+ type: "object",
11
+ properties: {
12
+ language: { type: "string" },
13
+ category: { type: "string" },
14
+ effort: { type: "string" },
15
+ original: { type: "string" },
16
+ suggested: { type: "string" },
17
+ reason: { type: "string" }
18
+ },
19
+ required: %w[language category effort original suggested reason]
20
+ }.freeze
21
+
22
+ AUDIT = {
23
+ type: "object",
24
+ properties: {
25
+ steps: {
26
+ type: "array",
27
+ items: {
28
+ type: "object",
29
+ properties: { step: { type: "integer" }, issues: { type: "array", items: ISSUE } },
30
+ required: %w[step issues]
31
+ }
32
+ }
33
+ },
34
+ required: %w[steps]
35
+ }.freeze
36
+
37
+ REVIEW = {
38
+ type: "object",
39
+ properties: { issues: { type: "array", items: ISSUE } },
40
+ required: %w[issues]
41
+ }.freeze
42
+
43
+ BY_ROLE = { audit: AUDIT, review: REVIEW }.freeze
44
+
45
+ module_function
46
+
47
+ def for_role(role) = BY_ROLE.fetch(role)
48
+ end
49
+ end
50
+ end
51
+ end
@@ -52,7 +52,7 @@ module Yuno
52
52
  count, remaining, problem = take_count(args)
53
53
  return usage_error(problem) if problem
54
54
 
55
- options, rest, unknown = split_args(remaining, %w[dry-run force verbose next include-not-due])
55
+ options, rest, unknown = split_args(remaining, %w[dry-run force verbose next include-not-due review])
56
56
  problem = audit_args_problem(options, rest, unknown, count)
57
57
  return usage_error(problem) if problem
58
58
 
@@ -62,7 +62,8 @@ module Yuno
62
62
  end
63
63
 
64
64
  def audit_page(site, page, options)
65
- result = audit_runner(site).run(page, dry_run: options.key?("dry-run"), force: options.key?("force"))
65
+ result = audit_runner(site, review: review?(site, options))
66
+ .run(page, dry_run: options.key?("dry-run"), force: options.key?("force"))
66
67
  Audit::LogFields.record(log, result)
67
68
  Audit::Report.new(result, verbose: options.key?("verbose")).lines.each { |line| @out.puts line }
68
69
  0
@@ -81,12 +82,15 @@ module Yuno
81
82
  "audit --next takes no page name, only a settings file" if rest.size > 1
82
83
  end
83
84
 
84
- def audit_runner(site, store = store_for(site))
85
+ def audit_runner(site, store = store_for(site), review: site.review)
85
86
  audit_client = Llm.client_for(site, env: @env, transport: @llm_transport, log:)
86
- review_client = Llm.client_for(site, env: @env, review: true, transport: @llm_transport, log:)
87
+ review_client = (Llm.client_for(site, env: @env, review: true, transport: @llm_transport, log:) if review)
87
88
  Audit::Runner.new(site:, store:, fetcher: Pages::Fetcher.new(site, http_client), audit_client:,
88
- review_client:, progress: ->(message) { @out.puts message }, log:)
89
+ review_client:, review:, progress: ->(message) { @out.puts message }, log:)
89
90
  end
91
+
92
+ # The setting turns the review on for every run
93
+ def review?(site, options) = site.review || options.key?("review")
90
94
  end
91
95
  end
92
96
  end
@@ -19,6 +19,10 @@ module Yuno
19
19
  rescue StandardError => e
20
20
  log.error("run failed", error: e.class.name, message: e.message, seconds: elapsed(started))
21
21
  raise
22
+ rescue Interrupt
23
+ log.info("run interrupted", seconds: elapsed(started))
24
+ @err.puts "Interrupted."
25
+ 130
22
26
  end
23
27
 
24
28
  private
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yuno
4
+ module Proofreader
5
+ # The commands that write files from what the site already says: generate llms.
6
+ module GenerateCommands
7
+ GENERATORS = { "llms" => :generate_llms }.freeze
8
+ DEFAULT_PAGES = 50
9
+ PAGES_FILE = "llms-pages.json"
10
+
11
+ private
12
+
13
+ def generate(args)
14
+ kind, *rest = args
15
+ action = GENERATORS[kind]
16
+ return usage_error("Unknown generate command: #{kind.inspect}. Try: generate llms") unless action
17
+
18
+ send(action, rest)
19
+ end
20
+
21
+ def generate_llms(args)
22
+ count, remaining, problem = take_count(args)
23
+ return usage_error(problem) if problem
24
+
25
+ options, rest, unknown = split_args(remaining, %w[all no-ai language full-text resume])
26
+ problem = generate_args_problem(options, rest, unknown, count)
27
+ return usage_error(problem) if problem
28
+
29
+ site = Site.load(rest.first || CLI::DEFAULT_SITE_FILE)
30
+ language = options["language"]
31
+ if language && !site.languages.include?(language)
32
+ return usage_error("Unknown language for --language: #{language}")
33
+ end
34
+
35
+ run_generate_llms(site, options, count, language)
36
+ end
37
+
38
+ def generate_args_problem(options, rest, unknown, count)
39
+ return "Unknown option: #{unknown.first}" unless unknown.empty?
40
+ return "--language needs a language, for example --language=de" if options["language"] == true
41
+
42
+ combination_problem(options, count) || ("Too many arguments for generate llms" if rest.size > 1)
43
+ end
44
+
45
+ def combination_problem(options, count)
46
+ return resume_problem if options.key?("resume") && fresh_option?(options, count)
47
+
48
+ "--count and --all cannot be used together" if count && options.key?("all")
49
+ end
50
+
51
+ def fresh_option?(options, count) = count || options.key?("all") || options.key?("full-text")
52
+
53
+ def resume_problem
54
+ "--resume reuses the pages saved by the last run, so --count, --all and --full-text cannot be used with it"
55
+ end
56
+
57
+ # The model client is built first, so a missing API key stops the command before any page is fetched.
58
+ def run_generate_llms(site, options, count, only)
59
+ client = wording_client(site, options)
60
+ saved = saved_pages(site, options)
61
+ collected = saved ? saved.collected : fresh_pages(site, options, count)
62
+ languages = languages_to_write(site, client, only)
63
+ files = write_llms_files(site, collected, client, languages)
64
+ show_llms_report(collected, languages, files, saved)
65
+ files.any? { |file| file.built.failure } ? 1 : 0
66
+ end
67
+
68
+ def saved_pages(site, options)
69
+ return unless options.key?("resume")
70
+
71
+ Generate::Cache.load(pages_path(site), website: site.website)
72
+ end
73
+
74
+ # With --resume and a provider that needs a person, the answer is already in the answer file, so nothing is
75
+ # asked: it is waited for. With an API provider, the model is simply asked again.
76
+ def wording_client(site, options)
77
+ return if options.key?("no-ai")
78
+
79
+ provider = Llm::Providers.resolve(site.provider)
80
+ if options.key?("resume") && provider.interactive?
81
+ handoff = Llm::Handoff.new(input: @input, output: @out)
82
+ return Generate::SavedAnswer.new(handoff:, model: Llm.models_for(site, provider).names.first,
83
+ say: ->(message) { @out.puts message })
84
+ end
85
+
86
+ Llm.client_for(site, env: @env, transport: @llm_transport, log:)
87
+ end
88
+
89
+ # The language of the prompt that is waiting in the prompt file goes first, so its answer is used.
90
+ def languages_to_write(site, client, only)
91
+ languages = only ? [only] : site.languages
92
+ client.is_a?(Generate::SavedAnswer) ? client.order(languages) : languages
93
+ end
94
+
95
+ def write_llms_files(site, collected, client, languages)
96
+ builder = Generate::LlmsBuilder.new(client:, progress: ->(message) { @out.puts message }, log:)
97
+ Generate::LlmsWriter.new(site:, builder:).call(collected, languages)
98
+ end
99
+
100
+ def show_llms_report(collected, languages, files, saved)
101
+ report = Generate::LlmsReport.new(collected:, requested: languages, files:, saved_at: saved&.saved_at)
102
+ report.lines.each { |line| @out.puts line }
103
+ end
104
+
105
+ def fresh_pages(site, options, count)
106
+ limit = options.key?("all") ? nil : (count || DEFAULT_PAGES)
107
+ collected = collect_pages(site, limit, full_text: options.key?("full-text"))
108
+ Generate::Cache.save(pages_path(site), collected, website: site.website)
109
+ @out.puts "Saved what was read to #{pages_path(site)}: if a later step is interrupted, " \
110
+ "generate llms --resume continues from it without fetching again."
111
+ collected
112
+ end
113
+
114
+ def pages_path(site) = File.join(File.expand_path(site.data_dir), PAGES_FILE)
115
+
116
+ def collect_pages(site, limit, full_text:)
117
+ records = store_for(site).pages
118
+ raise Error, "The Pages tab is empty. Run: yuno-proofreader pages import" if records.empty?
119
+
120
+ collector = Generate::Collector.new(site:, fetcher: Pages::Fetcher.new(site, http_client), full_text:,
121
+ progress: ->(message) { @out.puts message })
122
+ collected = collector.call(records, limit:)
123
+ raise Error, nothing_read_message(collected) if collected.empty?
124
+
125
+ collected
126
+ end
127
+
128
+ def nothing_read_message(collected)
129
+ "None of the pages could be read, so nothing was written (#{collected.problems.first(3).join('; ')})."
130
+ end
131
+ end
132
+ end
133
+ end
@@ -81,7 +81,8 @@ module Yuno
81
81
  def init_lines(path, site)
82
82
  problems = Array(site.audit_problems)
83
83
  suffix = path == CLI::DEFAULT_SITE_FILE ? "" : " #{path}"
84
- ["", "Wrote #{path}.", *readiness(problems), "", "Outside this file you also need:", *environment_lines, "",
84
+ ["", "Wrote #{path}.", *readiness(problems), "",
85
+ "Outside this file you also need:", *environment_lines(site), "",
85
86
  "Next:", *next_steps(suffix)]
86
87
  end
87
88
 
@@ -91,13 +92,13 @@ module Yuno
91
92
  ["Before an audit can run, this is still missing:", *problems.map { |problem| " - #{problem}" }]
92
93
  end
93
94
 
94
- def environment_lines
95
- keys = Llm::Providers.ids.map { |id| [Llm::Providers.resolve(id).api_key_env, "the API key of #{id}"] }
96
- lines = [["SPREADSHEET_ID", "the id of your Google Sheet"], *keys].map do |name, meaning|
97
- environment_line(name, meaning)
98
- end
99
- [*lines, " Put them in a .env file in this folder, or export them.",
100
- " Google credentials: see the README, section \"Connecting to Google\""]
95
+ def environment_lines(site)
96
+ provider = Llm::Providers.resolve(site.provider)
97
+ rows = []
98
+ rows << ["SPREADSHEET_ID", "the id of your Google Sheet"] if site.store == "sheets"
99
+ rows << [provider.api_key_env, "the API key of #{provider.id}"] if provider.api_key_env
100
+ [*rows.map { |name, meaning| environment_line(name, meaning) }, *provider_hint(provider),
101
+ " Put them in a .env file in this folder, or export them.", *google_hint(site)]
101
102
  end
102
103
 
103
104
  def environment_line(name, meaning)
@@ -106,11 +107,24 @@ module Yuno
106
107
  end
107
108
 
108
109
  def next_steps(suffix)
109
- [" yuno-proofreader prepare#{suffix} creates the tabs in your Google Sheet",
110
- " yuno-proofreader pages import#{suffix} adds your pages to the sheet",
110
+ [" yuno-proofreader prepare#{suffix} creates the tabs (CSV files, or a Google Sheet)",
111
+ " yuno-proofreader pages import#{suffix} adds your pages",
111
112
  " yuno-proofreader analyze#{suffix} ranks the pages by importance",
112
113
  " yuno-proofreader audit --next#{suffix} audits the most important page that is due"]
113
114
  end
115
+
116
+ def provider_hint(provider)
117
+ return [] if provider.api_key_env
118
+
119
+ [" No model account is needed: each prompt is saved to tmp/handoff/prompt.md for you to paste into a chat.",
120
+ " To call a model automatically, set provider: gemini in the settings file and export GEMINI_API_KEY."]
121
+ end
122
+
123
+ def google_hint(site)
124
+ return [] unless site.store == "sheets"
125
+
126
+ [" Google credentials: see the README, section \"Connecting to Google\""]
127
+ end
114
128
  end
115
129
  end
116
130
  end
@@ -19,16 +19,24 @@ module Yuno
19
19
  end
20
20
 
21
21
  def print_models(provider, available, used, source)
22
+ return print_manual_models(used, source) unless provider.class.api_key_env
23
+
22
24
  @out.puts "Models your #{provider.class.id} key can use for text generation:"
23
25
  available.each { |name| @out.puts " #{name}#{' (in use)' if used.include?(name)}" }
24
- origin = source == :settings ? "from your settings" : "built-in default"
25
- @out.puts "", "In use (#{origin}): #{used.join(', ')}"
26
+ @out.puts "", "In use (#{origin_of(source)}): #{used.join(', ')}"
26
27
  missing = used - available
27
28
  return if missing.empty?
28
29
 
29
30
  @out.puts "Not available to this key: #{missing.join(', ')}. A model that fails is skipped, " \
30
31
  "so set models in proofreader.yml to the ones you want."
31
32
  end
33
+
34
+ def print_manual_models(used, source)
35
+ @out.puts "The manual provider has no list of models: you pick the model in the chat yourself.",
36
+ "Label shown with each prompt (#{origin_of(source)}): #{used.join(', ')}"
37
+ end
38
+
39
+ def origin_of(source) = source == :settings ? "from your settings" : "built-in default"
32
40
  end
33
41
  end
34
42
  end
@@ -54,8 +54,9 @@ module Yuno
54
54
 
55
55
  # The model clients are built first, so a missing API key stops the command before anything is read.
56
56
  def audit_batch(site, options, count)
57
+ check_batch_allowed!(site, options, count)
57
58
  store = store_for(site)
58
- runner = audit_runner(site, store)
59
+ runner = audit_runner(site, store, review: review?(site, options))
59
60
  picks = agenda_for(site, store)
60
61
  pool = options.key?("include-not-due") ? picks : picks.select(&:due?)
61
62
  chosen = pool.first(count || 1)
@@ -84,6 +85,15 @@ module Yuno
84
85
  skipped: statuses.fetch(:skipped, 0), failed: statuses.fetch(:failed, 0),
85
86
  still_due:, dry_run:, stopped: outcome.stopped, **Llm::Usage.of(calls))
86
87
  end
88
+
89
+ def check_batch_allowed!(site, options, count)
90
+ return unless count.to_i > 1 && Llm::Providers.resolve(site.provider).interactive?
91
+
92
+ per_page = review?(site, options) ? "two" : "one"
93
+ raise ConfigError, "audit --next --count=#{count} would ask you to paste the answers for #{count} pages in a " \
94
+ "row (#{per_page} per page). With provider: manual, run audit --next once per page, " \
95
+ "or set provider: gemini."
96
+ end
87
97
  end
88
98
  end
89
99
  end
@@ -50,7 +50,10 @@ module Yuno
50
50
  end
51
51
 
52
52
  def store_for(site)
53
- @store || Store::Sheets.connect(Config.from_env(@env), site)
53
+ return @store if @store
54
+ return Store::Sheets.connect(Config.from_env(@env, sheet: true), site) if site.store == "sheets"
55
+
56
+ Store::Sheets.local(site, dir: File.expand_path(site.data_dir))
54
57
  end
55
58
  end
56
59
  end
@@ -11,6 +11,7 @@ module Yuno
11
11
  include InitCommand
12
12
  prepend CommandLog
13
13
  include QueueCommands
14
+ include GenerateCommands
14
15
 
15
16
  DEFAULT_SITE_FILE = "proofreader.yml"
16
17
  STATE_LABELS = { set: "set", empty: "not set", placeholder: "still the [FILL IN] example text" }.freeze
@@ -19,7 +20,8 @@ module Yuno
19
20
  "version" => :version, "-v" => :version, "--version" => :version,
20
21
  "doctor" => :doctor, "sitemap" => :sitemap, "fetch" => :fetch, "settings" => :settings,
21
22
  "models" => :models, "prepare" => :prepare, "pages" => :pages, "prompt" => :prompt,
22
- "analyze" => :analyze, "init" => :init, "queue" => :queue, "audit" => :audit
23
+ "analyze" => :analyze, "init" => :init, "queue" => :queue, "audit" => :audit,
24
+ "generate" => :generate
23
25
  }.freeze
24
26
  USAGE = <<~TEXT
25
27
  Usage: yuno-proofreader <command>
@@ -30,20 +32,21 @@ module Yuno
30
32
  fetch PAGE [FILE] [--html=LANG]
31
33
  Download all language versions of one page and show how the tool sees them.
32
34
  PAGE is a name from `sitemap --all`, or any address of the page
33
- prepare [FILE] Create the tabs the tool needs in your Google Sheet (safe to run again)
34
- pages import [FILE] Add the pages of the sitemap to the Pages tab of the sheet
35
+ prepare [FILE] Create the tables the tool needs: CSV files in the data folder, or tabs in
36
+ your Google Sheet (safe to run again)
37
+ pages import [FILE] Add the pages of the sitemap to the Pages table
35
38
  models [FILE] List the models your API key can use for text generation, and which are in use
36
39
  init [FILE] [OPTIONS] Ask about your site and write a settings file (default proofreader.yml).
37
40
  --template shows the full commented template, or with a FILE writes it there.
38
41
  For scripts: --website, --language CODE[:PREFIX], --note CODE=TEXT, --business,
39
42
  --audience, --tone, --sitemap, --skip-path, --rule, --ignore-term, --difference.
40
43
  --yes accepts what was detected, --offline makes no request. Does not overwrite a file
41
- audit PAGE [FILE] [--dry-run] [--force] [--verbose]
44
+ audit PAGE [FILE] [--dry-run] [--force] [--verbose] [--review]
42
45
  Audit one page: ask the model, compare the findings with the suggestions in the
43
46
  sheet and update the sheet. --dry-run writes nothing (the model is still called
44
47
  and costs the same), --force audits a page that has not changed, --verbose
45
- lists everything that was decided
46
- audit --next [FILE] [--count=N] [--include-not-due] [--dry-run] [--force] [--verbose]
48
+ lists everything that was decided, --review adds an independent second review
49
+ audit --next [FILE] [--count=N] [--include-not-due] [--dry-run] [--force] [--verbose] [--review]
47
50
  Audit the pages that are due, the most important first (default 1 page)
48
51
  queue [FILE] [--count=N] [--all]
49
52
  Show which pages are due for an audit and why. Calls no model and fetches no page
@@ -51,9 +54,18 @@ module Yuno
51
54
  Rank every page by importance and write it to the Pages tab. --dry-run writes
52
55
  nothing, --no-ai skips the models, --reuse-ai takes their judgement from the
53
56
  last run instead of asking again
57
+ generate llms [FILE] [--count=N] [--all] [--language=CODE] [--no-ai] [--full-text] [--resume]
58
+ Write one llms.txt per language to the data folder: your most important pages
59
+ grouped into sections by their addresses, with headings, summaries and link texts
60
+ a model wrote from the texts of your pages (one call per language). Default 50
61
+ pages, --all for every page, --full-text hands the model whole pages, --no-ai
62
+ skips the model. --resume continues the last run without fetching the pages
63
+ again: it uses the pages saved in the data folder and, with provider: manual, the
64
+ answer already in answer.md when prompt.md is that language's prompt, otherwise
65
+ it asks as usual (no pages are fetched)
54
66
  settings [FILE] Show which settings that describe your site are filled in, and whether an
55
67
  audit can start
56
- doctor Check that the required environment variables are set
68
+ doctor [FILE] Check that the settings file can be read and the variables it needs are set
57
69
  version Print the version
58
70
  help Show this help
59
71
  TEXT
@@ -97,13 +109,18 @@ module Yuno
97
109
  0
98
110
  end
99
111
 
100
- def doctor(_args = nil)
101
- config = Config.from_env(@env)
102
- @out.puts "Configuration looks complete."
103
- @out.puts config.inspect
112
+ def doctor(args)
113
+ file, problem = single_file(args, "doctor")
114
+ return usage_error(problem) if problem
115
+
116
+ site = Site.load(file)
117
+ config = Config.from_env(@env, sheet: site.store == "sheets")
118
+ @out.puts "Configuration looks complete.", "Store: #{store_summary(site)}", config.inspect
104
119
  0
105
120
  end
106
121
 
122
+ def store_summary(site) = site.store == "sheets" ? "sheets" : "csv (#{site.data_dir})"
123
+
107
124
  def sitemap(args)
108
125
  options, rest, unknown = split_args(args, %w[all])
109
126
  return usage_error("Unknown option: #{unknown.first}") unless unknown.empty?
@@ -9,11 +9,11 @@ module Yuno
9
9
  REQUIRED = %w[SPREADSHEET_ID].freeze
10
10
  LOG_LEVELS = %w[debug info warn error].freeze
11
11
 
12
- def self.from_env(env = ENV)
13
- missing = REQUIRED.select { |name| env[name].to_s.strip.empty? }
12
+ def self.from_env(env = ENV, sheet: false)
13
+ missing = sheet ? REQUIRED.select { |name| env[name].to_s.strip.empty? } : []
14
14
  raise ConfigError, "Missing environment variables: #{missing.join(', ')}" unless missing.empty?
15
15
 
16
- new(spreadsheet_id: env["SPREADSHEET_ID"].strip, log_level: Log.level_from(env["LOG_LEVEL"]))
16
+ new(spreadsheet_id: env["SPREADSHEET_ID"]&.strip, log_level: Log.level_from(env["LOG_LEVEL"]))
17
17
  end
18
18
 
19
19
  def inspect
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+
6
+ module Yuno
7
+ module Proofreader
8
+ module Generate
9
+ # What generate llms read from the site, saved to a file so that a later run can continue without fetching the
10
+ # pages again (generate llms --resume). The file holds page text, so it lives in the data folder.
11
+ module Cache
12
+ FORMAT = 1
13
+ Loaded = Data.define(:collected, :saved_at)
14
+
15
+ module_function
16
+
17
+ def save(path, collected, website:, now: Time.now.utc)
18
+ data = { "format" => FORMAT, "website" => website, "saved_at" => now.strftime("%Y-%m-%d %H:%M"),
19
+ "considered" => collected.considered, "unranked" => collected.unranked,
20
+ "problems" => collected.problems, "home" => dump_page(collected.home),
21
+ "pages" => collected.pages.map { |page| dump_page(page) } }
22
+ write(path, JSON.pretty_generate(data))
23
+ end
24
+
25
+ def load(path, website:)
26
+ unless File.file?(path)
27
+ raise Error,
28
+ "Nothing is saved at #{path}. Run generate llms once without --resume first."
29
+ end
30
+
31
+ data = JSON.parse(File.read(path, encoding: "UTF-8"))
32
+ problem = problem_with(data, website)
33
+ raise Error, "#{path} #{problem}. Run generate llms again without --resume." if problem
34
+
35
+ Loaded.new(collected: collected_from(data), saved_at: data.fetch("saved_at"))
36
+ rescue JSON::ParserError, KeyError, TypeError, ArgumentError => e
37
+ raise Error, "#{path} could not be read (#{e.message}). Run generate llms again without --resume."
38
+ end
39
+
40
+ def problem_with(data, website)
41
+ return "is not a set of saved pages" unless data.is_a?(Hash) && data["format"] == FORMAT
42
+ return "was saved for #{data['website']}, not for #{website}" unless data["website"] == website
43
+
44
+ nil
45
+ end
46
+
47
+ def dump_page(page)
48
+ { "name" => page.name,
49
+ "versions" => page.versions.transform_values { |facts| facts.to_h.transform_keys(&:to_s) } }
50
+ end
51
+
52
+ def collected_from(data)
53
+ Collected.new(home: page_from(data.fetch("home")), pages: data.fetch("pages").map { |page| page_from(page) },
54
+ problems: data.fetch("problems"), considered: data.fetch("considered"),
55
+ unranked: data.fetch("unranked"))
56
+ end
57
+
58
+ def page_from(hash)
59
+ versions = hash.fetch("versions").to_h do |language, facts|
60
+ [language, Facts.new(**facts.transform_keys(&:to_sym))]
61
+ end
62
+ Page.new(name: hash.fetch("name"), versions:)
63
+ end
64
+
65
+ # Written to a temporary file first, so a crash cannot leave half a file behind.
66
+ def write(path, text)
67
+ FileUtils.mkdir_p(File.dirname(path))
68
+ temporary = "#{path}.tmp"
69
+ File.write(temporary, text, encoding: "UTF-8")
70
+ File.rename(temporary, path)
71
+ rescue SystemCallError => e
72
+ raise ConfigError, "Could not write #{path}: #{e.message}"
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end