コード例 #1
0
 def setUp(self):
     self.view = ImageViewSet.as_view()
     self.factory = APIRequestFactory()
     self.correct_data = {'uri': '/some/path/to/image.png'}
     self.error_data = {'random': 'random^2'}
     image = Image(uri='/some/path/to/Image1.png')
     image.save()
     image = Image(uri='/some/path/to/Image2.png')
     image.save()
     image = Image(uri='/some/path/to/Image3.png')
     image.save()
コード例 #2
0
def post_image_to_person(args, id):
    img = Image(**args)
    add_new_obj(img)
    #TODO: call to FaceDetector to wake up if not currently woken up, as there's a new image.
    #Think thorugh logic need to be absolutely sure that FaceDetector checks for this.
    # Send person id to the FaceDetector and tell it to add to the face:
    # profile_face=True, person_id_by_human, image_id, face_path
    return create_response(img.to_dict(), 201)
コード例 #3
0
ファイル: conftest.py プロジェクト: ErykKnesz/django-api
 def make_image(**kwargs):
     user = create_user()
     create_account(username=user.username, **kwargs)
     with open('default.JPG', 'rb') as f:
         file = File(f)
         img = Image(image=file, user=user)
         img.save()
         return img
コード例 #4
0
def test_save_image_without_pic():
    image = Image(
        title='my picture',
        description='my description',
    )
    image.save()

    assert image.title == 'my picture'
    assert image.description == 'my description'
コード例 #5
0
 def create(self, validated_data):
     user = None
     request = self.context.get("request")
     if request and hasattr(request, "user"):
         user = request.user
     image_instance = Image(**validated_data)
     image_instance.user = user
     image_instance.save()
     return image_instance
コード例 #6
0
ファイル: test_api.py プロジェクト: eduzen/elements
def test_parse_image_bad_url(mocker):
    mocker.patch('api.api.is_valid_url', return_value=False)
    image_url = 'some url'
    image = Image(
        title='my picture',
        description='my description',
    )
    result = parse_image(image, image_url)

    assert not result
コード例 #7
0
ファイル: test_api.py プロジェクト: eduzen/elements
def test_parse_image_good_url_non_picture(mocker):
    mocker.patch('api.api.is_valid_url', return_value=True)
    mocker.patch('api.api.retrieve_image', return_value=(None, None))
    image_url = 'some url'
    image = Image(
        title='my picture',
        description='my description',
    )
    result = parse_image(image, image_url)

    assert not result
コード例 #8
0
def fill_tables():
    r1 = Repository(repository_path="img_dir", repository_type="local")
    p1 = Person(name="Nick")
    p2 = Person(name="John")
    p3 = Person(name="Mary")
    img1 = Image(image_path="img1.png", repository=r1)
    img2 = Image(image_path="img2.png", repository=r1)
    face1 = Face(face_path=".face/f1.png",
                 image=img1,
                 person_by_human=p1,
                 profile_face=True)
    face2 = Face(face_path=".face/f2.png",
                 image=img1,
                 person_by_human=p2,
                 profile_face=True)
    # want to check getting unknown faces
    np_arr = np.array([1, 2, 4, 3], dtype=np.float32)
    bin_data = pickle.dumps(np_arr)
    logger.info(bin_data)
    face3 = Face(face_path=".face/f3.png", image=img2, embedding=bin_data)
    db.session.add_all([face1, face2, face3])
    db.session.commit()
    return create_response()
コード例 #9
0
def add_image():
    item_id = request.form['id']
    print(item_id)
    img = request.files['file']
    filename = str(datetime.now().year) + str(datetime.now().month) + str(
        datetime.now().day) + str(datetime.now().hour) + str(
            datetime.now().minute) + str(datetime.now().second) + str(
                datetime.now().microsecond) + "." + img.filename.split(".")[-1]
    img.save(os.path.join(UPLOAD_DIRECTORY, filename))
    itm = Item.query.filter_by(id=item_id).first()
    im = Image(picname=filename, item=itm)
    db.session.add(im)
    db.session.commit()
    return './pics/' + filename, 201
コード例 #10
0
def add_directories(repo):
    logger.info("adding directories")
    repo_path = repo.repository_path
    image_paths = []
    extensions = ['.jpg', '.JPG']
    for ext in extensions:
        for path in Path(repo_path).rglob(f"*{ext}"):
            formatted_path = Path(str(path).replace(repo_path, ""))
            image_paths.append(str(formatted_path))
    images = []
    for img_path in image_paths:
        images.append(Image(image_path=img_path, repository_id=repo.id))
    add_new_obj(images)
    logger.info(image_paths)
コード例 #11
0
ファイル: services.py プロジェクト: adaniy/spectro
def take_photo(photo_id, group, sample_id):
    '''
    Calls the Picam class to have the hardware take a picture.
    Returns a Picture object
    '''
    camera = Picam()
    file_path = camera.take_still(str(photo_id) + '.jpg')
    image = Image(id=photo_id,
                  group=group,
                  sample_id=sample_id,
                  type=Image.PHOTO,
                  subject=group.subject,
                  file_path=file_path)
    image.save()
    return image
コード例 #12
0
 def setUp(self):
     self.user_data = {
         "username": "******",
         "first_name": "black",
         "last_name": "panther",
     }
     user_instance = User(**self.user_data)
     user_instance.set_password("gamora")
     user_instance.save()
     image_instance = Image()
     image_instance.user = user_instance
     image_instance.image = File(create_test_image())
     image_instance.name = "test"
     image_instance.color = "BLACK"
     image_instance.save()
コード例 #13
0
ファイル: main.py プロジェクト: hack4impact-uiuc/mentee
def uploadImage(id):
    image = request.files["image"]
    try:
        account_type = int(request.form["account_type"])
    except:
        msg = "Level param doesn't exist or isn't an int"
        return create_response(status=422, message=msg)

    account = None

    try:
        image_response = imgur_client.send_image(image)
    except:
        return create_response(status=400, message=f"Image upload failed")

    try:
        if account_type == Account.MENTEE:
            account = MenteeProfile.objects.get(id=id)
        elif account_type == Account.MENTOR:
            account = MentorProfile.objects.get(id=id)
        else:
            msg = "Level param doesn't match existing account types"
            return create_response(status=422, message=msg)
    except:
        msg = ""
        if account_type == Account.MENTEE:
            msg = "No mentee with that id"
        elif account_type == Account.MENTOR:
            msg = "No mentor with that id"
        logger.info(msg)
        return create_response(status=422, message=msg)

    try:
        if account.image is True and account.image.image_hash is True:
            image_response = imgur_client.delete_image(
                account.image.image_hash)
    except:
        logger.info("Failed to delete image but saving new image")

    new_image = Image(
        url=image_response["data"]["link"],
        image_hash=image_response["data"]["deletehash"],
    )

    account.image = new_image

    account.save()
    return create_response(status=200, message=f"Success")
コード例 #14
0
ファイル: views.py プロジェクト: wotmshuaisi/BookExchange
def image_upload(request):
    if request.method != "POST":
        return HttpResponse()
    source = request.FILES.get('file')
    if source != None:
        source.name = ImageTool.get_new_random_file_name(source.name)
        image = Image(
            img=source
        )
        image.save()
        return HttpResponse(json.dumps({
            'success': True,
            'path': image.img.url
        }))
    else:
        return HttpResponse(json.dumps({
            'success': False,
        }))
コード例 #15
0
    def run(self):
        # Close connections to database, to prevent problems.
        db.connections.close_all()
        for row in csv_reader(self.csv_file, self.charset):
            for value in row:
                # Skip already saved files.
                if Image.objects.filter(source__iexact=value):
                    continue
                image_file, image_type = download_image(value)
                if image_file is None:
                    continue
                random_string = get_random_string(RANDOM_FILENAME_LENGTH)
                # Create database image object and save it.
                image = Image(source=value, type=image_type)

                # Saving file as described in
                # http://www.revsys.com/blog/2014/dec/03/loading-django-files-from-code/
                image.file.save('{}.original.{}'.format(
                    random_string, image_type),
                                image_file,
                                save=True)
コード例 #16
0
def uploadFile():
    if request.method == "POST":
        for i in request.files:
            form_picture = request.files[str(i)]
            # Create hexa filename
            random_hex = secrets.token_hex(8)
            # Get extension of the file
            _, f_ext = os.path.splitext(form_picture.filename)
            # build new filename
            picture_filename = random_hex + f_ext
            # Build path
            picture_path = os.path.join("images/", picture_filename)
            # Resize image
            output_size = (600, 600)
            img = PilImage.open(form_picture)
            img.thumbnail(output_size)
            # Save image in filesystem
            img.save(picture_path)
            # add to database
            db_image = Image(source=picture_filename)
            db.session.add(db_image)
        # COMMIT OUTSIDE OF THE LOOP ?
        db.session.commit()
        return json.dumps({"status": "success"})
コード例 #17
0
ファイル: services.py プロジェクト: adaniy/spectro
def generate_chart(sample_id, image_id):
    sample = get_object_or_404(Sample, id=sample_id)
    readings = csv_string_to_int_list(sample.data)

    the_title = 'Readings for ' + sample.reading_type + ' sample ' + str(
        sample_id)
    if sample.description:
        the_title += "\n" + sample.description

    x = range(len(readings))
    plt.bar(x, readings, 1, color='black')
    plt.title(the_title)
    plt.xlabel('wavelength (340 - 780nm)')
    plt.ylabel('magnitude')

    root_directory = '/home/pi/Pictures'  # TODO move this into settings:IMAGE_SAVE_PATH
    file_path = os.path.join(root_directory, (str(image_id) + '.png'))
    image = Image(id=image_id,
                  group=sample.group,
                  sample_id=sample_id,
                  type=Image.BAR_CHART,
                  file_path=file_path)
    image.save()  # save the image record
    plt.savefig(file_path)  # save the actual file with the image
コード例 #18
0
 def test_default_values(self):
     image = Image()
     self.assertEqual(image.file, '')
コード例 #19
0
 def create(self, valideted_data):
     img = Image()
     img.image = valideted_data['image']
     img.save()
     return img
コード例 #20
0
def new_task():

    post_json = request.get_json()
    
    # Kunde anlegen oder über ID selektieren
    customer = None
    cus_id = None
    if hasattr(post_json, "cusID"):
        cus_id = post_json["cusID"]
    else:
        customer = Customer(
            cus_title = post_json["gender"],
            cus_first_name = post_json["firstName"],
            cus_last_name = post_json["lastName"],
            cus_email = post_json["email"],
            cus_phone_no = post_json["prefixNumber"] + " " + post_json["phone"],
            cus_street = post_json["street"],
            cus_house_number = post_json["houseNumber"],
            cus_post_code = post_json["postCode"]
        )
        db.session.add(customer) # pylint: disable=maybe-no-member
        db.session.commit() # pylint: disable=maybe-no-member
        cus_id = customer.cus_id

    # Gerät anlegen oder über ID selektieren
    device = None
    dev_id = None
    if hasattr(post_json, "devID"):
        dev_id = post_json["devID"]
    else:
        device = Device(
            dev_name = post_json["devName"],
            dev_model = post_json["devModel"],
            dev_category = post_json["categoryName"],
            dev_electronic_mechanical_type = post_json["electricalMechanical"],
            dev_mnf_name = post_json["manufacturerName"],
        )
        db.session.add(device) # pylint: disable=maybe-no-member
        db.session.commit() # pylint: disable=maybe-no-member
        dev_id = device.dev_id

    new_task = Task(
        tsk_fault_description = post_json["faultDescription"],
        tsk_creation_date = datetime.now(),
        tsk_cus_id = cus_id,
        tsk_dev_id = dev_id,
        tsk_state = "new",
        tsk_next_step = "not_set",
    )

    db.session.add(new_task) # pylint: disable=maybe-no-member
    db.session.commit() # pylint: disable=maybe-no-member

    tk = generate_token("customer", new_task.tsk_id)

    # QR-Code generieren
    image_file = generate_qrcode_label("customer", new_task.tsk_id, tk)

    # Files anlegen
    files = post_json["files"]
    for filename in files:
        new_file = Image(img_filename=filename, img_tsk_id=new_task.tsk_id)
        db.session.add(new_file) # pylint: disable=maybe-no-member
        db.session.commit() # pylint: disable=maybe-no-member

    # Token als neuer Token in der Session speichern.
    session['NEW_TOKEN'] = tk

    return {'tsk_id':new_task.tsk_id, 'tsk_token': tk}