~bzg/ox-skos

ref: 6fb2847b7a8dfa732daa9c7053f1161f04c64c86 ox-skos/ox-skos.el -rw-r--r-- 15.0 KiB
6fb2847bBastien Add skos-xl and iso-thes data 5 years ago
                                                                                
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
;;; ox-skos.el --- SKOS Back-End for Org Export Engine

;; Copyright (C) 2017 Bastien Guerry

;; Author: Bastien Guerry <bzg@gnu.org>
;; Keywords: skos

;; This file is not part of GNU Emacs.

;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; This library implements a SKOS back-end (as TTL or XML/RDF) for Org
;; exporter, based on the `html' back-end.
;;
;; This backend understands these new option keywords:
;;
;; #+SKOS_EXTENSION: rdf (the default)
;; #+SKOS_CONCEPTSCHEMEURI: set the base concept scheme URI.
;;
;;; Todo:
;;
;; - use :skos:note:fr: to specify the language
;; - use :skos:note:1 or :skos:note:note_label for multiple notes
;; - implement related (add var with list of properties?)
;; - use SKOS_EXTENSION for ttl output ?
;; - write ox-skos-html to export to html
;; - write ox-skos-latex to export to latex (anf scribble?!)

;;; Code:

(require 'ox-html)
(require 'ob-core)
(require 'url-util)
(declare-function url-encode-url "url-util" (url))
(declare-function org-babel-parse-header-arguments "ob-core" (arg-string))

;;; Variables and options

(defgroup org-export-skos nil
  "Options specific to SKOS export back-end."
  :tag "Org SKOS"
  :group 'org-export)

(defcustom org-skos-extension "rdf"
  "File extension for the SKOS output file."
  :group 'org-export-skos
  :type 'string)

;;; Define backend

(org-export-define-derived-backend 'skos 'html
  :menu-entry
  '(?s "Export to SKOS"
       ((?s "As SKOS buffer"
	    (lambda (a s v b) (org-skos-export-as-skos a s v)))
	(?S "As SKOS file" (lambda (a s v b) (org-skos-export-to-skos a s v)))))
  :options-alist
  '((:description "DESCRIPTION" nil nil newline)
    (:coverage    "COVERAGE" nil nil newline)
    (:type        "TYPE" nil nil newline)
    (:source      "SOURCE" nil nil newline)
    (:contributor "CONTRIBUTOR" nil nil newline)
    (:homepage    "HOMEPAGE" nil nil newline)
    (:rights      "RIGHTS" nil nil newline)
    (:publisher   "PUBLISHER" nil nil newline)
    (:subject     "SUBJECT" nil nil newline)
    (:keywords    "KEYWORDS" nil nil space)
    (:skos-conceptschemeuri "SKOS_CONCEPTSCHEMEURI" nil nil t)
    (:with-toc nil nil nil)
    (:skos-extension "SKOS_EXTENSION" nil org-skos-extension))
  :filters-alist '((:filter-final-output . org-skos-final-function))
  :translate-alist '((headline . org-skos-headline)
		     (comment . (lambda (&rest args) ""))
		     (comment-block . (lambda (&rest args) ""))
		     (section . org-skos-section)
		     (paragraph . (lambda (&rest args) ""))
		     (template . org-skos-template)))

;;; Export variables

(defvar org-skos-uri-separator "#")

(defvar org-skos-terms nil
  "A list of terms to generate iso-thes data.")

;;; Export functions

;;;###autoload
(defun org-skos-export-as-skos (&optional async subtreep visible-only)
  "Export current buffer to a SKOS buffer.

If narrowing is active in the current buffer, only export its
narrowed part.

If a region is active, export that region.

A non-nil optional argument ASYNC means the process should happen
asynchronously.  The resulting buffer should be accessible
through the `org-export-stack' interface.

When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.

When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.

Export is done in a buffer named \"*Org SKOS Export*\", which will
be displayed when `org-export-show-temporary-export-buffer' is
non-nil."
  (interactive)
  (setq org-skos-terms nil)
  (org-export-to-buffer 'skos "*Org SKOS Export*"
    async subtreep visible-only nil nil (lambda () (text-mode))))

;;;###autoload
(defun org-skos-export-to-skos (&optional async subtreep visible-only)
  "Export current buffer to a SKOS file.

If narrowing is active in the current buffer, only export its
narrowed part.

If a region is active, export that region.

A non-nil optional argument ASYNC means the process should happen
asynchronously.  The resulting file should be accessible through
the `org-export-stack' interface.

When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.

When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.

Return output file's name."
  (interactive)
  (setq org-skos-terms nil)
  (let ((outfile (org-export-output-file-name
		  (concat "." org-skos-extension) subtreep)))
    (org-export-to-file 'skos outfile async subtreep visible-only)))

;;;###autoload
(defun org-skos-publish-to-skos (plist filename pub-dir)
  "Publish an org file to SKOS.

FILENAME is the filename of the Org file to be published.  PLIST
is the property list for the given project.  PUB-DIR is the
publishing directory.

Return output file name."
  (setq org-skos-terms nil)
  (org-publish-org-to
   'skos filename (concat "." org-skos-extension) plist pub-dir))

;;; Main transcoding functions

(defun org-skos-i18n (value lang attr conceptschemeuri)
  "Convert VALUE with LANG into xml attribute ATTR.
VALUE can be a string or an alist."
  (if (null value) ""
    (let* ((values (org-babel-parse-header-arguments value))
	   (uuid (org-id-new))
	   (attr0 (when (string-match "[^:]+:\\(.+\\)" attr)
		    (match-string 1 attr)))
	   (iso-thes-attr
	    (cond ((string= attr0 "prefLabel") "PreferredTerm")
		  ((string= attr0 "altLabel") "SimpleNonPreferredTerm")
		  (t ""))))
      (concat
       (when (or (string= attr0 "prefLabel")
		 (string= attr0 "altLabel"))
	 ;; Update the global list of terms
	 (push (list uuid attr0 values)
	       org-skos-terms)
	 (format (concat
		  "<xl:" attr0 ">\n<iso-thes:" iso-thes-attr
		  " rdf:about=\"%s" org-skos-uri-separator
		  "%s\" />\n</xl:" attr0 ">\n")
		 conceptschemeuri uuid))
       (mapconcat
	(lambda (lv)
	  (let ((l (if (cdr lv) (substring (symbol-name (car lv)) 1) lang))
		(v (if (cdr lv) (cdr lv) (symbol-name (car lv)))))
	    (format "<%s xml:lang=\"%s\">%s</%s>" attr l v attr)))
	values
	"\n")))))

(defun org-skos-headline (headline contents info)
  "Transcode HEADLINE element into SKOS format.
CONTENTS is the headline contents.  INFO is a plist used as a
communication channel."
  (let* ((uri (concat "#" 
		      (or (org-element-property :ID headline)
			  (url-encode-url
			   (org-element-property :URI headline)))))
	 (lang (org-export-data (plist-get info :language) info))
	 (timestr (format-time-string-ISO-8601))
	 ;; FIXME: check skos:scopeNote
	 (conceptschemeuri
	  (url-encode-url (plist-get info :skos-conceptschemeuri)))
	 (notation
	  (org-skos-i18n
	   (org-element-property :SKOS:NOTATION headline)
	   lang "skos:notation" conceptschemeuri))
	 (example
	  (org-skos-i18n
	   (org-element-property :SKOS:EXAMPLE headline)
	   lang "skos:example" conceptschemeuri))
	 (note
	  (org-skos-i18n
	   (org-element-property :SKOS:NOTE headline)
	   lang "skos:note" conceptschemeuri))
	 (altlabel
	  (org-skos-i18n
	   (org-element-property :SKOS:ALTLABEL headline)
	   lang "skos:altLabel" conceptschemeuri))
	 (preflabel
	  (org-skos-i18n
	   (or (org-element-property :SKOS:PREFLABEL headline)
	       (org-element-property :raw-value headline))
	   lang "skos:prefLabel" conceptschemeuri))
	 (broader
	  (org-element-property :URI (org-export-get-parent-headline headline)))
	 (narrower  ;; a list of narrower URIs
	  (org-element-map (plist-get info :parse-tree) 'headline
	    (lambda (h)
	      (if (equal
		   (org-element-property
		    :raw-value (org-export-get-parent-headline h))
		   (org-element-property :raw-value headline))
		  (org-element-property :URI h)))))
	 (parent (org-element-property :parent headline))
	 ;; FIXME use org-export-get-previous-element?
	 (first-para
	  (car (delete
		nil
		(org-element-map parent 'paragraph
		  (lambda (p)
		    (if (eq (org-element-property
			     :parent (org-element-property :parent p))
			    headline)
			p))))))
	 (definition
	   (or (org-skos-i18n
		(org-element-property :SKOS:DEFINITION headline)
		lang "skos:definition" conceptschemeuri)
	       (and first-para
		    (format "<skos:definition xml:lang=\"%s\">%s</skos:definition>"
			    lang
			    (org-trim
			     (buffer-substring-no-properties
			      (org-element-property :contents-begin first-para)
			      (org-element-property :contents-end first-para)))))
	       "NO DEFINITION")))
    (concat
     ;; Add basic SKOS info
     (format
      "<skos:Concept rdf:about=\"%s%s\">
  <rdf:type rdf:resource=\"http://www.w3.org/2004/02/skos/core#Concept\"/>
  <skos:inScheme>
    <skos:ConceptScheme rdf:about=\"%s\"/>
  </skos:inScheme>
<dct:modified>%s</dct:modified>
<dct:created>%s</dct:created>
  %s
  %s
  %s
  %s
  %s
  %s
<iso-thes:status>1</iso-thes:status>
"
      timestr timestr
      conceptschemeuri uri conceptschemeuri
      definition notation preflabel altlabel example note)
     ;; Possibly add "broader"
     (if broader
  	 (format "<skos:broader rdf:resource=\"%s%s\"/>\n" conceptschemeuri broader))
     ;; Possibly add "narrower"
     (if narrower
	 (mapconcat
	  (lambda (n)
	    (format "<skos:narrower rdf:resource=\"%s%s\"/>" conceptschemeuri n))
	  narrower "\n"))
     ;; Possibly add topConceptOf
     (if (= (org-element-property :level headline) 1)
  	 (format "<skos:topConceptOf rdf:resource=\"%s\"/>" conceptschemeuri))
     "\n</skos:Concept>\n"
     contents)))

(defun org-skos-build-iso-thes-term (term conceptschemeuri)
  "Use `term' to build iso-thes bloc.
`term' is a list with a uuid, an iso-thes attribute and a list of
cons formed from a language specified and a litteral."
  (let ((timestr (format-time-string-ISO-8601))
	(uuid (car term))
	(attr (nth 1 term))
	(values (nth 2 term)))
    (format
     "<iso-thes:%s rdf:about=\"%s%s%s\">
        <iso-thes:status>1</iso-thes:status>
        %s
        <dct:modified>%s</dct:modified>
        <dct:created>%s</dct:created>
    </iso-thes:%s>"
     attr
     conceptschemeuri org-skos-uri-separator uuid
     (mapconcat
      (lambda(v)
	(format "<xl:literalForm xml:lang=\"%s\">%s</xl:literalForm>"
		;; (car v)
		(substring (symbol-name (car v)) 1)
		(cdr v)))
      values "\n")
     timestr timestr
     attr)))

(defun org-skos-build-iso-thes-terms (contents info)
  "Build the list of iso-thes terms using `org-skos-terms'."
  (let ((conceptschemeuri (plist-get info :skos-conceptschemeuri)))
    (mapconcat
     (lambda (term)
       (org-skos-build-iso-thes-term term conceptschemeuri))
     org-skos-terms
     "\n")))

(defun format-time-string-ISO-8601 ()
  (concat
   (format-time-string "%Y-%m-%dT%T")
   ((lambda (x) (concat (substring x 0 3) ":" (substring x 3 5)))
    (format-time-string "%z"))))

(defun org-skos-build-top-level-description (contents info)
  (let ((conceptschemeuri (plist-get info :skos-conceptschemeuri))
	(description (plist-get info :description))
	(lang (org-export-data (plist-get info :language) info))
	(title (org-export-data (plist-get info :title) info))
	(publisher (org-export-data (plist-get info :publisher) info))
	(homepage (org-export-data (plist-get info :homepage) info))
	(rights (org-export-data (plist-get info :rights) info))
	(email (org-export-data (plist-get info :email) info))
	(type (org-export-data (plist-get info :type) info))
	(source (org-export-data (plist-get info :source) info))
	(author (org-export-data (plist-get info :author) info))
	(contributor (org-export-data (plist-get info :contributor) info))
	(subject (org-export-data (plist-get info :subject) info))
	(coverage (org-export-data (plist-get info :coverage) info))
	(timestr (format-time-string-ISO-8601)))
    (concat
     (format "<skos:ConceptScheme rdf:about=\"%s\">
<rdf:type rdf:resource=\"http://www.w3.org/2004/02/skos/core#ConceptScheme\"/>
<dc:rights>%s</dc:rights>
<dct:created>%s</dct:created>
<dc:relation></dc:relation>
<dct:issued>Publication</dct:issued>
<dct:modified>%s</dct:modified>
<dc:type>%s</dc:type>
<dc:source>%s</dc:source>
<dc:subject>%s</dc:subject>
<dc:coverage>%s</dc:coverage>
<dc:language>%s-%s</dc:language>
<dc:publisher>%s</dc:publisher>
<dc:contributor>%s</dc:contributor>
<dc:creator>
  <foaf:Organization>
    <foaf:mbox>%s</foaf:mbox>
    <foaf:homepage>%s</foaf:homepage>
    <foaf:name>%s</foaf:name>
  </foaf:Organization>
</dc:creator>
<dct:description xml:lang=\"%s\">%s</dct:description>
<dct:title xml:lang=\"%s\">%s</dct:title>\n"
	     conceptschemeuri
	     rights
	     timestr
	     timestr
	     type
	     source
	     subject
	     coverage
	     lang (upcase lang)
	     publisher
	     contributor
	     email homepage author
	     lang description lang title)
     (mapconcat
      (lambda (uri)
	(format "<skos:hasTopConcept rdf:resource=\"%s%s\"/>"
		conceptschemeuri
		uri))
      (org-element-map (plist-get info :parse-tree)
	  'headline (lambda (h)
		      ;; Only consider top-level concepts
		      (if (= (org-element-property :level h) 1)
			  (concat "#" (or (org-element-property :ID h)
					  (url-encode-url
					   (org-element-property :URI h)))))))
      "\n")
     "\n</skos:ConceptScheme>")))

(defun org-skos-template (contents info)
  "Return complete document string after SKOS conversion.
CONTENTS is the transcoded contents string.  INFO is a plist used
as a communication channel."
  (concat
   (format "<?xml version=\"1.0\" encoding=\"%s\"?>\n"
	   (symbol-name org-html-coding-system))
   "<rdf:RDF
    xmlns:schema=\"http://schema.org/\"
    xmlns:owl=\"http://www.w3.org/2002/07/owl#\"
    xmlns:org=\"http://www.w3.org/ns/org#\"
    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"
    xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"
    xmlns:dct=\"http://purl.org/dc/terms/\"
    xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
    xmlns:prov=\"http://www.w3.org/ns/prov#\"
    xmlns:foaf=\"http://xmlns.com/foaf/0.1/\"
    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
    xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"
    xmlns:skosxl=\"http://www.w3.org/2008/05/skos-xl#\"
    xmlns:euvoc=\"http://publications.europa.eu/ontology/euvoc#\">"
   "\n"
   "\n"
   ;; Add description of top-level concepts
   (org-skos-build-top-level-description contents info)
   "\n"
   contents
   (org-skos-build-iso-thes-terms contents info)
   "\n</rdf:RDF>"))

(defun org-skos-section (section contents info)
  "Transcode SECTION element into SKOS format.
CONTENTS is the section contents.  INFO is a plist used as
a communication channel."
  contents)

;;; Filters

(defun org-skos-final-function (contents backend info)
  "Prettify the SKOS output."
  (with-temp-buffer
    (xml-mode)
    (insert contents)
    (indent-region (point-min) (point-max))
    (buffer-substring-no-properties (point-min) (point-max))))

(provide 'ox-skos)

;;; ox-skos.el ends here