Exemple #1
0
def upload():
    if request.method == 'POST':
        description = request.cookies.get('description')
        imagepost = ImagePost(author_id=current_user.id, content=description)
        db.session.add(imagepost)
        db.session.commit()
        for key, f in request.files.items():
            if key.startswith('file'):
                filename = random_filename(f.filename)
                upload_path = os.path.join(
                    current_app.config['APP_UPLOAD_PATH']) + '/' + str(
                        current_user.id)
                if not os.path.exists(upload_path):
                    os.mkdir(upload_path)
                f.save(os.path.join(upload_path, filename))
                filename_s = resize_image(f, filename, 200)
                filename_m = resize_image(f, filename, 800)
                photo = Photo(filename=filename,
                              filename_s=filename_s,
                              filename_m=filename_m,
                              imagepost_id=imagepost.id,
                              author_id=current_user.id)
                db.session.add(photo)
        db.session.commit()
        attention_body = "您的好友" + current_user.nickname + "发布了图像日志。"
        attention_url = url_for('main.show_imagepost',
                                id=imagepost.id,
                                _external=True)
        store_attentions(imagepost.author.get_friends(), attention_body,
                         attention_url)
    return render_template('upload.html')
Exemple #2
0
def upload_avatar(request):
    """
    Sets new user's avatar.
    """
    validate_api_secret_key(request.data.get('app_key'))
    request_serializer = UploadAvatarRequest(data=request.data)

    if request_serializer.is_valid():
        with transaction.atomic():
            profile_user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))

            try:
                profile_user.user_photo.save('user_{}.png'.format(profile_user.id), request.data.get('file'))
                profile_user.save()
                logger.info("User '{}' changed his avatar.".format(profile_user))

                resize_image(profile_user.user_photo.path, AVATAR_WIDTH)
                logger.info("Image '{}' successfully resized!".format(profile_user.user_photo.path))

                return Response({'detail': 'successful',
                                 'data': {'profile_image': '{}?{}'.format(profile_user.user_photo.url,
                                                                          random.randint(0, 1000))}},
                                status=status.HTTP_200_OK)

            except ValidationError:
                logger.info("User '{}' tried to upload not an image as avatar!".format(profile_user))

                return Response({'detail': 'tried to upload not an image',
                                 'data': {}},
                                status=status.HTTP_404_NOT_FOUND)
    else:
        return invalid_data_response(request_serializer)
Exemple #3
0
    def handle(self, *args, **options):
        print('Start processing...')
        current_iteration = 1

        for root, dirs, files in os.walk(options['path']):
            if current_iteration > 1:
                print('Folder "{}" processing'.format(root))

                with open('{}/{}'.format(root, 'meta.json')) as json_file:
                    data = json.loads(json_file.read())

                    book_path = None
                    book_cover = None
                    for filename in files:
                        if filename.endswith('.pdf'):
                            book_path = '{}/{}'.format(root, filename)
                        if filename.endswith('.png'):
                            book_cover = '{}/{}'.format(root, filename)

                    self.prepare_meta(data)

                    with transaction.atomic():
                        author = self.get_author(data)
                        category = self.get_category(data)

                        book = Book.objects.create(
                            book_name=data['name'],
                            id_author=author,
                            id_category=category,
                            description=data['description'],
                            language=Language.objects.get(id=1),
                            who_added=TheUser.objects.get(id=1))
                        book.book_file.save(os.path.basename(book_path),
                                            File(open(book_path, 'rb')))
                        if book_cover:
                            book.photo.save(os.path.basename(book_cover),
                                            File(open(book_cover, 'rb')))
                            resize_image(book.photo.path, BOOK_COVER_HEIGHT)

                        book.save()

                        compress_pdf_task.delay(book.book_file.path, book.id)

                        print(
                            'Book with ID: "{}" name: "{}" uploaded successfully!'
                            .format(book.id, book.book_name))

                        shutil.rmtree(root)

            current_iteration += 1
            print('Processed books: ' + str(current_iteration))
Exemple #4
0
def upload():
    if request.method == 'POST' and 'file' in request.files:
        f = request.files.get('file')
        filename = rename_image(f.filename)
        f.save(os.path.join(current_app.config['ALBUM_UPLOAD_PATH'], filename))
        filename_s = resize_image(
            f, filename, current_app.config['ALBUM_PHOTO_SIZE']['small'])
        filename_m = resize_image(
            f, filename, current_app.config['ALBUM_PHOTO_SIZE']['medium'])
        photo = Photo(filename=filename,
                      filename_s=filename_s,
                      filename_m=filename_m,
                      author=current_user._get_current_object())
        db.session.add(photo)
        db.session.commit()
    return render_template('main/upload.html')
Exemple #5
0
    def img_2_text(self, img):
        img, angle = self.img_rotation(img)
        if self.qrcode_dewarp:
            img = utils.qrcode_dewarp(img)
        self.im = img

        d_wight, d_height = utils.resize_image(
            img, max_predict_size.get(self.invoice_type, 800))
        img = img.resize((d_wight, d_height), Image.NEAREST).convert('RGB')

        im = self.im.convert('RGB')
        large = {}
        ocr_score, score_ = {}, {}

        def __predict(bb, mask, idx):
            try:
                x_gap = (bb[2] - bb[0]) / (img.width / im.width)
                y_gap = (bb[3] - bb[1]) / (img.height / im.height)
                bb_large = [
                    math.ceil((bb[0] / (img.width / im.width)) - 1),
                    math.ceil((bb[1] / (img.height / im.height)) -
                              0.1 * y_gap),
                    math.ceil((bb[2] / (img.width / im.width)) + 1),
                    math.ceil((bb[3] / (img.height / im.height)) + 0.1 * y_gap)
                ]
                large[idx] = bb_large
                corped_im = im.crop(bb_large)
                corped_im = utils.mask_croped_img(corped_im, mask, bb_large)
                self.ocr.predict(utils.handle_img(corped_im),
                                 __predict_callback, idx)
            except:
                ocr_score[idx] = ''
                score_[idx] = None
                self.code = '202'
                self.msg = 'img bbox ocr error'
                logger.error(self.msg)

        def __predict_callback(predict, i):
            ocr_score[i] = utils.decode_mask(predict)
            score_[i] = predict

        tasks = []
        for i, (_, box, mask) in enumerate(self.text_bbox(img)):
            tasks.append(i)
            __predict(box, mask, i)
        while len(ocr_score) < len(tasks):
            pass
        self.box = [
            i[1] for i in sorted(large.items(), key=lambda item: item[0])
        ]
        self.ocr_score = [
            i[1][0]
            for i in sorted(ocr_score.items(), key=lambda item: item[0])
        ]
        self.score_ = [
            i[1][0] for i in sorted(score_.items(), key=lambda item: item[0])
        ]
        logger.info('ocr raw results: {}'.format(self.ocr_score))
        return self.ocr_score, self.box, self.score_, angle
Exemple #6
0
def upload():
    if request.method == 'POST' and 'file' in request.files:
        f = request.files.get('file')  # 获取图片对象
        filename = random_filename(f.filename)  # 重命名文件
        f.save(os.path.join(current_app.config['ALBUMY_UPLOAD_PATH'],
                            filename))  # 保存图片文件到服务器目录
        filename_s = resize_image(
            f, filename, current_app.config['ALBUMY_PHOTO_SIZE']['small'])
        filename_m = resize_image(
            f, filename, current_app.config['ALBUMY_PHOTO_SIZE']['medium'])

        # 创建图片的数据库记录
        photo = Photo(
            filename=filename,
            filename_s=filename_s,
            filename_m=filename_m,
            # 这里使用author关系属性与用户建立关系,需要对代理对象current_user调用_get_current_object方法获取真实用户对象,而不是使用代理对象current_user
            author=current_user._get_current_object())

        db.session.add(photo)
        db.session.commit()
    return render_template('main/upload.html')