firagne commited on
Commit
1f67700
·
1 Parent(s): 3369f08

V1 florian

Browse files

unlock gradio

Files changed (2) hide show
  1. README.md +1 -1
  2. app.py +155 -74
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 🌍
4
  colorFrom: blue
5
  colorTo: red
6
  sdk: gradio
7
- sdk_version: 3.41.0
8
  app_file: app.py
9
  pinned: false
10
  python_version: 3.8
 
4
  colorFrom: blue
5
  colorTo: red
6
  sdk: gradio
7
+ sdk_version: 4.16.0
8
  app_file: app.py
9
  pinned: false
10
  python_version: 3.8
app.py CHANGED
@@ -8,118 +8,199 @@ import datetime
8
  from huggingface_hub import hf_hub_download
9
 
10
  # NO GPU
11
- os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
12
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
13
 
14
  max_results = 100
15
  max_output = 50
16
 
17
 
18
  # Cacher le nom du repo
19
- python_path = hf_hub_download(repo_id=os.environ['REPO_ID'], repo_type="space", filename=os.environ['MODEL_FILE'],
20
- use_auth_token=os.environ['TOKEN'])
 
 
 
 
21
  print(python_path)
22
- sys.path.append(os.environ['PRIVATE_DIR'])
23
  from models import *
 
24
  preprocess_model, model = get_models()
25
  url_dict = get_durl_myma()
26
  dict_catalog = get_dict_catalog()
27
- #audio_names = get_audio_names()
28
  audio_names = get_audio_names_pickle()
29
  index = get_index()
30
- #encoder_text = get_encoder_text() #Error ??
31
- encoder_text = tf.keras.models.load_model("encoder_text_retrievaltext_bmg_221022_54_clean")
 
 
 
32
 
33
  def process(prompt, lang):
34
  now = datetime.datetime.now()
35
-
36
  print()
37
- print('*************')
38
  print("Current Time: ", str(now))
39
  print("Text input : ", prompt)
40
- print('*************')
41
  print()
42
- a=time.time()
43
 
44
- embed_query = get_predict(encoder_text, prompt, preprocess_model, model)
45
  print("Embed time : ", time.time() - a)
46
  do_normalize(embed_query)
47
  D, I = get_distance(index, embed_query, max_output)
48
  print("Search + Embed time : ", time.time() - a)
49
-
50
- #print(I)
51
- #print(D)
52
- #print("----")
53
- #for i in range(len(I[0])):
54
  # print(audio_names[I[0][i]], " with distance ", D[0][i])
55
  # print(" url : ", get_url_myma(I[0][i], audio_names, url_dict))
56
 
57
- formated = []
58
  output_csv = f"prompt_{prompt}_results.csv"
59
- out = [output_csv]
60
-
61
  with open(output_csv, "w") as w:
62
  writer = csv.writer(w)
63
  header = False
64
- count = 0
65
- for top in I[0]:
66
- if count > max_output:
67
  break
68
-
69
- #formated.append(get_url_myma(top, audio_names, url_dict)
70
- #formated.append(audio_names[top].split('.')[0])
71
- file = os.path.splitext(os.path.basename(audio_names[top]))[0]
72
- try :
73
  if not header:
74
  writer.writerow(list(dict_catalog[file].keys()))
75
  header = True
76
  writer.writerow(dict_catalog[file].values())
77
- except KeyError:
78
  writer.writerow([file, "no metadata provided"])
79
- count += 1
80
 
81
- out.append(file)
82
- out.append(get_url_myma(top, audio_names, url_dict))
 
 
 
 
83
 
84
  print("Total time : ", time.time() - a)
85
- return out
86
-
87
- '''return [output_csv,
88
- audio_names[I[0][0]].split('.')[0], get_url_myma(I[0][0], audio_names, url_dict),
89
- '''
90
- inputs = [gr.Textbox(label="Input", value="type your description", max_lines=2),
91
- gr.Radio(label="Language", choices=["en"], value="en")]
92
-
93
- poc_examples = [
94
- ["Mysterious filmscore with Arabic influenced instruments","en"],
95
- ["Let's go on a magical adventure with wizzards, dragons and castles","en"],
96
- ["Creepy piano opening evolves and speeds up into a cinematic orchestral piece","en"],
97
- ["Chilled electronic","en"],
98
- #["","en"],
99
- ["Relax piano","en"],
100
- ["Halloween rock with creepy organ","en"],
101
- ["Rhythmic electro dance track for sport, motivation and sweating","en"],
102
- ["soundtrack for an action movie from the eighties in a retro synth wave style","en"],
103
- ["Choral female singing is rhythmically accompanied in a church with medieval instruments","en"],
104
- ["Christmas","en"],
105
- ["love romantic with piano, strings and vocals","en"],
106
- ["Electronic soundscapes for chilling and relaxing","en"],
107
- ["Minimal, emotional, melancholic piano","en"],
108
- ["A calm and romantic acoustic guitar melody","en"],
109
- ["horror suspense piano","en"],
110
- ["Big Band","en"],
111
- ["90 eurodance beat","en"],
112
- ]
113
-
114
- outputs = [gr.File(label="Results CSV file : ready for download", show_label=True)]
115
- for i in range(max_output):
116
- outputs.append(gr.Textbox(label=f"top{i+1} track name", show_label=True))
117
- outputs.append(gr.Audio(label=f"top{i+1}", show_label=False))
118
-
119
- '''outputs = [gr.File(),
120
- gr.Textbox(label="Track name 1"), gr.Audio(label="Track 1", show_label=False),
121
- '''
122
- demo1 = gr.Interface(fn=process, inputs=inputs, outputs=outputs, examples=poc_examples, cache_examples=False, examples_per_page=20)
123
-
124
- demo1.launch(debug=False)
125
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  from huggingface_hub import hf_hub_download
9
 
10
  # NO GPU
11
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
12
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
13
 
14
  max_results = 100
15
  max_output = 50
16
 
17
 
18
  # Cacher le nom du repo
19
+ python_path = hf_hub_download(
20
+ repo_id=os.environ["REPO_ID"],
21
+ repo_type="space",
22
+ filename=os.environ["MODEL_FILE"],
23
+ use_auth_token=os.environ["TOKEN"],
24
+ )
25
  print(python_path)
26
+ sys.path.append(os.environ["PRIVATE_DIR"])
27
  from models import *
28
+
29
  preprocess_model, model = get_models()
30
  url_dict = get_durl_myma()
31
  dict_catalog = get_dict_catalog()
32
+ # audio_names = get_audio_names()
33
  audio_names = get_audio_names_pickle()
34
  index = get_index()
35
+ # encoder_text = get_encoder_text() #Error ??
36
+ encoder_text = tf.keras.models.load_model(
37
+ "encoder_text_retrievaltext_bmg_221022_54_clean"
38
+ )
39
+
40
 
41
  def process(prompt, lang):
42
  now = datetime.datetime.now()
43
+
44
  print()
45
+ print("*************")
46
  print("Current Time: ", str(now))
47
  print("Text input : ", prompt)
48
+ print("*************")
49
  print()
50
+ a = time.time()
51
 
52
+ embed_query = get_predict(encoder_text, prompt, preprocess_model, model)
53
  print("Embed time : ", time.time() - a)
54
  do_normalize(embed_query)
55
  D, I = get_distance(index, embed_query, max_output)
56
  print("Search + Embed time : ", time.time() - a)
57
+
58
+ # print(I)
59
+ # print(D)
60
+ # print("----")
61
+ # for i in range(len(I[0])):
62
  # print(audio_names[I[0][i]], " with distance ", D[0][i])
63
  # print(" url : ", get_url_myma(I[0][i], audio_names, url_dict))
64
 
65
+ formated = [{"f": "Choose a result to play", "t": ""}]
66
  output_csv = f"prompt_{prompt}_results.csv"
 
 
67
  with open(output_csv, "w") as w:
68
  writer = csv.writer(w)
69
  header = False
70
+ for position, top in enumerate(I[0]):
71
+ if len(formated) / 2 >= max_output:
 
72
  break
73
+
74
+ file = os.path.splitext(os.path.basename(audio_names[top]))[0]
75
+ if file in dict_catalog:
 
 
76
  if not header:
77
  writer.writerow(list(dict_catalog[file].keys()))
78
  header = True
79
  writer.writerow(dict_catalog[file].values())
80
+ else:
81
  writer.writerow([file, "no metadata provided"])
 
82
 
83
+ formated.append(
84
+ {
85
+ "f": f"{position+1} - {file}",
86
+ "t": get_url_myma(top, audio_names, url_dict),
87
+ }
88
+ )
89
 
90
  print("Total time : ", time.time() - a)
91
+ return output_csv, formated
92
+
93
+ """return [output_csv,
94
+ audio_names[I[0][0]].split('.')[0], get_url_myma(I[0][0], audio_names, url_dict),
95
+ """
96
+
97
+
98
+ with gr.Blocks() as demo:
99
+ with gr.Row():
100
+ with gr.Column():
101
+ with gr.Row():
102
+ with gr.Column():
103
+ input_search = gr.Textbox(
104
+ label="Input", value="type your description", max_lines=2
105
+ )
106
+
107
+ input_search_lang = gr.Radio(
108
+ label="Language", choices=["en"], value="en"
109
+ )
110
+
111
+ analyze_btn = gr.Button("Search")
112
+
113
+ with gr.Column():
114
+ csv_results = gr.File(
115
+ label="Results CSV file : ready for download", show_label=True
116
+ )
117
+ results = gr.JSON(visible=False)
118
+ select_results = gr.Dropdown(label="Results", choices=[])
119
+ audio_player = gr.Audio(None, label="Results player")
120
+
121
+ @select_results.select(inputs=select_results, outputs=audio_player)
122
+ def change_audio(value):
123
+ if value:
124
+ return gr.Audio(value, label="Results player")
125
+ return gr.Audio(None, label="Results player")
126
+
127
+ @results.change(
128
+ inputs=results,
129
+ outputs=select_results,
130
+ )
131
+ def update_select(json_results):
132
+ try:
133
+ return gr.Dropdown(
134
+ label="Results",
135
+ choices=[(k["f"], k["t"]) for k in json_results],
136
+ value=None,
137
+ )
138
+ except:
139
+ return gr.Dropdown(
140
+ choices=[],
141
+ label="Results",
142
+ )
143
+
144
+ @input_search.change(
145
+ outputs=[results, select_results, csv_results, audio_player]
146
+ )
147
+ def cleanup_on_url():
148
+ print("cleanup on url change")
149
+ return (
150
+ gr.JSON([{"f": "Choose a result to play", "t": ""}], visible=False),
151
+ gr.Dropdown(choices=[], label="Results"),
152
+ gr.File(None, label="Results as CSV"),
153
+ gr.Audio(None, label="Results player"),
154
+ )
155
+
156
+ gr.Examples(
157
+ examples=[
158
+ ["Mysterious filmscore with Arabic influenced instruments", "en"],
159
+ [
160
+ "Let's go on a magical adventure with wizzards, dragons and castles",
161
+ "en",
162
+ ],
163
+ [
164
+ "Creepy piano opening evolves and speeds up into a cinematic orchestral piece",
165
+ "en",
166
+ ],
167
+ ["Chilled electronic", "en"],
168
+ # ["","en"],
169
+ ["Relax piano", "en"],
170
+ ["Halloween rock with creepy organ", "en"],
171
+ [
172
+ "Rhythmic electro dance track for sport, motivation and sweating",
173
+ "en",
174
+ ],
175
+ [
176
+ "soundtrack for an action movie from the eighties in a retro synth wave style",
177
+ "en",
178
+ ],
179
+ [
180
+ "Choral female singing is rhythmically accompanied in a church with medieval instruments",
181
+ "en",
182
+ ],
183
+ ["Christmas", "en"],
184
+ ["love romantic with piano, strings and vocals", "en"],
185
+ ["Electronic soundscapes for chilling and relaxing", "en"],
186
+ ["Minimal, emotional, melancholic piano", "en"],
187
+ ["A calm and romantic acoustic guitar melody", "en"],
188
+ ["horror suspense piano", "en"],
189
+ ["Big Band", "en"],
190
+ ["90 eurodance beat", "en"],
191
+ ],
192
+ inputs=[input_search, input_search_lang],
193
+ outputs=[csv_results, results],
194
+ cache_examples=False,
195
+ fn=process,
196
+ examples_per_page=20,
197
+ run_on_click=True,
198
+ )
199
+
200
+ analyze_btn.click(
201
+ process,
202
+ inputs=[input_search, input_search_lang],
203
+ outputs=[csv_results, results],
204
+ )
205
+
206
+ demo.launch(debug=False)