File size: 17,882 Bytes
cc1bad4
 
3392a2f
cc1bad4
 
 
 
 
 
8deac30
56588b0
9e72422
b98996a
d7205d9
06d6d0a
 
8911f9d
02214f9
04dd2d0
597e146
 
 
 
 
768647a
597e146
768647a
cc1bad4
 
 
 
 
 
782ddf5
 
 
 
 
 
 
 
 
cc1bad4
 
 
 
0afe578
91186c1
cc1bad4
0afe578
91186c1
cc1bad4
 
195c5f1
91186c1
cc1bad4
 
 
 
 
 
4cf7ea6
 
 
 
 
 
 
 
 
 
cc1bad4
4cf7ea6
7b3cbf2
4cf7ea6
 
 
782ddf5
4cf7ea6
7b3cbf2
f0797fe
4cf7ea6
 
f5cd731
 
4cf7ea6
f0797fe
4cf7ea6
e3b77c6
4cf7ea6
 
 
eb68364
 
4cf7ea6
 
 
 
 
eb68364
f0797fe
 
c57016e
f0797fe
06d6d0a
 
c25597c
 
e3b77c6
f0797fe
256d194
7b3cbf2
4cf7ea6
cc1bad4
4cf7ea6
 
 
 
 
 
 
597e146
651d68e
 
9c860eb
 
 
 
a840685
98a0325
9c860eb
 
 
a840685
933f493
a840685
4cf7ea6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3b99f7
d4253a5
 
 
 
9a62502
 
 
 
 
 
 
 
d4253a5
 
 
 
 
 
 
 
 
 
 
9a62502
 
 
 
 
80f55a4
 
 
 
9a62502
230f3ee
4cf7ea6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4d1ee5
4cf7ea6
 
 
 
 
 
 
 
 
 
 
95d3f6c
4cf7ea6
 
47b7e28
4cf7ea6
 
 
 
 
 
 
f5cd731
47b7e28
5b1f262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de373da
5b1f262
 
 
 
 
cc1bad4
 
 
0b400c4
 
 
 
 
cc1bad4
2ac0b62
3f9039f
cc1bad4
 
 
 
 
 
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import time
import streamlit as st
# from transformers import pipeline
import os
import torch
import datetime
import numpy as np
import soundfile
from wavmark.utils import file_reader
from audioseal import AudioSeal
import torchaudio
from pydub import AudioSegment
import io
import librosa
import ffmpeg

#from torchaudio.io import CodecConfig
# import numpy

# def my_read_file(audio_path, max_second):
#     signal, sr, audio_length_second = read_as_single_channel_16k(audio_path, default_sr)
#     if audio_length_second > max_second:
#         signal = signal[0:default_sr * max_second]
#         audio_length_second = max_second

#     return signal, sr, audio_length_second

def create_default_value():
    if "def_value" not in st.session_state:
        def_val_npy = np.random.choice([0, 1], size=32 - len_start_bit)
        def_val_str = "".join([str(i) for i in def_val_npy])
        st.session_state.def_value = def_val_str

def download_sample_audio():
    url = "https://keithito.com/LJ-Speech-Dataset/LJ037-0171.wav"
    with open("test.wav", "wb") as f:
        resp = urllib.request.urlopen(url)
        f.write(resp.read())
    
    wav, sample_rate = torchaudio.load("test.wav")
    return wav, sample_rate

# Main web app
def main():
    create_default_value()

    # st.title("MDS07 Demo Presentation")
    # st.write("https://github.com/ravindi-r/audioseal")
    markdown_text = """
    # MDS07 Demo Presentation
    [AudioSeal](https://github.com/ravindi-r/audioseal) is the next-generation watermarking tool driven by AI. 
    You can upload an audio file and encode a custom 16-bit watermark or perform decoding from a watermarked audio.
    
    This page is for demonstration usage. 
    If you have longer files for processing, we recommend using [our python toolkit](https://github.com/ravindi-r/audioseal).
    """

    # 使用st.markdown渲染Markdown文本
    st.markdown(markdown_text)

    audio_file = st.file_uploader("Upload Audio", type=["wav", "mp3"], accept_multiple_files=False)
    try:
        if audio_file:
            #2nd attempt
            # Save file to local storage
            tmp_input_audio_file = os.path.join("/tmp/", audio_file.name)
            file_extension = os.path.splitext(tmp_input_audio_file)[1].lower()
            #st.markdown(file_extension)
            if file_extension in [".wav", ".flac"]:
                with open("test.wav", "wb") as f:
                    f.write(audio_file.getbuffer())

                st.audio("test.wav", format="audio/wav")

            elif file_extension == ".mp3":
                with open("test.mp3", "wb") as f:
                    f.write(audio_file.getbuffer())

                st.audio("test.mp3", format="audio/mpeg")

        #Load the WAV file using torchaudio
            if file_extension in [".wav", ".flac"]: 
                wav, sample_rate = torchaudio.load("test.wav")
            # st.markdown("Before unsquueze wav")
            # st.markdown(wav)
                file_extension_ori =".wav"
            #Unsqueeze for line 176
                wav= wav.unsqueeze(0)
                
            elif file_extension == ".mp3":
                # Load an MP3 file
                audio = AudioSegment.from_mp3("test.mp3")

            # Export it as a WAV file
                audio.export("test.wav", format="wav")
                wav3, sample_rate = torchaudio.load("test.wav")
                wav= wav3.unsqueeze(0)
                file_extension_ori =".mp3"
                file_extension =".wav"

            #RuntimeError: Could not infer dtype of numpy.float32
            #wav = torch.tensor(wav3).float() / 32768.0
            
            #RuntimeError: Numpy is not available
            # wav = torch.from_numpy(wav3) #/32768.0
            # wav = wav.unsqueeze(0).unsqueeze(0)
            # st.markdown("Before unsqueeze mp3")
            # st.markdown(wav)
        
        #Unsqueeze for line 176
        # wav= wav.unsqueeze(0)

            action = st.selectbox("Select Action", ["Add Watermark", "Detect Watermark"])

            if action == "Add Watermark":
                #watermark_text = st.text_input("The watermark (0, 1 list of length-16):", value=st.session_state.def_value)
                add_watermark_button = st.button("Add Watermark", key="add_watermark_btn")
                if add_watermark_button:  # 点击按钮后执行的
                    #if audio_file and watermark_text:
                    if audio_file:
                        with st.spinner("Adding Watermark..."):
                        #wav = my_read_file(wav,max_second_encode)
                        
                        #1st attempt
                            watermark = model.get_watermark(wav, default_sr)
                            watermarked_audio = wav + watermark
                            print(watermarked_audio.size())
                            size = watermarked_audio.size()
                        #st.markdown(size)

                            print(watermarked_audio.squeeze())
                            squeeze = watermarked_audio.squeeze(1)
                            shape = squeeze.size()
                        #st.markdown(shape)

                        #st.markdown(squeeze)
                        if file_extension_ori in [".wav", ".flac"]:
                            torchaudio.save("output.wav", squeeze, default_sr, bits_per_sample=16)
                            watermarked_wav = torchaudio.save("output.wav", squeeze, default_sr, bits_per_sample=16)

                            st.audio("output.wav", format="audio/wav")

                            with open("output.wav", "rb") as file:
                                #file.read()
                                #file.write(watermarked_wav.getbuffer())
                                binary_data = file.read()
                                btn = st.download_button(
                                    label="Download watermarked audio",
                                    data=binary_data,
                                    file_name="output.wav",
                                    mime="audio/wav",
                                )


                        elif file_extension_ori == ".mp3":
                            torchaudio.save("output.wav", squeeze, default_sr)
                            watermarked_mp3 = torchaudio.save("output.wav", squeeze, default_sr)
                            audio = AudioSegment.from_wav("output.wav")

                            # Export as MP3
                            audio.export("output.mp3", format="mp3")
                            st.audio("output.mp3", format="audio/mpeg")
                        
                            with open("output.mp3", "rb") as file:
                                #file.write(watermarked_wav.getbuffer())
                                binary_data = file.read()
                                st.download_button(
                                    label="Download watermarked audio",
                                    data=binary_data,
                                    file_name="output.mp3",
                                    mime="audio/mpeg",
                                )
            elif action == "Detect Watermark":
                detect_watermark_button = st.button("Detect Watermark", key="detect_watermark_btn")                               
                if detect_watermark_button:
                    with st.spinner("Detecting..."):
                    # result, message = detector.detect_watermark(watermarked_audio, sample_rate=default_sr, message_threshold=0.5)
                    # st.markdown("Probability of audio being watermarked: ")
                    # st.markdown(result)
                    # st.markdown("This is likely a watermarked audio!")
                    # print(f"\nThis is likely a watermarked audio: {result}")

                    #Run on an unwatermarked audio

                        if file_extension in [".wav", ".flac"]: 
                            wav, sample_rate = torchaudio.load("test.wav")
                            wav= wav.unsqueeze(0)

                        elif file_extension == ".mp3":
                            # Load an MP3 file
                            audio = AudioSegment.from_mp3("test.mp3")
                            # Export it as a WAV file
                            audio.export("test.wav", format="wav")
                            wav, sample_rate = torchaudio.load("test.wav")
                            wav= wav.unsqueeze(0)
                        
                    result2, message2 = detector.detect_watermark(wav, sample_rate=default_sr, message_threshold=0.5)
                    print(f"This is likely an unwatermarked audio: {result2}")
                    st.markdown("Probability of audio being watermarked: ")
                    st.markdown(result2)
                    if result2 < 0.5:
                        st.markdown("This is likely an unwatermarked audio!")
                    else:
                        st.markdown("This is likely an watermarked audio!")

    except RuntimeError:
        st.error("Please input audio with one channel (mono-channel)")
        
    # if audio_file:
    #     # 保存文件到本地:
    #     # tmp_input_audio_file = os.path.join("/tmp/", audio_file.name)
    #     # st.markdown(tmp_input_audio_file)
    #     # with open(tmp_input_audio_file, "wb") as f:
    #     #     f.write(audio_file.getbuffer())
    #     # st.audio(tmp_input_audio_file, format="mp3/wav")


    #     #1st attempt
    #     #audio_path = " audio_file.name"

    #     # audio, sr = torchaudio.load(audio_file)
    #     # st.audio(audio_file, format="audio/mpeg")
    #     # audio= audio.unsqueeze(0)

    #     # st.markdown("SR")
    #     # st.markdown(sr)
    #     # st.markdown("after unsqueeze wav or mp3")
    #     # st.markdown(audio)
        
    #     #2nd attempt
    #     # Save file to local storage
    #     tmp_input_audio_file = os.path.join("/tmp/", audio_file.name)
    #     file_extension = os.path.splitext(tmp_input_audio_file)[1].lower()
    #     #st.markdown(file_extension)
    #     if file_extension in [".wav", ".flac"]:
    #         with open("test.wav", "wb") as f:
    #             f.write(audio_file.getbuffer())

    #         st.audio("test.wav", format="audio/wav")

    #     elif file_extension == ".mp3":
    #         with open("test.mp3", "wb") as f:
    #             f.write(audio_file.getbuffer())

    #         st.audio("test.mp3", format="audio/mpeg")

    #     #Load the WAV file using torchaudio
    #     if file_extension in [".wav", ".flac"]: 
    #         wav, sample_rate = torchaudio.load("test.wav")
    #         # st.markdown("Before unsquueze wav")
    #         # st.markdown(wav)
    #         file_extension_ori =".wav"
    #         #Unsqueeze for line 176
    #         wav= wav.unsqueeze(0)
                
    #     elif file_extension == ".mp3":
    #         # Load an MP3 file
    #         audio = AudioSegment.from_mp3("test.mp3")

    #         # Export it as a WAV file
    #         audio.export("test.wav", format="wav")
    #         wav3, sample_rate = torchaudio.load("test.wav")
    #         wav= wav3.unsqueeze(0)
    #         file_extension_ori =".mp3"
    #         file_extension =".wav"

    #         #RuntimeError: Could not infer dtype of numpy.float32
    #         #wav = torch.tensor(wav3).float() / 32768.0
            
    #         #RuntimeError: Numpy is not available
    #         # wav = torch.from_numpy(wav3) #/32768.0
    #         # wav = wav.unsqueeze(0).unsqueeze(0)
    #         # st.markdown("Before unsqueeze mp3")
    #         # st.markdown(wav)
        
    #     #Unsqueeze for line 176
    #     # wav= wav.unsqueeze(0)

    #     action = st.selectbox("Select Action", ["Add Watermark", "Detect Watermark"])

    #     if action == "Add Watermark":
    #         #watermark_text = st.text_input("The watermark (0, 1 list of length-16):", value=st.session_state.def_value)
    #         add_watermark_button = st.button("Add Watermark", key="add_watermark_btn")
    #         if add_watermark_button:  # 点击按钮后执行的
    #             #if audio_file and watermark_text:
    #             if audio_file:
    #                 with st.spinner("Adding Watermark..."):
    #                     #wav = my_read_file(wav,max_second_encode)
                        
    #                     #1st attempt
    #                     watermark = model.get_watermark(wav, default_sr)
    #                     watermarked_audio = wav + watermark
    #                     print(watermarked_audio.size())
    #                     size = watermarked_audio.size()
    #                     #st.markdown(size)

    #                     print(watermarked_audio.squeeze())
    #                     squeeze = watermarked_audio.squeeze(1)
    #                     shape = squeeze.size()
    #                     #st.markdown(shape)

    #                     #st.markdown(squeeze)
    #                 if file_extension_ori in [".wav", ".flac"]:
    #                     torchaudio.save("output.wav", squeeze, default_sr, bits_per_sample=16)
    #                     watermarked_wav = torchaudio.save("output.wav", squeeze, default_sr, bits_per_sample=16)

    #                     st.audio("output.wav", format="audio/wav")

    #                     with open("output.wav", "rb") as file:
    #                         #file.read()
    #                         #file.write(watermarked_wav.getbuffer())
    #                         binary_data = file.read()
    #                         btn = st.download_button(
    #                             label="Download watermarked audio",
    #                             data=binary_data,
    #                             file_name="output.wav",
    #                             mime="audio/wav",
    #                         )


    #                 elif file_extension_ori == ".mp3":
    #                     torchaudio.save("output.wav", squeeze, default_sr)
    #                     watermarked_mp3 = torchaudio.save("output.wav", squeeze, default_sr)
    #                     audio = AudioSegment.from_wav("output.wav")

    #                     # Export as MP3
    #                     audio.export("output.mp3", format="mp3")
    #                     st.audio("output.mp3", format="audio/mpeg")
                        
    #                     with open("output.mp3", "rb") as file:
    #                         #file.write(watermarked_wav.getbuffer())
    #                         binary_data = file.read()
    #                         st.download_button(
    #                             label="Download watermarked audio",
    #                             data=binary_data,
    #                             file_name="output.mp3",
    #                             mime="audio/mpeg",
    #                         )
    #                 # except RuntimeError:
    #                 #     st.error("Please input audio with one channel (mono-channel)")
                                 
    #     elif action == "Detect Watermark":
    #         detect_watermark_button = st.button("Detect Watermark", key="detect_watermark_btn")

    #         # if audio_file:
    #         #     #1st attempt
    #         #     watermark = model.get_watermark(wav, default_sr)
    #         #     watermarked_audio = wav + watermark
    #         #     print(watermarked_audio.size())
    #         #     size = watermarked_audio.size()
    #         #     #st.markdown(size)

                
            # if detect_watermark_button:
            #     with st.spinner("Detecting..."):
            #         # result, message = detector.detect_watermark(watermarked_audio, sample_rate=default_sr, message_threshold=0.5)
            #         # st.markdown("Probability of audio being watermarked: ")
            #         # st.markdown(result)
            #         # st.markdown("This is likely a watermarked audio!")
            #         # print(f"\nThis is likely a watermarked audio: {result}")

            #         #Run on an unwatermarked audio

            #         if file_extension in [".wav", ".flac"]: 
            #             wav, sample_rate = torchaudio.load("test.wav")
            #             wav= wav.unsqueeze(0)

            #         elif file_extension == ".mp3":
            #             # Load an MP3 file
            #             audio = AudioSegment.from_mp3("test.mp3")
            #             # Export it as a WAV file
            #             audio.export("test.wav", format="wav")
            #             wav, sample_rate = torchaudio.load("test.wav")
            #             wav= wav.unsqueeze(0)
                        
            #         result2, message2 = detector.detect_watermark(wav, sample_rate=default_sr, message_threshold=0.5)
            #         print(f"This is likely an unwatermarked audio: {result2}")
            #         st.markdown("Probability of audio being watermarked: ")
            #         st.markdown(result2)
            #         st.markdown("This is likely an unwatermarked audio!")


if __name__ == "__main__":
    default_sr = 16000
    max_second_encode = 60
    max_second_decode = 30
    len_start_bit = 16
    device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    # model = wavmark.load_model().to(device)
    model = AudioSeal.load_generator("audioseal_wm_16bits")
    detector = AudioSeal.load_detector(("audioseal_detector_16bits"))
    main()

    # audio_path = "/Users/my/Library/Mobile Documents/com~apple~CloudDocs/CODE/PycharmProjects/4_语音水印/419_huggingface水印/WavMark/example.wav"

    # decoded_watermark, decode_cost = decode_watermark(audio_path)
    # print(decoded_watermark)