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