|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Jobs |
| 4 | + class LocalizePosts < ::Jobs::Base |
| 5 | + cluster_concurrency 1 |
| 6 | + sidekiq_options retry: false |
| 7 | + |
| 8 | + BATCH_SIZE = 50 |
| 9 | + |
| 10 | + def execute(args) |
| 11 | + return if !SiteSetting.discourse_ai_enabled |
| 12 | + return if !SiteSetting.ai_translation_enabled |
| 13 | + |
| 14 | + locales = SiteSetting.experimental_content_localization_supported_locales.split("|") |
| 15 | + return if locales.blank? |
| 16 | + |
| 17 | + limit = args[:limit] || BATCH_SIZE |
| 18 | + |
| 19 | + locales.each do |locale| |
| 20 | + posts = |
| 21 | + Post |
| 22 | + .joins( |
| 23 | + "LEFT JOIN post_localizations pl ON pl.post_id = posts.id AND pl.locale = #{ActiveRecord::Base.connection.quote(locale)}", |
| 24 | + ) |
| 25 | + .where(deleted_at: nil) |
| 26 | + .where("posts.user_id > 0") |
| 27 | + .where.not(raw: [nil, ""]) |
| 28 | + .where.not(locale: nil) |
| 29 | + .where.not(locale: locale) |
| 30 | + .where("pl.id IS NULL") |
| 31 | + |
| 32 | + if SiteSetting.ai_translation_backfill_limit_to_public_content |
| 33 | + posts = |
| 34 | + posts.joins(:topic).where( |
| 35 | + topics: { |
| 36 | + category_id: Category.where(read_restricted: false).select(:id), |
| 37 | + archetype: "regular", |
| 38 | + }, |
| 39 | + ) |
| 40 | + end |
| 41 | + |
| 42 | + if SiteSetting.ai_translation_backfill_max_age_days > 0 |
| 43 | + posts = |
| 44 | + posts.where( |
| 45 | + "posts.created_at > ?", |
| 46 | + SiteSetting.ai_translation_backfill_max_age_days.days.ago, |
| 47 | + ) |
| 48 | + end |
| 49 | + |
| 50 | + posts = posts.order(updated_at: :desc).limit(limit) |
| 51 | + |
| 52 | + next if posts.empty? |
| 53 | + |
| 54 | + posts.each do |post| |
| 55 | + begin |
| 56 | + DiscourseAi::Translation::PostLocalizer.localize(post, locale) |
| 57 | + rescue FinalDestination::SSRFDetector::LookupFailedError |
| 58 | + # do nothing, there are too many sporadic lookup failures |
| 59 | + rescue => e |
| 60 | + DiscourseAi::Translation::VerboseLogger.log( |
| 61 | + "Failed to translate post #{post.id} to #{locale}: #{e.message}", |
| 62 | + ) |
| 63 | + end |
| 64 | + end |
| 65 | + |
| 66 | + DiscourseAi::Translation::VerboseLogger.log("Translated #{posts.size} posts to #{locale}") |
| 67 | + end |
| 68 | + end |
| 69 | + end |
| 70 | +end |
0 commit comments