jackdewinter commited on
Commit
2ab2fba
·
1 Parent(s): 7032a30

Upload folder using huggingface_hub

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.github/workflows/update_space.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Python script
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+
12
+ steps:
13
+ - name: Checkout
14
+ uses: actions/checkout@v2
15
+
16
+ - name: Set up Python
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: '3.9'
20
+
21
+ - name: Install Gradio
22
+ run: python -m pip install gradio
23
+
24
+ - name: Log in to Hugging Face
25
+ run: python -c 'import huggingface_hub; huggingface_hub.login(token="${{ secrets.hf_token }}")'
26
+
27
+ - name: Deploy to Spaces
28
+ run: gradio deploy
.gitignore ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyc
5
+ *.pyo
6
+ *.pyd
7
+ .Python
8
+ db.sqlite3
9
+
10
+ # C extensions
11
+ *.so
12
+
13
+ # Distribution / packaging
14
+ .Python
15
+ env/
16
+ build/
17
+ develop-eggs/
18
+ dist/
19
+ downloads/
20
+ eggs/
21
+ .eggs/
22
+ lib/
23
+ lib64/
24
+ parts/
25
+ sdist/
26
+ var/
27
+ wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ *.manifest
35
+ *.spec
36
+
37
+ # Installer logs
38
+ pip-log.txt
39
+ pip-delete-this-directory.txt
40
+
41
+ # Unit test / coverage reports
42
+ htmlcov/
43
+ .tox/
44
+ .nox/
45
+ .coverage
46
+ .coverage.*
47
+ .cache
48
+ nosetests.xml
49
+ coverage.xml
50
+ *.cover
51
+ *.py,cover
52
+ .hypothesis/
53
+ .pytest_cache/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # IPython Notebook
60
+ .ipynb_checkpoints
61
+
62
+ # pyenv
63
+ .python-version
64
+
65
+ # dotenv
66
+ .env
67
+
68
+ # virtualenv
69
+ .venv
70
+ venv/
71
+ ENV/
72
+
73
+ # Pyre type checker
74
+ .pyre/
75
+
76
+ # Conda files
77
+ conda-meta/
78
+ .env/
79
+ conda_env*
80
+
81
+ # other
82
+ flagged/
83
+ .DS_Store
README.md CHANGED
@@ -1,12 +1,40 @@
1
  ---
2
- title: Lofi University
3
- emoji: 🌍
4
- colorFrom: yellow
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 3.45.2
8
- app_file: app.py
9
- pinned: false
10
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
1
  ---
2
+ title: Lofi_University
3
+ app_file: app.py
 
 
4
  sdk: gradio
5
  sdk_version: 3.45.2
 
 
6
  ---
7
+ Set up initial anaconda environment
8
+
9
+ ```
10
+ conda create --name lofi-uni python=3.9
11
+ ```
12
+
13
+ Activate created environment
14
+
15
+ ```
16
+ conda activate lofi-uni
17
+ ```
18
+
19
+ Install dependencies
20
+
21
+ ```
22
+ pip install -r requirements.txt
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ Running a model for the first time will take a while as the model needs to be
28
+ downloaded.
29
+
30
+ Run app
31
+
32
+ ```
33
+ python -m app
34
+ ```
35
+
36
+ Run with public link
37
 
38
+ ```
39
+ python -m app --share
40
+ ```
__pycache__/app.cpython-39.pyc ADDED
Binary file (6.38 kB). View file
 
__pycache__/meta_demo.cpython-39.pyc ADDED
Binary file (14.5 kB). View file
 
app.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from concurrent.futures import ProcessPoolExecutor
3
+ import time
4
+ import subprocess as sp
5
+ from pathlib import Path
6
+ import typing as tp
7
+ import warnings
8
+ from tempfile import NamedTemporaryFile
9
+ import gradio as gr
10
+ from audiocraft.data.audio import audio_write
11
+ from audiocraft.models import MusicGen
12
+
13
+ MODEL = None
14
+ INTERRUPTING = False
15
+
16
+ # We have to wrap subprocess call to clean a bit the log when using gr.make_waveform
17
+ _old_call = sp.call
18
+
19
+
20
+ def _call_nostderr(*args, **kwargs):
21
+ # Avoid ffmpeg vomiting on the logs.
22
+ kwargs['stderr'] = sp.DEVNULL
23
+ kwargs['stdout'] = sp.DEVNULL
24
+ _old_call(*args, **kwargs)
25
+
26
+
27
+ sp.call = _call_nostderr
28
+ # Preallocating the pool of processes.
29
+ pool = ProcessPoolExecutor(4)
30
+ pool.__enter__()
31
+
32
+ def interrupt():
33
+ global INTERRUPTING
34
+ INTERRUPTING = True
35
+
36
+ class FileCleaner:
37
+ def __init__(self, file_lifetime: float = 3600):
38
+ self.file_lifetime = file_lifetime
39
+ self.files = []
40
+
41
+ def add(self, path: tp.Union[str, Path]):
42
+ self._cleanup()
43
+ self.files.append((time.time(), Path(path)))
44
+
45
+ def _cleanup(self):
46
+ now = time.time()
47
+ for time_added, path in list(self.files):
48
+ if now - time_added > self.file_lifetime:
49
+ if path.exists():
50
+ path.unlink()
51
+ self.files.pop(0)
52
+ else:
53
+ break
54
+
55
+
56
+ file_cleaner = FileCleaner()
57
+
58
+ def make_waveform(*args, **kwargs):
59
+ # Further remove some warnings.
60
+ waveform_start = time.time()
61
+ with warnings.catch_warnings():
62
+ warnings.simplefilter('ignore')
63
+ out = gr.make_waveform(*args, **kwargs)
64
+ print("Make a video took", time.time() - waveform_start)
65
+ return out
66
+
67
+ def load_model(version='facebook/musicgen-medium'):
68
+ global MODEL
69
+ print("Loading model", version)
70
+ if MODEL is None or MODEL.name != version:
71
+ MODEL = MusicGen.get_pretrained(version)
72
+
73
+ def _do_predictions(texts, duration, progress=False, **gen_kwargs):
74
+ MODEL.set_generation_params(duration=duration, **gen_kwargs)
75
+ generate_start = time.time()
76
+ outputs = MODEL.generate(texts, progress=progress)
77
+ outputs = outputs.detach().cpu().float()
78
+ pending_videos = []
79
+ out_wavs = []
80
+ for output in outputs:
81
+ with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
82
+ audio_write(
83
+ file.name, output, MODEL.sample_rate, strategy="loudness",
84
+ loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)
85
+ pending_videos.append(pool.submit(make_waveform, file.name))
86
+ out_wavs.append(file.name)
87
+ file_cleaner.add(file.name)
88
+ out_videos = [pending_video.result() for pending_video in pending_videos]
89
+ for video in out_videos:
90
+ file_cleaner.add(video)
91
+ print("generation took", time.time() - generate_start)
92
+ print("Tempfiles currently stored: ", len(file_cleaner.files))
93
+ return out_videos, out_wavs
94
+
95
+ def predict_full(model, text, duration, bpm, topk, topp, temperature, cfg_coef, progress=gr.Progress()):
96
+
97
+ text = "lofi " + text + " bpm: " + str(bpm)
98
+
99
+ global INTERRUPTING
100
+ INTERRUPTING = False
101
+ if temperature < 0:
102
+ raise gr.Error("Temperature must be >= 0.")
103
+ if topk < 0:
104
+ raise gr.Error("Topk must be non-negative.")
105
+ if topp < 0:
106
+ raise gr.Error("Topp must be non-negative.")
107
+
108
+ topk = int(topk)
109
+ load_model(model)
110
+
111
+ def _progress(generated, to_generate):
112
+ progress((min(generated, to_generate), to_generate))
113
+ if INTERRUPTING:
114
+ raise gr.Error("Interrupted.")
115
+ MODEL.set_custom_progress_callback(_progress)
116
+
117
+ videos, wavs = _do_predictions(
118
+ [text], duration, progress=True,
119
+ top_k=topk, top_p=topp, temperature=temperature, cfg_coef=cfg_coef)
120
+
121
+ return videos[0], wavs[0], None, None
122
+
123
+ def ui(launch_kwargs):
124
+ with gr.Blocks() as interface:
125
+ gr.Markdown(
126
+ """
127
+ # Lofi University
128
+ Generate lofi tracks to help study.
129
+ """
130
+ )
131
+ with gr.Row():
132
+ with gr.Column():
133
+ with gr.Row():
134
+ text = gr.Text(label="Describe your lofi", interactive=True)
135
+ with gr.Row():
136
+ submit = gr.Button("Submit")
137
+ _ = gr.Button("Interrupt").click(fn=interrupt, queue=False)
138
+ with gr.Row():
139
+ model = gr.Radio(["facebook/musicgen-medium", "facebook/musicgen-small",
140
+ "facebook/musicgen-large"],
141
+ label="Model", value="facebook/musicgen-medium", interactive=True)
142
+ with gr.Row():
143
+ bpm = gr.Slider(minimum=50, maximum=150, value=80, label="BPM", interactive=True)
144
+ with gr.Row():
145
+ duration = gr.Slider(minimum=1, maximum=120, value=10, label="Duration", interactive=True)
146
+ with gr.Row():
147
+ topk = gr.Number(label="Top-k", value=250, interactive=True)
148
+ topp = gr.Number(label="Top-p", value=0, interactive=True)
149
+ temperature = gr.Number(label="Temperature", value=1.0, interactive=True)
150
+ cfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)
151
+ with gr.Column():
152
+ output = gr.Video(label="Generated Music")
153
+ audio_output = gr.Audio(label="Generated Music (wav)", type='filepath')
154
+
155
+ submit.click(predict_full, inputs=[model, text, duration, bpm, topk, topp, temperature, cfg_coef], outputs=[output, audio_output])
156
+
157
+ gr.Examples(
158
+ fn=predict_full,
159
+ examples=[
160
+ [
161
+ "Dreamy synth layers with light beats",
162
+ "facebook/musicgen-medium",
163
+ ],
164
+ [
165
+ "Mellow piano chords are accompanied by a subtle, relaxed drum loop",
166
+ "facebook/musicgen-medium",
167
+ ],
168
+ ],
169
+ inputs=[text, model],
170
+ outputs=[output]
171
+ )
172
+ interface.queue().launch(**launch_kwargs)
173
+
174
+ if __name__ == "__main__":
175
+ parser = argparse.ArgumentParser()
176
+ parser.add_argument(
177
+ '--server_port',
178
+ type=int,
179
+ default=0,
180
+ help='Port to run the server listener on',
181
+ )
182
+ parser.add_argument(
183
+ '--inbrowser', action='store_true', help='Open in browser'
184
+ )
185
+ parser.add_argument(
186
+ '--share', action='store_true', help='Share the gradio UI'
187
+ )
188
+
189
+ args = parser.parse_args()
190
+
191
+ launch_kwargs = {}
192
+
193
+ if args.server_port:
194
+ launch_kwargs['server_port'] = args.server_port
195
+ if args.inbrowser:
196
+ launch_kwargs['inbrowser'] = args.inbrowser
197
+ if args.share:
198
+ launch_kwargs['share'] = args.share
199
+
200
+ ui(launch_kwargs)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch>=2.0
2
+ audiocraft
3
+ argparse