🎨 Redesign from AnyCoder

#11
by angeldove - opened
Files changed (1) hide show
  1. app.py +112 -279
app.py CHANGED
@@ -1,284 +1,117 @@
1
- import gradio as gr
2
- import json
3
- from datetime import datetime
4
- import yaml
5
- import time
6
- import re
7
  import os
8
- import os.path as op
9
- import torch
10
- import soundfile as sf
11
- import numpy as np
12
- import tempfile
13
-
14
- from download import download_model
15
-
16
- # 下载模型
17
- APP_DIR = op.dirname(op.abspath(__file__))
18
- download_model(APP_DIR)
19
- large_model_path = op.join(APP_DIR, "ckpt", "SongGeneration-v1.5-beta")
20
- download_model(large_model_path, repo_id="waytan22/SongGeneration-v1.5-beta", revision="db10f47")
21
- print("Successful downloaded model.")
22
-
23
- # 模型初始化
24
- from levo_inference import LeVoInference
25
- MODEL = LeVoInference(large_model_path)
26
-
27
- EXAMPLE_LYRICS = """
28
- [intro-medium]
29
-
30
- [verse]
31
- 夜晚的街灯闪烁
32
- 我漫步在熟悉的角落
33
- 回忆像潮水般涌来
34
- 你的笑容如此清晰
35
- 在心头无法抹去
36
- 那些曾经的甜蜜
37
- 如今只剩我独自回忆
38
-
39
- [chorus]
40
- 回忆的温度还在
41
- 你却已不在
42
- 我的心被爱填满
43
- 却又被思念刺痛
44
- 音乐的节奏奏响
45
- 我的心却在流浪
46
- 没有你的日子
47
- 我该如何继续向前
48
-
49
- [inst-medium]
50
-
51
- [verse]
52
- 手机屏幕亮起
53
- 是你发来的消息
54
- 简单的几个字
55
- 却让我泪流满面
56
- 曾经的拥抱温暖
57
- 如今却变得遥远
58
- 我多想回到从前
59
- 重新拥有你的陪伴
60
-
61
- [chorus]
62
- 回忆的温度还在
63
- 你却已不在
64
- 我的心被爱填满
65
- 却又被思念刺痛
66
- 音乐的节奏奏响
67
- 我的心却在流浪
68
- 没有你的日子
69
- 我该如何继续向前
70
-
71
- [outro-medium]
72
- """.strip()
73
-
74
- with open(op.join(APP_DIR, 'conf/vocab.yaml'), 'r', encoding='utf-8') as file:
75
- STRUCTS = yaml.safe_load(file)
76
-
77
-
78
- def save_as_flac(sample_rate, audio_data):
79
- if isinstance(audio_data, tuple):
80
- sample_rate, audio_data = audio_data
81
-
82
- if audio_data.dtype == np.float64:
83
- audio_data = audio_data.astype(np.float32)
84
-
85
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".flac")
86
- sf.write(temp_file, audio_data, sample_rate, format='FLAC')
87
- return temp_file.name
88
-
89
-
90
- # 模拟歌曲生成函数
91
- def generate_song(lyric, description=None, prompt_audio=None, genre=None, cfg_coef=None, temperature=0.1, top_k=-1, gen_type="mixed", progress=gr.Progress(track_tqdm=True)):
92
- global MODEL
93
- global STRUCTS
94
- params = {'cfg_coef':cfg_coef, 'temperature':temperature, 'top_k':top_k}
95
- params = {k:v for k,v in params.items() if v is not None}
96
- vocal_structs = ['[verse]', '[chorus]', '[bridge]']
97
- sample_rate = MODEL.cfg.sample_rate
98
-
99
- # format lyric
100
- lyric = lyric.replace("[intro]", "[intro-short]").replace("[inst]", "[inst-short]").replace("[outro]", "[outro-short]")
101
- paragraphs = [p.strip() for p in lyric.strip().split('\n\n') if p.strip()]
102
- if len(paragraphs) < 1:
103
- return None, json.dumps("Lyrics can not be left blank")
104
- paragraphs_norm = []
105
- vocal_flag = False
106
- for para in paragraphs:
107
- lines = para.splitlines()
108
- struct_tag = lines[0].strip().lower()
109
- if struct_tag not in STRUCTS:
110
- return None, json.dumps(f"Segments should start with a structure tag in {STRUCTS}")
111
- if struct_tag in vocal_structs:
112
- vocal_flag = True
113
- if len(lines) < 2 or not [line.strip() for line in lines[1:] if line.strip()]:
114
- return None, json.dumps("The following segments require lyrics: [verse], [chorus], [bridge]")
115
- else:
116
- new_para_list = []
117
- for line in lines[1:]:
118
- new_para_list.append(re.sub(r"[^\w\s\[\]\-\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af\u00c0-\u017f]", "", line))
119
- new_para_str = f"{struct_tag} {'.'.join(new_para_list)}"
120
- else:
121
- if len(lines) > 1:
122
- return None, json.dumps("The following segments should not contain lyrics: [intro], [intro-short], [intro-medium], [inst], [inst-short], [inst-medium], [outro], [outro-short], [outro-medium]")
123
- else:
124
- new_para_str = struct_tag
125
- paragraphs_norm.append(new_para_str)
126
- if not vocal_flag:
127
- return None, json.dumps(f"The lyric must contain at least one of the following structures: {vocal_structs}")
128
- lyric_norm = " ; ".join(paragraphs_norm)
129
-
130
- # format prompt
131
- if prompt_audio is not None:
132
- genre = None
133
- description = None
134
- elif description is not None and description != "":
135
- genre = None
136
-
137
- progress(0.0, "Start Generation")
138
- start = time.time()
139
-
140
- audio_data = MODEL(lyric_norm, description, prompt_audio, genre, op.join(APP_DIR, "tools/new_prompt.pt"), gen_type, params).cpu().permute(1, 0).float().numpy()
141
-
142
- end = time.time()
143
-
144
- # 创建输入配置的JSON
145
- input_config = {
146
- "lyric": lyric_norm,
147
- "genre": genre,
148
- "prompt_audio": prompt_audio,
149
- "description": description,
150
- "params": params,
151
- "inference_duration": end - start,
152
- "timestamp": datetime.now().isoformat(),
153
- }
154
-
155
- filepath = save_as_flac(sample_rate, audio_data)
156
- return filepath, json.dumps(input_config, indent=2)
157
-
158
-
159
- # 创建Gradio界面
160
- with gr.Blocks(title="SongGeneration Demo Space") as demo:
161
- gr.Markdown("# 🎵 SongGeneration Demo Space")
162
- gr.Markdown("Demo interface for the song generation model. Provide a lyrics, and optionally an audio or text prompt, to generate a custom song. The code is in [GIT](https://github.com/tencent-ailab/SongGeneration)")
163
-
164
- with gr.Row():
165
- with gr.Column():
166
- lyric = gr.Textbox(
167
- label="Lyrics",
168
- lines=5,
169
- max_lines=15,
170
- value=EXAMPLE_LYRICS,
171
- info="Each paragraph represents a segment starting with a structure tag and ending with a blank line, each line is a sentence without punctuation, segments [intro], [inst], [outro] should not contain lyrics, while [verse], [chorus], and [bridge] require lyrics.",
172
- placeholder="""Lyric Format
173
- '''
174
- [structure tag]
175
- lyrics
176
-
177
- [structure tag]
178
- lyrics
179
- '''
180
- 1. One paragraph represents one segments, starting with a structure tag and ending with a blank line
181
- 2. One line represents one sentence, punctuation is not recommended inside the sentence
182
- 3. The following segments should not contain lyrics: [intro-short], [intro-medium], [inst-short], [inst-medium], [outro-short], [outro-medium]
183
- 4. The following segments require lyrics: [verse], [chorus], [bridge]
184
  """
185
- )
186
 
187
- with gr.Tabs(elem_id="extra-tabs"):
188
- with gr.Tab("Genre Select"):
189
- genre = gr.Radio(
190
- choices=["Auto", "Pop", "R&B", "Dance", "Jazz", "Folk", "Rock", "Chinese Style", "Chinese Tradition", "Metal", "Reggae", "Chinese Opera"],
191
- label="Genre Select(Optional)",
192
- value="Auto",
193
- interactive=True,
194
- elem_id="single-select-radio"
195
- )
196
- with gr.Tab("Audio Prompt"):
197
- prompt_audio = gr.Audio(
198
- label="Prompt Audio (Optional)",
199
- type="filepath",
200
- elem_id="audio-prompt"
201
- )
202
- with gr.Tab("Text Prompt"):
203
- gr.Markdown("For detailed usage, please refer to [here](https://github.com/tencent-ailab/SongGeneration?tab=readme-ov-file#-description-input-format)")
204
- description = gr.Textbox(
205
- label="Song Description (Optional)",
206
- info="Describe the gender, timbre, genre, emotion, instrument and bpm of the song. Only English is supported currently.​",
207
- placeholder="female, dark, pop, sad, piano and drums, the bpm is 125.",
208
- lines=1,
209
- max_lines=2
210
- )
211
 
212
- with gr.Accordion("Advanced Config", open=False):
213
- cfg_coef = gr.Slider(
214
- label="CFG Coefficient",
215
- minimum=0.1,
216
- maximum=3.0,
217
- step=0.1,
218
- value=1.5,
219
- interactive=True,
220
- elem_id="cfg-coef",
221
- )
222
- temperature = gr.Slider(
223
- label="Temperature",
224
- minimum=0.1,
225
- maximum=2.0,
226
- step=0.1,
227
- value=0.8,
228
- interactive=True,
229
- elem_id="temperature",
230
- )
231
- # top_k = gr.Slider(
232
- # label="Top-K",
233
- # minimum=1,
234
- # maximum=100,
235
- # step=1,
236
- # value=50,
237
- # interactive=True,
238
- # elem_id="top_k",
239
- # )
240
- with gr.Row():
241
- generate_btn = gr.Button("Generate Song", variant="primary")
242
- generate_bgm_btn = gr.Button("Generate Pure Music", variant="primary")
243
-
244
- with gr.Column():
245
- output_audio = gr.Audio(label="Generated Song", type="filepath")
246
- output_json = gr.JSON(label="Generated Info")
247
-
248
- # # 示例按钮
249
- # examples = gr.Examples(
250
- # examples=[
251
- # ["male, bright, rock, happy, electric guitar and drums, the bpm is 150."],
252
- # ["female, warm, jazz, romantic, synthesizer and piano, the bpm is 100."]
253
- # ],
254
- # inputs=[description],
255
- # label="Text Prompt examples"
256
- # )
257
-
258
- # examples = gr.Examples(
259
- # examples=[
260
- # "[intro-medium]\n\n[verse]\n在这个疯狂的世界里\n谁不渴望一点改变\n在爱情面前\n我们都显得那么不安全\n你紧紧抱着我\n告诉我再靠近一点\n别让这璀璨的夜晚白白浪费\n我那迷茫的眼睛\n看不见未来的路\n在情感消散之前\n我们对爱的渴望永不熄灭\n你给我留下一句誓言\n想知道我们的爱是否能持续到永远\n[chorus]\n\n约定在那最后的夜晚\n不管命运如何摆布\n我们的心是否依然如初\n我会穿上红衬衫\n带着摇滚的激情\n回到我们初遇的地方\n约定在那最后的夜晚\n就算全世界都变了样\n我依然坚守诺言\n铭记这一天\n你永远是我心中的爱恋\n\n[outro-medium]\n",
261
- # "[intro-short]\n\n[verse]\nThrough emerald canyons where fireflies dwell\nCerulean berries kiss morning's first swell\nCrystalline dew crowns each Vitamin Dawn's confection dissolves slowly on me\nAmbrosia breezes through honeycomb vines\nNature's own candy in Fibonacci lines\n[chorus] Blueberry fruit so sweet\n takes you higher\n can't be beat\n In your lungs\n it starts to swell\n You're under its spell\n [verse] Resin of sunlight in candied retreat\nMarmalade moonbeams melt under bare feet\nNectar spirals bloom chloroplast champagne\nPhotosynthesis sings through my veins\nChlorophyll rhythms pulse warm in my blood\nThe forest's green pharmacy floods every bud[chorus] Blueberry fruit so sweet\n takes you higher\n can't be beat\n In your lungs\n it starts to swell\n You're under its spell\n feel the buzz\n ride the wave\n Limey me\n blueberry\n your mind's enslaved\n In the haze\n lose all time\n floating free\n feeling fine\n Blueberry\n fruit so sweet\n takes you higher\n can't be beat\n In your lungs\n it starts to swell\n cry\n You're under its spell\n\n[outro-short]\n",
262
- # ],
263
- # inputs=[lyric],
264
- # label="Lyrics examples",
265
- # )
266
-
267
- # 生成按钮点击事件
268
- generate_btn.click(
269
- fn=generate_song,
270
- inputs=[lyric, description, prompt_audio, genre, cfg_coef, temperature, gr.State(50)],
271
- outputs=[output_audio, output_json]
272
- )
273
- generate_bgm_btn.click(
274
- fn=generate_song,
275
- inputs=[lyric, description, prompt_audio, genre, cfg_coef, temperature, gr.State(50), gr.State("bgm")],
276
- outputs=[output_audio, output_json]
277
- )
278
-
279
-
280
- # 启动应用
281
  if __name__ == "__main__":
282
- torch.set_num_threads(1)
283
- demo.launch(server_name="0.0.0.0", server_port=7860)
284
-
 
 
 
 
 
 
 
 
1
  import os
2
+ from flask import Flask, render_template_string
3
+
4
+ app = Flask(__name__)
5
+
6
+ # HTML Template with embedded CSS for a clean look
7
+ HTML_TEMPLATE = """
8
+ <!DOCTYPE html>
9
+ <html lang="en">
10
+ <head>
11
+ <meta charset="UTF-8">
12
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
13
+ <title>Docker on Hugging Face Spaces</title>
14
+ <style>
15
+ body {
16
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
17
+ margin: 0;
18
+ padding: 0;
19
+ background-color: #f5f5f5;
20
+ color: #333;
21
+ display: flex;
22
+ flex-direction: column;
23
+ min-height: 100vh;
24
+ }
25
+ /* Header Styling */
26
+ header {
27
+ background-color: #fff;
28
+ padding: 1rem 2rem;
29
+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);
30
+ display: flex;
31
+ justify-content: flex-start;
32
+ align-items: center;
33
+ }
34
+ .brand-link {
35
+ text-decoration: none;
36
+ color: #007bff;
37
+ font-weight: 600;
38
+ font-size: 1rem;
39
+ transition: color 0.2s;
40
+ }
41
+ .brand-link:hover {
42
+ color: #0056b3;
43
+ text-decoration: underline;
44
+ }
45
+ /* Main Content Styling */
46
+ main {
47
+ flex: 1;
48
+ display: flex;
49
+ flex-direction: column;
50
+ align-items: center;
51
+ justify-content: center;
52
+ padding: 2rem;
53
+ text-align: center;
54
+ }
55
+ .card {
56
+ background: white;
57
+ padding: 3rem;
58
+ border-radius: 12px;
59
+ box-shadow: 0 4px 6px rgba(0,0,0,0.05);
60
+ max-width: 600px;
61
+ width: 100%;
62
+ }
63
+ h1 {
64
+ margin-top: 0;
65
+ color: #111;
66
+ }
67
+ p {
68
+ color: #666;
69
+ line-height: 1.6;
70
+ }
71
+ .status-badge {
72
+ display: inline-block;
73
+ margin-top: 1rem;
74
+ padding: 0.25rem 0.75rem;
75
+ background-color: #e6fffa;
76
+ color: #047481;
77
+ border-radius: 9999px;
78
+ font-size: 0.875rem;
79
+ font-weight: 500;
80
+ }
81
+ </style>
82
+ </head>
83
+ <body>
84
+
85
+ <!-- Header Section with Required Link -->
86
+ <header>
87
+ <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" class="brand-link">
88
+ Built with anycoder
89
+ </a>
90
+ </header>
91
+
92
+ <!-- Main Content -->
93
+ <main>
94
+ <div class="card">
95
+ <h1>Docker Space Running</h1>
96
+ <p>
97
+ Your containerized application is successfully running on Hugging Face Spaces.
98
+ This page is being served by a Flask application running inside a Docker container.
99
+ </p>
100
+ <div class="status-badge">● System Operational</div>
101
+ </div>
102
+ </main>
103
+
104
+ </body>
105
+ </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  """
 
107
 
108
+ @app.route("/")
109
+ def home():
110
+ """Render the main landing page."""
111
+ return render_template_string(HTML_TEMPLATE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  if __name__ == "__main__":
114
+ # Hugging Face Spaces expects the app to run on port 7860
115
+ # We bind to 0.0.0.0 to accept connections from outside the container
116
+ port = int(os.environ.get("PORT", 7860))
117
+ app.run(host="0.0.0.0", port=port)