Class: YouTubeChapterGenerationWorker

Inherits:
Object
  • Object
show all
Includes:
Sidekiq::Job
Defined in:
app/workers/youtube_chapter_generation_worker.rb

Overview

Generates YouTube chapter markers via AssemblyAI LLM and persists them as
VideoChapter rows on the Video for review/edit. Push to YouTube happens
from the CRM via YouTube::ChapterService#push_chapters.

Instance Method Summary collapse

Instance Method Details

#perform(video_id) ⇒ Object



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
# File 'app/workers/youtube_chapter_generation_worker.rb', line 12

def perform(video_id)
  video = Video.find_by(id: video_id)
  unless video
    Rails.logger.warn("[YouTubeChapterGenerationWorker] Video #{video_id} not found, skipping")
    return
  end

  if video.youtube_id.blank?
    Rails.logger.info("[YouTubeChapterGenerationWorker] Video #{video_id} has no YouTube ID, skipping")
    mark_failed(video, 'Video has no YouTube ID.')
    return
  end

  unless video.has_structured_transcript_json? && video.structured_transcript_paragraphs.present?
    Rails.logger.info("[YouTubeChapterGenerationWorker] Video #{video_id} has no structured transcript, skipping")
    mark_failed(video, 'Video has no transcript paragraphs.')
    return
  end

  video.update!(
    youtube_chapters_generation_status: 'processing',
    youtube_chapters_generation_error: nil
  )

  Rails.logger.info("[YouTubeChapterGenerationWorker] Generating chapters for video #{video_id}")

  chapter_service = YouTube::ChapterService.new
  chapters = chapter_service.preview_chapters(video)

  if chapters.empty?
    mark_failed(
      video,
      chapter_service.preview_failure_message.presence ||
        'No chapters could be generated. The transcript may be too short, or paragraph timings may be missing — re-run transcript polish, then try again.'
    )
    Rails.logger.warn("[YouTubeChapterGenerationWorker] No chapters for video #{video_id}")
    return
  end

  chapter_service.replace_chapters!(video, chapters)
  video.update!(
    youtube_chapters_generation_status: 'complete',
    youtube_chapters_generation_error: nil
  )

  Rails.logger.info("[YouTubeChapterGenerationWorker] Saved #{chapters.length} chapters for video #{video_id}")
rescue YouTube::OauthService::TokenRefreshError, YouTube::ApiClient::ApiError => e
  v = Video.find_by(id: video_id)
  mark_failed(v, e.message) if v
  Rails.logger.error("[YouTubeChapterGenerationWorker] API/OAuth error for video #{video_id}: #{e.message}")
  raise
rescue StandardError => e
  v = Video.find_by(id: video_id)
  mark_failed(v, e.message) if v
  Rails.logger.error("[YouTubeChapterGenerationWorker] Error for video #{video_id}: #{e.message}")
  raise
end