Skip to content

Mongo


MongoDB database interface module.

This module provides functions for interacting with the MongoDB database, handling user data, annotations, videos, and concept maps.

get_annotation_infos(video_id, fields=None)

Get annotation information for a video.

Parameters:

Name Type Description Default
video_id str

Video identifier

required
fields list

Specific fields to retrieve

None

Returns:

Type Description
list

List of annotation information

Source code in apps/annotator/code/database/mongo.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def get_annotation_infos(video_id, fields:list=None):
    """
    Get annotation information for a video.

    Parameters
    ----------
    video_id : str
        Video identifier
    fields : list, optional
        Specific fields to retrieve

    Returns
    -------
    list
        List of annotation information
    """
    if fields is None:
        fields = []
    fields = {field:1 for field in fields}
    fields.update({"_id":0})
    return list(db.graphs.find({"video_id":video_id}, fields))

get_annotation_status(annotator, video_id)

Get annotation completion status.

Parameters:

Name Type Description Default
annotator str

Annotator identifier

required
video_id str

Video identifier

required

Returns:

Type Description
dict or None

Annotation completion status if found

Source code in apps/annotator/code/database/mongo.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
def get_annotation_status(annotator, video_id):
    """
    Get annotation completion status.

    Parameters
    ----------
    annotator : str
        Annotator identifier  
    video_id : str
        Video identifier

    Returns
    -------
    dict or None
        Annotation completion status if found
    """
    return db.graphs.find_one({"video_id":video_id, "annotator_id":str(annotator)},{"annotation_completed":1}) 

get_concept_map(annotator, video_id)

Get concept map relationships.

Parameters:

Name Type Description Default
annotator str

Annotator identifier

required
video_id str

Video identifier

required

Returns:

Type Description
list

List of concept map relationships

Source code in apps/annotator/code/database/mongo.py
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
def get_concept_map(annotator, video_id):
    """
    Get concept map relationships.

    Parameters
    ----------
    annotator : str
        Annotator identifier
    video_id : str  
        Video identifier

    Returns
    -------
    list
        List of concept map relationships
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::get_concept_map(): Inizio ******")

    collection = db.graphs

    pipeline = [
        {"$unwind": "$graph.@graph"},
        {
            "$match":
                {
                    "video_id": str(video_id),
                    "annotator_id": str(annotator),
                    "graph.@graph.type": "Annotation",
                    "graph.@graph.motivation": "edu:linkingPrerequisite",
                }

        },

        {"$project":
            {
                "prerequisite": "$graph.@graph.body",
                "target": "$graph.@graph.target.dcterms:subject.id",
                "weight": "$graph.@graph.skos:note",
                "time": "$graph.@graph.target.selector.value",
                "sent_id": "$graph.@graph.target.selector.edu:conllSentId",
                "word_id": "$graph.@graph.target.selector.edu:conllWordId",
                "xywh": "$graph.@graph.target.selector.edu:hasMediaFrag",
                "creator": "$graph.@graph.creator",
                "_id": 0
            }
        },

        {"$sort": {"time": 1}}

    ]

    aggregation = collection.aggregate(pipeline)
    concept_map = list(aggregation)

    for rel in concept_map:
        rel["prerequisite"] = rel["prerequisite"].replace("concept_","").replace("_"," ")
        rel["target"] = rel["target"].replace("concept_","").replace("_"," ")
        rel["weight"] = (rel["weight"].replace("Prerequisite","")).capitalize()
        rel["time"] = rel["time"].replace("^^xsd:dateTime","")
        if "xywh" not in rel:
            rel["xywh"] = "None"
        if "word_id" not in rel:
            rel["word_id"] = "None"
        if "sent_id" not in rel:
            rel["sent_id"] = "None"

    print("***** EKEEL - Video Annotation: db_mongo.py::get_concept_map(): Fine ******")

    return concept_map

get_concepts(annotator, video_id)

Get list of concepts for an annotation.

Parameters:

Name Type Description Default
annotator str

Annotator identifier

required
video_id str

Video identifier

required

Returns:

Type Description
list

List of concept names

Source code in apps/annotator/code/database/mongo.py
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
def get_concepts(annotator, video_id):
    """
    Get list of concepts for an annotation.

    Parameters
    ----------
    annotator : str
        Annotator identifier
    video_id : str
        Video identifier

    Returns
    -------
    list
        List of concept names
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::get_concepts(): Inizio ******")

    collection = db.graphs

    pipeline = [
        {"$unwind": "$graph.@graph"},
        {
            "$match":
                {
                    "video_id": str(video_id),
                    "annotator_id": str(annotator),
                    "graph.@graph.type": "skos:Concept"
                }

        },

        {"$project":
            {
                "concept": "$graph.@graph.id",
                "_id": 0
            }
        }

    ]

    aggregation = collection.aggregate(pipeline)
    results = list(aggregation)
    concepts = []

    for concept in results:
        concepts.append(concept["concept"].replace("concept_","").replace("_"," "))

    print("***** EKEEL - Video Annotation: db_mongo.py::get_concepts(): Fine ******")


    return concepts

get_definitions(annotator, video_id)

Retrieve definitions from the database for a given annotator and video.

Parameters:

Name Type Description Default
annotator str

The ID of the annotator.

required
video_id str

The ID of the video.

required

Returns:

Type Description
list of dict

A list of definitions with their respective details such as concept, start, end, start_sent_id, end_sent_id, creator, and description_type.

Source code in apps/annotator/code/database/mongo.py
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
def get_definitions(annotator, video_id):
    """
    Retrieve definitions from the database for a given annotator and video.

    Parameters
    ----------
    annotator : str
        The ID of the annotator.
    video_id : str
        The ID of the video.

    Returns
    -------
    list of dict
        A list of definitions with their respective details such as concept, start, end, start_sent_id, end_sent_id, creator, and description_type.
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::get_definitions(): Inizio ******")

    collection = db.graphs

    pipeline = [
        {"$unwind": "$graph.@graph"},
        {
            "$match":
                {
                    "video_id": str(video_id),
                    "annotator_id": str(annotator),
                    "graph.@graph.type": "Annotation",
                    "graph.@graph.motivation": "describing",
                }

        },

        {"$project":
            {
                "concept": "$graph.@graph.body",
                "start": "$graph.@graph.target.selector.startSelector.value",
                "end": "$graph.@graph.target.selector.endSelector.value",
                "start_sent_id": "$graph.@graph.target.selector.startSelector.edu:conllSentId",
                "end_sent_id": "$graph.@graph.target.selector.endSelector.edu:conllSentId",
                "creator": "$graph.@graph.creator",
                "description_type": "$graph.@graph.skos:note",
                "_id": 0
            }
        },

        {"$sort": {"start": 1}}

    ]

    aggregation = collection.aggregate(pipeline)
    definitions = list(aggregation)

    for d in definitions:
        d["concept"] = d["concept"].replace("concept_","").replace("_"," ")
        d["end"] = d["end"].replace("^^xsd:dateTime","")
        d["start"] = d["start"].replace("^^xsd:dateTime", "")
        d["description_type"] = d["description_type"].replace("concept", "")

    print("***** EKEEL - Video Annotation: db_mongo.py::get_definitions(): Fine ******")

    return definitions

get_emails_registered()

Get list of all registered email addresses.

Returns:

Type Description
list

List of email addresses

Source code in apps/annotator/code/database/mongo.py
40
41
42
43
44
45
46
47
48
49
def get_emails_registered():
    """
    Get list of all registered email addresses.

    Returns
    -------
    list
        List of email addresses
    """
    return [user['email'] for user in users.find({}, {"email": 1, "_id": 0})]

get_graph(user, video)

Get concept map graph for user and video.

Parameters:

Name Type Description Default
user str

User identifier

required
video str

Video identifier

required

Returns:

Type Description
dict or None

Graph data if found, None otherwise

Source code in apps/annotator/code/database/mongo.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def get_graph(user, video):
    """
    Get concept map graph for user and video.

    Parameters
    ----------
    user : str
        User identifier
    video : str
        Video identifier

    Returns
    -------
    dict or None
        Graph data if found, None otherwise
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::get_graph() ******")
    collection = db.graphs
    item = collection.find_one({"annotator_id":user, "video_id":video},{"_id":0,"graph":1})
    if item is not None:
        return item["graph"]
    return None

get_graphs_info(selected_video=None)

Get graph information for videos.

Parameters:

Name Type Description Default
selected_video str

Video ID to get specific info for

None

Returns:

Type Description
dict

Graph information including titles and annotators

Source code in apps/annotator/code/database/mongo.py
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
def get_graphs_info(selected_video=None):
    """
    Get graph information for videos.

    Parameters
    ----------
    selected_video : str, optional
        Video ID to get specific info for

    Returns
    -------
    dict
        Graph information including titles and annotators
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::get_graphs_info(): Inizio ******")

    # If selected video is None
    # Returns all videos graphs, with the title, creator and the annotators
    # Else returns only the selected video

    collection = db.graphs

    pipeline = [

        # join con videos collection

        {
            "$lookup":{
                "from": "videos",
                "localField": "video_id",
                "foreignField": "video_id",
                "as": "video"
            }
        },

        {"$project":
            {
                "annotator_id": 1,
                "annotator_name": 1,
                "video_id": 1,
                "title": "$video.title",
                "creator": "$video.creator",
                "_id": 0}
         },

        {"$sort": {"creator": pymongo.ASCENDING}}
    ]

    aggregation = list(collection.aggregate(pipeline))
    graphs_info = {}

    # Remove possibly unavailable videos from resulting list
    for vid in reversed(aggregation):
        if not len(vid["creator"]) or not len(vid["title"]):
            aggregation.remove(vid)

    for vid in aggregation:

        if "annotator_id" in vid:
            annotator = {"id": vid["annotator_id"], "name": vid["annotator_name"]}

            if vid["video_id"] not in graphs_info:
                graphs_info[vid["video_id"]] = {"title": vid["title"][0], "creator": vid["creator"][0], "annotators": [annotator]}
            else:
                graphs_info[vid["video_id"]]["annotators"].append(annotator)

    if selected_video is not None:
        if selected_video in graphs_info:
            return graphs_info[selected_video]
        else:
            return None

    print("***** EKEEL - Video Annotation: db_mongo.py::get_graphs_info(): Fine ******")

    return graphs_info

get_untranscribed_videos()

Get list of videos needing transcription.

Returns:

Type Description
list

List of tuples containing (video_id, language)

Source code in apps/annotator/code/database/mongo.py
306
307
308
309
310
311
312
313
314
315
316
317
318
def get_untranscribed_videos():
    """
    Get list of videos needing transcription.

    Returns
    -------
    list
        List of tuples containing (video_id, language)
    """
    docs = list(db.videos.find({"transcript_data.is_whisper_transcribed":False},{"video_id":1, "language":1}))
    if len(docs):
        docs = [(doc["video_id"], doc["language"]) for doc in docs]
    return docs

get_video_data(video_id, fields=None)

Get video metadata from database.

Parameters:

Name Type Description Default
video_id str

ID of video to retrieve

required
fields list

Specific fields to retrieve

None

Returns:

Type Description
dict

Video metadata

Source code in apps/annotator/code/database/mongo.py
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
def get_video_data(video_id:str, fields:list | None= None):
    """
    Get video metadata from database.

    Parameters
    ----------
    video_id : str
        ID of video to retrieve
    fields : list, optional
        Specific fields to retrieve

    Returns
    -------
    dict
        Video metadata
    """
    collection = db.videos
    if fields is None:
        metadata = collection.find_one({"video_id": video_id})
        if metadata is not None:
            metadata.pop('_id')
    else:

        def build_projection(fields:"dict|list"):
            projection = {}

            for field in fields:
                if isinstance(field, dict):
                    # Handle nested fields
                    for outer_key, inner_keys in field.items():
                        projection[outer_key] = {key: True for key in inner_keys}
                else:
                    # For top-level fields
                    projection[field] = True

            return projection

        projection = build_projection(fields)
        metadata = list(collection.find({"video_id":video_id}, projection))
        if len(metadata):
            metadata = metadata[0]
            metadata.pop("_id")
    return metadata

get_vocabulary(annotator, video_id)

Get concept vocabulary with synonyms.

Parameters:

Name Type Description Default
annotator str

Annotator identifier

required
video_id str

Video identifier

required

Returns:

Type Description
dict or None

Concept vocabulary mapping if found

Source code in apps/annotator/code/database/mongo.py
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
def get_vocabulary(annotator, video_id):
    """
    Get concept vocabulary with synonyms.

    Parameters
    ----------
    annotator : str
        Annotator identifier
    video_id : str
        Video identifier

    Returns
    -------
    dict or None
        Concept vocabulary mapping if found
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::get_vocabulary(): Inizio ******")


    collection = db.graphs

    pipeline = [
        {"$unwind": "$conceptVocabulary.@graph"},
        {
            "$match":
                {
                    "video_id": str(video_id),
                    "annotator_id": str(annotator),
                    "conceptVocabulary.@graph.type": "skos:Concept"
                }
        },

        {"$project":
            {
                "prefLabel": "$conceptVocabulary.@graph.skos:prefLabel.@value",
                "altLabel": "$conceptVocabulary.@graph.skos:altLabel.@value",
                "_id": 0
            }
        }

    ]

    aggregation = collection.aggregate(pipeline)
    results = list(aggregation)

    # define new concept vocabulary
    conceptVocabulary = {}

    # if there is none on DB
    if len(results) == 0:
        return None

    # iterate for each concept and build the vocabulary basing on the number of synonyms
    for concept in results: 

        if "altLabel" in concept :
            if isinstance(concept["altLabel"], list):
                conceptVocabulary[concept["prefLabel"]] = concept["altLabel"]
            else:
                conceptVocabulary[concept["prefLabel"]] = [concept["altLabel"]]
        else:
            conceptVocabulary[concept["prefLabel"]]=[]

    print("***** EKEEL - Video Annotation: db_mongo.py::get_vocabulary(): Fine ******")

    return conceptVocabulary

insert_burst(data)

Insert or update burst analysis data.

Parameters:

Name Type Description Default
data dict

Burst data containing extraction_method and video_id

required
Source code in apps/annotator/code/database/mongo.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def insert_burst(data):
    """
    Insert or update burst analysis data.

    Parameters
    ----------
    data : dict
        Burst data containing extraction_method and video_id
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::insert_burst(): Inizio ******")

    collection = db.graphs
    query = {
        "extraction_method": "Burst",
        "video_id": data["video_id"]
    }

    if collection.find_one(query) is None:
        collection.insert_one(data)
    else:
        new_graph = {"$set": {"graph": data["graph"]}}
        collection.update_one(query, new_graph)

    print("***** EKEEL - Video Annotation: db_mongo.py::insert_burst(): Fine ******")

insert_conll_MongoDB(data)

Insert CoNLL format data into database.

Parameters:

Name Type Description Default
data dict

CoNLL data with video_id field

required
Source code in apps/annotator/code/database/mongo.py
164
165
166
167
168
169
170
171
172
173
174
175
176
def insert_conll_MongoDB(data):
    """
    Insert CoNLL format data into database.

    Parameters
    ----------
    data : dict
        CoNLL data with video_id field
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::insert_conll_MongoDB() ******")
    collection = db.conlls
    if collection.find_one({"video_id": data["video_id"]}) is None:
        collection.insert_one(data)

insert_gold(data)

Insert or update gold standard data.

Parameters:

Name Type Description Default
data dict

Gold standard data including graph and concept vocabulary

required
Source code in apps/annotator/code/database/mongo.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def insert_gold(data):
    """
    Insert or update gold standard data.

    Parameters
    ----------
    data : dict
        Gold standard data including graph and concept vocabulary
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::insert_gold(): Inizio ******")


    collection = db.graphs
    query = {
        "graph_type": "gold_standard",
        "video_id": data["video_id"]
    }

    if collection.find_one(query) is None:
        collection.insert_one(data)
    else:
        new_graph = {"$set": {"graph": data["graph"], "conceptVocabulary": data["conceptVocabulary"]}}
        collection.update_one(query, new_graph)

insert_graph(data)

Insert or update graph data in database.

Parameters:

Name Type Description Default
data dict

Graph data including annotator_id and video_id

required
Source code in apps/annotator/code/database/mongo.py
 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
def insert_graph(data):
    """
    Insert or update graph data in database.

    Parameters
    ----------
    data : dict
        Graph data including annotator_id and video_id
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::insert_graph(): Inizio ******")


    collection = db.graphs
    query = {
        "annotator_id": data["annotator_id"],
        "video_id": data["video_id"]
    }

    if collection.find_one(query) is None:
        collection.insert_one(data)
    else:
        new_graph = {"$set": 
                {   "graph": data["graph"], 
                    "conceptVocabulary": data["conceptVocabulary"], 
                    "annotation_completed": data["annotation_completed"],
                    "last_modification": data["last_modification"]
                }
            }
        collection.update_one(query, new_graph)

    print("***** EKEEL - Video Annotation: db_mongo.py::insert_graph(): Fine ******")    

insert_video_data(data, update=True)

Insert or update video data.

Parameters:

Name Type Description Default
data dict

Video data to insert/update

required
update bool

Whether to update existing document or replace

True

Returns:

Type Description
None
Source code in apps/annotator/code/database/mongo.py
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
def insert_video_data(data:dict, update=True):
    """
    Insert or update video data.

    Parameters
    ----------
    data : dict
        Video data to insert/update
    update : bool, optional
        Whether to update existing document or replace

    Returns
    -------
    None
    """
    collection = db.videos
    mongo_doc:dict | None = collection.find_one({'video_id':data['video_id'] })
    if mongo_doc is None:
        collection.insert_one(data)
        return
    elif update:
        mongo_doc.pop("_id")
        for key,value in data.items():
            mongo_doc[key] = value
    else:
        mongo_doc = data
    collection.delete_one({'video_id':data['video_id']})
    collection.insert_one(mongo_doc)

remove_account(email)

Remove user account.

Parameters:

Name Type Description Default
email str

Email address of account to remove

required

Returns:

Type Description
str

Status message indicating result

Warning

This operation is destructive and may affect related data

Source code in apps/annotator/code/database/mongo.py
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
def remove_account(email):
    """
    Remove user account.

    Parameters
    ----------
    email : str
        Email address of account to remove

    Returns
    -------
    str
        Status message indicating result

    Warning
    -------
    This operation is destructive and may affect related data
    """
    print("***** EKEEL - Video Annotation: db_mongo.py::remove_account() ******")

    query = {"email": email}

    if users.find_one(query) is not None:
        try: 
            users.delete_one(query)
        except:
            return "Error"
        return "Done verified removed"
    elif unverified_users.find_one(query) is not None:
        try: 
            unverified_users.delete_one(query)
        except:
            return "Error"
        return "Done unverified removed"
    return "Not Found"

remove_annotations_data(video_id, user=None)

Remove annotation data for a video.

Parameters:

Name Type Description Default
video_id str

ID of video to remove annotations for

required
user dict

User data to filter annotations by

None
Source code in apps/annotator/code/database/mongo.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def remove_annotations_data(video_id:str, user:dict=None):
    """
    Remove annotation data for a video.

    Parameters
    ----------
    video_id : str
        ID of video to remove annotations for
    user : dict, optional
        User data to filter annotations by
    """
    for coll in [db.graphs, db.conlls]:
        if user is None:
            while True:
                doc = coll.find_one_and_delete({"video_id":video_id})
                if doc is None:
                    return

    [coll.find_one_and_delete({"video_id":video_id, "annotator_id": user["id"], "annotator_name": user["name"]}) for coll in [db.graphs, db.conlls]]

remove_video(video_id)

Remove video and associated data.

Parameters:

Name Type Description Default
video_id str

ID of video to remove

required
Warning

This operation is destructive and may affect related data

Source code in apps/annotator/code/database/mongo.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
def remove_video(video_id):
    """
    Remove video and associated data.

    Parameters
    ----------
    video_id : str
        ID of video to remove

    Warning
    -------
    This operation is destructive and may affect related data
    """
    query = {"video_id":video_id}
    collections = ['videos','graphs','conlls']
    for coll_name in collections:
        collection = db.get_collection(coll_name)
        if collection.find_one(query):
            try:
                collection.delete_many(query)
                #collection.delete_one(query)
                print(f'removing from {coll_name}')
            except:
                pass

string_to_seconds(str)

Convert time string to seconds.

Parameters:

Name Type Description Default
str str

Time string in format "HH:MM:SS^^"

required

Returns:

Type Description
int

Total seconds

Source code in apps/annotator/code/database/mongo.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def string_to_seconds(str):
    """
    Convert time string to seconds.

    Parameters
    ----------
    str : str
        Time string in format "HH:MM:SS^^"

    Returns
    -------
    int
        Total seconds
    """
    s = str.split("^^")[0].split(":")
    seconds = int(s[2]) + int(s[1]) * 60 + int(s[0]) * 60 * 60

    return seconds