Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,6 +5,7 @@ from diffusers import StableDiffusionPipeline
|
|
5 |
import torch
|
6 |
import numpy as np
|
7 |
from PIL import Image
|
|
|
8 |
|
9 |
class AIServices:
|
10 |
def __init__(self):
|
@@ -12,6 +13,9 @@ class AIServices:
|
|
12 |
self.image_generator = None
|
13 |
self.translator = None
|
14 |
self.sentiment_analyzer = None
|
|
|
|
|
|
|
15 |
|
16 |
def load_image_generator(self):
|
17 |
if self.image_generator is None:
|
@@ -56,20 +60,80 @@ class AIServices:
|
|
56 |
except Exception as e:
|
57 |
return f"Erro na análise: {str(e)}"
|
58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
# Instância global dos serviços
|
60 |
services = AIServices()
|
61 |
|
62 |
# Interface Gradio
|
63 |
-
with gr.Blocks(title="Serviços de IA") as demo:
|
64 |
gr.Markdown("""
|
65 |
-
#
|
66 |
|
67 |
-
Esta aplicação oferece serviços de
|
68 |
""")
|
69 |
|
70 |
# 1. Geração de Imagem
|
71 |
with gr.Tab("Geração de Imagem"):
|
72 |
-
gr.Markdown("### Gerador de Imagens com Stable Diffusion")
|
73 |
with gr.Row():
|
74 |
img_prompt = gr.Textbox(
|
75 |
label="Descrição da imagem",
|
@@ -85,7 +149,7 @@ with gr.Blocks(title="Serviços de IA") as demo:
|
|
85 |
step=1,
|
86 |
label="Número de imagens"
|
87 |
)
|
88 |
-
img_button = gr.Button("Gerar Imagem")
|
89 |
img_button.click(
|
90 |
services.generate_image,
|
91 |
inputs=[img_prompt, img_num],
|
@@ -94,7 +158,7 @@ with gr.Blocks(title="Serviços de IA") as demo:
|
|
94 |
|
95 |
# 2. Tradução
|
96 |
with gr.Tab("Tradutor"):
|
97 |
-
gr.Markdown("### Tradutor Multilíngue")
|
98 |
with gr.Row():
|
99 |
trans_input = gr.Textbox(
|
100 |
label="Texto para traduzir",
|
@@ -116,7 +180,7 @@ with gr.Blocks(title="Serviços de IA") as demo:
|
|
116 |
value="pt",
|
117 |
label="Idioma de destino"
|
118 |
)
|
119 |
-
trans_button = gr.Button("Traduzir")
|
120 |
trans_button.click(
|
121 |
services.translate,
|
122 |
inputs=[trans_input, src_lang, tgt_lang],
|
@@ -125,7 +189,7 @@ with gr.Blocks(title="Serviços de IA") as demo:
|
|
125 |
|
126 |
# 3. Análise de Sentimentos
|
127 |
with gr.Tab("Análise de Sentimentos"):
|
128 |
-
gr.Markdown("### Análise de Sentimentos
|
129 |
with gr.Row():
|
130 |
sent_input = gr.Textbox(
|
131 |
label="Texto para análise",
|
@@ -136,15 +200,90 @@ with gr.Blocks(title="Serviços de IA") as demo:
|
|
136 |
label="Resultado da análise",
|
137 |
lines=2
|
138 |
)
|
139 |
-
sent_button = gr.Button("Analisar Sentimento")
|
140 |
sent_button.click(
|
141 |
services.analyze_sentiment,
|
142 |
inputs=sent_input,
|
143 |
outputs=sent_output
|
144 |
)
|
145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
gr.Markdown("""
|
147 |
-
### Notas:
|
148 |
- A geração de imagens requer GPU para melhor performance
|
149 |
- Os modelos são carregados sob demanda para economizar memória
|
150 |
- Primeira execução pode ser mais lenta devido ao download dos modelos
|
|
|
5 |
import torch
|
6 |
import numpy as np
|
7 |
from PIL import Image
|
8 |
+
import spacy
|
9 |
|
10 |
class AIServices:
|
11 |
def __init__(self):
|
|
|
13 |
self.image_generator = None
|
14 |
self.translator = None
|
15 |
self.sentiment_analyzer = None
|
16 |
+
self.summarizer = None
|
17 |
+
self.ner_model = None
|
18 |
+
self.classifier = None
|
19 |
|
20 |
def load_image_generator(self):
|
21 |
if self.image_generator is None:
|
|
|
60 |
except Exception as e:
|
61 |
return f"Erro na análise: {str(e)}"
|
62 |
|
63 |
+
def summarize_text(self, text, max_length=150, min_length=50):
|
64 |
+
if self.summarizer is None:
|
65 |
+
self.summarizer = pipeline('summarization', model='facebook/bart-large-cnn')
|
66 |
+
try:
|
67 |
+
summary = self.summarizer(text, max_length=max_length, min_length=min_length)[0]
|
68 |
+
return summary['summary_text']
|
69 |
+
except Exception as e:
|
70 |
+
return f"Erro ao resumir: {str(e)}"
|
71 |
+
|
72 |
+
def extract_entities(self, text):
|
73 |
+
try:
|
74 |
+
if self.ner_model is None:
|
75 |
+
self.ner_model = spacy.load("pt_core_news_sm")
|
76 |
+
|
77 |
+
doc = self.ner_model(text)
|
78 |
+
entities = []
|
79 |
+
|
80 |
+
for ent in doc.ents:
|
81 |
+
entities.append({
|
82 |
+
'text': ent.text,
|
83 |
+
'label': ent.label_,
|
84 |
+
'start': ent.start_char,
|
85 |
+
'end': ent.end_char
|
86 |
+
})
|
87 |
+
|
88 |
+
# Formatando a saída
|
89 |
+
result = ""
|
90 |
+
for e in entities:
|
91 |
+
result += f"📌 {e['text']} ({e['label']})\n"
|
92 |
+
|
93 |
+
return result if result else "Nenhuma entidade encontrada."
|
94 |
+
except Exception as e:
|
95 |
+
return f"Erro na extração de entidades: {str(e)}"
|
96 |
+
|
97 |
+
def classify_text(self, text):
|
98 |
+
if self.classifier is None:
|
99 |
+
self.classifier = pipeline(
|
100 |
+
"zero-shot-classification",
|
101 |
+
model="facebook/bart-large-mnli"
|
102 |
+
)
|
103 |
+
try:
|
104 |
+
# Categorias predefinidas
|
105 |
+
candidate_labels = [
|
106 |
+
"negócios", "tecnologia", "política",
|
107 |
+
"entretenimento", "esportes", "ciência",
|
108 |
+
"saúde", "educação"
|
109 |
+
]
|
110 |
+
|
111 |
+
result = self.classifier(text, candidate_labels, multi_label=True)
|
112 |
+
|
113 |
+
# Formatando a saída
|
114 |
+
output = "🏷️ Classificação:\n"
|
115 |
+
for label, score in zip(result['labels'], result['scores']):
|
116 |
+
if score > 0.1: # Mostra apenas scores relevantes
|
117 |
+
output += f"{label}: {score:.1%}\n"
|
118 |
+
|
119 |
+
return output
|
120 |
+
except Exception as e:
|
121 |
+
return f"Erro na classificação: {str(e)}"
|
122 |
+
|
123 |
# Instância global dos serviços
|
124 |
services = AIServices()
|
125 |
|
126 |
# Interface Gradio
|
127 |
+
with gr.Blocks(title="Hub de Serviços de IA") as demo:
|
128 |
gr.Markdown("""
|
129 |
+
# 🤖 Hub de Serviços de IA
|
130 |
|
131 |
+
Esta aplicação oferece diversos serviços de IA para processamento de texto e imagem.
|
132 |
""")
|
133 |
|
134 |
# 1. Geração de Imagem
|
135 |
with gr.Tab("Geração de Imagem"):
|
136 |
+
gr.Markdown("### 🎨 Gerador de Imagens com Stable Diffusion")
|
137 |
with gr.Row():
|
138 |
img_prompt = gr.Textbox(
|
139 |
label="Descrição da imagem",
|
|
|
149 |
step=1,
|
150 |
label="Número de imagens"
|
151 |
)
|
152 |
+
img_button = gr.Button("🎨 Gerar Imagem")
|
153 |
img_button.click(
|
154 |
services.generate_image,
|
155 |
inputs=[img_prompt, img_num],
|
|
|
158 |
|
159 |
# 2. Tradução
|
160 |
with gr.Tab("Tradutor"):
|
161 |
+
gr.Markdown("### 🌐 Tradutor Multilíngue")
|
162 |
with gr.Row():
|
163 |
trans_input = gr.Textbox(
|
164 |
label="Texto para traduzir",
|
|
|
180 |
value="pt",
|
181 |
label="Idioma de destino"
|
182 |
)
|
183 |
+
trans_button = gr.Button("🔄 Traduzir")
|
184 |
trans_button.click(
|
185 |
services.translate,
|
186 |
inputs=[trans_input, src_lang, tgt_lang],
|
|
|
189 |
|
190 |
# 3. Análise de Sentimentos
|
191 |
with gr.Tab("Análise de Sentimentos"):
|
192 |
+
gr.Markdown("### 😊 Análise de Sentimentos")
|
193 |
with gr.Row():
|
194 |
sent_input = gr.Textbox(
|
195 |
label="Texto para análise",
|
|
|
200 |
label="Resultado da análise",
|
201 |
lines=2
|
202 |
)
|
203 |
+
sent_button = gr.Button("💭 Analisar Sentimento")
|
204 |
sent_button.click(
|
205 |
services.analyze_sentiment,
|
206 |
inputs=sent_input,
|
207 |
outputs=sent_output
|
208 |
)
|
209 |
|
210 |
+
# 4. Resumo de Texto
|
211 |
+
with gr.Tab("Resumo"):
|
212 |
+
gr.Markdown("### 📝 Resumo Automático de Texto")
|
213 |
+
with gr.Row():
|
214 |
+
sum_input = gr.Textbox(
|
215 |
+
label="Texto para resumir",
|
216 |
+
placeholder="Cole aqui o texto que deseja resumir...",
|
217 |
+
lines=8
|
218 |
+
)
|
219 |
+
sum_output = gr.Textbox(
|
220 |
+
label="Resumo",
|
221 |
+
lines=4
|
222 |
+
)
|
223 |
+
with gr.Row():
|
224 |
+
max_len = gr.Slider(
|
225 |
+
minimum=50,
|
226 |
+
maximum=500,
|
227 |
+
value=150,
|
228 |
+
step=10,
|
229 |
+
label="Tamanho máximo do resumo"
|
230 |
+
)
|
231 |
+
min_len = gr.Slider(
|
232 |
+
minimum=30,
|
233 |
+
maximum=200,
|
234 |
+
value=50,
|
235 |
+
step=10,
|
236 |
+
label="Tamanho mínimo do resumo"
|
237 |
+
)
|
238 |
+
sum_button = gr.Button("📚 Gerar Resumo")
|
239 |
+
sum_button.click(
|
240 |
+
services.summarize_text,
|
241 |
+
inputs=[sum_input, max_len, min_len],
|
242 |
+
outputs=sum_output
|
243 |
+
)
|
244 |
+
|
245 |
+
# 5. Extração de Entidades
|
246 |
+
with gr.Tab("Entidades"):
|
247 |
+
gr.Markdown("### 🔍 Reconhecimento de Entidades")
|
248 |
+
with gr.Row():
|
249 |
+
ner_input = gr.Textbox(
|
250 |
+
label="Texto para análise",
|
251 |
+
placeholder="Digite o texto para extrair entidades...",
|
252 |
+
lines=5
|
253 |
+
)
|
254 |
+
ner_output = gr.Textbox(
|
255 |
+
label="Entidades encontradas",
|
256 |
+
lines=5
|
257 |
+
)
|
258 |
+
ner_button = gr.Button("🎯 Extrair Entidades")
|
259 |
+
ner_button.click(
|
260 |
+
services.extract_entities,
|
261 |
+
inputs=ner_input,
|
262 |
+
outputs=ner_output
|
263 |
+
)
|
264 |
+
|
265 |
+
# 6. Classificação de Texto
|
266 |
+
with gr.Tab("Classificação"):
|
267 |
+
gr.Markdown("### 📋 Classificação de Texto")
|
268 |
+
with gr.Row():
|
269 |
+
class_input = gr.Textbox(
|
270 |
+
label="Texto para classificar",
|
271 |
+
placeholder="Digite o texto para classificar...",
|
272 |
+
lines=5
|
273 |
+
)
|
274 |
+
class_output = gr.Textbox(
|
275 |
+
label="Classificação",
|
276 |
+
lines=5
|
277 |
+
)
|
278 |
+
class_button = gr.Button("🏷️ Classificar Texto")
|
279 |
+
class_button.click(
|
280 |
+
services.classify_text,
|
281 |
+
inputs=class_input,
|
282 |
+
outputs=class_output
|
283 |
+
)
|
284 |
+
|
285 |
gr.Markdown("""
|
286 |
+
### 📝 Notas:
|
287 |
- A geração de imagens requer GPU para melhor performance
|
288 |
- Os modelos são carregados sob demanda para economizar memória
|
289 |
- Primeira execução pode ser mais lenta devido ao download dos modelos
|