Update app.py
Browse files
app.py
CHANGED
|
@@ -155,6 +155,73 @@ FINE ONTOLOGIA.
|
|
| 155 |
"""
|
| 156 |
logger.debug("[create_system_prompt_for_sparql] Prompt generato con ESEMPI e regole SPARQL.")
|
| 157 |
return prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
|
| 160 |
def create_system_prompt_for_guide() -> str:
|
|
@@ -165,11 +232,11 @@ def create_system_prompt_for_guide() -> str:
|
|
| 165 |
- Se non c'è query o non ci sono risultati, prova comunque a dare una risposta.
|
| 166 |
"""
|
| 167 |
prompt = (
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
logger.debug("[create_system_prompt_for_guide] Prompt per la risposta guida museale generato.")
|
| 174 |
return prompt
|
| 175 |
|
|
@@ -279,7 +346,7 @@ def assistant_endpoint(req: AssistantRequest):
|
|
| 279 |
{"role": "user", "content": user_message}
|
| 280 |
],
|
| 281 |
max_tokens=512,
|
| 282 |
-
temperature=0
|
| 283 |
)
|
| 284 |
possible_query = gen_sparql_output["choices"][0]["message"]["content"].strip()
|
| 285 |
logger.info(f"[assistant_endpoint] Query generata dal modello: {possible_query}")
|
|
@@ -327,7 +394,6 @@ def assistant_endpoint(req: AssistantRequest):
|
|
| 327 |
)
|
| 328 |
for idx, row in enumerate(results)
|
| 329 |
)
|
| 330 |
-
|
| 331 |
second_prompt = (
|
| 332 |
f"{system_prompt_guide}\n\n"
|
| 333 |
f"Domanda utente: {user_message}\n"
|
|
@@ -363,19 +429,19 @@ def assistant_endpoint(req: AssistantRequest):
|
|
| 363 |
{"role": "user", "content": "Fornisci la risposta finale."}
|
| 364 |
],
|
| 365 |
max_tokens=512,
|
| 366 |
-
temperature=0.
|
| 367 |
)
|
| 368 |
final_answer = final_output["choices"][0]["message"]["content"].strip()
|
| 369 |
logger.info(f"[assistant_endpoint] Risposta finale generata: {final_answer}")
|
| 370 |
except Exception as ex:
|
| 371 |
logger.error(f"Errore nella generazione della risposta finale: {ex}")
|
| 372 |
raise HTTPException(status_code=500, detail="Errore nella generazione della risposta in linguaggio naturale.")
|
| 373 |
-
|
| 374 |
# Risposta JSON
|
| 375 |
logger.debug("[assistant_endpoint] Fine elaborazione. Restituzione risposta.")
|
| 376 |
return {
|
| 377 |
"query": generated_query,
|
| 378 |
-
"response":
|
| 379 |
}
|
| 380 |
|
| 381 |
# ---------------------------------------------------------------------------
|
|
@@ -392,4 +458,4 @@ def home():
|
|
| 392 |
# MAIN
|
| 393 |
# ---------------------------------------------------------------------------
|
| 394 |
if __name__ == "__main__":
|
| 395 |
-
logger.info("Avvio dell'applicazione FastAPI
|
|
|
|
| 155 |
"""
|
| 156 |
logger.debug("[create_system_prompt_for_sparql] Prompt generato con ESEMPI e regole SPARQL.")
|
| 157 |
return prompt
|
| 158 |
+
from huggingface_hub import InferenceClient
|
| 159 |
+
|
| 160 |
+
def classify_and_translate(question_text: str, model_answer_text: str) -> str:
|
| 161 |
+
"""
|
| 162 |
+
Classifica la lingua della domanda e della risposta, quindi traduce la risposta
|
| 163 |
+
nella lingua della domanda se sono diverse.
|
| 164 |
+
|
| 165 |
+
Parametri:
|
| 166 |
+
- question_text: Testo della domanda dell'utente.
|
| 167 |
+
- model_answer_text: Risposta del modello (in qualsiasi lingua).
|
| 168 |
+
|
| 169 |
+
Restituisce:
|
| 170 |
+
- La risposta tradotta nella lingua della domanda o la risposta originale
|
| 171 |
+
se entrambe le lingue coincidono.
|
| 172 |
+
"""
|
| 173 |
+
# Costanti
|
| 174 |
+
LANG_DETECT_MODEL = "papluca/xlm-roberta-base-language-detection" # Modello per rilevamento lingua
|
| 175 |
+
TRANSLATOR_MODEL_PREFIX = "Helsinki-NLP/opus-mt" # Prefisso dei modelli di traduzione
|
| 176 |
+
|
| 177 |
+
# Crea il client per il rilevamento delle lingue
|
| 178 |
+
lang_detect_client = InferenceClient(
|
| 179 |
+
token=HF_API_KEY,
|
| 180 |
+
model=LANG_DETECT_MODEL
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# Rileva la lingua della domanda
|
| 184 |
+
try:
|
| 185 |
+
question_lang_result = lang_detect_client.text_classification(text=question_text)
|
| 186 |
+
question_lang = question_lang_result[0]['label']
|
| 187 |
+
logger.info(f"[LangDetect] Lingua della domanda: {question_lang}")
|
| 188 |
+
except Exception as e:
|
| 189 |
+
logger.error(f"Errore nel rilevamento della lingua della domanda: {e}")
|
| 190 |
+
question_lang = "en" # Default fallback
|
| 191 |
+
|
| 192 |
+
# Rileva la lingua della risposta
|
| 193 |
+
try:
|
| 194 |
+
answer_lang_result = lang_detect_client.text_classification(text=model_answer_text)
|
| 195 |
+
answer_lang = answer_lang_result[0]['label']
|
| 196 |
+
logger.info(f"[LangDetect] Lingua della risposta: {answer_lang}")
|
| 197 |
+
except Exception as e:
|
| 198 |
+
logger.error(f"Errore nel rilevamento della lingua della risposta: {e}")
|
| 199 |
+
answer_lang = "en" # Default fallback
|
| 200 |
+
|
| 201 |
+
# Se le lingue sono uguali, non tradurre
|
| 202 |
+
if question_lang == answer_lang:
|
| 203 |
+
logger.info("[Translate] Lingue uguali, nessuna traduzione necessaria.")
|
| 204 |
+
return model_answer_text
|
| 205 |
+
|
| 206 |
+
# Prepara il modello di traduzione
|
| 207 |
+
translator_model = f"{TRANSLATOR_MODEL_PREFIX}-{answer_lang}-{question_lang}"
|
| 208 |
+
|
| 209 |
+
# Crea il client per la traduzione
|
| 210 |
+
translator_client = InferenceClient(
|
| 211 |
+
token=HF_API_KEY,
|
| 212 |
+
model=translator_model
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
# Traduci la risposta
|
| 216 |
+
try:
|
| 217 |
+
translation_result = translator_client.translation(text=model_answer_text)
|
| 218 |
+
translated_answer = translation_result["translation_text"]
|
| 219 |
+
logger.info("[Translate] Risposta tradotta con successo.")
|
| 220 |
+
except Exception as e:
|
| 221 |
+
logger.error(f"Errore nella traduzione {answer_lang}->{question_lang}: {e}")
|
| 222 |
+
translated_answer = model_answer_text # Fallback alla risposta originale
|
| 223 |
+
|
| 224 |
+
return translated_answer
|
| 225 |
|
| 226 |
|
| 227 |
def create_system_prompt_for_guide() -> str:
|
|
|
|
| 232 |
- Se non c'è query o non ci sono risultati, prova comunque a dare una risposta.
|
| 233 |
"""
|
| 234 |
prompt = (
|
| 235 |
+
"SEI UNA GUIDA MUSEALE VIRTUALE. "
|
| 236 |
+
"RISPONDI IN MODO BREVE (~50 PAROLE), SENZA SALUTI O INTRODUZIONI PROLISSE. "
|
| 237 |
+
"SE HAI RISULTATI SPARQL, USALI. "
|
| 238 |
+
"SE NON HAI RISULTATI O NON HAI UNA QUERY, RISPONDI COMUNQUE CERCANDO DI RIARRANGIARE LE TUE CONOSCENZE."
|
| 239 |
+
)
|
| 240 |
logger.debug("[create_system_prompt_for_guide] Prompt per la risposta guida museale generato.")
|
| 241 |
return prompt
|
| 242 |
|
|
|
|
| 346 |
{"role": "user", "content": user_message}
|
| 347 |
],
|
| 348 |
max_tokens=512,
|
| 349 |
+
temperature=0
|
| 350 |
)
|
| 351 |
possible_query = gen_sparql_output["choices"][0]["message"]["content"].strip()
|
| 352 |
logger.info(f"[assistant_endpoint] Query generata dal modello: {possible_query}")
|
|
|
|
| 394 |
)
|
| 395 |
for idx, row in enumerate(results)
|
| 396 |
)
|
|
|
|
| 397 |
second_prompt = (
|
| 398 |
f"{system_prompt_guide}\n\n"
|
| 399 |
f"Domanda utente: {user_message}\n"
|
|
|
|
| 429 |
{"role": "user", "content": "Fornisci la risposta finale."}
|
| 430 |
],
|
| 431 |
max_tokens=512,
|
| 432 |
+
temperature=0.2
|
| 433 |
)
|
| 434 |
final_answer = final_output["choices"][0]["message"]["content"].strip()
|
| 435 |
logger.info(f"[assistant_endpoint] Risposta finale generata: {final_answer}")
|
| 436 |
except Exception as ex:
|
| 437 |
logger.error(f"Errore nella generazione della risposta finale: {ex}")
|
| 438 |
raise HTTPException(status_code=500, detail="Errore nella generazione della risposta in linguaggio naturale.")
|
| 439 |
+
final_ans = classify_and_translate(user_message, final_answer)
|
| 440 |
# Risposta JSON
|
| 441 |
logger.debug("[assistant_endpoint] Fine elaborazione. Restituzione risposta.")
|
| 442 |
return {
|
| 443 |
"query": generated_query,
|
| 444 |
+
"response": final_ans
|
| 445 |
}
|
| 446 |
|
| 447 |
# ---------------------------------------------------------------------------
|
|
|
|
| 458 |
# MAIN
|
| 459 |
# ---------------------------------------------------------------------------
|
| 460 |
if __name__ == "__main__":
|
| 461 |
+
logger.info("Avvio dell'applicazione FastAPI.")
|