Class: GptTranslate::Generator

Inherits:
Jekyll::Generator
  • Object
show all
Defined in:
lib/jekyll-chatgpt-translate/generator.rb

Overview

Pages generator.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2023-2024 Yegor Bugayenko

License

MIT

Defined Under Namespace

Classes: DownloadedFile

Instance Method Summary collapse

Instance Method Details

#generate(site) ⇒ Object

Main plugin action, called by Jekyll-core



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/jekyll-chatgpt-translate/generator.rb', line 46

def generate(site)
  Jekyll.logger.info("jekyll-chatgpt-translate #{GptTranslate::VERSION} starting...")
  config ||= site.config['chatgpt-translate'] || {}
  home = config['tmpdir'] || '_chatgpt-translate'
  key = api_key(config)
  if key.nil?
    Jekyll.logger.info('jekyll-chatgpt-translate requires OPENAI_API_KEY environment variable')
    return
  end
  layout = config['layout'] || 'translated'
  version = config['version'] || GptTranslate::VERSION
  threshold = config['threshold'] || 1024
  min_chars = config['min_chars'] || 128
  start = Time.now
  translated = 0
  copied = 0
  model = config['model'] || 'gpt-3.5-turbo'
  marker = "Translated by ChatGPT #{model}#{version.empty? ? '' : "/#{version}"}"
  site.posts.docs.shuffle.each_with_index do |doc, pos|
    plain = GptTranslate::Plain.new(doc.content).to_s
    layout = doc['layout']
    config['targets'].each do |target|
      pstart = Time.now
      link = GptTranslate::Permalink.new(doc, target['permalink']).to_path
      lang = target['language']
      raise 'Language must be defined for each target' if target.nil?
      only = target['only']
      if !only.nil? && layout != only
        Jekyll.logger.debug("Not translating #{link.inspect}, b/c 'only' set to '#{only}'")
        next
      end
      path = File.join(home, lang, doc.basename.gsub(/\.md$/, "-#{lang}.md"))
      FileUtils.mkdir_p(File.dirname(path))
      File.write(
        path,
        [
          '---',
          "layout: #{target['layout'] || layout}",
          "title: #{doc['title'].to_json}",
          "description: #{doc['description'].to_json}",
          "permalink: #{link.to_json}",
          'chatgpt-translate:',
          "  original-url: #{doc.url.to_json}",
          "  language: #{lang.to_json}",
          "  model: #{model.to_json}",
          '---'
        ].join("\n")
      )
      html = config['no_download'].nil? ? GptTranslate::Ping.new(site, link).download : nil
      needed = false
      added = false
      if html.nil?
        Jekyll.logger.info("The page is absent, need to translate #{link.inspect}")
        needed = true
      else
        copied += 1
        site.static_files << DownloadedFile.new(site, link, html)
        added = true
        if version.empty?
          Jekyll.logger.info("Re-translation not required, since version is empty: #{link.inspect}")
        elsif html.include?(marker)
          Jekyll.logger.info("No need to translate, the page exists at \
#{link.inspect} (#{html.split.count} words)")
        else
          Jekyll.logger.info("Re-translation required for #{link.inspect}")
          needed = true
        end
      end
      if translated >= threshold
        Jekyll.logger.info("Page ##{pos} is ignored, we are over the threshold of #{threshold}: #{link}")
      elsif needed
        gpt = GptTranslate::ChatGPT.new(
          key,
          model,
          target['source'] || config['source'] || 'en',
          lang
        )
        foreign = gpt.translate(
          plain,
          min: min_chars,
          window_length: (config['window_length'] || '2048').to_i
        )
        File.write(
          path,
          [
            '',
            foreign,
            '',
            "#{marker} on #{Time.now.strftime('%Y-%m-%d at %H:%M')}\n{: .jekyll-chatgpt-translate}"
          ].join("\n"),
          mode: 'a+'
        )
        site.pages << Jekyll::Page.new(site, site.source, File.dirname(path), File.basename(path))
        site.static_files.delete_if { |f| f.is_a?(DownloadedFile) && f.link == link }
        added = true
        translated += 1
        Jekyll.logger.info("Translated via ChatGPT \
in #{(Time.now - pstart).round(2)}s: #{path} (#{File.size(path)} bytes)")
      end
      next unless added
      doc.data['chatgpt-translate'] ||= {}
      doc.data['chatgpt-translate']['model'] ||= model
      doc.data['chatgpt-translate']['urls'] ||= {}
      doc.data['chatgpt-translate']['urls'][lang] = link
    end
  end
  Jekyll.logger.info("jekyll-chatgpt-translate #{GptTranslate::VERSION}: \
#{translated} pages translated and #{copied} pages copied in #{(Time.now - start).round(2)}s")
end