Script Python pronto all’uso per normalizzare un TTL remoto (rimuove BOM, aggiunge prefissi comuni, valida con RDFLib e riscrive Turtle con i prefissi in testa)
Cosa fa
- scarica l’IRI fornito;
- rimuove BOM/encoding problematici;
- tenta il parsing con RDFLib (Turtle/Trig/TTL);
- aggiunge binding per prefissi comuni eventualmente mancanti;
- serializza un Turtle “pulito” con i prefissi in testa;
- salva file di output e stampa errori di parsing.
Prerequisiti
- Python 3.9+
- pacchetti:
rdflib,requestsInstallazione rapida:
bash
Data format:
python -m pip install rdflib requests
python
Data format:
#!/usr/bin/env python3
"""
normalize_ttl.py
Scarica un file RDF/Turtle da un URL, rimuove BOM/encoding,
aggiunge prefissi comuni mancanti, valida con rdflib e riscrive
un Turtle normalizzato con i prefissi in testa.
Uso:
python normalize_ttl.py https://www.atlantisfound.it/ontology/psca output_normalized.ttl
"""
import sys
import requests
from rdflib import Graph, Namespace
from rdflib.namespace import RDF, RDFS, XSD, OWL
COMMON_PREFIXES = {
"psca": "https://www.atlantisfound.it/ontology/psca#",
"": "https://www.atlantisfound.it/ontology/psca#", # default base
"wd": "http://www.wikidata.org/entity/",
"wdt": "http://www.wikidata.org/prop/direct/",
"schema": "https://schema.org/",
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"xsd": "http://www.w3.org/2001/XMLSchema#",
"prov": "http://www.w3.org/ns/prov#",
"geo": "http://www.opengis.net/ont/geosparql#",
"crm": "http://www.cidoc-crm.org/cidoc-crm/",
"foaf": "http://xmlns.com/foaf/0.1/",
"dcterms": "http://purl.org/dc/terms/",
"skos": "http://www.w3.org/2004/02/skos/core#"
}
def fetch_url(url, timeout=30):
resp = requests.get(url, timeout=timeout)
resp.raise_for_status()
# try to decode as utf-8, fallback to resp.apparent_encoding
content = resp.content
# remove UTF-8 BOM if present
if content.startswith(b'\xef\xbb\xbf'):
content = content[3:]
# decode
enc = resp.encoding if resp.encoding else resp.apparent_encoding
text = content.decode(enc, errors='replace')
return text
def try_parse(text, formats=("turtle","trig","n3","xml","json-ld")):
g = Graph()
last_err = None
for fmt in formats:
try:
g.parse(data=text, format=fmt)
print(f"[OK] Parsed as {fmt}")
return g
except Exception as e:
last_err = e
raise RuntimeError(f"Parsing failed for all tried formats. Last error: {last_err}")
def bind_common_prefixes(g):
for pfx, uri in COMMON_PREFIXES.items():
# avoid rebinding if already present
if pfx not in [p for p, _ in g.namespaces()]:
g.bind(pfx, Namespace(uri))
def main():
if len(sys.argv) < 3:
print("Usage: python normalize_ttl.py <remote_url> <output_file.ttl>")
sys.exit(1)
url = sys.argv[1]
out_file = sys.argv[2]
print(f"Fetching {url} ...")
try:
text = fetch_url(url)
except Exception as e:
print(f"[ERROR] Failed to fetch URL: {e}")
sys.exit(2)
# Quick heuristic: if the fetched content looks like HTML, warn and save raw
if text.lstrip().startswith("<!DOCTYPE") or text.lstrip().startswith("<html"):
print("[WARNING] The fetched resource looks like HTML. Check the URL or server response.")
# save raw for inspection
with open(out_file + ".raw.html", "w", encoding="utf-8") as fh:
fh.write(text)
print(f"Saved raw response to {out_file}.raw.html")
sys.exit(3)
# Try parsing with multiple formats
try:
g = try_parse(text)
except Exception as e:
print(f"[ERROR] {e}")
# save the fetched text for debugging
with open(out_file + ".fetch.txt", "w", encoding="utf-8") as fh:
fh.write(text)
print(f"Saved fetched content to {out_file}.fetch.txt for inspection.")
sys.exit(4)
# Bind common prefixes if missing
bind_common_prefixes(g)
# Optional: print current namespaces
print("Namespaces in graph after binding:")
for pfx, ns in g.namespaces():
print(f" {pfx or '(default)'} -> {ns}")
# Serialize to Turtle (rdflib will place prefixes at top)
try:
g.serialize(destination=out_file, format="turtle")
print(f"[OK] Normalized Turtle written to {out_file}")
except Exception as e:
print(f"[ERROR] Failed to serialize graph: {e}")
sys.exit(5)
if __name__ == "__main__":
main()
Note operative e consigli
- Se il server restituisce HTML (pagina di errore o redirect), lo script salva il body in
output.fetch.txtper debug e si interrompe: correggi l’URL o la configurazione del server. - Il binding dei prefissi aggiunge prefissi comuni; se usi prefissi non standard (es.
wdt:) assicurati che la URI sia corretta. - Validazione più rigorosa: dopo aver ottenuto
output_normalized.ttl, eseguiriot --validate output_normalized.ttl(Apache Jena) per messaggi di validazione più dettagliati. - Se il file è TriG / named graphs, modifica
g.parse(..., format="trig")o lascia che lo script provi più formati (già incluso). - Backup: lavora sempre su copie; non sovrascrivere l’originale sul server finché non sei sicuro.