2024-07-02 11:51:59 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Jobs
|
|
|
|
class StreamTopicAiSummary < ::Jobs::Base
|
|
|
|
sidekiq_options retry: false
|
|
|
|
|
|
|
|
def execute(args)
|
|
|
|
return unless topic = Topic.find_by(id: args[:topic_id])
|
|
|
|
return unless user = User.find_by(id: args[:user_id])
|
|
|
|
|
2024-07-03 20:48:18 -04:00
|
|
|
strategy = DiscourseAi::Summarization.default_strategy
|
|
|
|
return if strategy.nil? || !Guardian.new(user).can_see_summary?(topic)
|
2024-07-02 11:51:59 -04:00
|
|
|
|
|
|
|
guardian = Guardian.new(user)
|
|
|
|
return unless guardian.can_see?(topic)
|
|
|
|
|
2024-08-13 07:47:47 -04:00
|
|
|
skip_age_check = !!args[:skip_age_check]
|
2024-07-02 11:51:59 -04:00
|
|
|
|
|
|
|
streamed_summary = +""
|
|
|
|
start = Time.now
|
|
|
|
|
|
|
|
summary =
|
|
|
|
DiscourseAi::TopicSummarization
|
2024-08-13 07:47:47 -04:00
|
|
|
.new(strategy, topic, user)
|
|
|
|
.summarize(skip_age_check: skip_age_check) do |partial_summary|
|
2024-07-02 11:51:59 -04:00
|
|
|
streamed_summary << partial_summary
|
|
|
|
|
|
|
|
# Throttle updates.
|
2024-08-29 18:07:07 -04:00
|
|
|
if (Time.now - start > 0.3) || Rails.env.test?
|
2024-07-02 11:51:59 -04:00
|
|
|
payload = { done: false, ai_topic_summary: { summarized_text: streamed_summary } }
|
|
|
|
|
|
|
|
publish_update(topic, user, payload)
|
|
|
|
start = Time.now
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
publish_update(
|
|
|
|
topic,
|
|
|
|
user,
|
|
|
|
AiTopicSummarySerializer.new(summary, { scope: guardian }).as_json.merge(done: true),
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def publish_update(topic, user, payload)
|
|
|
|
MessageBus.publish("/discourse-ai/summaries/topic/#{topic.id}", payload, user_ids: [user.id])
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|