Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM | |
from transformers import MarianMTModel, MarianTokenizer | |
from diffusers import StableDiffusionPipeline, DiffusionPipeline | |
import torch | |
import numpy as np | |
import imageio | |
from PIL import Image | |
from modelscope.pipelines import pipeline as ms_pipeline | |
from modelscope.outputs import OutputKeys | |
class MultiModalServices: | |
def __init__(self): | |
self.device = "cuda" if torch.cuda.is_available() else "cpu" | |
self.image_generator = None | |
self.video_generator = None | |
self.translator = None | |
self.sentiment_analyzer = None | |
def load_image_generator(self): | |
if self.image_generator is None: | |
model_id = "CompVis/stable-diffusion-v1-4" | |
self.image_generator = StableDiffusionPipeline.from_pretrained( | |
model_id, | |
torch_dtype=torch.float32 | |
).to(self.device) | |
return self.image_generator | |
def load_video_generator(self): | |
if self.video_generator is None: | |
self.video_generator = ms_pipeline( | |
'text-to-video-synthesis', | |
'damo/text-to-video-synthesis' | |
) | |
return self.video_generator | |
def generate_image(self, prompt, num_images=1): | |
try: | |
generator = self.load_image_generator() | |
images = generator( | |
prompt, | |
num_images_per_prompt=num_images, | |
guidance_scale=7.5 | |
).images | |
return images[0] if num_images == 1 else images | |
except Exception as e: | |
return f"Erro na geração de imagem: {str(e)}" | |
def generate_video(self, prompt, duration=3): | |
try: | |
generator = self.load_video_generator() | |
output = generator({'text': prompt}) | |
return output[OutputKeys.OUTPUT_VIDEO] | |
except Exception as e: | |
return f"Erro na geração de vídeo: {str(e)}" | |
def translate(self, text, src_lang, tgt_lang): | |
if self.translator is None: | |
model_name = f'Helsinki-NLP/opus-mt-{src_lang}-{tgt_lang}' | |
self.translator = pipeline('translation', model=model_name) | |
try: | |
result = self.translator(text)[0]['translation_text'] | |
return result | |
except Exception as e: | |
return f"Erro na tradução: {str(e)}" | |
def analyze_sentiment(self, text): | |
if self.sentiment_analyzer is None: | |
self.sentiment_analyzer = pipeline( | |
'sentiment-analysis', | |
model='nlptown/bert-base-multilingual-uncased-sentiment' | |
) | |
try: | |
result = self.sentiment_analyzer(text)[0] | |
return f"Sentimento: {result['label']}, Confiança: {result['score']:.2f}" | |
except Exception as e: | |
return f"Erro na análise: {str(e)}" | |
# Instância global dos serviços | |
services = MultiModalServices() | |
# Interface Gradio | |
with gr.Blocks(title="Serviços de IA Multimodal") as demo: | |
gr.Markdown(""" | |
# 🎨 Hub de Serviços de IA Multimodal | |
Esta aplicação oferece serviços de geração de imagem, vídeo e processamento de texto. | |
""") | |
# 1. Geração de Imagem | |
with gr.Tab("Geração de Imagem"): | |
gr.Markdown("### Gerador de Imagens com Stable Diffusion") | |
with gr.Row(): | |
img_prompt = gr.Textbox( | |
label="Descrição da imagem", | |
placeholder="Descreva a imagem que deseja gerar...", | |
lines=3 | |
) | |
img_output = gr.Image(label="Imagem Gerada") | |
with gr.Row(): | |
img_num = gr.Slider( | |
minimum=1, | |
maximum=4, | |
value=1, | |
step=1, | |
label="Número de imagens" | |
) | |
img_button = gr.Button("Gerar Imagem") | |
img_button.click( | |
services.generate_image, | |
inputs=[img_prompt, img_num], | |
outputs=img_output | |
) | |
# 2. Geração de Vídeo | |
with gr.Tab("Geração de Vídeo"): | |
gr.Markdown("### Gerador de Vídeos") | |
with gr.Row(): | |
vid_prompt = gr.Textbox( | |
label="Descrição do vídeo", | |
placeholder="Descreva o vídeo que deseja gerar...", | |
lines=3 | |
) | |
vid_output = gr.Video(label="Vídeo Gerado") | |
with gr.Row(): | |
vid_duration = gr.Slider( | |
minimum=1, | |
maximum=10, | |
value=3, | |
step=1, | |
label="Duração (segundos)" | |
) | |
vid_button = gr.Button("Gerar Vídeo") | |
vid_button.click( | |
services.generate_video, | |
inputs=[vid_prompt, vid_duration], | |
outputs=vid_output | |
) | |
# 3. Tradução | |
with gr.Tab("Tradutor"): | |
gr.Markdown("### Tradutor Multilíngue") | |
with gr.Row(): | |
trans_input = gr.Textbox( | |
label="Texto para traduzir", | |
placeholder="Digite o texto aqui...", | |
lines=3 | |
) | |
trans_output = gr.Textbox( | |
label="Tradução", | |
lines=3 | |
) | |
with gr.Row(): | |
src_lang = gr.Dropdown( | |
choices=["en", "pt", "es", "fr", "de"], | |
value="en", | |
label="Idioma de origem" | |
) | |
tgt_lang = gr.Dropdown( | |
choices=["pt", "en", "es", "fr", "de"], | |
value="pt", | |
label="Idioma de destino" | |
) | |
trans_button = gr.Button("Traduzir") | |
trans_button.click( | |
services.translate, | |
inputs=[trans_input, src_lang, tgt_lang], | |
outputs=trans_output | |
) | |
# 4. Análise de Sentimentos | |
with gr.Tab("Análise de Sentimentos"): | |
gr.Markdown("### Análise de Sentimentos Multilíngue") | |
with gr.Row(): | |
sent_input = gr.Textbox( | |
label="Texto para análise", | |
placeholder="Digite o texto para analisar o sentimento...", | |
lines=3 | |
) | |
sent_output = gr.Textbox( | |
label="Resultado da análise", | |
lines=2 | |
) | |
sent_button = gr.Button("Analisar Sentimento") | |
sent_button.click( | |
services.analyze_sentiment, | |
inputs=sent_input, | |
outputs=sent_output | |
) | |
gr.Markdown(""" | |
### Notas: | |
- A geração de imagens e vídeos requer GPU para melhor performance | |
- Os modelos são carregados sob demanda para economizar memória | |
- Primeira execução pode ser mais lenta devido ao download dos modelos | |
- Todos os modelos são open source | |
""") | |
if __name__ == "__main__": | |
demo.launch() |