예제 #1
0
 def delay_mode(self, frame):
     target = 5
     e = time() - self.time
     f = frame.copy()
     add_text(
         f,
         f"starting in {target - e:.2f}s",
         size=2,
         pos=(0.5, 0.5),
         anchor="center",
     )
     if e >= target:
         self.init_record_mode(frame)
     return f
예제 #2
0
def check_proverb(req):
    """Check if the proverb the user said is correct or not."""

    resp = new_response()
    user_data = load_user_data(req)
    finding_id = user_data.setdefault("finding_id", 0)

    if not finding_id:
        resp = add_text(
            resp, "Para tentares adivinhar um provérbio, escreve 'jogar'!")
        return add_quick_replies(
            resp,
            "Ou escolhe qualquer uma das outras opções...",
            [QR_PLAY, QR_PROGRESS, QR_SUGGESTION, QR_GOODBYE, QR_INSTRUCTIONS],
        )

    intent_name = req["queryResult"]["intent"]["displayName"]

    # Get the proverb the player is trying to guess and check for correct guess
    proverb = proverbs[finding_id]
    # If the intents match, the player got it right!
    if intent_name == proverb["intent"]:
        found = user_data.setdefault("found", [])
        found.append(finding_id)
        user_data["found"] = found
        user_data["finding_id"] = None
        user_data["emojis"] = ""
        user_data["hint_given"] = False
        save_user_data(req, user_data)

        return add_quick_replies(
            resp,
            get_random_string(CORRECT),
            [QR_PLAY_AGAIN, QR_PROGRESS, QR_SUGGESTION, QR_GOODBYE],
        )

    else:
        resp = add_text(resp, "Woops, erraste...")
        return add_quick_replies(
            resp,
            "Tenta outra vez!",
            [
                QR_HINT,
                QR_GIVE_UP,
                QR_PROGRESS,
                QR_SUGGESTION,
                QR_GOODBYE,
                QR_INSTRUCTIONS,
            ],
        )
예제 #3
0
def msg(message):
    chat_id = message.from_user.id
    if chat_id in ads.state_dict:
        if ads.state_dict[chat_id] == 'text':
            utils.add_text(message)
        elif ads.state_dict[chat_id] == 'question':
            text = message.text + '\n@' + message.from_user.username
            del ads.state_dict[chat_id]
            bot_handlers.send_message(config.admin_id, text)
            bot_handlers.send_message(message.from_user.id,
                                      'Ваш вопрос принят. Ожидайте ответа.')
    elif message.text == 'Создать объявление':
        utils.new_ad(chat_id, message.from_user.first_name)
    elif message.text == 'Задать вопрос':
        utils.ask_question(chat_id, message.from_user.username)
    elif message.text == 'Связаться с нами':
        utils.contacts(chat_id)
    else:
        utils.start_over(message)
예제 #4
0
    def record_mode(self, frame):
        f, score = self.differ.compare(self.base, frame)
        f = differ.colorize_diff(f, score, self.threshold)

        if score > self.threshold and self.moved:
            self.moved = False
            self.count += 1

        if score <= self.threshold:
            self.moved = True

        add_text(f, text=f"score: {score:.2f}", pos=(1, 0), anchor=(1, 1))
        add_text(
            f,
            text=f"{self.count}",
            size=6,
            thickness=20,
            pos=(0.5, 0.5),
            anchor="center",
        )
        return f
예제 #5
0
    def stitch_images(self):
        IMAGES_LIST = [
            '淘宝/信.png',
            '淘宝/淘宝图1:放大镜1.jpg',
            '淘宝/淘宝图2:打印效果.jpg',
            '淘宝/淘宝图3:PDF+JPG.jpg',
            '淘宝/淘宝图4:指法标注.jpg',
            '淘宝/淘宝图5:教学视频.jpg',
            '淘宝/淘宝图6:演奏音频.jpg',
            # '淘宝/淘宝图7:粉丝群.jpg',
            '淘宝/淘宝图8:发货说明.jpg',
            '淘宝/淘宝图9:五星好评.jpg'
        ]
        # parser = argparse.ArgumentParser()
        # parser.add_argument('score_file', help='请输入乐谱第一页的文件路径', type=str)
        # parser.add_argument('pages', help='请输入全谱页数', type=str)
        # parser.add_argument('--nofinger', help='添加此参数表示不输出指法页', action='store_true')
        # parser.add_argument('--novideo', help='添加此参数表示不输出教学视频页', action='store_true')
        # parser.add_argument('--noaudio', help='添加此参数表示不输出演奏音频页', action='store_true')
        # args = parser.parse_args()
        file_name = os.path.basename(self.jpg_file_path).split('.')[-2]
        output_dir = os.path.dirname(self.jpg_file_path) + '/' + str(file_name)

        score_title = Image.open('淘宝/淘宝图0:乐谱预览.jpg')
        score_img = Image.open(self.jpg_file_path)
        score_bottom = Image.open('淘宝/淘宝图10:blank.jpg')

        # if args.nofinger:
        #     IMAGES_LIST.remove('淘宝/淘宝图4:指法标注.jpg')
        # if args.novideo:
        #     IMAGES_LIST.remove('淘宝/淘宝图5:教学视频.jpg')
        # if args.noaudio:
        #     IMAGES_LIST.remove('淘宝/淘宝图6:演奏音频.jpg')
        imgs = load_images(IMAGES_LIST)
        c = Canvas(CANVAS_WIDTH)

        score_bottom = add_text(score_bottom, '全谱共' + self.total_pages + '页',
                                '汉仪小麦体简.ttf')

        score = image_stitch(score_title, score_img)
        score = image_stitch(score, score_bottom)
        imgs.insert(1, score)

        for key, img in enumerate(imgs):
            if key == 0:  # first page
                c.append(img)
            else:
                c.append(img, round_corner=50)
        print(self.export_preview_only.get())
        c.export(save_to_disk=output_dir,
                 preview_only=self.export_preview_only.get())
        self.label2['text'] = '图片生成成功,文件存储在:\n' + output_dir
예제 #6
0
def main_hint(req):
    """Called when the user asks for a hint on a given proverb."""

    resp = new_response()
    user_data = load_user_data(req)
    if finding_id := user_data["finding_id"]:
        hint = proverbs[finding_id]["hint"]
        if not hint:
            return add_quick_replies(
                resp,
                "Woops, para este provérbio não tenho nenhuma dica... Desculpa!",
                [
                    QR_GIVE_UP,
                    QR_PROGRESS,
                    QR_SUGGESTION,
                    QR_GOODBYE,
                    QR_INSTRUCTIONS,
                ],
            )

        if user_data["hint_given"]:
            resp = add_text(resp, f"A dica que tenho para te dar é: {hint}")
            return add_quick_replies(
                resp,
                "Mas já to tinha dito!",
                [
                    QR_GIVE_UP,
                    QR_PROGRESS,
                    QR_SUGGESTION,
                    QR_GOODBYE,
                    QR_INSTRUCTIONS,
                ],
            )
        else:
            user_data["hint_given"] = True
            user_data["hints_given"] += 1
            save_user_data(req, user_data)
            return add_quick_replies(
                resp,
                f"A dica que tenho para ti é: {hint}",
                [
                    QR_GIVE_UP,
                    QR_PROGRESS,
                    QR_SUGGESTION,
                    QR_GOODBYE,
                    QR_INSTRUCTIONS,
                ],
            )
예제 #7
0
def main_give_up(req):
    """Called when the user wants to give up on a given proverb."""

    resp = new_response()
    user_data = load_user_data(req)
    # If the user isn't trying to guess any proverb, the user can't give up
    if not user_data["finding_id"]:
        return add_quick_replies(
            resp,
            'Se não estás a tentar adivinhar nenhum provérbio, queres _"desistir"_ de quê?',
            [QR_PLAY, QR_PROGRESS, QR_SUGGESTION, QR_GOODBYE, QR_INSTRUCTIONS],
        )
    # If the user has found all other proverbs, don't let the user give up
    if len(user_data["found"]) == len(proverbs) - 1:
        return add_text(
            resp,
            "Só te falta mais este provérbio! Não podes desistir agora \U0001F4AA",
        )

    # Otherwise, stop signaling this proverb as the one being guessed
    seen = user_data.get("seen", [])  # Retrieve the `seen` list safely
    seen.append(user_data["finding_id"])  # as previous users may not have it
    user_data["seen"] = seen
    user_data["finding_id"] = 0
    user_data["emojis"] = ""
    save_user_data(req, user_data)

    reply = get_random_string(GIVE_UP)
    return add_quick_replies(
        resp,
        reply,
        [
            QR_PLAY_AGAIN, QR_PROGRESS, QR_SUGGESTION, QR_GOODBYE,
            QR_INSTRUCTIONS
        ],
    )
예제 #8
0
def main_play(req):
    """Called when the user wants to play."""

    resp = new_response()
    user_data = load_user_data(req)
    finding_id = user_data.get("finding_id", 0)

    if finding_id:
        emojis = user_data["emojis"]
        resp = add_text(resp, emojis)
        return add_quick_replies(
            resp,
            "Se estiver a ficar difícil podes desistir ou pedir uma pista!",
            [
                QR_HINT,
                QR_GIVE_UP,
                QR_PROGRESS,
                QR_SUGGESTION,
                QR_GOODBYE,
                QR_INSTRUCTIONS,
            ],
        )

    buff_size = user_data.get("buffer_size", TEMPLATE_USER_DATA["buffer_size"])
    # Retrieve as many proverbs as the user can see, as defined by the buffer.
    found = user_data.get("found", [])
    to_be_found = [id for id in difficulty_ratings if id not in found]
    rotation = to_be_found[:buff_size]
    # Then check what is the next unseen proverb that is available
    seen = user_data.get("seen", [])
    to_be_seen = [id for id in rotation if id not in seen]

    if not to_be_found:
        return add_quick_replies(
            resp,
            "Já descobriste todos os provérbios!",
            [QR_SUGGESTION, QR_GOODBYE],
        )

    # Determine if we will start another cycle over some proverbs
    elif not to_be_seen:
        # Increase the buffer size only if it is not already too large;
        # give some extra room in case new proverbs are added to the game later.
        if buff_size <= len(to_be_found):
            buff_size += BUFFER_SIZE_STEP
            user_data["buffer_size"] = buff_size
        to_be_seen = to_be_found[:buff_size]  # no need to redefine `rotation`
        user_data["seen"] = []

        resp = add_text(
            resp,
            "Já te mostrei alguns provérbios diferentes, agora vou começar "
            "a repeti-los, ok? Se estiveres mesmo com dificuldades, pede "
            "ajuda a alguém que esteja por perto \U0001F60E... "
            "Ou pede-me uma pista!",
        )
        # Tell the player if there are other proverbs the player won't see yet
        if len(to_be_found) > len(to_be_seen):
            resp = add_text(
                resp,
                "Assim que fizeres mais algum progresso posso começar "
                "a mostrar outros provérbios ainda mais difíceis!",
            )

    proverb_id = to_be_seen[0]
    proverb = proverbs[proverb_id]
    user_data["emojis"] = proverb["emojis"]
    user_data["finding_id"] = proverb_id
    user_data["hint_given"] = False
    save_user_data(req, user_data)

    return add_quick_replies(
        resp,
        proverb["emojis"],
        [QR_GIVE_UP, QR_PROGRESS, QR_SUGGESTION, QR_GOODBYE, QR_INSTRUCTIONS],
    )
예제 #9
0
def thumb_generator(background_path,
                    picture_path,
                    first_line,
                    second_line,
                    third_line,
                    font_face,
                    color=(0.0, 0.0, 0.0)):

    pdb.gimp_context_set_foreground(color)

    # Create an show new image window with background
    img = my.load_file(background_path)
    gimp.displays_flush()
    gimp.context_push()

    # Add overlay
    overlay = my.create_layer(image=img,
                              width=img.width,
                              height=img.height,
                              image_type=RGB_IMAGE,
                              name='overlay',
                              opacity=35,
                              mode=NORMAL_MODE,
                              add_to_img=False)
    overlay.fill(FILL_WHITE)
    my.add_layer(img, overlay)

    # Add bottom rectangle
    bottom_rect_h = int(round(img.height * .09))
    bottom_rect_layer = my.create_layer(image=img,
                                        width=img.width,
                                        height=bottom_rect_h,
                                        image_type=RGB_IMAGE,
                                        name='bottom_rect',
                                        opacity=100,
                                        mode=NORMAL_MODE)
    pdb.gimp_drawable_edit_fill(bottom_rect_layer, FILL_FOREGROUND)
    my.translate_layer(bottom_rect_layer, 0, img.height - bottom_rect_h)

    # Load popping out
    if (picture_path):
        picture_layer = my.load_image(img, picture_path)
        picture_w = int(round(img.width) * .47)
        my.scale_layer(picture_layer, picture_w, keep_proportion=True)
        my.translate_layer(picture_layer, img.width - picture_w,
                           img.height - picture_layer.height)
        pdb.script_fu_drop_shadow(img, picture_layer, -4, -4, 20, '#000000',
                                  90, FALSE)

    # Create the text lines
    font_size_big = img.height * .24
    font_size_ordinary = img.height * .12
    margin_top = img.height / 7
    margin_left = img.width / 25

    first_line_layer = my.add_text(image=img,
                                   x=margin_left,
                                   y=margin_top,
                                   content=first_line,
                                   font_size=font_size_big,
                                   font_face=font_face)

    second_line_layer = my.add_text(image=img,
                                    x=margin_left,
                                    y=margin_top + font_size_big,
                                    content=' ' + second_line + ' ',
                                    font_size=font_size_ordinary,
                                    font_face=font_face)
    my.set_layer_text_color(second_line_layer, '#FFF')
    pdb.gimp_selection_all(img)
    pdb.gimp_edit_bucket_fill(second_line_layer, BUCKET_FILL_FG,
                              LAYER_MODE_BEHIND, 100, 0, False, 0, 0)

    tl_top = margin_top + font_size_big + font_size_ordinary
    third_line_layer = my.add_text(image=img,
                                   x=margin_left,
                                   y=tl_top,
                                   content=third_line,
                                   font_size=font_size_ordinary,
                                   font_face=font_face)

    gimp.context_pop()
예제 #10
0
def add_random_objects(view_struct, num_objects, args, cams):
    """
  Add random objects to the current blender scene
  """

    # Load the property file
    with open(args.properties_json, 'r') as f:
        properties = json.load(f)
        color_name_to_rgba = {}
        for name, rgb in properties['colors'].items():
            rgba = [float(c) / 255.0 for c in rgb] + [1.0]
            color_name_to_rgba[name] = rgba
        material_mapping = [(v, k) for k, v in properties['materials'].items()]
        object_mapping = [(v, k) for k, v in properties['shapes'].items()]
        size_mapping = list(properties['sizes'].items())

    shape_color_combos = None
    if args.shape_color_combos_json is not None:
        with open(args.shape_color_combos_json, 'r') as f:
            shape_color_combos = list(json.load(f).items())

    positions = []
    objects = {cam.name: [] for cam in cams}
    blender_objects = []
    texts = []
    blender_texts = []
    all_chars = []
    for i in range(num_objects):
        # Choose a random size
        size_name, r = ('large', 0.7)  #random.choice(size_mapping)

        # Try to place the object, ensuring that we don't intersect any existing
        # objects and that we are more than the desired margin away from all existing
        # objects along all cardinal directions.
        num_tries = 0
        while True:
            # If we try and fail to place an object too many times, then delete all
            # the objects in the scene and start over.
            num_tries += 1
            if num_tries > args.max_retries:
                for obj in blender_objects:
                    utils.delete_object(obj)
                for text in blender_texts:
                    utils.delete_object(text)
                return add_random_objects(view_struct, num_objects, args, cams)
            x = uniform(-3, 3)
            y = uniform(-3, 3)
            # Check to make sure the new object is further than min_dist from all
            # other objects, and further than margin along the four cardinal directions
            dists_good = True
            margins_good = True
            for (xx, yy, rr) in positions:
                dx, dy = x - xx, y - yy
                dist = math.sqrt(dx * dx + dy * dy)
                if dist - r - rr < args.min_dist:
                    dists_good = False
                    break
                for direction_name in ['left', 'right', 'front', 'behind']:
                    direction_vec = view_struct['cc']['directions'][
                        direction_name]
                    assert direction_vec[2] == 0
                    margin = dx * direction_vec[0] + dy * direction_vec[1]
                    if 0 < margin < args.margin:
                        __builtin__.print(margin, args.margin, direction_name)
                        __builtin__.print('BROKEN MARGIN!')
                        margins_good = False
                        break
                if not margins_good:
                    break

            if dists_good and margins_good:
                break

        # Choose random color and shape
        if shape_color_combos is None:
            obj_name, obj_name_out = choice(object_mapping)
            color_name, rgba = choice(list(color_name_to_rgba.items()))
        else:
            obj_name_out, color_choices = choice(shape_color_combos)
            color_name = choice(color_choices)
            obj_name = [k for k, v in object_mapping if v == obj_name_out][0]
            rgba = color_name_to_rgba[color_name]

        # For cube, adjust the size a bit
        if obj_name == 'Cube':
            r /= math.sqrt(2)

        # Choose random orientation for the object.
        theta = 360.0 * random()

        # Actually add the object to the scene
        utils.add_object(args.shape_dir, obj_name, r, (x, y), theta=theta)
        obj = bpy.context.object
        blender_objects.append(obj)
        positions.append((x, y, r))
        __builtin__.print("added random object " + str(i))

        # Attach a random material
        mat_name, mat_name_out = choice(material_mapping)
        utils.add_material(mat_name, Color=rgba)

        # Record data about the object in the scene data structure
        for cam in cams:
            pixel_coords = utils.get_camera_coords(cam, obj.location)
            objects[cam.name].append({
                'shape': obj_name_out,
                'size': size_name,
                'material': mat_name_out,
                '3d_coords': tuple(obj.location),
                'rotation': theta,
                'pixel_coords': pixel_coords,
                'color': color_name,
            })

        # Generate Text
        num_chars = 1  # random.choice(range(1, 7))
        chars = choice(
            string.ascii_lowercase
        )  # "".join([random.choice(string.printable[:36]) for _ in range(num_chars)])

        # Add text to Blender
        if args.text:
            try:
                word_bboxes, char_bboxes, chars = utils.add_text(
                    chars, args.random_text_rotation, cams)
                all_chars.extend(chars)
            except Exception as e:
                return purge(blender_objects, blender_texts, view_struct,
                             num_objects, args, cams)

            # Select material and color for text
            text = bpy.context.scene.objects.active
            temp_dict = color_name_to_rgba.copy()
            del temp_dict[color_name]
            mat_name, mat_name_out = choice(material_mapping)
            color_name, rgba = choice(list(temp_dict.items()))
            utils.add_material(mat_name, Color=rgba)

            for char in chars:
                bpy.context.scene.objects.active = char
                utils.add_material(mat_name, Color=rgba)

            blender_texts.append(text)
            __builtin__.print("added text to object " + str(i))

            # Check that all objects are at least partially visible in the rendered image
            for cam in cams:
                bpy.context.scene.camera = cam
                all_objects_visible, visible_chars = check_visibility(
                    blender_objects + all_chars, args.min_pixels_per_object,
                    cams)
                for textid, visible_pixels in visible_chars.items():
                    for char_bbox in char_bboxes[cam.name]:
                        if char_bbox['id'] == textid:
                            char_bbox['visible_pixels'] = visible_pixels
            all_chars_visible = [
                c['visible_pixels'] > args.min_char_pixels
                for c in char_bboxes['cc']
            ]
            if args.all_chars_visible and not all(all_chars_visible):
                __builtin__.print(
                    "not all characters were visible, purging and retrying...")
                return purge(blender_objects, blender_texts, view_struct,
                             num_objects, args, cams)

            for cam in cams:
                x, y, _ = utils.get_camera_coords(cam, text.location)
                objects[cam.name][-1]['text'] = {
                    "font":
                    text.data.font.name,
                    "body":
                    text.data.body,
                    "3d_coords":
                    tuple(text.location),
                    "pixel_coords":
                    (x / bpy.context.scene.render.resolution_x,
                     y / bpy.context.scene.render.resolution_y),
                    "color":
                    color_name,
                    "char_bboxes":
                    char_bboxes,
                    "word_bboxes":
                    word_bboxes
                }
        else:
            all_objects_visible, visible_chars = check_visibility(
                blender_objects + all_chars, args.min_pixels_per_object, cams)

    if args.enforce_obj_visibility and not all_objects_visible:
        __builtin__.print(
            "not all objects were visible, purging and retrying...")
        return purge(blender_objects, blender_texts, view_struct, num_objects,
                     args, cams)

    return texts, blender_texts, objects, blender_objects