File size: 4,124 Bytes
3d59d93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58f5730
3d59d93
 
 
 
58f5730
3d59d93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
import asyncio
from enum import Enum
from io import BytesIO
import os
from pathlib import Path
import shutil
import sys
from typing import List
import uuid

pwd = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(pwd, "../"))

import edge_tts
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np

import streamlit as st
from streamlit_shortcuts import shortcut_button

from project_settings import project_path, temp_dir

# ENTRYPOINT ["streamlit", "run", "streamlit/nx_noise_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
# streamlit run streamlit/nx_noise_app.py --server.port=8501 --server.address=0.0.0.0


def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--src_dir",
        default=(project_path / "data/speech/en-PH/2025-01-14/2025-01-14").as_posix(),
        type=str
    )
    parser.add_argument(
        "--tgt_dir",
        default=(project_path / "data/speech/en-PH/2025-01-14/2025-01-14/finished").as_posix(),
        type=str
    )
    args = parser.parse_args()
    return args


class Labels(Enum):
    noise = "noise"
    noisy = "noisy"


async def edge_tts_text_to_speech(text: str, speaker: str = "zh-CN-XiaoxiaoNeural"):
    communicate = edge_tts.Communicate(text, speaker)

    audio_file = temp_dir / f"{uuid.uuid4()}.wav"
    audio_file = audio_file.as_posix()

    await communicate.save(audio_file)
    return audio_file


def generate_spectrogram(filename: str, title: str = "Spectrogram"):
    signal, sample_rate = librosa.load(filename, sr=None)

    mag = np.abs(librosa.stft(signal))
    # mag_db = librosa.amplitude_to_db(mag, ref=np.max)
    mag_db = librosa.amplitude_to_db(mag, ref=20)

    plt.figure(figsize=(10, 4))
    librosa.display.specshow(mag_db, sr=sample_rate)
    plt.title(title)

    buf = BytesIO()
    plt.savefig(buf, format="png", bbox_inches="tight")
    plt.close()
    buf.seek(0)
    return buf


def when_click_annotation_button(filename: Path, label: str, tgt_dir: Path):
    sub_tgt_dir = tgt_dir / label
    sub_tgt_dir.mkdir(parents=True, exist_ok=True)
    shutil.move(filename.as_posix(), sub_tgt_dir)


def main():
    args = get_args()

    src_dir = Path(args.src_dir)
    tgt_dir = Path(args.tgt_dir)

    # @st.cache_data
    # def get_shortcut_audio():
    #     result = {
    #         Labels.noise.value: asyncio.run(edge_tts_text_to_speech("噪音")),
    #         Labels.noisy.value: asyncio.run(edge_tts_text_to_speech("加噪语音")),
    #     }
    #     return result
    #
    # shortcut_audio = get_shortcut_audio()

    # 获取文件列表
    audio_files: List[Path] = [filename for filename in src_dir.glob("**/*.wav")]
    if len(audio_files) == 0:
        st.error("没有未标注的音频了。")
        st.stop()

    audio_file: Path = audio_files[0]

    # session_state
    if "play_audio" not in st.session_state:
        st.session_state.play_audio = False

    # ui
    st.title("🔊 音频文件浏览器")

    column1, column2 = st.columns([4, 1])
    with column1:
        st.audio(audio_file, format=f"{audio_file.suffix}", autoplay=True)

        with st.spinner("生成频谱图中..."):
            spectrogram = generate_spectrogram(audio_file)
        st.image(spectrogram, use_container_width=True)

    with column2:
        shortcut_button(
            label=Labels.noise.value,
            shortcut="1",
            on_click=when_click_annotation_button,
            kwargs={
                "filename": audio_file,
                "label": Labels.noise.value,
                "tgt_dir": tgt_dir,
            },
            type="primary",
        )
        shortcut_button(
            shortcut="2",
            label=Labels.noisy.value,
            on_click=when_click_annotation_button,
            kwargs={
                "filename": audio_file,
                "label": Labels.noisy.value,
                "tgt_dir": tgt_dir,
            },
            type="primary",
        )

    return


if __name__ == "__main__":
    main()