Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,52 +1,11 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import pipeline
|
| 3 |
-
from transformers import MarianMTModel, MarianTokenizer
|
| 4 |
-
from diffusers import StableDiffusionPipeline
|
| 5 |
-
import torch
|
| 6 |
import numpy as np
|
| 7 |
-
from PIL import Image
|
| 8 |
-
import spacy
|
| 9 |
|
| 10 |
-
class
|
| 11 |
def __init__(self):
|
| 12 |
-
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 13 |
-
self.image_generator = None
|
| 14 |
-
self.translator = None
|
| 15 |
self.sentiment_analyzer = None
|
| 16 |
-
self.
|
| 17 |
-
self.ner_model = None
|
| 18 |
-
self.classifier = 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 generate_image(self, prompt, num_images=1):
|
| 30 |
-
try:
|
| 31 |
-
generator = self.load_image_generator()
|
| 32 |
-
images = generator(
|
| 33 |
-
prompt,
|
| 34 |
-
num_images_per_prompt=num_images,
|
| 35 |
-
guidance_scale=7.5
|
| 36 |
-
).images
|
| 37 |
-
return images[0] if num_images == 1 else images
|
| 38 |
-
except Exception as e:
|
| 39 |
-
return f"Erro na geração de imagem: {str(e)}"
|
| 40 |
-
|
| 41 |
-
def translate(self, text, src_lang, tgt_lang):
|
| 42 |
-
if self.translator is None:
|
| 43 |
-
model_name = f'Helsinki-NLP/opus-mt-{src_lang}-{tgt_lang}'
|
| 44 |
-
self.translator = pipeline('translation', model=model_name)
|
| 45 |
-
try:
|
| 46 |
-
result = self.translator(text)[0]['translation_text']
|
| 47 |
-
return result
|
| 48 |
-
except Exception as e:
|
| 49 |
-
return f"Erro na tradução: {str(e)}"
|
| 50 |
|
| 51 |
def analyze_sentiment(self, text):
|
| 52 |
if self.sentiment_analyzer is None:
|
|
@@ -60,134 +19,101 @@ class AIServices:
|
|
| 60 |
except Exception as e:
|
| 61 |
return f"Erro na análise: {str(e)}"
|
| 62 |
|
| 63 |
-
def
|
| 64 |
-
if self.summarizer is None:
|
| 65 |
-
self.summarizer = pipeline('summarization', model='facebook/bart-large-cnn')
|
| 66 |
try:
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
-
return f"Erro
|
| 71 |
|
| 72 |
-
def
|
| 73 |
try:
|
| 74 |
-
|
| 75 |
-
|
|
|
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
'text': ent.text,
|
| 83 |
-
'label': ent.label_,
|
| 84 |
-
'start': ent.start_char,
|
| 85 |
-
'end': ent.end_char
|
| 86 |
-
})
|
| 87 |
|
| 88 |
-
|
| 89 |
-
result = ""
|
| 90 |
-
for e in entities:
|
| 91 |
-
result += f"📌 {e['text']} ({e['label']})\n"
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
except Exception as e:
|
| 95 |
-
return f"Erro na
|
| 96 |
|
| 97 |
-
def
|
| 98 |
-
if self.classifier is None:
|
| 99 |
-
self.classifier = pipeline(
|
| 100 |
-
"zero-shot-classification",
|
| 101 |
-
model="facebook/bart-large-mnli"
|
| 102 |
-
)
|
| 103 |
try:
|
| 104 |
-
#
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
|
| 111 |
-
|
|
|
|
| 112 |
|
| 113 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
except Exception as e:
|
| 121 |
-
return f"Erro na
|
| 122 |
|
| 123 |
# Instância global dos serviços
|
| 124 |
-
services =
|
| 125 |
|
| 126 |
# Interface Gradio
|
| 127 |
-
with gr.Blocks(title="
|
| 128 |
gr.Markdown("""
|
| 129 |
-
#
|
| 130 |
|
| 131 |
-
|
| 132 |
""")
|
| 133 |
|
| 134 |
-
# 1.
|
| 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",
|
| 140 |
-
placeholder="Descreva a imagem que deseja gerar...",
|
| 141 |
-
lines=3
|
| 142 |
-
)
|
| 143 |
-
img_output = gr.Image(label="Imagem Gerada")
|
| 144 |
-
with gr.Row():
|
| 145 |
-
img_num = gr.Slider(
|
| 146 |
-
minimum=1,
|
| 147 |
-
maximum=4,
|
| 148 |
-
value=1,
|
| 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],
|
| 156 |
-
outputs=img_output
|
| 157 |
-
)
|
| 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",
|
| 165 |
-
placeholder="Digite o texto aqui...",
|
| 166 |
-
lines=3
|
| 167 |
-
)
|
| 168 |
-
trans_output = gr.Textbox(
|
| 169 |
-
label="Tradução",
|
| 170 |
-
lines=3
|
| 171 |
-
)
|
| 172 |
-
with gr.Row():
|
| 173 |
-
src_lang = gr.Dropdown(
|
| 174 |
-
choices=["en", "pt", "es", "fr", "de"],
|
| 175 |
-
value="en",
|
| 176 |
-
label="Idioma de origem"
|
| 177 |
-
)
|
| 178 |
-
tgt_lang = gr.Dropdown(
|
| 179 |
-
choices=["pt", "en", "es", "fr", "de"],
|
| 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],
|
| 187 |
-
outputs=trans_output
|
| 188 |
-
)
|
| 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():
|
|
@@ -207,87 +133,96 @@ with gr.Blocks(title="Hub de Serviços de IA") as demo:
|
|
| 207 |
outputs=sent_output
|
| 208 |
)
|
| 209 |
|
| 210 |
-
#
|
| 211 |
-
with gr.Tab("
|
| 212 |
-
gr.Markdown("###
|
| 213 |
with gr.Row():
|
| 214 |
-
|
| 215 |
-
label="Texto para
|
| 216 |
-
placeholder="
|
| 217 |
-
lines=
|
| 218 |
)
|
| 219 |
-
|
| 220 |
-
label="
|
| 221 |
-
lines=
|
| 222 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
with gr.Row():
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
step=10,
|
| 229 |
-
label="Tamanho máximo do resumo"
|
| 230 |
)
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
value=50,
|
| 235 |
-
step=10,
|
| 236 |
-
label="Tamanho mínimo do resumo"
|
| 237 |
)
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
services.
|
| 241 |
-
inputs=
|
| 242 |
-
outputs=
|
| 243 |
)
|
| 244 |
|
| 245 |
-
#
|
| 246 |
-
with gr.Tab("
|
| 247 |
-
gr.Markdown("###
|
| 248 |
with gr.Row():
|
| 249 |
-
|
| 250 |
label="Texto para análise",
|
| 251 |
-
placeholder="Digite o texto para
|
| 252 |
lines=5
|
| 253 |
)
|
| 254 |
-
|
| 255 |
-
label="
|
| 256 |
-
lines=
|
| 257 |
)
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
services.
|
| 261 |
-
inputs=
|
| 262 |
-
outputs=
|
| 263 |
)
|
| 264 |
|
| 265 |
-
#
|
| 266 |
-
with gr.Tab("
|
| 267 |
-
gr.Markdown("###
|
| 268 |
with gr.Row():
|
| 269 |
-
|
| 270 |
-
label="
|
| 271 |
-
placeholder="Digite o
|
| 272 |
-
lines=
|
| 273 |
)
|
| 274 |
-
|
| 275 |
-
label="
|
| 276 |
-
|
|
|
|
| 277 |
)
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
)
|
| 284 |
|
| 285 |
gr.Markdown("""
|
| 286 |
### 📝 Notas:
|
| 287 |
-
-
|
| 288 |
-
-
|
| 289 |
-
-
|
| 290 |
-
- Todos os modelos são open source
|
| 291 |
""")
|
| 292 |
|
| 293 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
| 3 |
import numpy as np
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
class LightAIServices:
|
| 6 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
| 7 |
self.sentiment_analyzer = None
|
| 8 |
+
self.text_classifier = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
def analyze_sentiment(self, text):
|
| 11 |
if self.sentiment_analyzer is None:
|
|
|
|
| 19 |
except Exception as e:
|
| 20 |
return f"Erro na análise: {str(e)}"
|
| 21 |
|
| 22 |
+
def classify_text(self, text):
|
|
|
|
|
|
|
| 23 |
try:
|
| 24 |
+
if self.text_classifier is None:
|
| 25 |
+
self.text_classifier = pipeline(
|
| 26 |
+
"text-classification",
|
| 27 |
+
model="bert-base-uncased"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
result = self.text_classifier(text)[0]
|
| 31 |
+
return f"Classificação: {result['label']}\nConfiança: {result['score']:.2f}"
|
| 32 |
except Exception as e:
|
| 33 |
+
return f"Erro na classificação: {str(e)}"
|
| 34 |
|
| 35 |
+
def analyze_text_length(self, text):
|
| 36 |
try:
|
| 37 |
+
words = text.split()
|
| 38 |
+
characters = len(text)
|
| 39 |
+
sentences = text.count('.') + text.count('!') + text.count('?')
|
| 40 |
|
| 41 |
+
return f"""📊 Análise do Texto:
|
| 42 |
+
• Palavras: {len(words)}
|
| 43 |
+
• Caracteres: {characters}
|
| 44 |
+
• Sentenças: {sentences}
|
| 45 |
+
• Média de palavras por sentença: {len(words)/max(1,sentences):.1f}"""
|
| 46 |
+
except Exception as e:
|
| 47 |
+
return f"Erro na análise: {str(e)}"
|
| 48 |
+
|
| 49 |
+
def analyze_text_stats(self, text):
|
| 50 |
+
try:
|
| 51 |
+
# Contagem básica
|
| 52 |
+
total_chars = len(text)
|
| 53 |
+
total_words = len(text.split())
|
| 54 |
+
|
| 55 |
+
# Contagem de tipos de caracteres
|
| 56 |
+
uppercase = sum(1 for c in text if c.isupper())
|
| 57 |
+
lowercase = sum(1 for c in text if c.islower())
|
| 58 |
+
digits = sum(1 for c in text if c.isdigit())
|
| 59 |
+
spaces = sum(1 for c in text if c.isspace())
|
| 60 |
|
| 61 |
+
# Palavras únicas
|
| 62 |
+
unique_words = len(set(text.lower().split()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
return f"""📊 Estatísticas Detalhadas:
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
Contagens Básicas:
|
| 67 |
+
• Total de caracteres: {total_chars}
|
| 68 |
+
• Total de palavras: {total_words}
|
| 69 |
+
• Palavras únicas: {unique_words}
|
| 70 |
+
|
| 71 |
+
Tipos de Caracteres:
|
| 72 |
+
• Maiúsculas: {uppercase}
|
| 73 |
+
• Minúsculas: {lowercase}
|
| 74 |
+
• Dígitos: {digits}
|
| 75 |
+
• Espaços: {spaces}
|
| 76 |
+
|
| 77 |
+
Proporções:
|
| 78 |
+
• Diversidade de vocabulário: {unique_words/total_words:.2%}
|
| 79 |
+
• Densidade de caracteres: {total_chars/total_words:.1f} caracteres/palavra"""
|
| 80 |
except Exception as e:
|
| 81 |
+
return f"Erro na análise: {str(e)}"
|
| 82 |
|
| 83 |
+
def text_similarity(self, text1, text2):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
try:
|
| 85 |
+
# Análise básica de similaridade
|
| 86 |
+
words1 = set(text1.lower().split())
|
| 87 |
+
words2 = set(text2.lower().split())
|
| 88 |
+
|
| 89 |
+
# Intersecção de palavras
|
| 90 |
+
common_words = words1.intersection(words2)
|
| 91 |
|
| 92 |
+
# Métricas de similaridade
|
| 93 |
+
similarity = len(common_words) / max(len(words1), len(words2))
|
| 94 |
|
| 95 |
+
return f"""🔄 Análise de Similaridade:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
• Palavras em comum: {len(common_words)}
|
| 98 |
+
• Similaridade: {similarity:.1%}
|
| 99 |
+
• Palavras texto 1: {len(words1)}
|
| 100 |
+
• Palavras texto 2: {len(words2)}
|
| 101 |
+
• Palavras em comum: {', '.join(list(common_words)[:10])}"""
|
| 102 |
except Exception as e:
|
| 103 |
+
return f"Erro na análise de similaridade: {str(e)}"
|
| 104 |
|
| 105 |
# Instância global dos serviços
|
| 106 |
+
services = LightAIServices()
|
| 107 |
|
| 108 |
# Interface Gradio
|
| 109 |
+
with gr.Blocks(title="Análise de Texto") as demo:
|
| 110 |
gr.Markdown("""
|
| 111 |
+
# 📝 Hub de Análise de Texto
|
| 112 |
|
| 113 |
+
Serviços de processamento e análise de texto usando IA.
|
| 114 |
""")
|
| 115 |
|
| 116 |
+
# 1. Análise de Sentimentos
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
with gr.Tab("Análise de Sentimentos"):
|
| 118 |
gr.Markdown("### 😊 Análise de Sentimentos")
|
| 119 |
with gr.Row():
|
|
|
|
| 133 |
outputs=sent_output
|
| 134 |
)
|
| 135 |
|
| 136 |
+
# 2. Classificação
|
| 137 |
+
with gr.Tab("Classificação"):
|
| 138 |
+
gr.Markdown("### 📋 Classificação de Texto")
|
| 139 |
with gr.Row():
|
| 140 |
+
class_input = gr.Textbox(
|
| 141 |
+
label="Texto para classificar",
|
| 142 |
+
placeholder="Digite o texto para classificar...",
|
| 143 |
+
lines=5
|
| 144 |
)
|
| 145 |
+
class_output = gr.Textbox(
|
| 146 |
+
label="Classificação",
|
| 147 |
+
lines=2
|
| 148 |
)
|
| 149 |
+
class_button = gr.Button("🏷️ Classificar Texto")
|
| 150 |
+
class_button.click(
|
| 151 |
+
services.classify_text,
|
| 152 |
+
inputs=class_input,
|
| 153 |
+
outputs=class_output
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# 3. Análise de Comprimento
|
| 157 |
+
with gr.Tab("Análise de Comprimento"):
|
| 158 |
+
gr.Markdown("### 📏 Análise de Comprimento do Texto")
|
| 159 |
with gr.Row():
|
| 160 |
+
len_input = gr.Textbox(
|
| 161 |
+
label="Texto para análise",
|
| 162 |
+
placeholder="Digite ou cole o texto para analisar...",
|
| 163 |
+
lines=5
|
|
|
|
|
|
|
| 164 |
)
|
| 165 |
+
len_output = gr.Textbox(
|
| 166 |
+
label="Estatísticas",
|
| 167 |
+
lines=5
|
|
|
|
|
|
|
|
|
|
| 168 |
)
|
| 169 |
+
len_button = gr.Button("📏 Analisar Comprimento")
|
| 170 |
+
len_button.click(
|
| 171 |
+
services.analyze_text_length,
|
| 172 |
+
inputs=len_input,
|
| 173 |
+
outputs=len_output
|
| 174 |
)
|
| 175 |
|
| 176 |
+
# 4. Estatísticas Detalhadas
|
| 177 |
+
with gr.Tab("Estatísticas"):
|
| 178 |
+
gr.Markdown("### 📊 Estatísticas Detalhadas do Texto")
|
| 179 |
with gr.Row():
|
| 180 |
+
stats_input = gr.Textbox(
|
| 181 |
label="Texto para análise",
|
| 182 |
+
placeholder="Digite ou cole o texto para análise detalhada...",
|
| 183 |
lines=5
|
| 184 |
)
|
| 185 |
+
stats_output = gr.Textbox(
|
| 186 |
+
label="Estatísticas Detalhadas",
|
| 187 |
+
lines=10
|
| 188 |
)
|
| 189 |
+
stats_button = gr.Button("📊 Analisar Estatísticas")
|
| 190 |
+
stats_button.click(
|
| 191 |
+
services.analyze_text_stats,
|
| 192 |
+
inputs=stats_input,
|
| 193 |
+
outputs=stats_output
|
| 194 |
)
|
| 195 |
|
| 196 |
+
# 5. Comparação de Textos
|
| 197 |
+
with gr.Tab("Comparação"):
|
| 198 |
+
gr.Markdown("### 🔄 Comparação de Textos")
|
| 199 |
with gr.Row():
|
| 200 |
+
comp_input1 = gr.Textbox(
|
| 201 |
+
label="Primeiro texto",
|
| 202 |
+
placeholder="Digite o primeiro texto...",
|
| 203 |
+
lines=3
|
| 204 |
)
|
| 205 |
+
comp_input2 = gr.Textbox(
|
| 206 |
+
label="Segundo texto",
|
| 207 |
+
placeholder="Digite o segundo texto...",
|
| 208 |
+
lines=3
|
| 209 |
)
|
| 210 |
+
comp_output = gr.Textbox(
|
| 211 |
+
label="Resultado da comparação",
|
| 212 |
+
lines=6
|
| 213 |
+
)
|
| 214 |
+
comp_button = gr.Button("🔄 Comparar Textos")
|
| 215 |
+
comp_button.click(
|
| 216 |
+
services.text_similarity,
|
| 217 |
+
inputs=[comp_input1, comp_input2],
|
| 218 |
+
outputs=comp_output
|
| 219 |
)
|
| 220 |
|
| 221 |
gr.Markdown("""
|
| 222 |
### 📝 Notas:
|
| 223 |
+
- Todos os serviços funcionam localmente
|
| 224 |
+
- Análises rápidas e eficientes
|
| 225 |
+
- Suporte para textos em português e inglês
|
|
|
|
| 226 |
""")
|
| 227 |
|
| 228 |
if __name__ == "__main__":
|