Пример #1
0
 def testUpdateAnnotaton(self, user, admin):
     publicFolder = utilities.namedFolder(user, 'Public')
     item = Item().createItem('sample', admin, publicFolder)
     annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
     annot = Annotation().load(annot['_id'], region={'sort': 'size'}, user=admin)
     saved = Annotation().updateAnnotation(annot, updateUser=user)
     assert saved['updatedId'] == user['_id']
Пример #2
0
 def testRevertVersion(self, admin):
     privateFolder = utilities.namedFolder(admin, 'Private')
     Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, True)
     item = Item().createItem('sample', admin, privateFolder)
     annot = Annotation().createAnnotation(item, admin, copy.deepcopy(sampleAnnotation))
     annot['annotation']['name'] = 'First Change'
     annot['annotation']['elements'].extend([
         {'type': 'point', 'center': [20.0, 25.0, 0]},
         {'type': 'point', 'center': [10.0, 24.0, 0]},
         {'type': 'point', 'center': [25.5, 23.0, 0]},
     ])
     annot = Annotation().save(annot)
     annot['annotation']['name'] = 'Second Change'
     annot['annotation']['elements'].pop(2)
     annot = Annotation().save(annot)
     versions = list(Annotation().versionList(annot['_id'], user=admin))
     assert Annotation().revertVersion(
         annot['_id'], versions[0]['_version'] + 1, user=admin) is None
     assert len(Annotation().revertVersion(
         annot['_id'], force=True)['annotation']['elements']) == 4
     assert len(Annotation().revertVersion(
         annot['_id'], force=True)['annotation']['elements']) == 3
     assert len(Annotation().revertVersion(
         annot['_id'], versions[2]['_version'], force=True)['annotation']['elements']) == 1
     Annotation().remove(annot)
     assert len(Annotation().revertVersion(
         annot['_id'], user=admin)['annotation']['elements']) == 1
Пример #3
0
    def testAnnotationCopy(self, server, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')
        # create annotation on an item
        itemSrc = Item().createItem('sample', admin, publicFolder)
        annot = Annotation().createAnnotation(itemSrc, admin, sampleAnnotation)
        assert Annotation().load(annot['_id'], user=admin) is not None

        # Create a new item
        itemDest = Item().createItem('sample', admin, publicFolder)

        # Copy the annotation from one item to an other
        resp = server.request(path='/annotation/{}/copy'.format(annot['_id']),
                              method='POST',
                              user=admin,
                              params={'itemId': itemDest.get('_id')})
        assert utilities.respStatus(resp) == 200
        itemDest = Item().load(itemDest.get('_id'), level=AccessType.READ)

        # Check if the annotation is in the destination item
        resp = server.request(path='/annotation',
                              method='GET',
                              user=admin,
                              params={
                                  'itemId': itemDest.get('_id'),
                                  'name': 'sample'
                              })
        assert utilities.respStatus(resp) == 200
        assert resp.json is not None
Пример #4
0
def makeResources(server, fsAssetstore, admin, user):
    # Create an item in the admin Public folder
    adminPublicFolder = Folder().childFolders(  # noqa: B305
        admin, 'user', filters={
            'name': 'Public'
        }).next()
    Item().createItem('Empty', admin, adminPublicFolder)
    # Upload a sample file
    file = utilities.uploadExternalFile(
        'data/sample_svs_image.TCGA-DU-6399-01A-01-TS1.e8eb65de-d63e-42db-'
        'af6f-14fefbbdf7bd.svs.sha512',
        user,
        fsAssetstore,
        name='image')
    item = Item().load(file['itemId'], force=True)
    # We have to ask to make this a large image item, because we renamed it
    # 'image' without an extension
    ImageItem().createImageItem(item, file, user=user, createJob=False)
    ImageItem().copyItem(item, user, name='copy')

    annotation = Annotation().createAnnotation(item, admin,
                                               {'name': 'admin annotation'})
    annotation = Annotation().setAccessList(annotation, {},
                                            force=True,
                                            save=False)
    annotation = Annotation().setPublic(annotation, True, save=True)
Пример #5
0
 def testGetAnnotationWithCentroids(self, server, admin):
     publicFolder = utilities.namedFolder(admin, 'Public')
     item = Item().createItem('sample', admin, publicFolder)
     annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
     annotId = str(annot['_id'])
     resp = server.request(path='/annotation/%s' % annotId,
                           user=admin,
                           params={'centroids': 'true'},
                           isJson=False)
     assert utilities.respStatus(resp) == 200
     result = utilities.getBody(resp, text=False)
     assert b'\x00' in result
     elements = result.split(b'\x00', 1)[1].rsplit(b'\x00', 1)[0]
     data = result.split(b'\x00', 1)[0] + result.rsplit(b'\x00', 1)[1]
     data = json.loads(data.decode('utf8'))
     assert len(data['_elementQuery']['props']) == 1
     assert len(elements) == 28 * 1
     x, y, r, s = struct.unpack('<fffl', elements[12:28])
     assert x == annot['annotation']['elements'][0]['center'][0]
     assert y == annot['annotation']['elements'][0]['center'][1]
     assert s == 0
     largeSample = makeLargeSampleAnnotation()
     annot = Annotation().createAnnotation(item, admin, largeSample)
     annotId = str(annot['_id'])
     resp = server.request(path='/annotation/%s' % annotId,
                           user=admin,
                           params={'centroids': 'true'},
                           isJson=False)
     assert utilities.respStatus(resp) == 200
     result = utilities.getBody(resp, text=False)
     elements = result.split(b'\x00', 1)[1].rsplit(b'\x00', 1)[0]
     assert len(elements) == 28 * len(largeSample['elements'])
Пример #6
0
 def testRemoveElements(self, admin):
     publicFolder = utilities.namedFolder(admin, 'Public')
     item = Item().createItem('sample', admin, publicFolder)
     annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
     assert len(Annotation().load(
         annot['_id'], user=admin)['annotation']['elements']) == 1
     Annotationelement().removeElements(annot)
     assert len(Annotation().load(
         annot['_id'], user=admin)['annotation']['elements']) == 0
Пример #7
0
    def testSave(self, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')
        item = Item().createItem('sample', admin, publicFolder)
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
        annot = Annotation().load(annot['_id'], region={'sort': 'size'}, user=admin)
        annot['annotation']['elements'].extend([
            {'type': 'point', 'center': [20.0, 25.0, 0]},
            {'type': 'point', 'center': [10.0, 24.0, 0]},
            {'type': 'point', 'center': [25.5, 23.0, 0]},
        ])
        assert len(list(Annotation().versionList(annot['_id']))) == 1
        # Test without history
        Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, False)
        saved = Annotation().save(annot)
        loaded = Annotation().load(annot['_id'], region={'sort': 'size'}, user=admin)
        assert len(saved['annotation']['elements']) == 4
        assert len(loaded['annotation']['elements']) == 4
        assert saved['annotation']['elements'][0]['type'] == 'rectangle'
        assert loaded['annotation']['elements'][0]['type'] == 'point'
        assert saved['annotation']['elements'][-1]['type'] == 'point'
        assert loaded['annotation']['elements'][-1]['type'] == 'rectangle'
        assert len(list(Annotation().versionList(saved['_id']))) == 1

        # Test with history
        Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, True)
        saved['annotation']['name'] = 'New name'
        saved2 = Annotation().save(saved)
        versions = list(Annotation().versionList(saved2['_id']))
        assert len(versions) == 2
        # If we save with an old version, we should get the original id back
        assert not versions[1]['_id'] == loaded['_id']
        saved3 = Annotation().save(versions[1])
        assert saved3['_id'] == loaded['_id']
Пример #8
0
 def testValidate(self):
     annot = copy.deepcopy(sampleAnnotation)
     doc = {'annotation': annot}
     assert Annotation().validate(doc) is not None
     annot['elements'][0]['id'] = ObjectId('012345678901234567890123')
     annot['elements'].append(annot['elements'][0])
     with pytest.raises(ValidationException, match='not unique'):
         Annotation().validate(doc)
     annot['elements'][1] = copy.deepcopy(annot['elements'][0])
     annot['elements'][1]['id'] = ObjectId('012345678901234567890124')
     assert Annotation().validate(doc) is not None
Пример #9
0
    def testGetVersion(self, user, admin):
        privateFolder = utilities.namedFolder(admin, 'Private')
        Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY,
                      True)
        item = Item().createItem('sample', admin, privateFolder)
        annot = Annotation().createAnnotation(item, admin,
                                              copy.deepcopy(sampleAnnotation))
        annot['annotation']['name'] = 'First Change'
        annot['annotation']['elements'].extend([
            {
                'type': 'point',
                'center': [20.0, 25.0, 0]
            },
            {
                'type': 'point',
                'center': [10.0, 24.0, 0]
            },
            {
                'type': 'point',
                'center': [25.5, 23.0, 0]
            },
        ])
        annot = Annotation().save(annot)
        annot['annotation']['name'] = 'Second Change'
        annot['annotation']['elements'].pop(2)
        annot = Annotation().save(annot)
        versions = list(Annotation().versionList(annot['_id'], user=admin))

        with pytest.raises(AccessException):
            Annotation().getVersion(annot['_id'],
                                    versions[0]['_version'],
                                    user=user)
        assert len(
            Annotation().getVersion(annot['_id'],
                                    versions[0]['_version'],
                                    user=admin)['annotation']['elements']) == 3
        assert len(
            Annotation().getVersion(annot['_id'],
                                    versions[1]['_version'],
                                    user=admin)['annotation']['elements']) == 4
        assert len(
            Annotation().getVersion(annot['_id'],
                                    versions[2]['_version'],
                                    user=admin)['annotation']['elements']) == 1
        # We can get a version by its own id
        assert len(
            Annotation().getVersion(str(versions[1]['_id']),
                                    versions[1]['_version'],
                                    user=admin)['annotation']['elements']) == 4
        # Asking for an invalid version gets us None
        assert Annotation().getVersion(
            annot['_id'], versions[0]['_version'] + 1, user=admin) is None
Пример #10
0
 def testDeleteAnnotation(self, server, admin):
     publicFolder = utilities.namedFolder(admin, 'Public')
     Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY,
                   False)
     item = Item().createItem('sample', admin, publicFolder)
     annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
     annotId = str(annot['_id'])
     assert Annotation().load(annot['_id'], user=admin) is not None
     resp = server.request(path='/annotation/%s' % annotId,
                           user=admin,
                           method='DELETE')
     assert utilities.respStatus(resp) == 200
     assert Annotation().load(annot['_id']) is None
Пример #11
0
 def testHeatmapAnnotation(self, db, admin, fsAssetstore):
     item = Item().createItem('sample', admin, utilities.namedFolder(admin, 'Public'))
     annotation = {
         'name': 'testAnnotation',
         'elements': [{
             'type': 'heatmap',
             'points': [[random.random() for _ in range(4)] for _ in range(10240)]
         }]
     }
     annot = Annotation().createAnnotation(item, admin, annotation)
     assert Annotation().load(annot['_id'], user=admin) is not None
     Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, False)
     result = Annotation().remove(annot)
     Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, True)
     assert result.deleted_count == 1
     assert Annotation().load(annot['_id'], user=admin) is None
Пример #12
0
 def testAnnotationCreate(self, admin):
     item = Item().createItem('sample', admin, utilities.namedFolder(admin, 'Public'))
     annotation = {
         'name': 'testAnnotation',
         'elements': [{
             'type': 'rectangle',
             'center': [10, 20, 0],
             'width': 5,
             'height': 10,
         }]
     }
     result = Annotation().createAnnotation(item, admin, annotation)
     assert '_id' in result
     annotId = result['_id']
     result = Annotation().load(annotId, user=admin)
     assert len(result['annotation']['elements']) == 1
Пример #13
0
def process_annotations(event):
    """Add annotations to an image on a ``data.process`` event"""
    results = _itemFromEvent(event, 'AnnotationFile')
    if not results:
        return
    item = results['item']
    user = results['user']

    file = File().load(event.info.get('file', {}).get('_id'),
                       level=AccessType.READ,
                       user=user)

    if not file:
        logger.error('Could not load models from the database')
        return
    try:
        data = json.loads(b''.join(File().download(file)()).decode('utf8'))
    except Exception:
        logger.error('Could not parse annotation file')
        raise

    if not isinstance(data, list):
        data = [data]
    for annotation in data:
        try:
            Annotation().createAnnotation(item, user, annotation)
        except Exception:
            logger.error('Could not create annotation object from data')
            raise
Пример #14
0
    def testMigrateAnnotationAccessControlNullUserError(self, user, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')
        # create an annotation
        item = Item().createItem('userItem', user, publicFolder)
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)

        # remove the access control properties and save back to the database
        del annot['access']
        del annot['public']
        annot['creatorId'] = None
        Annotation().save(annot)
        with mock.patch('girder_large_image_annotation.models.annotation.logger') as logger:
            Annotation()._migrateDatabase()
            logger.warning.assert_called_once()
        annot = Annotation().load(annot['_id'], force=True)
        assert 'access' not in annot
Пример #15
0
    def testAnnotationGroup(self, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')
        item = Item().createItem('sample', admin, publicFolder)
        elements = [{
            'type': 'rectangle',
            'center': [20.0, 25.0, 0],
            'width': 14.0,
            'height': 15.0,
            'group': 'a'
        }, {
            'type': 'rectangle',
            'center': [40.0, 15.0, 0],
            'width': 5.0,
            'height': 5.0
        }]
        annotationWithGroup = {'name': 'groups', 'elements': elements}

        annot = Annotation().createAnnotation(item, admin, annotationWithGroup)
        result = Annotation().load(annot['_id'], user=admin)
        assert result['annotation']['elements'][0]['group'] == 'a'
Пример #16
0
    def testMigrateAnnotationAccessControl(self, user, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')
        # create an annotation
        item = Item().createItem('userItem', user, publicFolder)
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)

        # assert ACL's work
        with pytest.raises(AccessException):
            Annotation().load(annot['_id'], user=user, level=AccessType.WRITE)

        # remove the access control properties and save back to the database
        del annot['access']
        del annot['public']
        Annotation().save(annot)

        # load the annotation and assert access properties were added
        annot = Annotation().load(annot['_id'], force=True)

        assert annot['access'] == publicFolder['access']
        assert annot['public'] is True
Пример #17
0
 def testUpdateAnnotation(self, server, admin):
     publicFolder = utilities.namedFolder(admin, 'Public')
     item = Item().createItem('sample', admin, publicFolder)
     annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
     import sys
     sys.stderr.write('%r\n' % [annot])  # ##DWM::
     sys.stderr.write('%r\n' % [sampleAnnotation])
     resp = server.request(path='/annotation/%s' % annot['_id'], user=admin)
     assert utilities.respStatus(resp) == 200
     annot = resp.json
     annot['annotation']['elements'].extend([
         {
             'type': 'point',
             'center': [20.0, 25.0, 0]
         },
         {
             'type': 'point',
             'center': [10.0, 24.0, 0]
         },
         {
             'type': 'point',
             'center': [25.5, 23.0, 0]
         },
     ])
     resp = server.request('/annotation/%s' % annot['_id'],
                           method='PUT',
                           user=admin,
                           type='application/json',
                           body=json.dumps(annot['annotation']))
     assert utilities.respStatus(resp) == 200
     assert resp.json['annotation']['name'] == 'sample'
     assert len(resp.json['annotation']['elements']) == 4
     # Test update without elements
     annotNoElem = copy.deepcopy(annot)
     del annotNoElem['annotation']['elements']
     annotNoElem['annotation']['name'] = 'newname'
     resp = server.request('/annotation/%s' % annot['_id'],
                           method='PUT',
                           user=admin,
                           type='application/json',
                           body=json.dumps(annotNoElem['annotation']))
     assert utilities.respStatus(resp) == 200
     assert resp.json['annotation']['name'] == 'newname'
     assert 'elements' not in resp.json['annotation']
     # Test with passed item id
     item2 = Item().createItem('sample2', admin, publicFolder)
     resp = server.request('/annotation/%s' % annot['_id'],
                           method='PUT',
                           user=admin,
                           params={'itemId': item2['_id']},
                           type='application/json',
                           body=json.dumps(annot['annotation']))
     assert utilities.respStatus(resp) == 200
     assert resp.json['itemId'] == str(item2['_id'])
 def testAnnotationWithGirderIdHandlerAltOrder(self, server, fsAssetstore,
                                               admin):
     file = utilities.uploadExternalFile('Easy1.png', admin, fsAssetstore)
     item = Item().load(file['itemId'], user=admin)
     utilities.uploadTestFile('sample_girder_id.anot',
                              admin,
                              fsAssetstore,
                              reference=json.dumps({
                                  'identifier':
                                  'IsAnAnnotationFile',
                                  'uuid':
                                  '12346',
                                  'userId':
                                  str(admin['_id']),
                                  'itemId':
                                  str(item['_id']),
                                  'fileId':
                                  str(file['_id']),
                              }))
     assert Annotation().findOne({'itemId': item['_id']}) is None
     utilities.uploadExternalFile('Easy1.png',
                                  admin,
                                  fsAssetstore,
                                  reference=json.dumps({
                                      'identifier':
                                      'ImageRecord1',
                                      'uuid':
                                      '12346',
                                      'userId':
                                      str(admin['_id']),
                                      'itemId':
                                      str(item['_id']),
                                      'fileId':
                                      str(file['_id']),
                                  }))
     starttime = time.time()
     while time.time() < starttime + 10:
         if Annotation().findOne({'itemId': item['_id']}) is not None:
             break
         time.sleep(0.1)
     assert Annotation().findOne({'itemId': item['_id']}) is not None
Пример #19
0
 def testGridHeatmapAnnotation(self, db, admin, fsAssetstore):
     item = Item().createItem('sample', admin, utilities.namedFolder(admin, 'Public'))
     annotation = {
         'name': 'testAnnotation',
         'elements': [{
             'type': 'griddata',
             'interpretation': 'heatmap',
             'origin': [30, 40, 50],
             'dx': 3,
             'dy': 4,
             'gridWidth': 128,
             'values': [random.random() for _ in range(10240)]
         }]
     }
     annot = Annotation().createAnnotation(item, admin, annotation)
     assert Annotation().load(annot['_id'], user=admin) is not None
     Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, False)
     result = Annotation().remove(annot)
     Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, True)
     assert result.deleted_count == 1
     assert Annotation().load(annot['_id'], user=admin) is None
Пример #20
0
    def testAnnotationAccessControlEndpoints(self, server, user, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')
        # create an annotation
        item = Item().createItem('userItem', user, publicFolder)
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)

        # Try to get ACL's as a user
        resp = server.request('/annotation/%s/access' % annot['_id'],
                              user=user)
        assert utilities.respStatus(resp) == 403

        # Get the ACL's as an admin
        resp = server.request('/annotation/%s/access' % annot['_id'],
                              user=admin)
        assert utilities.respStatus(resp) == 200
        access = dict(**resp.json)

        # Set the public flag to false and try to read as a user
        resp = server.request('/annotation/%s/access' % annot['_id'],
                              method='PUT',
                              user=admin,
                              params={
                                  'access': json.dumps(access),
                                  'public': False
                              })
        assert utilities.respStatus(resp) == 200
        resp = server.request('/annotation/%s' % annot['_id'], user=user)
        assert utilities.respStatus(resp) == 403
        # The admin should still be able to get the annotation with elements
        resp = server.request('/annotation/%s' % annot['_id'], user=admin)
        assert utilities.respStatus(resp) == 200
        assert len(resp.json['annotation']['elements']) == 1

        # Give the user admin access
        access['users'].append({
            'login': user['login'],
            'flags': [],
            'id': str(user['_id']),
            'level': AccessType.ADMIN
        })
        resp = server.request('/annotation/%s/access' % annot['_id'],
                              method='PUT',
                              user=admin,
                              params={'access': json.dumps(access)})
        assert utilities.respStatus(resp) == 200

        # Get the ACL's as a user
        resp = server.request('/annotation/%s/access' % annot['_id'],
                              user=user)
        assert utilities.respStatus(resp) == 200
Пример #21
0
 def testAnnotationHandler(self, server, fsAssetstore, admin):
     file = utilities.uploadExternalFile('data/Easy1.png.sha512', admin,
                                         fsAssetstore)
     item = Item().load(file['itemId'], user=admin)
     utilities.uploadTestFile('sample.anot',
                              admin,
                              fsAssetstore,
                              reference=json.dumps({
                                  'identifier':
                                  'NotAnAnnotation',
                                  'userId':
                                  str(admin['_id']),
                                  'itemId':
                                  str(item['_id']),
                                  'fileId':
                                  str(file['_id']),
                              }))
     assert Annotation().findOne({'itemId': item['_id']}) is None
     utilities.uploadTestFile('sample.anot',
                              admin,
                              fsAssetstore,
                              reference=json.dumps({
                                  'identifier':
                                  'IsAnAnnotationFile',
                                  'userId':
                                  str(admin['_id']),
                                  'itemId':
                                  str(item['_id']),
                                  'fileId':
                                  str(file['_id']),
                              }))
     starttime = time.time()
     while time.time() < starttime + 10:
         if Annotation().findOne({'itemId': item['_id']}) is not None:
             break
         time.sleep(0.1)
     assert Annotation().findOne({'itemId': item['_id']}) is not None
Пример #22
0
def process_annotations(event):
    """Add annotations to an image on a ``data.process`` event"""
    info = event.info
    identifier = None
    reference = info.get('reference', None)
    if reference is not None:
        try:
            reference = json.loads(reference)
            if (isinstance(reference, dict) and isinstance(
                    reference.get('identifier'), six.string_types)):
                identifier = reference['identifier']
        except (ValueError, TypeError):
            logger.debug('Failed to parse data.process reference: %r',
                         reference)
    if identifier is not None and identifier.endswith('AnnotationFile'):
        if 'userId' not in reference or 'itemId' not in reference:
            logger.error(
                'Annotation reference does not contain required information.')
            return

        userId = reference['userId']
        imageId = reference['fileId']

        # load models from the database
        user = User().load(userId, force=True)
        image = File().load(imageId, level=AccessType.READ, user=user)
        item = Item().load(image['itemId'], level=AccessType.READ, user=user)
        file = File().load(info.get('file', {}).get('_id'),
                           level=AccessType.READ,
                           user=user)

        if not (item and user and file):
            logger.error('Could not load models from the database')
            return

        try:
            data = json.loads(b''.join(File().download(file)()).decode('utf8'))
        except Exception:
            logger.error('Could not parse annotation file')
            raise

        if not isinstance(data, list):
            data = [data]
        for annotation in data:
            try:
                Annotation().createAnnotation(item, user, annotation)
            except Exception:
                logger.error('Could not create annotation object from data')
                raise
Пример #23
0
 def testAnnotationsAfterCopyItem(self, server, admin):
     publicFolder = utilities.namedFolder(admin, 'Public')
     item = Item().createItem('sample', admin, publicFolder)
     Annotation().createAnnotation(item, admin, sampleAnnotation)
     resp = server.request('/annotation',
                           user=admin,
                           params={'itemId': item['_id']})
     assert utilities.respStatus(resp) == 200
     assert len(resp.json) == 1
     resp = server.request('/item/%s/copy' % item['_id'],
                           method='POST',
                           user=admin)
     assert utilities.respStatus(resp) == 200
     resp = server.request('/annotation',
                           user=admin,
                           params={'itemId': resp.json['_id']})
     assert utilities.respStatus(resp) == 200
     assert len(resp.json) == 1
     resp = server.request('/item/%s/copy' % item['_id'],
                           method='POST',
                           user=admin,
                           params={'copyAnnotations': 'true'})
     assert utilities.respStatus(resp) == 200
     resp = server.request('/annotation',
                           user=admin,
                           params={'itemId': resp.json['_id']})
     assert utilities.respStatus(resp) == 200
     assert len(resp.json) == 1
     resp = server.request('/item/%s/copy' % item['_id'],
                           method='POST',
                           user=admin,
                           params={'copyAnnotations': 'false'})
     assert utilities.respStatus(resp) == 200
     resp = server.request('/annotation',
                           user=admin,
                           params={'itemId': resp.json['_id']})
     assert utilities.respStatus(resp) == 200
     assert len(resp.json) == 0
     resp = server.request('/item/%s/copy' % item['_id'],
                           method='POST',
                           user=admin,
                           params={'copyAnnotations': True})
     assert utilities.respStatus(resp) == 200
     resp = server.request('/annotation',
                           user=admin,
                           params={'itemId': resp.json['_id']})
     assert utilities.respStatus(resp) == 200
     assert len(resp.json) == 1
Пример #24
0
    def testGetAnnotationWithBoundingBox(self, server, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')
        item = Item().createItem('sample', admin, publicFolder)
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
        annotId = str(annot['_id'])
        resp = server.request(path='/annotation/%s' % annotId, user=admin)
        assert utilities.respStatus(resp) == 200
        assert 'bbox' not in resp.json['_elementQuery']
        assert '_bbox' not in resp.json['annotation']['elements'][0]

        resp = server.request(path='/annotation/%s' % annotId,
                              user=admin,
                              params={'bbox': 'true'})
        assert utilities.respStatus(resp) == 200
        assert 'bbox' in resp.json['_elementQuery']
        assert '_bbox' in resp.json['annotation']['elements'][0]
Пример #25
0
    def testRemove(self, db, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')
        # Test without history
        Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, False)
        item = Item().createItem('sample', admin, publicFolder)
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
        assert Annotation().load(annot['_id'], user=admin) is not None
        result = Annotation().remove(annot)
        assert result.deleted_count == 1
        assert Annotation().load(annot['_id'], user=admin) is None

        # Test with history
        Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, True)
        item = Item().createItem('sample', admin, publicFolder)
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
        assert Annotation().load(annot['_id'], user=admin) is not None
        result = Annotation().remove(annot)
        assert result.modified_count == 1
        assert not Annotation().load(annot['_id'], user=admin)['_active']
Пример #26
0
 def testSimilarElementStructure(self):
     ses = Annotation()._similarElementStructure
     assert ses('a', 'a')
     assert not ses('a', 'b')
     assert ses(10, 10)
     assert ses(10, 11)
     assert not ses(10, 10.0)
     assert ses({'a': 10}, {'a': 12})
     assert not ses({'a': 10}, {'a': 'b'})
     assert not ses({'a': 10, 'b': 11}, {'a': 10})
     assert not ses({'a': 10, 'b': 11}, {'a': 10, 'c': 11})
     assert ses({'id': '012345678901234567890123'},
                {'id': '01234567890123456789ffff'})
     assert not ses({'id': '012345678901234567890123'},
                    {'id': '01234567890123456789----'})
     assert ses([1, 2, 3, 4], [2, 3, 4, 5])
     assert not ses([1, 2, 3, 4], [2, 3, 4, 5, 6])
     assert not ses([1, 2, 3, 4], [2, 3, 4, 'a'])
     assert ses({'points': [
         [1, 2, 3],
         [4, 5, 6],
         [7, 8, 9],
     ]}, {
         'points': [
             [10, 11, 12],
             [13, 14, 15],
             [16, 17, 18],
             [19, 20, 21.1],
         ]
     })
     assert not ses({'points': [
         [1, 2, 3],
         [4, 5, 6],
         [7, 8, 9],
     ]}, {
         'points': [
             [10, 11, 12],
             [13, 14, 15],
             [16, 17, 18],
             [19, 20, 'b'],
         ]
     })
Пример #27
0
    def testLoad(self, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')

        item = Item().createItem('sample', admin, publicFolder)
        with pytest.raises(Exception, match='Invalid ObjectId'):
            Annotation().load('nosuchid')
        assert Annotation().load('012345678901234567890123', user=admin) is None
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
        loaded = Annotation().load(annot['_id'], user=admin)
        assert (loaded['annotation']['elements'][0]['center'] ==
                annot['annotation']['elements'][0]['center'])

        annot0 = Annotation().createAnnotation(item, admin, sampleAnnotationEmpty)
        loaded = Annotation().load(annot0['_id'], user=admin)
        assert len(loaded['annotation']['elements']) == 0
Пример #28
0
def process_annotations(event):
    """Add annotations to an image on a ``data.process`` event"""
    results = _itemFromEvent(event, 'AnnotationFile')
    if not results:
        return
    item = results['item']
    user = results['user']

    file = File().load(event.info.get('file', {}).get('_id'),
                       level=AccessType.READ,
                       user=user)

    if not file:
        logger.error('Could not load models from the database')
        return
    try:
        data = json.loads(b''.join(File().download(file)()).decode('utf8'))
    except Exception:
        logger.error('Could not parse annotation file')
        raise

    if not isinstance(data, list):
        data = [data]
    # Check some of the early elements to see if there are any girderIds
    # that need resolution.
    if 'uuid' in results:
        girderIds = [
            element for annotation in data
            for element in annotation.get('elements', [])[:100]
            if 'girderId' in element
        ]
        if len(girderIds):
            if not resolveAnnotationGirderIds(event, results, data, girderIds):
                return
    for annotation in data:
        try:
            Annotation().createAnnotation(item, user, annotation)
        except Exception:
            logger.error('Could not create annotation object from data')
            raise
Пример #29
0
 def testGetElementsByCentroids(self, admin):
     publicFolder = utilities.namedFolder(admin, 'Public')
     item = Item().createItem('sample', admin, publicFolder)
     largeSample = makeLargeSampleAnnotation()
     # Use a copy of largeSample so we don't just have a reference to it
     annot = Annotation().createAnnotation(item, admin, largeSample.copy())
     # Clear existing element data, the get elements
     annot.pop('elements', None)
     annot.pop('_elementQuery', None)
     Annotationelement().getElements(annot, {'centroids': True})
     assert '_elementQuery' in annot
     assert len(annot['annotation']['elements']) == len(largeSample['elements'])  # 7707
     assert annot['_elementQuery']['centroids'] is True
     assert 'props' in annot['_elementQuery']
     elements = annot['annotation']['elements']
     assert isinstance(elements[0], list)
Пример #30
0
    def testOnItemRemove(self, admin):
        publicFolder = utilities.namedFolder(admin, 'Public')
        # Test without history
        Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, False)
        item = Item().createItem('sample', admin, publicFolder)
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
        assert Annotation().load(annot['_id'], user=admin) is not None
        Item().remove(item)
        assert Annotation().load(annot['_id'], user=admin) is None

        # Test with history
        Setting().set(constants.PluginSettings.LARGE_IMAGE_ANNOTATION_HISTORY, True)
        item = Item().createItem('sample', admin, publicFolder)
        annot = Annotation().createAnnotation(item, admin, sampleAnnotation)
        assert Annotation().load(annot['_id'], user=admin) is not None
        Item().remove(item)
        loaded = Annotation().load(annot['_id'], user=admin)
        assert loaded is not None
        assert not loaded['_active']