Class: Natsukantou::ChatGpt

Inherits:
Object
  • Object
show all
Includes:
UtilityBase
Defined in:
lib/natsukantou/chat_gpt.rb

Constant Summary collapse

SYSTEM_ROLE_TEMPLATE =
<<~SYSTEM_ROLE_TEMPLATE
  You are a professional XML translator, translating from %<lang_from>s to %<lang_to>s.
  You will be given a raw XML document. When translating, maintain XML structure as is.
  You are only allowed to return the translated XML and nothing else.
  IMPORTANT: ONLY RETURN TRANSLATED TEXT AND NOTHING ELSE.
SYSTEM_ROLE_TEMPLATE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logger

#logger

Methods included from ParseXml

#dom, #dom_node

Constructor Details

#initialize(app, access_token:, translate_by_section:) ⇒ ChatGpt

Returns a new instance of ChatGpt.

Parameters:

  • app (Hash)
  • access_token (String)

    API access token

  • translate_by_section (String)

    CSS selector to translate matched elements one by one. Specify a css path (e.g. “body>p”) to translate in smaller chunks.



24
25
26
27
28
29
30
31
32
33
# File 'lib/natsukantou/chat_gpt.rb', line 24

def initialize(
  app, access_token:,
  translate_by_section:
)
  @app = app
  @access_token = access_token

  ### Non request related setting
  @translate_by_section = translate_by_section
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



36
37
38
# File 'lib/natsukantou/chat_gpt.rb', line 36

def access_token
  @access_token
end

#envObject (readonly)

Returns the value of attribute env.



35
36
37
# File 'lib/natsukantou/chat_gpt.rb', line 35

def env
  @env
end

#translate_by_sectionObject (readonly)

Returns the value of attribute translate_by_section.



37
38
39
# File 'lib/natsukantou/chat_gpt.rb', line 37

def translate_by_section
  @translate_by_section
end

Instance Method Details

#call(env) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/natsukantou/chat_gpt.rb', line 39

def call(env)
  @env = env

  if translate_by_section
    env[:dom].css(translate_by_section).each do |node|
      next if node.text.empty?

      translated_xml = translate(node.to_xml)
      node.replace(dom_node(translated_xml))
    end
  else
    # TODO
  end

  env[:dom].lang = env[:lang_to].code

  @app.call(env)
end