Spaces:
Sleeping
Sleeping
Download app.py from Carranca/First_agent_template: direct link, hf CLI and curl.
- Browser
- Download file 6.45 kB
-
https://huggingface.co/spaces/Carranca/First_agent_template/resolve/main/app.py
- Command line
-
hf download hf://spaces/Carranca/First_agent_template/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Carranca/First_agent_template/resolve/main/app.py
6.45 kB
| 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 ! | |
| 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}") | |
| 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() |