예제 #1
0
def test_basic_context(in_file, has_template, has_css):
    out_file = nonrepeat_filename(str(Path('tests/output').joinpath(in_file)))
    in_path = Path('tests/input').joinpath(in_file)
    if in_path.exists():
        shutil.copy(str(in_path), out_file)

    with Anki(out_file) as test_anki:
        test_deck = test_anki.deck('test')

        test_deck.add_item("Hello", "Bonjour")
        test_deck.add_item("How are you ?", "Comment ca va ?")
        test_deck.add_item("Flower", "fleur")
        test_deck.add_item("House", "Maison")

        model_kwargs = dict(name='test_model',
                            fields=["English", "Spanish", "French"])

        if has_template:
            model_kwargs['templates'] = ["{0} - {1} \n<hr id=answer>\n {2}"]
        if has_css:
            model_kwargs['css'] = '.card { font-family: Tahoma; }'

        test_anki.new_model(**model_kwargs)

        test_deck.add_item("Hello", "Hola", "Bonjour", model='test_model')
        test_deck.add_item("How are you ?",
                           "Como estas?",
                           "Comment ca va ?",
                           model='test_model')
        test_deck.add_item("Flower", "flor", "fleur", model='test_model')
        test_deck.add_item("House", "Casa", "Maison", model='test_model')
예제 #2
0
def rename_image():
    global filename

    if filename is not None:
        new_filename = Path(request.get_json()['filename']).with_suffix(Path(filename).suffix)
        new_filename.parent.mkdir(parents=True, exist_ok=True)

        new_filename = new_filename.with_name(secure_filename(new_filename.name))
        new_filename = nonrepeat_filename(str(new_filename))

        shutil.move(filename, new_filename)
        filename = new_filename

        return jsonify({
            'filename': filename
        }), 201

    return Response(status=304)
예제 #3
0
def create_image():
    global filename

    if 'file' in request.files:
        image_path = Path(request.form.get('imagePath'))
        if image_path.suffix:
            image_path = image_path.parent
        image_path.mkdir(parents=True, exist_ok=True)

        file = request.files['file']
        filename = str(image_path.joinpath(secure_filename(file.filename)))
        filename = nonrepeat_filename(filename,
                                      primary_suffix=datetime.now().isoformat()[:10])
        file.save(filename)

        return jsonify({
            'filename': filename
        }), 201

    return Response(status=304)
예제 #4
0
    def from_bytes_io(cls, im_bytes_io, filename=None, tags=None):
        """

        :param im_bytes_io:
        :param str filename:
        :param str|list|tuple tags:
        :return:
        """
        if not filename or filename == 'image.png':
            filename = 'blob/' + str(uuid4())[:8] + '.png'

        image_path = Path(config['folder'])
        image_path.joinpath(filename).parent.mkdir(parents=True, exist_ok=True)

        filename = str(
            image_path.joinpath(filename).relative_to(config['folder']))
        filename = nonrepeat_filename(filename,
                                      primary_suffix=slugify('-'.join(tags)),
                                      root=str(image_path))

        return cls._create(filename, tags=tags, pil_handle=im_bytes_io)
예제 #5
0
    def from_bytes_io(cls, im_bytes_io, filename=None, tags=None):
        """
        :param im_bytes_io:
        :param str filename:
        :param str|list|tuple tags:
        :return:
        """

        if tags is None:
            tags = list()
        elif isinstance(tags, str):
            tags = [tags]

        if not filename or filename == 'image.png':
            filename = slugify('-'.join(tags)) + str(uuid4())[:8] + '.png'

        filename = nonrepeat_filename(filename,
                                      root=str(config['blob_folder']))

        filename = str(config['blob_folder'].joinpath(filename))
        checksum = get_checksum(im_bytes_io)

        im = PIL.Image.open(im_bytes_io)
        image_hash = get_image_hash(im)

        im.save(filename)

        db_image = cls.create(file_id=os.stat(filename).st_ino,
                              filename=filename,
                              checksum=checksum,
                              image_hash=image_hash)

        for tag in set(tags):
            db_image.tags.add(Tag.get_or_create(name=tag)[0])

        return db_image
예제 #6
0
    def move(self, new_filename):
        new_filename = Path(new_filename).relative_to(config['folder'])
        new_filename = new_filename \
            .with_name(new_filename.name) \
            .with_suffix(self.path.suffix)

        if self.filename and self.filename != new_filename:
            new_filename = nonrepeat_filename(str(new_filename),
                                              primary_suffix='-'.join(
                                                  self.tags),
                                              root=config['folder'])

            true_filename = Path(config['folder']).joinpath(new_filename)
            true_filename.parent.mkdir(parents=True, exist_ok=True)

            shutil.move(str(self.path), str(true_filename))

            config['recent'].append(
                {'moved': [(str(self.path), str(true_filename))]})

            self.filename = new_filename
            config['session'].commit()

            return new_filename
예제 #7
0
    def _join(self, db_images, h_align=None, v_align=None):
        if not any(self.id == db_image.id for db_image in db_images):
            db_images.insert(0, self)

        pil_images = list(
            map(PIL.Image.open, (db_image.path for db_image in db_images)))
        widths, heights = zip(*(i.size for i in pil_images))

        max_height = None
        max_width = None
        total_width = None
        total_height = None
        x_offset = 0
        y_offset = 0
        if v_align:
            total_width = sum(widths)
            max_height = max(heights)
            new_im = PIL.Image.new('RGBA', (total_width, max_height))
        else:
            max_width = max(widths)
            total_height = sum(heights)
            new_im = PIL.Image.new('RGBA', (max_width, total_height))

        for im in pil_images:
            w, h = im.size

            if v_align:
                y_offset = {
                    VAlign.TOP.value: 0,
                    VAlign.MIDDLE.value: (max_height - h) / 2,
                    VAlign.BOTTOM.value: max_height - h
                }.get(getattr(v_align, 'value', v_align), 0)
            else:
                x_offset = {
                    HAlign.LEFT.value: 0,
                    HAlign.CENTER.value: (max_width - w) / 2,
                    HAlign.RIGHT.value: max_width - w
                }.get(getattr(h_align, 'value', h_align), 0)

            new_im.paste(im, (int(x_offset), int(y_offset)))

            if v_align:
                x_offset += w
            else:
                y_offset += h

        assert x_offset == total_width or y_offset == total_height

        recent_items = {'deleted': [self.path]}

        new_im_filename = nonrepeat_filename(str(self.path))
        self.path = new_im_filename
        new_im.save(new_im_filename)
        config['session'].commit()

        for db_image in db_images:
            if self.id != db_image.id:
                self.add_tags(db_image.tags)
                recent_items = db_image.delete(recent_items)

        config['recent'].append(recent_items)

        return self