2024-07-02 11:51:59 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
2024-10-15 12:53:26 -04:00
|
|
|
# A cache layer on top of our topic summarization engine. Also handle permissions.
|
2024-07-02 11:51:59 -04:00
|
|
|
class TopicSummarization
|
2024-10-15 12:53:26 -04:00
|
|
|
def self.for(topic, user)
|
|
|
|
new(DiscourseAi::Summarization.topic_summary(topic), user)
|
2024-07-03 20:48:18 -04:00
|
|
|
end
|
|
|
|
|
2024-10-15 12:53:26 -04:00
|
|
|
def initialize(summarizer, user)
|
|
|
|
@summarizer = summarizer
|
2024-08-13 07:47:47 -04:00
|
|
|
@user = user
|
2024-07-02 11:51:59 -04:00
|
|
|
end
|
|
|
|
|
2024-08-13 07:47:47 -04:00
|
|
|
def cached_summary
|
2024-10-15 12:53:26 -04:00
|
|
|
summarizer.existing_summary
|
2024-08-13 07:47:47 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def summarize(skip_age_check: false, &on_partial_blk)
|
2024-07-02 11:51:59 -04:00
|
|
|
# Existing summary shouldn't be nil in this scenario because the controller checks its existence.
|
2024-10-15 12:53:26 -04:00
|
|
|
return if !user && !cached_summary
|
2024-07-02 11:51:59 -04:00
|
|
|
|
2024-10-15 12:53:26 -04:00
|
|
|
return cached_summary if use_cached?(skip_age_check)
|
2024-07-02 11:51:59 -04:00
|
|
|
|
2024-10-15 12:53:26 -04:00
|
|
|
summarizer.delete_cached_summaries! if cached_summary
|
2024-07-02 11:51:59 -04:00
|
|
|
|
2024-10-15 12:53:26 -04:00
|
|
|
summarizer.summarize(user, &on_partial_blk)
|
2024-07-02 11:51:59 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2024-10-15 12:53:26 -04:00
|
|
|
attr_reader :summarizer, :user
|
2024-07-02 11:51:59 -04:00
|
|
|
|
2024-08-13 07:47:47 -04:00
|
|
|
def use_cached?(skip_age_check)
|
|
|
|
can_summarize = Guardian.new(user).can_request_summary?
|
|
|
|
|
2024-10-15 12:53:26 -04:00
|
|
|
cached_summary &&
|
2024-07-02 11:51:59 -04:00
|
|
|
!(
|
2024-10-15 12:53:26 -04:00
|
|
|
can_summarize && cached_summary.outdated &&
|
|
|
|
(skip_age_check || cached_summary.created_at < 1.hour.ago)
|
2024-07-02 11:51:59 -04:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|