-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.xqm
1679 lines (1592 loc) · 48.2 KB
/
api.xqm
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
xquery version "3.1";
module namespace api = "http://dracor.org/ns/exist/v1/api";
import module namespace config = "http://dracor.org/ns/exist/v1/config" at "config.xqm";
import module namespace dutil = "http://dracor.org/ns/exist/v1/util" at "util.xqm";
import module namespace load = "http://dracor.org/ns/exist/v1/load" at "load.xqm";
import module namespace wd = "http://dracor.org/ns/exist/v1/wikidata" at "wikidata.xqm";
import module namespace openapi = "https://lab.sub.uni-goettingen.de/restxqopenapi";
declare namespace rest = "http://exquery.org/ns/restxq";
declare namespace http = "http://expath.org/ns/http-client";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare namespace repo = "http://exist-db.org/xquery/repo";
declare namespace expath = "http://expath.org/ns/pkg";
declare namespace json = "http://www.w3.org/2013/XSL/json";
declare namespace tei = "http://www.tei-c.org/ns/1.0";
declare namespace jsn = "http://www.json.org";
declare namespace test = "http://exist-db.org/xquery/xqsuite";
declare namespace rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
declare variable $api:metadata-columns := (
"name",
"id",
"wikidataId",
"firstAuthor",
"numOfCoAuthors",
"title",
"subtitle",
"normalizedGenre",
"digitalSource",
"originalSourcePublisher",
"originalSourcePubPlace",
"originalSourceYear",
"originalSourceNumberOfPages",
"yearNormalized",
"size",
"libretto",
"averageClustering",
"density",
"averagePathLength",
"maxDegreeIds",
"averageDegree",
"diameter",
"datePremiered",
"yearPremiered",
"yearPrinted",
"maxDegree",
"numOfSpeakers",
"numOfSpeakersFemale",
"numOfSpeakersMale",
"numOfSpeakersUnknown",
"numOfPersonGroups",
"numConnectedComponents",
"numEdges",
"yearWritten",
"numOfSegments",
"wikipediaLinkCount",
"numOfActs",
"wordCountText",
"wordCountSp",
"wordCountStage",
"numOfP",
"numOfL"
);
(:~
: API base
:
: Mirrors api:info
:
: @result JSON object
:)
declare
%rest:GET
%rest:path("/v1")
%rest:produces("application/json")
%output:method("json")
function api:base() {
api:info()
};
(:~
: API info
:
: Shows version numbers of the dracor-api app and the underlying eXist-db.
:
: @result JSON object
:)
declare
%rest:GET
%rest:path("/v1/info")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
function api:info() {
let $expath := config:expath-descriptor()
let $repo := config:repo-descriptor()
return map {
"name": $expath/expath:title/string(),
"version": $expath/@version/string(),
"status": $repo/repo:status/string(),
"existdb": system:get-version(),
"base": $config:api-base,
"openapi": $config:api-base || "/openapi.yaml"
}
};
(:~
: OpenAPI info
:
: @result JSON object
:)
declare
%rest:GET
%rest:path("/v1/openapi")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
function api:openapi() {
openapi:main($config:app-root)
};
(:~
: OpenAPI info yaml
:
: @result YAML
:)
declare
%rest:GET
%rest:path("/v1/openapi.yaml")
%rest:produces("application/yaml")
%output:media-type("application/yaml")
%output:method("text")
function api:openapi-yaml() {
let $path := $config:app-root || "/api.yaml"
let $expath := config:expath-descriptor()
let $yaml := util:base64-decode(xs:string(util:binary-doc($path)))
return replace(
replace($yaml, 'https://dracor.org/api/v1', $config:api-base),
'version: [0-9.]+',
'version: ' || $expath/@version/string()
)
};
declare
%rest:GET
%rest:path("/v1/resources")
%rest:produces("application/xml", "text/xml")
function api:resources() {
rest:resource-functions()
};
declare function local:get-index-keys ($collection as xs:string, $elem as xs:string) {
<terms element="{$elem}" collection="{$collection}">
{
util:index-keys(
collection($collection)//tei:*[name() eq $elem], "",
function($key, $count) {
<term name="{$key}" count="{$count[1]}"docs="{$count[2]}" pos="{$count[3]}"/>
},
-1,
"lucene-index"
)
}
</terms>
};
(:~
: Resolve DraCor ID of a play
:
: Depending on the `Accept` header this endpoint redirects to either the RDF
: representation, the JSON metadata or the dracor.org page of the play
: identified by $id.
:
: @param $id DraCor ID
: @param $accept Accept header value
: @result redirect
:)
declare
%rest:GET
%rest:path("/v1/id/{$id}")
%rest:header-param("Accept", "{$accept}")
function api:id-to-url($id, $accept) {
let $url := dutil:id-to-url($id, $accept)
return if (not($url)) then
<rest:response>
<http:response status="404"/>
</rest:response>
else
<rest:response>
<http:response status="303">
<http:header name="location" value="{$url}"/>
</http:response>
</rest:response>
};
declare function local:get-corpus-metrics ($corpus as xs:string) {
let $collection-uri := concat($config:corpora-root, "/", $corpus)
let $col := collection($collection-uri)
let $num-plays := count($col/tei:TEI)
let $list := $col//tei:particDesc/tei:listPerson
let $num-characters := count($list/(tei:person|tei:personGrp))
let $num-male := count($list/(tei:person|tei:personGrp)[@sex="MALE"])
let $num-female := count($list/(tei:person|tei:personGrp)[@sex="FEMALE"])
let $num-text := count($col//tei:text)
let $num-stage := count($col//tei:stage)
let $num-sp := count($col//tei:sp)
return map {
"plays": $num-plays,
"characters": $num-characters,
"male": $num-male,
"female": $num-female,
"text": $num-text,
"sp": $num-sp,
"stage": $num-stage,
"wordcount": map {
"text": sum($col/metrics/text),
"sp": sum($col/metrics/sp),
"stage": sum($col/metrics/stage)
},
"updated": max($col/metrics/xs:dateTime(@updated))
}
};
(:~
: List available corpora
:
: @result JSON array of objects
:)
declare
%rest:GET
%rest:path("/v1/corpora")
%rest:query-param("include", "{$include}")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
function api:corpora($include) {
array {
for $corpus in collection($config:corpora-root)//tei:teiCorpus
let $info := dutil:get-corpus-info($corpus)
let $name := $info?name
order by $name
return map:merge ((
$info,
map:entry("uri", $config:api-base || '/corpora/' || $name),
if ($include = "metrics") then (
map:entry("metrics", local:get-corpus-metrics($name))
) else ()
))
}
};
(:~
: Add new corpus
:
: @param $data corpus.xml containing teiCorpus element.
: @result XML document
:
: FIXME: create utility function that can be used both here and in
: api:corpora-post-json() below.
:)
declare
%rest:POST("{$data}")
%rest:path("/v1/corpora")
%rest:header-param("Authorization", "{$auth}")
%rest:consumes("application/xml", "text/xml")
%rest:produces("application/json")
%output:method("json")
function api:corpora-post-tei($data, $auth) {
if (not($auth)) then
(
<rest:response>
<http:response status="401"/>
</rest:response>,
map {
"message": "authorization required"
}
)
else
let $header := $data//tei:teiCorpus/tei:teiHeader
let $name := $header//tei:publicationStmt/tei:idno[
@type = "URI" and @xml:base = "https://dracor.org/"
]/text()
let $title := $header//tei:titleStmt/tei:title[1]/text()
return if (not($header)) then
(
<rest:response>
<http:response status="400"/>
</rest:response>,
map {
"error": "invalid document, expecting <teiCorpus>"
}
)
else if (not($name) or not($title)) then
(
<rest:response>
<http:response status="400"/>
</rest:response>,
map {
"error": "missing name or title"
}
)
else if (not(matches($name, '^[-a-z0-1]+$'))) then
(
<rest:response>
<http:response status="400"/>
</rest:response>,
map {
"error": "invalid name",
"message": "Only lower case ASCII letters and digits are accepted."
}
)
else
let $corpus := dutil:get-corpus($name)
return if ($corpus) then (
<rest:response>
<http:response status="409"/>
</rest:response>,
map {
"error": "corpus already exists"
}
) else (
dutil:create-corpus($name, $data/tei:teiCorpus),
map {
"name": $name,
"title": $title
}
)
};
(:~
: Add new corpus
:
: @param $data JSON object describing corpus meta data
: @result JSON object
:
: FIXME: create utility function that can be used both here and in
: api:corpora-post-tei() above.
:)
declare
%rest:POST("{$data}")
%rest:path("/v1/corpora")
%rest:consumes("application/json")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
function api:corpora-post-json($data) {
let $json := parse-json(util:base64-decode($data))
let $name := $json?name
let $description := $json?description
let $corpus := dutil:get-corpus($name)
return if ($corpus) then
(
<rest:response>
<http:response status="409"/>
</rest:response>,
map {
"error": "corpus already exists"
}
)
else if (not($name) or not($json?title)) then
(
<rest:response>
<http:response status="400"/>
</rest:response>,
map {
"error": "missing name or title"
}
)
else if (not(matches($name, '^[-a-z0-1]+$'))) then
(
<rest:response>
<http:response status="400"/>
</rest:response>,
map {
"error": "invalid name",
"message": "Only lower case ASCII letters and digits are accepted."
}
)
else (
dutil:create-corpus($json),
$json
)
};
(:~
: List corpus content
:
: Lists all plays available in the corpus including the id, title, author(s)
: and other meta data.
:
: @param $corpusname
: @result
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
function api:corpus-index($corpusname) {
let $corpus := dutil:get-corpus-info-by-name($corpusname)
let $title := $corpus?title
let $description := $corpus?description
let $collection := $config:corpora-root || "/" || $corpusname
let $col := collection($collection)
return
if (not($corpus?name) or not(xmldb:collection-available($collection))) then
<rest:response>
<http:response status="404"/>
</rest:response>
else map:merge((
$corpus,
map:entry("plays", array {
for $tei in $col//tei:TEI
let $paths := dutil:filepaths(base-uri($tei))
let $name := $paths?playname
let $id := dutil:get-dracor-id($tei)
let $titles := dutil:get-titles($tei)
let $titlesEng := dutil:get-titles($tei, 'eng')
let $years := dutil:get-years-iso($tei)
let $authors := dutil:get-authors($tei)
let $play-uri :=
$config:api-base || "/corpora/" || $corpusname || "/plays/" || $name
let $metrics-url := $paths?files?metrics
let $network-size := doc($metrics-url)//network/size/text()
let $yearNormalized := dutil:get-normalized-year($tei)
let $premiere-date := dutil:get-premiere-date($tei)
let $source := dutil:get-source($tei)
order by $authors[1]?name
return map:merge((
map:entry("id", $id),
map:entry("uri", $play-uri),
map:entry("name", $name),
map:entry("title", $titles?main),
if ($titles?sub) then map:entry("subtitle", $titles?sub) else (),
if ($titlesEng?main) then map:entry("titleEn", $titlesEng?main) else (),
if ($titlesEng?sub) then map:entry("subtitleEn", $titlesEng?sub) else (),
map:entry("authors", array { $authors }),
if (count($source)) then map:entry("source", $source) else (),
map:entry("yearNormalized", $yearNormalized),
map:entry("yearPrinted", $years?print),
map:entry("yearPremiered", $years?premiere),
if($premiere-date) then map:entry("datePremiered", $premiere-date) else (),
map:entry("yearWritten", $years?written),
map:entry("networkSize", xs:integer($network-size)),
map:entry("networkdataCsvUrl", $play-uri || "/networkdata/csv"),
map:entry("wikidataId", dutil:get-play-wikidata-id($tei))
))
})
))
};
(:~
: Load corpus data from its repository
:
: Posting `{"load": true}` to the corpus URI reloads the data for this corpus
: from its repository (if defined). This endpoint requires authorization.
:
: @param $corpusname Corpus name
: @param $data JSON object
: @param $auth Authorization header value
: @result JSON object
:)
declare
%rest:POST("{$data}")
%rest:path("/v1/corpora/{$corpusname}")
%rest:header-param("Authorization", "{$auth}")
%rest:consumes("application/json")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
%test:arg("corpusname", "test")
%test:arg("data", '{"load": true}')
%test:arg("auth", "Basic YWRtaW46")
function api:post-corpus($corpusname, $data, $auth) {
if (not($auth)) then
(
<rest:response>
<http:response status="401"/>
</rest:response>,
map {
"message": "authorization required"
}
)
else
let $json := parse-json(util:base64-decode($data))
let $corpus := dutil:get-corpus-info-by-name($corpusname)
return
if (not($corpus?name)) then
(
<rest:response><http:response status="404"/></rest:response>,
map {"message": "no such corpus"}
)
else if (count($json) = 0) then
(
<rest:response><http:response status="400"/></rest:response>,
map {"message": "missing payload"}
)
else if ($json?load) then
let $job-name := "load-corpus-" || $corpusname
let $params := (
<parameters>
<param name="corpusname" value="{$corpusname}"/>
</parameters>
)
(: delete completed job before scheduling new one :)
(: NB: usually this seems to happen automatically but apparently we
: cannot rely on it. :)
let $jobs := scheduler:get-scheduled-jobs()
let $complete := $jobs//scheduler:job
[@name=$job-name and scheduler:trigger/state = 'COMPLETE']
let $log := if ($complete) then (
util:log("info", "deleting completed job"),
scheduler:delete-scheduled-job($job-name)
) else ()
let $result := scheduler:schedule-xquery-periodic-job(
$config:app-root || "/jobs/load-corpus.xq",
1, $job-name, $params, 0, 0
)
return if ($result) then
(
<rest:response><http:response status="202"/></rest:response>,
map {"message": "corpus update scheduled"}
)
else
(
<rest:response><http:response status="409"/></rest:response>,
map {"message": "cannot schedule update"}
)
else
(
<rest:response><http:response status="400"/></rest:response>,
map {"message": "invalid payload"}
)
};
(:~
: Remove corpus from database
:
: @param $corpusname Corpus name
: @param $auth Authorization header value
: @result JSON object
:)
declare
%rest:DELETE
%rest:path("/v1/corpora/{$corpusname}")
%rest:header-param("Authorization", "{$auth}")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
function api:delete-corpus($corpusname, $auth) {
if (not($auth)) then
(
<rest:response>
<http:response status="401"/>
</rest:response>,
map {
"message": "authorization required"
}
)
else
let $corpus := dutil:get-corpus($corpusname)
return
if (not($corpus)) then
<rest:response>
<http:response status="404"/>
</rest:response>
else
let $url := $config:corpora-root || "/" || $corpusname || "/corpus.xml"
return
if ($url = $corpus/base-uri()) then
(
xmldb:remove($config:corpora-root || "/" || $corpusname),
map {
"message": "corpus deleted",
"uri": $url
}
)
else
(
<rest:response>
<http:response status="404"/>
</rest:response>
)
};
(:~
: List of metadata for all plays in a corpus
:
: @param $corpusname Corpus name
: @result JSON array of metadata for all plays
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/metadata")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
function api:corpus-meta-data($corpusname) {
let $corpus := dutil:get-corpus($corpusname)
return
if (not($corpus)) then
(
<rest:response><http:response status="404"/></rest:response>,
map {"message": "no such corpus"}
)
else
let $meta := dutil:get-corpus-meta-data($corpusname)
return array { $meta }
};
declare function api:get-corpus-meta-data-csv($corpusname) {
let $corpus := dutil:get-corpus($corpusname)
return
if (not($corpus)) then
<rest:response>
<http:response status="404"/>
</rest:response>
else
let $meta := dutil:get-corpus-meta-data($corpusname)
let $header := concat(string-join($api:metadata-columns, ","), " ")
let $rows :=
for $m in $meta return concat(
'"',
string-join((
for $c in $api:metadata-columns
return if (count($m($c)) = 0) then '' else dutil:csv-escape($m($c))
), '","'), '" ')
return ($header, $rows)
};
(:~
: List of metadata for all plays in a corpus
:
: @param $corpusname Corpus name
: @result comma separated list of metadata for all plays
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/metadata")
%rest:produces("text/csv", "text/plain")
%output:media-type("text/csv")
%output:method("text")
function api:corpus-meta-data-csv($corpusname) {
api:get-corpus-meta-data-csv($corpusname)
};
(:~
: List of metadata for all plays in a corpus
:
: @param $corpusname Corpus name
: @result comma separated list of metadata for all plays
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/metadata/csv")
%rest:produces("text/csv", "text/plain")
%output:media-type("text/csv")
%output:method("text")
function api:corpus-meta-data-csv-endpoint($corpusname) {
api:get-corpus-meta-data-csv($corpusname)
};
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/word-frequencies/{$elem}")
%rest:produces("application/xml", "text/xml")
function api:word-frequencies-xml($corpusname, $elem) {
let $collection := concat($config:corpora-root, "/", $corpusname)
let $terms := local:get-index-keys($collection, $elem)
return $terms
};
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/word-frequencies/{$elem}")
%rest:produces("text/csv", "text/plain")
%output:media-type("text/csv")
%output:method("text")
function api:word-frequencies-csv($corpusname, $elem) {
let $collection := concat($config:corpora-root, "/", $corpusname)
let $terms := local:get-index-keys($collection, $elem)
for $t in $terms/term
order by number($t/@count) descending
return concat($t/@name, ", ", $t/@count, ", ", $t/@docs, " ")
};
(:~
: Get metadata for a single play
:
: @param $corpusname Corpus name
: @param $playname Play name
: @result JSON object with play meta data
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/plays/{$playname}")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
function api:play-info($corpusname, $playname) {
let $info := dutil:get-play-info($corpusname, $playname)
return
if (count($info)) then
$info
else
<rest:response>
<http:response status="404"/>
</rest:response>
};
(:~
: Remove a single play from the corpus
:
: @param $corpusname Corpus name
: @param $playname Play name
: @param $auth Authorization header value
: @result JSON object
:)
declare
%rest:DELETE
%rest:path("/v1/corpora/{$corpusname}/plays/{$playname}")
%rest:header-param("Authorization", "{$auth}")
%output:method("json")
function api:play-delete($corpusname, $playname, $data, $auth) {
if (not($auth)) then
<rest:response>
<http:response status="401"/>
</rest:response>
else
let $paths := dutil:filepaths($corpusname, $playname)
return
if (not(doc($paths?files?tei))) then
<rest:response>
<http:response status="404"/>
</rest:response>
else
xmldb:remove($paths?collections?play)
};
(:~
: Get metrics for a single play
:
: @param $corpusname Corpus name
: @param $playname Play name
: @result JSON object with play metrics
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/plays/{$playname}/metrics")
%rest:produces("application/json")
%output:media-type("application/json")
%output:method("json")
function api:play-metrics($corpusname, $playname) {
let $metrics := dutil:get-play-metrics($corpusname, $playname)
return
if (count($metrics)) then
$metrics
else
<rest:response>
<http:response status="404"/>
</rest:response>
};
(:~
: Get TEI representation of a single play
:
: @param $corpusname Corpus name
: @param $playname Play name
: @result TEI document
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/plays/{$playname}/tei")
%rest:produces("application/xml", "text/xml")
%output:media-type("application/xml")
function api:play-tei($corpusname, $playname) {
let $doc := dutil:get-doc($corpusname, $playname)
return
if (not($doc)) then
<rest:response>
<http:response status="404"/>
</rest:response>
else
let $tei := $doc//tei:TEI
let $model-pi := $doc/processing-instruction(xml-model)
return if ($model-pi) then
document {
processing-instruction {'xml-model'} {$model-pi/string()},
$tei
}
else $tei
};
(:~
: Add new or update existing TEI document
:
: When sending a PUT request to a new play URI, the request body is stored in
: the database as a new document accessible under that URI. If the URI already
: exists the corresponding TEI document is updated with the request body.
:
: The `playname` parameter of a new URI must consist of lower case ASCII
: characters, digits and/or dashes only.
:
: @param $corpusname Corpus name
: @param $playname Play name
: @param $data TEI document
: @param $auth Authorization header value
: @result updated TEI document
:)
declare
%rest:PUT("{$data}")
%rest:path("/v1/corpora/{$corpusname}/plays/{$playname}/tei")
%rest:header-param("Authorization", "{$auth}")
%rest:consumes("application/xml", "text/xml")
%output:method("xml")
function api:play-tei-put($corpusname, $playname, $data, $auth) {
if (not($auth)) then
<rest:response>
<http:response status="401"/>
</rest:response>
else
let $corpus := dutil:get-corpus($corpusname)
let $doc := dutil:get-doc($corpusname, $playname)
return
if (not($corpus)) then
(
<rest:response>
<http:response status="404"/>
</rest:response>,
<message>No such corpus</message>
)
else if (
not($doc) and
not(matches($playname, "^[a-z0-9]+(-?[a-z0-9]+)*$"))
)
then
(
<rest:response>
<http:response status="400"/>
</rest:response>,
<message>Unacceptable play name '{$playname}'. Use lower case ASCII characters, digits and dashes only.</message>
)
else if (not($data/tei:TEI)) then
(
<rest:response>
<http:response status="400"/>
</rest:response>,
<message>TEI document required</message>
)
else
let $collection := xmldb:create-collection(
$config:corpora-root || "/" || $corpusname, $playname
)
let $result := xmldb:store($collection, "tei.xml", $data/tei:TEI)
return $data
};
(:~
: Get RDF document for a single play
:
: @param
: @result
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/plays/{$playname}/rdf")
%rest:produces("application/xml", "text/xml")
%output:media-type("application/xml")
function api:play-rdf($corpusname, $playname) {
let $paths := dutil:filepaths($corpusname, $playname)
let $doc := doc($paths?files?rdf)
return
if (not($doc)) then
<rest:response>
<http:response status="404"/>
</rest:response>
else $doc
};
(:~
: Get network data of a play as CSV
:
: @param $corpusname Corpus name
: @param $playname Play name
: @result CSV document
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/plays/{$playname}/networkdata/csv")
%rest:produces("text/csv", "text/plain")
%output:media-type("text/csv")
%output:method("text")
function api:networkdata-csv($corpusname, $playname) {
let $doc := dutil:get-doc($corpusname, $playname)
return
if (not($doc)) then
<rest:response>
<http:response status="404"/>
</rest:response>
else
let $speakers := dutil:distinct-speakers($doc//tei:body)
let $segments :=
<segments>
{
for $seg in dutil:get-segments($doc//tei:TEI)
return
<sgm>
{
for $id in dutil:distinct-speakers($seg)
return <spkr>{$id}</spkr>
}
</sgm>
}
</segments>
let $links := map:merge(
for $spkr in $speakers
let $cooccurences := $segments//sgm[spkr=$spkr]/spkr/text()
return map:entry($spkr, distinct-values($cooccurences)[.!=$spkr])
)
let $rows :=
for $spkr at $pos in $speakers
for $cooc in $links($spkr)
where index-of($speakers, $cooc)[1] gt $pos
let $weight := $segments//sgm[spkr=$spkr][spkr=$cooc] => count()
return string-join(($spkr, 'Undirected',$cooc, $weight), ",")
return string-join(("Source,Type,Target,Weight", $rows, ""), " ")
};
declare function local:make-gexf-nodes($speakers, $doc) as element()* {
for $n in $speakers?*
let $id := $n?id
let $label := $n?name
let $sex := $n?sex
let $group := if ($n?isGroup) then 1 else 0
let $wc := dutil:num-of-spoken-words($doc//tei:body, $id)
return
<node xmlns="http://www.gexf.net/1.2draft"
id="{$id}" label="{$label}">
<attvalues>
<attvalue for="person-group" value="{$group}" />
<attvalue for="number-of-words" value="{$wc}" />
{
if ($sex) then
<attvalue for="gender" value="{$sex}"></attvalue>
else ()
}
</attvalues>
</node>
};
(:~
: Get network data of a play as GEXF
:
: @param $corpusname Corpus name
: @param $playname Play name
: @result GEXF document
:)
declare
%rest:GET
%rest:path("/v1/corpora/{$corpusname}/plays/{$playname}/networkdata/gexf")
%output:method("xml")
%output:omit-xml-declaration("no")
function api:networkdata-gexf($corpusname, $playname) {
let $doc := dutil:get-doc($corpusname, $playname)
return
if (not($doc)) then
<rest:response>
<http:response status="404"/>
</rest:response>
else
let $speakers := dutil:distinct-speakers($doc//tei:body)
let $segments :=
<segments>
{
for $seg in dutil:get-segments($doc//tei:TEI)
return
<sgm>
{