[
  {
    "path": ".gitattributes",
    "content": "# Auto detect text files and perform LF normalization\n* text=auto\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n\n.DS_Store\n/input/*\n/output/*\n/pretrain/wav2vec2-large-robust-12-ft-emotion-msp-dim/*.bin"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 KakaruHayate\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# ColorSplitter\n\n![result](IMG/20240102162212.png)\n\n[中文文档](README_CN.md)\n\n[webui](https://github.com/KakaruHayate/ColorSplitter/tree/main/viewer)\n\nA command-line tool for separating vocal timbres\n\n# Introduction\n\nColorSplitter is a command-line tool for classifying the vocal timbre styles of single-speaker data in the pre-processing stage of vocal data.\n\nFor scenarios that do not require style classification, using this tool to filter data can also reduce the problem of unstable timbre performance of the model.\n\n**Please note** that this project is based on Speaker Verification technology, and it is not clear whether the timbre changes of singing are completely related to the voiceprint differences, just for fun :)\n\nThe research in this field is still scarce, hoping to inspire more ideas.\n\nThanks to the community user: 洛泠羽\n\n# New version features\n\nImplemented automatic optimization of clustering results, no longer need users to judge the optimal clustering results themselves.\n\n`splitter.py` deleted the `--nmax` parameter, added `--nmin` (minimum number of timbre types, invalid when cluster parameter is 2) `--cluster` (clustering method, 1:SpectralCluster, 2:UmapHdbscan), `--mer_cosine` to merge clusters that are too similar.\n\n**New version tips**\n\n1. Run `splitter.py` directly with the default parameters by specifying the speaker.\n\n2. If the result has only one cluster, observe the distribution map, set `--nmin` to the number you think is reasonable, and run `splitter.py` again.\n\n3. The optimal value of `--nmin` may be smaller than expected in actual tests.\n\n4. The new clustering algorithm is faster, it is recommended to try multiple times.\n\n5. The emotion classification function has now been implemented and can be called through the `--encoder emotion` function. Go to when using https://huggingface.co/audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim/tree/main Download `pytorch_Model.bin` is placed in the `wav2vec2-large-robust-12-ft-emotion-msp-dim` directory.\n\n6. You can also use `--encoder mix` to filter audio that matches two similar features at the same time. This feature can help you filter `GPT SoVITS` or `Bert-VITS2.3` prompts. \n\n# Progress\n\n- [x] **Correctly trained weights**\n- [x] Clustering algorithm optimization\n- [ ] ~SSL~\n- [x] emotional encoder\n- [x] embed mix\n\n# Environment Configuration\n\nIt works normally under `python3.8`, please go to install [Microsoft C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/)\n\nThen use the following command to install environment dependencies\n\n```\npip install -r requirements.txt\n```\n\nTips: If you are only using the timbre encoder, you only need to install the CPU version of pytorch. In other cases, it is recommended to use the GPU version. \n\n# How to Use\n\n**1. Move your well-made Diffsinger dataset to the `.\\input` folder and run the following command**\n\n```\npython splitter.py --spk <speaker_name> --nmin <'N'_min_num>\n```\n\nEnter the speaker name after `--spk`, and enter the minimum number of timbre types after `--nmin` (minimum 1, maximum 14，default 1)\n\nTips: This project does not need to read the annotation file (transcriptions.csv) of the Diffsinger dataset, so as long as the file structure is as shown below, it can work normally\n```\n    - input\n        - <speaker_name>\n            - raw\n                - wavs\n                    - audio1.wav\n                    - audio2.wav\n                    - ...\n```\nThe wav files are best already split\n\n\n**2. After you select the optimal result you think, run the following command to classify the wav files in the dataset**\n```\npython move_files.py --spk <speaker_name>\n```\nThe classified results will be saved in `.\\output\\<speaker_name>\\<clust_num>`\nAfter that, you still need to manually merge the too small clusters to meet the training requirements\n\n\n**3. (Optional) Move `clean_csv.py` to the same level as `transcriptions.csv` and run it, you can delete the wav file entries that are not included in the `wavs` folder**\n\n\n# Based on Project\n\n[Resemblyzer](https://github.com/resemble-ai/Resemblyzer/)\n\n[3D-Speaker](https://github.com/alibaba-damo-academy/3D-Speaker/)\n\n[wav2vec2-large-robust-12-ft-emotion-msp-dim](https://huggingface.co/audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim)\n\n[GTSinger](https://github.com/AaronZ345/GTSinger)\n"
  },
  {
    "path": "README_CN.md",
    "content": "# ColorSplitter\n\n![result](IMG/20240102162212.png)\n\n[webui](https://github.com/KakaruHayate/ColorSplitter/tree/main/viewer)\n\n一个用于分离歌声音色的命令行工具\n\n# 介绍\n\nColorSplitter是一个为了在歌声数据的处理前期，对单说话人数据的音色风格进行分类的命令行工具\n\n对于不需要进行风格分类的场合，使用本工具进行数据筛选，也可以减轻模型的音色表现不稳定问题\n\n**请注意**，本项目基于说话人确认（Speaker Verification）技术，目前并不确定唱歌的音色变化是与声纹差异完全相关，just for fun：)\n\n目前该领域研究仍然匮乏，抛砖引玉\n\n感谢社区用户：洛泠羽\n\n# 新版本特性\n\n实装了聚类结果自动优化，不再需要用户自己判断聚类最优结果\n\n`splitter.py`删除了`--nmax`参数，添加了`--nmin`（最小音色类型数量，cluster参数为2时无效）`--cluster`（聚类方式，1:SpectralCluster, 2:UmapHdbscan），`--mer_cosine`合并过于相似的簇\n\n**新版本使用技巧**\n\n1.默认参数直接指定说话人运行`splitter.py`\n\n2.如果结果只有一个簇，观察分布图，将`--nmin`设为你认为合理的数量，再次运行`splitter.py`\n\n3.实际测试下`--nmin`的最优值可能比想象的要小\n\n4.新的聚类算法速度较快，建议多次尝试\n\n5.新版本已支持情绪编码器的使用，可以通过`--encoder emotion`调用。使用时前往 https://huggingface.co/audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim/tree/main 下载 `pytorch_model.bin` 放置在 `pretrain/wav2vec2-large-robust-12-ft-emotion-msp-dim` 目录下\n\n6.你也可以用`--encoder mix`筛选同时符合两个特征相似的音频，这个功能可以帮助你筛选`GPT SoVITS`和`BertVITS2.3`的参考音频\n\n# 进展\n\n- [x] **正确训练的权重**\n- [x] 聚类算法优化\n- [ ] ~SSL~\n- [x] emotional encoder\n- [x] embed mix\n\n# 环境配置\n\n`python3.8`下使用正常，请先安装[Microsoft C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/)\n\n之后使用以下命令安装环境依赖\n\n```\npip install -r requirements.txt\n```\n注意：如果你只是用音色编码器则只需要安装CPU版本的pytorch，其他情况下建议使用GPU版本\n\n# 如何使用\n\n**1.将你制作好的Diffsinger数据集移动到`.\\input`文件夹下，运行以下命令**\n\n```\npython splitter.py --spk <speaker_name> --nmin <'N'_min_num>\n```\n\n其中`--spk`后输入说话人名称，`--nmin`后输入最小音色类型数量（最小1最大14默认1）\n\ntips:本项目并不需要读取Diffsinger数据集的标注文件（transcriptions.csv），所以保证只要文件结构如下所示就可以正常工作\n```\n    - input\n        - <speaker_name>\n            - raw\n                - wavs\n                    - audio1.wav\n                    - audio2.wav\n                    - ...\n```\n其中wav文件最好已经进行过切分\n\n**2.选定你认为的最优结果后，运行以下命令将数据集中的wav文件分类**\n\n```\npython move_files.py --spk <speaker_name>\n```\n分类后结果将保存到`.\\output\\<speaker_name>\\<clust_num>`中\n在那之后还需要人工对过小的簇进行归并，以达到训练的需求\n\n**3.（可选）将`clean_csv.py`移动到与`transcriptions.csv`同级后运行，可以删除`wavs`文件夹中没有包含的wav文件条目**\n\n# 基于项目\n\n[Resemblyzer](https://github.com/resemble-ai/Resemblyzer/)\n\n[3D-Speaker](https://github.com/alibaba-damo-academy/3D-Speaker/)\n\n[wav2vec2-large-robust-12-ft-emotion-msp-dim](https://huggingface.co/audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim)\n\n[GTSinger](https://github.com/AaronZ345/GTSinger)\n"
  },
  {
    "path": "clean_csv.py",
    "content": "import os\nimport csv\n\n\nwav_files = set(f[:-4] for f in os.listdir('wavs') if f.endswith('.wav'))\nwith open('transcriptions.csv', 'r') as f:\n    reader = csv.reader(f)\n    header = next(reader)\n    rows = [row for row in reader if row[0] in wav_files]\n\nwith open('transcriptions.csv', 'w', newline='') as f:\n    writer = csv.writer(f)\n    writer.writerow(header)\n    writer.writerows(rows)"
  },
  {
    "path": "kick.py",
    "content": "import os\nimport shutil\nimport pandas as pd\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--spk', type=str, help='Speaker name')\nparser.add_argument('--clust', type=int, help='Cluster value')\nparser.add_argument('--encoder', type=str, default='timbre', help='encoder type')\nargs = parser.parse_args()\n\nSpeaker_name = args.spk #Speaker name\nclust_value = args.clust # Cluster value\nencoder_name = args.encoder\n\ndata = pd.read_csv(os.path.join('output', Speaker_name, f'clustered_files({encoder_name}).csv'))\n\nfor index, row in data.iterrows():\n    file_path = row['filename']\n    clust = row['clust']\n\n    if clust == clust_value:\n        clust_dir = os.path.join('input', f'{Speaker_name}_{clust_value}')\n        if not os.path.exists(clust_dir):\n            os.makedirs(clust_dir)\n\n        shutil.move(file_path, clust_dir)\n"
  },
  {
    "path": "load_npy.py",
    "content": "import pandas as pd\nfrom pathlib import Path\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom modules.visualizations import plot_projections, process_json_file\nfrom modules.cluster import CommonClustering\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--path', type=str, help='path to the .npy file')\nparser.add_argument('--reducer', type=int, default=2, help='1:tSNE, 2:Umap')\nparser.add_argument('--json', type=str, default=None, help='path to the .json file')\nargs = parser.parse_args()\n\nif args.reducer == 1:\n\tcluster_name = 'spectral'\nelif args.reducer == 2:\n\tcluster_name = 'umap_hdbscan'\nelse:\n\traise ValueError('reducer type error')\n\nnpy_path = args.path\n\nembeds = np.load(npy_path)\n\nif args.json == None:\n\ttoken_names = np.arange(embeds.shape[0])\nelse:\n\ttoken_names = process_json_file(args.json)\nlabels = np.ones_like(token_names)\n\noutput_dir = f'output/npy_result'\nif not os.path.exists(output_dir):\n\tos.makedirs(output_dir)\n\ndf = pd.DataFrame({\n\t'token': [f'{i}' for i in range(embeds.shape[0])],\n\t'clust': labels\n})\ndf.to_csv(f'{output_dir}/clustered_files({os.path.basename(npy_path)}).csv', index=False)\n\n\nplot_projections(embeds, labels, title=\"Embedding projections\", cluster_name=cluster_name, labels=token_names)\nplt.savefig(f'{output_dir}/embedding_projections({os.path.basename(npy_path)}).png', dpi=600)\nplt.show()\n"
  },
  {
    "path": "modules/cluster.py",
    "content": "# Copyright 3D-Speaker (https://github.com/alibaba-damo-academy/3D-Speaker). All Rights Reserved.\n# Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\nimport numpy as np\nimport scipy\nimport sklearn\nfrom sklearn.cluster._kmeans import k_means\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ntry:\n    import umap, hdbscan\nexcept ImportError:\n    raise ImportError(\n        \"Package \\\"umap\\\" or \\\"hdbscan\\\" not found. \\\n        Please install them first by \\\"pip install umap-learn hdbscan\\\".\"\n        )\n\n\nclass SpectralCluster:\n    \"\"\"A spectral clustering method using unnormalized Laplacian of affinity matrix.\n    This implementation is adapted from https://github.com/speechbrain/speechbrain.\n    \"\"\"\n\n    def __init__(self, min_num_spks=1, max_num_spks=14, pval=0.02, min_pnum=6, oracle_num=None):\n        self.min_num_spks = min_num_spks\n        self.max_num_spks = max_num_spks\n        self.min_pnum = min_pnum\n        self.pval = pval\n        self.k = oracle_num\n\n    def __call__(self, X, pval=None, oracle_num=None):\n        # Similarity matrix computation\n        sim_mat = self.get_sim_mat(X)\n\n        # Refining similarity matrix with pval\n        prunned_sim_mat = self.p_pruning(sim_mat, pval)\n\n        # Symmetrization\n        sym_prund_sim_mat = 0.5 * (prunned_sim_mat + prunned_sim_mat.T)\n\n        # Laplacian calculation\n        laplacian = self.get_laplacian(sym_prund_sim_mat)\n\n        # Get Spectral Embeddings\n        emb, num_of_spk = self.get_spec_embs(laplacian, oracle_num)\n\n        # Perform clustering\n        labels = self.cluster_embs(emb, num_of_spk)\n\n        return labels\n\n    def get_sim_mat(self, X):\n        # Cosine similarities\n        M = cosine_similarity(X, X)\n        return M\n\n    def p_pruning(self, A, pval=None):\n        if pval is None:\n            pval = self.pval\n        n_elems = int((1 - pval) * A.shape[0])\n        n_elems = min(n_elems, A.shape[0]-self.min_pnum)\n\n        # For each row in a affinity matrix\n        for i in range(A.shape[0]):\n            low_indexes = np.argsort(A[i, :])\n            low_indexes = low_indexes[0:n_elems]\n\n            # Replace smaller similarity values by 0s\n            A[i, low_indexes] = 0\n        return A\n\n    def get_laplacian(self, M):\n        M[np.diag_indices(M.shape[0])] = 0\n        D = np.sum(np.abs(M), axis=1)\n        D = np.diag(D)\n        L = D - M\n        return L\n\n    def get_spec_embs(self, L, k_oracle=None):\n        if k_oracle is None:\n            k_oracle = self.k\n\n        lambdas, eig_vecs = scipy.linalg.eigh(L)\n\n        if k_oracle is not None:\n            num_of_spk = k_oracle\n        else:\n            lambda_gap_list = self.getEigenGaps(\n                lambdas[self.min_num_spks - 1:self.max_num_spks + 1])\n            num_of_spk = np.argmax(lambda_gap_list) + self.min_num_spks\n\n        emb = eig_vecs[:, :num_of_spk]\n        return emb, num_of_spk\n\n    def cluster_embs(self, emb, k):\n        # k-means\n        _, labels, _ = k_means(emb, k, n_init='auto')\n        return labels\n\n    def getEigenGaps(self, eig_vals):\n        eig_vals_gap_list = []\n        for i in range(len(eig_vals) - 1):\n            gap = float(eig_vals[i + 1]) - float(eig_vals[i])\n            eig_vals_gap_list.append(gap)\n        return eig_vals_gap_list\n\n\nclass UmapHdbscan:\n    \"\"\"\n    Reference:\n    - Siqi Zheng, Hongbin Suo. Reformulating Speaker Diarization as Community Detection With \n      Emphasis On Topological Structure. ICASSP2022\n    \"\"\"\n\n    def __init__(self, n_neighbors=20, n_components=60, min_samples=20, min_cluster_size=10, metric='euclidean'):\n        self.n_neighbors = n_neighbors\n        self.n_components = n_components\n        self.min_samples = min_samples\n        self.min_cluster_size = min_cluster_size\n        self.metric = metric\n\n    def __call__(self, X):\n        umap_X = umap.UMAP(\n            n_neighbors=self.n_neighbors,\n            min_dist=0.0,\n            n_components=min(self.n_components, X.shape[0]-2),\n            metric=self.metric,\n        ).fit_transform(X)\n        labels = hdbscan.HDBSCAN(min_samples=self.min_samples, min_cluster_size=self.min_cluster_size).fit_predict(umap_X)\n        return labels\n\n\nclass CommonClustering:\n    \"\"\"Perfom clustering for input embeddings and output the labels.\n    \"\"\"\n\n    def __init__(self, cluster_type, cluster_line=10, mer_cos=None, min_cluster_size=4, **kwargs):\n        self.cluster_type = cluster_type\n        self.cluster_line = cluster_line\n        self.min_cluster_size = min_cluster_size\n        self.mer_cos = mer_cos\n        if self.cluster_type == 'spectral':\n            self.cluster = SpectralCluster(**kwargs)\n        elif self.cluster_type == 'umap_hdbscan':\n            kwargs['min_cluster_size'] = min_cluster_size\n            self.cluster = UmapHdbscan(**kwargs)\n        else:\n            raise ValueError(\n                '%s is not currently supported.' % self.cluster_type\n            )\n\n    def __call__(self, X):\n        # clustering and return the labels\n        assert len(X.shape) == 2, 'Shape of input should be [N, C]'\n        if X.shape[0] < self.cluster_line:\n            return np.ones(X.shape[0], dtype=int)\n        # clustering\n        labels = self.cluster(X)\n\n        # remove extremely minor cluster\n        labels = self.filter_minor_cluster(labels, X, self.min_cluster_size)\n        # merge similar  speaker\n        if self.mer_cos is not None:\n            labels = self.merge_by_cos(labels, X, self.mer_cos)\n        \n        return labels\n    \n    def filter_minor_cluster(self, labels, x, min_cluster_size):\n        cset = np.unique(labels)\n        csize = np.array([(labels == i).sum() for i in cset])\n        minor_idx = np.where(csize < self.min_cluster_size)[0]\n        if len(minor_idx) == 0:\n            return labels\n        \n        minor_cset = cset[minor_idx]\n        major_idx = np.where(csize >= self.min_cluster_size)[0]\n        major_cset = cset[major_idx]\n        major_center = np.stack([x[labels == i].mean(0) \\\n            for i in major_cset])\n        for i in range(len(labels)):\n            if labels[i] in minor_cset:\n                cos_sim = cosine_similarity(x[i][np.newaxis], major_center)\n                labels[i] = major_cset[cos_sim.argmax()]\n\n        return labels\n\n    def merge_by_cos(self, labels, x, cos_thr):\n        # merge the similar speakers by cosine similarity\n        assert cos_thr > 0 and cos_thr <= 1\n        while True:\n            cset = np.unique(labels)\n            if len(cset) == 1:\n                break\n            centers = np.stack([x[labels == i].mean(0) \\\n                for i in cset])\n            affinity = cosine_similarity(centers, centers)\n            affinity = np.triu(affinity, 1)\n            idx = np.unravel_index(np.argmax(affinity), affinity.shape)\n            if affinity[idx] < cos_thr:\n                break\n            c1, c2 = cset[np.array(idx)]\n            labels[labels==c2]=c1\n        return labels\n"
  },
  {
    "path": "modules/model/emotion_encoder.py",
    "content": "import torch\nimport torch.nn as nn\nfrom transformers import Wav2Vec2Processor\nfrom transformers.models.wav2vec2.modeling_wav2vec2 import (\n    Wav2Vec2Model,\n    Wav2Vec2PreTrainedModel,\n)\nimport os\nimport librosa\nimport numpy as np\n\n\nclass RegressionHead(nn.Module):\n    r\"\"\"Classification head.\"\"\"\n\n    def __init__(self, config):\n        super().__init__()\n\n        self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n        self.dropout = nn.Dropout(config.final_dropout)\n        self.out_proj = nn.Linear(config.hidden_size, config.num_labels)\n\n    def forward(self, features, **kwargs):\n        x = features\n        x = self.dropout(x)\n        x = self.dense(x)\n        x = torch.tanh(x)\n        x = self.dropout(x)\n        x = self.out_proj(x)\n\n        return x\n\n\nclass EmotionModel(Wav2Vec2PreTrainedModel):\n    r\"\"\"Speech emotion classifier.\"\"\"\n\n    def __init__(self, config):\n        super().__init__(config)\n\n        self.config = config\n        self.wav2vec2 = Wav2Vec2Model(config)\n        self.classifier = RegressionHead(config)\n        self.init_weights()\n\n    def forward(\n            self,\n            input_values,\n    ):\n        outputs = self.wav2vec2(input_values)\n        hidden_states = outputs[0]\n        hidden_states = torch.mean(hidden_states, dim=1)\n        logits = self.classifier(hidden_states)\n\n        return hidden_states, logits\n\n\n# load model from hub\ndevice = 'cuda' if torch.cuda.is_available() else \"cpu\"\nmodel_path = './pretrain/wav2vec2-large-robust-12-ft-emotion-msp-dim'\nprocessor = Wav2Vec2Processor.from_pretrained(model_path)\nmodel = EmotionModel.from_pretrained(model_path).to(device)\n\n\ndef process_func(\n        x: np.ndarray,\n        sampling_rate: int,\n        embeddings: bool = False,\n) -> np.ndarray:\n    r\"\"\"Predict emotions or extract embeddings from raw audio signal.\"\"\"\n\n    # run through processor to normalize signal\n    # always returns a batch, so we just get the first entry\n    # then we put it on the device\n    y = processor(x, sampling_rate=sampling_rate)\n    y = y['input_values'][0]\n    y = y.reshape(1, -1)\n    y = torch.from_numpy(y).to(device)\n\n    # run through model\n    with torch.no_grad():\n        y = model(y)[0 if embeddings else 1]\n\n    # convert to numpy\n    y = y.detach().cpu().numpy()\n\n    return y\n\n\ndef extract_wav(path):\n    wav, sr = librosa.load(path, sr = 16000)\n    emb = process_func(np.expand_dims(wav, 0), sr, embeddings=True)\n    return emb\n\n"
  },
  {
    "path": "modules/model/voice_encoder.py",
    "content": "from resemblyzer.hparams import *\nfrom resemblyzer import audio\nfrom pathlib import Path\nfrom typing import Union, List\nfrom torch import nn\nfrom time import perf_counter as timer\nimport numpy as np\nimport torch\n\n\nclass VoiceEncoder(nn.Module):\n    def __init__(self, device: Union[str, torch.device]=\"cpu\", verbose=True, weights_fpath: Union[Path, str]=None):\n        \"\"\"\n        If None, defaults to cuda if it is available on your machine, otherwise the model will\n        run on cpu. Outputs are always returned on the cpu, as numpy arrays.\n        :param weights_fpath: path to \"<CUSTOM_MODEL>.pt\" file path.\n        If None, defaults to built-in \"pretrained.pt\" model\n        \"\"\"\n        super().__init__()\n\n        # Define the network\n        self.lstm = nn.LSTM(mel_n_channels, model_hidden_size, model_num_layers, batch_first=True)\n        self.linear = nn.Linear(model_hidden_size, model_embedding_size)\n        self.relu = nn.ReLU()\n\n        # Get the target device\n        if device is None:\n            device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n        elif isinstance(device, str):\n            device = torch.device(device)\n        self.device = device\n\n        # Load the pretrained model'speaker weights\n        if weights_fpath is None:\n            weights_fpath = Path(__file__).resolve().parent.joinpath(\"pretrained.pt\")\n        else:\n            weights_fpath = Path(weights_fpath)\n\n        if not weights_fpath.exists():\n            raise Exception(\"Couldn't find the voice encoder pretrained model at %s.\" %\n                            weights_fpath)\n        start = timer()\n        checkpoint = torch.load(weights_fpath, map_location=\"cpu\")\n        self.load_state_dict(checkpoint[\"model_state\"], strict=False)\n        self.to(device)\n\n        if verbose:\n            print(\"Loaded the voice encoder model on %s in %.2f seconds.\" %\n                  (device.type, timer() - start))\n\n    def forward(self, mels: torch.FloatTensor):\n        \"\"\"\n        Computes the embeddings of a batch of utterance spectrograms.\n\n        :param mels: a batch of mel spectrograms of same duration as a float32 tensor of shape\n        (batch_size, n_frames, n_channels)\n        :return: the embeddings as a float 32 tensor of shape (batch_size, embedding_size).\n        Embeddings are positive and L2-normed, thus they lay in the range [0, 1].\n        \"\"\"\n        # Pass the input through the LSTM layers and retrieve the final hidden state of the last\n        # layer. Apply a cutoff to 0 for negative values and L2 normalize the embeddings.\n        _, (hidden, _) = self.lstm(mels)\n        embeds_raw = self.relu(self.linear(hidden[-1]))\n        return embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True)\n\n    @staticmethod\n    def compute_partial_slices(n_samples: int, rate, min_coverage):\n        \"\"\"\n        Computes where to split an utterance waveform and its corresponding mel spectrogram to\n        obtain partial utterances of <partials_n_frames> each. Both the waveform and the\n        mel spectrogram slices are returned, so as to make each partial utterance waveform\n        correspond to its spectrogram.\n\n        The returned ranges may be indexing further than the length of the waveform. It is\n        recommended that you pad the waveform with zeros up to wav_slices[-1].stop.\n\n        :param n_samples: the number of samples in the waveform\n        :param rate: how many partial utterances should occur per second. Partial utterances must\n        cover the span of the entire utterance, thus the rate should not be lower than the inverse\n        of the duration of a partial utterance. By default, partial utterances are 1.6s long and\n        the minimum rate is thus 0.625.\n        :param min_coverage: when reaching the last partial utterance, it may or may not have\n        enough frames. If at least <min_pad_coverage> of <partials_n_frames> are present,\n        then the last partial utterance will be considered by zero-padding the audio. Otherwise,\n        it will be discarded. If there aren't enough frames for one partial utterance,\n        this parameter is ignored so that the function always returns at least one slice.\n        :return: the waveform slices and mel spectrogram slices as lists of array slices. Index\n        respectively the waveform and the mel spectrogram with these slices to obtain the partial\n        utterances.\n        \"\"\"\n        assert 0 < min_coverage <= 1\n\n        # Compute how many frames separate two partial utterances\n        samples_per_frame = int((sampling_rate * mel_window_step / 1000))\n        n_frames = int(np.ceil((n_samples + 1) / samples_per_frame))\n        frame_step = int(np.round((sampling_rate / rate) / samples_per_frame))\n        assert 0 < frame_step, \"The rate is too high\"\n        assert frame_step <= partials_n_frames, \"The rate is too low, it should be %f at least\" % \\\n            (sampling_rate / (samples_per_frame * partials_n_frames))\n\n        # Compute the slices\n        wav_slices, mel_slices = [], []\n        steps = max(1, n_frames - partials_n_frames + frame_step + 1)\n        for i in range(0, steps, frame_step):\n            mel_range = np.array([i, i + partials_n_frames])\n            wav_range = mel_range * samples_per_frame\n            mel_slices.append(slice(*mel_range))\n            wav_slices.append(slice(*wav_range))\n\n        # Evaluate whether extra padding is warranted or not\n        last_wav_range = wav_slices[-1]\n        coverage = (n_samples - last_wav_range.start) / (last_wav_range.stop - last_wav_range.start)\n        if coverage < min_coverage and len(mel_slices) > 1:\n            mel_slices = mel_slices[:-1]\n            wav_slices = wav_slices[:-1]\n\n        return wav_slices, mel_slices\n\n    def embed_utterance(self, wav: np.ndarray, return_partials=False, rate=1.3, min_coverage=0.75):\n        \"\"\"\n        Computes an embedding for a single utterance. The utterance is divided in partial\n        utterances and an embedding is computed for each. The complete utterance embedding is the\n        L2-normed average embedding of the partial utterances.\n\n        TODO: independent batched version of this function\n\n        :param wav: a preprocessed utterance waveform as a numpy array of float32\n        :param return_partials: if True, the partial embeddings will also be returned along with\n        the wav slices corresponding to each partial utterance.\n        :param rate: how many partial utterances should occur per second. Partial utterances must\n        cover the span of the entire utterance, thus the rate should not be lower than the inverse\n        of the duration of a partial utterance. By default, partial utterances are 1.6s long and\n        the minimum rate is thus 0.625.\n        :param min_coverage: when reaching the last partial utterance, it may or may not have\n        enough frames. If at least <min_pad_coverage> of <partials_n_frames> are present,\n        then the last partial utterance will be considered by zero-padding the audio. Otherwise,\n        it will be discarded. If there aren't enough frames for one partial utterance,\n        this parameter is ignored so that the function always returns at least one slice.\n        :return: the embedding as a numpy array of float32 of shape (model_embedding_size,). If\n        <return_partials> is True, the partial utterances as a numpy array of float32 of shape\n        (n_partials, model_embedding_size) and the wav partials as a list of slices will also be\n        returned.\n        \"\"\"\n        # Compute where to split the utterance into partials and pad the waveform with zeros if\n        # the partial utterances cover a larger range.\n        wav_slices, mel_slices = self.compute_partial_slices(len(wav), rate, min_coverage)\n        max_wave_length = wav_slices[-1].stop\n        if max_wave_length >= len(wav):\n            wav = np.pad(wav, (0, max_wave_length - len(wav)), \"constant\")\n\n        # Split the utterance into partials and forward them through the model\n        mel = audio.wav_to_mel_spectrogram(wav)\n        mels = np.array([mel[s] for s in mel_slices])\n        with torch.no_grad():\n            mels = torch.from_numpy(mels).to(self.device)\n            partial_embeds = self(mels).cpu().numpy()\n\n        # Compute the utterance embedding from the partial embeddings\n        raw_embed = np.mean(partial_embeds, axis=0)\n        embed = raw_embed / np.linalg.norm(raw_embed, 2)\n\n        if return_partials:\n            return embed, partial_embeds, wav_slices\n        return embed\n\n    def embed_speaker(self, wavs: List[np.ndarray], **kwargs):\n        \"\"\"\n        Compute the embedding of a collection of wavs (presumably from the same speaker) by\n        averaging their embedding and L2-normalizing it.\n\n        :param wavs: list of wavs a numpy arrays of float32.\n        :param kwargs: extra arguments to embed_utterance()\n        :return: the embedding as a numpy array of float32 of shape (model_embedding_size,).\n        \"\"\"\n        raw_embed = np.mean([self.embed_utterance(wav, return_partials=False, **kwargs) \\\n                             for wav in wavs], axis=0)\n        return raw_embed / np.linalg.norm(raw_embed, 2)"
  },
  {
    "path": "modules/utils.py",
    "content": "from resemblyzer import preprocess_wav\nfrom modules.model.voice_encoder import VoiceEncoder\nfrom tqdm import tqdm\nimport numpy as np\nimport pickle\nimport os\nimport importlib\n\nclass GetEmbeds:\n    \"\"\" Used to obtain embedding vectors for audio. Directly input wav.\n    \"\"\"\n\n    def __init__(self, encoder_type, Speaker_name):\n        self.encoder_type = encoder_type\n        self.Speaker_name = Speaker_name\n        if self.encoder_type == 'timbre':\n            self.encoder = VoiceEncoder(weights_fpath=\"pretrain/encoder_1570000.bak\")\n        elif self.encoder_type == 'emotion':\n            self.emotion_module = importlib.import_module('modules.model.emotion_encoder')\n        elif self.encoder_type == 'mix':\n            self.encoder = VoiceEncoder(weights_fpath=\"pretrain/encoder_1570000.bak\")\n            self.emotion_module = importlib.import_module('modules.model.emotion_encoder')\n        else:\n            raise ValueError(\n                '%s is not currently supported.' % self.encoder_type\n            )\n\n    def __call__(self, wav_fpaths):\n        if self.encoder_type == 'timbre':\n            embeds = self.timbre_encoder(wav_fpaths)\n        if self.encoder_type == 'emotion':\n            embeds = self.emotion_encoder(wav_fpaths)\n        if self.encoder_type == 'mix':\n            embeds = self.mix_encoder(wav_fpaths)\n        \n        return embeds\n    \n    def timbre_encoder(self, wav_fpaths):\n        features_path = os.path.join(\"input\", self.Speaker_name, \"features(timbre).pkl\")\n        # Check if features already exist\n        if os.path.exists(features_path):\n            with open(features_path, 'rb') as f:\n                embeds = pickle.load(f)\n        else:\n            wavs = [preprocess_wav(wav_fpath) for wav_fpath in \\\n                    tqdm(wav_fpaths, f\"Preprocessing wavs ({len(wav_fpaths)} utterances)\")] \n            embeds = np.array(list(map(self.encoder.embed_utterance, wavs)))\n            with open(features_path, 'wb') as f:\n                pickle.dump(embeds, f)\n        \n        return embeds\n    \n    def emotion_encoder(self, wav_fpaths):\n        features_path = os.path.join(\"input\", self.Speaker_name, \"features(emotion).pkl\")\n        # Check if features already exist\n        if os.path.exists(features_path):\n            with open(features_path, 'rb') as f:\n                embeds = pickle.load(f)\n        else:\n            embeds = [self.emotion_module.extract_wav(wav_fpath) for wav_fpath in \\\n                    tqdm(wav_fpaths, f\"Preprocessing wavs ({len(wav_fpaths)} utterances)\")] \n            embeds = np.concatenate(embeds,axis=0)\n            with open(features_path, 'wb') as f:\n                pickle.dump(embeds, f)\n        \n        return embeds\n    \n    def mix_encoder(self, wav_fpaths):\n        features_path = os.path.join(\"input\", self.Speaker_name, \"features(mix).pkl\")\n        # Check if features already exist\n        if os.path.exists(features_path):\n            with open(features_path, 'rb') as f:\n                embeds = pickle.load(f)\n        else:\n            timber_embeds = self.timbre_encoder(wav_fpaths)\n            emotion_embeds = self.emotion_encoder(wav_fpaths)\n            embeds = np.concatenate((timber_embeds, emotion_embeds), axis=1)\n            with open(features_path, 'wb') as f:\n                pickle.dump(embeds, f)\n        \n        return embeds\n        "
  },
  {
    "path": "modules/visualizations.py",
    "content": "from mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.animation import FuncAnimation\nfrom resemblyzer import sampling_rate\nfrom matplotlib import cm\nfrom time import sleep, perf_counter as timer\nfrom umap import UMAP\nfrom sys import stderr\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.manifold import TSNE\nimport json\n\n\n_default_colors = plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\n_my_colors = np.array([\n    [0, 127, 70],\n    [255, 0, 0],\n    [255, 217, 38],\n    [0, 135, 255],\n    [165, 0, 165],\n    [255, 167, 255],\n    [97, 142, 151],\n    [0, 255, 255],\n    [255, 96, 38],\n    [142, 76, 0],\n    [33, 0, 127],\n    [0, 0, 0],\n    [183, 183, 183],\n    [76, 255, 0],\n], dtype=float) / 255\n\n\ndef generate_colors(n):\n    cm = plt.get_cmap('gist_rainbow')\n    colors = [cm(1.*i/n) for i in range(n)]\n    return colors\n\n\ndef play_wav(wav, blocking=True):\n    try:\n        import sounddevice as sd\n        # Small bug with sounddevice.play: the audio is cut 0.5 second too early. We pad it to \n        # make up for that\n        wav = np.concatenate((wav, np.zeros(sampling_rate // 2)))\n        sd.play(wav, sampling_rate, blocking=blocking)\n    except Exception as e:\n        print(\"Failed to play audio: %s\" % repr(e))\n\n\ndef plot_similarity_matrix(matrix, labels_a=None, labels_b=None, ax: plt.Axes=None, title=\"\"):\n    if ax is None:\n        _, ax = plt.subplots()\n    fig = plt.gcf()\n        \n    img = ax.matshow(matrix, extent=(-0.5, matrix.shape[0] - 0.5, \n                                     -0.5, matrix.shape[1] - 0.5))\n\n    ax.xaxis.set_ticks_position(\"bottom\")\n    if labels_a is not None:\n        ax.set_xticks(range(len(labels_a)))\n        ax.set_xticklabels(labels_a, rotation=90)\n    if labels_b is not None:\n        ax.set_yticks(range(len(labels_b)))\n        ax.set_yticklabels(labels_b[::-1])  # Upper origin -> reverse y axis\n    ax.set_title(title)\n\n    cax = make_axes_locatable(ax).append_axes(\"right\", size=\"5%\", pad=0.15)\n    fig.colorbar(img, cax=cax, ticks=np.linspace(0.4, 1, 7))\n    img.set_clim(0.4, 1)\n    img.set_cmap(\"inferno\")\n    \n    return ax\n    \n    \ndef plot_histograms(all_samples, ax=None, names=None, title=\"\"):\n    \"\"\"\n    Plots (possibly) overlapping histograms and their median \n    \"\"\"\n    if ax is None:\n        _, ax = plt.subplots()\n    \n    for samples, color, name in zip(all_samples, _default_colors, names):\n        ax.hist(samples, density=True, color=color + \"80\", label=name)\n    ax.legend()\n    ax.set_xlim(0.35, 1)\n    ax.set_yticks([])\n    ax.set_title(title)\n        \n    ylim = ax.get_ylim()\n    ax.set_ylim(*ylim)      # Yeah, I know\n    for samples, color in zip(all_samples, _default_colors):\n        median = np.median(samples)\n        ax.vlines(median, *ylim, color, \"dashed\")\n        ax.text(median, ylim[1] * 0.15, \"median\", rotation=270, color=color)\n    \n    return ax\n\n\ndef plot_projections(embeds, speakers, ax=None, colors=None, markers=None, legend=True, \n                     title=\"\", cluster_name=\"\", labels=None, **kwargs):\n    if ax is None:\n        _, ax = plt.subplots(figsize=(6, 6))\n        \n    if cluster_name == 'spectral':\n        reducer = TSNE(init='pca', **kwargs)\n    if cluster_name == 'umap_hdbscan':\n        reducer = UMAP(**kwargs)\n    \n    # Compute the 2D projections. You could also project to another number of dimensions (e.g. \n    # for a 3D plot) or use a different different dimensionality reduction like PCA or TSNE.\n    \n    projs = reducer.fit_transform(embeds)\n    \n    # Draw the projections\n    speakers = np.array(speakers)\n    colors = generate_colors(len(np.unique(speakers)))\n    colors = colors or _my_colors\n    for i, speaker in enumerate(np.unique(speakers)):\n        speaker_projs = projs[speakers == speaker]\n        marker = \"o\" if markers is None else markers[i]\n        label = speaker if legend else None\n        ax.scatter(*speaker_projs.T, s=60, c=[colors[i]], marker=marker, label=label, edgecolors='k')\n        if labels is not None:\n            for j, (proj_x, proj_y) in enumerate(speaker_projs):\n                label_index = np.where(speakers == speaker)[0][j]\n                ax.text(proj_x, proj_y, str(labels[label_index]), fontsize=8, ha='right')\n        center = speaker_projs.mean(axis=0)\n        ax.scatter(*center, s=200, c=[colors[i]], marker=\"X\", edgecolors='k')\n\n        \n    if legend:\n        ax.legend(title=\"Speakers\", ncol=2)\n    ax.set_title(title)\n    #ax.set_xticks([])\n    #ax.set_yticks([])\n    ax.grid(True)\n    ax.set_aspect(\"equal\")\n    \n    return projs\n\n\ndef interactive_diarization(similarity_dict, wav, wav_splits, x_crop=5, show_time=False):\n    fig, ax = plt.subplots()\n    lines = [ax.plot([], [], label=name)[0] for name in similarity_dict.keys()]\n    text = ax.text(0, 0, \"\", fontsize=10)\n    \n    def init():\n        ax.set_ylim(0.4, 1)\n        ax.set_ylabel(\"Similarity\")\n        if show_time:\n            ax.set_xlabel(\"Time (seconds)\")\n        else:\n            ax.set_xticks([])\n        ax.set_title(\"Diarization\")\n        ax.legend(loc=\"lower right\")\n        return lines + [text]\n    \n    times = [((s.start + s.stop) / 2) / sampling_rate for s in wav_splits]\n    rate = 1 / (times[1] - times[0])\n    crop_range = int(np.round(x_crop * rate))\n    ticks = np.arange(0, len(wav_splits), rate)\n    ref_time = timer()\n    \n    def update(i):\n        # Crop plot\n        crop = (max(i - crop_range // 2, 0), i + crop_range // 2)\n        ax.set_xlim(i - crop_range // 2, crop[1])\n        if show_time:\n            crop_ticks = ticks[(crop[0] <= ticks) * (ticks <= crop[1])]\n            ax.set_xticks(crop_ticks)\n            ax.set_xticklabels(np.round(crop_ticks / rate).astype(np.int))\n\n        # Plot the prediction\n        similarities = [s[i] for s in similarity_dict.values()]\n        best = np.argmax(similarities)\n        name, similarity = list(similarity_dict.keys())[best], similarities[best]\n        if similarity > 0.75:\n            message = \"Speaker: %s (confident)\" % name\n            color = _default_colors[best]\n        elif similarity > 0.65:\n            message = \"Speaker: %s (uncertain)\" % name\n            color = _default_colors[best]\n        else:\n            message = \"Unknown/No speaker\"\n            color = \"black\"\n        text.set_text(message)\n        text.set_c(color)\n        text.set_position((i, 0.96))\n        \n        # Plot data\n        for line, (name, similarities) in zip(lines, similarity_dict.items()):\n            line.set_data(range(crop[0], i + 1), similarities[crop[0]:i + 1])\n        \n        # Block to synchronize with the audio (interval is not reliable)\n        current_time = timer() - ref_time\n        if current_time < times[i]:\n            sleep(times[i] - current_time)\n        elif current_time - 0.2 > times[i]:\n            print(\"Animation is delayed further than 200ms!\", file=stderr)\n        return lines + [text]\n    \n    ani = FuncAnimation(fig, update, frames=len(wav_splits), init_func=init, blit=not show_time,\n                        repeat=False, interval=1)\n    play_wav(wav, blocking=False)\n    plt.show()\n\n\ndef plot_embedding_as_heatmap(embed, ax=None, title=\"\", shape=None, color_range=(0, 0.30)):\n    if ax is None:\n        _, ax = plt.subplots()\n    \n    if shape is None:\n        height = int(np.sqrt(len(embed)))\n        shape = (height, -1)\n    embed = embed.reshape(shape)\n    \n    cmap = cm.get_cmap()\n    mappable = ax.imshow(embed, cmap=cmap)\n    cbar = plt.colorbar(mappable, ax=ax, fraction=0.046, pad=0.04)\n    cbar.set_clim(*color_range)\n    \n    ax.set_xticks([]), ax.set_yticks([])\n    ax.set_title(title)\n\n\ndef process_json_file(file_path):\n    with open(file_path, 'r', encoding='utf-8') as file:\n        data = json.load(file)\n    merged_data = {}\n    for key, value in data.items():\n        if value not in merged_data:\n            merged_data[value] = []\n        merged_data[value].append(key)\n\n    result_str = [\"</PAD>\"]\n    for keys in merged_data.values():\n        result_str.append(','.join(keys))\n\n    return result_str\n"
  },
  {
    "path": "move_files.py",
    "content": "import os\nimport shutil\nimport pandas as pd\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--spk', type=str, help='Speaker name')\nparser.add_argument('--encoder', type=str, default='timbre', help='encoder type')\nargs = parser.parse_args()\n\n\nSpeaker_name = args.spk #Speaker name\nencoder_name = args.encoder\n \ndata = pd.read_csv(os.path.join('output', Speaker_name, f'clustered_files({encoder_name}).csv'))\n\nfor index, row in data.iterrows():\n    file_path = row['filename']\n    clust = row['clust']\n\n    clust_dir = os.path.join('output', Speaker_name, str(clust))\n    if not os.path.exists(clust_dir):\n        os.makedirs(clust_dir)\n\n    shutil.copy(file_path, clust_dir)\n"
  },
  {
    "path": "pretrain/wav2vec2-large-robust-12-ft-emotion-msp-dim/LICENSE",
    "content": "Attribution-NonCommercial-ShareAlike 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n    wiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More considerations\n     for the public:\n    wiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution-NonCommercial-ShareAlike 4.0 International\nPublic License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution-NonCommercial-ShareAlike 4.0 International Public License\n(\"Public License\"). To the extent this Public License may be\ninterpreted as a contract, You are granted the Licensed Rights in\nconsideration of Your acceptance of these terms and conditions, and the\nLicensor grants You such rights in consideration of benefits the\nLicensor receives from making the Licensed Material available under\nthese terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. BY-NC-SA Compatible License means a license listed at\n     creativecommons.org/compatiblelicenses, approved by Creative\n     Commons as essentially the equivalent of this Public License.\n\n  d. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n\n  e. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  f. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  g. License Elements means the license attributes listed in the name\n     of a Creative Commons Public License. The License Elements of this\n     Public License are Attribution, NonCommercial, and ShareAlike.\n\n  h. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  i. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  j. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  k. NonCommercial means not primarily intended for or directed towards\n     commercial advantage or monetary compensation. For purposes of\n     this Public License, the exchange of the Licensed Material for\n     other material subject to Copyright and Similar Rights by digital\n     file-sharing or similar means is NonCommercial provided there is\n     no payment of monetary compensation in connection with the\n     exchange.\n\n  l. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  m. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  n. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part, for NonCommercial purposes only; and\n\n            b. produce, reproduce, and Share Adapted Material for\n               NonCommercial purposes only.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. Additional offer from the Licensor -- Adapted Material.\n               Every recipient of Adapted Material from You\n               automatically receives an offer from the Licensor to\n               exercise the Licensed Rights in the Adapted Material\n               under the conditions of the Adapter's License You apply.\n\n            c. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties, including when\n          the Licensed Material is used other than for NonCommercial\n          purposes.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n  b. ShareAlike.\n\n     In addition to the conditions in Section 3(a), if You Share\n     Adapted Material You produce, the following conditions also apply.\n\n       1. The Adapter's License You apply must be a Creative Commons\n          license with the same License Elements, this version or\n          later, or a BY-NC-SA Compatible License.\n\n       2. You must include the text of, or the URI or hyperlink to, the\n          Adapter's License You apply. You may satisfy this condition\n          in any reasonable manner based on the medium, means, and\n          context in which You Share Adapted Material.\n\n       3. You may not offer or impose any additional or different terms\n          or conditions on, or apply any Effective Technological\n          Measures to, Adapted Material that restrict exercise of the\n          rights granted under the Adapter's License You apply.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database for NonCommercial purposes\n     only;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material,\n     including for purposes of Section 3(b); and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n=======================================================================\n\nCreative Commons is not a party to its public\nlicenses. Notwithstanding, Creative Commons may elect to apply one of\nits public licenses to material it publishes and in those instances\nwill be considered the “Licensor.” The text of the Creative Commons\npublic licenses is dedicated to the public domain under the CC0 Public\nDomain Dedication. Except for the limited purpose of indicating that\nmaterial is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the\npublic licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n\n"
  },
  {
    "path": "pretrain/wav2vec2-large-robust-12-ft-emotion-msp-dim/config.json",
    "content": "{\n  \"_name_or_path\": \"torch\",\n  \"activation_dropout\": 0.1,\n  \"adapter_kernel_size\": 3,\n  \"adapter_stride\": 2,\n  \"add_adapter\": false,\n  \"apply_spec_augment\": true,\n  \"architectures\": [\n    \"Wav2Vec2ForSpeechClassification\"\n  ],\n  \"attention_dropout\": 0.1,\n  \"bos_token_id\": 1,\n  \"classifier_proj_size\": 256,\n  \"codevector_dim\": 768,\n  \"contrastive_logits_temperature\": 0.1,\n  \"conv_bias\": true,\n  \"conv_dim\": [\n    512,\n    512,\n    512,\n    512,\n    512,\n    512,\n    512\n  ],\n  \"conv_kernel\": [\n    10,\n    3,\n    3,\n    3,\n    3,\n    2,\n    2\n  ],\n  \"conv_stride\": [\n    5,\n    2,\n    2,\n    2,\n    2,\n    2,\n    2\n  ],\n  \"ctc_loss_reduction\": \"sum\",\n  \"ctc_zero_infinity\": false,\n  \"diversity_loss_weight\": 0.1,\n  \"do_stable_layer_norm\": true,\n  \"eos_token_id\": 2,\n  \"feat_extract_activation\": \"gelu\",\n  \"feat_extract_dropout\": 0.0,\n  \"feat_extract_norm\": \"layer\",\n  \"feat_proj_dropout\": 0.1,\n  \"feat_quantizer_dropout\": 0.0,\n  \"final_dropout\": 0.1,\n  \"finetuning_task\": \"wav2vec2_reg\",\n  \"gradient_checkpointing\": false,\n  \"hidden_act\": \"gelu\",\n  \"hidden_dropout\": 0.1,\n  \"hidden_dropout_prob\": 0.1,\n  \"hidden_size\": 1024,\n  \"id2label\": {\n    \"0\": \"arousal\",\n    \"1\": \"dominance\",\n    \"2\": \"valence\"\n  },\n  \"initializer_range\": 0.02,\n  \"intermediate_size\": 4096,\n  \"label2id\": {\n    \"arousal\": 0,\n    \"dominance\": 1,\n    \"valence\": 2\n  },\n  \"layer_norm_eps\": 1e-05,\n  \"layerdrop\": 0.1,\n  \"mask_feature_length\": 10,\n  \"mask_feature_min_masks\": 0,\n  \"mask_feature_prob\": 0.0,\n  \"mask_time_length\": 10,\n  \"mask_time_min_masks\": 2,\n  \"mask_time_prob\": 0.05,\n  \"model_type\": \"wav2vec2\",\n  \"num_adapter_layers\": 3,\n  \"num_attention_heads\": 16,\n  \"num_codevector_groups\": 2,\n  \"num_codevectors_per_group\": 320,\n  \"num_conv_pos_embedding_groups\": 16,\n  \"num_conv_pos_embeddings\": 128,\n  \"num_feat_extract_layers\": 7,\n  \"num_hidden_layers\": 12,\n  \"num_negatives\": 100,\n  \"output_hidden_size\": 1024,\n  \"pad_token_id\": 0,\n  \"pooling_mode\": \"mean\",\n  \"problem_type\": \"regression\",\n  \"proj_codevector_dim\": 768,\n  \"tdnn_dilation\": [\n    1,\n    2,\n    3,\n    1,\n    1\n  ],\n  \"tdnn_dim\": [\n    512,\n    512,\n    512,\n    512,\n    1500\n  ],\n  \"tdnn_kernel\": [\n    5,\n    3,\n    3,\n    1,\n    1\n  ],\n  \"torch_dtype\": \"float32\",\n  \"transformers_version\": \"4.17.0.dev0\",\n  \"use_weighted_layer_sum\": false,\n  \"vocab_size\": null,\n  \"xvector_output_dim\": 512\n}\n"
  },
  {
    "path": "pretrain/wav2vec2-large-robust-12-ft-emotion-msp-dim/preprocessor_config.json",
    "content": "{\n  \"do_normalize\": true,\n  \"feature_extractor_type\": \"Wav2Vec2FeatureExtractor\",\n  \"feature_size\": 1,\n  \"padding_side\": \"right\",\n  \"padding_value\": 0.0,\n  \"return_attention_mask\": true,\n  \"sampling_rate\": 16000\n}\n"
  },
  {
    "path": "pretrain/wav2vec2-large-robust-12-ft-emotion-msp-dim/vocab.json",
    "content": "{}"
  },
  {
    "path": "requirements.txt",
    "content": "torch\nmatplotlib>=3.0.0\nnumpy>=1.20.3\npandas\nResemblyzer\nscikit_learn\nsounddevice\ntqdm\numap_learn\nhdbscan\ntransformers\n"
  },
  {
    "path": "splitter.py",
    "content": "import pandas as pd\nfrom pathlib import Path\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom modules.utils import GetEmbeds\nfrom modules.visualizations import plot_projections\nfrom modules.cluster import CommonClustering\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--spk\", type=str, help=\"Speaker name\")\nparser.add_argument(\"--nmin\", type=int, default=1, help=\"minimum number of clusters\")\nparser.add_argument(\n    \"--cluster\", type=int, default=1, help=\"1:SpectralCluster, 2:UmapHdbscan\"\n)\nparser.add_argument(\"--mer_cosine\", type=str, default=None, help=\"merge similar embeds\")\nparser.add_argument(\"--encoder\", type=str, default=\"timbre\", help=\"encoder type\")\nargs = parser.parse_args()\n\nSpeaker_name = args.spk  # Speaker name\nNmin = args.nmin  # set Nmax values\nmerge_cos = args.mer_cosine\nencoder_name = args.encoder\n\ndata_dir = os.path.join(\"input\", Speaker_name, \"raw\", \"wavs\")\nwav_fpaths = list(Path(data_dir).glob(\"*.wav\"))\n\nencoder = GetEmbeds(encoder_type=encoder_name, Speaker_name=Speaker_name)\n\nembeds = encoder.__call__(wav_fpaths)\n\nwhile True:\n    if args.cluster == 1:\n        cluster_name = \"spectral\"\n        min_num_spks = Nmin\n        mer_cos = merge_cos\n        Cluster = CommonClustering(\n            cluster_type=cluster_name, mer_cos=None, min_num_spks=Nmin\n        )\n    elif args.cluster == 2:\n        cluster_name = \"umap_hdbscan\"\n        mer_cos = merge_cos\n        Cluster = CommonClustering(mer_cos=None, cluster_type=cluster_name)\n    else:\n        raise ValueError(\"cluster type error\")\n\n    labels = Cluster.__call__(embeds)\n\n    output_dir = f\"output/{Speaker_name}\"\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n\n    df = pd.DataFrame(\n        {\"filename\": [str(fpath) for fpath in wav_fpaths], \"clust\": labels}\n    )\n    proj = plot_projections(\n        embeds, labels, title=\"Embedding projections\", cluster_name=cluster_name\n    )\n    df[\"x\"] = proj[:, 0]\n    df[\"y\"] = proj[:, 1]\n\n    plt.savefig(f\"{output_dir}/embedding_projections({encoder_name}).png\", dpi=600)\n    plt.show()\n    df.to_csv(f\"{output_dir}/clustered_files({encoder_name}).csv\", index=False)\n\n    user_input = input(\"Are you satisfied with the results?/是否满意结果？(y/n): \")\n    if user_input.lower() == \"y\":\n        break\n    else:\n        Nmin = int(input(\"Please enter a new Nmin value/请输入新的Nmin值: \"))\n"
  },
  {
    "path": "viewer/.gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndist-ssr\n*.local\n\n# Editor directories and files\n.vscode/*\n!.vscode/extensions.json\n.idea\n.DS_Store\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?\n"
  },
  {
    "path": "viewer/README.md",
    "content": "# Cluster viewer\n\nAfter running Colour Splitter you would get a csv file. You can use this viewer to load this csv file, listen to each point in the scatter plot and interactively explore the cluster result.\n\n## Prerequisites\n\n- Bun (faster) or npm\n- Modern web browser\n\n## Build\n\n1. Navigate to the viewer directory:\n\n```bash\ncd viewer\n```\n\n2. Install dependencies:\n\n```bash\n# Using Bun\nbun install\n\n# Or using npm\nnpm install\n```\n\n## Serve\n\nYou'll need to run two servers simultaneously *in viewer directory*:\n\n1. Web Application Server\n\n```bash\n# Using Bun\nbun run dev\n\n# Or using npm\nnpm run dev\n```\n\n2. Audio file server\n\n```bash\n# Using Bun\nbunx http-server --cors -p 8080\n\n# Or using npm\nnpx http-server --cors -p 8080\n```\n\n## Usage\n\n![screenshot](screenshot.png)\n\n1. Open your browser and navigate to the URL shown by the web application server (typically something like http://localhost:5173)\n2. Look for the tab titled \"Vite + React + TS\"\n3. Drag and drop your CSV file (generated by the color splitter) into the designated dropping area\n4. Explore your clusters and play audio samples by clicking on individual data points\n"
  },
  {
    "path": "viewer/eslint.config.js",
    "content": "import js from '@eslint/js'\nimport globals from 'globals'\nimport reactHooks from 'eslint-plugin-react-hooks'\nimport reactRefresh from 'eslint-plugin-react-refresh'\nimport tseslint from 'typescript-eslint'\n\nexport default tseslint.config(\n  { ignores: ['dist'] },\n  {\n    extends: [js.configs.recommended, ...tseslint.configs.recommended],\n    files: ['**/*.{ts,tsx}'],\n    languageOptions: {\n      ecmaVersion: 2020,\n      globals: globals.browser,\n    },\n    plugins: {\n      'react-hooks': reactHooks,\n      'react-refresh': reactRefresh,\n    },\n    rules: {\n      ...reactHooks.configs.recommended.rules,\n      'react-refresh/only-export-components': [\n        'warn',\n        { allowConstantExport: true },\n      ],\n    },\n  },\n)\n"
  },
  {
    "path": "viewer/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/vite.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite + React + TS</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "viewer/package.json",
    "content": "{\n  \"name\": \"viewer\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc -b && vite build\",\n    \"lint\": \"eslint .\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@tremor/react\": \"^3.18.7\",\n    \"autoprefixer\": \"^10.4.20\",\n    \"lucide-react\": \"^0.473.0\",\n    \"postcss\": \"^8.5.1\",\n    \"react\": \"^18.3.1\",\n    \"react-dom\": \"^18.3.1\",\n    \"recharts\": \"^2.15.0\",\n    \"tailwindcss\": \"^3.4.17\"\n  },\n  \"devDependencies\": {\n    \"@eslint/js\": \"^9.17.0\",\n    \"@types/react\": \"^18.3.18\",\n    \"@types/react-dom\": \"^18.3.5\",\n    \"@vitejs/plugin-react-swc\": \"^3.5.0\",\n    \"eslint\": \"^9.17.0\",\n    \"eslint-plugin-react-hooks\": \"^5.0.0\",\n    \"eslint-plugin-react-refresh\": \"^0.4.16\",\n    \"globals\": \"^15.14.0\",\n    \"typescript\": \"~5.6.2\",\n    \"typescript-eslint\": \"^8.18.2\",\n    \"vite\": \"^6.0.5\"\n  }\n}\n"
  },
  {
    "path": "viewer/postcss.config.js",
    "content": "export default {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n}\n"
  },
  {
    "path": "viewer/src/App.tsx",
    "content": "import AudioVisualizer from \"./ScatterPlot\"\n\nfunction App() {\n  return (\n    <AudioVisualizer />\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "viewer/src/ScatterPlot.tsx",
    "content": "import React, { useState, useCallback } from 'react';\nimport { ScatterChart, Scatter, XAxis, YAxis, CartesianGrid } from 'recharts';\nimport { Play, Pause } from 'lucide-react';\n\ninterface DataPoint {\n    filename: string;\n    clust: number;\n    x: number;\n    y: number;\n}\n\n\nconst AudioVisualizer = () => {\n    const [data, setData] = useState<DataPoint[]>([]);\n    const [selectedFile, setSelectedFile] = useState<string | null>(null);\n\n\n    const [currentAudio, setCurrentAudio] = useState<{\n        file: string;\n        audio: HTMLAudioElement | null;\n        isPlaying: boolean;\n        progress: number;\n    } | null>(null);\n\n    const handlePlay = (filename: string) => {\n        if (currentAudio?.file === filename) {\n            // Resume/pause existing audio\n            if (currentAudio.isPlaying) {\n                currentAudio.audio?.pause();\n                setCurrentAudio(prev => prev ? { ...prev, isPlaying: false } : null);\n            } else {\n                currentAudio.audio?.play();\n                setCurrentAudio(prev => prev ? { ...prev, isPlaying: true } : null);\n            }\n        } else {\n            // Stop previous audio if any\n            currentAudio?.audio?.pause();\n\n            // Create new audio\n            const audio = new Audio(`http://localhost:8080/${filename}`);\n            audio.addEventListener('ended', () => {\n                setCurrentAudio(prev => prev ? { ...prev, isPlaying: false, progress: 0 } : null);\n            });\n            audio.play();\n            setCurrentAudio({\n                file: filename,\n                audio,\n                isPlaying: true,\n                progress: 0\n            });\n        }\n    };\n\n\n    const handleDragOver = useCallback((e: React.DragEvent) => {\n        e.preventDefault();\n    }, []);\n\n    const handleDrop = useCallback((e: React.DragEvent) => {\n        e.preventDefault();\n        const file = e.dataTransfer.files[0];\n        if (file && file.name.endsWith('.csv')) {\n            const reader = new FileReader();\n            reader.onload = (event) => {\n                const text = event.target?.result as string;\n                const lines = text.split('\\n');\n                const parsedData: DataPoint[] = lines.slice(1)\n                    .filter(line => line.trim())\n                    .map(line => {\n                        const values = line.split(',');\n                        return {\n                            filename: values[0],\n                            clust: parseInt(values[1], 10),\n                            x: parseFloat(values[2]),\n                            y: parseFloat(values[3])\n                        };\n                    });\n                setData(parsedData);\n            };\n            reader.readAsText(file);\n        }\n    }, []);\n\n    const handleClick = (point: DataPoint) => {\n        setSelectedFile(point.filename);\n    };\n\n    const handleReset = () => {\n        setSelectedFile(null);\n    };\n\n    const displayFiles = selectedFile ? data.filter(d => d.filename === selectedFile) : data;\n\n    return (\n        <div className=\"flex h-screen p-4 gap-4\">\n            <div className=\"flex-1\">\n                <div\n                    className=\"w-full h-32 border-2 border-dashed border-gray-300 rounded-lg mb-4 flex items-center justify-center bg-gray-50\"\n                    onDragOver={handleDragOver}\n                    onDrop={handleDrop}\n                >\n                    <p className=\"text-gray-500\">Drop CSV here</p>\n                </div>\n\n                {data.length > 0 && (\n                    <ScatterChart\n                        width={800}\n                        height={600}\n                        margin={{ top: 20, right: 20, bottom: 20, left: 20 }}\n                    >\n                        <CartesianGrid strokeDasharray=\"3 3\" />\n                        <XAxis type=\"number\" dataKey=\"x\" name=\"X\" />\n                        <YAxis type=\"number\" dataKey=\"y\" name=\"Y\" />\n                        {(() => {\n                            const maxCluster = Math.max(...data.map(d => d.clust));\n                            const numClusters = maxCluster + 1;  // Since clusters start from 0\n\n                            return Array.from(new Set(data.map(d => d.clust))).map((cluster) => {\n                                const hue = (360 / numClusters) * cluster;\n                                return (\n                                    <Scatter\n                                        key={cluster}\n                                        data={data.filter(d => d.clust === cluster)}\n                                        fill={`hsl(${hue}deg, 70%, 50%)`}\n                                        onClick={(point) => {\n                                            const p = point as unknown as DataPoint;\n                                            handleClick(p);\n                                            handlePlay(p.filename);\n                                        }}\n                                        cursor=\"pointer\"\n                                    />\n                                );\n                            });\n                        })()}\n                    </ScatterChart>\n                )}\n            </div>\n\n            <div className=\"w-96 border rounded-lg p-4 flex flex-col\">\n                <div className=\"flex justify-between items-center mb-4\">\n                    <h2 className=\"text-lg font-semibold\">Files</h2>\n                    <button\n                        onClick={handleReset}\n                        className=\"px-3 py-1 bg-gray-100 hover:bg-gray-200 rounded\"\n                    >\n                        Reset\n                    </button>\n                </div>\n                <div className=\"flex-1 overflow-auto\">\n                    {displayFiles.map((file, index) => (\n                        <div\n                            key={index}\n                            className={`p-2 text-sm ${file.filename === selectedFile ? 'bg-blue-100' : 'hover:bg-gray-50'\n                                }`}\n                        >\n                            <div className=\"flex items-center gap-2\">\n                                <button\n                                    onClick={() => handlePlay(file.filename)}\n                                    className=\"p-1 hover:bg-gray-200 rounded\"\n                                >\n                                    {currentAudio?.file === file.filename && currentAudio.isPlaying ?\n                                        <Pause className=\"w-4 h-4\" /> :\n                                        <Play className=\"w-4 h-4\" />\n                                    }\n                                </button>\n                                <span>{file.filename.split('/').pop()}</span>\n                            </div>\n                        </div>\n                    ))}\n                </div>\n            </div>\n        </div>\n    );\n};\n\nexport default AudioVisualizer;"
  },
  {
    "path": "viewer/src/index.css",
    "content": "@tailwind base;\n@tailwind components;\n@tailwind utilities;"
  },
  {
    "path": "viewer/src/main.tsx",
    "content": "import { StrictMode } from 'react'\nimport { createRoot } from 'react-dom/client'\nimport './index.css'\nimport App from './App.tsx'\n\ncreateRoot(document.getElementById('root')!).render(\n  <StrictMode>\n    <App />\n  </StrictMode>,\n)\n"
  },
  {
    "path": "viewer/src/vite-env.d.ts",
    "content": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "viewer/tailwind.config.js",
    "content": "/** @type {import('tailwindcss').Config} */\nexport default {\n  content: [\n    \"./index.html\",\n    \"./src/**/*.{js,ts,jsx,tsx}\",\n  ],\n  theme: {\n    extend: {},\n  },\n  plugins: [],\n}\n\n"
  },
  {
    "path": "viewer/tsconfig.app.json",
    "content": "{\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \"./node_modules/.tmp/tsconfig.app.tsbuildinfo\",\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"ESNext\",\n    \"skipLibCheck\": true,\n\n    /* Bundler mode */\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"isolatedModules\": true,\n    \"moduleDetection\": \"force\",\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n\n    /* Linting */\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noUncheckedSideEffectImports\": true\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "viewer/tsconfig.json",
    "content": "{\n  \"files\": [],\n  \"references\": [\n    { \"path\": \"./tsconfig.app.json\" },\n    { \"path\": \"./tsconfig.node.json\" }\n  ]\n}\n"
  },
  {
    "path": "viewer/tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \"./node_modules/.tmp/tsconfig.node.tsbuildinfo\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2023\"],\n    \"module\": \"ESNext\",\n    \"skipLibCheck\": true,\n\n    /* Bundler mode */\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"isolatedModules\": true,\n    \"moduleDetection\": \"force\",\n    \"noEmit\": true,\n\n    /* Linting */\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noUncheckedSideEffectImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n"
  },
  {
    "path": "viewer/vite.config.ts",
    "content": "import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react-swc'\n\n// https://vite.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n})\n"
  }
]