File size: 21,358 Bytes
800ffef
4644579
 
 
 
 
dd9c7ae
 
 
 
 
 
 
 
 
800ffef
4644579
07e0495
4644579
 
4f18cef
4644579
 
 
 
 
 
 
 
 
 
07e0495
500d7f4
07e0495
 
 
4644579
 
 
 
 
 
 
 
 
089e4be
a833ae6
089e4be
 
 
07e0495
089e4be
 
 
4644579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d79b9b1
4644579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
089e4be
 
 
 
 
 
 
 
 
4644579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f18cef
4644579
 
4f18cef
4644579
 
 
1c4f5a9
4644579
 
 
bf7dff7
4644579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e563dec
4644579
 
 
 
 
 
 
 
 
 
 
4f18cef
4644579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31746c1
4644579
 
 
089e4be
 
07e0495
089e4be
 
 
bf7dff7
089e4be
31746c1
 
 
4644579
1ed8d0b
bf7dff7
 
 
 
 
4644579
5f6b497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07e0495
 
 
 
 
 
 
 
 
 
 
 
dd9c7ae
4644579
 
dd9c7ae
4644579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c4f5a9
 
 
 
 
 
 
 
 
 
 
 
 
4644579
 
 
 
 
 
 
089e4be
 
 
 
 
 
4644579
 
 
 
 
 
 
 
 
 
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
import gradio as gr
import whisper
from datetime import datetime
from PIL import Image
import flag
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import LabelEncoder
import seaborn as sns

plt.switch_backend('Agg')
pd.options.display.max_columns = 25
pd.options.display.max_rows = 300

stable_diffusion = gr.Blocks.load(name="spaces/stabilityai/stable-diffusion")
code_generation=gr.Blocks.load(name="spaces/THUDM/CodeGeeX")
### β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

title="DataTeller"

### β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

whisper_model = whisper.load_model("small")


def get_images(prompt):
    gallery_dir = stable_diffusion(prompt, fn_index=2)
    return [os.path.join(gallery_dir, img) for img in os.listdir(gallery_dir)]

def get_code(prompt):
    examples_dir = code_generation(prompt, fn_index=0)
    return [os.path.join(examples_dir, output) for output in os.listdir(examples_dir)]



def magic_whisper_to_sd(audio, guidance_scale, nb_iterations, seed):

    whisper_results = translate(audio)
    prompt = whisper_results[2]
    images = get_images(prompt)

    return whisper_results[0], whisper_results[1], whisper_results[2], images


def generate_code(audio):

    whisper_results = translate(audio)
    prompt = whisper_results[2]
    code = get_code(prompt)

    return code

def translate(audio):
    print("""
    β€”
    Sending audio to Whisper ...
    β€”
    """)
    now = datetime.now()
    date_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
    print('DateTime String:', date_time_str)

    audio = whisper.load_audio(audio)
    audio = whisper.pad_or_trim(audio)

    mel = whisper.log_mel_spectrogram(audio).to(whisper_model.device)

    _, probs = whisper_model.detect_language(mel)

    transcript_options = whisper.DecodingOptions(task="transcribe", fp16 = False)
    translate_options = whisper.DecodingOptions(task="translate", fp16 = False)

    transcription = whisper.decode(whisper_model, mel, transcript_options)
    translation = whisper.decode(whisper_model, mel, translate_options)

    print("language spoken: " + transcription.language)
    print("transcript: " + transcription.text)
    print("β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”")
    print("translated: " + translation.text)
    if transcription.language == "en":
        tr_flag = flag.flag('GB')
    else:
        tr_flag = flag.flag(transcription.language)
    return tr_flag, transcription.text, translation.text


### β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

css = """
        .container {
            max-width: 880px;
            margin: auto;
            padding-top: 1.5rem;
        }
        a {
            text-decoration: underline;
        }
        h1 {
            font-weight: 900;
            margin-bottom: 7px;
            text-align: center;
            font-size: 2em;
            margin-bottom: 1em;
        }
        #w2sd_container{
            margin-top: 20px;
        }
        .footer {
            margin-bottom: 45px;
            margin-top: 35px;
            text-align: center;
            border-bottom: 1px solid #e5e5e5;
        }
        .footer>p {
            font-size: .8rem;
            display: inline-block;
            padding: 0 10px;
            transform: translateY(10px);
            background: white;
        }
        .dark .footer {
            border-color: #303030;
        }
        .dark .footer>p {
            background: #0b0f19;
        }
        .tabitem {
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
        }
        #record_tab, #upload_tab {
            font-size: 1.2em;
        }
        #record_btn{

        }
        #record_btn > div > button > span {
            width: 2.375rem;
            height: 2.375rem;
        }
        #record_btn > div > button > span > span {
            width: 2.375rem;
            height: 2.375rem;
        }
        audio {
            margin-bottom: 10px;
        }
        div#record_btn > .mt-6{
            margin-top: 0!important;
        }
        div#record_btn > .mt-6 button {
            font-size: 2em;
            width: 100%;
            padding: 20px;
            height: 160px;
        }
        div#upload_area {
            height: 11.1rem;
        }
        div#upload_area > div.w-full > div {
            min-height: 9rem;
        }
        #check_btn_1, #check_btn_2{
            color: #fff;
            --tw-gradient-from: #4caf50;
            --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
            --tw-gradient-to: #4caf50;
            border-color: #8bc34a;
        }
        #magic_btn_1, #magic_btn_2{
            color: #fff;
            --tw-gradient-from: #f44336;
            --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
            --tw-gradient-to: #ff9800;
            border-color: #ff9800;
        }
        input::-webkit-inner-spin-button, input::-webkit-outer-spin-button {
            -webkit-appearance: none;
        }
        input[type=number] {
            -moz-appearance: textfield;
        }
        input[type=range] {
            -webkit-appearance: none;
            cursor: pointer;
            height: 1px;
            background: currentColor;
        }
        input[type=range]::-webkit-slider-thumb {
            -webkit-appearance: none;
            width: 0.5em;
            height: 1.2em;
            border-radius: 10px;
            background: currentColor;
        }
        input[type=range]::-moz-range-thumb{
            width: 0.5em;
            height: 1.2em;
            border-radius: 10px;
            background: currentColor;
        }
        div#spoken_lang textarea {
            font-size: 4em;
            line-height: 1em;
            text-align: center;
        }
        div#transcripted {
            flex: 4;
        }
        div#translated textarea {
            font-size: 1.5em;
            line-height: 1.25em;
        }
        #sd_settings {
            margin-bottom: 20px;
        }
        #diffuse_btn {
            color: #fff;
            font-size: 1em;
            margin-bottom: 20px;
            --tw-gradient-from: #4caf50;
            --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
            --tw-gradient-to: #4caf50;
            border-color: #8bc34a;
        }
         #codegen_btn {
            color: #fff;
            font-size: 1em;
            margin-bottom: 20px;
            --tw-gradient-from: #4caf50;
            --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
            --tw-gradient-to: #4caf50;
            border-color: #8bc34a;
        }
        #notice {
            padding: 20px 14px 10px;
            display: flex;
            align-content: space-evenly;
            gap: 20px;
            line-height: 1em;
            font-size: .8em;
            border: 1px solid #374151;
            border-radius: 10px;
        }
        #about {
            padding: 20px;
        }
        #notice > div {
            flex: 1;
        }

"""

### β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

with gr.Blocks(css=css) as demo:
    with gr.Column():
        gr.HTML('''
            <h1>
                DataTeller
            </h1>
            <p style='text-align: center;'>
                Generate data visualizations by speaking in your native language ! Try it in Romanian πŸ˜‰
            </p>

            <p style='text-align: center;'>
                This demo is wired to the official SD Space and using the Whisperer model
            </p>

        ''')


        gr.Markdown(
            """

            ## 1. Record audio or Upload an audio file:
            """
        )

        with gr.Tab(label="Record audio input", elem_id="record_tab"):
            with gr.Column():
                record_input = gr.Audio(
                                    source="microphone",
                                    type="filepath",
                                    show_label=False,
                                    elem_id="record_btn"
                                )
                with gr.Row():
                    audio_r_translate = gr.Button("Check Whisper first ? πŸ‘", elem_id="check_btn_1")
                    audio_r_direct_sd = gr.Button("Magic Whisper β€Ί SD right now!", elem_id="magic_btn_1")

        with gr.Tab(label="Upload audio input", elem_id="upload_tab"):
            with gr.Column():
                upload_input = gr.Audio(
                                    source="upload",
                                    type="filepath",
                                    show_label=False,
                                    elem_id="upload_area"
                                )
                with gr.Row():
                    audio_u_translate = gr.Button("Check Whisper first ? πŸ‘", elem_id="check_btn_2")
                    # audio_u_direct_sd = gr.Button("Magic Whisper β€Ί SD right now!", elem_id="magic_btn_2")

        with gr.Accordion(label="Stable Diffusion Settings", elem_id="sd_settings", visible=False):
            with gr.Row():
                guidance_scale = gr.Slider(2, 15, value = 7, label = 'Guidance Scale')
                nb_iterations = gr.Slider(10, 50, value = 25, step = 1, label = 'Steps')
                seed = gr.Slider(label = "Seed", minimum = 0, maximum = 2147483647, step = 1, randomize = True)

        gr.Markdown(
            """
            ## 2. Check Whisper output, correct it if necessary:
            """
        )

        with gr.Row():

            transcripted_output = gr.Textbox(
                                    label="Transcription in your detected spoken language",
                                    lines=3,
                                    elem_id="transcripted"
                                )
            language_detected_output = gr.Textbox(label="Native language", elem_id="spoken_lang",lines=3)

        with gr.Column():
            translated_output = gr.Textbox(
                                    label="Transcript translated in English by Whisper",
                                    lines=4,
                                    elem_id="translated"
                                )
            with gr.Row():
                clear_btn = gr.Button(value="Clear")
                diffuse_btn = gr.Button(value="OK, Diffuse this prompt !", elem_id="diffuse_btn")
                codegen_btn = gr.Button(value="Generate code from this prompt!", elem_id="codegen_btn")

                clear_btn.click(fn=lambda value: gr.update(value=""), inputs=clear_btn, outputs=translated_output)

        gr.Markdown(
            """
            ## 3. Use whisper results for code generation
            """
        )
        with gr.Column():

            with gr.Row():
                # clear_btn = gr.Button(value="Clear")
                # diffuse_btn = gr.Button(value="Diffuse this prompt!", elem_id="diffuse_btn")
                # codegen_btn = gr.Button(value="Generate code from this prompt!", elem_id="codegen_btn")

                code = gr.Textbox(
                                    label="Code generated",
                                    lines=4,
                                    elem_id="translated"
                                )
                # clear_btn.click(fn=lambda value: gr.update(value=""), inputs=clear_btn, outputs=translated_output)

        # gr.Markdown("""
        #     ## 4. Plot the generated code  β˜•οΈ
        #     Inference time is about ~20-30 seconds, when it's your turn 😬
        #     """
        #     )
        # with gr.Column():
        #     with gr.Row():
        #         def outbreak(plot_type):
        #             df = pd.read_csv('emp_experience_data.csv')
        #             data_encoded = df.copy(deep=True)
        #             categorical_column = ['Attrition', 'Gender', 'BusinessTravel', 'Education', 'EmployeeExperience', 'EmployeeFeedbackSentiments', 'Designation',
        #                                     'SalarySatisfaction', 'HealthBenefitsSatisfaction', 'UHGDiscountProgramUsage', 'HealthConscious', 'CareerPathSatisfaction', 'Region']
        #             label_encoding = LabelEncoder()
        #             for col in categorical_column:
        #                 data_encoded[col] = label_encoding.fit_transform(data_encoded[col])

        #             if plot_type == "Find Data Correlation":
        #                 fig = plt.figure()
        #                 data_correlation = data_encoded.corr()
        #                 sns.heatmap(data_correlation, xticklabels = data_correlation.columns, yticklabels = data_correlation.columns)
        #                 return fig
        #             if plot_type == "Filter Correlation Data":
        #                 fig = plt.figure()
        #                 filtered_df = df[['EmployeeExperience', 'EmployeeFeedbackSentiments', 'Age', 'SalarySatisfaction', 'BusinessTravel', 'HealthBenefitsSatisfaction']]
        #                 correlation_filter_data = filtered_df.corr()
        #                 sns.heatmap(correlation_filter_data, xticklabels = filtered_df.columns, yticklabels = filtered_df.columns)
        #                 return fig
        #             if plot_type == "Age vs Attrition":
        #                 fig = plt.figure()
        #                 plt.hist(data_encoded['Age'], bins=np.arange(0,80,10), alpha=0.8, rwidth=0.9, color='red')
        #                 plt.xlabel("Age")
        #                 plt.ylabel("Count")
        #                 plt.title("Age vs Attrition")
        #                 return fig
        #             if plot_type == "Business Travel vs Attrition":
        #                 fig = plt.figure()
        #                 ax = sns.countplot(x="BusinessTravel", hue="Attrition", data=data_encoded)
        #                 for p in ax.patches:
        #                     ax.annotate('{}'.format(p.get_height()), (p.get_x(), p.get_height()+1))
        #                 return fig
        #             if plot_type == "Employee Experience vs Attrition":
        #                 fig = plt.figure()
        #                 ax = sns.countplot(x="EmployeeExperience", hue="Attrition", data=data_encoded)
        #                 for p in ax.patches:
        #                     ax.annotate('{}'.format(p.get_height()), (p.get_x(), p.get_height()+1))
        #                 return figure

    #         inputs = [
    #             gr.Dropdown(["Find Data Correlation", "Filter Correlation Data", "Business Travel vs Attrition", "Employee Experience vs Attrition", "Age vs Attrition",], label="Data Correlation and Visualization")
    #         ]
    #         outputs = gr.Plot()

    #         demo2 = gr.Interface(
    #             fn = outbreak,
    #             inputs = inputs,
    #             outputs = outputs,
    #             title="Employee-Experience: Data Correlation and Pattern Visualization",
    #             allow_flagging=False
    #         )


        gr.Markdown("""
            ## 5. Wait for Stable Diffusion Results β˜•οΈ
            Inference time is about ~20-30 seconds, when it's your turn 😬
            """
            )

        sd_output = gr.Gallery().style(grid=2, height="auto")


        gr.Markdown("""
            ### πŸ“Œ About the models
            <p style='font-size: 1em;line-height: 1.5em;'>
            <strong>Whisper</strong> is a general-purpose speech recognition model.<br /><br />
            It is trained on a large dataset of diverse audio and is also a multi-task model that can perform multilingual speech recognition as well as speech translation and language identification. <br />
            β€”
            </p>
            <p style='font-size: 1em;line-height: 1.5em;'>
            <strong>Stable Diffusion</strong> is a state of the art text-to-image model that generates images from text.
            </p>
            <div id="notice">
                <div>
                LICENSE
                <p style='font-size: 0.8em;'>
                The model is licensed with a <a href="https://huggingface.co/spaces/CompVis/stable-diffusion-license" target="_blank">CreativeML Open RAIL-M</a> license.</p>
                <p style='font-size: 0.8em;'>
                The authors claim no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in this license.</p>
                <p style='font-size: 0.8em;'>
                The license forbids you from sharing any content that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, spread misinformation and target vulnerable groups.</p>
                <p style='font-size: 0.8em;'>
                For the full list of restrictions please <a href="https://huggingface.co/spaces/CompVis/stable-diffusion-license" target="_blank" target="_blank">read the license</a>.
                 </p>
                 </div>
                 <div>
                 Biases and content acknowledgment
                 <p style='font-size: 0.8em;'>
                 Despite how impressive being able to turn text into image is, beware to the fact that this model may output content that reinforces or exacerbates societal biases, as well as realistic faces, pornography and violence.</p>
                <p style='font-size: 0.8em;'>
                The model was trained on the <a href="https://laion.ai/blog/laion-5b/" target="_blank">LAION-5B dataset</a>, which scraped non-curated image-text-pairs from the internet (the exception being the removal of illegal content) and is meant for research purposes.</p>
                <p style='font-size: 0.8em;'>  You can read more in the <a href="https://huggingface.co/CompVis/stable-diffusion-v1-4" target="_blank">model card</a>.
                 </p>
                 </div>
             </div>

        """, elem_id="about")

        audio_r_translate.click(translate,
                                inputs = record_input,
                                outputs = [
                                    language_detected_output,
                                    transcripted_output,
                                    translated_output
                                ])

        audio_u_translate.click(translate,
                                inputs = upload_input,
                                outputs = [
                                    language_detected_output,
                                    transcripted_output,
                                    translated_output
                                ])

        audio_r_direct_sd.click(magic_whisper_to_sd,
                                inputs = [
                                    record_input,
                                    guidance_scale,
                                    nb_iterations,
                                    seed
                                ],
                                outputs = [
                                    language_detected_output,
                                    transcripted_output,
                                    translated_output,
                                    sd_output
                                ])

        # audio_u_direct_sd.click(magic_whisper_to_sd,
        #                         inputs = [
        #                             upload_input,
        #                             guidance_scale,
        #                             nb_iterations,
        #                             seed
        #                         ],
        #                         outputs = [
        #                             language_detected_output,
        #                             transcripted_output,
        #                             translated_output,
        #                             sd_output
        #                         ])

        diffuse_btn.click(get_images,
                              inputs = [
                                  translated_output
                                  ],
                              outputs = sd_output
                          )
        codegen_btn.click(generate_code,
                              inputs = [
                                  translated_output
                                  ],
                              outputs = code
                          )
        gr.HTML('''
                <div class="footer">
                    <p>Whisper by <a href="https://github.com/openai/whisper" target="_blank">OpenAI</a> - Stable Diffusion by <a href="https://huggingface.co/CompVis" target="_blank">CompVis</a> and <a href="https://huggingface.co/stabilityai"  target="_blank">Stability AI</a>
                    </p>
                </div>
                ''')


if __name__ == "__main__":
    demo.launch()