yuno-proofreader 0.1.0 → 0.1.1

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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +9 -0
  3. data/README.md +169 -58
  4. data/lib/yuno/proofreader/audit/attempt.rb +11 -4
  5. data/lib/yuno/proofreader/audit/report.rb +6 -1
  6. data/lib/yuno/proofreader/audit/runner.rb +27 -13
  7. data/lib/yuno/proofreader/cli/audit_commands.rb +9 -5
  8. data/lib/yuno/proofreader/cli/command_log.rb +4 -0
  9. data/lib/yuno/proofreader/cli/generate_commands.rb +133 -0
  10. data/lib/yuno/proofreader/cli/init_command.rb +24 -10
  11. data/lib/yuno/proofreader/cli/model_commands.rb +10 -2
  12. data/lib/yuno/proofreader/cli/queue_commands.rb +11 -1
  13. data/lib/yuno/proofreader/cli/sheet_commands.rb +4 -1
  14. data/lib/yuno/proofreader/cli.rb +28 -11
  15. data/lib/yuno/proofreader/config.rb +3 -3
  16. data/lib/yuno/proofreader/generate/cache.rb +77 -0
  17. data/lib/yuno/proofreader/generate/collector.rb +115 -0
  18. data/lib/yuno/proofreader/generate/describe.rb +29 -0
  19. data/lib/yuno/proofreader/generate/llm/prompt.rb +62 -0
  20. data/lib/yuno/proofreader/generate/llm/reader.rb +114 -0
  21. data/lib/yuno/proofreader/generate/llm/rules.yml +14 -0
  22. data/lib/yuno/proofreader/generate/llm/wording.rb +20 -0
  23. data/lib/yuno/proofreader/generate/llms_builder.rb +50 -0
  24. data/lib/yuno/proofreader/generate/llms_report.rb +112 -0
  25. data/lib/yuno/proofreader/generate/llms_txt.rb +107 -0
  26. data/lib/yuno/proofreader/generate/llms_writer.rb +54 -0
  27. data/lib/yuno/proofreader/generate/outline.rb +91 -0
  28. data/lib/yuno/proofreader/generate/passage.rb +54 -0
  29. data/lib/yuno/proofreader/generate/saved_answer.rb +50 -0
  30. data/lib/yuno/proofreader/llm/defaults.yml +3 -0
  31. data/lib/yuno/proofreader/llm/factory.rb +9 -6
  32. data/lib/yuno/proofreader/llm/handoff.rb +114 -0
  33. data/lib/yuno/proofreader/llm/provider.rb +4 -1
  34. data/lib/yuno/proofreader/llm/providers/manual.rb +44 -0
  35. data/lib/yuno/proofreader/llm/providers.rb +4 -10
  36. data/lib/yuno/proofreader/site.rb +2 -1
  37. data/lib/yuno/proofreader/site_reader.rb +29 -3
  38. data/lib/yuno/proofreader/store/gateways/csv.rb +79 -0
  39. data/lib/yuno/proofreader/store/sheets.rb +8 -4
  40. data/lib/yuno/proofreader/version.rb +1 -1
  41. data/lib/yuno/proofreader.rb +17 -0
  42. data/proofreader.example.yml +31 -7
  43. metadata +41 -7
  44. data/lib/yuno/proofreader/llm/model_commands.rb +0 -34
  45. /data/lib/yuno/proofreader/store/{google_gateway.rb → gateways/google.rb} +0 -0
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "yaml"
5
+
6
+ module Yuno
7
+ module Proofreader
8
+ module Generate
9
+ module Wording
10
+ # What the model is asked: the rules of rules.yml, and the outline with everything each page says about itself.
11
+ class Prompt
12
+ RULES = File.join(__dir__, "rules.yml")
13
+ LANGUAGES = { "de" => "German", "en" => "English", "es" => "Spanish", "fr" => "French",
14
+ "it" => "Italian", "pt" => "Portuguese", "nl" => "Dutch" }.freeze
15
+
16
+ def initialize(language:, rules: YAML.safe_load_file(RULES))
17
+ @language = language
18
+ @name = LANGUAGES.fetch(language) { "the language with the code \"#{language}\"" }
19
+ @rules = rules
20
+ end
21
+
22
+ def system_prompt
23
+ rules = @rules.fetch("rules").each_with_index.map { |rule, index| "#{index + 1}. #{fill(rule)}" }
24
+ [fill(@rules.fetch("role")), "", "## RULES", *rules, "", "## ANSWER", @rules.fetch("answer"),
25
+ @rules.fetch("shape")].join("\n")
26
+ end
27
+
28
+ # home: the facts of the home page in this language, or nil.
29
+ def user_message(outline, home)
30
+ JSON.generate("language" => @language, "site" => site(home),
31
+ "sections" => outline.sections.map { |section| section_json(section) },
32
+ "other_pages" => outline.loose.map(&:id),
33
+ "pages" => outline.items.map { |item| page_json(item) })
34
+ end
35
+
36
+ private
37
+
38
+ def fill(text) = text.gsub("{language}", @name)
39
+
40
+ def site(home)
41
+ { "title" => home&.title, "description" => home&.description }.reject { |_key, value| value.to_s.empty? }
42
+ end
43
+
44
+ def section_json(section)
45
+ { "id" => section.id, "slug" => section.slug, "index_page" => section.hub&.id,
46
+ "pages" => section.items.map(&:id), "sections" => section.children.map { |child| section_json(child) } }
47
+ .reject { |_key, value| value.nil? || value == [] }
48
+ end
49
+
50
+ # Everything is handed over as it is: the description whole, and the paragraphs whole.
51
+ def page_json(item)
52
+ facts = item.facts
53
+ { "id" => item.id, "name" => facts.name, "title" => (facts.title unless facts.title == facts.name),
54
+ "path" => facts.path, "importance" => facts.importance, "tier" => facts.tier,
55
+ "description" => facts.description, "text" => facts.paragraphs, "more_text" => (true if facts.cut) }
56
+ .reject { |_key, value| value.nil? || value == "" || value == [] }
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yuno
4
+ module Proofreader
5
+ module Generate
6
+ module Wording
7
+ # Reads the answer of the model. There is no limit on how long a summary or a text may be. Whatever does not
8
+ # hold up is left out and noted: a text that does not end in a whole sentence, or that has a number its page
9
+ # does not have. A page left without a text shows the description it already has.
10
+ class Reader
11
+ HEADING_MAX = 100
12
+ NUMBER = /\d+(?:[.,]\d+)?/
13
+ MARKDOWN_START = /\A[#>*\-\s]+/
14
+ SENTENCE_END = /[.!?]["'”’»)]*\z/
15
+ ELLIPSIS = /(?:\.\.\.|…)["'”’»)]*\z/
16
+
17
+ def self.call(data, outline) = new(data, outline).call
18
+
19
+ def initialize(data, outline)
20
+ @data = data
21
+ @sections = outline.all_sections.to_h { |section| [section.id, section] }
22
+ @items = outline.items.to_h { |item| [item.id, item] }
23
+ @notes = []
24
+ end
25
+
26
+ def call
27
+ headings = {}
28
+ summaries = {}
29
+ entries("sections") do |entry|
30
+ section = @sections[entry["id"].to_s]
31
+ next skip("section #{entry['id'].inspect} is not in the outline") unless section
32
+
33
+ heading = heading_of(entry["heading"], section)
34
+ summary = summary_of(entry["summary"], section)
35
+ headings[section.id] = heading if heading
36
+ summaries[section.id] = summary if summary
37
+ end
38
+ Result.new(headings:, summaries:, texts: texts, notes: @notes)
39
+ end
40
+
41
+ private
42
+
43
+ def entries(key)
44
+ list = @data.is_a?(Hash) ? @data[key] : nil
45
+ return skip("the answer has no list of #{key}") unless list.is_a?(Array)
46
+
47
+ list.each { |entry| yield entry if entry.is_a?(Hash) }
48
+ end
49
+
50
+ def skip(note)
51
+ @notes << note
52
+ nil
53
+ end
54
+
55
+ def clean(value) = Findings::Text.collapse(value.to_s).sub(MARKDOWN_START, "").strip
56
+
57
+ def whole?(text) = text.match?(SENTENCE_END) && !text.match?(ELLIPSIS)
58
+
59
+ def heading_of(value, section)
60
+ text = clean(value)
61
+ return if text.empty?
62
+
63
+ long = text.length > HEADING_MAX
64
+ long ? skip("#{section.id}: the heading is longer than #{HEADING_MAX} characters") : text
65
+ end
66
+
67
+ def summary_of(value, section)
68
+ text = clean(value)
69
+ return if text.empty?
70
+ return skip("#{section.id}: the summary does not end in a whole sentence") unless whole?(text)
71
+
72
+ invented = numbers_not_in(text, section.all_items)
73
+ return text if invented.empty?
74
+
75
+ skip("#{section.id}: the summary has numbers that its pages do not have (#{invented.join(', ')})")
76
+ end
77
+
78
+ def texts
79
+ found = {}
80
+ entries("pages") do |entry|
81
+ item = @items[entry["id"].to_s]
82
+ next skip("page #{entry['id'].inspect} is not in the outline") unless item
83
+
84
+ text = text_of(entry["text"], item)
85
+ found[item.id] = text if text
86
+ end
87
+ found
88
+ end
89
+
90
+ # The text, an empty string when the model chose to write nothing, or nil when the text cannot be used.
91
+ def text_of(value, item)
92
+ return skip("page #{item.id}: the text is missing or is not text") unless value.is_a?(String)
93
+
94
+ text = clean(value)
95
+ return "" if text.empty?
96
+ return skip("page #{item.id}: the text does not end in a whole sentence") unless whole?(text)
97
+
98
+ invented = numbers_not_in(text, [item])
99
+ return text if invented.empty?
100
+
101
+ skip("page #{item.id}: the text has numbers that the page does not have (#{invented.join(', ')})")
102
+ end
103
+
104
+ def numbers_not_in(text, items)
105
+ source = items.flat_map { |item| source_of(item.facts) }.join(" ")
106
+ text.scan(NUMBER).uniq.reject { |number| source.match?(/(?<!\d)#{Regexp.escape(number)}(?!\d)/) }
107
+ end
108
+
109
+ def source_of(facts) = [facts.name, facts.title, facts.description, *facts.paragraphs, facts.path]
110
+ end
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,14 @@
1
+ role: "You write an llms.txt file for a website: a guide that tells AI assistants, which have never seen the site, what it offers and where to find it. You write the headings and summaries of its sections and the text beside each link, working only from the texts you are given for each page."
2
+ rules:
3
+ - "Write every heading, summary and text in {language}, the language of the texts you are given."
4
+ - "For every page you are given its name, title, address, importance (0 to 100) and tier (1 is the most important, a higher number is less important, and no tier means the page has not been ranked yet), the description from its meta tag, and the opening paragraphs of its text, always whole paragraphs. 'more_text' means the page has more text than you see. The pages of a section are listed from the most important to the least important."
5
+ - "Importance decides how much you write. The more important a page, the more you write about it, and the more it counts when you describe its section. As a rough guide, a tier 1 page gets up to three or four sentences that say what it offers and what sets it apart, a tier 2 page two sentences, a tier 3 page one sentence, and a page of a lower tier or without a tier one short sentence or nothing. A page whose link text already says everything gets an empty text. You decide each length yourself."
6
+ - "Write only whole sentences, each ending with a full stop. Never end a text in the middle of a sentence and never shorten with an ellipsis. Choose the most important parts of what you were given and keep them, or put several parts together in your own words. Do not start a text with the name of the page."
7
+ - "Use only facts that are in the texts of that page. Do not add numbers, prices, names or claims that are not there. Do not copy spelling or grammar mistakes: write correctly. Do not copy slogans, rows of check marks or arrows, sales calls such as 'book now', or praise such as 'a must'. Say plainly what is there. No exclamation marks."
8
+ - "The file lists only a selection of the site's pages, the most important ones, not everything the site has. A section is about its topic as a whole, not about the pages listed below it. Never describe a section by naming, listing or counting the pages listed below it, never write 'includes', 'covers', 'contains' or 'such as' followed by their names, and never suggest that the list is complete."
9
+ - "A section that has an index page is linked from its heading, and its index page is not listed as a link of its own. Its text is the starting point of the summary: merge what it says with what the other pages of the section show into your own sentences, so that nothing important the index page says is lost, and do not copy it word for word. Do not write a text for an index page."
10
+ - "Weigh a summary by importance. Say what the section is mostly about: what its index page and its most important pages (tiers 1 and 2) show, and the kinds of page that make up most of it. Leave out whatever only one or two minor pages show. For example, if a single low-ranked page of a section about trips is about a trip to a neighbouring country, the summary does not mention neighbouring countries. Something belongs in a summary only if the index page says it too, or an important page is about it, or it applies to many of the pages. A summary is one to three plain sentences, and may be longer only for an important section with many important pages."
11
+ - "A heading names the topic of its section in one to four words: a plain noun phrase, without the name of the site, without punctuation such as pipes or colons, and without words that the heading above it already contains. Name a subsection by what sets it apart from the other subsections of its parent, such as a region or a kind of page, and a section by what its index page is about. Never name a section after one of the pages listed in it."
12
+ - "Give every section a heading and a summary (an empty summary if its texts give you nothing to summarize), and every listed page a text (an empty string when it needs none)."
13
+ answer: "Answer with JSON only, in exactly this shape. Use the ids you were given."
14
+ shape: '{"sections":[{"id":"s1","heading":"...","summary":"..."}],"pages":[{"id":"p1","text":"..."}]}'
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yuno
4
+ module Proofreader
5
+ module Generate
6
+ # What the model decides for an llms.txt file: headings and summaries of the sections, and the text beside each
7
+ # link. Everything is by id. A page that has no entry in texts has no usable text from the model, and an entry
8
+ # that is empty means the model chose to write nothing. notes says what was left out of its answer and why.
9
+ module Wording
10
+ Result = Data.define(:headings, :summaries, :texts, :notes) do
11
+ # What is shown beside a link: the model's text (which may be empty on purpose), and without one the
12
+ # description the page already has.
13
+ def text_for(item) = texts.fetch(item.id) { Describe.fallback(item.facts) }
14
+ end
15
+
16
+ NONE = Result.new(headings: {}.freeze, summaries: {}.freeze, texts: {}.freeze, notes: [].freeze).freeze
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yuno
4
+ module Proofreader
5
+ module Generate
6
+ # Builds the llms.txt of one language: groups the pages, asks the model for the wording (unless there is no
7
+ # client), and renders the file. If the model cannot answer, the file is still made, without summaries, and the
8
+ # failure is reported, so the pages that were fetched are not lost.
9
+ class LlmsBuilder
10
+ # answer is the model's answer, or nil. failure is why there is none, or nil.
11
+ Result = Data.define(:text, :pages, :sections, :without_text, :answer, :notes, :failure)
12
+
13
+ def initialize(client: nil, progress: ->(_message) {}, log: Log.null)
14
+ @client = client
15
+ @progress = progress
16
+ @log = log
17
+ end
18
+
19
+ # others: [language code, address] for the llms.txt of each other language, listed at the end of the file.
20
+ def call(collected, language:, fallback_title:, others: [])
21
+ outline = Grouper.call(collected.entries(language))
22
+ home = collected.home.versions[language]
23
+ answer, wording, failure = ask(outline, home, language)
24
+ text = LlmsTxt.call(outline:, home:, wording:, language:, fallback_title:, others:)
25
+ Result.new(text:, pages: outline.items.size, sections: outline.all_sections.size,
26
+ without_text: without_text(outline, wording), answer:, notes: wording.notes, failure:)
27
+ end
28
+
29
+ private
30
+
31
+ def ask(outline, home, language)
32
+ return [nil, Wording::NONE, nil] unless @client && !outline.items.empty?
33
+
34
+ prompt = Wording::Prompt.new(language:)
35
+ @progress.call("Wording the #{language} file (this can take a minute)...")
36
+ answer = @client.generate(system: prompt.system_prompt, user: prompt.user_message(outline, home))
37
+ @progress.call("Got the wording: #{answer.model}, #{answer.seconds.round} s.")
38
+ [answer, Wording::Reader.call(answer.data, outline), nil]
39
+ rescue LlmError => e
40
+ @log.warn("llms wording failed", language:, message: e.message)
41
+ [nil, Wording::NONE, e.message]
42
+ end
43
+
44
+ def without_text(outline, wording)
45
+ outline.listed.count { |item| wording.text_for(item).empty? }
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yuno
4
+ module Proofreader
5
+ module Generate
6
+ # The lines generate llms prints: what was read, each file that was written and everything left out.
7
+ class LlmsReport
8
+ SHOWN_PROBLEMS = 10
9
+ SHOWN_NOTES = 5
10
+ CLOSING = "Check each file before you upload it: the headings, summaries and link texts that a model " \
11
+ "wrote can be wrong."
12
+
13
+ # requested: the languages that were asked for. files: the LlmsFile of each one that was written.
14
+ # saved_at: when the pages were saved, for a run that used saved pages, or nil.
15
+ def initialize(collected:, requested:, files:, saved_at: nil)
16
+ @collected = collected
17
+ @requested = requested
18
+ @files = files
19
+ @saved_at = saved_at
20
+ end
21
+
22
+ def lines
23
+ [read_line, "", *@files.map { |file| file_line(file) }, *unwritten_lines, *wording_lines,
24
+ *unranked_lines, *problem_lines, "", CLOSING]
25
+ end
26
+
27
+ private
28
+
29
+ def read_line
30
+ return saved_line if @saved_at
31
+
32
+ hint = partial? ? " (--all reads every page)" : ""
33
+ "Read the home page and #{pages_taken}#{hint}."
34
+ end
35
+
36
+ def saved_line
37
+ "Used the pages saved on #{@saved_at} UTC, nothing was fetched: the home page and #{pages_taken}."
38
+ end
39
+
40
+ def partial? = @collected.pages.size < @collected.considered
41
+
42
+ def pages_taken
43
+ others = @collected.considered
44
+ return "all #{others} other pages" unless partial?
45
+
46
+ "the #{@collected.pages.size} most important of #{others} other pages"
47
+ end
48
+
49
+ def file_line(file)
50
+ built = file.built
51
+ detail = ["#{built.pages} pages in #{built.sections} sections"]
52
+ detail << "#{built.without_text} without a text" if built.without_text.positive?
53
+ detail << model_detail(built.answer) if built.answer
54
+ "Wrote #{file.path} (#{detail.join(', ')}). Upload it to #{file.address}"
55
+ end
56
+
57
+ def model_detail(answer)
58
+ "#{answer.model}, #{answer.seconds.round} s, tokens in/out " \
59
+ "#{thousands(answer.input_tokens)} / #{thousands(answer.output_tokens)}"
60
+ end
61
+
62
+ def thousands(number) = number.to_i.to_s.reverse.scan(/\d{1,3}/).join(",").reverse
63
+
64
+ def unwritten_lines
65
+ (@requested - @files.map(&:language)).map do |language|
66
+ "No #{language} version could be read, so llms-#{language}.txt was not written."
67
+ end
68
+ end
69
+
70
+ def wording_lines
71
+ lines = @files.flat_map { |file| [*failure_lines(file), *unused_lines(file)] }
72
+ lines.empty? ? [] : ["", *lines]
73
+ end
74
+
75
+ def failure_lines(file)
76
+ failure = file.built.failure
77
+ return [] unless failure
78
+
79
+ ["The model could not word llms-#{file.language}.txt (#{failure}). It has no summaries, and its " \
80
+ "headings are made from the page addresses."]
81
+ end
82
+
83
+ def unused_lines(file)
84
+ notes = file.built.notes
85
+ return [] if notes.empty?
86
+
87
+ ["Left out of the model's answer for #{file.language}:", *notes.first(SHOWN_NOTES).map do |note|
88
+ " - #{note}"
89
+ end,
90
+ *more_line(notes.size - SHOWN_NOTES)]
91
+ end
92
+
93
+ def unranked_lines
94
+ return [] unless @collected.unranked.positive?
95
+
96
+ ["", "#{@collected.unranked} of these pages have no importance yet, so they come in the order of the " \
97
+ "sheet. Run: yuno-proofreader analyze"]
98
+ end
99
+
100
+ def problem_lines
101
+ problems = @collected.problems
102
+ return [] if problems.empty?
103
+
104
+ ["", "Left out:", *problems.first(SHOWN_PROBLEMS).map { |problem| " - #{problem}" },
105
+ *more_line(problems.size - SHOWN_PROBLEMS)]
106
+ end
107
+
108
+ def more_line(count) = count.positive? ? [" ... and #{count} more"] : []
109
+ end
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yuno
4
+ module Proofreader
5
+ module Generate
6
+ # Writes the llms.txt of one language, in the format described at llmstxt.org: the title and a quoted summary
7
+ # of the site (from the home page), then one section per group of pages with its summary and its links. A
8
+ # section with an index page is linked from its heading, and the index page is not listed again. The file ends
9
+ # with links to the llms.txt of the other languages. The headings, summaries and link texts are the model's.
10
+ # Without a model, headings are made from the addresses and the summary of a section is the description of its
11
+ # index page. others: [language code, address] for each other language that has a file.
12
+ class LlmsTxt
13
+ MORE_PAGES = { "de" => "Weitere Seiten", "en" => "More pages", "es" => "Más páginas", "fr" => "Autres pages",
14
+ "it" => "Altre pagine", "pt" => "Outras páginas" }.freeze
15
+ DEFAULT_MORE = "More pages"
16
+ OTHER_LANGUAGES = { "de" => "Andere Sprachen", "en" => "Other languages", "es" => "Otros idiomas",
17
+ "fr" => "Autres langues", "it" => "Altre lingue", "pt" => "Outros idiomas",
18
+ "nl" => "Andere talen" }.freeze
19
+ DEFAULT_OTHER = "Other languages"
20
+ NAMES = { "de" => "Deutsch", "en" => "English", "es" => "Español", "fr" => "Français", "it" => "Italiano",
21
+ "pt" => "Português", "nl" => "Nederlands" }.freeze
22
+
23
+ def self.call(**) = new(**).call
24
+
25
+ def initialize(outline:, home:, wording:, language:, fallback_title:, others: [])
26
+ @outline = outline
27
+ @home = home
28
+ @wording = wording
29
+ @language = language
30
+ @fallback_title = fallback_title
31
+ @others = others
32
+ end
33
+
34
+ def call
35
+ lines = ["# #{title}"]
36
+ lines.push("", "> #{@home.description}") if @home && !@home.description.empty?
37
+ @outline.sections.each { |section| lines.concat(section_lines(section, "##")) }
38
+ lines.concat(more_pages_lines)
39
+ lines.concat(other_language_lines)
40
+ "#{lines.join("\n")}\n"
41
+ end
42
+
43
+ private
44
+
45
+ def title = [@home&.title, @home&.name].find { |text| !text.to_s.empty? } || @fallback_title
46
+
47
+ def base(code) = code.split("-").first
48
+
49
+ def section_lines(section, mark)
50
+ lines = ["", "#{mark} #{heading(section)}"]
51
+ summary = summary_for(section)
52
+ lines.push("", summary) if summary
53
+ links = section.items.map { |item| link(item) }
54
+ lines.push("", *links) unless links.empty?
55
+ lines.concat(section.children.flat_map { |child| section_lines(child, "###") })
56
+ end
57
+
58
+ def heading(section)
59
+ text = @wording.headings.fetch(section.id) { humanize(section.slug) }
60
+ section.hub ? "[#{escape(text)}](#{address(section.hub.facts.url)})" : text
61
+ end
62
+
63
+ # The model's summary already carries what the index page says. Without one, the index page's own description.
64
+ def summary_for(section)
65
+ @wording.summaries[section.id] || (own_text(section.hub) if section.hub)
66
+ end
67
+
68
+ def own_text(hub)
69
+ text = Describe.fallback(hub.facts)
70
+ text unless text.empty?
71
+ end
72
+
73
+ def link(item)
74
+ facts = item.facts
75
+ line = "- [#{escape(Describe.label(facts.name))}](#{address(facts.url)})"
76
+ text = @wording.text_for(item)
77
+ text.empty? ? line : "#{line}: #{text}"
78
+ end
79
+
80
+ def more_pages_lines
81
+ return [] if @outline.loose.empty?
82
+
83
+ ["", "## #{MORE_PAGES.fetch(base(@language), DEFAULT_MORE)}", "", *@outline.loose.map { |item| link(item) }]
84
+ end
85
+
86
+ def other_language_lines
87
+ return [] if @others.empty?
88
+
89
+ ["", "## #{OTHER_LANGUAGES.fetch(base(@language), DEFAULT_OTHER)}", "",
90
+ *@others.map { |code, url| "- [#{escape(language_name(code))}](#{url})" }]
91
+ end
92
+
93
+ # The name of a language in that language. A region such as pt-br stays visible, so two variants differ.
94
+ def language_name(code)
95
+ name = NAMES.fetch(base(code), code)
96
+ code.include?("-") ? "#{name} (#{code})" : name
97
+ end
98
+
99
+ def humanize(slug) = slug.tr("-_", " ").split.map(&:capitalize).join(" ")
100
+
101
+ def escape(text) = text.gsub(/[\[\]]/) { |bracket| "\\#{bracket}" }
102
+
103
+ def address(url) = url.gsub(" ", "%20").gsub(")", "%29")
104
+ end
105
+ end
106
+ end
107
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "uri"
5
+
6
+ module Yuno
7
+ module Proofreader
8
+ module Generate
9
+ # One llms.txt written to the data folder, with the address it is meant to be uploaded to.
10
+ LlmsFile = Data.define(:language, :path, :address, :built)
11
+
12
+ # Writes the llms.txt of each language to the data folder, with links to the files of the other languages.
13
+ class LlmsWriter
14
+ def initialize(site:, builder:)
15
+ @site = site
16
+ @builder = builder
17
+ end
18
+
19
+ # Returns the files that were written. A language none of whose pages could be read has no file.
20
+ def call(collected, languages)
21
+ languages.filter_map { |language| write(collected, language) }
22
+ end
23
+
24
+ private
25
+
26
+ def write(collected, language)
27
+ return unless collected.readable?(language)
28
+
29
+ built = @builder.call(collected, language:, fallback_title: URI.parse(@site.website).host,
30
+ others: others(collected, language))
31
+ path = File.join(File.expand_path(@site.data_dir), "llms-#{language}.txt")
32
+ write_text(path, built.text)
33
+ LlmsFile.new(language:, path:, address: address(language), built:)
34
+ end
35
+
36
+ # The llms.txt of the other languages, as [code, address].
37
+ # Only languages whose pages could be read have one.
38
+ def others(collected, language)
39
+ (@site.languages - [language]).select { |code| collected.readable?(code) }
40
+ .map { |code| [code, address(code)] }
41
+ end
42
+
43
+ def address(language) = "#{@site.website}#{@site.prefixes.fetch(language)}/llms.txt"
44
+
45
+ def write_text(path, text)
46
+ FileUtils.mkdir_p(File.dirname(path))
47
+ File.write(path, text, encoding: "UTF-8")
48
+ rescue SystemCallError => e
49
+ raise ConfigError, "Could not write #{path}: #{e.message}"
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yuno
4
+ module Proofreader
5
+ module Generate
6
+ # One page in the outline, with the id the model refers to it by.
7
+ Item = Data.define(:id, :facts)
8
+
9
+ # A group of pages that share the start of their address. hub is the page at the address of the group itself
10
+ # (its index page), when there is one. items are the other pages directly in the group, children the groups
11
+ # below it. Ids are given in the order the file lists things.
12
+ Section = Data.define(:id, :slug, :hub, :items, :children) do
13
+ def all_items = [hub, *items, *children.flat_map(&:all_items)].compact
14
+
15
+ def listed_items = [*items, *children.flat_map(&:listed_items)]
16
+ end
17
+
18
+ # The sections in order of their most important page, and the pages that belong to no section.
19
+ Outline = Data.define(:sections, :loose) do
20
+ def all_sections = sections.flat_map { |section| [section, *section.children] }
21
+
22
+ def items = [*sections.flat_map(&:all_items), *loose]
23
+
24
+ def listed = [*sections.flat_map(&:listed_items), *loose]
25
+ end
26
+
27
+ # Groups pages by the start of their address. The first part of the path makes a section and the second a
28
+ # subsection, and a group needs at least two pages to get a heading of its own. Nothing here asks a model:
29
+ # the addresses of a site already say what belongs together.
30
+ class Grouper
31
+ MIN_GROUP = 2
32
+ Row = Data.define(:facts, :rank, :segments)
33
+
34
+ def self.call(entries) = new(entries).call
35
+
36
+ # entries: Facts, most important first.
37
+ def initialize(entries)
38
+ rows = entries.each_with_index.map do |facts, index|
39
+ Row.new(facts:, rank: index, segments: segments_of(facts.path))
40
+ end
41
+ @rows = rows.reject { |row| row.segments.empty? }.uniq(&:segments)
42
+ @counters = Hash.new(0)
43
+ end
44
+
45
+ def call
46
+ sections = []
47
+ loose = []
48
+ @rows.group_by { |row| row.segments.first }.each do |slug, group|
49
+ group.size >= MIN_GROUP ? sections << top(slug, group) : loose.concat(group)
50
+ end
51
+ Outline.new(sections:, loose: loose.map { |row| item(row) })
52
+ end
53
+
54
+ private
55
+
56
+ def segments_of(path) = path.split("/").reject(&:empty?)
57
+
58
+ def next_id(prefix) = "#{prefix}#{@counters[prefix] += 1}"
59
+
60
+ def item(row) = Item.new(id: next_id("p"), facts: row.facts)
61
+
62
+ def split_hub(rows, depth)
63
+ hub = rows.find { |row| row.segments.size == depth }
64
+ [hub, rows - [hub]]
65
+ end
66
+
67
+ def top(slug, group)
68
+ hub, rest = split_hub(group, 1)
69
+ nested, flat = subgroups(rest)
70
+ id = next_id("s")
71
+ Section.new(id:, slug:, hub: (item(hub) if hub), items: items_of(flat.flat_map(&:last)),
72
+ children: nested.map { |name, rows| leaf(name, rows) })
73
+ end
74
+
75
+ # The pages below a section: the groups that get a heading of their own, and the single pages that do not.
76
+ def subgroups(rows)
77
+ rows.group_by { |row| row.segments[1] }.partition { |_name, group| group.size >= MIN_GROUP }
78
+ end
79
+
80
+ def items_of(rows) = rows.sort_by(&:rank).map { |row| item(row) }
81
+
82
+ def leaf(slug, rows)
83
+ hub, rest = split_hub(rows, 2)
84
+ id = next_id("s")
85
+ hub_item = hub && item(hub)
86
+ Section.new(id:, slug:, hub: hub_item, items: rest.sort_by(&:rank).map { |row| item(row) }, children: [])
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end