sasha's picture
sasha HF staff
Update app.py
63f9337
import gradio as gr
#import torch
import whisper
from datetime import datetime
from PIL import Image
import flag
import os
#MY_SECRET_TOKEN=os.environ.get('HF_TOKEN_SD')
#from diffusers import StableDiffusionPipeline
whisper = gr.Interface.load(name="spaces/sanchit-gandhi/whisper-large-v2")
stable_diffusion = gr.Blocks.load(name="spaces/runwayml/stable-diffusion-v1-5")
### β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
title="Draw Me an Insect 🐞 /Dessine-moi un insecte 🐞"
### β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", use_auth_token=MY_SECRET_TOKEN)
#pipe.to(device)
### β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
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 magic_whisper_to_sd(audio, guidance_scale, nb_iterations, seed):
whisper_results = translate_better(audio)
prompt = whisper_results[1]
images = get_images(prompt)
return whisper_results[0], whisper_results[1], images
#def diffuse(prompt, guidance_scale, nb_iterations, seed):
#
# generator = torch.Generator(device=device).manual_seed(int(seed))
#
# print("""
# β€”
# Sending prompt to Stable Diffusion ...
# β€”
# """)
# print("prompt: " + prompt)
# print("guidance scale: " + str(guidance_scale))
# print("inference steps: " + str(nb_iterations))
# print("seed: " + str(seed))
#
# images_list = pipe(
# [prompt] * 2,
# guidance_scale=guidance_scale,
# num_inference_steps=nb_iterations,
# generator=generator
# )
#
# images = []
#
# safe_image = Image.open(r"unsafe.png")
#
# for i, image in enumerate(images_list["sample"]):
# if(images_list["nsfw_content_detected"][i]):
# images.append(safe_image)
# else:
# images.append(image)
#
#
# print("Stable Diffusion has finished")
# print("β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”")
#
# return images
def translate_better(audio):
print("""
β€”
Sending audio to Whisper ...
β€”
""")
transcribe_text_result = whisper(audio, None, "transcribe", fn_index=0)
translate_text_result = whisper(audio, None, "translate", fn_index=0)
print("transcript: " + transcribe_text_result)
print("β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”")
print("translated: " + translate_text_result)
return transcribe_text_result, translate_text_result
### β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
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;
}
#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>
Draw Me an Insect 🐞
Dessine-moi un insecte 🐞
</h1>
<p style='text-align: center;'>
Tell the AI the story of your first insect encounter and it will generate an image to illustrate it!
</p>
<p style='text-align: center;'>
Raconte à l'IA l'histoire de ta première rencontre avec les insectes et ça va génerer une image pour l'illustrer! </p>
''')
# with gr.Row(elem_id="w2sd_container"):
# with gr.Column():
gr.Markdown(
"""
## 1. Record audio or Upload an audio file/ Enregistrer de l'audio ou tΓ©lΓ©verser un fichier audio :
"""
)
with gr.Tab(label="Record/Enregistrer", 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 the transcription/VΓ©rifier la transcription πŸ‘", elem_id="check_btn_1")
audio_r_direct_sd = gr.Button("Generate the image right now! / GΓ©nerer l'image directement! πŸ–ŒοΈ", elem_id="magic_btn_1")
with gr.Tab(label="Upload audio/TΓ©lΓ©verser audio", 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 the transcription/VΓ©rifier la transcription πŸ‘", elem_id="check_btn_2")
audio_u_direct_sd = gr.Button("Generate the image right now! / GΓ©nerer l'image directement! πŸ–ŒοΈ", elem_id="magic_btn_2")
with gr.Accordion(label="Image generation Settings/Configuration de gΓ©nΓ©ration d'image", 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 the text output, correct it if necessary/VΓ©rifier la transcription, corriger si nΓ©cessaire:
"""
)
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")
clear_btn.click(fn=lambda value: gr.update(value=""), inputs=clear_btn, outputs=translated_output)
# with gr.Column():
gr.Markdown("""
## 3. Wait for your image/Attendre ton image β˜•οΈ
This can take ~20-30 seconds/ Ceci peut prendre jusqu'Γ  20-30 secondes.
"""
)
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_better,
inputs = record_input,
outputs = [
#language_detected_output,
transcripted_output,
translated_output
])
audio_u_translate.click(translate_better,
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
)
gr.HTML('''
<div class="footer">
<p> This Space is based on the <a href="https://huggingface.co/spaces/fffiloni/whisper-to-stable-diffusion" target="_blank">Whisper to Stable Diffusion Space</a> created by <a href="https://twitter.com/fffiloni" target="_blank">Sylvain Filoni</a>.
</p>
<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.queue(max_size=32, concurrency_count=20).launch()