Spaces:
Runtime error
Runtime error
File size: 8,205 Bytes
017ef28 8fe992b 017ef28 9b5b26a afa88b1 017ef28 6e34b89 017ef28 9b5b26a 017ef28 afa88b1 017ef28 afa88b1 017ef28 8c01ffb 017ef28 8c01ffb 017ef28 afa88b1 017ef28 afa88b1 017ef28 ae7a494 017ef28 ae7a494 017ef28 8c01ffb 017ef28 8c01ffb afa88b1 017ef28 8c01ffb 017ef28 9b5b26a 017ef28 8fe992b 017ef28 |
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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
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à!
@tool
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
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""Uno strumento che recupera l'ora locale corrente in un fuso orario specificato.
Argomenti:
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)}"
@tool
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)}"
@tool
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)}"
@tool
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)}"
@tool
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)}"
@tool
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() |