Ejemplo n.º 1
0
    def test_can_exclude_annotations_with_null_tags(self):
        with self._session():
            user = User.create(**user1())
            user_id = user.id

        with self._session() as s:
            user = next(s.filter(User.id == user_id))
            snd = sound(user)
            sound_id = snd.id

        with self._session() as s:
            user = next(s.filter(User.id == user_id))
            snd = next(s.filter(Sound.id == sound_id))
            annotation = Annotation.create(
                creator=user,
                created_by=user,
                sound=snd,
                start_seconds=1,
                duration_seconds=1,
                tags=['drums'],
                data_url=None)
            Annotation.create(
                creator=user,
                created_by=user,
                sound=snd,
                start_seconds=1,
                duration_seconds=1,
                tags=None,
                data_url=None)

        with self._session() as s:
            annotations = list(s.filter(Annotation.tags != []))
            self.assertEqual(1, len(annotations))
            self.assertEqual(annotation.id, annotations[0].id)
Ejemplo n.º 2
0
 def __init__(self, mid):
     Annotation.__init__(self, mid, 
                         name=u"Informação Simples",
                         mtype=InformationAnnotation.TYPE)
     
     self.notification_icon_file = None
     self.notification_icon_duration = None
     self.information_media = None
     self.information_media_timestamp = None
     self.information_media_duration = None
Ejemplo n.º 3
0
    def save_experiment(self, data):
        """
        Try to save results into MongoDB
        :param metabolites_by_feature:
        :param data
        @return: None
        """
        logging.info("Saving experiment in mongo db...")

        mongo = os.environ.get('MONGOHQ_URL')
        if mongo is not None :
            connect('hola', host=mongo)
        else:
            connect('omicsservices')

        exp = MetabolomicsExperiment()
        #exp.parameters = "All the xcms file goes here"
        exp.organization = data.get('organization', "IMS")
        exp.description = data['description']  #get('description', '')
        exp.title = data.get('title', "Alzeihmer")
        exp.software = data.get('software', "XCMS")
        exp.version = data.get('version', "3.18")

        exp.save()

        for p in self.peakels:
            ft = Feature()
            if p.main_attribution is not None:
                ft.main_attribution = p.main_attribution.attribution
            else:
                ft.main_attribution = self._get_main_putative_attribution(p)

            for k, v in p.area_by_sample_name.items():
                ab = Abundance(sample=k, abundance=v)
                ft.abundances.append(ab)

            #ft.attributions = p.attributions

            for m in p.annotations:
                annot = Annotation()
                annot.annotation = m.metabolite.name
                annot.score1 = m.score_isos
                annot.score2 = m.score_network
                ft.annotations.append(annot)

            ft.mass = p.moz
            ft.rt = p.rt
            ft.experiment_id = exp
            ft.save()

        logging.info("Done.")
Ejemplo n.º 4
0
    def test_can_store_and_retrieve_with_no_data_url(self):
        with self._session():
            user = User.create(**user1())
            user_id = user.id

        with self._session() as s:
            user = next(s.filter(User.id == user_id))
            snd = sound(user)
            sound_id = snd.id

        with self._session() as s:
            user = next(s.filter(User.id == user_id))
            snd = next(s.filter(Sound.id == sound_id))
            annotation = Annotation.create(
                creator=user,
                created_by=user,
                sound=snd,
                start_seconds=1,
                duration_seconds=1,
                tags=['drums'],
                data_url=None)
            annotation_id = annotation.id

        with self._session():
            annotation = next(s.filter(Annotation.id == annotation_id))
            self.assertIsNone(annotation.data_url)
Ejemplo n.º 5
0
    def test_error_when_setting_computed_field(self):
        with self._session():
            user = User.create(**user1())
            user_id = user.id

        with self._session() as s:
            user = next(s.filter(User.id == user_id))
            snd = sound(user)
            sound_id = snd.id

        with self._session() as s:
            user = next(s.filter(User.id == user_id))
            snd = next(s.filter(Sound.id == sound_id))
            annotation = Annotation.create(
                creator=user,
                created_by=user,
                sound=snd,
                start_seconds=1,
                duration_seconds=1,
                tags=['drums'],
                data_url=None)

        def x():
            annotation.end_seconds = 10

        self.assertRaises(ImmutableError, x)
Ejemplo n.º 6
0
    def get_model_example(self, content_type):
        dataset = User.create(
            user_name='HalIncandenza',
            password='******',
            email='*****@*****.**',
            user_type=UserType.DATASET,
            about_me='Tennis 4 Life')

        snd = Sound.create(
            creator=dataset,
            created_by=dataset,
            info_url='https://example.com/sound',
            audio_url='https://example.com/sound/file.wav',
            low_quality_audio_url='https://example.com/sound/file.mp3',
            license_type=LicenseType.BY,
            title='A sound',
            duration_seconds=12.3,
            tags=['test'])

        annotations = [
            Annotation.create(
                creator=dataset,
                created_by=dataset,
                sound=snd,
                start_seconds=1,
                duration_seconds=1,
                tags=['kick']
            ),
            Annotation.create(
                creator=dataset,
                created_by=dataset,
                sound=snd,
                start_seconds=2,
                duration_seconds=1,
                tags=['snare']
            ),
        ]
        results = build_list_response(
            actor=dataset,
            items=annotations,
            total_count=100,
            add_next_page=True,
            link_template=self.link_template(dataset.id),
            page_size=2,
            page_number=2)
        return JSONHandler(AppEntityLinks()) \
            .serialize(results, content_type).decode()
Ejemplo n.º 7
0
    def on_post(self, req, resp, sound_id, session, actor):
        """
        description:
            Create a new annotation for the sound with identifier `sound_id`.
            Text tags can be added directly to the resource via the `tags`
            field, or arbitrary binary or other structured data may be pointed
            to via the `data_url` parameter.
        url_params:
            sound_id: The identifier of the sound to annotate
        example_request_body:
            python: get_example_post_body
        responses:
            - status_code: 201
              description: Successful annotation creation
            - status_code: 400
              description: Input model validation error
            - status_code: 404
              description: Provided an invalid `sound_id`
            - status_code: 401
              description: Unauthorized request
            - status_code: 403
              description: User is not permitted to create annotations
        """
        sound = session.find_one(Sound.id == sound_id)

        annotations_key = 'annotations'

        annotations = req.media.get(annotations_key)
        if not annotations:
            error = ValueError(
                'You must provide one or more '
                'annotations in field "annotations"')
            raise CompositeValidationError((annotations_key, error))

        for annotation in annotations:
            annotation['created_by'] = actor
            annotation['sound'] = sound
            Annotation.create(
                creator=actor,
                **annotation)
        resp.set_header('Location', f'/sounds/{sound_id}/annotations')
        resp.status = falcon.HTTP_CREATED
Ejemplo n.º 8
0
    def on_get(self, req, resp, session, actor):
        """
        description:
            Get a list of annotations
        query_params:
            page_size: The number of results per page
            page_number: The page of results to view
            low_id: Only return identifiers occurring later in the series than
                this one
            order: If `desc`, return results from most to least recent, if `asc`
                return results from least to most recent.
            tags: Only return annotations with all specified tags
            with_tags: Only return annotations that have at least one tag,
                generally excluding dense features computed by featurebots.  This
                parameter is mutually exclusive with `tags` and will be ignored
                if it is present.
        responses:
            - status_code: 200
              description: Successfully fetched an annotation
              example:
                python: get_example_list_model
            - status_code: 401
              description: Unauthorized request
            - status_code: 403
              description: User is not permitted to access this annotation
        """
        query = Annotation.all_query()

        # TODO: This is near-duplicate code from the /sounds resource below.
        # factor it out
        additional_params = {}
        tags = req.get_param_as_list('tags')
        with_tags = req.get_param_as_bool('with_tags')
        if tags:
            # look for specific tags
            additional_params['tags'] = tags
            for tag in tags:
                query = query & (Annotation.tags == tag)
        elif with_tags:
            # only ensure that some tags are present
            additional_params['with_tags'] = with_tags
            query = query & (Annotation.tags != [])

        list_entity(
            req,
            resp,
            session,
            actor,
            query,
            Annotation,
            self.LINK_TEMPLATE,
            additional_params=additional_params)
Ejemplo n.º 9
0
 def on_get(self, req, resp, session):
     """
     description:
         Return some high-level stats about users, sounds and annotations
     responses:
         - status_code: 200
           example:
             python: get_model_example
           description: Successfully fetched stats
     """
     resp.media = self._get_model(
         total_sounds=session.count(Sound.all_query()),
         total_annotations=session.count(Annotation.all_query()),
         total_users=session.count(User.all_query()),
     )
     resp.status = falcon.HTTP_200
Ejemplo n.º 10
0
def save_data_annotate():
	req_body = request.get_json()
	if req_body is None or "path_file" not in req_body:
		return abort(400)
	file_name = req_body["path_file"]
	if '..' in file_name:
		return abort(400)
	if "get" in req_body:
		try:
# 			print(req_body)
			sopiuid = req_body["sopiuid"]
			path_file = os.path.basename(req_body["path_file"])
			siuid = req_body["siuid"]

			file_auto_analysis = "/root/tuannm/dicom-server/data/json_machine/{}__{}__{}.json".format(siuid, sopiuid, path_file)
			
			print("Read Auto analysis file: {}".format(file_auto_analysis))
			_logger.info("Read Auto analysis file: {}".format(file_auto_analysis))

			with open(file_auto_analysis, 'r') as fr:
				data = json.load(fr)
			fr.close()
			
			return jsonify(status=True, data=data)
		except Exception as e:
			# _logger.info(f"GO TO get_auto_analysis: {req_body}")	
			_logger.error(e)
			return {'status': False, 'error': e}, 500
		
	try:
		req_body["timestamp"] = datetime.datetime.now().strftime("%s")
		savedfile_path, savedfile_location = Annotation.save(req_body)
		print("Saved file: {}".format(savedfile_path))
		_logger.info("Save file: {}".format(savedfile_path))
		return jsonify(status=True, data=urllib.parse.urljoin(
			request.host_url, urllib.parse.quote(savedfile_location)
		))
	except Exception as e:
		_logger.error(e)
		return {'status': False, 'error': e}, 500
Ejemplo n.º 11
0
    def test_created_by_user_name_is_computed(self):
        with self._session():
            user = User.create(**user1())
            user_id = user.id

        with self._session() as s:
            user = next(s.filter(User.id == user_id))
            snd = sound(user)
            sound_id = snd.id

        with self._session() as s:
            user = next(s.filter(User.id == user_id))
            snd = next(s.filter(Sound.id == sound_id))
            annotation = Annotation.create(
                creator=user,
                created_by=user,
                sound=snd,
                start_seconds=1,
                duration_seconds=1,
                tags=['drums'],
                data_url=None)

        self.assertEqual(user.user_name, annotation.created_by_user_name)
Ejemplo n.º 12
0
    def test_permissions_error_when_creator_is_aggregator(self):
        with self._session():
            creator = User.create(**user1(user_type=UserType.HUMAN))
            creator_id = creator.id
            aggregator = User.create(**user1(user_type=UserType.AGGREGATOR))
            aggregator_id = aggregator.id

        with self._session() as s:
            creator = s.find_one(User.id == creator_id)
            snd = sound(creator)
            snd_id = snd.id

        with self._session() as s:
            snd = s.find_one(Sound.id == snd_id)
            aggregator = s.find_one(User.id == aggregator_id)
            self.assertRaises(PermissionsError, lambda: Annotation.create(
                creator=aggregator,
                created_by=aggregator,
                sound=snd,
                start_seconds=1,
                duration_seconds=1,
                tags=['drums'],
                data_url=None
            ))