File size: 6,451 Bytes
9b5b26a
09a38d8
9b5b26a
 
c19d193
6aae614
09a38d8
 
8fe992b
9b5b26a
 
5df72d6
9b5b26a
09a38d8
 
 
9b5b26a
09a38d8
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
09a38d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
 
6aae614
ae7a494
 
 
 
e121372
bf6d34c
 
29ec968
fe328e0
13d500a
8c01ffb
 
9b5b26a
 
8c01ffb
861422e
 
9b5b26a
8c01ffb
8fe992b
d2f6a24
8c01ffb
 
 
 
 
 
861422e
8fe992b
 
9b5b26a
8c01ffb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
from datetime import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from typing import Dict, List, Union
import re

from Gradio_UI import GradioUI

# Below is an example of a tool that does nothing. Amaze us with your creativity !
@tool
def text_analyzer(text: str, analysis_type: str = "sentiment") -> Dict[str, Union[str, float, List[str]]]:
    """Uma ferramenta que realiza análises complexas em texto.
    
    Args:
        text: O texto a ser analisado
        analysis_type: Tipo de análise a realizar. Opções:
            - "sentiment": análise de sentimento
            - "keywords": extração de palavras-chave
            - "entities": reconhecimento de entidades
            - "summary": resumo automático
            
    Returns:
        Dict contendo os resultados da análise solicitada:
        - Para sentiment: score de -1 a 1
        - Para keywords: lista das principais palavras
        - Para entities: lista de entidades identificadas
        - Para summary: texto resumido
    """
    # Validação inicial
    if not text or not isinstance(text, str):
        raise ValueError("O texto deve ser uma string não vazia")
        
    if analysis_type not in ["sentiment", "keywords", "entities", "summary"]:
        raise ValueError("Tipo de análise inválido")
    
    # Preprocessamento básico
    text = text.lower()
    text = re.sub(r'[^\w\s]', '', text)
    
    results = {}
    
    if analysis_type == "sentiment":
        # Implementar análise de sentimento usando léxicos ou modelo
        # Este é um exemplo simplificado
        positive_words = set(['bom', 'ótimo', 'excelente', 'feliz'])
        negative_words = set(['ruim', 'péssimo', 'triste', 'raiva'])
        
        words = text.split()
        positive_count = sum(1 for word in words if word in positive_words)
        negative_count = sum(1 for word in words if word in negative_words)
        
        if positive_count + negative_count > 0:
            sentiment_score = (positive_count - negative_count) / (positive_count + negative_count)
        else:
            sentiment_score = 0
            
        results["sentiment_score"] = sentiment_score
        results["analysis_timestamp"] = datetime.now().isoformat()
        
    elif analysis_type == "keywords":
        # Implementar extração de palavras-chave
        # Exemplo usando frequência de palavras
        stopwords = set(['o', 'a', 'os', 'as', 'de', 'do', 'da', 'em', 'no', 'na'])
        words = [word for word in text.split() if word not in stopwords]
        
        word_freq = {}
        for word in words:
            word_freq[word] = word_freq.get(word, 0) + 1
            
        keywords = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:5]
        results["keywords"] = [word for word, _ in keywords]
        
    elif analysis_type == "entities":
        # Implementar reconhecimento de entidades
        # Exemplo simplificado procurando padrões comuns
        patterns = {
            'email': r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
            'phone': r'\b\d{2}[\s-]?\d{4,5}[-\s]?\d{4}\b',
            'date': r'\b\d{2}/\d{2}/\d{4}\b'
        }
        
        entities = {}
        for entity_type, pattern in patterns.items():
            matches = re.findall(pattern, text)
            if matches:
                entities[entity_type] = matches
                
        results["entities"] = entities
        
    elif analysis_type == "summary":
        # Implementar geração de resumo
        # Exemplo usando as primeiras sentenças
        sentences = text.split('.')
        if len(sentences) > 3:
            summary = '. '.join(sentences[:3]) + '.'
        else:
            summary = text
            
        results["summary"] = summary
        
    return results

# Exemplo de uso:
if __name__ == "__main__":
    texto_exemplo = """
    Hoje foi um dia ótimo! Tivemos uma reunião excelente com o cliente João Silva 
    (email: joao@exemplo.com, tel: 11-98765-4321) no dia 15/02/2024. O projeto está 
    avançando muito bem e todos estão felizes com os resultados alcançados até agora.
    """
    
    # Análise de sentimento
    sentiment_results = text_analyzer(texto_exemplo, "sentiment")
    print(f"Análise de sentimento: {sentiment_results}")
    
    # Extração de palavras-chave
    keyword_results = text_analyzer(texto_exemplo, "keywords")
    print(f"Palavras-chave: {keyword_results}")
    
    # Reconhecimento de entidades
    entity_results = text_analyzer(texto_exemplo, "entities")
    print(f"Entidades: {entity_results}")
    
    # Geração de resumo
    summary_results = text_analyzer(texto_exemplo, "summary")
    print(f"Resumo: {summary_results}")

@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """A tool that fetches the current local time in a specified timezone.
    Args:
        timezone: A string representing a valid timezone (e.g., 'America/New_York').
    """
    try:
        # Create timezone object
        tz = pytz.timezone(timezone)
        # Get current time in that timezone
        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
        return f"The current local time in {timezone} is: {local_time}"
    except Exception as e:
        return f"Error fetching time for timezone '{timezone}': {str(e)}"


final_answer = FinalAnswerTool()

# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 

model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
custom_role_conversions=None,
)


# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)

with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)
    
agent = CodeAgent(
    model=model,
    tools=[final_answer], ## add your tools here (don't remove final answer)
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates
)


GradioUI(agent).launch()