-
Notifications
You must be signed in to change notification settings - Fork 0
/
LabbcatView.py
1567 lines (1248 loc) · 64 KB
/
LabbcatView.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
import json
import os
import re
import requests
import tempfile
import time
from zipfile import ZipFile
from labbcat.Response import Response
from labbcat.ResponseException import ResponseException
from labbcat import __version__
class LabbcatView:
""" API for querying a `LaBB--CAT <https://labbcat.canterbury.ac.nz/>`_ annotation graph
store; a database of linguistic transcripts represented using
`Annotation Graphs <https://nzilbb.github.io/ag/>`_
This interface provides only *read-only* operations, i.e. those that can be performed
by users with "view" permission.
Constructor arguments:
:param labbcatUrl: The 'home' URL of the LaBB-CAT server.
:type labbcatUrl: str
:param username: The username for logging in to the server, if necessary.
:type username: str or None
:param password: The password for logging in to the server, if necessary.
:type password: str or None
Attributes:
language: The language code for server message localization, e.g. "es-AR"
Example::
import labbcat
# create annotation store client
corpus = labbcat.LabbcatView("https://labbcat.canterbury.ac.nz", "demo", "demo");
# show some basic information
print("Information about LaBB-CAT at " + corpus.getId())
layerIds = corpus.getLayerIds()
for layerId in layerIds:
print("layer: " + layerId)
corpora = corpus.getCorpusIds()
for c in corpora:
print("transcripts in: " + c)
for transcript in corpus.getTranscriptIdsInCorpus(c):
print(" " + transcript)
"""
def __init__(self, labbcatUrl, username=None, password=None):
""" Constructor. """
if labbcatUrl.endswith("/"):
self.labbcatUrl = labbcatUrl
else:
self.labbcatUrl = labbcatUrl + "/"
self.username = username
self.password = password
self.verbose = False
self.language = "en"
def _labbcatUrl(self, resource):
return self.labbcatUrl + resource
def _storeQueryUrl(self, resource):
return self.labbcatUrl + "api/store/" + resource
def _getRequest(self, url, params):
if self.verbose: print("_getRequest " + url + " : " + str(params))
if self.username == None:
auth = None
else:
auth = (self.username, self.password)
response = Response(
requests.get(
url=url, params=params, auth=auth, headers={
"Accept":"application/json",
"Accept-Language":self.language,
"user-agent": "labbcat-py/"+__version__}),
self.verbose)
response.checkForErrors()
if self.verbose: print("response: " + str(response.text))
return(response.model)
def _postRequest(self, url, params, json=None):
if self.verbose: print("_postRequest " + url + " : " + str(params) + " : " + str(json))
if self.username == None:
auth = None
else:
auth = (self.username, self.password)
response = Response(
requests.post(
url=url, data=params, json=json, auth=auth, headers={
"Accept":"application/json",
"Accept-Language":self.language,
"user-agent": "labbcat-py/"+__version__}),
self.verbose)
response.checkForErrors()
if self.verbose: print("model: " + str(response.model))
return(response.model)
def _putRequest(self, url, params, json=None):
if self.verbose: print("_putRequest " + url + " : " + str(params) + " : " + str(json))
if self.username == None:
auth = None
else:
auth = (self.username, self.password)
response = Response(
requests.put(
url=url, params=params, json=json, auth=auth, headers={
"Accept":"application/json",
"Accept-Language":self.language,
"user-agent": "labbcat-py/"+__version__
}),
self.verbose)
response.checkForErrors()
if self.verbose: print("model: " + str(response.model))
return(response.model)
def _deleteRequest(self, url, params, json=None):
if self.verbose: print("_deleteRequest " + url + " : " + str(params) + " : " + str(json))
if self.username == None:
auth = None
else:
auth = (self.username, self.password)
response = Response(
requests.delete(
url=url, params=params, json=json, auth=auth, headers={
"Accept":"application/json",
"Accept-Language":self.language,
"user-agent": "labbcat-py/"+__version__
}),
self.verbose)
response.checkForErrors()
if self.verbose: print("model: " + str(response.model))
return(response.model)
def _postRequestToFile(self, url, params, dir=None):
if self.verbose: print("_postRequestToFile " + url + " : " + str(params) + " -> " + dir)
if self.username == None:
auth = None
else:
auth = (self.username, self.password)
response = requests.post(
url=url, data=params, auth=auth, headers={
"Accept":"application/json",
"Accept-Language":self.language,
"user-agent": "labbcat-py/"+__version__
})
if self.verbose: print(response.request.body)
# ensure status was ok
response.raise_for_status();
# figure out the content type
contentType = response.headers['Content-Type'];
if self.verbose: print("Content-Type: " + contentType)
extension = ".bin"
if contentType.startswith("text/csv"): extension = ".csv"
elif contentType.startswith("application/json"): extension = ".json"
elif contentType.startswith("text/plain"): extension = ".txt"
elif contentType.startswith("text/html"): extension = ".html"
elif contentType.startswith("application/zip"): extension = ".zip"
elif contentType.startswith("audio/wav"): extension = ".wav"
elif contentType.startswith("audio/x-wav"): extension = ".wav"
elif contentType.startswith("audio/mpeg"): extension = ".mp3"
elif contentType.startswith("video/mpeg"): extension = ".mp4"
fileName = None
if dir == None:
# save to temporary file
fd, fileName = tempfile.mkstemp(extension, "labbcat-py-")
if self.verbose: print("file: " + fileName)
with open(fileName, "wb") as file:
file.write(response.content)
os.close(fd)
else:
# save into the given directory...
# use the name given by the server, if any
contentDisposition = None
if "content-disposition" in response.headers:
contentDisposition = response.headers["content-disposition"];
if self.verbose: print("contentDisposition: " + contentDisposition)
if contentDisposition != None:
# something like attachment; filename=blah.wav
equals = contentDisposition.find("=")
if equals >= 0:
fileName = contentDisposition[equals + 1:]
if self.verbose: print("fileName: " + fileName)
if fileName == "":
fileName = None
else:
fileName = os.path.join(dir, fileName)
if fileName == None:
lastSlash = url.rfind('/')
if lastSlash >= 0:
fileName = url[lastSlash + 1:]
if not fileName.endswith(extension): fileName = fileName + extension
fileName = os.path.join(dir, fileName)
else:
fd, fileName = tempfile.mkstemp(extension, "labbcat-py-", dir)
os.close(fd)
if self.verbose: print("file: " + fileName)
with open(fileName, "wb") as file:
file.write(response.content)
return(fileName)
def _postMultipartRequest(self, url, params, files):
if self.verbose: print("_postMultipartRequest " + url + " : " + str(params) + " - " + str(files))
if self.username == None:
auth = None
else:
auth = (self.username, self.password)
response = Response(requests.post(
url=url, data=params, files=files, auth=auth, headers={
"Accept":"application/json",
"Accept-Language":self.language,
"user-agent": "labbcat-py/"+__version__
}))
# close the files
for param in files:
name, fd = files[param]
fd.close()
# check for errors
response.checkForErrors()
if self.verbose: print("model: " + str(response.model))
return(response.model)
def getId(self):
""" Gets the store's ID.
:returns: The annotation store's ID.
:rtype: str
"""
return(self._getRequest(self._storeQueryUrl("getId"), None))
def getLayerIds(self):
""" Gets a list of layer IDs (annotation 'types').
:returns: A list of layer IDs.
:rtype: list
"""
return(self._getRequest(self._storeQueryUrl("getLayerIds"), None))
def getLayers(self):
""" Gets a list of layer definitions.
:returns: A list of layer definitions.
:rtype: list of dictionaries
"""
return(self._getRequest(self._storeQueryUrl("getLayers"), None))
def getLayer(self, id):
""" Gets a layer definition.
:param id: ID of the layer to get the definition for.
:type id: str
:returns: The definition of the given layer.
:rtype: dictionary
"""
return(self._getRequest(self._storeQueryUrl("getLayer"), {"id":id}))
def getCorpusIds(self):
""" Gets a list of corpus IDs.
:returns: A list of corpus IDs.
:rtype: list
"""
return(self._getRequest(self._storeQueryUrl("getCorpusIds"), None))
def getParticipantIds(self):
""" Gets a list of participant IDs.
:returns: A list of participant IDs.
:rtype: list
"""
return(self._getRequest(self._storeQueryUrl("getParticipantIds"), None))
def getParticipant(self, id):
""" Gets the participant record specified by the given identifier.
:param id: The ID of the participant, which could be their name or their database
annotation ID.
:type id: str
:returns: An annotation representing the participant, or null if the participant
:rtype: dictionary
was not found.
"""
return(self._getRequest(self._storeQueryUrl("getParticipant"), {"id":id}))
def countMatchingParticipantIds(self, expression):
""" Counts the number of participants that match a particular pattern.
The expression language is loosely based on JavaScript; expressions such as the
following can be used:
- ``/Ada.+/.test(id)``
- ``labels('corpus').includes('CC')``
- ``labels('participant_languages').includes('en')``
- ``labels('transcript_language').includes('en')``
- ``!/Ada.+/.test(id) && my('corpus').label == 'CC'``
- ``list('transcript_rating').length < 2``
- ``list('participant_rating').length = 0``
- ``!annotators('transcript_rating').includes('labbcat')``
- ``my('participant_gender').label == 'NA'``
:param expression: An expression that determines which participants match.
:type expression: str
:returns: The number of matching participants.
:rtype: int
"""
return(self._getRequest(
self._storeQueryUrl("countMatchingParticipantIds"),
{ "expression":expression }))
def getMatchingParticipantIds(self, expression, pageLength=None, pageNumber=None):
""" Gets a list of IDs of participants that match a particular pattern.
The expression language is loosely based on JavaScript; expressions such as the
following can be used:
- ``/Ada.+/.test(id)``
- ``labels('corpus').includes('CC')``
- ``labels('participant_languages').includes('en')``
- ``labels('transcript_language').includes('en')``
- ``!/Ada.+/.test(id) && my('corpus').label == 'CC'``
- ``list('transcript_rating').length < 2``
- ``list('participant_rating').length = 0``
- ``!annotators('transcript_rating').includes('labbcat')``
- ``my('participant_gender').label == 'NA'``
:param expression: An expression that determines which participants match.
:type expression: str
:param pageLength: The maximum number of IDs to return, or null to return all.
:type pageLength: int or None
:param pageNumber: The zero-based page number to return, or null to return the first page.
:type pageNumber: int or None
:returns: A list of participant IDs.
:rtype: list
"""
return(self._getRequest(
self._storeQueryUrl("getMatchingParticipantIds"),
{"expression":expression,
"pageLength":pageLength, "pageNumber":pageNumber}))
def getTranscriptIds(self):
""" Gets a list of transcript IDs.
:returns: A list of transcript IDs.
:rtype: list
"""
return(self._getRequest(self._storeQueryUrl("getTranscriptIds"), None))
def getTranscriptIdsInCorpus(self, id):
""" Gets a list of transcript IDs in the given corpus.
:param id: A corpus ID.
:type id: str
:returns: A list of transcript IDs.
:rtype: list
"""
return(self._getRequest(self._storeQueryUrl("getTranscriptIdsInCorpus"), {"id":id}))
def getTranscriptIdsWithParticipant(self, id):
""" Gets a list of IDs of transcripts that include the given participant.
:param id: A participant ID.
:type id: str
:returns: A list of transcript IDs.
:rtype: list of str
"""
return(self._getRequest(self._storeQueryUrl("getTranscriptIdsWithParticipant"), {"id":id}))
def countMatchingTranscriptIds(self, expression):
""" Counts the number of transcripts that match a particular pattern.
The expression language is loosely based on JavaScript; expressions such as the
following can be used:
- ``/Ada.+/.test(id)``
- ``labels('participant').includes('Robert')``
- ``('CC', 'IA', 'MU').includes(my('corpus').label)``
- ``my('episode').label == 'Ada Aitcheson'``
- ``my('transcript_scribe').label == 'Robert'``
- ``my('participant_languages').label == 'en'``
- ``my('noise').label == 'bell'``
- ``labels('transcript_languages').includes('en')``
- ``labels('participant_languages').includes('en')``
- ``labels('noise').includes('bell')``
- ``list('transcript_languages').length gt; 1``
- ``list('participant_languages').length gt; 1``
- ``list('transcript').length gt; 100``
- ``annotators('transcript_rating').includes('Robert')``
- ``!/Ada.+/.test(id) && my('corpus').label == 'CC' && labels('participant').includes('Robert')``
:param expression: An expression that determines which transcripts match.
:type expression: str
:returns: The number of matching transcripts.
:rtype: int
"""
return(self._getRequest(
self._storeQueryUrl("countMatchingTranscriptIds"),
{ "expression":expression }))
def getMatchingTranscriptIds(self, expression, pageLength=None, pageNumber=None, order=None):
""" Gets a list of IDs of transcripts that match a particular pattern.
The results can be exhaustive, by omitting pageLength and pageNumber, or they can
be a subset (a 'page') of results, by given pageLength and pageNumber values.
The order of the list can be specified. If ommitted, the transcripts are listed
in ID order.
The expression language is loosely based on JavaScript; expressions such as the
following can be used:
- ``/Ada.+/.test(id)``
- ``labels('participant').includes('Robert')``
- ``('CC', 'IA', 'MU').includes(my('corpus').label)``
- ``my('episode').label == 'Ada Aitcheson'``
- ``my('transcript_scribe').label == 'Robert'``
- ``my('participant_languages').label == 'en'``
- ``my('noise').label == 'bell'``
- ``labels('transcript_languages').includes('en')``
- ``labels('participant_languages').includes('en')``
- ``labels('noise').includes('bell')``
- ``list('transcript_languages').length gt; 1``
- ``list('participant_languages').length gt; 1``
- ``list('transcript').length gt; 100``
- ``annotators('transcript_rating').includes('Robert')``
- ``!/Ada.+/.test(id) && my('corpus').label == 'CC' && labels('participant').includes('Robert')``
:param expression: An expression that determines which transcripts match.
:type expression: str
:param pageLength: The maximum number of IDs to return, or null to return all.
:type pageLength: int or None
:param pageNumber: The zero-based page number to return, or null to return the first page.
:type pageNumber: int or None
:param order: The ordering for the list of IDs, a string containing a
comma-separated list of expressions, which may be appended by " ASC" or " DESC",
or null for transcript ID order.
:type order: str
:returns: A list of transcript IDs.
:rtype: list of str
"""
return(self._getRequest(
self._storeQueryUrl("getMatchingTranscriptIds"),
{ "expression":expression,
"pageLength":pageLength, "pageNumber":pageNumber,
"order":order}))
def countMatchingAnnotations(self, expression):
""" Counts the number of annotations that match a particular pattern.
The expression language is loosely based on JavaScript; expressions such as the
following can be used:
- ``id == 'ew_0_456'``
- ``!/th[aeiou].//.test(label)``
- ``my('participant').label == 'Robert' && my('utterances').start.offset == 12.345``
- ``graph.id == 'AdaAicheson-01.trs' && layer.id == 'orthography' && start.offset < 10.5``
- ``previous.id == 'ew_0_456'``
*NB* all expressions must match by either id or layer.id.
:param expression: An expression that determines which participants match.
:type expression: str
:returns: The number of matching annotations.
:rtype: int
"""
return(self._getRequest(
self._storeQueryUrl("countMatchingAnnotations"),
{ "expression":expression }))
def getMatchingAnnotations(self, expression, pageLength=None, pageNumber=None):
""" Gets a list of annotations that match a particular pattern.
The expression language is loosely based on JavaScript; expressions such as the
following can be used:
- ``id == 'ew_0_456'``
- ``!/th[aeiou].//.test(label)``
- ``my('participant').label == 'Robert' && my('utterances').start.offset == 12.345``
- ``graph.id == 'AdaAicheson-01.trs' && layer.id == 'orthography' && start.offset < 10.5``
- ``previous.id == 'ew_0_456'``
*NB* all expressions must match by either id or layer.id.
:param expression: An expression that determines which transcripts match.
:type expression: str
:param pageLength: The maximum number of annotations to return, or null to return all.
:type pageLength: int or None
:param pageNumber: The zero-based page number to return, or null to return the first page.
:type pageNumber: int or None
:returns: A list of matching Annotations.
:rtype: list of dictionaries
"""
return(self._getRequest(
self._storeQueryUrl("getMatchingAnnotations"),
{ "expression":expression,
"pageLength":pageLength, "pageNumber":pageNumber }))
def countAnnotations(self, id, layerId):
""" Gets the number of annotations on the given layer of the given transcript.
:param id: The ID of the transcript.
:type id: str
:param layerId: The ID of the layer.
:type layerId: str
:returns: A (possibly empty) array of annotations.
:rtype: int
"""
return(self._getRequest(
self._storeQueryUrl("countAnnotations"),
{ "id":id, "layerId":layerId }))
def getAnnotations(self, id, layerId, pageLength=None, pageNumber=None):
""" Gets the annotations on the given layer of the given transcript.
:param id: The ID of the transcript.
:type id: str
:param layerId: The ID of the layer.
:type layerId:
:param pageLength: The maximum number of IDs to return, or null to return all.
:type pageLength: int or None
:param pageNumber: The zero-based page number to return, or null to return the first page.
:type pageNumber: int or None
:returns: A (possibly empty) list of annotations.
:rtype: list of dictionaries
"""
return(self._getRequest(
self._storeQueryUrl("getAnnotations"),
{ "id":id, "layerId":layerId,
"pageLength":pageLength, "pageNumber":pageNumber }))
def getAnchors(self, id, anchorIds):
""" Gets the given anchors in the given transcript.
:param id: The ID of the transcript.
:type id: str
:param anchorIds: A list of anchor IDs.
:type anchorIds: list of str
:returns: A (possibly empty) list of anchors.
:rtype: list of dictionaries
"""
return(self._getRequest(
self._storeQueryUrl("getAnchors"),
{ "id":id, "anchorIds":anchorIds }))
def getTranscript(self, id, layerIds=None):
""" Gets a transcript given its ID.
:param id: The given transcript ID.
:type id: str
:param layerIds: The IDs of the layers to load, or null if only transcript data is
required.
:type layerIds: list of str
:returns: The identified transcript.
:rtype: dictionary
"""
return(self._getRequest(
self._storeQueryUrl("getTranscript"),
{ "id":id, "layerIds":layerIds }))
def getMediaTracks(self):
""" List the predefined media tracks available for transcripts.
:returns: An ordered list of media track definitions.
:rtype: list of dictionaries
"""
return(self._getRequest(self._storeQueryUrl("getMediaTracks"), None))
def getAvailableMedia(self, id):
""" List the media available for the given transcript.
:param id: The transcript ID.
:type id: str
:returns: List of media files available for the given transcript.
:rtype: list of dictionaries
"""
return(self._getRequest(
self._storeQueryUrl("getAvailableMedia"),
{ "id":id }))
def getMediaUrl(self, id, trackSuffix, mimeType, startOffset=None, endOffset=None):
""" Gets a given media track URL for a given transcript.
:param id: The transcript ID.
:type id: str
:param trackSuffix: The track suffix of the media.
:type trackSuffix: str
:param mimeType: The MIME type of the media, which may include parameters for type
conversion, e.g. 'text/wav; samplerate=16000'
:type mimeType: str
:param startOffset: The start offset of the media sample, or null for the start of
the whole recording.
:type startOffset: float or None
:param endOffset: The end offset of the media sample, or null for the end of the
whole recording.
:type endOffset: float or None
:returns: A URL to the given media for the given transcript, or null if the given
media doesn't exist.
:rtype: str
"""
return(self._getRequest(
self._storeQueryUrl("getMedia"),
{ "id":id, "trackSuffix":trackSuffix, "mimeType":mimeType,
"startOffset":startOffset, "endOffset":endOffset }))
def getMedia(self, id, trackSuffix, mimeType, startOffset=None, endOffset=None, dir=None):
""" Downloads a given media track URL for a given transcript.
:param id: The transcript ID.
:type id: str
:param trackSuffix: The track suffix of the media.
:type trackSuffix: str
:param mimeType: The MIME type of the media, which may include parameters for type
conversion, e.g. 'text/wav; samplerate=16000'
:type mimeType: str
:param startOffset: The start offset of the media sample, or null for the start of
the whole recording.
:type startOffset: float or None
:param endOffset: The end offset of the media sample, or null for the end of the
whole recording.
:type endOffset: float or None
:param dir: A directory in which the file should be stored, or null for a temporary
folder. If specified, and the directory doesn't exist, it will be created.
:type dir: str
:returns: The file name of the resulting file. If *dir* is None, this file will be stored
under the system's temporary directory, so once processing is finished, it should
be deleted by the caller, or moved to a more permanent location.
:rtype: list of str
"""
# get the URL of the media
url = self.getMediaUrl(id, trackSuffix, mimeType, startOffset, endOffset)
# download the content of the URL
if dir == None:
dir = tempfile.mkdtemp("_wav", "getMedia_")
tempFiles = True
elif not os.path.exists(dir):
os.mkdir(dir)
return(self._postRequestToFile(url, None, dir))
def getEpisodeDocuments(self, id):
""" Get a list of documents associated with the episode of the given transcript.
:param id: The transcript ID.
:type id: str
:returns: List of URLs to documents.
:rtype: list of str
"""
return(self._getRequest(
self._storeQueryUrl("getEpisodeDocuments"),
{ "id":id }))
def taskStatus(self, threadId):
""" Gets the current state of the given task.
:param threadId: The ID of the task.
:type threadId: str.
:returns: The status of the task.
:rtype: dictionary
"""
return(self._getRequest(self._labbcatUrl("thread"), { "threadId" : threadId }))
def waitForTask(self, threadId, maxSeconds=0):
"""Wait for the given task to finish.
:param threadId: The task ID.
:type threadId: str
:param maxSeconds: The maximum time to wait for the task, or 0 for forever.
:type maxSeconds: int
:returns: The final task status. To determine whether the task finished or waiting
timed out, check *result.running*, which will be false if the task finished.
:rtype: dict
"""
if maxSeconds == 0: maxSeconds = -1
status = self.taskStatus(threadId)
if self.verbose: print("status : " + str(status["running"]))
while status["running"] and maxSeconds != 0:
if self.verbose: print("sleeping...")
time.sleep(1)
if maxSeconds != 0: maxSeconds = maxSeconds - 1
status = self.taskStatus(threadId)
if self.verbose: print("status "+str(maxSeconds)+" : " + str(status["running"]))
return(status)
def taskResults(self, threadId, dir=None):
""" Gets the results of the given task, as a file or list of files.
Some tasks produce a file for download when they're finished
(e.g. `getFragmentsAsync() <#labbcat.LabbcatView.getFragmentsAsync>`_)
so this function provides acces to this results file. If the results are
compressed into a zip file, this function automatically unpacks the contained files.
:param threadId: The ID of the task.
:type threadId: str.
:param dir: A directory in which the files should be stored, or null for a temporary
folder. If specified, and the directory doesn't exist, it will be created.
:type dir: str
:returns: A list of files. If *dir* is None, these files will be stored under the
system's temporary directory, so once processing is finished, they should be
deleted by the caller, or moved to a more permanent location.
If the task has no results (yet) this function returns None.
:rtype: list of str
"""
status = self.taskStatus(threadId)
if "resultUrl" in status:
resultUrl = status["resultUrl"]
fragments = []
tempFiles = False
if dir == None:
dir = tempfile.mkdtemp("_"+str(threadId), "taskResults_")
tempFiles = True
elif not os.path.exists(dir):
os.mkdir(dir)
# get result
fileName = self._postRequestToFile(resultUrl, None, dir)
fileNames = [ fileName ]
if fileName.endswith(".zip"):
# extract the zip file
with ZipFile(fileName, 'r') as zipObj:
zipObj.extractall(dir)
fileNames = [os.path.join(dir, fileName) for fileName in zipObj.namelist()]
# delete the temporary zip file
os.remove(fileName)
return fileNames
else: # no resultUrl
return None
def releaseTask(self, threadId):
""" Release a finished task, to free up server resources.
:param threadId: The ID of the task.
:type threadId: str.
"""
self._getRequest(self._labbcatUrl("threads"), {
"threadId" : threadId, "command" : "release" })
return()
def cancelTask(self, threadId):
""" Cancels (but does not release) a running task.
:param threadId: The ID of the task.
:type threadId: str.
"""
self._getRequest(self._labbcatUrl("threads"), {
"threadId" : threadId, "command" : "cancel" })
return()
def getTasks(self):
""" Gets a list of all tasks on the server.
:returns: A list of all task statuses.
:rtype: list of dictionaries
"""
return(self._getRequest(self._labbcatUrl("threads"), None))
def getTranscriptAttributes(self, transcriptIds, layerIds):
""" Get transcript attribute values.
Retrieves transcript attribute values for given transcript IDs, saves them to
a CSV file, and returns the name of the file.
In general, transcript attributes are layers whose ID is prefixed 'transcript',
however formally it's any layer where layer.parentId == 'graph' and layer.alignment
== 0, which includes 'corpus' as well as transcript attribute layers.
The resulting file is the responsibility of the caller to delete when finished.
:param transcriptIds: A list of transcript IDs
:type transcriptIds: list of str.
:param layerIds: A list of layer IDs corresponding to transcript attributes.
:type layerIds: list of str.
:rtype: str
"""
params = {
"layer" : ["transcript"]+layerIds,
"id" : transcriptIds }
return (self._postRequestToFile(self._labbcatUrl("api/attributes"), params))
def getParticipantAttributes(self, participantIds, layerIds):
""" Gets participant attribute values.
Retrieves participant attribute values for given participant IDs, saves them
to a CSV file, and returns the name of the file.
In general, participant attributes are layers whose ID is prefixed 'participant',
however formally it's any layer where layer.parentId == 'participant' and
layer.alignment == 0.
The resulting file is the responsibility of the caller to delete when finished.
:param participantIds: A list of participant IDs
:type participantIds: list of str.
:param layerIds: A list of layer IDs corresponding to participant attributes.
:type layerIds: list of str.
:rtype: str
"""
params = {
"type" : "participant",
"content-type" : "text/csv",
"csvFieldDelimiter" : ",",
"layer" : layerIds,
"participantId" : participantIds }
return (self._postRequestToFile(self._labbcatUrl("participantsExport"), params))
def search(self, pattern, participantIds=None, transcriptTypes=None, mainParticipant=True, aligned=False, matchesPerTranscript=None, overlapThreshold=None):
"""
Searches for tokens that match the given pattern.
Example::
pattern = {"columns":[{"layers":{"orthography":{"pattern":"the"}}}]}
Strictly speaking, *pattern* should be a dictionary that matches the structure of
the search matrix in the browser interface of LaBB-CAT; i.e. a dictionary with
with one entrye called "columns", which is a list of dictionaries.
Each element in the "columns" list contains a dictionary with an entry named
"layers", whose value is a dictionary for patterns to match on each layer, and
optionally an element named "adj", whose value is a number representing the
maximum distance, in tokens, between this column and the next column - if "adj"
is not specified, the value defaults to 1, so tokens are contiguous.
Each element in the "layers" dictionary is named after the layer it matches, and
the value is a dictionary with the following possible entries:
- "pattern" : A regular expression to match against the label
- "min" : An inclusive minimum numeric value for the label
- "max" : An exclusive maximum numeric value for the label
- "not" : True to negate the match
- "anchorStart" : True to anchor to the start of the annotation on this layer
(i.e. the matching word token will be the first at/after the start of the matching
annotation on this layer)
- "anchorEnd" : True to anchor to the end of the annotation on this layer
(i.e. the matching word token will be the last before/at the end of the matching
annotation on this layer)
- "target" : True to make this layer the target of the search; the results will
contain one row for each match on the target layer
Some examples of valid pattern objects are shown below.
Example::
## words starting with 'ps...'
pattern = {"columns":[{"layers":{"orthography":{"pattern":"ps.*"}}}]}
## the word 'the' followed immediately or with one intervening word by
## a hapax legomenon (word with a frequency of 1) that doesn't start with a vowel
pattern = { "columns" : [
{ "layers" : {
"orthography" : { "pattern" : "the" } }
"adj" : 2 },
{ "layers" : {
"phonemes" : { "not" : True, "pattern" : "[cCEFHiIPqQuUV0123456789~#\\$@].*" },
"frequency" : { max : "2" } } } ] }
For ease of use, the function will also accept the following abbreviated forms;
some examples are shown below.
Example::
## a single list representing a 'one column' search,
## and string values, representing regular expression pattern matching
pattern = { "orthography" : "ps.*" }
## a list containing the columns (adj defaults to 1, so matching tokens are contiguous)...
pattern = [
{ "orthography" : "the" },
{ "phonemes" : { "not" : True, "pattern" : "[cCEFHiIPqQuUV0123456789~#\\$@].*" },
"frequency" : { "max" : "2" } } ]
:param pattern: A dict representing the pattern to search for, which mirrors the
Search Matrix in the browser interface.
:type dictionary:
:param participantIds: An optional list of participant IDs to search the utterances
of. If null, all utterances in the corpus will be searched.
:type list of str:
:param transcriptTypes: An optional list of transcript types to limit the results
to. If null, all transcript types will be searched.
:type list of str:
:param mainParticipant: true to search only main-participant utterances, false to
search all utterances.
:type boolean:
:param aligned: true to include only words that are aligned (i.e. have anchor
confidence ≥ 50, false to search include un-aligned words as well.
:type boolean:
:param matchesPerTranscript: Optional maximum number of matches per transcript to
return. *None* means all matches.
:type int:
:param overlapThreshold: Optional percentage overlap with other utterances before
simultaneous speech is excluded. *None* means include all overlapping utterances.
:returns: The threadId of the resulting task, which can be passed in to
`getMatches() <#labbcat.LabbcatView.getMatches>`_,
`taskStatus() <#labbcat.LabbcatView.taskStatus>`_,
`waitForTask() <#labbcat.LabbcatView.waitForTask>`_
`releaseTask() <#labbcat.LabbcatView.releaseTask>`_, etc.
:rtype: str
"""
## first normalize the pattern...
## if pattern isn't a list with a "columns" element, wrap a list around it
if "columns" not in pattern: pattern = { "columns" : pattern }
## if pattern["columns"] isn't a list wrap a list around it
if not isinstance(pattern["columns"], list): pattern["columns"] = [ pattern["columns"] ]
## columns contain lists with no "layers" element, wrap a list around them
for c in range(len(pattern["columns"])):
if "layers" not in pattern["columns"][c]: