Class: Presentation

Inherits:
Object
  • Object
show all
Defined in:
lib/md2slides/audio.rb,
lib/md2slides/video.rb,
lib/md2slides/presentation.rb,
lib/md2slides/text_to_speech.rb

Constant Summary collapse

AUDIO_RATE =

XXX: Google Text to Speech produces at this rate…

24000
VIDEO_FRAME_RATE =
1
VIDEO_ONLY_DURATION =
4
APPLICATION_NAME =
'md2slides'
GOOGLE_OAUTH_SCOPE =
[
	"https://www.googleapis.com/auth/drive",
#		"https://www.googleapis.com/auth/userinfo.email",
#		"https://www.googleapis.com/auth/userinfo.profile",
	"https://www.googleapis.com/auth/presentations",
]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(md = nil) ⇒ Presentation

Returns a new instance of Presentation.



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
# File 'lib/md2slides/presentation.rb', line 22

def initialize(md = nil)
	@md = md
	url = md&.attributes[:url]
	if url =~ %r{https://docs.google.com/presentation/d/([^\/ ]+).*$}
		@id = $1
	elsif url
		raise("ERROR: invalid URL: #{url}")
	end

	@authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
		json_key_io: File.open(ENV['GOOGLE_APPLICATION_CREDENTIALS']),
		scope: GOOGLE_OAUTH_SCOPE)

	@slides_service = Google::Apis::SlidesV1::SlidesService.new
	@slides_service.client_options.application_name = APPLICATION_NAME
	@slides_service.authorization = @authorizer

	@drive_service = Google::Apis::DriveV3::DriveService.new
	@drive_service.client_options.application_name = APPLICATION_NAME
	@drive_service.authorization = @authorizer

	@requests = []

	# XXX: this seript always runs by an API user...
	#people_service = Google::Apis::PeopleV1::PeopleServiceService.new
	#people_service.authorization = @authorizer
	#profile = people_service.get_person("people/me", person_fields: "names,emailAddresses")
	#name = profile.names.first.display_name
	#email = profile.email_addresses.first.value
	#puts "#{name}: #{email}"
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



16
17
18
# File 'lib/md2slides/presentation.rb', line 16

def id
  @id
end

Class Method Details

.filename_sanitize(s) ⇒ Object



18
19
20
# File 'lib/md2slides/presentation.rb', line 18

def self.filename_sanitize(s)
	s&.gsub(/[\/\\:\*\?"<>\|]/, '')
end

.text_to_speech(text, filename) ⇒ Object



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
# File 'lib/md2slides/text_to_speech.rb', line 8

def self.text_to_speech(text, filename)
	extname = File.extname(filename)
	if extname
		if filename =~ /^(.*)#{extname}$/
			filename = $1
		else
			raise("invalid extname #{extname} in \"#{filename}\"")
		end
	end
	filename += '.mp3'

	text.strip!
	if text !~ /^<speak>/
		text = "<speak>#{text}</speak>"
	end

	response = Google::Cloud::TextToSpeech.new.synthesize_speech(
	    # XXX: I don't know how to create an object of Google::Cloud::TextToSpeech::SynthesisInput...
	    { ssml: text },
	    #
	    # Standard is the cheapest.
	    #	ja-JP-Standard-A, B female
	    #	ja-JP-Standard-C, D male
	    # Wavenet is more expensive than standard.
	    #	https://cloud.google.com/text-to-speech/docs/voices?hl=ja
	    #	https://cloud.google.com/text-to-speech/pricing?hl=ja
	    #
	    #{ language_code: 'ja-JP', name: 'ja-JP-Wavenet-B' },
	    { language_code: 'ja-JP', name: 'ja-JP-Standard-D' },
	    { audio_encoding: :MP3 },
	    )

	File.open(filename, 'wb') do |file|
		file.write(response.audio_content)
	end

	return filename
end

Instance Method Details

#__data_path(basedir) ⇒ Object



366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/md2slides/presentation.rb', line 366

def __data_path(basedir)
	basedir = '.' if basedir.nil?
	if @md
		title = @md.first.title
		subtitle = @md.first.subtitle
	elsif @presentation
		title, subtitle = get_title
	end
	title = self.class.filename_sanitize(title)
	subtitle = self.class.filename_sanitize(subtitle)
	File.join(basedir, "#{title}-#{subtitle}-#{@id}")
end

#__data_slide_path(i, ext, basedir = nil) ⇒ Object



379
380
381
382
383
384
385
# File 'lib/md2slides/presentation.rb', line 379

def __data_slide_path(i, ext, basedir = nil)
	path = "slide-#{i}#{ext}"
	if basedir
		path = File.join(basedir, path)
	end
	path
end

#__get_element_text(element) ⇒ Object



242
243
244
# File 'lib/md2slides/presentation.rb', line 242

def __get_element_text(element)
	element&.shape&.text&.text_elements&.collect { |e| e.text_run&.content&.strip }&.compact&.join("\n")
end

#__get_presentationObject



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/md2slides/presentation.rb', line 54

def __get_presentation
	begin
		@authorizer.fetch_access_token!
		@presentation = @slides_service.get_presentation(@id)
	rescue => e
		require 'webrick'
		raise(e, "#{e.message} (#{e.status_code} " +
		    "#{WEBrick::HTTPStatus.reason_phrase(e.status_code)})\n" +
		    "#{e.full_message}")
	end
end

#__requestObject



150
151
152
153
154
155
156
157
158
159
160
# File 'lib/md2slides/presentation.rb', line 150

def __request
	return if @requests.empty?
	batch_update_request = Google::Apis::SlidesV1::BatchUpdatePresentationRequest.new(requests: @requests)
	begin
		@slides_service.batch_update_presentation(@id, batch_update_request)
		@requests = []
	rescue => e
		raise(e, "#{e.body}\n#{e.full_message}")
	end
	@presentation = @slides_service.get_presentation(@id)
end

#clearObject



299
300
301
302
303
304
305
306
307
# File 'lib/md2slides/presentation.rb', line 299

def clear
	existence_check
	n = @presentation.slides&.size.to_i
	while n > 0
		n -= 1
		delete_object(@presentation.slides[n].object_id_prop)
	end
	__request
end

#create(name) ⇒ Object



119
120
121
122
123
124
125
126
127
# File 'lib/md2slides/presentation.rb', line 119

def create(name)
	if exists?
		raise("already presentation exists!!")
	end
	presentation0 = Google::Apis::SlidesV1::Presentation.new(title: name)
	@presentation = @slides_service.create_presentation(presentation0)
	@id = @presentation.presentation_id
	puts "Create presentation #{name}: #{url}"
end

#create_slide(layout = 'TITLE_AND_BODY', insertion_index = nil) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/md2slides/presentation.rb', line 170

def create_slide(layout = 'TITLE_AND_BODY', insertion_index = nil)
	insertion_index ||= @presentation.slides&.size.to_i	# at the tail
	#
	# layout can be:
	# https://developers.google.com/apps-script/reference/slides/predefined-layout
	#
	@requests.push({
		create_slide: {
			#
			# XXX: object ID should be specified for performance...
			#
#				object_id_prop: object_id_prop,
			insertion_index: insertion_index,
			slide_layout_reference: {
				predefined_layout: layout,
			}
		}
	})
	__request
	@presentation.slides[insertion_index]
end

#deleteObject



129
130
131
132
133
134
135
136
137
138
# File 'lib/md2slides/presentation.rb', line 129

def delete
	existence_check
	begin
		@drive_service.delete_file(@id)
		@presentation = nil
		puts "deleted ID: #{@id}"
	rescue Google::Apis::ClientError => e
		puts "ERROR: failed deleting #{@id}: #{e.full_message}"
	end
end

#delete_object(object_id) ⇒ Object



162
163
164
165
166
167
168
# File 'lib/md2slides/presentation.rb', line 162

def delete_object(object_id)
	@requests.push({
		delete_object: {
			object_id_prop: object_id,
		}
	})
end

#delete_text(element) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/md2slides/presentation.rb', line 192

def delete_text(element)
	return if ! element.shape.instance_variable_defined?(:@placeholder)
	return if ! element.shape.instance_variable_defined?(:@text)
	@requests.push({
		delete_text: {
			object_id_prop: element.object_id_prop,
			text_range: {
				type: 'ALL'
			}
		}
	})
end

#download(dir = nil) ⇒ Object



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/md2slides/presentation.rb', line 421

def download(dir = nil)
	existence_check
	dir = __data_path(dir)
	parent = File.dirname(dir)
	files = Dir.glob("#{File.join(parent, "*#{@id}*")}")
	if files.empty?
		FileUtils.mkdir_p(dir)
	elsif files[0] != dir
		File.rename(files[0], dir)
	end
	lockfile = File.join(dir, '.lock')
	File.open(lockfile, File::RDWR|File::CREAT, 0644) do |f|
		f.flock(File::LOCK_EX | File::LOCK_NB)
		@presentation.slides.each_with_index do |slide, i|
			download_slide(i + 1, slide, dir)
		end
	end
end

#download_slide(i, slide, dir) ⇒ Object



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/md2slides/presentation.rb', line 404

def download_slide(i, slide, dir)
	print "slide #{i}: downloading..."
	#
	# a size of a width can be: SMALL (200), MEDIUM (800), LARGE (1600)
	# https://developers.google.com/workspace/slides/api/reference/rest/v1/presentations.pages/getThumbnail
	#
	thumbnail = @slides_service.get_presentation_page_thumbnail(
	    @id, slide.object_id_prop, thumbnail_properties_thumbnail_size: 'LARGE')
	URI.open(thumbnail.content_url) do |remote_file|
		path = __data_slide_path(i, '.png', dir)
		File.open(path, 'wb') do |file|
			file.write(remote_file.read)
		end
	end
	puts 'done'
end

#download_slide0(i, slide, dir) ⇒ Object

XXX: these do not work when the presentation is not shared globally.



394
395
396
397
398
399
400
401
402
# File 'lib/md2slides/presentation.rb', line 394

def download_slide0(i, slide, dir)
	url = export_url(i)
	URI.open(url) do |remote_file|
		path = __data_slide_path(i, '.png', dir)
		File.open(path, 'wb') do |file|
			file.write(remote_file.read)
		end
	end
end

#existence_checkObject



74
75
76
77
78
# File 'lib/md2slides/presentation.rb', line 74

def existence_check
	if ! exists?
		raise("presentation (ID: #{@id}) does not exists!!!")
	end
end

#exists?Boolean

Returns:

  • (Boolean)


66
67
68
69
70
71
72
# File 'lib/md2slides/presentation.rb', line 66

def exists?
	return false if ! @id
	if @presentation.nil?
		__get_presentation
	end
	!! @presentation
end

#export_url(i) ⇒ Object

XXX: these do not work when the presentation is not shared globally.



388
389
390
391
# File 'lib/md2slides/presentation.rb', line 388

def export_url(i)
	#@id && "https://docs.google.com/presentation/d/#{@id}/export/png?id=#{@id}&pageid=#{slide.object_id_prop}&width=1920&height=1080"
	@id && "https://docs.google.com/presentation/d/#{@id}/export/png?id=#{@id}&pageid=p#{i}&width=1920&height=1080"
end

#extentObject



84
85
86
87
88
89
90
# File 'lib/md2slides/presentation.rb', line 84

def extent
	existence_check
	width = @presentation.page_size.width.magnitude
	height = @presentation.page_size.height.magnitude
	unit = @presentation.page_size.width.unit
	return width, height, unit
end

#find_element(slide, type) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
# File 'lib/md2slides/presentation.rb', line 230

def find_element(slide, type)
	slide&.page_elements&.find do |e|
		case e.shape&.placeholder&.type
		when type
			true
#			else
#				p e.shape&.placeholder&.type
#				false
		end
	end
end

#generate_audio(dir = nil) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/md2slides/audio.rb', line 45

def generate_audio(dir = nil)
	dir = __data_path(dir)
	if @md
		@md.each_with_index do |page, i|
			generate_audio0(i + 1, page.comments, dir)
		end
	else
		@presentation.slides.each_with_index do |slide, i|
			generate_audio0(i + 1, get_slide_note(slide), dir)
		end
	end
end

#generate_audio0(i, notes, dir) ⇒ 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
# File 'lib/md2slides/audio.rb', line 5

def generate_audio0(i, notes, dir)
	print "slide \##{i}: generating audio... "
	path = __data_slide_path(i, '.m4a', dir)
	if notes
		opath = __data_slide_path(i, '.mp3', dir)
		opath = Presentation::text_to_speech(notes, opath)
		#
		# convert to .m4a, which contains duration in meta data.
		# this prevents unreasonable audio duration when combining
		# audio and video.
		#
		heading_silence = 2
		trailing_silence = 1
		cmd = <<~CMD
			ffmpeg -hide_banner -y				\
			    -f lavfi -t #{heading_silence}		\
			    -i anullsrc=r=#{AUDIO_RATE}:cl=mono		\
			    -i #{opath}					\
			    -f lavfi -t #{trailing_silence}		\
			    -i anullsrc=r=#{AUDIO_RATE}:cl=mono		\
			    -filter_complex "[0:a][1:a][2:a]concat=n=3:v=0:a=1[out]"	\
			    -map "[out]"				\
			    -c:a aac -b:a 64k #{path}
		CMD
		msg, errmsg, status = Open3.capture3(cmd)
		File.delete(opath) rescue
		if ! status.success?
			raise("ERROR: cannot convert audio: #{errmsg}")
		end
		puts 'done'
	else
		begin
			File.delete(path)
		rescue Errno::ENOENT => e
			# okay
		end
		puts "skip (no notes)"
	end
end

#generate_slide_video(i, dir) ⇒ Object



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
# File 'lib/md2slides/video.rb', line 7

def generate_slide_video(i, dir)
	img = __data_slide_path(i, '.png', dir)
	audio = __data_slide_path(i, '.m4a', dir)
	video = __data_slide_path(i, '.mp4', dir)

	if File.exists?(audio)
		audioin = "-i \"#{audio}\""
		timeopt = '-shortest'
	else
		audioin = "-f lavfi -i aevalsrc=0"
		timeopt = "-vframes #{VIDEO_FRAME_RATE * VIDEO_ONLY_DURATION}"
	end
	cmd = <<~CMD
		ffmpeg -hide_banner -y				\
		    -framerate #{VIDEO_FRAME_RATE} -loop 1 -i "#{img}" \
		    #{audioin} -map 0:v:0 -map 1:a:0		\
		    -c:v libx264 -tune stillimage		\
		    -c:a aac -ar #{AUDIO_RATE} -ac 1		\
		    -pix_fmt yuv420p #{timeopt} "#{video}"
	CMD
	msg, errmsg, status = Open3.capture3(cmd)
	if ! status.success?
		raise("ERROR: cannot produce video: #{errmsg}")
	end
end

#generate_video(dir = nil) ⇒ Object



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
# File 'lib/md2slides/video.rb', line 33

def generate_video(dir = nil)
	dir = __data_path(dir)
	pages = @md&.size || @presentation&.slides&.size.to_i
	for i in 1..pages
		print "slide \##{i}: generating video..."
		generate_slide_video(i, dir)
		puts "done"
	end

	print "concatenate video files..."
	videolist = 'video-list.txt'
	File.open(File.join(dir, videolist), 'w') do |f|
		for i in 1..pages
			f.puts("file #{__data_slide_path(i, '.mp4')}")
		end
	end
	video = 'video.mp4'
	cmd = <<~CMD
		cd "#{dir}" &&					\
		    ffmpeg -hide_banner -y -f concat -safe 0	\
		    -i "#{videolist}" -c copy "#{video}"
	CMD
	msg, errmsg, status = Open3.capture3(cmd)
	if ! status.success?
		raise("ERROR: cannot produce video: #{errmsg}")
	else
		puts 'done'
	end
end

#get_slide_note(slide) ⇒ Object



285
286
287
288
# File 'lib/md2slides/presentation.rb', line 285

def get_slide_note(slide)
	notes = slide.slide_properties.notes_page
	__get_element_text(find_element(notes, 'BODY'))
end

#get_slide_text(slide, re = 'BODY') ⇒ Object



246
247
248
# File 'lib/md2slides/presentation.rb', line 246

def get_slide_text(slide, re = 'BODY')
	__get_element_text(find_element(slide, re))
end

#get_titleObject



250
251
252
253
254
255
# File 'lib/md2slides/presentation.rb', line 250

def get_title
	slide = @presentation&.slides.first
	title = get_slide_text(slide, /(^TITLE|[^a-zA-Z]TITLE)$/)
	subtitle = get_slide_text(slide, 'SUBTITLE')
	return title, subtitle
end

#heightObject



96
97
98
# File 'lib/md2slides/presentation.rb', line 96

def height
	extent[1]
end

#listObject



309
310
311
312
313
314
315
316
# File 'lib/md2slides/presentation.rb', line 309

def list
	existence_check
	puts "title: #{@presentation.title}"
	puts "pages: #{@presentation.slides.size}"
	@presentation.slides.each_with_index do |slide, i|
		puts "- slide \##{i + 1} contains #{slide.page_elements.count} elements."
	end
end

#list_allObject



318
319
320
321
322
323
324
# File 'lib/md2slides/presentation.rb', line 318

def list_all
	query = "mimeType = 'application/vnd.google-apps.presentation' and trashed = false"
	response = @drive_service.list_files(q: query, fields: 'files(id, name)', page_size: 100)
	response.files.each do |file|
		puts "#{file.name}: #{file.id}"
	end
end

#set_bullet(element, bullet) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/md2slides/presentation.rb', line 217

def set_bullet(element, bullet)
	return if bullet.nil?
	@requests.push({
		create_paragraph_bullets: {
			object_id_prop: element.object_id_prop,
			text_range: {
				type: 'ALL',
			},
			bullet_preset: bullet,
		}
	})
end

#set_slide_note(slide, text) ⇒ Object



290
291
292
293
294
295
296
297
# File 'lib/md2slides/presentation.rb', line 290

def set_slide_note(slide, text)
	notes = slide.slide_properties.notes_page
	element = find_element(notes, 'BODY')
	if element.nil?
		raise("ERROR: no text box element found in notes!!!")
	end
	update_text(element, text)
end

#set_slide_subtitle(slide, title) ⇒ Object



270
271
272
# File 'lib/md2slides/presentation.rb', line 270

def set_slide_subtitle(slide, title)
	set_slide_title(slide, title, 'SUBTITLE')
end

#set_slide_text(slide, text, re = 'BODY', bullet = 'BULLET_DISC_CIRCLE_SQUARE') ⇒ Object



257
258
259
260
261
262
263
264
# File 'lib/md2slides/presentation.rb', line 257

def set_slide_text(slide, text, re = 'BODY', bullet = 'BULLET_DISC_CIRCLE_SQUARE')
	element = find_element(slide, re)
	if element.nil?
		raise("ERROR: no text element found!!!")
	end
	update_text(element, text)
	set_bullet(element, bullet)
end

#set_slide_title(slide, title, re = /(^TITLE|[^a-zA-Z]TITLE)$/) ⇒ Object



266
267
268
# File 'lib/md2slides/presentation.rb', line 266

def set_slide_title(slide, title, re = /(^TITLE|[^a-zA-Z]TITLE)$/)
	set_slide_text(slide, title, re, nil)
end

#set_title(title, subtitle = nil) ⇒ Object



274
275
276
277
278
279
280
281
282
283
# File 'lib/md2slides/presentation.rb', line 274

def set_title(title, subtitle = nil)
	existence_check
	if @presentation&.slides&.size.to_i == 0
		create_slide('TITLE')
	end
	slide = @presentation.slides.first
	set_slide_title(slide, title)
	set_slide_subtitle(slide, subtitle)
	__request
end

#share(user) ⇒ Object



140
141
142
143
144
145
146
147
148
# File 'lib/md2slides/presentation.rb', line 140

def share(user)
	existence_check
	permission = Google::Apis::DriveV3::Permission.new(
	    type: 'user',
	    role: 'writer', # 'reader', 'commenter', 'writer'
	    email_address: user
	    )
	@drive_service.create_permission(@id, permission, fields: "id")
end

#stick_out_checkObject



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/md2slides/presentation.rb', line 100

def stick_out_check
	msgs = []
	@presentation.slides.each_with_index do |slide, i|
		slide.page_elements.each do |element|
			next unless element.shape
			next unless element.transform
			x1 = element.transform.translate_x || 0
			x2 = x1 + element.size.width.magnitude rescue 0
			y1 = element.transform.translate_y || 0
			y2 = y1 + element.size.width.magnitude rescue 0
			puts "width: #{width}, height: #{height}"
			if x2 > width || y2 > height || x1 < 0 || y1 < 0
				msgs.push("slide #{i + 1}: sticking out: (#{x1},#{y1})-(#{x2},#{y2})")
			end
		end
	end
	raise(msgs.join("\n")) unless msgs.empty?
end

#updateObject



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/md2slides/presentation.rb', line 326

def update
	#
	# XXX: currently, clear all slides...
	#
	if exists?
		clear
	end
	@md.each do |page|
		if page.title_subtitle_only?
			layout = 'TITLE'
		elsif page.title_only?
			layout = 'SECTION_HEADER'
		else
			layout = 'TITLE_AND_BODY'
		end
		slide = create_slide(layout)
		if page.has_title?
			set_slide_title(slide, page.title)
		end
		if page.title_subtitle_only?
			set_slide_subtitle(slide, page.subtitle)
		else
			texts = page.map do |e|
				# calculate the indentation.
				n = (e.attributes&.[](:indent).to_i / 2).to_i
				"\t" * n + e.value
			end.join("\n")
			if texts.size > 0
				set_slide_text(slide, texts)
				# set_slide_text(slide, texts,
				#    'BODY', 'NUMBERED_DIGIT_ALPHA_ROMAN')
			end
		end
		if page.has_comments?
			set_slide_note(slide, page.comments)
		end
	end
	__request
end

#update_text(element, text) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
# File 'lib/md2slides/presentation.rb', line 205

def update_text(element, text)
	delete_text(element)
	return if text.nil? || text.empty?
	@requests.push({
		insert_text: {
			object_id_prop: element.object_id_prop,
			insertion_index: 0,
			text: text
		}
	})
end

#urlObject



80
81
82
# File 'lib/md2slides/presentation.rb', line 80

def url
	@id && "https://docs.google.com/presentation/d/#{@id}/edit"
end

#widthObject



92
93
94
# File 'lib/md2slides/presentation.rb', line 92

def width
	extent[0]
end