]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/nhk.py
[extractor/youtube] Extract `heatmap` data (#7100)
[yt-dlp.git] / yt_dlp / extractor / nhk.py
CommitLineData
77cc7c6e 1import re
061d1cd9 2
298a120a 3from .common import InfoExtractor
77cc7c6e
LNO
4from ..utils import (
5 parse_duration,
6 traverse_obj,
7 unescapeHTML,
8 unified_timestamp,
8f0be90e 9 urljoin,
10 url_or_none
77cc7c6e 11)
298a120a
AN
12
13
29f7c58a 14class NhkBaseIE(InfoExtractor):
6d1b3489 15 _API_URL_TEMPLATE = 'https://nwapi.nhk.jp/nhkworld/%sod%slist/v7b/%s/%s/%s/all%s.json'
29f7c58a 16 _BASE_URL_REGEX = r'https?://www3\.nhk\.or\.jp/nhkworld/(?P<lang>[a-z]{2})/ondemand'
17 _TYPE_REGEX = r'/(?P<type>video|audio)/'
298a120a 18
29f7c58a 19 def _call_api(self, m_id, lang, is_video, is_episode, is_clip):
20 return self._download_json(
21 self._API_URL_TEMPLATE % (
22 'v' if is_video else 'r',
23 'clip' if is_clip else 'esd',
24 'episode' if is_episode else 'program',
25 m_id, lang, '/all' if is_video else ''),
26 m_id, query={'apikey': 'EJfK8jdS57GqlupFgAfAAwr573q01y6k'})['data']['episodes'] or []
27
28 def _extract_episode_info(self, url, episode=None):
29 fetch_episode = episode is None
5ad28e7f 30 lang, m_type, episode_id = NhkVodIE._match_valid_url(url).groups()
6d1b3489 31 if len(episode_id) == 7:
061d1cd9 32 episode_id = episode_id[:4] + '-' + episode_id[4:]
f9b373af 33
061d1cd9 34 is_video = m_type == 'video'
29f7c58a 35 if fetch_episode:
36 episode = self._call_api(
37 episode_id, lang, is_video, True, episode_id[:4] == '9999')[0]
061d1cd9 38 title = episode.get('sub_title_clean') or episode['sub_title']
45396dd2 39
061d1cd9
RA
40 def get_clean_field(key):
41 return episode.get(key + '_clean') or episode.get(key)
45396dd2 42
061d1cd9 43 series = get_clean_field('title')
45396dd2 44
061d1cd9
RA
45 thumbnails = []
46 for s, w, h in [('', 640, 360), ('_l', 1280, 720)]:
47 img_path = episode.get('image' + s)
48 if not img_path:
49 continue
50 thumbnails.append({
51 'id': '%dp' % h,
52 'height': h,
53 'width': w,
54 'url': 'https://www3.nhk.or.jp' + img_path,
55 })
298a120a 56
061d1cd9
RA
57 info = {
58 'id': episode_id + '-' + lang,
f9b373af 59 'title': '%s - %s' % (series, title) if series and title else title,
061d1cd9
RA
60 'description': get_clean_field('description'),
61 'thumbnails': thumbnails,
f9b373af
S
62 'series': series,
63 'episode': title,
64 }
061d1cd9 65 if is_video:
29f7c58a 66 vod_id = episode['vod_id']
061d1cd9
RA
67 info.update({
68 '_type': 'url_transparent',
a373befa 69 'ie_key': 'Piksel',
29f7c58a 70 'url': 'https://player.piksel.com/v/refid/nhkworld/prefid/' + vod_id,
71 'id': vod_id,
061d1cd9
RA
72 })
73 else:
29f7c58a 74 if fetch_episode:
75 audio_path = episode['audio']['audio']
76 info['formats'] = self._extract_m3u8_formats(
77 'https://nhkworld-vh.akamaihd.net/i%s/master.m3u8' % audio_path,
78 episode_id, 'm4a', entry_protocol='m3u8_native',
79 m3u8_id='hls', fatal=False)
80 for f in info['formats']:
81 f['language'] = lang
82 else:
83 info.update({
84 '_type': 'url_transparent',
85 'ie_key': NhkVodIE.ie_key(),
86 'url': url,
87 })
061d1cd9 88 return info
29f7c58a 89
90
91class NhkVodIE(NhkBaseIE):
6d1b3489 92 # the 7-character IDs can have alphabetic chars too: assume [a-z] rather than just [a-f], eg
93 _VALID_URL = r'%s%s(?P<id>[0-9a-z]{7}|[^/]+?-\d{8}-[0-9a-z]+)' % (NhkBaseIE._BASE_URL_REGEX, NhkBaseIE._TYPE_REGEX)
29f7c58a 94 # Content available only for a limited period of time. Visit
95 # https://www3.nhk.or.jp/nhkworld/en/ondemand/ for working samples.
96 _TESTS = [{
97 # video clip
98 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/9999011/',
99 'md5': '7a90abcfe610ec22a6bfe15bd46b30ca',
100 'info_dict': {
101 'id': 'a95j5iza',
102 'ext': 'mp4',
103 'title': "Dining with the Chef - Chef Saito's Family recipe: MENCHI-KATSU",
104 'description': 'md5:5aee4a9f9d81c26281862382103b0ea5',
105 'timestamp': 1565965194,
106 'upload_date': '20190816',
107 },
108 }, {
109 # audio clip
110 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/r_inventions-20201104-1/',
111 'info_dict': {
112 'id': 'r_inventions-20201104-1-en',
113 'ext': 'm4a',
114 'title': "Japan's Top Inventions - Miniature Video Cameras",
115 'description': 'md5:07ea722bdbbb4936fdd360b6a480c25b',
116 },
117 'params': {
118 # m3u8 download
119 'skip_download': True,
120 },
121 }, {
122 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/2015173/',
123 'only_matching': True,
124 }, {
125 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/plugin-20190404-1/',
126 'only_matching': True,
127 }, {
128 'url': 'https://www3.nhk.or.jp/nhkworld/fr/ondemand/audio/plugin-20190404-1/',
129 'only_matching': True,
130 }, {
131 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/j_art-20150903-1/',
132 'only_matching': True,
6d1b3489 133 }, {
134 # video, alphabetic character in ID #29670
135 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/9999a34/',
136 'only_matching': True,
137 'info_dict': {
138 'id': 'qfjay6cg',
139 'ext': 'mp4',
140 'title': 'DESIGN TALKS plus - Fishermen’s Finery',
141 'description': 'md5:8a8f958aaafb0d7cb59d38de53f1e448',
142 'thumbnail': r're:^https?:/(/[a-z0-9.-]+)+\.jpg\?w=1920&h=1080$',
143 'upload_date': '20210615',
144 'timestamp': 1623722008,
145 }
29f7c58a 146 }]
147
148 def _real_extract(self, url):
149 return self._extract_episode_info(url)
150
151
152class NhkVodProgramIE(NhkBaseIE):
153 _VALID_URL = r'%s/program%s(?P<id>[0-9a-z]+)(?:.+?\btype=(?P<episode_type>clip|(?:radio|tv)Episode))?' % (NhkBaseIE._BASE_URL_REGEX, NhkBaseIE._TYPE_REGEX)
154 _TESTS = [{
155 # video program episodes
156 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/program/video/japanrailway',
157 'info_dict': {
158 'id': 'japanrailway',
159 'title': 'Japan Railway Journal',
160 },
161 'playlist_mincount': 1,
162 }, {
163 # video program clips
164 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/program/video/japanrailway/?type=clip',
165 'info_dict': {
166 'id': 'japanrailway',
167 'title': 'Japan Railway Journal',
168 },
169 'playlist_mincount': 5,
170 }, {
171 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/program/video/10yearshayaomiyazaki/',
172 'only_matching': True,
173 }, {
174 # audio program
175 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/program/audio/listener/',
176 'only_matching': True,
177 }]
178
179 def _real_extract(self, url):
5ad28e7f 180 lang, m_type, program_id, episode_type = self._match_valid_url(url).groups()
29f7c58a 181
182 episodes = self._call_api(
183 program_id, lang, m_type == 'video', False, episode_type == 'clip')
184
185 entries = []
186 for episode in episodes:
187 episode_path = episode.get('url')
188 if not episode_path:
189 continue
190 entries.append(self._extract_episode_info(
191 urljoin(url, episode_path), episode))
192
193 program_title = None
194 if entries:
195 program_title = entries[0].get('series')
196
197 return self.playlist_result(entries, program_id, program_title)
77cc7c6e
LNO
198
199
200class NhkForSchoolBangumiIE(InfoExtractor):
201 _VALID_URL = r'https?://www2\.nhk\.or\.jp/school/movie/(?P<type>bangumi|clip)\.cgi\?das_id=(?P<id>[a-zA-Z0-9_-]+)'
202 _TESTS = [{
203 'url': 'https://www2.nhk.or.jp/school/movie/bangumi.cgi?das_id=D0005150191_00000',
204 'info_dict': {
205 'id': 'D0005150191_00003',
206 'title': 'にている かな',
207 'duration': 599.999,
208 'timestamp': 1396414800,
209
210 'upload_date': '20140402',
211 'ext': 'mp4',
212
213 'chapters': 'count:12'
214 },
215 'params': {
216 # m3u8 download
217 'skip_download': True,
218 },
219 }]
220
221 def _real_extract(self, url):
222 program_type, video_id = self._match_valid_url(url).groups()
223
224 webpage = self._download_webpage(
225 f'https://www2.nhk.or.jp/school/movie/{program_type}.cgi?das_id={video_id}', video_id)
226
227 # searches all variables
228 base_values = {g.group(1): g.group(2) for g in re.finditer(r'var\s+([a-zA-Z_]+)\s*=\s*"([^"]+?)";', webpage)}
229 # and programObj values too
230 program_values = {g.group(1): g.group(3) for g in re.finditer(r'(?:program|clip)Obj\.([a-zA-Z_]+)\s*=\s*(["\'])([^"]+?)\2;', webpage)}
231 # extract all chapters
232 chapter_durations = [parse_duration(g.group(1)) for g in re.finditer(r'chapterTime\.push\(\'([0-9:]+?)\'\);', webpage)]
233 chapter_titles = [' '.join([g.group(1) or '', unescapeHTML(g.group(2))]).strip() for g in re.finditer(r'<div class="cpTitle"><span>(scene\s*\d+)?</span>([^<]+?)</div>', webpage)]
234
235 # this is how player_core.js is actually doing (!)
236 version = base_values.get('r_version') or program_values.get('version')
237 if version:
238 video_id = f'{video_id.split("_")[0]}_{version}'
239
240 formats = self._extract_m3u8_formats(
241 f'https://nhks-vh.akamaihd.net/i/das/{video_id[0:8]}/{video_id}_V_000.f4v/master.m3u8',
242 video_id, ext='mp4', m3u8_id='hls')
77cc7c6e
LNO
243
244 duration = parse_duration(base_values.get('r_duration'))
245
246 chapters = None
247 if chapter_durations and chapter_titles and len(chapter_durations) == len(chapter_titles):
248 start_time = chapter_durations
249 end_time = chapter_durations[1:] + [duration]
250 chapters = [{
251 'start_time': s,
252 'end_time': e,
253 'title': t,
254 } for s, e, t in zip(start_time, end_time, chapter_titles)]
255
256 return {
257 'id': video_id,
258 'title': program_values.get('name'),
259 'duration': parse_duration(base_values.get('r_duration')),
260 'timestamp': unified_timestamp(base_values['r_upload']),
261 'formats': formats,
262 'chapters': chapters,
263 }
264
265
266class NhkForSchoolSubjectIE(InfoExtractor):
267 IE_DESC = 'Portal page for each school subjects, like Japanese (kokugo, 国語) or math (sansuu/suugaku or 算数・数学)'
268 KNOWN_SUBJECTS = (
269 'rika', 'syakai', 'kokugo',
270 'sansuu', 'seikatsu', 'doutoku',
271 'ongaku', 'taiiku', 'zukou',
272 'gijutsu', 'katei', 'sougou',
273 'eigo', 'tokkatsu',
274 'tokushi', 'sonota',
275 )
276 _VALID_URL = r'https?://www\.nhk\.or\.jp/school/(?P<id>%s)/?(?:[\?#].*)?$' % '|'.join(re.escape(s) for s in KNOWN_SUBJECTS)
277
278 _TESTS = [{
279 'url': 'https://www.nhk.or.jp/school/sougou/',
280 'info_dict': {
281 'id': 'sougou',
282 'title': '総合的な学習の時間',
283 },
284 'playlist_mincount': 16,
285 }, {
286 'url': 'https://www.nhk.or.jp/school/rika/',
287 'info_dict': {
288 'id': 'rika',
289 'title': '理科',
290 },
291 'playlist_mincount': 15,
292 }]
293
294 def _real_extract(self, url):
295 subject_id = self._match_id(url)
296 webpage = self._download_webpage(url, subject_id)
297
298 return self.playlist_from_matches(
299 re.finditer(rf'href="((?:https?://www\.nhk\.or\.jp)?/school/{re.escape(subject_id)}/[^/]+/)"', webpage),
300 subject_id,
301 self._html_search_regex(r'(?s)<span\s+class="subjectName">\s*<img\s*[^<]+>\s*([^<]+?)</span>', webpage, 'title', fatal=False),
302 lambda g: urljoin(url, g.group(1)))
303
304
305class NhkForSchoolProgramListIE(InfoExtractor):
306 _VALID_URL = r'https?://www\.nhk\.or\.jp/school/(?P<id>(?:%s)/[a-zA-Z0-9_-]+)' % (
307 '|'.join(re.escape(s) for s in NhkForSchoolSubjectIE.KNOWN_SUBJECTS)
308 )
309 _TESTS = [{
310 'url': 'https://www.nhk.or.jp/school/sougou/q/',
311 'info_dict': {
312 'id': 'sougou/q',
313 'title': 'Q~こどものための哲学',
314 },
315 'playlist_mincount': 20,
316 }]
317
318 def _real_extract(self, url):
319 program_id = self._match_id(url)
320
321 webpage = self._download_webpage(f'https://www.nhk.or.jp/school/{program_id}/', program_id)
322
62b8dac4 323 title = (self._generic_title('', webpage)
04f3fd2c 324 or self._html_search_regex(r'<h3>([^<]+?)とは?\s*</h3>', webpage, 'title', fatal=False))
77cc7c6e
LNO
325 title = re.sub(r'\s*\|\s*NHK\s+for\s+School\s*$', '', title) if title else None
326 description = self._html_search_regex(
327 r'(?s)<div\s+class="programDetail\s*">\s*<p>[^<]+</p>',
328 webpage, 'description', fatal=False, group=0)
329
330 bangumi_list = self._download_json(
331 f'https://www.nhk.or.jp/school/{program_id}/meta/program.json', program_id)
332 # they're always bangumi
333 bangumis = [
334 self.url_result(f'https://www2.nhk.or.jp/school/movie/bangumi.cgi?das_id={x}')
335 for x in traverse_obj(bangumi_list, ('part', ..., 'part-video-dasid')) or []]
336
337 return self.playlist_result(bangumis, program_id, title, description)
8f0be90e 338
339
340class NhkRadiruIE(InfoExtractor):
341 _GEO_COUNTRIES = ['JP']
342 IE_DESC = 'NHK らじる (Radiru/Rajiru)'
343 _VALID_URL = r'https?://www\.nhk\.or\.jp/radio/(?:player/ondemand|ondemand/detail)\.html\?p=(?P<site>[\da-zA-Z]+)_(?P<corner>[\da-zA-Z]+)(?:_(?P<headline>[\da-zA-Z]+))?'
344 _TESTS = [{
345 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=0449_01_3853544',
346 'skip': 'Episode expired on 2023-04-16',
347 'info_dict': {
348 'channel': 'NHK-FM',
349 'description': 'md5:94b08bdeadde81a97df4ec882acce3e9',
350 'ext': 'm4a',
351 'id': '0449_01_3853544',
352 'series': 'ジャズ・トゥナイト',
353 'thumbnail': 'https://www.nhk.or.jp/prog/img/449/g449.jpg',
354 'timestamp': 1680969600,
355 'title': 'ジャズ・トゥナイト NEWジャズ特集',
356 'upload_date': '20230408',
357 'release_timestamp': 1680962400,
358 'release_date': '20230408',
359 'was_live': True,
360 },
361 }, {
362 # playlist, airs every weekday so it should _hopefully_ be okay forever
363 'url': 'https://www.nhk.or.jp/radio/ondemand/detail.html?p=0458_01',
364 'info_dict': {
365 'id': '0458_01',
366 'title': 'ベストオブクラシック',
367 'description': '世界中の上質な演奏会をじっくり堪能する本格派クラシック番組。',
368 'channel': 'NHK-FM',
369 'thumbnail': 'https://www.nhk.or.jp/prog/img/458/g458.jpg',
370 },
371 'playlist_mincount': 3,
372 }, {
373 # one with letters in the id
374 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=F300_06_3738470',
375 'note': 'Expires on 2024-03-31',
376 'info_dict': {
377 'id': 'F300_06_3738470',
378 'ext': 'm4a',
379 'title': '有島武郎「一房のぶどう」',
380 'description': '朗読:川野一宇(ラジオ深夜便アンカー)\r\n\r\n(2016年12月8日放送「ラジオ深夜便『アンカー朗読シリーズ』」より)',
381 'channel': 'NHKラジオ第1、NHK-FM',
382 'timestamp': 1635757200,
383 'thumbnail': 'https://www.nhk.or.jp/radioondemand/json/F300/img/corner/box_109_thumbnail.jpg',
384 'release_date': '20161207',
385 'series': 'らじる文庫 by ラジオ深夜便 ',
386 'release_timestamp': 1481126700,
387 'upload_date': '20211101',
388 }
389 }, {
390 # news
391 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=F261_01_3855109',
392 'skip': 'Expires on 2023-04-17',
393 'info_dict': {
394 'id': 'F261_01_3855109',
395 'ext': 'm4a',
396 'channel': 'NHKラジオ第1',
397 'timestamp': 1681635900,
398 'release_date': '20230416',
399 'series': 'NHKラジオニュース',
400 'title': '午後6時のNHKニュース',
401 'thumbnail': 'https://www.nhk.or.jp/radioondemand/json/F261/img/RADIONEWS_640.jpg',
402 'upload_date': '20230416',
403 'release_timestamp': 1681635600,
404 },
405 }]
406
407 def _extract_episode_info(self, headline, programme_id, series_meta):
408 episode_id = f'{programme_id}_{headline["headline_id"]}'
409 episode = traverse_obj(headline, ('file_list', 0, {dict}))
410
411 return {
412 **series_meta,
413 'id': episode_id,
414 'formats': self._extract_m3u8_formats(episode.get('file_name'), episode_id, fatal=False),
415 'container': 'm4a_dash', # force fixup, AAC-only HLS
416 'was_live': True,
417 'series': series_meta.get('title'),
418 'thumbnail': url_or_none(headline.get('headline_image')) or series_meta.get('thumbnail'),
419 **traverse_obj(episode, {
420 'title': 'file_title',
421 'description': 'file_title_sub',
422 'timestamp': ('open_time', {unified_timestamp}),
423 'release_timestamp': ('aa_vinfo4', {lambda x: x.split('_')[0]}, {unified_timestamp}),
424 }),
425 }
426
427 def _real_extract(self, url):
428 site_id, corner_id, headline_id = self._match_valid_url(url).group('site', 'corner', 'headline')
429 programme_id = f'{site_id}_{corner_id}'
430
431 if site_id == 'F261':
432 json_url = 'https://www.nhk.or.jp/s-media/news/news-site/list/v1/all.json'
433 else:
434 json_url = f'https://www.nhk.or.jp/radioondemand/json/{site_id}/bangumi_{programme_id}.json'
435
436 meta = self._download_json(json_url, programme_id)['main']
437
438 series_meta = traverse_obj(meta, {
439 'title': 'program_name',
440 'channel': 'media_name',
441 'thumbnail': (('thumbnail_c', 'thumbnail_p'), {url_or_none}),
442 }, get_all=False)
443
444 if headline_id:
445 return self._extract_episode_info(
446 traverse_obj(meta, (
447 'detail_list', lambda _, v: v['headline_id'] == headline_id), get_all=False),
448 programme_id, series_meta)
449
450 def entries():
451 for headline in traverse_obj(meta, ('detail_list', ..., {dict})):
452 yield self._extract_episode_info(headline, programme_id, series_meta)
453
454 return self.playlist_result(
455 entries(), programme_id, playlist_description=meta.get('site_detail'), **series_meta)
456
457
458class NhkRadioNewsPageIE(InfoExtractor):
459 _VALID_URL = r'https?://www\.nhk\.or\.jp/radionews/?(?:$|[?#])'
460 _TESTS = [{
461 # airs daily, on-the-hour most hours
462 'url': 'https://www.nhk.or.jp/radionews/',
463 'playlist_mincount': 5,
464 'info_dict': {
465 'id': 'F261_01',
466 'thumbnail': 'https://www.nhk.or.jp/radioondemand/json/F261/img/RADIONEWS_640.jpg',
467 'description': 'md5:bf2c5b397e44bc7eb26de98d8f15d79d',
468 'channel': 'NHKラジオ第1',
469 'title': 'NHKラジオニュース',
470 }
471 }]
472
473 def _real_extract(self, url):
474 return self.url_result('https://www.nhk.or.jp/radio/ondemand/detail.html?p=F261_01', NhkRadiruIE)