Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,171 +1,200 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import pipeline
|
3 |
-
import
|
4 |
-
import
|
5 |
import torch
|
|
|
|
|
6 |
from PIL import Image
|
7 |
-
import
|
8 |
-
import
|
9 |
-
import soundfile as sf
|
10 |
-
from googletrans import Translator
|
11 |
-
import spacy
|
12 |
-
|
13 |
-
# 1. Reconhecimento de Texto em Imagens (OCR)
|
14 |
-
def ocr_text(image):
|
15 |
-
reader = easyocr.Reader(['pt', 'en'])
|
16 |
-
result = reader.readtext(image)
|
17 |
-
return " ".join([text[1] for text in result])
|
18 |
|
19 |
-
|
20 |
-
def
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
label = f"{result['label']}: {result['score']:.2f}"
|
27 |
-
cv2.rectangle(
|
28 |
-
np.array(annotated_image),
|
29 |
-
(int(box['xmin']), int(box['ymin'])),
|
30 |
-
(int(box['xmax']), int(box['ymax'])),
|
31 |
-
(255, 0, 0),
|
32 |
-
2
|
33 |
-
)
|
34 |
-
return annotated_image
|
35 |
-
|
36 |
-
# 3. Análise de Sentimentos
|
37 |
-
def analyze_sentiment(text):
|
38 |
-
classifier = pipeline("sentiment-analysis", model="neuralmind/bert-base-portuguese-cased")
|
39 |
-
result = classifier(text)
|
40 |
-
return f"Sentimento: {result[0]['label']}, Confiança: {result[0]['score']:.2f}"
|
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 |
-
qa_pipeline = pipeline("question-answering", model="pierreguillou/bert-base-cased-squad-v1.1-portuguese")
|
81 |
-
result = qa_pipeline(question=question, context=context)
|
82 |
-
return result['answer']
|
83 |
|
84 |
# Interface Gradio
|
85 |
-
with gr.Blocks(title="
|
86 |
-
gr.Markdown("
|
|
|
87 |
|
88 |
-
|
89 |
-
|
90 |
-
with gr.Row():
|
91 |
-
ocr_input = gr.Image(type="numpy", label="Imagem com Texto")
|
92 |
-
ocr_output = gr.Textbox(label="Texto Extraído")
|
93 |
-
ocr_button = gr.Button("Extrair Texto")
|
94 |
-
ocr_button.click(ocr_text, inputs=ocr_input, outputs=ocr_output)
|
95 |
|
96 |
-
#
|
97 |
-
with gr.Tab("
|
|
|
98 |
with gr.Row():
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
with gr.Tab("Análise de Sentimentos"):
|
106 |
with gr.Row():
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
-
#
|
113 |
-
with gr.Tab("
|
|
|
114 |
with gr.Row():
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
with gr.Tab("Resumo de Texto"):
|
122 |
with gr.Row():
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
|
128 |
-
#
|
129 |
-
with gr.Tab("
|
|
|
130 |
with gr.Row():
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
|
|
|
|
138 |
with gr.Row():
|
139 |
-
|
140 |
-
|
141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
trans_button = gr.Button("Traduzir")
|
143 |
-
trans_button.click(
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
ner_input = gr.Textbox(label="Texto para Análise")
|
149 |
-
ner_output = gr.Textbox(label="Entidades Encontradas")
|
150 |
-
ner_button = gr.Button("Extrair Entidades")
|
151 |
-
ner_button.click(extract_entities, inputs=ner_input, outputs=ner_output)
|
152 |
-
|
153 |
-
# 9. Classificação de Imagens
|
154 |
-
with gr.Tab("Classificação de Imagens"):
|
155 |
-
with gr.Row():
|
156 |
-
class_input = gr.Image(type="numpy", label="Imagem")
|
157 |
-
class_output = gr.Textbox(label="Classificação")
|
158 |
-
class_button = gr.Button("Classificar Imagem")
|
159 |
-
class_button.click(classify_image, inputs=class_input, outputs=class_output)
|
160 |
|
161 |
-
#
|
162 |
-
with gr.Tab("
|
|
|
163 |
with gr.Row():
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
169 |
|
170 |
if __name__ == "__main__":
|
171 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
3 |
+
from transformers import MarianMTModel, MarianTokenizer
|
4 |
+
from diffusers import StableDiffusionPipeline, DiffusionPipeline
|
5 |
import torch
|
6 |
+
import numpy as np
|
7 |
+
import imageio
|
8 |
from PIL import Image
|
9 |
+
from modelscope.pipelines import pipeline as ms_pipeline
|
10 |
+
from modelscope.outputs import OutputKeys
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
+
class MultiModalServices:
|
13 |
+
def __init__(self):
|
14 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
15 |
+
self.image_generator = None
|
16 |
+
self.video_generator = None
|
17 |
+
self.translator = None
|
18 |
+
self.sentiment_analyzer = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
+
def load_image_generator(self):
|
21 |
+
if self.image_generator is None:
|
22 |
+
model_id = "CompVis/stable-diffusion-v1-4"
|
23 |
+
self.image_generator = StableDiffusionPipeline.from_pretrained(
|
24 |
+
model_id,
|
25 |
+
torch_dtype=torch.float32
|
26 |
+
).to(self.device)
|
27 |
+
return self.image_generator
|
28 |
|
29 |
+
def load_video_generator(self):
|
30 |
+
if self.video_generator is None:
|
31 |
+
self.video_generator = ms_pipeline(
|
32 |
+
'text-to-video-synthesis',
|
33 |
+
'damo/text-to-video-synthesis'
|
34 |
+
)
|
35 |
+
return self.video_generator
|
36 |
|
37 |
+
def generate_image(self, prompt, num_images=1):
|
38 |
+
try:
|
39 |
+
generator = self.load_image_generator()
|
40 |
+
images = generator(
|
41 |
+
prompt,
|
42 |
+
num_images_per_prompt=num_images,
|
43 |
+
guidance_scale=7.5
|
44 |
+
).images
|
45 |
+
return images[0] if num_images == 1 else images
|
46 |
+
except Exception as e:
|
47 |
+
return f"Erro na geração de imagem: {str(e)}"
|
48 |
|
49 |
+
def generate_video(self, prompt, duration=3):
|
50 |
+
try:
|
51 |
+
generator = self.load_video_generator()
|
52 |
+
output = generator({'text': prompt})
|
53 |
+
return output[OutputKeys.OUTPUT_VIDEO]
|
54 |
+
except Exception as e:
|
55 |
+
return f"Erro na geração de vídeo: {str(e)}"
|
56 |
|
57 |
+
def translate(self, text, src_lang, tgt_lang):
|
58 |
+
if self.translator is None:
|
59 |
+
model_name = f'Helsinki-NLP/opus-mt-{src_lang}-{tgt_lang}'
|
60 |
+
self.translator = pipeline('translation', model=model_name)
|
61 |
+
try:
|
62 |
+
result = self.translator(text)[0]['translation_text']
|
63 |
+
return result
|
64 |
+
except Exception as e:
|
65 |
+
return f"Erro na tradução: {str(e)}"
|
66 |
|
67 |
+
def analyze_sentiment(self, text):
|
68 |
+
if self.sentiment_analyzer is None:
|
69 |
+
self.sentiment_analyzer = pipeline(
|
70 |
+
'sentiment-analysis',
|
71 |
+
model='nlptown/bert-base-multilingual-uncased-sentiment'
|
72 |
+
)
|
73 |
+
try:
|
74 |
+
result = self.sentiment_analyzer(text)[0]
|
75 |
+
return f"Sentimento: {result['label']}, Confiança: {result['score']:.2f}"
|
76 |
+
except Exception as e:
|
77 |
+
return f"Erro na análise: {str(e)}"
|
78 |
|
79 |
+
# Instância global dos serviços
|
80 |
+
services = MultiModalServices()
|
|
|
|
|
|
|
81 |
|
82 |
# Interface Gradio
|
83 |
+
with gr.Blocks(title="Serviços de IA Multimodal") as demo:
|
84 |
+
gr.Markdown("""
|
85 |
+
# 🎨 Hub de Serviços de IA Multimodal
|
86 |
|
87 |
+
Esta aplicação oferece serviços de geração de imagem, vídeo e processamento de texto.
|
88 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
+
# 1. Geração de Imagem
|
91 |
+
with gr.Tab("Geração de Imagem"):
|
92 |
+
gr.Markdown("### Gerador de Imagens com Stable Diffusion")
|
93 |
with gr.Row():
|
94 |
+
img_prompt = gr.Textbox(
|
95 |
+
label="Descrição da imagem",
|
96 |
+
placeholder="Descreva a imagem que deseja gerar...",
|
97 |
+
lines=3
|
98 |
+
)
|
99 |
+
img_output = gr.Image(label="Imagem Gerada")
|
|
|
100 |
with gr.Row():
|
101 |
+
img_num = gr.Slider(
|
102 |
+
minimum=1,
|
103 |
+
maximum=4,
|
104 |
+
value=1,
|
105 |
+
step=1,
|
106 |
+
label="Número de imagens"
|
107 |
+
)
|
108 |
+
img_button = gr.Button("Gerar Imagem")
|
109 |
+
img_button.click(
|
110 |
+
services.generate_image,
|
111 |
+
inputs=[img_prompt, img_num],
|
112 |
+
outputs=img_output
|
113 |
+
)
|
114 |
|
115 |
+
# 2. Geração de Vídeo
|
116 |
+
with gr.Tab("Geração de Vídeo"):
|
117 |
+
gr.Markdown("### Gerador de Vídeos")
|
118 |
with gr.Row():
|
119 |
+
vid_prompt = gr.Textbox(
|
120 |
+
label="Descrição do vídeo",
|
121 |
+
placeholder="Descreva o vídeo que deseja gerar...",
|
122 |
+
lines=3
|
123 |
+
)
|
124 |
+
vid_output = gr.Video(label="Vídeo Gerado")
|
|
|
125 |
with gr.Row():
|
126 |
+
vid_duration = gr.Slider(
|
127 |
+
minimum=1,
|
128 |
+
maximum=10,
|
129 |
+
value=3,
|
130 |
+
step=1,
|
131 |
+
label="Duração (segundos)"
|
132 |
+
)
|
133 |
+
vid_button = gr.Button("Gerar Vídeo")
|
134 |
+
vid_button.click(
|
135 |
+
services.generate_video,
|
136 |
+
inputs=[vid_prompt, vid_duration],
|
137 |
+
outputs=vid_output
|
138 |
+
)
|
139 |
|
140 |
+
# 3. Tradução
|
141 |
+
with gr.Tab("Tradutor"):
|
142 |
+
gr.Markdown("### Tradutor Multilíngue")
|
143 |
with gr.Row():
|
144 |
+
trans_input = gr.Textbox(
|
145 |
+
label="Texto para traduzir",
|
146 |
+
placeholder="Digite o texto aqui...",
|
147 |
+
lines=3
|
148 |
+
)
|
149 |
+
trans_output = gr.Textbox(
|
150 |
+
label="Tradução",
|
151 |
+
lines=3
|
152 |
+
)
|
153 |
with gr.Row():
|
154 |
+
src_lang = gr.Dropdown(
|
155 |
+
choices=["en", "pt", "es", "fr", "de"],
|
156 |
+
value="en",
|
157 |
+
label="Idioma de origem"
|
158 |
+
)
|
159 |
+
tgt_lang = gr.Dropdown(
|
160 |
+
choices=["pt", "en", "es", "fr", "de"],
|
161 |
+
value="pt",
|
162 |
+
label="Idioma de destino"
|
163 |
+
)
|
164 |
trans_button = gr.Button("Traduzir")
|
165 |
+
trans_button.click(
|
166 |
+
services.translate,
|
167 |
+
inputs=[trans_input, src_lang, tgt_lang],
|
168 |
+
outputs=trans_output
|
169 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
|
171 |
+
# 4. Análise de Sentimentos
|
172 |
+
with gr.Tab("Análise de Sentimentos"):
|
173 |
+
gr.Markdown("### Análise de Sentimentos Multilíngue")
|
174 |
with gr.Row():
|
175 |
+
sent_input = gr.Textbox(
|
176 |
+
label="Texto para análise",
|
177 |
+
placeholder="Digite o texto para analisar o sentimento...",
|
178 |
+
lines=3
|
179 |
+
)
|
180 |
+
sent_output = gr.Textbox(
|
181 |
+
label="Resultado da análise",
|
182 |
+
lines=2
|
183 |
+
)
|
184 |
+
sent_button = gr.Button("Analisar Sentimento")
|
185 |
+
sent_button.click(
|
186 |
+
services.analyze_sentiment,
|
187 |
+
inputs=sent_input,
|
188 |
+
outputs=sent_output
|
189 |
+
)
|
190 |
+
|
191 |
+
gr.Markdown("""
|
192 |
+
### Notas:
|
193 |
+
- A geração de imagens e vídeos requer GPU para melhor performance
|
194 |
+
- Os modelos são carregados sob demanda para economizar memória
|
195 |
+
- Primeira execução pode ser mais lenta devido ao download dos modelos
|
196 |
+
- Todos os modelos são open source
|
197 |
+
""")
|
198 |
|
199 |
if __name__ == "__main__":
|
200 |
demo.launch()
|