Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import pipeline | |
import numpy as np | |
class LightAIServices: | |
def __init__(self): | |
self.sentiment_analyzer = None | |
self.text_classifier = None | |
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)}" | |
def classify_text(self, text): | |
try: | |
if self.text_classifier is None: | |
self.text_classifier = pipeline( | |
"text-classification", | |
model="bert-base-uncased" | |
) | |
result = self.text_classifier(text)[0] | |
return f"Classificação: {result['label']}\nConfiança: {result['score']:.2f}" | |
except Exception as e: | |
return f"Erro na classificação: {str(e)}" | |
def analyze_text_length(self, text): | |
try: | |
words = text.split() | |
characters = len(text) | |
sentences = text.count('.') + text.count('!') + text.count('?') | |
return f"""📊 Análise do Texto: | |
• Palavras: {len(words)} | |
• Caracteres: {characters} | |
• Sentenças: {sentences} | |
• Média de palavras por sentença: {len(words)/max(1,sentences):.1f}""" | |
except Exception as e: | |
return f"Erro na análise: {str(e)}" | |
def analyze_text_stats(self, text): | |
try: | |
# Contagem básica | |
total_chars = len(text) | |
total_words = len(text.split()) | |
# Contagem de tipos de caracteres | |
uppercase = sum(1 for c in text if c.isupper()) | |
lowercase = sum(1 for c in text if c.islower()) | |
digits = sum(1 for c in text if c.isdigit()) | |
spaces = sum(1 for c in text if c.isspace()) | |
# Palavras únicas | |
unique_words = len(set(text.lower().split())) | |
return f"""📊 Estatísticas Detalhadas: | |
Contagens Básicas: | |
• Total de caracteres: {total_chars} | |
• Total de palavras: {total_words} | |
• Palavras únicas: {unique_words} | |
Tipos de Caracteres: | |
• Maiúsculas: {uppercase} | |
• Minúsculas: {lowercase} | |
• Dígitos: {digits} | |
• Espaços: {spaces} | |
Proporções: | |
• Diversidade de vocabulário: {unique_words/total_words:.2%} | |
• Densidade de caracteres: {total_chars/total_words:.1f} caracteres/palavra""" | |
except Exception as e: | |
return f"Erro na análise: {str(e)}" | |
def text_similarity(self, text1, text2): | |
try: | |
# Análise básica de similaridade | |
words1 = set(text1.lower().split()) | |
words2 = set(text2.lower().split()) | |
# Intersecção de palavras | |
common_words = words1.intersection(words2) | |
# Métricas de similaridade | |
similarity = len(common_words) / max(len(words1), len(words2)) | |
return f"""🔄 Análise de Similaridade: | |
• Palavras em comum: {len(common_words)} | |
• Similaridade: {similarity:.1%} | |
• Palavras texto 1: {len(words1)} | |
• Palavras texto 2: {len(words2)} | |
• Palavras em comum: {', '.join(list(common_words)[:10])}""" | |
except Exception as e: | |
return f"Erro na análise de similaridade: {str(e)}" | |
# Instância global dos serviços | |
services = LightAIServices() | |
# Interface Gradio | |
with gr.Blocks(title="Análise de Texto") as demo: | |
gr.Markdown(""" | |
# 📝 Hub de Análise de Texto | |
Serviços de processamento e análise de texto usando IA. | |
""") | |
# 1. Análise de Sentimentos | |
with gr.Tab("Análise de Sentimentos"): | |
gr.Markdown("### 😊 Análise de Sentimentos") | |
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 | |
) | |
# 2. Classificação | |
with gr.Tab("Classificação"): | |
gr.Markdown("### 📋 Classificação de Texto") | |
with gr.Row(): | |
class_input = gr.Textbox( | |
label="Texto para classificar", | |
placeholder="Digite o texto para classificar...", | |
lines=5 | |
) | |
class_output = gr.Textbox( | |
label="Classificação", | |
lines=2 | |
) | |
class_button = gr.Button("🏷️ Classificar Texto") | |
class_button.click( | |
services.classify_text, | |
inputs=class_input, | |
outputs=class_output | |
) | |
# 3. Análise de Comprimento | |
with gr.Tab("Análise de Comprimento"): | |
gr.Markdown("### 📏 Análise de Comprimento do Texto") | |
with gr.Row(): | |
len_input = gr.Textbox( | |
label="Texto para análise", | |
placeholder="Digite ou cole o texto para analisar...", | |
lines=5 | |
) | |
len_output = gr.Textbox( | |
label="Estatísticas", | |
lines=5 | |
) | |
len_button = gr.Button("📏 Analisar Comprimento") | |
len_button.click( | |
services.analyze_text_length, | |
inputs=len_input, | |
outputs=len_output | |
) | |
# 4. Estatísticas Detalhadas | |
with gr.Tab("Estatísticas"): | |
gr.Markdown("### 📊 Estatísticas Detalhadas do Texto") | |
with gr.Row(): | |
stats_input = gr.Textbox( | |
label="Texto para análise", | |
placeholder="Digite ou cole o texto para análise detalhada...", | |
lines=5 | |
) | |
stats_output = gr.Textbox( | |
label="Estatísticas Detalhadas", | |
lines=10 | |
) | |
stats_button = gr.Button("📊 Analisar Estatísticas") | |
stats_button.click( | |
services.analyze_text_stats, | |
inputs=stats_input, | |
outputs=stats_output | |
) | |
# 5. Comparação de Textos | |
with gr.Tab("Comparação"): | |
gr.Markdown("### 🔄 Comparação de Textos") | |
with gr.Row(): | |
comp_input1 = gr.Textbox( | |
label="Primeiro texto", | |
placeholder="Digite o primeiro texto...", | |
lines=3 | |
) | |
comp_input2 = gr.Textbox( | |
label="Segundo texto", | |
placeholder="Digite o segundo texto...", | |
lines=3 | |
) | |
comp_output = gr.Textbox( | |
label="Resultado da comparação", | |
lines=6 | |
) | |
comp_button = gr.Button("🔄 Comparar Textos") | |
comp_button.click( | |
services.text_similarity, | |
inputs=[comp_input1, comp_input2], | |
outputs=comp_output | |
) | |
gr.Markdown(""" | |
### 📝 Notas: | |
- Todos os serviços funcionam localmente | |
- Análises rápidas e eficientes | |
- Suporte para textos em português e inglês | |
""") | |
if __name__ == "__main__": | |
demo.launch() |