File size: 1,847 Bytes
74f2c64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""
Notes
-----
This module contains the functions for audiobook_gen that take the generated audio tensors and output to audio files,
as well as assembling the final zip archive for user download.
"""
import logging

from src import config


def write_audio(audio_list, sample_path):
    """
    Invokes torchaudio to save generated audio tensors to a file.

    Parameters
    ----------
    audio_list : torch.tensor
        pytorch tensor containing generated audio

    sample_path : str
        file name and path for outputting tensor to audio file

    Returns
    -------
    None

    """
    import torch
    import torchaudio
    from src import config as cf

    if not config.output_path.exists():
        config.output_path.mkdir()

    if len(audio_list) > 0:
        audio_file = torch.cat(audio_list).reshape(1, -1)
        torchaudio.save(sample_path, audio_file, cf.SAMPLE_RATE)
        logging.info(f'Audio generated at: {sample_path}')
    else:
        logging.info(f'Audio at: {sample_path} is empty.')


def assemble_zip(title):
    """
    Creates a zip file and inserts all .wav files in the output directory,
    and returns the name / path of the zip file.

    Parameters
    ----------
    title : str
        title of document, used to name zip directory

    Returns
    -------
    zip_name : str
        name and path of zip directory generated

    """
    import zipfile
    from stqdm import stqdm

    if not config.output_path.exists():
        config.output_path.mkdir()

    zip_name = config.output_path / f'{title}.zip'

    with zipfile.ZipFile(zip_name, mode="w") as archive:
        for file_path in stqdm(config.output_path.iterdir()):
            if file_path.suffix == '.wav':
                archive.write(file_path, arcname=file_path.name)
                file_path.unlink()

    return zip_name