File size: 1,800 Bytes
7405904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pathlib import Path
import zipfile
import shutil
import io
import streamlit as st


def save_temp_file(file: st.runtime.uploaded_file_manager.UploadedFile) -> str:
    """Saves in a temporary directory an Streamlit uploaded file

    Parameters
    ----------
    file : st.runtime.uploaded_file_manager.UploadedFile
        File from st.file_uploader return

    Returns
    -------
    str
        Path were file is saved temporary
    """
    temp_dir = Path(".temp")
    temp_file_path = temp_dir.joinpath(file.name)
    with open(str(temp_file_path), "wb") as temp_file:
        temp_file.write(file.getvalue())
    return temp_file_path


def create_temp_directory(dir_name: str = ".temp") -> Path:
    """Create a temporary directory.

    Parameters
    ----------
    dir_name : str, optional
        Name of the temporary directory, by default ".temp"

    Returns
    -------
    Path
        Path object representing the created temporary directory.
    """
    temp_dir = Path(dir_name)
    temp_dir.mkdir(exist_ok=True)
    return temp_dir


def clean_temp_directory() -> None:
    """Cleans .temp directory"""
    shutil.rmtree(Path(".temp"))


def compress_utterances_folder(utterances_folder: Path) -> io.BytesIO:
    """Compresses the contents of utterances_folder into a zip file.

    Parameters
    ----------
    utterances_folder : Path
        Path to the folder containing utterances.

    Returns
    -------
    io.BytesIO
        A BytesIO object representing the compressed zip file.
    """
    memory_file = io.BytesIO()
    with zipfile.ZipFile(memory_file, "w") as zip_file:
        for file_i in utterances_folder.iterdir():
            zip_file.write(str(file_i), arcname=file_i.name)

    memory_file.seek(0)
    clean_temp_directory()
    return memory_file