metadata.py
1.44 KB
1
2
3
4
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
44
45
46
47
48
# -*- coding: utf-8 -*-
"""This module contains the YouTubeMetadata class."""
import json
from typing import Dict
from typing import List
from typing import Optional
class YouTubeMetadata:
def __init__(self, metadata: List):
self._raw_metadata: List = metadata
self._metadata = [{}]
for el in metadata:
# We only add metadata to the dict if it has a simpleText title.
if 'title' in el and 'simpleText' in el['title']:
metadata_title = el['title']['simpleText']
else:
continue
contents = el['contents'][0]
if 'simpleText' in contents:
self._metadata[-1][metadata_title] = contents['simpleText']
elif 'runs' in contents:
self._metadata[-1][metadata_title] = contents['runs'][0]['text']
# Upon reaching a dividing line, create a new grouping
if el.get('hasDividerLine', False):
self._metadata.append({})
# If we happen to create an empty dict at the end, drop it
if self._metadata[-1] == {}:
self._metadata = self._metadata[:-1]
def __iter__(self):
for el in self._metadata:
yield el
def __str__(self):
return json.dumps(self._metadata)
@property
def raw_metadata(self) -> Optional[Dict]:
return self._raw_metadata
@property
def metadata(self):
return self._metadata