File size: 12,021 Bytes
eaef376
 
 
 
 
9451c98
eaef376
9451c98
c9f7614
eaef376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9451c98
eaef376
 
 
 
 
 
 
 
3d5ca20
eaef376
1d5a327
eaef376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62bb70d
 
 
eaef376
 
9451c98
 
eaef376
 
9451c98
eaef376
62bb70d
eaef376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5708de0
eaef376
 
 
 
 
 
609c9bd
eaef376
 
 
d74b2a8
 
 
 
eaef376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9451c98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eaef376
 
 
 
d74b2a8
 
eaef376
 
 
9451c98
eaef376
 
 
 
 
12a0eab
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
import gradio as gr
import re
import requests
import time
import tempfile
import os

token = os.environ['apikey']
API_HOST = "https://api.voicemod.net"
        


def separate_syllables(string):
    #numbers = [ 4, 4, 8, 5 ]
    numbers = [ 8, 9, 8, 9 ]
    # Split the string into a list of characters
    parts = string.split(" ")
    string = "".join(parts)
    print("the new string: "+ string)
    chars = list(string)

    # Create a list to store the syllables
    syllables = []

    # Iterate over the numbers
    for num in numbers:
        # Get the next num characters from the string
        syllable = "".join(chars[:num])
        print("Appending " + "".join(chars[:num]))
        # Add the syllable to the list
        syllables.append(syllable)
        # Remove the syllable from the list of characters
        chars = chars[num:]

    # If there are any remaining characters, add them as a new line
    if chars:
        syllables.append("-")
        for num in numbers:
            # Get the next num characters from the remaining characters
            syllable = "".join(chars[:num])
            # Add the syllable to the list
            syllables.append(syllable)
            # Remove the syllable from the list of characters
            chars = chars[num:]

    # Return the list of syllables joined by spaces
    if("-" in syllables): 
        results = [[]]
        lines = 0
        for i ,v in enumerate(syllables):
            if v == '-':
                lines=lines+1
            else: 
                if(len(results) == 1):
                    results.append([])
                results[lines].append(v)

        return list(map(lambda words: " ".join(words), results))
    else:
        return " ".join(syllables)


def flattenLines(lyrics):
    newValues = []
    for i,val in enumerate(lyrics): 
        if(type(lyrics[i]) == list):
            newValues.append(lyrics[i][0])
            newValues.append(lyrics[i][1])
        else:
            newValues.append(lyrics[i])

    return newValues

def getPayload(index):
    print("Getting payload for index: " + str(index))
    match index:
        case 0:
            return {
                "voiceModel":"CFV_2",
                "voiceModelStyle":"mezzo",
                "language":"en",
                "scoreFileRemotePath":"themes/DeckTheHalls/score/TTS_XMAS_DeckTheHalls_Melody_C_200bpm_4x4_ABCD.json",
                "scoreDataFileRemotePath":"themes/DeckTheHalls/score/TTS_XMAS_DeckTheHalls_Score_Data_ABCD.json",
                "dspFileRemotePath": "themes/DeckTheHalls/dsp/XML/TTS_XMAS_DeckTheHalls_DSP_C_200bpm_ABCD.xml",
                "lyrics": [],
                "dspEffect": "",
                "backgroundSounds":False,
                "artistName":"Cecilia",
                "songName":"Deck The Halls",
                "singerImageRemotePath":"singers/Singer-Cecilia-VideoImageBackground.png",
                "backgroundImageRemotePath":"themes/DeckTheHalls/images/Song-DeckTheHalls-VideoImageBackground02.png"
            }
        case 1:
            return {
                "voiceModel":"CFV_2",
                "voiceModelStyle":"mezzo",
                "language":"en",
                "scoreDataFileRemotePath": "themes/MoveYourBody/score/MoveYourBody_Score_Data_ABCD.json",
                "scoreFileRemotePath": "themes/MoveYourBody/score/MoveYourBody_Melody_ABCD.json",
                "singerImageRemotePath": "singers/Singer-Cecilia-VideoImageBackground.png",
                "dspFileRemotePath": "themes/MoveYourBody/dsp/XML/MoveYourBody_DSP_ABCD.xml",
                "dspEffect":"",
                "lyrics": [],
                "backgroundSounds":False,
                "artistName":"Cecilia",
                "songName":"Move Your Body",
                "backgroundImageRemotePath":"themes/DeckTheHalls/images/Song-DeckTheHalls-VideoImageBackground02.png"
            }
 
        case 2:
            return {
                "voiceModel": "Randy_v3o",
                "voiceModelStyle": "randy",
                "language": "en",
                "scoreFileRemotePath": "themes/DarkTrap/score/DarkTrap_Melody_ABCDEFGH.json", #"themes/DeckTheHalls/score/TTS_XMAS_DeckTheHalls_Melody_C_200bpm_4x4_ABCD.json",
                "scoreDataFileRemotePath": "themes/DarkTrap/score/DarkTrap_Score_Data_ABCDEFGH.json", #"themes/DeckTheHalls/score/TTS_XMAS_DeckTheHalls_Score_Data_ABCD.json",
                "dspFileRemotePath": "themes/DarkTrap/dsp/XML/DarkTrap_DSP_ABCDEFGH.xml", #"themes/DeckTheHalls/dsp/XML/TTS_XMAS_DeckTheHalls_DSP_C_200bpm_ABCD.xml",
                "dspEffect": "",
                "lyrics": [],
                "backgroundSounds": False,
                "artistName": "Jerry",
                "songName": "Dark Trap", #"Deck The Halls",
                "singerImageRemotePath": "singers/Singer-Jerry-VideoImageBackground.png",
                "backgroundImageRemotePath": "themes/DeckTheHalls/images/Song-DeckTheHalls-VideoImageBackground01.png"
            }

        case 3:
            return {
                "artistName": "Jerry",
                "backgroundImageRemotePath": "themes/HappyBirthday/images/Song-HappyBirthday-VideoImageBackground01.png",
                "backgroundSounds": False,
                "dspEffect": "",    
                "dspFileRemotePath": "themes/HappyBirthday/dsp/XML/HappyBirthday_DSP_ABCD.xml",
                "language": "en",
                "lyrics": [],
                "scoreDataFileRemotePath": "themes/HappyBirthday/score/HappyBirthday_Score_Data_ABCD.json",
                "scoreFileRemotePath": "themes/HappyBirthday/score/HappyBirthday_Melody_ABCD.json", 
                "singerImageRemotePath": "singers/Singer-Jerry-VideoImageBackground.png",
                "songName": "Happy Birthday",   
                "voiceModel": "CFV_2",
                "voiceModelStyle": "baritone"
            }
 
        case 4:
            return {
                "voiceModel": "Randy_v3o",
                "voiceModelStyle": "randy",
                "language": "en",
                "scoreFileRemotePath": "themes/Levitate/score/Levitate_Melody_ABCD.json", #"themes/DeckTheHalls/score/TTS_XMAS_DeckTheHalls_Melody_C_200bpm_4x4_ABCD.json",
                "scoreDataFileRemotePath": "themes/Levitate/score/Levitate_Score_Data_ABCD.json", #"themes/DeckTheHalls/score/TTS_XMAS_DeckTheHalls_Score_Data_ABCD.json",
                "dspFileRemotePath": "themes/Levitate/dsp/XML/Levitate_DSP_ABCD.xml", #"themes/DeckTheHalls/dsp/XML/TTS_XMAS_DeckTheHalls_DSP_C_200bpm_ABCD.xml",
                "dspEffect": "",
                "lyrics": [],
                "backgroundSounds": False,
                "artistName": "Jerry",
                "songName": "Levitate", #"Deck The Halls",
                "singerImageRemotePath": "singers/Singer-Ed-VideoImageBackground.png",
                "backgroundImageRemotePath": "themes/Levitate/images/Song-Levitate-VideoImageBackground02.png"
            }
 

def cleanUpLines(lines):
    return list(filter(None, lines))


def greet(index, lyrics):
    url = API_HOST + "/v2/cloud/partners/ttsing"
    verification_url = API_HOST + "/v2/cloud/partners/ttsing/"

    print("Calling api with "+ lyrics)
    print("URL: " + url)

    lines = cleanUpLines(lyrics.split("\n"))
    #newLines = flattenLines(list(map(separate_syllables, lines)))

    payload = getPayload(index)
    payload["lyrics"] = lines


    headers = {
        'x-api-key': token
    }


    print(payload)
    print("Before the call")
    response = requests.request("POST", url, headers=headers, json=payload)
    print("After the call...")
    jsonResp = response.json()
    print(response.text)
    jobID = jsonResp['jobId']
    verification_url += jsonResp['jobId']
    while(True):
        response = requests.request('GET', verification_url, headers=headers)
        print(response.text)
        print(jobID)
        jsonResp = response.json()
        if(jsonResp['status'] == 'failed'):
            return ""

        if('transformedAudioUrl' in jsonResp and jsonResp['transformedAudioUrl'] is not None):
            return gr.make_waveform(download_file(jsonResp['transformedAudioUrl']))
            #return download_file(jsonResp['urlVideoWithBackground'])
        print("Still processing...")
        time.sleep(1)




def download_file(url):
    response = requests.get(url)
    if response.status_code == 200:
        with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
            tmp_file.write(response.content)
            tmp_file.flush()
            return tmp_file.name
    else:
        print("Error: Unable to download file")


with gr.Blocks() as demo:
    #def handleChange():
    #    line3.update(visible=False)

    gr.Markdown("""
        ## Voicemod's Text-to-Sing API
        To use this API follow the instructions:
        1. First, select the melody you want from the dropdown
        2. Then write the lyrics for it

        ### Disclaimer
        Each melody has specific requirements for the lyrics (number of notes per verse and duration of each note).

        Use the examples provided to understand how they work and write valid lyrics to get best results

        Also, the length of the song is fixed, if you go over the line numbers the extra lyrics will be ignored.

        ## Join our Community
        If you'd like to know more and meet other developers working with this technology, join our [Discord Server](https://discord.gg/vm-dev-community)!
    
        """)

    music_options = ["Deck the Halls by Cecilia", 
                     "Move your Body by Cecilia",
                     "Dark Trap by Jerry",
                     "Happy Birthday by Jerry",
                     "Levitate by Ed"]

    with gr.Row():                
        with gr.Column():
            with gr.Row():
                dd = gr.Dropdown(choices=music_options, type="index", label="Select the melody...")
                lines = gr.Textbox(lines=10, placeholder="Write your lyrics here...", label="Lyrics")

            with gr.Row():
                btn = gr.Button("Run")
        with gr.Column():
            video = gr.Video(label="Generated output")
            video.style(height=300)
        
    gr.Markdown("""
    ## Example lyrics

    To make your life easier, while testing the API, you can use and modify the following lyrics for each song:
    """)

    gr.Examples(fn=greet, 
                examples=[["Move your Body by Cecilia", """this is just a test  
don’t worry now  
the lyrics will come the less you think about them  
just feel the melody"""
                ],
                ["Dark Trap by Jerry","""this is just a test  
don't worry about what I say  
the lyrics want to  go crazy  
when pushed too hard  
take it easy and relax  
this is moving too fast  
I can help you be  
a better singer""" 
                ],
                ["Happy Birthday by Jerry","""happy birthday to you   
happy birthday to you!   
happy birthday dear Laura  
happy birthday to you!"""]    ,
            ["Deck the Halls by Cecilia", """Deck the halls with boughs of holly  
Fa la la la la, la la la la   
'Tis the season to be jolly  
Fa la la la la, la la la la""" ],
            ["Levitate by Ed", """this is just a test  
don’t worry about what I say  
the lyrics want to go crazy  
when pushed too hard"""]

            ],
             inputs=[
                    dd,
                    lines
              ],
                outputs=video,
                cache_examples=True
    )


    gr.Markdown("""
        ## Want to use this API for your project?

        If you'd like to use this API for your own project, request access through our [form here](https://voicemod.typeform.com/to/KqeNN6bO?typeform-source=huggingface) and join
        our [Dev Community on Discord](https://discord.gg/vm-dev-community)!
    """)

    btn.click(fn=greet, 
             inputs=[
                    dd,
                    lines
              ],
                outputs=video)

demo.launch()