-
Notifications
You must be signed in to change notification settings - Fork 0
/
libvocab.py
1575 lines (1294 loc) · 58.7 KB
/
libvocab.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# total rewrite. --danbri
#
# modifications and extensions: Bob Ferris, July 2010
# + multiple property and class types
# + multiple restrictions modeling
# + rdfs:label, rdfs:comment
# + classes and properties from other namespaces
# + inverse properties (explicit and anonymous)
# + sub properties
# + union ranges and domains (appear only in the property descriptions, not on the class descriptions)
# + equivalent properties
# + simple individuals as optional feature
#
# Copyright 2010 Bob Ferris <http://smiy.wordpress.com/author/zazi0815/>
#
# Usage:
#
# >>> from libvocab import Vocab, Term, Class, Property
#
# >>> from libvocab import Vocab, Term, Class, Property
# >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/')
# >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum')
# >>> dna.label
# 'DNA checksum'
# >>> dna.comment
# 'A checksum for the DNA of some thing. Joke.'
# >>> dna.id
# u'dnaChecksum'
# >>> dna.uri
# 'http://xmlns.com/foaf/0.1/dnaChecksum'
#
#
# Python OO notes:
# http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/
# http://www.daniweb.com/code/snippet354.html
# http://docs.python.org/reference/datamodel.html#specialnames
#
# RDFlib:
# http://www.science.uva.nl/research/air/wiki/RDFlib
#
# http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql
#
# We define basics, Vocab, Term, Property, Class
# and populate them with data from RDF schemas, OWL, translations ... and nearby html files.
import rdflib
from rdflib import term
from rdflib.namespace import Namespace
from rdflib.graph import Graph, ConjunctiveGraph
rdflib.plugin.register('sparql', rdflib.query.Processor,
'rdfextras.sparql.processor', 'Processor')
rdflib.plugin.register('sparql', rdflib.query.Result,
'rdfextras.sparql.query', 'SPARQLQueryResult')
# pre3: from rdflib.sparql.sparqlGraph import SPARQLGraph
#from rdflib.sparql.graphPattern import GraphPattern
#from rdflib.sparql import Query
CO = Namespace('http://purl.org/ontology/co/core#')
FOAF = Namespace('http://xmlns.com/foaf/0.1/')
RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#')
XFN = Namespace("http://gmpg.org/xfn/1#")
RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
OWL = Namespace('http://www.w3.org/2002/07/owl#')
VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#')
DC = Namespace('http://purl.org/dc/elements/1.1/')
DOAP = Namespace('http://usefulinc.com/ns/doap#')
SIOC = Namespace('http://rdfs.org/sioc/ns#')
SIOCTYPES = Namespace('http://rdfs.org/sioc/types#')
SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#')
#
# TODO: rationalise these two lists. or at least check they are same.
import sys, time, re, urllib, getopt
import logging
import os.path
import cgi
import operator
def speclog(str):
sys.stderr.write("LOG: " + str + "\n")
# todo: shouldn't be foaf specific
def termlink(text):
result = re.sub(r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text)
return result
# a Term has... (intrinsically and via it's RDFS/OWL description)
# uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage'
# id - a local-to-spec ID, eg. 'workplaceHomepage'
# ns - an ns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/')
#
# label - an rdfs:label
# comment - an rdfs:comment
#
# Beyond this, properties vary. Some have vs:status. Some have owl Deprecated.
# Some have OWL descriptions, and RDFS descriptions; eg. property range/domain
# or class disjointness.
def ns_split(uri):
regexp = re.compile("^(.*[/#])([^/#]+)$")
rez = regexp.search(uri)
return(rez.group(1), rez.group(2))
class Term(object):
def __init__(self, uri = 'file://dev/null'):
self.uri = str(uri)
self.uri = self.uri.rstrip()
# speclog("Parsing URI " + uri)
a, b = ns_split(uri)
self.id = b
self.ns = a
# print "namspace ",a
# print "concept ",b
if self.id == None:
speclog("Error parsing URI. " + uri)
if self.ns == None:
speclog("Error parsing URI. " + uri)
# print "self.id: "+ self.id + " self.ns: " + self.ns
def uri(self):
try:
s = self.uri
except NameError:
self.uri = None
s = '[NOURI]'
speclog('No URI for' + self)
return s
def id(self):
print "trying id"
try:
s = self.id
except NameError:
self.id = None
s = '[NOID]'
speclog('No ID for' + self)
return str(s)
def is_external(self, vocab):
print "Comparing property URI ", self.uri, " with vocab uri: " + vocab.uri
return(False)
#def __repr__(self):
# return(self.__str__)
def __str__(self):
try:
s = self.id
except NameError:
self.label = None
speclog('No label for ' + self + ' todo: take from uri regex')
s = (str(self))
return(str(s))
# so we can treat this like a string
def __add__(self, s):
return (s + str(self))
def __radd__(self, s):
return (s + str(self))
def simple_report(self):
t = self
s = ''
s += "default: \t\t" + t + "\n"
s += "id: \t\t" + t.id + "\n"
s += "uri: \t\t" + t.uri + "\n"
s += "ns: \t\t" + t.ns + "\n"
s += "label: \t\t" + t.label + "\n"
s += "comment: \t\t" + t.comment + "\n"
s += "status: \t\t" + t.status + "\n"
s += "\n"
return s
def _get_status(self):
try:
return self._status
except:
return 'unknown'
def _set_status(self, value):
self._status = str(value)
status = property(_get_status, _set_status)
# a Python class representing an RDFS/OWL property.
#
class Property(Term):
# OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap.
def is_property(self):
# print "Property.is_property called on "+self
return(True)
def is_class(self):
# print "Property.is_class called on "+self
return(False)
def is_individual(self):
# print "Property.is_property called on "+self
return(False)
# A Python class representing an RDFS/OWL class
#
class Class(Term):
# OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap.
def is_property(self):
# print "Class.is_property called on "+self
return(False)
def is_class(self):
# print "Class.is_class called on "+self
return(True)
def is_individual(self):
# print "Property.is_property called on "+self
return(False)
# a Python class representing an RDFS/OWL individual.
#
class Individual(Term):
# OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap.
def is_individual(self):
# print "Property.is_property called on "+self
return(True)
def is_class(self):
# print "Property.is_class called on "+self
return(False)
def is_property(self):
# print "Class.is_property called on "+self
return(False)
# A python class representing (a description of) some RDF vocabulary
#
class Vocab(object):
def __init__(self, dir, f = 'index.rdf', uri = None):
self.graph = ConjunctiveGraph()
self._uri = uri
self.dir = dir
self.filename = os.path.join(dir, f)
# print "ontology file name ", self.filename
self.graph.parse(self.filename)
self.terms = []
self.uterms = []
# should also load translations here?
# and deal with a base-dir?
##if f != None:
## self.index()
self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf",
"http://www.w3.org/2000/01/rdf-schema#" : "rdfs",
"http://www.w3.org/2002/07/owl#" : "owl",
"http://www.w3.org/2001/XMLSchema#" : "xsd",
"http://rdfs.org/sioc/ns#" : "sioc",
"http://xmlns.com/foaf/0.1/" : "foaf",
"http://purl.org/dc/elements/1.1/" : "dc",
"http://purl.org/dc/terms/" : "dcterms",
"http://usefulinc.com/ns/doap#" : "doap",
"http://www.w3.org/2003/06/sw-vocab-status/ns#" : "vs",
"http://purl.org/rss/1.0/modules/content/" : "content",
"http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo",
"http://www.w3.org/2004/02/skos/core#" : "skos",
"http://purl.org/NET/c4dm/event.owl#" : "event",
"http://purl.org/ontology/co/core#" : "co",
"http://purl.org/ontology/olo/core#" : "olo",
"http://purl.org/ontology/is/core#" : "is",
"http://purl.org/ontology/similarity/" : "sim",
"http://purl.org/stuff/rev#" : "rev",
"http://purl.org/ontology/ao/core#" : "ao",
"http://purl.org/ontology/bibo/" : "bibo",
"http://purl.org/vocab/frbr/core#" : "frbr",
"http://www.w3.org/2006/time#" : "time",
"http://purl.org/ontology/pbo/core#" : "pbo",
"http://purl.org/ontology/rec/core#" : "rec",
"http://purl.org/ontology/wi/core#" : "wi",
"http://purl.org/ontology/wo/core#" : "wo",
"http://purl.org/ontology/cco/core#" : "cco",
"http://purl.org/ontology/prv/core#" : "prv",
"http://purl.org/NET/scovo#" : "scovo"
}
def addShortName(self, sn):
self.ns_list[self._uri] = sn
self.shortName = sn
#print self.ns_list
# not currently used
def unique_terms(self):
tmp = []
for t in list(set(self.terms)):
s = str(t)
if (not s in tmp):
self.uterms.append(t)
tmp.append(s)
# TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri
def _get_uri(self):
return self._uri
def _set_uri(self, value):
v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining.
if ':' not in v:
speclog("Warning: this doesn't look like a URI: " + v)
# raise Exception("This doesn't look like a URI.")
self._uri = str(value)
uri = property(_get_uri, _set_uri)
def set_filename(self, filename):
self.filename = filename
# TODO: be explicit if/where we default to English
# TODO: do we need a separate index(), versus just use __init__ ?
def index(self):
# speclog("Indexing description of "+str(self))
# blank down anything we learned already
self.terms = []
self.properties = []
self.classes = []
self.individuals = []
tmpclasses = []
tmpproperties = []
tmpindividuals = []
g = self.graph
# extend query for different property types
query = 'SELECT ?x ?l ?c ?t WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x rdf:type ?t . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) }'
relations = g.query(query)
for (term, label, comment, type) in relations:
p = Property(term)
# print "Made a property! "+str(p) + " using label: "+str(label)
p.label = str(label)
p.comment = str(comment)
p.type = self.niceName(type)
self.terms.append(p)
if (not str(p) in tmpproperties):
tmpproperties.append(str(p))
self.properties.append(p)
query = 'SELECT ?x ?l ?c ?t WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x rdf:type ?t . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }'
relations = g.query(query)
for (term, label, comment, type) in relations:
c = Class(term)
# print "Made a class! "+str(c) + " using comment: "+comment
c.label = str(label)
c.comment = str(comment)
c.type = self.niceName(type)
self.terms.append(c)
if (not str(c) in tmpclasses):
self.classes.append(c)
tmpclasses.append(str(c))
# ATTENTION: the owl:Ontology individual shouldn't be included into this list here
query = 'SELECT ?x ?title ?description ?type WHERE { ?x <http://purl.org/dc/elements/1.1/title> ?title . ?x <http://purl.org/dc/elements/1.1/description> ?description . ?x rdf:type ?type . ?x a ?t FILTER (?t != <http://www.w3.org/2002/07/owl#Ontology> ) }'
relations = g.query(query)
for (term, title, description, type) in relations:
i = Individual(term)
print "Made an individual! "+str(i) + " using label: "+str(title)
i.label = str(title)
i.comment = str(description)
i.type = self.niceName(type)
self.terms.append(i)
if (not str(i) in tmpindividuals):
tmpindividuals.append(str(i))
self.individuals.append(i)
self.terms.sort(key = operator.attrgetter('id'))
self.classes.sort(key = operator.attrgetter('id'))
self.properties.sort(key = operator.attrgetter('id'))
self.individuals.sort(key = operator.attrgetter('id'))
# http://www.w3.org/2003/06/sw-vocab-status/ns#"
query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }'
status = g.query(query)
# print "status results: ",status.__len__()
for x, vs in status:
#print "STATUS: ",vs, " for ",x
t = self.lookup(x)
if t != None:
t.status = vs
# print "Set status.", t.status
else:
speclog("Couldn't lookup term: " + x)
# self.terms.sort() # does this even do anything?
# self.classes.sort()
# self.properties.sort()
# todo, use a dictionary index instead. RTFM.
def lookup(self, uri):
uri = str(uri)
for t in self.terms:
# print "Lookup: comparing '"+t.uri+"' to '"+uri+"'"
# print "type of t.uri is ",t.uri.__class__
if t.uri == uri:
# print "Matched." # should we str here, to be more liberal?
return t
else:
# print "Fail."
''
return None
# print a raw debug summary, direct from the RDF
def raw(self):
g = self.graph
query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } '
relations = g.query(query)
print "Properties and Classes (%d terms)" % len(relations)
print 40 * "-"
for (term, label, comment) in relations:
print "term %s l: %s \t\tc: %s " % (term, label, comment)
print
# TODO: work out how to do ".encode('UTF-8')" here
# for debugging only
def detect_types(self):
self.properties = []
self.classes = []
self.individuals = []
for t in self.terms:
# print "Doing t: "+t+" which is of type " + str(t.__class__)
if t.is_property():
# print "is_property."
self.properties.append(t)
if t.is_class():
# print "is_class."
self.classes.append(t)
if t.is_individual():
# print "is_individual."
self.individuals.append(t)
# CODE FROM ORIGINAL specgen:
def niceName(self, uri = None):
if uri is None:
return
# speclog("Nicing uri "+uri)
regexp = re.compile("^(.*[/#])([^/#]+)$")
rez = regexp.search(uri)
if rez == None:
#print "Failed to niceName. Returning the whole thing."
return(uri)
pref = rez.group(1)
# print "...",self.ns_list.get(pref, pref),":",rez.group(2)
# todo: make this work when uri doesn't match the regex --danbri
# AttributeError: 'NoneType' object has no attribute 'group'
return self.ns_list.get(pref, pref) + ":" + rez.group(2)
# HTML stuff, should be a separate class
def azlist(self):
"""Builds the A-Z list of terms"""
c_ids = []
p_ids = []
i_ids = []
for p in self.properties:
p_ids.append(str(p.id))
for c in self.classes:
c_ids.append(str(c.id))
for i in self.individuals:
i_ids.append(str(i.id))
c_ids.sort()
p_ids.sort()
i_ids.sort()
return (c_ids, p_ids, i_ids)
class VocabReport(object):
def __init__(self, vocab, basedir = './examples/', temploc = 'template.html', templatedir = './examples/'):
self.vocab = vocab
self.basedir = basedir
self.temploc = temploc
self.templatedir = templatedir
self._template = "no template loaded"
# text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>"
def codelink(self, s):
reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""")
return(re.sub(reg1, r"""<code><a href="#\1">foaf:\1</a></code>""", s))
def _get_template(self):
self._template = self.load_template() # should be conditional
return self._template
def _set_template(self, value):
self._template = str(value)
template = property(_get_template, _set_template)
def load_template(self):
filename = os.path.join(self.templatedir, self.temploc)
f = open(filename, "r")
template = f.read()
return(template)
def generate(self):
tpl = self.template
azlist = self.az()
termlist = self.termlist()
f = open (self.vocab.filename, "r")
rdfdata = f.read()
# print "GENERATING >>>>>>>> "
## having the rdf in there was making it invalid
## removed in favour of RDFa
## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata)
#
# IMPORTANT: this is the code, which is responsible for write code fragments to the template
tpl = tpl % (self.concepttypes.encode("utf-8"),
self.concepttypes2.encode("utf-8"),
azlist.encode("utf-8"),
self.concepttypes.encode("utf-8"),
self.concepttypes3.encode("utf-8"),
azlist.encode("utf-8"),
termlist.encode("utf-8"))
# tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"))
return(tpl)
def az(self):
"""AZ List for html doc"""
c_ids, p_ids , i_ids = self.vocab.azlist()
az = """<div class="azlist">"""
az = """%s\n<p>Classes: |""" % az
# print c_ids, p_ids
for c in c_ids:
# speclog("Class "+c+" in az generation.")
az = """%s <a href="#%s">%s</a> | """ % (az, str(c).replace(" ", ""), c)
az = """%s\n</p>""" % az
az = """%s\n<p>Properties: |""" % az
for p in p_ids:
# speclog("Property "+p+" in az generation.")
az = """%s <a href="#%s">%s</a> | """ % (az, str(p).replace(" ", ""), p)
az = """%s\n</p>""" % az
if (len(self.vocab.individuals) > 0):
az = """%s\n<p>Individuals: |""" % az
for i in i_ids:
# speclog("Individual "+p+" in az generation.")
az = """%s <a href="#%s">%s</a> | """ % (az, str(i).replace(" ", ""), i)
az = """%s\n</p>""" % az
az = """%s\n</div>""" % az
return(az)
def termlist(self):
"""Term List for html doc"""
stableTxt = ''
testingTxt = ''
unstableTxt = ''
archaicTxt = ''
queries = ''
c_ids, p_ids, i_ids = self.vocab.azlist()
tl = """<div class="termlist">"""
# look, whether individuals are available
if (len(self.vocab.individuals) > 0):
tl = """%s<h3>Classes, Properties and Individuals (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl
self.concepttypes = "Classes, Properties and Individuals"
self.concepttypes2 = "class (categories or types), by property and by individual"
self.concepttypes3 = "classes, properties and individuals"
else:
tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl
self.concepttypes = "Classes and Properties"
self.concepttypes2 = "class (categories or types) and by property"
self.concepttypes3 = "classes and properties"
# danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs
# first classes, then properties
eg = """<div class="specterm" id="%s" about="%s" typeof="%s">
<h3>%s: %s</h3>
<em property="rdfs:label" >%s</em> - <span property="rdfs:comment" >%s</span> <br /><table style="th { float: top; }">
<tr><th>Status:</th>
<td><span property="vs:status" >%s</span></td></tr>
%s
%s
</table>
%s
<p style="float: right; font-size: small;">[<a href="#%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p>
<br/>
</div>"""
# for individuals
ig = """<div class="specterm" id="%s" about="%s" typeof="%s">
<h3>%s: %s</h3>
<em property="dc:title" >%s</em> - <span property="dc:description" >%s</span> <br /><table style="th { float: top; }">
<tr><th>Status:</th>
<td><span property="vs:status" >%s</span></td></tr>
%s
</table>
%s
<p style="float: right; font-size: small;">[<a href="#%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p>
<br/>
</div>"""
# replace this if you want validation queries: xxx danbri
# <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p>
# todo, push this into an api call (c_ids currently setup by az above)
# classes
for term in self.vocab.classes:
# strings to use later
domainsOfClass = ''
rangesOfClass = ''
#class in domain of -> only for classes included in this ontology specification
g = self.vocab.graph
q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri)
relations = g.query(q)
startStr = '<tr><th>Properties include:</th>\n'
contentStr = ''
for (domain, label) in relations:
dom = Term(domain)
# danbri hack 20100101
# termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label)
termStr = """<a href="#%s">%s</a>\n""" % (dom.id, dom.id)
contentStr = "%s %s" % (contentStr, termStr)
if contentStr != "":
domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr)
# class in range of -> only for classes included in this ontology specification
q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri)
relations2 = g.query(q2)
startStr = '<tr><th>Used with:</th>\n'
contentStr = ''
for (range, label) in relations2:
ran = Term(range)
# termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label)
# danbri hack 20100101 better to use exact IDs here
termStr = """<a href="#%s">%s</a>\n""" % (ran.id, ran.id)
contentStr = "%s %s" % (contentStr, termStr)
if contentStr != "":
rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr)
# class sub class of -> handles only "real" super classes
subClassOf = ''
restriction = ''
q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri)
relations = g.query(q)
startStr = '<tr><th>Sub class of</th>\n'
contentStr = ''
contentStr2 = ''
for (subclass, label) in relations:
sub = Term(subclass)
termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#%s">%s</a></span>\n""" % (subclass, sub.id, label)
contentStr = "%s %s" % (contentStr, termStr)
if contentStr != "":
subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr)
# else:
q1 = 'SELECT ?sc WHERE {<%s> rdfs:subClassOf ?sc } ' % (term.uri)
relations = g.query(q1)
ordone = False
for (subclass) in relations:
subclassnice = self.vocab.niceName(subclass)
# print "subclass ",subclass
# print "subclassnice ",subclassnice
# check niceName result
# TODO: handle other sub class types (...) currently owl:Restriction only
colon = subclassnice.find(':')
print "ns uri ", str(self.vocab._get_uri())
if(subclass.find(str(self.vocab._get_uri())) < 0):
if (colon > 0):
termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="%s">%s</a></span>\n""" % (subclass, subclass, subclassnice)
contentStr = "%s %s" % (contentStr, termStr)
print "must be super class from another ns: ", subclassnice
elif (ordone == False):
# with that query I get all restrictions of a concept :\
# TODO: enable a query with bnodes (_:bnode currently doesn't work :( )
# that's why the following code isn't really nice
q2 = 'SELECT ?orsc ?or ?orv WHERE { <%s> rdfs:subClassOf ?orsc . ?orsc rdf:type <http://www.w3.org/2002/07/owl#Restriction> . ?orsc ?or ?orv }' % (term.uri)
print "try to fetch owl:Restrictions with query ", q2
orrelations = g.query(q2)
startStr2 = '<tr><th class="restrictions">Restriction(s):</th>\n'
orpcounter = 0
orsubclass = ''
contentStr3 = ''
termStr1 = ''
termStr2 = ''
prop = ''
oronproperty = ''
orproperty = ''
orpropertyvalue = ''
orscope = ''
for (orsc, orp, orpv) in orrelations:
orproperty2 = ''
orpropertyvalue2 = ''
orscope2 = ''
if (orsubclass == ""):
print "initialize orsubclass with ", orsc
orsubclass = orsc
if(orsubclass != orsc):
termStr1 = """<span about="%s" rel="rdfs:subClassOf" resource="[_:%s]"></span>\n""" % (term.uri, orsubclass)
termStr2 = """<span about="[_:%s]" typeof="owl:Restriction"></span>The property
<span about="[_:%s]" rel="owl:onProperty" href="%s"><a href="#%s">%s</a></span> must be set <em>%s</em>
<span about="[_:%s]" property="%s" datatype="xsd:nonNegativeInteger" >%s</span> time(s)""" % (orsubclass, orsubclass, oronproperty, prop.id, prop.type, orscope, orsubclass, orproperty, orpropertyvalue)
contentStr2 = "%s %s %s %s<br/>" % (contentStr2, termStr1, termStr2, contentStr3)
print "change orsubclass to", orsc
orsubclass = orsc
contentStr3 = ''
orpcounter = 0
termStr1 = ''
termStr2 = ''
prop = ''
oronproperty = ''
orproperty = ''
orpropertyvalue = ''
orscope = ''
print "orp ", orp
print "orpv", orpv
if (str(orp) == "http://www.w3.org/2002/07/owl#onProperty"):
oronproperty = orpv
prop = Term(orpv)
prop.type = self.vocab.niceName(orpv)
print "found new owl:Restriction"
print "write onproperty property"
elif ((str(orp) != "http://www.w3.org/1999/02/22-rdf-syntax-ns#type") & (str(orp) != "http://www.w3.org/2002/07/owl#onProperty")):
if (orpcounter == 0):
orproperty = self.vocab.niceName(orp)
# <- that must be a specific cardinality restriction
orpropertyvalue = orpv
if (str(orp) == "http://www.w3.org/2002/07/owl#cardinality"):
orscope = "exactly"
if (str(orp) == "http://www.w3.org/2002/07/owl#minCardinality"):
orscope = "at least"
if (str(orp) == "http://www.w3.org/2002/07/owl#maxCardinality"):
orscope = "at most"
print "write 1st cardinality of restriction"
else:
orproperty2 = self.vocab.niceName(orp)
# <- that must be another specific cardinality restriction
orpropertyvalue2 = orpv
if (str(orp) == "http://www.w3.org/2002/07/owl#cardinality"):
orscope2 = "exactly"
if (str(orp) == "http://www.w3.org/2002/07/owl#minCardinality"):
orscope2 = "at least"
if (str(orp) == "http://www.w3.org/2002/07/owl#maxCardinality"):
orscope2 = "at most"
print "write another cardinality of restriction"
orpcounter = orpcounter + 1
else:
print "here I am with ", orp
if (str(orproperty2) != ""):
termStr3 = """ and <em>%s</em>
<span about="[_:%s]" property="%s" >%s</span> time(s)""" % (orscope2, orsubclass, orproperty2, orpropertyvalue2)
contentStr3 = "%s %s" % (contentStr3, termStr3)
# write also last/one restriction
termStr1 = """<span about ="%s" rel="rdfs:subClassOf" resource="[_:%s]"></span>\n""" % (term.uri, orsubclass)
termStr2 = """<span about="[_:%s]" typeof="owl:Restriction"></span>The property
<span about="[_:%s]" rel="owl:onProperty" href="%s"><a href="#%s">%s</a></span> must be set <em>%s</em>
<span about="[_:%s]" property="%s" datatype="xsd:nonNegativeInteger" >%s</span> time(s)""" % (orsubclass, orsubclass, oronproperty, prop.id, prop.type, orscope, orsubclass, orproperty, orpropertyvalue)
contentStr2 = "%s %s %s %s\n" % (contentStr2, termStr1, termStr2, contentStr3)
ordone = True
print "owl restriction modelling done for", term.uri
if contentStr != "":
subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr)
if contentStr2 != "":
restriction = "%s <td> %s </td></tr>" % (startStr2, contentStr2)
# class has sub class -> handles only "real" super classes
hasSubClass = ''
q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri)
relations = g.query(q)
startStr = '<tr><th>Has sub class</th>\n'
contentStr = ''
for (subclass, label) in relations:
sub = Term(subclass)
termStr = """<a href="#%s">%s</a>\n""" % (sub.id, label)
contentStr = "%s %s" % (contentStr, termStr)
if contentStr != "":
hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr)
q = 'SELECT ?sc WHERE {?sc rdfs:subClassOf <%s> } ' % (term.uri)
relations = g.query(q)
for (subclass) in relations:
subclassnice = self.vocab.niceName(subclass)
print "has subclass ", subclass
print "has subclassnice ", subclassnice
# check niceName result
colon = subclassnice.find(':')
if(subclass.find(str(self.vocab._get_uri())) < 0):
if colon > 0:
termStr = """<a href="%s">%s</a>\n""" % (subclass, subclassnice)
contentStr = "%s %s" % (contentStr, termStr)
if contentStr != "":
hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr)
# is defined by
classIsDefinedBy = ''
q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri)
relations = g.query(q)
startStr = '\n'
contentStr = ''
for (isdefinedby) in relations:
termStr = """<span rel="rdfs:isDefinedBy" href="%s"></span>\n""" % (isdefinedby)
contentStr = "%s %s" % (contentStr, termStr)
if contentStr != "":
classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr)
# disjoint with
isDisjointWith = ''
q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri)
relations = g.query(q)
startStr = '<tr><th>Disjoint With:</th>\n'
contentStr = ''
for (disjointWith, label) in relations:
termStr = """<span rel="owl:disjointWith" href="%s"><a href="#%s">%s</a></span>\n""" % (disjointWith, label, label)
contentStr = "%s %s" % (contentStr, termStr)
if contentStr != "":
isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr)
# owl class
oc = ''
termStr = ''
q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#Class> } ' % (term.uri)
relations = g.query(q)
startStr = '<tr><th colspan="2">OWL Class</th>\n'
if (len(relations) > 0):
if (str(term.type) != "owl:Class"):
termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#Class"></span>"""
oc = "%s <td> %s </td></tr>" % (startStr, termStr)
# rdfs class
rc = ''
termStr = ''
q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2000/01/rdf-schema#Class> } ' % (term.uri)
relations = g.query(q)
startStr = '<tr><th colspan="2">RDFS Class</th>\n'
if (len(relations) > 0):
if (str(term.type) != "rdfs:Class"):
termStr = """<span rel="rdf:type" href="http://www.w3.org/2000/01/rdf-schema#Class"></span>"""
rc = "%s <td> %s </td></tr>" % (startStr, termStr)
# dcterms agent class
dctac = ''
termStr = ''
q = 'SELECT * WHERE { <%s> rdf:type <http://purl.org/dc/terms/AgentClass> } ' % (term.uri)
relations = g.query(q)
startStr = '<tr><th colspan="2">DCTerms Agent Class</th>\n'
if (len(relations) > 0):
if (str(term.type) != "dcterms:AgentClass"):
termStr = """<span rel="rdf:type" href="ttp://purl.org/dc/terms/AgentClass"></span>"""
dctac = "%s <td> %s </td></tr>" % (startStr, termStr)
# end
dn = os.path.join(self.basedir, "doc")
filename = os.path.join(dn, term.id + ".en")
s = ''
try:
f = open (filename, "r")
s = f.read()
except:
s = ''
# if we want validation queries this is where it looks for them.
filename = os.path.join(dn, term.id + ".sparql")
fileStr = ''
try:
f = open (filename, "r")
fileStr = f.read()
fileStr = "<h4><a name=\"queries_" + term.id + "\"></a>" + term.id + " Validation Query</h4><pre>" + cgi.escape(ss) + "</pre>"
except:
fileStr = ''
queries = queries + "\n" + fileStr
sn = self.vocab.niceName(term.uri)
s = termlink(s)
# danbri added another term.id 20010101 and removed term.status
# ATTENTION: writing all class descriptions into template here
zz = eg % (term.id, term.uri, term.type, "Class", sn, term.label, term.comment, term.status, domainsOfClass, rangesOfClass + subClassOf + restriction + hasSubClass + classIsDefinedBy + isDisjointWith + oc + rc + dctac, s, term.id, term.id)
## we add to the relevant string - stable, unstable, testing or archaic
if(term.status == "stable"):
stableTxt = stableTxt + zz
if(term.status == "testing"):
testingTxt = testingTxt + zz
if(term.status == "unstable"):
unstableTxt = unstableTxt + zz
if(term.status == "archaic"):
archaicTxt = archaicTxt + zz
if((term.status == None) or (term.status == "") or (term.status == "unknown")):
archaicTxt = archaicTxt + zz
## then add the whole thing to the main tl string
tl = tl + "<h2>Classes</h2>\n"
tl = "%s %s" % (tl, stableTxt + "\n" + testingTxt + "\n" + unstableTxt + "\n" + archaicTxt)
tl = tl + "<h2>Properties</h2>\n"
# properties
stableTxt = ''
testingTxt = ''
unstableTxt = ''
archaicTxt = ''
for term in self.vocab.properties:
domainsOfProperty = ''
rangesOfProperty = ''
# domain of properties
g = self.vocab.graph
q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri)
# print "term.uri before ", term.uri
relations = g.query(q)
startStr = '<tr><th>Domain:</th>\n'
contentStr = ''
contentStr3 = ''
for (domain, label) in relations:
dom = Term(domain)
termStr = """<span rel="rdfs:domain" href="%s"><a href="#%s">%s</a></span>\n""" % (domain, dom.id, label)
contentStr = "%s %s" % (contentStr, termStr)
q = 'SELECT ?d WHERE {<%s> rdfs:domain ?d } ' % (term.uri)
relations = g.query(q)
for (domain) in relations: