Пример #1
0
async def api_slots() -> Union[str, Response]:
    """Get the values of all slots."""
    assert core is not None

    if request.method == "POST":
        overwrite_all = request.args.get("overwrite_all",
                                         "false").lower() == "true"
        new_slot_values = await request.json

        slots_dir = Path(
            core.profile.write_path(
                core.profile.get("speech_to_text.slots_dir", "slots")))

        if overwrite_all:
            # Remote existing values first
            for name in new_slot_values.keys():
                slots_path = safe_join(slots_dir, f"{name}")
                if slots_path.is_file():
                    try:
                        slots_path.unlink()
                    except Exception:
                        logger.exception("api_slots")

        for name, values in new_slot_values.items():
            if isinstance(values, str):
                values = [values]

            slots_path = slots_dir / name

            # Create directories
            slots_path.parent.mkdir(parents=True, exist_ok=True)

            # Write data
            with open(slots_path, "a") as slots_file:
                for value in values:
                    value = value.strip()
                    if value:
                        print(value, file=slots_file)

        return "OK"

    # Read slots into dictionary
    slots_dir = Path(
        core.profile.read_path(
            core.profile.get("speech_to_text.slots_dir", "slots")))

    slots_dict = {}

    if slots_dir.is_dir():
        for slot_file_path in slots_dir.glob("*"):
            if slot_file_path.is_file():
                slot_name = slot_file_path.name
                slots_dict[slot_name] = [
                    line.strip()
                    for line in slot_file_path.read_text().splitlines()
                ]

    return jsonify(slots_dict)
Пример #2
0
async def open_file_raw(filename):
    filename = safe_join('/site/cfgs', filename)
    try:
        with open(filename, "rb") as fd:
            lines = b''.join(line for line in fd)

        return Response(lines, status=200, content_type="text/plain; charset=utf-8")
        # return await render_template('file.html', file=filename, strings=lines)
    except NotFound:
        return await abort(404)
Пример #3
0
def api_slots_by_name(name: str) -> typing.Union[str, Response]:
    """Get or set the values of a slot list."""
    assert core is not None
    overwrite_all = request.args.get("overwrite_all",
                                     "false").lower() == "true"

    slots_dir = Path(
        core.profile.read_path(
            core.profile.get("speech_to_text.slots_dir", "slots")))

    if request.method == "POST":
        if overwrite_all:
            # Remote existing values first
            slots_path = safe_join(slots_dir, f"{name}")
            if slots_path.is_file():
                try:
                    slots_path.unlink()
                except Exception:
                    _LOGGER.exception("api_slots_by_name")

        slots_path = Path(
            core.profile.write_path(
                core.profile.get("speech_to_text.slots_dir", "slots"),
                f"{name}"))

        # Create directories
        slots_path.parent.mkdir(parents=True, exist_ok=True)

        # Write data
        with open(slots_path, "wb") as slots_file:
            slots_file.write(request.data)

        return f"Wrote {len(request.data)} byte(s) to {slots_path}"

    # Load slots values
    slot_values: typing.List[str] = []
    slot_file_path = slots_dir / name
    if slot_file_path.is_file():
        slot_values = [
            line.strip() for line in slot_file_path.read_text().splitlines()
        ]

    return jsonify(slot_values)
Пример #4
0
def get_current_qr_code():
    return send_file(safe_join(SCRIPT_PATH, CODE_FILE_NAME))
Пример #5
0
async def get_mod_icon(filename):
  path = safe_join(MOD_ICON_DIR, filename)
  return await send_file(path)
Пример #6
0
async def get_map_thumb(filename):
  path = safe_join(MAP_THUMBNAIL_DIR, filename)
  return await send_file(path)
Пример #7
0
async def api_slots() -> Union[str, Response]:
    """Get the values of all slots."""
    assert core is not None

    if request.method == "POST":
        overwrite_all = request.args.get("overwrite_all", "false").lower() == "true"
        new_slot_values = json5.loads(await request.data)

        word_casing = core.profile.get(
            "speech_to_text.dictionary_casing", "ignore"
        ).lower()
        word_transform = lambda s: s

        if word_casing == "lower":
            word_transform = str.lower
        elif word_casing == "upper":
            word_transform = str.upper

        slots_dir = Path(
            core.profile.write_path(
                core.profile.get("speech_to_text.slots_dir", "slots")
            )
        )

        if overwrite_all:
            # Remote existing values first
            for name in new_slot_values:
                slots_path = safe_join(slots_dir, f"{name}")
                if slots_path.is_file():
                    try:
                        slots_path.unlink()
                    except Exception:
                        logger.exception("api_slots")

        for name, values in new_slot_values.items():
            if isinstance(values, str):
                values = [values]

            slots_path = slots_dir / name

            # Create directories
            slots_path.parent.mkdir(parents=True, exist_ok=True)

            # Merge with existing values
            values = {word_transform(v.strip()) for v in values}
            if slots_path.is_file():
                values.update(
                    word_transform(line.strip())
                    for line in slots_path.read_text().splitlines()
                )

            # Write merged values
            if values:
                with open(slots_path, "w") as slots_file:
                    for value in values:
                        if value:
                            print(value, file=slots_file)

        return "OK"

    # Read slots into dictionary
    slots_dir = Path(
        core.profile.read_path(core.profile.get("speech_to_text.slots_dir", "slots"))
    )

    slots_dict = {}

    if slots_dir.is_dir():
        for slot_file_path in slots_dir.glob("*"):
            if slot_file_path.is_file():
                slot_name = slot_file_path.name
                slots_dict[slot_name] = [
                    line.strip() for line in slot_file_path.read_text().splitlines()
                ]

    return jsonify(slots_dict)