Spaces:
Sleeping
Sleeping
Update app.py
Browse filesAdd a tool the reads sentiment on texts, extract key words and make summaries
app.py
CHANGED
|
@@ -1,22 +1,131 @@
|
|
| 1 |
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
|
| 2 |
-
import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
from tools.final_answer import FinalAnswerTool
|
|
|
|
|
|
|
| 7 |
|
| 8 |
from Gradio_UI import GradioUI
|
| 9 |
|
| 10 |
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
| 11 |
@tool
|
| 12 |
-
def
|
| 13 |
-
|
| 14 |
-
|
| 15 |
Args:
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
"""
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
@tool
|
| 22 |
def get_current_time_in_timezone(timezone: str) -> str:
|
|
|
|
| 1 |
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
|
| 2 |
+
from datetime import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
from tools.final_answer import FinalAnswerTool
|
| 7 |
+
from typing import Dict, List, Union
|
| 8 |
+
import re
|
| 9 |
|
| 10 |
from Gradio_UI import GradioUI
|
| 11 |
|
| 12 |
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
| 13 |
@tool
|
| 14 |
+
def text_analyzer(text: str, analysis_type: str = "sentiment") -> Dict[str, Union[str, float, List[str]]]:
|
| 15 |
+
"""Uma ferramenta que realiza análises complexas em texto.
|
| 16 |
+
|
| 17 |
Args:
|
| 18 |
+
text: O texto a ser analisado
|
| 19 |
+
analysis_type: Tipo de análise a realizar. Opções:
|
| 20 |
+
- "sentiment": análise de sentimento
|
| 21 |
+
- "keywords": extração de palavras-chave
|
| 22 |
+
- "entities": reconhecimento de entidades
|
| 23 |
+
- "summary": resumo automático
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
Dict contendo os resultados da análise solicitada:
|
| 27 |
+
- Para sentiment: score de -1 a 1
|
| 28 |
+
- Para keywords: lista das principais palavras
|
| 29 |
+
- Para entities: lista de entidades identificadas
|
| 30 |
+
- Para summary: texto resumido
|
| 31 |
+
"""
|
| 32 |
+
# Validação inicial
|
| 33 |
+
if not text or not isinstance(text, str):
|
| 34 |
+
raise ValueError("O texto deve ser uma string não vazia")
|
| 35 |
+
|
| 36 |
+
if analysis_type not in ["sentiment", "keywords", "entities", "summary"]:
|
| 37 |
+
raise ValueError("Tipo de análise inválido")
|
| 38 |
+
|
| 39 |
+
# Preprocessamento básico
|
| 40 |
+
text = text.lower()
|
| 41 |
+
text = re.sub(r'[^\w\s]', '', text)
|
| 42 |
+
|
| 43 |
+
results = {}
|
| 44 |
+
|
| 45 |
+
if analysis_type == "sentiment":
|
| 46 |
+
# Implementar análise de sentimento usando léxicos ou modelo
|
| 47 |
+
# Este é um exemplo simplificado
|
| 48 |
+
positive_words = set(['bom', 'ótimo', 'excelente', 'feliz'])
|
| 49 |
+
negative_words = set(['ruim', 'péssimo', 'triste', 'raiva'])
|
| 50 |
+
|
| 51 |
+
words = text.split()
|
| 52 |
+
positive_count = sum(1 for word in words if word in positive_words)
|
| 53 |
+
negative_count = sum(1 for word in words if word in negative_words)
|
| 54 |
+
|
| 55 |
+
if positive_count + negative_count > 0:
|
| 56 |
+
sentiment_score = (positive_count - negative_count) / (positive_count + negative_count)
|
| 57 |
+
else:
|
| 58 |
+
sentiment_score = 0
|
| 59 |
+
|
| 60 |
+
results["sentiment_score"] = sentiment_score
|
| 61 |
+
results["analysis_timestamp"] = datetime.now().isoformat()
|
| 62 |
+
|
| 63 |
+
elif analysis_type == "keywords":
|
| 64 |
+
# Implementar extração de palavras-chave
|
| 65 |
+
# Exemplo usando frequência de palavras
|
| 66 |
+
stopwords = set(['o', 'a', 'os', 'as', 'de', 'do', 'da', 'em', 'no', 'na'])
|
| 67 |
+
words = [word for word in text.split() if word not in stopwords]
|
| 68 |
+
|
| 69 |
+
word_freq = {}
|
| 70 |
+
for word in words:
|
| 71 |
+
word_freq[word] = word_freq.get(word, 0) + 1
|
| 72 |
+
|
| 73 |
+
keywords = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:5]
|
| 74 |
+
results["keywords"] = [word for word, _ in keywords]
|
| 75 |
+
|
| 76 |
+
elif analysis_type == "entities":
|
| 77 |
+
# Implementar reconhecimento de entidades
|
| 78 |
+
# Exemplo simplificado procurando padrões comuns
|
| 79 |
+
patterns = {
|
| 80 |
+
'email': r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
|
| 81 |
+
'phone': r'\b\d{2}[\s-]?\d{4,5}[-\s]?\d{4}\b',
|
| 82 |
+
'date': r'\b\d{2}/\d{2}/\d{4}\b'
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
entities = {}
|
| 86 |
+
for entity_type, pattern in patterns.items():
|
| 87 |
+
matches = re.findall(pattern, text)
|
| 88 |
+
if matches:
|
| 89 |
+
entities[entity_type] = matches
|
| 90 |
+
|
| 91 |
+
results["entities"] = entities
|
| 92 |
+
|
| 93 |
+
elif analysis_type == "summary":
|
| 94 |
+
# Implementar geração de resumo
|
| 95 |
+
# Exemplo usando as primeiras sentenças
|
| 96 |
+
sentences = text.split('.')
|
| 97 |
+
if len(sentences) > 3:
|
| 98 |
+
summary = '. '.join(sentences[:3]) + '.'
|
| 99 |
+
else:
|
| 100 |
+
summary = text
|
| 101 |
+
|
| 102 |
+
results["summary"] = summary
|
| 103 |
+
|
| 104 |
+
return results
|
| 105 |
+
|
| 106 |
+
# Exemplo de uso:
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
texto_exemplo = """
|
| 109 |
+
Hoje foi um dia ótimo! Tivemos uma reunião excelente com o cliente João Silva
|
| 110 |
+
(email: joao@exemplo.com, tel: 11-98765-4321) no dia 15/02/2024. O projeto está
|
| 111 |
+
avançando muito bem e todos estão felizes com os resultados alcançados até agora.
|
| 112 |
"""
|
| 113 |
+
|
| 114 |
+
# Análise de sentimento
|
| 115 |
+
sentiment_results = text_analyzer(texto_exemplo, "sentiment")
|
| 116 |
+
print(f"Análise de sentimento: {sentiment_results}")
|
| 117 |
+
|
| 118 |
+
# Extração de palavras-chave
|
| 119 |
+
keyword_results = text_analyzer(texto_exemplo, "keywords")
|
| 120 |
+
print(f"Palavras-chave: {keyword_results}")
|
| 121 |
+
|
| 122 |
+
# Reconhecimento de entidades
|
| 123 |
+
entity_results = text_analyzer(texto_exemplo, "entities")
|
| 124 |
+
print(f"Entidades: {entity_results}")
|
| 125 |
+
|
| 126 |
+
# Geração de resumo
|
| 127 |
+
summary_results = text_analyzer(texto_exemplo, "summary")
|
| 128 |
+
print(f"Resumo: {summary_results}")
|
| 129 |
|
| 130 |
@tool
|
| 131 |
def get_current_time_in_timezone(timezone: str) -> str:
|