Class: RestaurantTags::AiHelpTitleAllTagWorker

Inherits:
ApplicationWorker show all
Defined in:
app/workers/restaurant_tags/ai_help_title_all_tag_worker.rb

Instance Method Summary collapse

Methods inherited from ApplicationWorker

unlimited_retry

Instance Method Details

#perform(tag_ids) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
# File 'app/workers/restaurant_tags/ai_help_title_all_tag_worker.rb', line 5

def perform(tag_ids)
  I18n.with_locale(:en) do
    restaurant_tags = RestaurantTag.where(id: tag_ids).where.not(title_en: [nil, ''])
    if restaurant_tags.blank?
      raise 'No RestaurantTag found.'
    end

    # Process restaurant tags in batches of 10
    restaurant_tags.in_groups_of(10, false) do |tag_batch|
      translation_items = tag_batch.map do |restaurant_tag|
        next if restaurant_tag.title_en.blank? # Skip if title_en is missing

        last_word = restaurant_tag.title_en.split(':').last.strip

        {
          'input_title_en' => last_word,
          'output_title_th' => '',
          'output_title_cn' => '',
        }
      end.compact

      prompt = <<~PROMPT
        Hungry Hub is an online reservation application for the best restaurant offers in Thailand.
        hungry hub has restaurant tags, which are keywords or short labels used to describe or categorize the type of cuisine, dining style, popular zone, shopping mall, BTS, MRT, Location, Facilities, Admin, Hashtag, Occasion, and Offer.
        These tags help customers quickly understand the restaurant's concept or theme and make it easier to find.

        You are a language specialist helping translate and generate titles for restaurant tags.

        Please help translate the following titles into both Thai and Chinese, using appropriate, natural phrasing for each language.

        Translation items:
        #{translation_items.to_json}

        Ensure that your response follows this JSON format with each item translated:

        [
          {
            "input_title_en": "Input English title",
            "output_title_th": "Translated Thai title",
            "output_title_cn": "Translated Chinese title"
          },
          ...
        ]
      PROMPT

      # Send the prompt to the AI API
      faraday = OpenrouterClient.create_connection
      response = faraday.post('/api/v1/chat/completions') do |req|
        req.body = {
          model: 'anthropic/claude-3.5-sonnet',
          messages: [
            { role: 'user', content: prompt },
          ],
        }.to_json
      end

      if response.success?
        response_data = JSON.parse(response.body)
        json_string = response_data['choices'][0]['message']['content']
        json_match = json_string.match(/\[.*\]/m)

        if json_match
          json_string = json_match[0]
          begin
            translations = JSON.parse(json_string)

            translations.each_with_index do |json_data, index|
              restaurant_tag = tag_batch[index]
              prefix = restaurant_tag.title_en.split(':').first.strip

              # Prefix the translations if present
              if json_data['output_title_th'].present?
                json_data['output_title_th'] =
                  "#{prefix}:#{json_data['output_title_th']}"
              end
              if json_data['output_title_cn'].present?
                json_data['output_title_cn'] =
                  "#{prefix}:#{json_data['output_title_cn']}"
              end

              save_data(restaurant_tag, json_data)
            end
          rescue JSON::ParserError
            raise "Error: The response content is not valid JSON for batch, response: #{json_string}"
          end
        else
          raise "Error: No valid JSON array found in the response for batch, response: #{json_string}"
        end
      else
        raise "HTTP error occurred: #{response.status} - #{response.body}"
      end
    end
  end
rescue ActiveRecord::RecordNotFound
  APMErrorHandler.report('Tag not found')
rescue StandardError => e
  APMErrorHandler.report('Failed to generate titles', exception: e)
end