msblend commited on
Commit
017ef28
·
verified ·
1 Parent(s): afa88b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +196 -46
app.py CHANGED
@@ -1,65 +1,215 @@
1
- da smolagents importa CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, strumento
2
- importa datetime
3
- importa richieste
4
- importa pytz
5
- importa yaml
6
- da tools.final_answer importa FinalAnswerTool
7
 
8
- da Gradio_UI importa GradioUI
9
 
10
  # Di seguito è riportato un esempio di uno strumento che non fa nulla. Stupiscici con la tua creatività!
 
 
 
 
 
 
 
 
 
11
 
12
- def my_custom_tool ( arg1: str , arg2: int )-> str : # è importante specificare il tipo di ritorno
13
- # Mantieni questo formato per la descrizione dello strumento / descrizione degli argomenti ma sentiti libero di modificare lo strumento
14
- """Uno strumento che non fa ancora nulla
15
  Argomenti:
16
- arg1: il primo argomento
17
- arg2: il secondo argomento
18
  """
19
- ritorna "Quale magia costruirai?"
 
 
 
 
 
 
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- def get_current_time_in_timezone ( timezone: str ) -> str :
23
- """Uno strumento che recupera l'ora locale corrente in un fuso orario specificato.
 
24
  Argomenti:
25
- fuso orario: una stringa che rappresenta un fuso orario valido (ad esempio, 'America/New_York').
26
- """
27
- prova :
28
- # Crea oggetto fuso orario
29
- tz = pytz.timezone(fuso orario)
30
- # Ottieni l'ora corrente in quel fuso orario
31
- local_time = datetime.datetime.now(tz).strftime( "%Y-%m-%d %H:%M:%S" )
32
- return f"L'ora locale corrente in {timezone} è: {local_time} "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  except Exception as e:
34
- return f"Errore durante il recupero dell'ora per il fuso orario ' {timezone} ': { str (e)} "
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- risposta_finale = StrumentoRispostaFinale()
38
- modello = HfApiModel(
39
- numero massimo di token = 2096 ,
40
- temperatura= 0,5 ,
41
- model_id= 'Qwen/Qwen2.5-Coder-32B-Istruzione' ,
42
- custom_role_conversions= Nessuno ,
43
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
 
 
 
 
 
 
45
 
46
  # Strumento di importazione dall'hub
47
- image_generation_tool = load_tool( "agents-course/text-to-image" , trust_remote_code= True )
48
 
49
- con open ( "prompts.yaml" , 'r' ) come flusso:
50
- prompt_templates = yaml.safe_load(flusso)
51
 
52
- agente = CodeAgent(
53
- modello=modello,
54
- tools=[final_answer], # aggiungi i tuoi strumenti qui (non rimuovere final_answer)
55
- max_steps= 6 ,
56
- livello_di_verbosità= 1 ,
57
- grammatica= Nessuna ,
58
- planning_interval= Nessuno ,
59
- nome= Nessuno ,
60
- descrizione= Nessuno ,
61
- prompt_templates=template_prompt
 
 
 
 
 
 
 
 
 
 
 
62
  )
63
 
64
-
65
- GradioUI(agente).launch()
 
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
  # Di seguito è riportato un esempio di uno strumento che non fa nulla. Stupiscici con la tua creatività!
11
+ @tool
12
+ def my_custom_tool(arg1: str, arg2: int) -> str: # è importante specificare il tipo di ritorno
13
+ """Uno strumento personalizzato che combina una stringa e un numero
14
+ Argomenti:
15
+ arg1: una stringa da elaborare
16
+ arg2: un numero intero da utilizzare come parametro
17
+ """
18
+ result = f"Input elaborato: {arg1} ripetuto {arg2} volte = {arg1 * arg2}"
19
+ return result
20
 
21
+ @tool
22
+ def get_current_time_in_timezone(timezone: str) -> str:
23
+ """Uno strumento che recupera l'ora locale corrente in un fuso orario specificato.
24
  Argomenti:
25
+ timezone: una stringa che rappresenta un fuso orario valido (ad esempio, 'America/New_York').
 
26
  """
27
+ try:
28
+ # Crea oggetto fuso orario
29
+ tz = pytz.timezone(timezone)
30
+ # Ottieni l'ora corrente in quel fuso orario
31
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
+ return f"L'ora locale corrente in {timezone} è: {local_time}"
33
+ except Exception as e:
34
+ return f"Errore durante il recupero dell'ora per il fuso orario '{timezone}': {str(e)}"
35
 
36
+ @tool
37
+ def analyze_sentiment(text: str) -> str:
38
+ """Analizza il sentimento di un testo fornito.
39
+ Argomenti:
40
+ text: il testo da analizzare
41
+ """
42
+ try:
43
+ # Implementazione semplificata, in produzione utilizzare una libreria NLP come transformers
44
+ positive_words = ["buono", "ottimo", "eccellente", "felice", "positivo", "meraviglioso"]
45
+ negative_words = ["cattivo", "terribile", "triste", "negativo", "pessimo", "orribile"]
46
+
47
+ text_lower = text.lower()
48
+ positive_count = sum(1 for word in positive_words if word in text_lower)
49
+ negative_count = sum(1 for word in negative_words if word in text_lower)
50
+
51
+ if positive_count > negative_count:
52
+ sentiment = "positivo"
53
+ elif negative_count > positive_count:
54
+ sentiment = "negativo"
55
+ else:
56
+ sentiment = "neutro"
57
+
58
+ return f"Analisi del sentimento: {sentiment} (parole positive: {positive_count}, parole negative: {negative_count})"
59
+ except Exception as e:
60
+ return f"Errore durante l'analisi del sentimento: {str(e)}"
61
 
62
+ @tool
63
+ def extract_entities(text: str) -> str:
64
+ """Estrae entità come nomi, luoghi e organizzazioni da un testo.
65
  Argomenti:
66
+ text: il testo da cui estrarre le entità
67
+ """
68
+ try:
69
+ # Implementazione semplificata, in produzione utilizzare spaCy o Hugging Face transformers
70
+ common_names = ["Mario", "Luigi", "Giovanni", "Maria", "Anna", "Giuseppe"]
71
+ common_places = ["Roma", "Milano", "Napoli", "Firenze", "Venezia", "Italia"]
72
+ common_orgs = ["Google", "Microsoft", "Apple", "Amazon", "Facebook", "Twitter"]
73
+
74
+ text_words = text.split()
75
+ names = [word for word in text_words if word in common_names]
76
+ places = [word for word in text_words if word in common_places]
77
+ orgs = [word for word in text_words if word in common_orgs]
78
+
79
+ result = {
80
+ "nomi": names,
81
+ "luoghi": places,
82
+ "organizzazioni": orgs
83
+ }
84
+
85
+ return f"Entità estratte: {result}"
86
+ except Exception as e:
87
+ return f"Errore durante l'estrazione delle entità: {str(e)}"
88
+
89
+ @tool
90
+ def image_classification(image_url: str) -> str:
91
+ """Classifica un'immagine da un URL.
92
+ Argomenti:
93
+ image_url: URL dell'immagine da classificare
94
+ """
95
+ try:
96
+ # Simulazione di classificazione, in produzione utilizzare un modello di vision come ViT
97
+ if not image_url.startswith("http"):
98
+ return "Errore: fornire un URL valido che inizia con http:// o https://"
99
+
100
+ # Controlla se l'URL è accessibile
101
+ response = requests.head(image_url, timeout=5)
102
+ if response.status_code != 200:
103
+ return f"Errore: impossibile accedere all'URL dell'immagine (status code: {response.status_code})"
104
+
105
+ # Simuliamo la classificazione
106
+ if "dog" in image_url.lower() or "cane" in image_url.lower():
107
+ return "Classificazione immagine: Cane (probabilità: 0.92)"
108
+ elif "cat" in image_url.lower() or "gatto" in image_url.lower():
109
+ return "Classificazione immagine: Gatto (probabilità: 0.89)"
110
+ else:
111
+ return "Classificazione immagine: Oggetto generico (probabilità: 0.75)"
112
  except Exception as e:
113
+ return f"Errore durante la classificazione dell'immagine: {str(e)}"
114
 
115
+ @tool
116
+ def translate_text(text: str, target_language: str) -> str:
117
+ """Traduce un testo in una lingua di destinazione.
118
+ Argomenti:
119
+ text: il testo da tradurre
120
+ target_language: la lingua di destinazione (es. 'en', 'fr', 'es', 'de')
121
+ """
122
+ try:
123
+ # Implementazione semplificata, in produzione utilizzare API come Google Translate o modelli NLP
124
+ language_map = {
125
+ 'en': 'inglese',
126
+ 'fr': 'francese',
127
+ 'es': 'spagnolo',
128
+ 'de': 'tedesco',
129
+ 'it': 'italiano'
130
+ }
131
+
132
+ if target_language not in language_map:
133
+ return f"Errore: lingua di destinazione '{target_language}' non supportata. Lingue supportate: {', '.join(language_map.keys())}"
134
+
135
+ return f"Testo tradotto in {language_map.get(target_language, target_language)}: [Simulazione di traduzione per '{text}']"
136
+ except Exception as e:
137
+ return f"Errore durante la traduzione: {str(e)}"
138
 
139
+ @tool
140
+ def summarize_text(text: str, max_length: int = 100) -> str:
141
+ """Riassume un testo lungo in una versione più breve.
142
+ Argomenti:
143
+ text: il testo da riassumere
144
+ max_length: lunghezza massima del riassunto in caratteri (default: 100)
145
+ """
146
+ try:
147
+ if len(text) <= max_length:
148
+ return f"Il testo è già abbastanza breve: {text}"
149
+
150
+ # Implementazione semplificata, in produzione utilizzare un modello NLP
151
+ words = text.split()
152
+ sentences = []
153
+ current_sentence = []
154
+
155
+ for word in words:
156
+ current_sentence.append(word)
157
+ if word.endswith('.') or word.endswith('!') or word.endswith('?'):
158
+ sentences.append(' '.join(current_sentence))
159
+ current_sentence = []
160
+
161
+ if current_sentence:
162
+ sentences.append(' '.join(current_sentence))
163
+
164
+ # Seleziona solo la prima frase o frasi fino al limite
165
+ summary = ""
166
+ for sentence in sentences:
167
+ if len(summary + sentence) <= max_length:
168
+ summary += sentence + " "
169
+ else:
170
+ break
171
+
172
+ return f"Riassunto: {summary.strip()}"
173
+ except Exception as e:
174
+ return f"Errore durante il riassunto del testo: {str(e)}"
175
+
176
+ final_answer = FinalAnswerTool()
177
+ search_tool = DuckDuckGoSearchTool()
178
 
179
+ model = HfApiModel(
180
+ max_tokens=2096,
181
+ temperature=0.5,
182
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruction',
183
+ custom_role_conversions=None,
184
+ )
185
 
186
  # Strumento di importazione dall'hub
187
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
188
 
189
+ with open("prompts.yaml", 'r') as stream:
190
+ prompt_templates = yaml.safe_load(stream)
191
 
192
+ agent = CodeAgent(
193
+ model=model,
194
+ tools=[
195
+ final_answer,
196
+ my_custom_tool,
197
+ get_current_time_in_timezone,
198
+ analyze_sentiment,
199
+ extract_entities,
200
+ image_classification,
201
+ translate_text,
202
+ summarize_text,
203
+ search_tool,
204
+ image_generation_tool
205
+ ],
206
+ max_steps=6,
207
+ verbosity_level=1,
208
+ grammar=None,
209
+ planning_interval=None,
210
+ name="AssistenteNLPCV",
211
+ description="Un assistente AI specializzato in NLP e Computer Vision con capacità di ricerca e generazione di immagini",
212
+ prompt_templates=prompt_templates
213
  )
214
 
215
+ GradioUI(agent).launch()