Delete prova.py
Browse files
prova.py
DELETED
|
@@ -1,211 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import logging
|
| 3 |
-
from rdflib import Graph
|
| 4 |
-
from pydantic import BaseModel
|
| 5 |
-
from fastapi import FastAPI, HTTPException
|
| 6 |
-
from huggingface_hub import InferenceClient
|
| 7 |
-
|
| 8 |
-
# Configurazione logging
|
| 9 |
-
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 10 |
-
logger = logging.getLogger(__name__)
|
| 11 |
-
|
| 12 |
-
# Configurazione API Hugging Face
|
| 13 |
-
API_KEY = os.getenv("HF_API_KEY")
|
| 14 |
-
client = InferenceClient(api_key=API_KEY)
|
| 15 |
-
|
| 16 |
-
# File RDF
|
| 17 |
-
RDF_FILE = "Ontologia.rdf"
|
| 18 |
-
|
| 19 |
-
####################################
|
| 20 |
-
# Caricamento RDF (riassunto)
|
| 21 |
-
####################################
|
| 22 |
-
def load_rdf_summary():
|
| 23 |
-
"""
|
| 24 |
-
Carica un riassunto dell'ontologia dal file RDF (se necessario).
|
| 25 |
-
Qui puoi usare parse e scansionare classi e proprietà reali.
|
| 26 |
-
"""
|
| 27 |
-
if not os.path.exists(RDF_FILE):
|
| 28 |
-
return "Nessun file RDF trovato."
|
| 29 |
-
try:
|
| 30 |
-
g = Graph()
|
| 31 |
-
g.parse(RDF_FILE, format="xml")
|
| 32 |
-
|
| 33 |
-
# Esempio di estrazione semplificata di classi e proprietà
|
| 34 |
-
classes = set()
|
| 35 |
-
properties = set()
|
| 36 |
-
for s, p, o in g.triples((None, None, None)):
|
| 37 |
-
if "Class" in str(o):
|
| 38 |
-
classes.add(s)
|
| 39 |
-
if "Property" in str(o):
|
| 40 |
-
properties.add(s)
|
| 41 |
-
|
| 42 |
-
class_summary = "\n".join([f"- Classe: {cls}" for cls in classes])
|
| 43 |
-
prop_summary = "\n".join([f"- Proprietà: {prop}" for prop in properties])
|
| 44 |
-
return f"Classi:\n{class_summary}\n\nProprietà:\n{prop_summary}"
|
| 45 |
-
except Exception as e:
|
| 46 |
-
logger.error(f"Errore durante il parsing del file RDF: {e}")
|
| 47 |
-
return "Errore nel caricamento del file RDF."
|
| 48 |
-
|
| 49 |
-
rdf_context = load_rdf_summary()
|
| 50 |
-
logger.info("RDF Summary: %s", rdf_context)
|
| 51 |
-
|
| 52 |
-
####################################
|
| 53 |
-
# Validazione SPARQL
|
| 54 |
-
####################################
|
| 55 |
-
def validate_sparql_query(query: str, rdf_file_path: str) -> bool:
|
| 56 |
-
"""
|
| 57 |
-
Esegue il parsing e l'esecuzione di test della query su RDF,
|
| 58 |
-
per verificare che sia sintatticamente e semanticamente corretta.
|
| 59 |
-
"""
|
| 60 |
-
g = Graph()
|
| 61 |
-
try:
|
| 62 |
-
g.parse(rdf_file_path, format="xml")
|
| 63 |
-
g.query(query) # Se c'è errore di sintassi o referenza, solleva eccezione
|
| 64 |
-
return True
|
| 65 |
-
except Exception as e:
|
| 66 |
-
logger.error(f"Errore durante la validazione della query SPARQL: {e}")
|
| 67 |
-
return False
|
| 68 |
-
|
| 69 |
-
####################################
|
| 70 |
-
# Prompt di Sistema molto stringente
|
| 71 |
-
####################################
|
| 72 |
-
def create_system_message(rdf_context: str) -> str:
|
| 73 |
-
"""
|
| 74 |
-
Prompt di sistema estremo:
|
| 75 |
-
- impone l'uso di un SOLO prefisso
|
| 76 |
-
- vieta righe multiple
|
| 77 |
-
- vieta di inventare prefissi
|
| 78 |
-
- obbliga a iniziare con `PREFIX base: ... SELECT` o `ASK`
|
| 79 |
-
"""
|
| 80 |
-
return f"""
|
| 81 |
-
Sei un assistente esperto nella generazione di query SPARQL basate su un'ontologia RDF.
|
| 82 |
-
Ecco un riassunto dell'ontologia su cui devi lavorare:
|
| 83 |
-
{rdf_context}
|
| 84 |
-
|
| 85 |
-
DI SEGUITO LE REGOLE TASSATIVE:
|
| 86 |
-
1. DEVI usare ESCLUSIVAMENTE questo prefisso di base (e NON modificarlo in nessun modo):
|
| 87 |
-
PREFIX base: <http://www.semanticweb.org/lucreziamosca/ontologies/2024/11/untitled-ontology-39/>
|
| 88 |
-
2. La query deve stare in UNA SOLA RIGA, senza andare a capo.
|
| 89 |
-
3. La query deve INIZIARE con:
|
| 90 |
-
PREFIX base: <http://www.semanticweb.org/lucreziamosca/ontologies/2024/11/untitled-ontology-39/> SELECT
|
| 91 |
-
oppure
|
| 92 |
-
PREFIX base: <http://www.semanticweb.org/lucreziamosca/ontologies/2024/11/untitled-ontology-39/> ASK
|
| 93 |
-
4. Se devi indicare una classe, usa: ?qualcosa a base:NomeClasse .
|
| 94 |
-
5. Se devi indicare una proprietà, usa: ?s base:NomeProprieta ?o .
|
| 95 |
-
6. NON generare alcun altro prefisso.
|
| 96 |
-
7. NON utilizzare URI lunghe senza < > e NON inventare prefissi o risorse inesistenti.
|
| 97 |
-
8. Se non puoi rispondere con una query SPARQL valida secondo questi criteri, scrivi:
|
| 98 |
-
"Non posso generare una query SPARQL per questa richiesta."
|
| 99 |
-
|
| 100 |
-
Esempio di query corretta (fittizia) in una sola riga:
|
| 101 |
-
PREFIX base: <http://www.semanticweb.org/lucreziamosca/ontologies/2024/11/untitled-ontology-39/> SELECT ?stanza WHERE {{ ?stanza a base:Stanza . }} LIMIT 10
|
| 102 |
-
|
| 103 |
-
RISPONDI ESCLUSIVAMENTE CON LA QUERY O IL MESSAGGIO DI IMPOSSIBILITA'.
|
| 104 |
-
"""
|
| 105 |
-
|
| 106 |
-
####################################
|
| 107 |
-
# Prompt di "correzione"
|
| 108 |
-
####################################
|
| 109 |
-
def create_correction_message(rdf_context: str, errore: str) -> str:
|
| 110 |
-
"""
|
| 111 |
-
Questo prompt serve per la seconda iterazione se la query non è valida.
|
| 112 |
-
Invita a correggere la query e a rispettare le regole.
|
| 113 |
-
"""
|
| 114 |
-
return f"""
|
| 115 |
-
La query che hai fornito è risultata NON valida per il seguente motivo:
|
| 116 |
-
{errore}
|
| 117 |
-
|
| 118 |
-
RICORDA LE REGOLE TASSATIVE, in particolare l'uso ESATTO del prefisso:
|
| 119 |
-
PREFIX base: <http://www.semanticweb.org/lucreziamosca/ontologies/2024/11/untitled-ontology-39/>
|
| 120 |
-
Riscrivi la query in UNA SOLA RIGA, rispettando la sintassi SPARQL e usando solo classi e proprietà presenti nell'ontologia.
|
| 121 |
-
Se non riesci, dì: "Non posso generare una query SPARQL per questa richiesta."
|
| 122 |
-
"""
|
| 123 |
-
|
| 124 |
-
####################################
|
| 125 |
-
# Funzione per chiamare il modello
|
| 126 |
-
####################################
|
| 127 |
-
async def call_model(messages, temperature=0.7, max_tokens=2048):
|
| 128 |
-
try:
|
| 129 |
-
response = client.chat.completions.create(
|
| 130 |
-
model="Qwen/Qwen2.5-72B-Instruct",
|
| 131 |
-
messages=messages,
|
| 132 |
-
temperature=temperature,
|
| 133 |
-
max_tokens=max_tokens,
|
| 134 |
-
top_p=0.7,
|
| 135 |
-
stream=False
|
| 136 |
-
)
|
| 137 |
-
raw_text = response["choices"][0]["message"]["content"]
|
| 138 |
-
# Rimuoviamo eventuali newline per forzare la singola riga
|
| 139 |
-
return raw_text.replace("\n", " ").strip()
|
| 140 |
-
except Exception as e:
|
| 141 |
-
logger.error(f"Errore nel modello: {e}")
|
| 142 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 143 |
-
|
| 144 |
-
####################################
|
| 145 |
-
# FastAPI
|
| 146 |
-
####################################
|
| 147 |
-
app = FastAPI()
|
| 148 |
-
|
| 149 |
-
class QueryRequest(BaseModel):
|
| 150 |
-
message: str
|
| 151 |
-
max_tokens: int = 2048
|
| 152 |
-
temperature: float = 0.7
|
| 153 |
-
|
| 154 |
-
@app.post("/generate-query/")
|
| 155 |
-
async def generate_query(request: QueryRequest):
|
| 156 |
-
# 1) Prima iterazione
|
| 157 |
-
system_msg = create_system_message(rdf_context)
|
| 158 |
-
user_msg = request.message
|
| 159 |
-
|
| 160 |
-
messages_first = [
|
| 161 |
-
{"role": "system", "content": system_msg},
|
| 162 |
-
{"role": "user", "content": user_msg}
|
| 163 |
-
]
|
| 164 |
-
response1 = await call_model(messages_first, request.temperature, request.max_tokens)
|
| 165 |
-
logger.info(f"[Prima iterazione] Risposta generata dal modello: {response1}")
|
| 166 |
-
|
| 167 |
-
# Controllo se comincia con il prefisso esatto
|
| 168 |
-
mandated_prefix = "PREFIX base: <http://www.semanticweb.org/lucreziamosca/ontologies/2024/11/untitled-ontology-39/>"
|
| 169 |
-
if not (response1.startswith(mandated_prefix + " SELECT") or response1.startswith(mandated_prefix + " ASK")):
|
| 170 |
-
return {
|
| 171 |
-
"query": None,
|
| 172 |
-
"explanation": "Il modello non ha usato il prefisso obbligatorio o non ha usato SELECT/ASK."
|
| 173 |
-
}
|
| 174 |
-
|
| 175 |
-
# Verifichiamo se la query è valida
|
| 176 |
-
if validate_sparql_query(response1, RDF_FILE):
|
| 177 |
-
return {"query": response1, "explanation": "Query valida alla prima iterazione."}
|
| 178 |
-
else:
|
| 179 |
-
# 2) Seconda iterazione (correzione)
|
| 180 |
-
correction_msg = create_correction_message(rdf_context, "Query non valida alla prima iterazione.")
|
| 181 |
-
# Comunichiamo al modello la query precedente come contesto e chiediamo la correzione
|
| 182 |
-
messages_second = [
|
| 183 |
-
{"role": "system", "content": system_msg}, # Prompt di sistema invariato
|
| 184 |
-
{"role": "assistant", "content": response1}, # La risposta 'errata'
|
| 185 |
-
{"role": "system", "content": correction_msg} # Istruzione di correzione
|
| 186 |
-
]
|
| 187 |
-
response2 = await call_model(messages_second, request.temperature, request.max_tokens)
|
| 188 |
-
logger.info(f"[Seconda iterazione] Risposta generata dal modello: {response2}")
|
| 189 |
-
|
| 190 |
-
# Ricontrollo se comincia con il prefisso esatto
|
| 191 |
-
if not (response2.startswith(mandated_prefix + " SELECT") and not response2.startswith(mandated_prefix + " ASK")):
|
| 192 |
-
# O se manca la SELECT e l'ASK
|
| 193 |
-
# Con un piccolo fix: potresti voler controllare sia SELECT che ASK qui
|
| 194 |
-
if not (response2.startswith(mandated_prefix + " SELECT") or response2.startswith(mandated_prefix + " ASK")):
|
| 195 |
-
return {
|
| 196 |
-
"query": None,
|
| 197 |
-
"explanation": "Anche la seconda iterazione non ha usato il prefisso e SELECT/ASK corretti."
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
# Validazione della seconda risposta
|
| 201 |
-
if validate_sparql_query(response2, RDF_FILE):
|
| 202 |
-
return {"query": response2, "explanation": "Query valida alla seconda iterazione (corretta)."}
|
| 203 |
-
else:
|
| 204 |
-
return {
|
| 205 |
-
"query": None,
|
| 206 |
-
"explanation": "Anche la seconda iterazione ha prodotto una query non valida. Interrompo."
|
| 207 |
-
}
|
| 208 |
-
|
| 209 |
-
@app.get("/")
|
| 210 |
-
async def root():
|
| 211 |
-
return {"message": "Server attivo e pronto a generare query SPARQL!"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|