Spaces:
Runtime error
Runtime error
| from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| from tools.final_answer import FinalAnswerTool | |
| from Gradio_UI import GradioUI | |
| # Di seguito è riportato un esempio di uno strumento che non fa nulla. Stupiscici con la tua creatività! | |
| def my_custom_tool(arg1: str, arg2: int) -> str: # è importante specificare il tipo di ritorno | |
| """Uno strumento personalizzato che combina una stringa e un numero | |
| Args: | |
| arg1: una stringa da elaborare | |
| arg2: un numero intero da utilizzare come parametro | |
| """ | |
| result = f"Input elaborato: {arg1} ripetuto {arg2} volte = {arg1 * arg2}" | |
| return result | |
| def get_current_time_in_timezone(timezone: str) -> str: | |
| """Uno strumento che recupera l'ora locale corrente in un fuso orario specificato. | |
| Args: | |
| timezone: una stringa che rappresenta un fuso orario valido (ad esempio, 'America/New_York'). | |
| """ | |
| try: | |
| # Crea oggetto fuso orario | |
| tz = pytz.timezone(timezone) | |
| # Ottieni l'ora corrente in quel fuso orario | |
| local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") | |
| return f"L'ora locale corrente in {timezone} è: {local_time}" | |
| except Exception as e: | |
| return f"Errore durante il recupero dell'ora per il fuso orario '{timezone}': {str(e)}" | |
| def analyze_sentiment(text: str) -> str: | |
| """Analizza il sentimento di un testo fornito. | |
| Argomenti: | |
| text: il testo da analizzare | |
| """ | |
| try: | |
| # Implementazione semplificata, in produzione utilizzare una libreria NLP come transformers | |
| positive_words = ["buono", "ottimo", "eccellente", "felice", "positivo", "meraviglioso"] | |
| negative_words = ["cattivo", "terribile", "triste", "negativo", "pessimo", "orribile"] | |
| text_lower = text.lower() | |
| positive_count = sum(1 for word in positive_words if word in text_lower) | |
| negative_count = sum(1 for word in negative_words if word in text_lower) | |
| if positive_count > negative_count: | |
| sentiment = "positivo" | |
| elif negative_count > positive_count: | |
| sentiment = "negativo" | |
| else: | |
| sentiment = "neutro" | |
| return f"Analisi del sentimento: {sentiment} (parole positive: {positive_count}, parole negative: {negative_count})" | |
| except Exception as e: | |
| return f"Errore durante l'analisi del sentimento: {str(e)}" | |
| def extract_entities(text: str) -> str: | |
| """Estrae entità come nomi, luoghi e organizzazioni da un testo. | |
| Argomenti: | |
| text: il testo da cui estrarre le entità | |
| """ | |
| try: | |
| # Implementazione semplificata, in produzione utilizzare spaCy o Hugging Face transformers | |
| common_names = ["Mario", "Luigi", "Giovanni", "Maria", "Anna", "Giuseppe"] | |
| common_places = ["Roma", "Milano", "Napoli", "Firenze", "Venezia", "Italia"] | |
| common_orgs = ["Google", "Microsoft", "Apple", "Amazon", "Facebook", "Twitter"] | |
| text_words = text.split() | |
| names = [word for word in text_words if word in common_names] | |
| places = [word for word in text_words if word in common_places] | |
| orgs = [word for word in text_words if word in common_orgs] | |
| result = { | |
| "nomi": names, | |
| "luoghi": places, | |
| "organizzazioni": orgs | |
| } | |
| return f"Entità estratte: {result}" | |
| except Exception as e: | |
| return f"Errore durante l'estrazione delle entità: {str(e)}" | |
| def image_classification(image_url: str) -> str: | |
| """Classifica un'immagine da un URL. | |
| Argomenti: | |
| image_url: URL dell'immagine da classificare | |
| """ | |
| try: | |
| # Simulazione di classificazione, in produzione utilizzare un modello di vision come ViT | |
| if not image_url.startswith("http"): | |
| return "Errore: fornire un URL valido che inizia con http:// o https://" | |
| # Controlla se l'URL è accessibile | |
| response = requests.head(image_url, timeout=5) | |
| if response.status_code != 200: | |
| return f"Errore: impossibile accedere all'URL dell'immagine (status code: {response.status_code})" | |
| # Simuliamo la classificazione | |
| if "dog" in image_url.lower() or "cane" in image_url.lower(): | |
| return "Classificazione immagine: Cane (probabilità: 0.92)" | |
| elif "cat" in image_url.lower() or "gatto" in image_url.lower(): | |
| return "Classificazione immagine: Gatto (probabilità: 0.89)" | |
| else: | |
| return "Classificazione immagine: Oggetto generico (probabilità: 0.75)" | |
| except Exception as e: | |
| return f"Errore durante la classificazione dell'immagine: {str(e)}" | |
| def translate_text(text: str, target_language: str) -> str: | |
| """Traduce un testo in una lingua di destinazione. | |
| Argomenti: | |
| text: il testo da tradurre | |
| target_language: la lingua di destinazione (es. 'en', 'fr', 'es', 'de') | |
| """ | |
| try: | |
| # Implementazione semplificata, in produzione utilizzare API come Google Translate o modelli NLP | |
| language_map = { | |
| 'en': 'inglese', | |
| 'fr': 'francese', | |
| 'es': 'spagnolo', | |
| 'de': 'tedesco', | |
| 'it': 'italiano' | |
| } | |
| if target_language not in language_map: | |
| return f"Errore: lingua di destinazione '{target_language}' non supportata. Lingue supportate: {', '.join(language_map.keys())}" | |
| return f"Testo tradotto in {language_map.get(target_language, target_language)}: [Simulazione di traduzione per '{text}']" | |
| except Exception as e: | |
| return f"Errore durante la traduzione: {str(e)}" | |
| def summarize_text(text: str, max_length: int = 100) -> str: | |
| """Riassume un testo lungo in una versione più breve. | |
| Argomenti: | |
| text: il testo da riassumere | |
| max_length: lunghezza massima del riassunto in caratteri (default: 100) | |
| """ | |
| try: | |
| if len(text) <= max_length: | |
| return f"Il testo è già abbastanza breve: {text}" | |
| # Implementazione semplificata, in produzione utilizzare un modello NLP | |
| words = text.split() | |
| sentences = [] | |
| current_sentence = [] | |
| for word in words: | |
| current_sentence.append(word) | |
| if word.endswith('.') or word.endswith('!') or word.endswith('?'): | |
| sentences.append(' '.join(current_sentence)) | |
| current_sentence = [] | |
| if current_sentence: | |
| sentences.append(' '.join(current_sentence)) | |
| # Seleziona solo la prima frase o frasi fino al limite | |
| summary = "" | |
| for sentence in sentences: | |
| if len(summary + sentence) <= max_length: | |
| summary += sentence + " " | |
| else: | |
| break | |
| return f"Riassunto: {summary.strip()}" | |
| except Exception as e: | |
| return f"Errore durante il riassunto del testo: {str(e)}" | |
| final_answer = FinalAnswerTool() | |
| search_tool = DuckDuckGoSearchTool() | |
| model = HfApiModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| model_id='Qwen/Qwen2.5-Coder-32B-Instruction', | |
| custom_role_conversions=None, | |
| ) | |
| # Strumento di importazione dall'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, | |
| my_custom_tool, | |
| get_current_time_in_timezone, | |
| analyze_sentiment, | |
| extract_entities, | |
| image_classification, | |
| translate_text, | |
| summarize_text, | |
| search_tool, | |
| image_generation_tool | |
| ], | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name="AssistenteNLPCV", | |
| description="Un assistente AI specializzato in NLP e Computer Vision con capacità di ricerca e generazione di immagini", | |
| prompt_templates=prompt_templates | |
| ) | |
| GradioUI(agent).launch() |