File size: 6,878 Bytes
c357e49
317fb1f
 
 
c357e49
317fb1f
 
b4277da
317fb1f
 
9860e17
317fb1f
 
 
 
 
 
 
c357e49
317fb1f
 
 
 
 
 
 
 
b4277da
317fb1f
 
 
 
 
 
 
b4277da
317fb1f
 
 
 
 
 
 
 
 
 
 
b4277da
317fb1f
 
 
 
 
 
 
b4277da
317fb1f
 
 
 
 
 
 
 
 
b4277da
317fb1f
 
 
 
 
 
 
 
 
 
 
b4277da
317fb1f
 
b4277da
 
317fb1f
 
 
2830ea2
317fb1f
 
2830ea2
317fb1f
 
 
b4277da
317fb1f
 
 
 
 
 
b4277da
317fb1f
 
 
 
 
 
 
 
 
 
 
 
 
2830ea2
317fb1f
 
 
b4277da
317fb1f
 
 
 
 
 
b4277da
317fb1f
 
 
 
 
 
 
 
 
 
 
 
 
9860e17
317fb1f
 
 
b4277da
317fb1f
 
 
 
 
 
 
 
 
b4277da
317fb1f
 
 
 
 
 
 
 
 
 
b4277da
317fb1f
 
 
 
 
b4277da
317fb1f
 
 
b4277da
317fb1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9860e17
b4277da
 
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
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()