Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,97 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
app = FastAPI()
|
4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
@app.get("/")
|
6 |
-
def
|
7 |
-
return {"
|
|
|
1 |
+
import os
|
2 |
+
from fastapi import FastAPI, HTTPException, Request
|
3 |
+
from huggingface_hub import InferenceClient
|
4 |
+
from rdflib import Graph
|
5 |
+
from pydantic import BaseModel
|
6 |
|
7 |
+
# Configurazione API Hugging Face
|
8 |
+
API_KEY = os.getenv("HF_API_KEY")
|
9 |
+
if not API_KEY:
|
10 |
+
raise ValueError("API Key non trovata. Assicurati che sia definita come variabile d'ambiente 'HF_API_KEY'.")
|
11 |
+
|
12 |
+
client = InferenceClient(api_key=API_KEY)
|
13 |
+
|
14 |
+
# File RDF
|
15 |
+
RDF_FILE = "Progetto.rdf"
|
16 |
+
|
17 |
+
# Carica il file RDF
|
18 |
+
def load_rdf():
|
19 |
+
if os.path.exists(RDF_FILE):
|
20 |
+
with open(RDF_FILE, "r") as f:
|
21 |
+
return f.read()
|
22 |
+
return ""
|
23 |
+
|
24 |
+
rdf_context = load_rdf()
|
25 |
+
|
26 |
+
# Valida le query SPARQL
|
27 |
+
def validate_sparql_query(query, rdf_data):
|
28 |
+
try:
|
29 |
+
g = Graph()
|
30 |
+
g.parse(data=rdf_data, format="xml")
|
31 |
+
g.query(query)
|
32 |
+
return True
|
33 |
+
except Exception as e:
|
34 |
+
return False
|
35 |
+
|
36 |
+
# FastAPI app
|
37 |
app = FastAPI()
|
38 |
|
39 |
+
# Modello di input per richieste POST
|
40 |
+
class QueryRequest(BaseModel):
|
41 |
+
message: str
|
42 |
+
max_tokens: int = 512
|
43 |
+
temperature: float = 0.7
|
44 |
+
|
45 |
+
# Messaggio di sistema con RDF incluso
|
46 |
+
def create_system_message(rdf_context):
|
47 |
+
return f"""
|
48 |
+
Sei un assistente specializzato nella generazione e riscrittura di query SPARQL basate su dati RDF.
|
49 |
+
La base di conoscenza RDF è la seguente:
|
50 |
+
{rdf_context}
|
51 |
+
Il tuo compito principale è:
|
52 |
+
1. Analizzare lo schema RDF o i dati RDF forniti e la domanda in linguaggio naturale posta dall'utente.
|
53 |
+
2. Generare una query SPARQL valida che recuperi le informazioni richieste dai dati RDF.
|
54 |
+
3. Se l'utente fornisce una query SPARQL con una richiesta di spiegazione o correzione, riscrivila per renderla più efficiente o corretta.
|
55 |
+
Regole:
|
56 |
+
- Non generare nulla al di fuori di una query SPARQL, a meno che non sia esplicitamente richiesto.
|
57 |
+
- Se la domanda non può essere soddisfatta con una query SPARQL, rispondi con: \"Non posso generare una query per questa domanda.\"
|
58 |
+
"""
|
59 |
+
|
60 |
+
# Funzione per inviare la richiesta al modello Hugging Face
|
61 |
+
def generate_response(message, max_tokens, temperature):
|
62 |
+
system_message = create_system_message(rdf_context)
|
63 |
+
messages = [
|
64 |
+
{"role": "system", "content": system_message},
|
65 |
+
{"role": "user", "content": message}
|
66 |
+
]
|
67 |
+
|
68 |
+
try:
|
69 |
+
completion = client.conversational(
|
70 |
+
model="Qwen/Qwen2.5-72B-Instruct",
|
71 |
+
messages=messages,
|
72 |
+
max_tokens=max_tokens,
|
73 |
+
temperature=temperature
|
74 |
+
)
|
75 |
+
response = completion.get("generated_text", "").strip()
|
76 |
+
return response
|
77 |
+
except Exception as e:
|
78 |
+
raise HTTPException(status_code=500, detail=f"Errore nell'elaborazione: {str(e)}")
|
79 |
+
|
80 |
+
# Endpoint per generare query SPARQL
|
81 |
+
@app.post("/generate-query/")
|
82 |
+
async def generate_query(request: QueryRequest):
|
83 |
+
# Genera risposta
|
84 |
+
response = generate_response(request.message, request.max_tokens, request.temperature)
|
85 |
+
|
86 |
+
# Valida la query se possibile
|
87 |
+
if response.startswith("SELECT") or response.startswith("ASK"):
|
88 |
+
is_valid = validate_sparql_query(response, rdf_context)
|
89 |
+
if not is_valid:
|
90 |
+
raise HTTPException(status_code=400, detail="La query generata non è valida rispetto al file RDF fornito.")
|
91 |
+
|
92 |
+
return {"query": response}
|
93 |
+
|
94 |
+
# Endpoint per verificare se il server è attivo
|
95 |
@app.get("/")
|
96 |
+
async def root():
|
97 |
+
return {"message": "Il server è attivo e pronto a generare query SPARQL!"
|