Update app.py
Browse files
app.py
CHANGED
|
@@ -7,7 +7,14 @@ from huggingface_hub import InferenceClient
|
|
| 7 |
from typing import Optional
|
| 8 |
|
| 9 |
# Configurazione logging
|
| 10 |
-
logging.basicConfig(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
# Configurazione API Hugging Face
|
|
@@ -29,6 +36,7 @@ def load_rdf_summary():
|
|
| 29 |
Carica un riassunto dell'ontologia dal file RDF.
|
| 30 |
Estrae le classi e le proprietà presenti nell'ontologia.
|
| 31 |
"""
|
|
|
|
| 32 |
if not os.path.exists(RDF_FILE):
|
| 33 |
logger.error("Nessun file RDF trovato.")
|
| 34 |
return "Nessun file RDF trovato."
|
|
@@ -47,13 +55,15 @@ def load_rdf_summary():
|
|
| 47 |
|
| 48 |
class_summary = "\n".join([f"- Classe: {cls}" for cls in classes])
|
| 49 |
prop_summary = "\n".join([f"- Proprietà: {prop}" for prop in properties])
|
| 50 |
-
|
|
|
|
|
|
|
| 51 |
except Exception as e:
|
| 52 |
logger.error(f"Errore durante il parsing del file RDF: {e}")
|
| 53 |
return "Errore nel caricamento del file RDF."
|
| 54 |
|
| 55 |
rdf_context = load_rdf_summary()
|
| 56 |
-
logger.info("RDF Summary
|
| 57 |
|
| 58 |
####################################
|
| 59 |
# Validazione SPARQL
|
|
@@ -62,10 +72,12 @@ def validate_sparql_query(query: str, rdf_file_path: str) -> bool:
|
|
| 62 |
"""
|
| 63 |
Verifica la validità della query SPARQL.
|
| 64 |
"""
|
|
|
|
| 65 |
g = Graph()
|
| 66 |
try:
|
| 67 |
g.parse(rdf_file_path, format="xml")
|
| 68 |
g.query(query) # Solleva un'eccezione se la query non è valida
|
|
|
|
| 69 |
return True
|
| 70 |
except Exception as e:
|
| 71 |
logger.error(f"Errore durante la validazione della query SPARQL: {e}")
|
|
@@ -121,6 +133,7 @@ async def call_model(messages, temperature=0.7, max_tokens=2048):
|
|
| 121 |
"""
|
| 122 |
Chiama il modello di linguaggio naturale con i messaggi forniti.
|
| 123 |
"""
|
|
|
|
| 124 |
try:
|
| 125 |
response = client.chat.completions.create(
|
| 126 |
model="Qwen/Qwen2.5-72B-Instruct",
|
|
@@ -131,10 +144,11 @@ async def call_model(messages, temperature=0.7, max_tokens=2048):
|
|
| 131 |
stream=False
|
| 132 |
)
|
| 133 |
raw_text = response["choices"][0]["message"]["content"]
|
|
|
|
| 134 |
# Rimuoviamo eventuali newline per forzare la singola riga
|
| 135 |
return raw_text.replace("\n", " ").strip()
|
| 136 |
except Exception as e:
|
| 137 |
-
logger.error(f"Errore
|
| 138 |
raise HTTPException(status_code=500, detail=str(e))
|
| 139 |
|
| 140 |
####################################
|
|
@@ -144,11 +158,14 @@ async def interpret_sparql_results(results):
|
|
| 144 |
"""
|
| 145 |
Invia i risultati delle query SPARQL al modello per ottenere una risposta naturale.
|
| 146 |
"""
|
|
|
|
| 147 |
if not results:
|
|
|
|
| 148 |
return "Mi dispiace, non sono riuscita a trovare le informazioni che stavi cercando."
|
| 149 |
|
| 150 |
# Converti i risultati in una stringa leggibile
|
| 151 |
results_str = "\n".join([", ".join([f"{k}: {v}" for k, v in row.asdict().items()]) for row in results])
|
|
|
|
| 152 |
|
| 153 |
# Crea un prompt per il modello per interpretare i risultati
|
| 154 |
interpret_prompt = f"""
|
|
@@ -157,13 +174,15 @@ Mi hai fornito i seguenti risultati di una query SPARQL:
|
|
| 157 |
|
| 158 |
Per favore, interpreta questi risultati e fornisci una risposta naturale ed enfatica come farebbe una guida museale femminile.
|
| 159 |
"""
|
| 160 |
-
|
| 161 |
messages = [
|
| 162 |
{"role": "system", "content": interpret_prompt},
|
| 163 |
{"role": "user", "content": ""}
|
| 164 |
]
|
| 165 |
|
|
|
|
| 166 |
natural_response = await call_model(messages, temperature=0.7, max_tokens=2048)
|
|
|
|
| 167 |
return natural_response
|
| 168 |
|
| 169 |
####################################
|
|
@@ -179,7 +198,8 @@ class QueryRequest(BaseModel):
|
|
| 179 |
@app.post("/generate-response/")
|
| 180 |
async def generate_response(request: QueryRequest):
|
| 181 |
user_msg = request.message
|
| 182 |
-
|
|
|
|
| 183 |
# 1) Generazione della risposta (SPARQL, INTERPRET o CHAT)
|
| 184 |
system_msg = create_system_message(rdf_context)
|
| 185 |
messages = [
|
|
@@ -187,35 +207,43 @@ async def generate_response(request: QueryRequest):
|
|
| 187 |
{"role": "user", "content": user_msg}
|
| 188 |
]
|
| 189 |
response_text = await call_model(messages, request.temperature, request.max_tokens)
|
|
|
|
| 190 |
logger.info(f"Risposta generata dal modello: {response_text}")
|
| 191 |
-
|
| 192 |
# 2) Determinazione se la risposta è una query SPARQL
|
| 193 |
if response_text.startswith("PREFIX base:"):
|
| 194 |
sparql_query = response_text
|
|
|
|
| 195 |
# Validazione della query SPARQL
|
| 196 |
if validate_sparql_query(sparql_query, RDF_FILE):
|
|
|
|
| 197 |
# Esegui la query su GraphDB
|
| 198 |
try:
|
| 199 |
g = Graph()
|
| 200 |
g.parse(RDF_FILE, format="xml")
|
| 201 |
results = g.query(sparql_query)
|
|
|
|
| 202 |
# Interpreta i risultati in una risposta naturale tramite il modello
|
| 203 |
interpreted_response = await interpret_sparql_results(results)
|
|
|
|
| 204 |
return {"type": "NATURAL", "response": interpreted_response}
|
| 205 |
except Exception as e:
|
| 206 |
logger.error(f"Errore durante l'esecuzione della query SPARQL: {e}")
|
| 207 |
return {"type": "ERROR", "response": "Mi dispiace, c'è stato un errore nell'esecuzione della tua richiesta."}
|
| 208 |
else:
|
|
|
|
| 209 |
return {"type": "ERROR", "response": "La query SPARQL generata non è valida. Per favore, riprova con una domanda diversa."}
|
| 210 |
|
| 211 |
elif "Non posso generare una query SPARQL" in response_text:
|
| 212 |
# Risposta di errore dal modello
|
|
|
|
| 213 |
return {"type": "ERROR", "response": response_text}
|
| 214 |
|
| 215 |
else:
|
| 216 |
# Presumiamo che sia una risposta naturale o una chat
|
|
|
|
| 217 |
return {"type": "NATURAL", "response": response_text}
|
| 218 |
|
| 219 |
@app.get("/")
|
| 220 |
async def root():
|
| 221 |
-
return {"message": "Server attivo e pronto a generare risposte!"}
|
|
|
|
| 7 |
from typing import Optional
|
| 8 |
|
| 9 |
# Configurazione logging
|
| 10 |
+
logging.basicConfig(
|
| 11 |
+
level=logging.INFO,
|
| 12 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 13 |
+
handlers=[
|
| 14 |
+
logging.FileHandler("app.log"),
|
| 15 |
+
logging.StreamHandler()
|
| 16 |
+
]
|
| 17 |
+
)
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
| 20 |
# Configurazione API Hugging Face
|
|
|
|
| 36 |
Carica un riassunto dell'ontologia dal file RDF.
|
| 37 |
Estrae le classi e le proprietà presenti nell'ontologia.
|
| 38 |
"""
|
| 39 |
+
logger.info("Inizio caricamento del file RDF.")
|
| 40 |
if not os.path.exists(RDF_FILE):
|
| 41 |
logger.error("Nessun file RDF trovato.")
|
| 42 |
return "Nessun file RDF trovato."
|
|
|
|
| 55 |
|
| 56 |
class_summary = "\n".join([f"- Classe: {cls}" for cls in classes])
|
| 57 |
prop_summary = "\n".join([f"- Proprietà: {prop}" for prop in properties])
|
| 58 |
+
summary = f"Classi:\n{class_summary}\n\nProprietà:\n{prop_summary}"
|
| 59 |
+
logger.info("Caricamento RDF completato con successo.")
|
| 60 |
+
return summary
|
| 61 |
except Exception as e:
|
| 62 |
logger.error(f"Errore durante il parsing del file RDF: {e}")
|
| 63 |
return "Errore nel caricamento del file RDF."
|
| 64 |
|
| 65 |
rdf_context = load_rdf_summary()
|
| 66 |
+
logger.info(f"RDF Summary:\n{rdf_context}")
|
| 67 |
|
| 68 |
####################################
|
| 69 |
# Validazione SPARQL
|
|
|
|
| 72 |
"""
|
| 73 |
Verifica la validità della query SPARQL.
|
| 74 |
"""
|
| 75 |
+
logger.info("Inizio validazione della query SPARQL.")
|
| 76 |
g = Graph()
|
| 77 |
try:
|
| 78 |
g.parse(rdf_file_path, format="xml")
|
| 79 |
g.query(query) # Solleva un'eccezione se la query non è valida
|
| 80 |
+
logger.info("Validazione della query SPARQL riuscita.")
|
| 81 |
return True
|
| 82 |
except Exception as e:
|
| 83 |
logger.error(f"Errore durante la validazione della query SPARQL: {e}")
|
|
|
|
| 133 |
"""
|
| 134 |
Chiama il modello di linguaggio naturale con i messaggi forniti.
|
| 135 |
"""
|
| 136 |
+
logger.info("Chiamata al modello iniziata.")
|
| 137 |
try:
|
| 138 |
response = client.chat.completions.create(
|
| 139 |
model="Qwen/Qwen2.5-72B-Instruct",
|
|
|
|
| 144 |
stream=False
|
| 145 |
)
|
| 146 |
raw_text = response["choices"][0]["message"]["content"]
|
| 147 |
+
logger.info(f"Risposta del modello ricevuta: {raw_text}")
|
| 148 |
# Rimuoviamo eventuali newline per forzare la singola riga
|
| 149 |
return raw_text.replace("\n", " ").strip()
|
| 150 |
except Exception as e:
|
| 151 |
+
logger.error(f"Errore durante la chiamata al modello: {e}")
|
| 152 |
raise HTTPException(status_code=500, detail=str(e))
|
| 153 |
|
| 154 |
####################################
|
|
|
|
| 158 |
"""
|
| 159 |
Invia i risultati delle query SPARQL al modello per ottenere una risposta naturale.
|
| 160 |
"""
|
| 161 |
+
logger.info("Inizio interpretazione dei risultati SPARQL.")
|
| 162 |
if not results:
|
| 163 |
+
logger.info("Nessun risultato trovato per la query SPARQL.")
|
| 164 |
return "Mi dispiace, non sono riuscita a trovare le informazioni che stavi cercando."
|
| 165 |
|
| 166 |
# Converti i risultati in una stringa leggibile
|
| 167 |
results_str = "\n".join([", ".join([f"{k}: {v}" for k, v in row.asdict().items()]) for row in results])
|
| 168 |
+
logger.debug(f"Risultati SPARQL:\n{results_str}")
|
| 169 |
|
| 170 |
# Crea un prompt per il modello per interpretare i risultati
|
| 171 |
interpret_prompt = f"""
|
|
|
|
| 174 |
|
| 175 |
Per favore, interpreta questi risultati e fornisci una risposta naturale ed enfatica come farebbe una guida museale femminile.
|
| 176 |
"""
|
| 177 |
+
|
| 178 |
messages = [
|
| 179 |
{"role": "system", "content": interpret_prompt},
|
| 180 |
{"role": "user", "content": ""}
|
| 181 |
]
|
| 182 |
|
| 183 |
+
logger.info("Invio dei risultati SPARQL al modello per l'interpretazione.")
|
| 184 |
natural_response = await call_model(messages, temperature=0.7, max_tokens=2048)
|
| 185 |
+
logger.info(f"Risposta interpretata ricevuta dal modello: {natural_response}")
|
| 186 |
return natural_response
|
| 187 |
|
| 188 |
####################################
|
|
|
|
| 198 |
@app.post("/generate-response/")
|
| 199 |
async def generate_response(request: QueryRequest):
|
| 200 |
user_msg = request.message
|
| 201 |
+
logger.info(f"Ricevuta richiesta: {user_msg}")
|
| 202 |
+
|
| 203 |
# 1) Generazione della risposta (SPARQL, INTERPRET o CHAT)
|
| 204 |
system_msg = create_system_message(rdf_context)
|
| 205 |
messages = [
|
|
|
|
| 207 |
{"role": "user", "content": user_msg}
|
| 208 |
]
|
| 209 |
response_text = await call_model(messages, request.temperature, request.max_tokens)
|
| 210 |
+
|
| 211 |
logger.info(f"Risposta generata dal modello: {response_text}")
|
| 212 |
+
|
| 213 |
# 2) Determinazione se la risposta è una query SPARQL
|
| 214 |
if response_text.startswith("PREFIX base:"):
|
| 215 |
sparql_query = response_text
|
| 216 |
+
logger.info("La risposta è stata identificata come una query SPARQL.")
|
| 217 |
# Validazione della query SPARQL
|
| 218 |
if validate_sparql_query(sparql_query, RDF_FILE):
|
| 219 |
+
logger.info("La query SPARQL è valida. Inizio esecuzione della query.")
|
| 220 |
# Esegui la query su GraphDB
|
| 221 |
try:
|
| 222 |
g = Graph()
|
| 223 |
g.parse(RDF_FILE, format="xml")
|
| 224 |
results = g.query(sparql_query)
|
| 225 |
+
logger.info(f"Query SPARQL eseguita con successo. Numero di risultati: {len(results)}")
|
| 226 |
# Interpreta i risultati in una risposta naturale tramite il modello
|
| 227 |
interpreted_response = await interpret_sparql_results(results)
|
| 228 |
+
logger.info(f"Risposta naturale interpretata: {interpreted_response}")
|
| 229 |
return {"type": "NATURAL", "response": interpreted_response}
|
| 230 |
except Exception as e:
|
| 231 |
logger.error(f"Errore durante l'esecuzione della query SPARQL: {e}")
|
| 232 |
return {"type": "ERROR", "response": "Mi dispiace, c'è stato un errore nell'esecuzione della tua richiesta."}
|
| 233 |
else:
|
| 234 |
+
logger.warning("La query SPARQL generata non è valida.")
|
| 235 |
return {"type": "ERROR", "response": "La query SPARQL generata non è valida. Per favore, riprova con una domanda diversa."}
|
| 236 |
|
| 237 |
elif "Non posso generare una query SPARQL" in response_text:
|
| 238 |
# Risposta di errore dal modello
|
| 239 |
+
logger.warning("Il modello ha risposto con un messaggio di errore.")
|
| 240 |
return {"type": "ERROR", "response": response_text}
|
| 241 |
|
| 242 |
else:
|
| 243 |
# Presumiamo che sia una risposta naturale o una chat
|
| 244 |
+
logger.info("La risposta è stata identificata come una risposta naturale o di chat.")
|
| 245 |
return {"type": "NATURAL", "response": response_text}
|
| 246 |
|
| 247 |
@app.get("/")
|
| 248 |
async def root():
|
| 249 |
+
return {"message": "Server attivo e pronto a generare risposte!"}
|