gurudesh/pytracebugs huggingface dataset:
# Buggy code
def entity_word_cloud(self, top: Optional[int] = None):
    """Make a word cloud based on the frequency of occurrence of each entity in a Jupyter notebook.

    :param top: The number of top entities to show. Defaults to 100.

    .. warning::

        This function requires the ``word_cloud`` package. Use ``pip install pykeen[plotting]`` to
        install it automatically, or install it yourself with
        ``pip install git+https://github.com/kavgan/word_cloud.git``.
    """
    text = [f"{h} {t}" for h, _, t in self.triples]
    return self._word_cloud(text=text, top=top or 100)


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def entity_word_cloud(self, top: Optional[int] = None):
    """Make a word cloud based on the frequency of occurrence of each entity in a Jupyter notebook.

    :param top: The number of top entities to show. Defaults to 100.

    .. warning::

        This function requires the ``word_cloud`` package. Use ``pip install pykeen[plotting]`` to
        install it automatically, or install it yourself with
        ``pip install git+https://github.com/kavgan/word_cloud.git``.
    """
    return self._word_cloud(
        ids=self.mapped_triples[:, [0, 2]],
        id_to_label=self.entity_id_to_label,
        top=top or 100,
    )
# Buggy code
def relation_word_cloud(self, top: Optional[int] = None):
    """Make a word cloud based on the frequency of occurrence of each relation in a Jupyter notebook.

    :param top: The number of top relations to show. Defaults to 100.

    .. warning::

        This function requires the ``word_cloud`` package. Use ``pip install pykeen[plotting]`` to
        install it automatically, or install it yourself with
        ``pip install git+https://github.com/kavgan/word_cloud.git``.
    """
    text = [r for _, r, _ in self.triples]
    return self._word_cloud(text=text, top=top or 100)


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def relation_word_cloud(self, top: Optional[int] = None):
    """Make a word cloud based on the frequency of occurrence of each relation in a Jupyter notebook.

    :param top: The number of top relations to show. Defaults to 100.

    .. warning::

        This function requires the ``word_cloud`` package. Use ``pip install pykeen[plotting]`` to
        install it automatically, or install it yourself with
        ``pip install git+https://github.com/kavgan/word_cloud.git``.
    """
    return self._word_cloud(
        ids=self.mapped_triples[:, 1],
        id_to_label=self.relation_id_to_label,
        top=top or 100,
    )
# Buggy code
def _word_cloud(self, *, text: List[str], top: int):
    try:
        from word_cloud.word_cloud_generator import WordCloud
    except ImportError:
        logger.warning(
            "Could not import module `word_cloud`. "
            "Try installing it with `pip install git+https://github.com/kavgan/word_cloud.git`",
        )
        return

    from IPython.core.display import HTML

    word_cloud = WordCloud()
    return HTML(word_cloud.get_embed_code(text=text, topn=top))


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def _word_cloud(
    self, *, ids: torch.LongTensor, id_to_label: Mapping[int, str], top: int
):
    try:
        from word_cloud.word_cloud_generator import WordCloud
    except ImportError:
        logger.warning(
            "Could not import module `word_cloud`. "
            "Try installing it with `pip install git+https://github.com/kavgan/word_cloud.git`",
        )
        return

    # pre-filter to keep only topk
    uniq, counts = ids.view(-1).unique(return_counts=True)
    top_counts, top_ids = counts.topk(k=top, largest=True)

    # generate text
    text = list(
        itertools.chain(
            *(
                itertools.repeat(id_to_label[e_id], count)
                for e_id, count in zip(top_ids.tolist(), top_counts.tolist())
            )
        )
    )

    from IPython.core.display import HTML

    word_cloud = WordCloud()
    return HTML(word_cloud.get_embed_code(text=text, topn=top))
# Buggy code
def _tf_cleanup_all(
    triples_groups: List[np.ndarray],
    *,
    random_state: RandomHint = None,
) -> List[np.ndarray]:
    """Cleanup a list of triples array with respect to the first array."""
    reference, *others = triples_groups
    rv = []
    for other in others:
        if random_state is not None:
            reference, other = _tf_cleanup_randomized(reference, other, random_state)
        else:
            reference, other = _tf_cleanup_deterministic(reference, other)
        rv.append(other)
    return [reference, *rv]


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def _tf_cleanup_all(
    triples_groups: List[MappedTriples],
    *,
    random_state: TorchRandomHint = None,
) -> Sequence[MappedTriples]:
    """Cleanup a list of triples array with respect to the first array."""
    reference, *others = triples_groups
    rv = []
    for other in others:
        if random_state is not None:
            reference, other = _tf_cleanup_randomized(reference, other, random_state)
        else:
            reference, other = _tf_cleanup_deterministic(reference, other)
        rv.append(other)
    # [...] is necessary for Python 3.7 compatibility
    return [reference, *rv]
# Buggy code
def _tf_cleanup_deterministic(
    training: np.ndarray, testing: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
    """Cleanup a triples array (testing) with respect to another (training)."""
    move_id_mask = _prepare_cleanup(training, testing)

    training = np.concatenate([training, testing[move_id_mask]])
    testing = testing[~move_id_mask]

    return training, testing


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def _tf_cleanup_deterministic(
    training: MappedTriples, testing: MappedTriples
) -> Tuple[MappedTriples, MappedTriples]:
    """Cleanup a triples array (testing) with respect to another (training)."""
    move_id_mask = _prepare_cleanup(training, testing)
    training = torch.cat([training, testing[move_id_mask]])
    testing = testing[~move_id_mask]
    return training, testing
# Buggy code
def _tf_cleanup_randomized(
    training: np.ndarray,
    testing: np.ndarray,
    random_state: RandomHint = None,
) -> Tuple[np.ndarray, np.ndarray]:
    """Cleanup a triples array, but randomly select testing triples and recalculate to minimize moves.

    1. Calculate ``move_id_mask`` as in :func:`_tf_cleanup_deterministic`
    2. Choose a triple to move, recalculate move_id_mask
    3. Continue until move_id_mask has no true bits
    """
    random_state = ensure_random_state(random_state)

    move_id_mask = _prepare_cleanup(training, testing)

    # While there are still triples that should be moved to the training set
    while move_id_mask.any():
        # Pick a random triple to move over to the training triples
        idx = random_state.choice(move_id_mask.nonzero()[0])
        training = np.concatenate([training, testing[idx].reshape(1, -1)])

        # Recalculate the testing triples without that index
        testing_mask = np.ones_like(move_id_mask)
        testing_mask[idx] = False
        testing = testing[testing_mask]

        # Recalculate the training entities, testing entities, to_move, and move_id_mask
        move_id_mask = _prepare_cleanup(training, testing)

    return training, testing


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def _tf_cleanup_randomized(
    training: MappedTriples,
    testing: MappedTriples,
    random_state: TorchRandomHint = None,
) -> Tuple[MappedTriples, MappedTriples]:
    """Cleanup a triples array, but randomly select testing triples and recalculate to minimize moves.

    1. Calculate ``move_id_mask`` as in :func:`_tf_cleanup_deterministic`
    2. Choose a triple to move, recalculate move_id_mask
    3. Continue until move_id_mask has no true bits
    """
    generator = ensure_torch_random_state(random_state)
    move_id_mask = _prepare_cleanup(training, testing)

    # While there are still triples that should be moved to the training set
    while move_id_mask.any():
        # Pick a random triple to move over to the training triples
        (candidates,) = move_id_mask.nonzero(as_tuple=True)
        idx = torch.randint(candidates.shape[0], size=(1,), generator=generator)
        idx = candidates[idx]

        # add to training
        training = torch.cat([training, testing[idx].view(1, -1)], dim=0)
        # remove from testing
        testing = torch.cat([testing[:idx], testing[idx + 1 :]], dim=0)
        # Recalculate the move_id_mask
        move_id_mask = _prepare_cleanup(training, testing)

    return training, testing
# Buggy code
def _prepare_cleanup(training: np.ndarray, testing: np.ndarray) -> np.ndarray:
    to_move_mask = None
    for col in [[0, 2], 1]:
        training_ids, test_ids = [
            np.unique(triples[:, col]) for triples in [training, testing]
        ]
        to_move = test_ids[~np.isin(test_ids, training_ids)]
        this_to_move_mask = np.isin(testing[:, col], to_move)
        if this_to_move_mask.ndim > 1:
            this_to_move_mask = this_to_move_mask.any(axis=1)
        if to_move_mask is None:
            to_move_mask = this_to_move_mask
        else:
            to_move_mask = this_to_move_mask | to_move_mask

    return to_move_mask


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def _prepare_cleanup(
    training: MappedTriples,
    testing: MappedTriples,
    max_ids: Optional[Tuple[int, int]] = None,
) -> torch.BoolTensor:
    """
    Calculate a mask for the test triples with triples containing test-only entities or relations.

    :param training: shape: (n, 3)
        The training triples.
    :param testing: shape: (m, 3)
        The testing triples.

    :return: shape: (m,)
        The move mask.
    """
    # base cases
    if len(testing) == 0:
        return torch.empty(0, dtype=torch.bool)
    if len(training) == 0:
        return torch.ones(testing.shape[0], dtype=torch.bool)

    columns = [[0, 2], [1]]
    to_move_mask = torch.zeros(1, dtype=torch.bool)
    if max_ids is None:
        max_ids = [
            max(training[:, col].max().item(), testing[:, col].max().item()) + 1
            for col in columns
        ]
    for col, max_id in zip(columns, max_ids):
        # IDs not in training
        not_in_training_mask = torch.ones(max_id, dtype=torch.bool)
        not_in_training_mask[training[:, col].view(-1)] = False

        # triples with exclusive test IDs
        exclusive_triples = (
            not_in_training_mask[testing[:, col].view(-1)]
            .view(-1, len(col))
            .any(dim=-1)
        )
        to_move_mask = to_move_mask | exclusive_triples
    return to_move_mask
# Buggy code
def get_entities(triples) -> Set:
    """Get all entities from the triples."""
    return set(triples[:, [0, 2]].flatten().tolist())


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def get_entities(triples: torch.LongTensor) -> Set[int]:
    """Get all entities from the triples."""
    return set(triples[:, [0, 2]].flatten().tolist())
# Buggy code
def get_relations(triples) -> Set:
    """Get all relations from the triples."""
    return set(triples[:, 1])


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def get_relations(triples: torch.LongTensor) -> Set[int]:
    """Get all relations from the triples."""
    return set(triples[:, 1].tolist())
# Buggy code
def invert_mapping(mapping: Mapping[str, int]) -> Mapping[int, str]:
    """
    Invert a mapping.

    :param mapping:
        The mapping, key -> value.

    :return:
        The inverse mapping, value -> key.
    """
    num_unique_values = len(set(mapping.values()))
    num_keys = len(mapping)
    if num_unique_values < num_keys:
        raise ValueError(
            f"Mapping is not bijective! Only {num_unique_values}/{num_keys} are unique."
        )
    return {value: key for key, value in mapping.items()}


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def invert_mapping(mapping: Mapping[K, V]) -> Mapping[V, K]:
    """
    Invert a mapping.

    :param mapping:
        The mapping, key -> value.

    :return:
        The inverse mapping, value -> key.
    """
    num_unique_values = len(set(mapping.values()))
    num_keys = len(mapping)
    if num_unique_values < num_keys:
        raise ValueError(
            f"Mapping is not bijective! Only {num_unique_values}/{num_keys} are unique."
        )
    return {value: key for key, value in mapping.items()}
# Buggy code
def create_lcwa_instances(self, use_tqdm: Optional[bool] = None) -> LCWAInstances:
    """Create LCWA instances for this factory's triples."""
    s_p_to_multi_tails = _create_multi_label_tails_instance(
        mapped_triples=self.mapped_triples,
        use_tqdm=use_tqdm,
    )
    sp, multi_o = zip(*s_p_to_multi_tails.items())
    mapped_triples: torch.LongTensor = torch.tensor(sp, dtype=torch.long)
    labels = np.array([np.array(item) for item in multi_o])

    return LCWAInstances(
        mapped_triples=mapped_triples,
        entity_to_id=self.entity_to_id,
        relation_to_id=self.relation_to_id,
        labels=labels,
    )


# Traceback (ValueError)
ValueError                                Traceback (most recent call last)
<ipython-input-13-ef15ccdc9011> in <module>
3
4 tf = TriplesFactory(path=work_path + '/eucalyptus_triplets.txt')
----> 5 training, testing = tf.split()
6
7 pipeline_result = pipeline(

~\anaconda3\envs\pykeen\lib\site-packages\pykeen\triples\triples_factory.py in split(self, ratios, random_state, randomize_cleanup)
419         idx = np.arange(n_triples)
420         if random_state is None:
--> 421             random_state = np.random.randint(0, 2 ** 32 - 1)
422             logger.warning(f'Using random_state={random_state} to split {self}')
423         if isinstance(random_state, int):

mtrand.pyx in numpy.random.mtrand.RandomState.randint()

_bounded_integers.pyx in numpy.random._bounded_integers._rand_int32()

ValueError: high is out of bounds for int32

# Fixed code
def create_lcwa_instances(self, use_tqdm: Optional[bool] = None) -> LCWAInstances:
    """Create LCWA instances for this factory's triples."""
    s_p_to_multi_tails = _create_multi_label_tails_instance(
        mapped_triples=self.mapped_triples,
        use_tqdm=use_tqdm,
    )
    sp, multi_o = zip(*s_p_to_multi_tails.items())
    mapped_triples: torch.LongTensor = torch.tensor(sp, dtype=torch.long)
    labels = np.array([np.array(item) for item in multi_o], dtype=object)

    return LCWAInstances(
        mapped_triples=mapped_triples,
        entity_to_id=self.entity_to_id,
        relation_to_id=self.relation_to_id,
        labels=labels,
    )
# Buggy code
def __init__(self, coresys: CoreSys, addon: AnyAddon) -> None:
    """Initialize Supervisor add-on builder."""
    self.coresys: CoreSys = coresys
    self.addon = addon

    super().__init__(
        find_one_filetype(self.addon.path_location, "build", FILE_SUFFIX_CONFIGURATION),
        SCHEMA_BUILD_CONFIG,
    )


# Traceback (AttributeError)
21-03-03 19:11:51 ERROR (MainThread) [supervisor.jobs] Unhandled exception: 'NoneType' object has no attribute 'is_file'
Traceback (most recent call last):
File "/usr/src/supervisor/supervisor/jobs/decorator.py", line 100, in wrapper
return await self._method(*args, **kwargs)
File "/usr/src/supervisor/supervisor/addons/init.py", line 182, in install
await addon.instance.install(store.version, store.image)
File "/usr/src/supervisor/supervisor/utils/init.py", line 32, in wrap_api
return await method(api, *args, **kwargs)
File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/src/supervisor/supervisor/docker/addon.py", line 491, in _install
self._build(version)
File "/usr/src/supervisor/supervisor/docker/addon.py", line 500, in _build
build_env = AddonBuild(self.coresys, self.addon)
File "/usr/src/supervisor/supervisor/addons/build.py", line 32, in init
super().init(
File "/usr/src/supervisor/supervisor/utils/common.py", line 59, in init
self.read_data()
File "/usr/src/supervisor/supervisor/utils/common.py", line 72, in read_data
if self._file.is_file():
AttributeError: 'NoneType' object has no attribute 'is_file'

# Fixed code
def __init__(self, coresys: CoreSys, addon: AnyAddon) -> None:
    """Initialize Supervisor add-on builder."""
    self.coresys: CoreSys = coresys
    self.addon = addon

    try:
        build_file = find_one_filetype(
            self.addon.path_location, "build", FILE_SUFFIX_CONFIGURATION
        )
    except ConfigurationFileError:
        build_file = self.addon.path_location / "build.json"

    super().__init__(build_file, SCHEMA_BUILD_CONFIG)
# Buggy code
def _read_git_repository(self, path: Path) -> None:
    """Process a custom repository folder."""
    slug = extract_hash_from_path(path)

    # exists repository json
    repository_file = find_one_filetype(path, "repository", FILE_SUFFIX_CONFIGURATION)

    if repository_file is None:
        _LOGGER.warning("No repository information exists at %s", path)
        return

    try:
        repository_info = SCHEMA_REPOSITORY_CONFIG(
            read_json_or_yaml_file(repository_file)
        )
    except ConfigurationFileError:
        _LOGGER.warning("Can't read repository information from %s", repository_file)
        return
    except vol.Invalid:
        _LOGGER.warning("Repository parse error %s", repository_file)
        return

    # process data
    self.repositories[slug] = repository_info
    self._read_addons_folder(path, slug)


# Traceback (AttributeError)
21-03-03 19:11:51 ERROR (MainThread) [supervisor.jobs] Unhandled exception: 'NoneType' object has no attribute 'is_file'
Traceback (most recent call last):
File "/usr/src/supervisor/supervisor/jobs/decorator.py", line 100, in wrapper
return await self._method(*args, **kwargs)
File "/usr/src/supervisor/supervisor/addons/init.py", line 182, in install
await addon.instance.install(store.version, store.image)
File "/usr/src/supervisor/supervisor/utils/init.py", line 32, in wrap_api
return await method(api, *args, **kwargs)
File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/src/supervisor/supervisor/docker/addon.py", line 491, in _install
self._build(version)
File "/usr/src/supervisor/supervisor/docker/addon.py", line 500, in _build
build_env = AddonBuild(self.coresys, self.addon)
File "/usr/src/supervisor/supervisor/addons/build.py", line 32, in init
super().init(
File "/usr/src/supervisor/supervisor/utils/common.py", line 59, in init
self.read_data()
File "/usr/src/supervisor/supervisor/utils/common.py", line 72, in read_data
if self._file.is_file():
AttributeError: 'NoneType' object has no attribute 'is_file'

# Fixed code
def _read_git_repository(self, path: Path) -> None:
    """Process a custom repository folder."""
    slug = extract_hash_from_path(path)

    # exists repository json
    try:
        repository_file = find_one_filetype(
            path, "repository", FILE_SUFFIX_CONFIGURATION
        )
    except ConfigurationFileError:
        _LOGGER.warning("No repository information exists at %s", path)
        return

    try:
        repository_info = SCHEMA_REPOSITORY_CONFIG(
            read_json_or_yaml_file(repository_file)
        )
    except ConfigurationFileError:
        _LOGGER.warning("Can't read repository information from %s", repository_file)
        return
    except vol.Invalid:
        _LOGGER.warning("Repository parse error %s", repository_file)
        return

    # process data
    self.repositories[slug] = repository_info
    self._read_addons_folder(path, slug)
# Buggy code
def find_one_filetype(
    path: Path, filename: str, filetypes: List[str]
) -> Optional[Path]:
    """Find first file matching filetypes."""
    for file in path.glob(f"**/{filename}.*"):
        if file.suffix in filetypes:
            return file
    return None


# Traceback (AttributeError)
21-03-03 19:11:51 ERROR (MainThread) [supervisor.jobs] Unhandled exception: 'NoneType' object has no attribute 'is_file'
Traceback (most recent call last):
File "/usr/src/supervisor/supervisor/jobs/decorator.py", line 100, in wrapper
return await self._method(*args, **kwargs)
File "/usr/src/supervisor/supervisor/addons/init.py", line 182, in install
await addon.instance.install(store.version, store.image)
File "/usr/src/supervisor/supervisor/utils/init.py", line 32, in wrap_api
return await method(api, *args, **kwargs)
File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/src/supervisor/supervisor/docker/addon.py", line 491, in _install
self._build(version)
File "/usr/src/supervisor/supervisor/docker/addon.py", line 500, in _build
build_env = AddonBuild(self.coresys, self.addon)
File "/usr/src/supervisor/supervisor/addons/build.py", line 32, in init
super().init(
File "/usr/src/supervisor/supervisor/utils/common.py", line 59, in init
self.read_data()
File "/usr/src/supervisor/supervisor/utils/common.py", line 72, in read_data
if self._file.is_file():
AttributeError: 'NoneType' object has no attribute 'is_file'

# Fixed code
def find_one_filetype(path: Path, filename: str, filetypes: List[str]) -> Path:
    """Find first file matching filetypes."""
    for file in path.glob(f"**/{filename}.*"):
        if file.suffix in filetypes:
            return file
    raise ConfigurationFileError(f"{path!s}/{filename}.({filetypes}) not exists!")
# Buggy code
def ipconfig_struct(config: IpConfig) -> dict:
    """Return a dict with information about ip configuration."""
    return {
        ATTR_METHOD: config.method,
        ATTR_ADDRESS: [address.with_prefixlen for address in config.address],
        ATTR_NAMESERVERS: [str(address) for address in config.nameservers],
        ATTR_GATEWAY: str(config.gateway) if config.gateway else None,
    }


# Traceback (AttributeError)
20-12-03 14:56:14 ERROR (MainThread) [aiohttp.server] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_protocol.py", line 422, in _handle_request
resp = await self._request_handler(request)
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/integrations/aiohttp.py", line 123, in sentry_app_handle
reraise(*_capture_exception(hub))
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/_compat.py", line 54, in reraise
raise value
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/integrations/aiohttp.py", line 113, in sentry_app_handle
response = await old_handle(self, request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_app.py", line 499, in _handle
resp = await handler(request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_middlewares.py", line 118, in impl
return await handler(request)
File "/usr/src/supervisor/supervisor/api/security.py", line 133, in system_validation
return await handler(request)
File "/usr/src/supervisor/supervisor/api/security.py", line 195, in token_validation
return await handler(request)
File "/usr/src/supervisor/supervisor/api/utils.py", line 60, in wrap_api
answer = await method(api, *args, **kwargs)
File "/usr/src/supervisor/supervisor/api/network.py", line 154, in info
ATTR_INTERFACES: [
File "/usr/src/supervisor/supervisor/api/network.py", line 155, in <listcomp>
interface_struct(interface)
File "/usr/src/supervisor/supervisor/api/network.py", line 114, in interface_struct
ATTR_VLAN: wifi_struct(interface.vlan) if interface.vlan else None,
File "/usr/src/supervisor/supervisor/api/network.py", line 96, in wifi_struct
ATTR_MODE: config.mode,
AttributeError: 'VlanConfig' object has no attribute 'mode'

# Fixed code
def ipconfig_struct(config: IpConfig) -> Dict[str, Any]:
    """Return a dict with information about ip configuration."""
    return {
        ATTR_METHOD: config.method,
        ATTR_ADDRESS: [address.with_prefixlen for address in config.address],
        ATTR_NAMESERVERS: [str(address) for address in config.nameservers],
        ATTR_GATEWAY: str(config.gateway) if config.gateway else None,
    }
# Buggy code
def wifi_struct(config: WifiConfig) -> dict:
    """Return a dict with information about wifi configuration."""
    return {
        ATTR_MODE: config.mode,
        ATTR_AUTH: config.auth,
        ATTR_SSID: config.ssid,
        ATTR_SIGNAL: config.signal,
    }


# Traceback (AttributeError)
20-12-03 14:56:14 ERROR (MainThread) [aiohttp.server] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_protocol.py", line 422, in _handle_request
resp = await self._request_handler(request)
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/integrations/aiohttp.py", line 123, in sentry_app_handle
reraise(*_capture_exception(hub))
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/_compat.py", line 54, in reraise
raise value
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/integrations/aiohttp.py", line 113, in sentry_app_handle
response = await old_handle(self, request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_app.py", line 499, in _handle
resp = await handler(request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_middlewares.py", line 118, in impl
return await handler(request)
File "/usr/src/supervisor/supervisor/api/security.py", line 133, in system_validation
return await handler(request)
File "/usr/src/supervisor/supervisor/api/security.py", line 195, in token_validation
return await handler(request)
File "/usr/src/supervisor/supervisor/api/utils.py", line 60, in wrap_api
answer = await method(api, *args, **kwargs)
File "/usr/src/supervisor/supervisor/api/network.py", line 154, in info
ATTR_INTERFACES: [
File "/usr/src/supervisor/supervisor/api/network.py", line 155, in <listcomp>
interface_struct(interface)
File "/usr/src/supervisor/supervisor/api/network.py", line 114, in interface_struct
ATTR_VLAN: wifi_struct(interface.vlan) if interface.vlan else None,
File "/usr/src/supervisor/supervisor/api/network.py", line 96, in wifi_struct
ATTR_MODE: config.mode,
AttributeError: 'VlanConfig' object has no attribute 'mode'

# Fixed code
def wifi_struct(config: WifiConfig) -> Dict[str, Any]:
    """Return a dict with information about wifi configuration."""
    return {
        ATTR_MODE: config.mode,
        ATTR_AUTH: config.auth,
        ATTR_SSID: config.ssid,
        ATTR_SIGNAL: config.signal,
    }
# Buggy code
def interface_struct(interface: Interface) -> dict:
    """Return a dict with information of a interface to be used in th API."""
    return {
        ATTR_INTERFACE: interface.name,
        ATTR_TYPE: interface.type,
        ATTR_ENABLED: interface.enabled,
        ATTR_CONNECTED: interface.connected,
        ATTR_PRIMARY: interface.primary,
        ATTR_IPV4: ipconfig_struct(interface.ipv4) if interface.ipv4 else None,
        ATTR_IPV6: ipconfig_struct(interface.ipv6) if interface.ipv6 else None,
        ATTR_WIFI: wifi_struct(interface.wifi) if interface.wifi else None,
        ATTR_VLAN: wifi_struct(interface.vlan) if interface.vlan else None,
    }


# Traceback (AttributeError)
20-12-03 14:56:14 ERROR (MainThread) [aiohttp.server] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_protocol.py", line 422, in _handle_request
resp = await self._request_handler(request)
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/integrations/aiohttp.py", line 123, in sentry_app_handle
reraise(*_capture_exception(hub))
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/_compat.py", line 54, in reraise
raise value
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/integrations/aiohttp.py", line 113, in sentry_app_handle
response = await old_handle(self, request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_app.py", line 499, in _handle
resp = await handler(request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_middlewares.py", line 118, in impl
return await handler(request)
File "/usr/src/supervisor/supervisor/api/security.py", line 133, in system_validation
return await handler(request)
File "/usr/src/supervisor/supervisor/api/security.py", line 195, in token_validation
return await handler(request)
File "/usr/src/supervisor/supervisor/api/utils.py", line 60, in wrap_api
answer = await method(api, *args, **kwargs)
File "/usr/src/supervisor/supervisor/api/network.py", line 154, in info
ATTR_INTERFACES: [
File "/usr/src/supervisor/supervisor/api/network.py", line 155, in <listcomp>
interface_struct(interface)
File "/usr/src/supervisor/supervisor/api/network.py", line 114, in interface_struct
ATTR_VLAN: wifi_struct(interface.vlan) if interface.vlan else None,
File "/usr/src/supervisor/supervisor/api/network.py", line 96, in wifi_struct
ATTR_MODE: config.mode,
AttributeError: 'VlanConfig' object has no attribute 'mode'

# Fixed code
def interface_struct(interface: Interface) -> Dict[str, Any]:
    """Return a dict with information of a interface to be used in th API."""
    return {
        ATTR_INTERFACE: interface.name,
        ATTR_TYPE: interface.type,
        ATTR_ENABLED: interface.enabled,
        ATTR_CONNECTED: interface.connected,
        ATTR_PRIMARY: interface.primary,
        ATTR_IPV4: ipconfig_struct(interface.ipv4) if interface.ipv4 else None,
        ATTR_IPV6: ipconfig_struct(interface.ipv6) if interface.ipv6 else None,
        ATTR_WIFI: wifi_struct(interface.wifi) if interface.wifi else None,
        ATTR_VLAN: wifi_struct(interface.vlan) if interface.vlan else None,
    }
# Buggy code
def accesspoint_struct(accesspoint: AccessPoint) -> dict:
    """Return a dict for AccessPoint."""
    return {
        ATTR_MODE: accesspoint.mode,
        ATTR_SSID: accesspoint.ssid,
        ATTR_FREQUENCY: accesspoint.frequency,
        ATTR_SIGNAL: accesspoint.signal,
        ATTR_MAC: accesspoint.mac,
    }


# Traceback (AttributeError)
20-12-03 14:56:14 ERROR (MainThread) [aiohttp.server] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_protocol.py", line 422, in _handle_request
resp = await self._request_handler(request)
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/integrations/aiohttp.py", line 123, in sentry_app_handle
reraise(*_capture_exception(hub))
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/_compat.py", line 54, in reraise
raise value
File "/usr/local/lib/python3.8/site-packages/sentry_sdk/integrations/aiohttp.py", line 113, in sentry_app_handle
response = await old_handle(self, request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_app.py", line 499, in _handle
resp = await handler(request)
File "/usr/local/lib/python3.8/site-packages/aiohttp/web_middlewares.py", line 118, in impl
return await handler(request)
File "/usr/src/supervisor/supervisor/api/security.py", line 133, in system_validation
return await handler(request)
File "/usr/src/supervisor/supervisor/api/security.py", line 195, in token_validation
return await handler(request)
File "/usr/src/supervisor/supervisor/api/utils.py", line 60, in wrap_api
answer = await method(api, *args, **kwargs)
File "/usr/src/supervisor/supervisor/api/network.py", line 154, in info
ATTR_INTERFACES: [
File "/usr/src/supervisor/supervisor/api/network.py", line 155, in <listcomp>
interface_struct(interface)
File "/usr/src/supervisor/supervisor/api/network.py", line 114, in interface_struct
ATTR_VLAN: wifi_struct(interface.vlan) if interface.vlan else None,
File "/usr/src/supervisor/supervisor/api/network.py", line 96, in wifi_struct
ATTR_MODE: config.mode,
AttributeError: 'VlanConfig' object has no attribute 'mode'

# Fixed code
def accesspoint_struct(accesspoint: AccessPoint) -> Dict[str, Any]:
    """Return a dict for AccessPoint."""
    return {
        ATTR_MODE: accesspoint.mode,
        ATTR_SSID: accesspoint.ssid,
        ATTR_FREQUENCY: accesspoint.frequency,
        ATTR_SIGNAL: accesspoint.signal,
        ATTR_MAC: accesspoint.mac,
    }
# Buggy code
def writerest(self, directory, item):
    """Write the item to an ReST file

    This will keep state (in the `rest` variable) in order to avoid
    writing continuously to the same files.
    """

    if item is None or slug(self.artist) != slug(item.albumartist):
        if self.rest is not None:
            path = os.path.join(directory, "artists", slug(self.artist) + ".rst")
            with open(path, "wb") as output:
                output.write(self.rest.encode("utf-8"))
            self.rest = None
            if item is None:
                return
        self.artist = item.albumartist.strip()
        self.rest = "%s\n%s\n\n.. contents::\n   :local:\n\n" % (
            self.artist,
            "=" * len(self.artist),
        )
    if self.album != item.album:
        tmpalbum = self.album = item.album.strip()
        if self.album == "":
            tmpalbum = "Unknown album"
        self.rest += "%s\n%s\n\n" % (tmpalbum, "-" * len(tmpalbum))
    title_str = ":index:`%s`" % item.title.strip()
    block = "| " + item.lyrics.replace("\n", "\n| ")
    self.rest += "%s\n%s\n\n%s\n\n" % (title_str, "~" * len(title_str), block)


# Traceback (AttributeError)
$ beet -vv lyrics artie shaw carioca
user configuration: /home/doron/.config/beets/config.yaml
data directory: /home/doron/.config/beets
plugin paths:
Sending event: pluginload
inline: adding item field isMultiDisc
library database: /var/lib/beets/db
library directory: /var/lib/mpd/music
Sending event: library_opened
lyrics: failed to fetch: https://www.musixmatch.com/lyrics/Artie-Shaw-and-His-Orchestra/Carioca (404)
lyrics: failed to fetch: https://www.musixmatch.com/lyrics/Artie-Shaw/Carioca (404)
lyrics: failed to fetch: https://www.musixmatch.com/es/letras/Buddy-Rich-Artie-Shaw/The-Carioca (404)
lyrics: failed to fetch: https://www.musixmatch.com/lyrics/Artie-Shaw/Carioca (404)
lyrics: lyrics not found: FLAC % Artie Shaw - Begin the Beguine | CD-04 | 25 Carioca
Traceback (most recent call last):
File "/usr/bin/beet", line 11, in <module>
load_entry_point('beets==1.4.6', 'console_scripts', 'beet')()
File "/usr/lib/python3.6/site-packages/beets/ui/__init__.py", line 1256, in main
_raw_main(args)
File "/usr/lib/python3.6/site-packages/beets/ui/__init__.py", line 1243, in _raw_main
subcommand.func(lib, suboptions, subargs)
File "/usr/lib/python3.6/site-packages/beetsplug/lyrics.py", line 734, in func
self.writerest(opts.writerest, None)
File "/usr/lib/python3.6/site-packages/beetsplug/lyrics.py", line 762, in writerest
self.artist = item.artist.strip()
AttributeError: 'NoneType' object has no attribute 'artist'

# Fixed code
def writerest(self, directory):
    """Write self.rest to a ReST file"""
    if self.rest is not None and self.artist is not None:
        path = os.path.join(directory, "artists", slug(self.artist) + ".rst")
        with open(path, "wb") as output:
            output.write(self.rest.encode("utf-8"))
# Buggy code
def open_audio_file(self, item):
    """Open the file to read the PCM stream from the using
    ``item.path``.

    :return: the audiofile instance
    :rtype: :class:`audiotools.AudioFile`
    :raises :exc:`ReplayGainError`: if the file is not found or the
    file format is not supported
    """
    try:
        audiofile = self._mod_audiotools.open(item.path)
    except IOError:
        raise ReplayGainError("File {} was not found".format(item.path))
    except self._mod_audiotools.UnsupportedFile:
        raise ReplayGainError("Unsupported file type {}".format(item.format))

    return audiofile


# Traceback (TypeError)
Sending event: library_opened
replaygain: analyzing Pink Floyd - The Wall - In the Flesh?
Traceback (most recent call last):
File "/usr/bin/beet", line 11, in <module>
load_entry_point('beets==1.5.0', 'console_scripts', 'beet')()
File "/usr/lib/python3.7/site-packages/beets-1.5.0-py3.7.egg/beets/ui/__init__.py", line 1267, in main
_raw_main(args)
File "/usr/lib/python3.7/site-packages/beets-1.5.0-py3.7.egg/beets/ui/__init__.py", line 1254, in _raw_main
subcommand.func(lib, suboptions, subargs)
File "/usr/lib/python3.7/site-packages/beets-1.5.0-py3.7.egg/beetsplug/replaygain.py", line 1052, in func
self.handle_track(item, write, force)
File "/usr/lib/python3.7/site-packages/beets-1.5.0-py3.7.egg/beetsplug/replaygain.py", line 1003, in handle_track
track_gains = backend_instance.compute_track_gain([item])
File "/usr/lib/python3.7/site-packages/beets-1.5.0-py3.7.egg/beetsplug/replaygain.py", line 752, in compute_track_gain
return [self._compute_track_gain(item) for item in items]
File "/usr/lib/python3.7/site-packages/beets-1.5.0-py3.7.egg/beetsplug/replaygain.py", line 752, in <listcomp>
return [self._compute_track_gain(item) for item in items]
File "/usr/lib/python3.7/site-packages/beets-1.5.0-py3.7.egg/beetsplug/replaygain.py", line 781, in _compute_track_gain
rg_track_gain, rg_track_peak = self._title_gain(rg, audiofile)
File "/usr/lib/python3.7/site-packages/beets-1.5.0-py3.7.egg/beetsplug/replaygain.py", line 764, in _title_gain
return rg.title_gain(audiofile.to_pcm())
File "/usr/lib/python3.7/site-packages/audiotools/mp3.py", line 217, in to_pcm
return MP3Decoder(self.filename)
TypeError: argument 1 must be str, not bytes

# Fixed code
def open_audio_file(self, item):
    """Open the file to read the PCM stream from the using
    ``item.path``.

    :return: the audiofile instance
    :rtype: :class:`audiotools.AudioFile`
    :raises :exc:`ReplayGainError`: if the file is not found or the
    file format is not supported
    """
    try:
        audiofile = self._mod_audiotools.open(py3_path(syspath(item.path)))
    except IOError:
        raise ReplayGainError("File {} was not found".format(item.path))
    except self._mod_audiotools.UnsupportedFile:
        raise ReplayGainError("Unsupported file type {}".format(item.format))

    return audiofile
# Buggy code
def authenticate(self):
    if self.m.is_authenticated():
        return
    # Checks for OAuth2 credentials,
    # if they don't exist - performs authorization
    oauth_file = self.config["oauth_file"].as_str()
    if os.path.isfile(oauth_file):
        uploader_id = self.config["uploader_id"]
        uploader_name = self.config["uploader_name"]
        self.m.login(
            oauth_credentials=oauth_file,
            uploader_id=uploader_id.as_str().upper() or None,
            uploader_name=uploader_name.as_str() or None,
        )
    else:
        self.m.perform_oauth(oauth_file)


# Traceback (AttributeError)
user configuration: /home/jlivin25/.config/beets/config.yaml
data directory: /home/jlivin25/.config/beets
plugin paths: /home/jlivin25/.config/beets/myplugins
Sending event: pluginload
Traceback (most recent call last):
File "/home/jlivin25/.local/bin/beet", line 11, in <module>
sys.exit(main())
File "/home/jlivin25/.local/lib/python2.7/site-packages/beets/ui/__init__.py", line 1266, in main
_raw_main(args)
File "/home/jlivin25/.local/lib/python2.7/site-packages/beets/ui/__init__.py", line 1249, in _raw_main
subcommands, plugins, lib = _setup(options, lib)
File "/home/jlivin25/.local/lib/python2.7/site-packages/beets/ui/__init__.py", line 1135, in _setup
plugins = _load_plugins(config)
File "/home/jlivin25/.local/lib/python2.7/site-packages/beets/ui/__init__.py", line 1121, in _load_plugins
plugins.send("pluginload")
File "/home/jlivin25/.local/lib/python2.7/site-packages/beets/plugins.py", line 488, in send
for handler in event_handlers()[event]:
File "/home/jlivin25/.local/lib/python2.7/site-packages/beets/plugins.py", line 471, in event_handlers
for plugin in find_plugins():
File "/home/jlivin25/.local/lib/python2.7/site-packages/beets/plugins.py", line 307, in find_plugins
_instances[cls] = cls()
File "/home/jlivin25/.local/lib/python2.7/site-packages/beetsplug/gmusic.py", line 39, in __init__
u'oauth_file': gmusicapi.clients.OAUTH_FILEPATH,
AttributeError: 'module' object has no attribute 'OAUTH_FILEPATH'

# Fixed code
def authenticate(self):
    if self.m.is_authenticated():
        return
    # Checks for OAuth2 credentials,
    # if they don't exist - performs authorization
    oauth_file = self.config["oauth_file"].as_filename()
    if os.path.isfile(oauth_file):
        uploader_id = self.config["uploader_id"]
        uploader_name = self.config["uploader_name"]
        self.m.login(
            oauth_credentials=oauth_file,
            uploader_id=uploader_id.as_str().upper() or None,
            uploader_name=uploader_name.as_str() or None,
        )
    else:
        self.m.perform_oauth(oauth_file)
# Buggy code
def lyrics_from_song_api_path(self, song_api_path):
    song_url = self.base_url + song_api_path
    response = requests.get(song_url, headers=self.headers)
    json = response.json()
    path = json["response"]["song"]["path"]
    # gotta go regular html scraping... come on Genius
    page_url = "https://genius.com" + path
    page = requests.get(page_url)
    html = BeautifulSoup(page.text, "html.parser")
    # remove script tags that they put in the middle of the lyrics
    [h.extract() for h in html("script")]
    # at least Genius is nice and has a tag called 'lyrics'!
    lyrics = html.find(
        "div", class_="lyrics"
    ).get_text()  # updated css where the lyrics are based in HTML
    return lyrics


# Traceback (AssertionError)
======================================================================
FAIL: Test default backends with songs known to exist in respective databases.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/flap/Dev/beets/test/test_lyrics.py", line 316, in test_backend_sources_ok
self.assertFalse(errors)
AssertionError: ['LyricsCom', 'MusiXmatch', 'Genius'] is not false
-------------------- >> begin captured logging << --------------------
[...]
beets.lyrics: DEBUG: lyrics: genius: requesting search https://api.genius.com/search?q=The%20Beatles%20Lady%20Madonna
requests.packages.urllib3.connectionpool: DEBUG: Starting new HTTPS connection (1): api.genius.com
requests.packages.urllib3.connectionpool: DEBUG: https://api.genius.com:443 "GET /search?q=The%20Beatles%20Lady%20Madonna HTTP/1.1" 200 None
beets.lyrics: DEBUG: lyrics: genius: requesting lyrics for link https://genius.com/The-beatles-lady-madonna-lyrics
requests.packages.urllib3.connectionpool: DEBUG: Starting new HTTP connection (1): genius-api.com
beets.lyrics: DEBUG: lyrics: genius: request error: HTTPConnectionPool(host='genius-api.com', port=80): Max retries exceeded with url: /api/lyricsInfo (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x104b29590>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))
--------------------- >> end captured logging << ---------------------

----------------------------------------------------------------------
Ran 17 tests in 15.582s

FAILED (failures=1)

# Fixed code
def lyrics_from_song_api_path(self, song_api_path):
    song_url = self.base_url + song_api_path
    response = requests.get(song_url, headers=self.headers)
    json = response.json()
    path = json["response"]["song"]["path"]

    # Gotta go regular html scraping... come on Genius.
    page_url = "https://genius.com" + path
    page = requests.get(page_url)
    html = BeautifulSoup(page.text, "html.parser")

    # Remove script tags that they put in the middle of the lyrics.
    [h.extract() for h in html("script")]

    # At least Genius is nice and has a tag called 'lyrics'!
    # Updated css where the lyrics are based in HTML.
    lyrics = html.find("div", class_="lyrics").get_text()

    return lyrics