Spaces:
Sleeping
Sleeping
Upload 5 files
Browse files- .gitattributes +1 -0
- Marianna.py +391 -0
- dati_per_database_riassunti.pkl +3 -0
- legends.pkl +3 -0
- marianna-102.jpeg +3 -0
- requirements.txt +3 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
marianna-102.jpeg filter=lfs diff=lfs merge=lfs -text
|
Marianna.py
ADDED
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import random
|
3 |
+
import pickle
|
4 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder, util
|
5 |
+
import os # Importa il modulo os
|
6 |
+
from google.colab import drive
|
7 |
+
|
8 |
+
|
9 |
+
class MariannaBot:
|
10 |
+
def __init__(self):
|
11 |
+
self.data_path_main = "dati_per_database_riassunti.pkl"
|
12 |
+
self.data_path_legends = "legends.pkl"
|
13 |
+
|
14 |
+
print("Inizializzazione di MariannaBot (senza DB)...") # Debug
|
15 |
+
|
16 |
+
self.database = self.load_data_from_pickle(self.data_path_main)
|
17 |
+
self.database_legends = self.load_data_from_pickle(self.data_path_legends)
|
18 |
+
self.database = self.database + self.database_legends
|
19 |
+
|
20 |
+
self.db_keys = [el[0] for el in self.database] if isinstance(self.database, list) else []
|
21 |
+
self.db_keys_legends = [el[0] for el in self.database] if isinstance(self.database, list) else []
|
22 |
+
# print("Chiavi principali caricate:", len(self.db_keys)) # Debug
|
23 |
+
# print("Chiavi leggende caricate:", len(self.db_keys_legends)) # Debug
|
24 |
+
|
25 |
+
self.query_dic = self.load_queries_dataset()
|
26 |
+
self.query_dic_keys = list(self.query_dic.keys())
|
27 |
+
# print("dataset query inziali caricato: ", len(self.query_dic))
|
28 |
+
|
29 |
+
self.reset_state()
|
30 |
+
|
31 |
+
def load_queries_dataset(self):
|
32 |
+
"""Loads queries dataset"""
|
33 |
+
return {"si, certo, certamente, ok, assolutamente si, sicuro, sisi":"si","no, non ho domande, non mi interessa, niente, nulla":"no","non so, scegli tu, fai tu, casuale, lascio a te, decidi tu, pensaci tu, sorprendimi":"non so","stronzo, vaffanculo, ti odio, pezzo di merda, cazzo":"parolacce"}
|
34 |
+
|
35 |
+
def load_data_from_pickle(self, file_path):
|
36 |
+
"""Loads data from a pickle file."""
|
37 |
+
try:
|
38 |
+
with open(file_path, 'rb') as f:
|
39 |
+
data = pickle.load(f)
|
40 |
+
print(f"Dati caricati da: {file_path}") # Debug
|
41 |
+
return data
|
42 |
+
except FileNotFoundError:
|
43 |
+
print(f"Errore: File non trovato: {file_path}")
|
44 |
+
return []
|
45 |
+
except Exception as e:
|
46 |
+
print(f"Errore durante il caricamento da pickle {file_path}: {e}")
|
47 |
+
return []
|
48 |
+
|
49 |
+
def initialize_encoder(self):
|
50 |
+
"""
|
51 |
+
Initialize encoder and cross-encoder model.
|
52 |
+
"""
|
53 |
+
try:
|
54 |
+
# Initialize the encoder model
|
55 |
+
encoder_model = "nickprock/sentence-bert-base-italian-xxl-uncased"
|
56 |
+
cross_encoder_model = "nickprock/cross-encoder-italian-bert-stsb"
|
57 |
+
self.encoder = SentenceTransformer(encoder_model)
|
58 |
+
self.cross_encoder = CrossEncoder(cross_encoder_model)
|
59 |
+
|
60 |
+
# Pre-encode all database keys
|
61 |
+
self.db_keys_embeddings = self.encoder.encode(self.db_keys, convert_to_tensor=True)
|
62 |
+
self.db_keys_legends_embeddings = self.encoder.encode(self.db_keys_legends, convert_to_tensor=True)
|
63 |
+
self.first_query_emb = self.encoder.encode(self.query_dic_keys, convert_to_tensor=True)
|
64 |
+
|
65 |
+
print(f"Encoder initialized with {len(self.db_keys)} keys.")
|
66 |
+
return True
|
67 |
+
except Exception as e:
|
68 |
+
print(f"Error initializing encoder: {str(e)}")
|
69 |
+
return False
|
70 |
+
|
71 |
+
def reset_state(self):
|
72 |
+
self.state = "initial"
|
73 |
+
self.welcome_sent = False
|
74 |
+
self.current_further_info_values = []
|
75 |
+
self.current_index = 0
|
76 |
+
self.main_k = []
|
77 |
+
self.is_telling_stories = False
|
78 |
+
|
79 |
+
def get_welcome_message(self):
|
80 |
+
return random.choice(["""Ciao, benvenuto!\n\nSono Marianna, la testa di Napoli, in napoletano 'a capa 'e Napule, una statua ritrovata per caso nel 1594. \nAll'epoca del mio ritrovamento, si pensò che fossi una rappresentazione della sirena Partenope, dalle cui spoglie, leggenda narra, nacque la città di Napoli. In seguito, diversi studiosi riconobbero in me una statua della dea Venere, probabilmente collocata in uno dei tanti templi che si trovavano nella città in epoca tardo-romana, quando ancora si chiamava Neapolis.
|
81 |
+
\nPosso raccontarti molte storie sulla città di Napoli e mostrarti le sue bellezze. \nC'è qualcosa in particolare che ti interessa?""","""Benvenuto!\nIo mi chiamo Marianna, 'a capa 'e Napule. Sono stata ritrovata casualmente nel 1594 a Napoli. All'epoca si pensava che fossi una rappresentazione della Sirena Partenope, dalle cui spoglie, secondo la leggenda, nacque la città di Napoli. In seguito, gli archeologi mi riconobbero come una statua della dea Venere, collocata, probabilmente, in uno dei templi della città di Neapolis in epoca tardo-romana.\nConosco molte storie e leggende di Napoli e posso illustrarti le sue bellezze. \nCosa ti interessa in particolare?"""])
|
82 |
+
|
83 |
+
def get_safe_example_keys(self, num_examples=3):
|
84 |
+
"""Safely get example keys from the loaded data."""
|
85 |
+
if not self.db_keys:
|
86 |
+
return []
|
87 |
+
return random.sample(self.db_keys, min(len(self.db_keys), num_examples))
|
88 |
+
|
89 |
+
def story_flow(self):
|
90 |
+
"""Gestisce la selezione casuale di una storia dai dati delle leggende."""
|
91 |
+
if not self.database_legends:
|
92 |
+
return random.choice(["Mi dispiace, al momento non ho leggende da raccontare.","Ti ho già raccontato tutte le leggende di cui sono a conoscenza!","Emmmm... Non mi viene in mente altro al momento, posso parlarti di altro?"])
|
93 |
+
|
94 |
+
available_topics = [item[0] for item in self.database_legends if item[0] not in self.main_k]
|
95 |
+
|
96 |
+
if not available_topics:
|
97 |
+
self.main_k = [] # Reset della lista delle storie raccontate
|
98 |
+
available_topics = [item[0] for item in self.database_legends]
|
99 |
+
|
100 |
+
if not available_topics:
|
101 |
+
return random.choice(["Sembra che tu abbia già ascoltato tutte le storie!","Ti ho già raccontato tutte le leggende di cui sono a conoscenza!","Emmmm... Non mi viene in mente altro al momento, posso parlarti di altro?"])
|
102 |
+
|
103 |
+
random_story_tuple = random.choice([item for item in self.database_legends if item[0] in available_topics])
|
104 |
+
topic = random_story_tuple[0]
|
105 |
+
content = random_story_tuple[1]['intro'] if 'intro' in random_story_tuple[1] else None
|
106 |
+
|
107 |
+
if not content:
|
108 |
+
return f"Mi dispiace, non ho trovato un'introduzione per la leggenda '{topic}'."
|
109 |
+
|
110 |
+
self.main_k.append(topic)
|
111 |
+
self.state = "follow_up"
|
112 |
+
self.is_telling_stories = True
|
113 |
+
|
114 |
+
return random.choice([f"Ok, lascia che ti racconti de '{topic}'.\n\n{content}\n\nVuoi che ti racconti un'altra storia?",f"Ora ti parlerò di {topic}!\n\n{content}\n\nPosso raccontarti un'altra storia?"])
|
115 |
+
|
116 |
+
def get_legend_content(self, key):
|
117 |
+
"""Helper function to get the content for a legend key."""
|
118 |
+
# Se self.database_legends è una lista di stringhe (le chiavi),
|
119 |
+
# potresti aver bisogno di caricare il contenuto da un altro file
|
120 |
+
# o averlo pre-caricato in un'altra struttura dati.
|
121 |
+
# Al momento, restituisco None, dovresti implementare la logica
|
122 |
+
# per recuperare il contenuto effettivo.
|
123 |
+
return self.database_legends.get(key) if isinstance(self.database_legends, dict) else None
|
124 |
+
|
125 |
+
def get_value(self, key):
|
126 |
+
"""Retrieve a value from the loaded main data by key."""
|
127 |
+
for k, v in self.database:
|
128 |
+
if k == key:
|
129 |
+
return v
|
130 |
+
return None
|
131 |
+
|
132 |
+
|
133 |
+
|
134 |
+
def handle_query(self, message):
|
135 |
+
"""Handle user queries by searching the database"""
|
136 |
+
try:
|
137 |
+
# Encode the user query
|
138 |
+
query_embedding = self.encoder.encode(message, convert_to_tensor=True)
|
139 |
+
|
140 |
+
# Perform semantic search on the keys
|
141 |
+
semantic_hits = util.semantic_search(query_embedding, self.db_keys_embeddings, top_k=3)
|
142 |
+
semantic_hits = semantic_hits[0]
|
143 |
+
|
144 |
+
cross_inp = [(message, self.db_keys[hit['corpus_id']]) for hit in semantic_hits]
|
145 |
+
cross_scores = self.cross_encoder.predict(cross_inp)
|
146 |
+
|
147 |
+
reranked_hits = sorted(
|
148 |
+
[{'corpus_id': hit['corpus_id'], 'cross-score': score}
|
149 |
+
for hit, score in zip(semantic_hits, cross_scores)],
|
150 |
+
key=lambda x: x['cross-score'], reverse=True
|
151 |
+
)
|
152 |
+
|
153 |
+
best_hit = reranked_hits[0]
|
154 |
+
best_title = self.db_keys[best_hit['corpus_id']]
|
155 |
+
best_score = best_hit['cross-score']
|
156 |
+
# print(best_title, best_score)
|
157 |
+
|
158 |
+
# Main treshold = 0.75
|
159 |
+
similarity_threshold = 0.75
|
160 |
+
|
161 |
+
# treshold granularity
|
162 |
+
if best_score < similarity_threshold:
|
163 |
+
# low confidence (< 0.35)
|
164 |
+
if best_score < 0.55:
|
165 |
+
return random.choice(["Mi dispiace, non ho informazioni su questo argomento. Puoi chiedermi di altro sulla città di Napoli.",
|
166 |
+
"Purtroppo non riesco a rammentare altro su questo argomento, la mia memoria non è più quella di un tempo. Chiedimi qualcos'altro su Napoli e le sue bellezze!",
|
167 |
+
"Mi dispiace tantissimo, ma non riesco a ricordare altro. Vuoi chiedermi altro sulla città di Napoli?"])
|
168 |
+
|
169 |
+
# medium confidence(0.55 - 0.75)
|
170 |
+
else:
|
171 |
+
alternative_hits = [self.db_keys[hit['corpus_id']] for hit in reranked_hits[:2]]
|
172 |
+
suggestions = ", ".join(alternative_hits)
|
173 |
+
value = self.get_value(best_title)
|
174 |
+
if value:
|
175 |
+
partial_info = value.get('short_intro', value.get('intro', '').split('.')[0] + '.')
|
176 |
+
self.state = "query"
|
177 |
+
self.is_telling_stories = False
|
178 |
+
return random.choice([f"Potrei avere alcune informazioni su {best_title}, ma non sono completamente sicura sia ciò che stai cercando. I miei suggerimenti sono {suggestions}. \n\nCosa ti interessa?",
|
179 |
+
f"Credo che tu stia parlando de {best_title}, ma per essere sicura di ciò che vuoi sapere, potresti specificare se parli di {suggestions}?",
|
180 |
+
f"Per assicurarmi di aver capito bene, vuoi che ti parli di {suggestions}?"])
|
181 |
+
else:
|
182 |
+
return f"Ho trovato qualcosa su {best_title}, ma non sono completamente sicura. Vuoi saperne di più?"
|
183 |
+
|
184 |
+
# high confidence (above the threshold)
|
185 |
+
if best_title is not None:
|
186 |
+
value = self.get_value(best_title)
|
187 |
+
|
188 |
+
if value:
|
189 |
+
key = best_title
|
190 |
+
self.main_k.append(key)
|
191 |
+
self.state = "follow_up"
|
192 |
+
self.is_telling_stories = False
|
193 |
+
response = value.get('intro', '')
|
194 |
+
if isinstance(value, dict):
|
195 |
+
self.current_further_info_values = list(value.get('further_info', {}).values())
|
196 |
+
else:
|
197 |
+
self.current_further_info_values = [] # Se il valore non è un dizionario
|
198 |
+
self.current_index = 0
|
199 |
+
return f"{response}\n\nVuoi sapere altro su {self.main_k[-1]}?"
|
200 |
+
else:
|
201 |
+
return random.choice(["Mi dispiace, non ho informazioni su questo argomento. Puoi chiedermi di altro sulla città di Napoli.",
|
202 |
+
"Purtroppo non riesco a rammentare altro su questo argomento, la mia memoria non è più quella di un tempo. Chiedimi qualcos'altro su Napoli e le sue bellezze!",
|
203 |
+
"Mi dispiace tantissimo, ma non riesco a ricordare altro. Vuoi chiedermi altro sulla città di Napoli?"])
|
204 |
+
|
205 |
+
except Exception as e:
|
206 |
+
print(e)
|
207 |
+
self.state = "initial"
|
208 |
+
return random.choice(["Mi dispiace, c'è stato un errore. Puoi riprovare con un'altra domanda? ",
|
209 |
+
"Scusami, sto facendo confusione. Puoi farmi un'altra domanda?",
|
210 |
+
"Mi dispiace, non ho capito. Puoi essere più preciso?"])
|
211 |
+
|
212 |
+
|
213 |
+
def first_query(self, message):
|
214 |
+
try:
|
215 |
+
# Encode the user query
|
216 |
+
query_embedding = self.encoder.encode(message, convert_to_tensor=True)
|
217 |
+
|
218 |
+
# Perform semantic search on the keys
|
219 |
+
semantic_hits = util.semantic_search(query_embedding, self.first_query_emb, top_k=4)
|
220 |
+
semantic_hits = semantic_hits[0]
|
221 |
+
print(semantic_hits)
|
222 |
+
cross_inp = [(message, self.query_dic_keys[hit['corpus_id']]) for hit in semantic_hits]
|
223 |
+
cross_scores = self.cross_encoder.predict(cross_inp)
|
224 |
+
reranked_hits = sorted(
|
225 |
+
[{'corpus_id': hit['corpus_id'], 'cross-score': score}
|
226 |
+
for hit, score in zip(semantic_hits, cross_scores)],
|
227 |
+
key=lambda x: x['cross-score'], reverse=True
|
228 |
+
)
|
229 |
+
best_hit = reranked_hits[0]
|
230 |
+
best_title = self.query_dic[self.query_dic_keys[best_hit['corpus_id']]]
|
231 |
+
best_score = best_hit['cross-score']
|
232 |
+
print(best_title, best_score)
|
233 |
+
# Main treshold = 0.75
|
234 |
+
similarity_threshold = 0.35
|
235 |
+
|
236 |
+
# treshold granularity
|
237 |
+
if best_score < similarity_threshold:
|
238 |
+
if message == "no":
|
239 |
+
value = "no"
|
240 |
+
return value
|
241 |
+
elif message == "si":
|
242 |
+
value = "si"
|
243 |
+
return value
|
244 |
+
else:
|
245 |
+
value='query'
|
246 |
+
return value
|
247 |
+
else:
|
248 |
+
value = best_title
|
249 |
+
|
250 |
+
return value
|
251 |
+
except Exception as e:
|
252 |
+
print(e)
|
253 |
+
self.state = "initial"
|
254 |
+
return random.choice(["Mi dispiace, c'è stato un errore. Puoi riprovare con un'altra domanda? ",
|
255 |
+
"Scusami, sto facendo confusione. Puoi farmi un'altra domanda?",
|
256 |
+
"Mi dispiace, non ho capito. Puoi essere più preciso?"])
|
257 |
+
|
258 |
+
|
259 |
+
def respond(self, message, history):
|
260 |
+
if not message:
|
261 |
+
return random.choice(["Mi dispiace, c'è stato un errore. Puoi riprovare con un'altra domanda? ",
|
262 |
+
"Scusami, sto facendo confusione. Puoi farmi un'altra domanda?",
|
263 |
+
"Mi dispiace, non ho capito. Puoi essere più preciso?"])
|
264 |
+
|
265 |
+
message = message.lower().strip()
|
266 |
+
|
267 |
+
if self.state == "initial":
|
268 |
+
value=self.first_query(message)
|
269 |
+
print("analizzando il messaggio....")
|
270 |
+
if value == "si":
|
271 |
+
self.state = "query"
|
272 |
+
self.is_telling_stories = False
|
273 |
+
return random.choice(["Cosa vorresti sapere?","Di cosa posso parlarti?","Cosa ti interessa?","Chiedi pure quello che vuoi"])
|
274 |
+
elif value == "no":
|
275 |
+
self.state = "end"
|
276 |
+
return random.choice(["Va bene, grazie per aver parlato con me.","Ti ringrazio per aver parlato con me. A presto!","Spero di rivederti presto! Ciao!","È stato un piacere conversare con te, alla prossima!","Spero di esserti stata di aiuto. A presto!"])
|
277 |
+
elif value == "non so":
|
278 |
+
return self.story_flow()
|
279 |
+
elif value == "parolacce":
|
280 |
+
return random.choice(["Mi dispiace sentirtelo dire. Per favore, chiedimi qualcosa","Sono veramente mortificata. Vuoi chiedermi altro?","Sono molto triste. Forse un'altra domanda miglirerà le cose!"])
|
281 |
+
elif value == "query":
|
282 |
+
return self.handle_query(message)
|
283 |
+
else:
|
284 |
+
return "Scusa, non ho capito."
|
285 |
+
|
286 |
+
elif self.state == "query":
|
287 |
+
return self.handle_query(message)
|
288 |
+
|
289 |
+
elif self.state == "follow_up":
|
290 |
+
value=self.first_query(message)
|
291 |
+
if value == "si":
|
292 |
+
if self.is_telling_stories:
|
293 |
+
return self.story_flow()
|
294 |
+
elif self.current_further_info_values and self.current_index < len(self.current_further_info_values):
|
295 |
+
value = self.current_further_info_values[self.current_index]
|
296 |
+
self.current_index += 1
|
297 |
+
|
298 |
+
if self.current_index < len(self.current_further_info_values):
|
299 |
+
return f"{value}\n\nVuoi sapere altro su {self.main_k[-1]}?"
|
300 |
+
else:
|
301 |
+
self.state = "initial"
|
302 |
+
return f"{value}\n\nNon ho altre informazioni su {self.main_k[-1]}. Ti interessa qualcos'altro?"
|
303 |
+
else:
|
304 |
+
self.state = "initial"
|
305 |
+
return f"Non ho altre informazioni su {self.main_k[-1]}. Ti interessa qualcos'altro?"
|
306 |
+
|
307 |
+
elif value == "no":
|
308 |
+
self.state = "initial"
|
309 |
+
self.is_telling_stories = False
|
310 |
+
return random.choice(["C'è qualcos'altro che ti interessa?","Hai qualche altra domanda?","Vuoi sapere qualcos'altro?"])
|
311 |
+
elif value == "non so":
|
312 |
+
return self.story_flow()
|
313 |
+
elif value == "parolacce":
|
314 |
+
return random.choice(["Mi dispiace sentirtelo dire. Per favore, chiedimi qualcosa","Sono veramente mortificata. Vuoi chiedermi altro?","Sono molto triste. Forse un'altra domanda miglirerà le cose!"])
|
315 |
+
elif value == "query":
|
316 |
+
return self.handle_query(message)
|
317 |
+
else:
|
318 |
+
return "Scusa, non ho capito."
|
319 |
+
|
320 |
+
return random.choice(["Mi dispiace, c'è stato un errore. Puoi riprovare con un'altra domanda? ",
|
321 |
+
"Scusami, sto facendo confusione. Puoi farmi un'altra domanda?",
|
322 |
+
"Mi dispiace, non ho capito. Puoi essere più preciso?"])
|
323 |
+
|
324 |
+
|
325 |
+
|
326 |
+
|
327 |
+
def main():
|
328 |
+
bot = MariannaBot()
|
329 |
+
if not bot.initialize_encoder():
|
330 |
+
print("Failed to initialize encoder. Exiting.")
|
331 |
+
return # Exit if encoder initialization fails
|
332 |
+
|
333 |
+
def update_chatbot(message, history):
|
334 |
+
if not message.strip():
|
335 |
+
return history, ""
|
336 |
+
response = bot.respond(message, history)
|
337 |
+
return history + [{"role": "user", "content": message}, {"role": "assistant", "content": response}], ""
|
338 |
+
|
339 |
+
def reset_chat():
|
340 |
+
bot.reset_state()
|
341 |
+
return [{"role": "assistant", "content": bot.get_welcome_message()}], ""
|
342 |
+
|
343 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
|
344 |
+
with gr.Row():
|
345 |
+
gr.Markdown("## Chatta con Marianna - 'La Testa di Napoli'")
|
346 |
+
|
347 |
+
with gr.Row():
|
348 |
+
gr.Image("marianna-102.jpeg",
|
349 |
+
elem_id="marianna-image",
|
350 |
+
width=250)
|
351 |
+
|
352 |
+
chatbot = gr.Chatbot(
|
353 |
+
value=[{"role": "assistant", "content": bot.get_welcome_message()}],
|
354 |
+
height=500,
|
355 |
+
type="messages"
|
356 |
+
)
|
357 |
+
|
358 |
+
msg = gr.Textbox(
|
359 |
+
placeholder="Scrivi il tuo messaggio qui...",
|
360 |
+
container=False
|
361 |
+
)
|
362 |
+
|
363 |
+
with gr.Row():
|
364 |
+
clear = gr.Button("Clicca qui per ricominciare")
|
365 |
+
|
366 |
+
msg.submit(
|
367 |
+
update_chatbot,
|
368 |
+
[msg, chatbot],
|
369 |
+
[chatbot, msg]
|
370 |
+
)
|
371 |
+
|
372 |
+
clear.click(
|
373 |
+
reset_chat,
|
374 |
+
[],
|
375 |
+
[chatbot, msg]
|
376 |
+
)
|
377 |
+
|
378 |
+
# Get example keys safely
|
379 |
+
example_keys = bot.get_safe_example_keys()
|
380 |
+
if example_keys:
|
381 |
+
examples = [key for key in example_keys]
|
382 |
+
gr.Examples(
|
383 |
+
examples=examples,
|
384 |
+
inputs=msg
|
385 |
+
)
|
386 |
+
|
387 |
+
demo.launch(share=True, debug=True)
|
388 |
+
|
389 |
+
|
390 |
+
if __name__ == "__main__":
|
391 |
+
main()
|
dati_per_database_riassunti.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5ff2b91a3f03b2b6ad66519b19237714e98ecf0c4363f889d38af7c1738089b6
|
3 |
+
size 639226
|
legends.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:373dc3bf62ef74b755bd2da0e6edcabf30de9a45d71adab5a5820119d6011f3a
|
3 |
+
size 13565
|
marianna-102.jpeg
ADDED
![]() |
Git LFS Details
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
pickle
|
2 |
+
gradio
|
3 |
+
sentence-transformers
|