Exemplo n.º 1
0
Arquivo: monday.py Projeto: hunj/yui
async def monday_dog(bot):
    monday_dog_say = functools.partial(
        bot.api.chat.postMessage,
        channel=C.general.get(),
        as_user=False,
        username='******',
        icon_url='https://i.imgur.com/UtBQSLl.jpg',
    )
    today = now()
    holiday = None
    try:
        holiday = await get_holiday_name(bot.config.TDCPROJECT_KEY, today)
    except aiohttp.client_exceptions.ClientOSError:
        pass

    if holiday:
        says = [
            '월' * random.randint(5, 15) + '…' + ''.join(
                random.choice(['?', '!'])
                for x in range(random.randint(3, 10))),
            '(하지만 {} 쉬는 날이었다고 한다)'.format(tossi.postfix(holiday, '(이)라'))
        ]
        for say in says:
            await monday_dog_say(text=say)
    else:
        says = [
            '월' * random.randint(60, 220),
            ''.join('월' * random.randint(1, 6) + '!' * random.randint(1, 3)
                    for x in range(40)),
            '월요일' * random.randint(30, 70),
        ]
        random.shuffle(says)

        for say in says[:min(bot.config.MONDAY_DOG_LIMIT, len(says))]:
            await monday_dog_say(text=say)
Exemplo n.º 2
0
def create_voice(request, story_id, user_id):
    scripts = Script.objects.filter(has_name=True)
    user = get_object_or_404(CustomUser, pk=user_id)
    denominator = int(request.GET.get('denominator', None))
    numerator = int(request.GET.get('numerator', None))

    if denominator is not None and numerator is not None:
        length = scripts.count()
        div = length // denominator
        start = (numerator - 1) * div
        if denominator == numerator:
            scripts = scripts[start:]
        else:
            scripts = scripts[start:start + div]
    for script in scripts:
        s = script.content
        s = s.replace('<br>', '.')

        splitted_string = s.split('{child_name}')
        wanted = splitted_string[1].split()[0].split('.')[0]

        temp = tossi.postfix(user.child_name, wanted)

        result_script = s.replace('{child_name}' + wanted, temp)

        store_path = f'{settings.BASE_DIR}/voice/story/{story_id}/user/{user_id}/'
        if not os.path.isdir(store_path):
            os.makedirs(store_path)

        TTS(result_script, f'{store_path}script_{script.id}.mp3')
    return Response(status=status.HTTP_200_OK)
Exemplo n.º 3
0
    async def convert(self, ctx, arg):
        arg = arg.lower()

        if arg in ["스플래쉬테일", "스플레시테일", "스플레쉬테일", "스플래시테일", "splashtail"]:
            return "스플래쉬테일"
        elif arg in ["플렌티핀", "플랜티핀", "plentifins"]:
            return "플렌티핀"
        elif arg in ["앤션트스케일", "엔션트스케일", "앤션트스캐일", "엔션트스캐일", "ancientscales"]:
            return "앤션트스케일"
        elif arg in ["와일드스플래쉬", "와일드스플래시", "와일드스플레쉬", "wildsplashes"]:
            return "와일드스플래쉬"
        elif arg in ["데빌피쉬", "데빌피시", "devilfish"]:
            return "데빌피쉬"
        elif arg in ["아일호퍼", "islehoppers"]:
            return "아일호퍼"
        elif arg in ["폰디", "pondies"]:
            return "폰디"
        elif arg in ["배틀길", "battlegills"]:
            return "배틀길"
        elif arg in ["스톰피쉬", "스톰피시", "stormfish"]:
            return "스톰피쉬"
        elif arg in ["래커", "레커", "wreckers"]:
            return "래커"

        arg = tossi.postfix(arg, "는")
        raise commands.BadArgument(f"{arg} 물고기 종류가 아닙니다.")
Exemplo n.º 4
0
def validate(_s, _p, _c, _answer, _triple_type):
    #print('validate')
    answer = _answer
    response = '답변이 이상합니다. 다시 말씀해주세요.'
    ner_result = ETRI_NER(answer)
    #print(ner_result)
    for item in [_s, _p]:
        for ner in ner_result:
            if item in ner:
                ner_result.remove(ner)
    if not ner_result:
        return response
    else:
        #print(_s, _p, _c, ner_result)
        response = _s + '의 ' + tossi.postfix(_p, '이') + ' ' + tossi.postfix(
            ner_result[0][0], '이') + ' 맞습니까?'
        #print(response)
        return response
    '''
Exemplo n.º 5
0
def determine_particle(word: str, particle: str) -> str:
    if not particle.startswith('('):
        return word + particle

    try:
        ret = tossi.postfix(word, particle)
    except ValueError as e:
        log.exception(e)
        return word + particle
    log.debug(f'tossi: {word} / {particle} -> {ret}')
    return ret
Exemplo n.º 6
0
 async def convert(self, ctx, arg):
     arg = arg.lower()
     if arg in ["닭", "치킨", "chicken"]:
         return "chicken"
     elif arg in ["돼지", "pig", "피그"]:
         return "pig"
     elif arg in ["뱀", "snake", "스네이크"]:
         return "snake"
     un = tossi.postfix(arg, "은")
     cmdname = ctx.command
     helpstr = str_help_by_cmd(cmdname)
     raise commands.BadArgument(f"{un} 동물 종류가 아닙니다. {helpstr}", arg)
Exemplo n.º 7
0
    async def convert(self, ctx, arg):
        arg = arg.lower()

        if arg in ["갤리온", "갤리언", "galleon"]:
            return {"name": "갤리온", "id": GALLEON}
        elif arg in ["브리건틴", "브리건타인", "브리간틴", "brigantine"]:
            return {"name": "브리건틴", "id": BRIG}
        elif arg in ["슬루프", "sloop"]:
            return {"name": "슬루프", "id": SLOOP}

        arg = tossi.postfix(arg, "는")
        raise commands.BadArgument(f"{arg} 배 종류가 아닙니다.")
Exemplo n.º 8
0
async def holiday_message(bot):
    holiday = None
    today = now()
    try:
        holiday = await get_holiday_name(bot.config.TDCPROJECT_KEY, today)
    except aiohttp.client_exceptions.ClientOSError:
        pass

    if holiday:
        await bot.say(
            C.general.get(),
            '오늘은 {}! 즐거운 휴일 되세요!'.format(tossi.postfix(holiday, '(이)에요'), ))
Exemplo n.º 9
0
    async def convert(self, ctx, arg):
        pos = arg.upper()
        pos = pos.replace("-", "")

        ispos = re.match(r"^[A-Z]{1}-*([1-9]|[0,1][0-9]|2[0-6])$", pos)
        ispos = True if ispos is not None else False

        if not ispos:
            un = tossi.postfix(arg, "은")
            cmdname = ctx.command
            helpstr = str_help_by_cmd(cmdname)
            raise commands.BadArgument(f"{un} 좌표가 아닙니다. {helpstr}", arg)

        return pos
Exemplo n.º 10
0
Arquivo: day.py Projeto: item4/yui
async def holiday_message(bot):
    holidays = None
    today = now()
    try:
        holidays = await get_holiday_names(today)
    except aiohttp.client_exceptions.ClientOSError:
        pass

    if holidays:
        await bot.say(
            bot.config.CHANNELS["general"],
            "오늘은 {}! 즐거운 휴일 되세요!".format(tossi.postfix(holidays[0],
                                                       "(이)에요"), ),
        )
Exemplo n.º 11
0
Arquivo: day.py Projeto: u1-liquid/yui
async def holiday_message(bot):
    holidays = None
    today = now()
    try:
        holidays = await get_holiday_names(today)
    except aiohttp.client_exceptions.ClientOSError:
        pass

    if holidays:
        await bot.say(
            C.general.get(),
            '오늘은 {}! 즐거운 휴일 되세요!'.format(tossi.postfix(holidays[0],
                                                       '(이)에요'), ),
        )
Exemplo n.º 12
0
def NLG(intro_triples, question_triple, keywords, pre_state, state):
    sentence = ''
    if (state == 'SET_Q'):
        if (pre_state == 'SET_Q'):
            sentence = '무슨 말인지 모르겠어요. 다시 말씀해주세요.'
        else:
            for triple in intro_triples:
                intro_sentence = generate_sentence(triple, 'answers')
                sentence += intro_sentence + '\n'
            question = generate_sentence(question_triple, 'questions')
            sentence += question
    elif (state == 'CHECK_Q'):
        s, p, o, _ = question_triple
        sentence = s + '의 ' + tossi.postfix(p, '이') + ' ' + tossi.postfix(
            o, '이') + ' 맞습니까?'
    elif (state == 'CLOSE'):
        if (keywords[0] == '네'):
            sentence = '감사합니다.'
        elif (keywords[0] == '아니요'):
            sentence = '제가 잘못 들었나보네요.'
    else:
        if (keywords == []):
            sentence = '새로운 주제로 대화를 진행해주세요.'
    return sentence, pre_state, state
Exemplo n.º 13
0
async def monday_dog(bot):
    name = getattr(bot.config, 'MONDAY_DOG_NAME', '월요일을 알리며 짖는 개')
    icon = getattr(
        bot.config,
        'MONDAY_DOG_ICON',
        'https://i.imgur.com/UtBQSLl.jpg',
    )
    monday_dog_say = functools.partial(
        bot.api.chat.postMessage,
        channel=C.general.get(),
        as_user=False,
        username=name,
        icon_url=icon,
    )
    today = now()
    holidays = None
    try:
        holidays = await get_holiday_names(today)
    except aiohttp.client_exceptions.ClientOSError:
        pass

    if holidays:
        says = [
            '월' * random.randint(3, 10)
            + '…'
            + ''.join(
                random.choice(['?', '!']) for x in range(random.randint(2, 4))
            ),
            '(하지만 {} 쉬는 날이었다고 한다)'.format(
                tossi.postfix(holidays[0], '(이)라'),
            ),
        ]
        for say in says:
            await monday_dog_say(text=say)
    else:
        says = [
            '월' * random.randint(60, 220),
            ''.join(
                '월' * random.randint(1, 6) + '!' * random.randint(1, 3)
                for x in range(40)
            ),
            '월요일' * random.randint(30, 70),
        ]
        random.shuffle(says)

        for say in says:
            await monday_dog_say(text=say)
Exemplo n.º 14
0
async def monday_dog(bot):
    name = getattr(bot.config, "MONDAY_DOG_NAME", "월요일을 알리며 짖는 개")
    icon = getattr(
        bot.config,
        "MONDAY_DOG_ICON",
        "https://i.imgur.com/UtBQSLl.jpg",
    )
    monday_dog_say = functools.partial(
        bot.api.chat.postMessage,
        channel=bot.config.CHANNEL["general"],
        as_user=False,
        username=name,
        icon_url=icon,
    )
    today = now()
    holidays = None
    try:
        holidays = await get_holiday_names(today)
    except aiohttp.client_exceptions.ClientOSError:
        pass

    if holidays:
        says = [
            "월" * random.randint(3, 10) + "…" + "".join(
                random.choice(["?", "!"])
                for x in range(random.randint(2, 4))),
            "(하지만 {} 쉬는 날이었다고 한다)".format(tossi.postfix(holidays[0],
                                                        "(이)라"), ),
        ]
        for say in says:
            await monday_dog_say(text=say)
    else:
        says = [
            "월" * random.randint(60, 220),
            "".join("월" * random.randint(1, 6) + "!" * random.randint(1, 3)
                    for x in range(40)),
            "월요일" * random.randint(30, 70),
        ]
        random.shuffle(says)

        for say in says:
            await monday_dog_say(text=say)
Exemplo n.º 15
0
def correct_tossi(sentence):
    hangul = re.compile('[ㄱ-ㅣ가-힣]+')
    tmp = sentence.split()
    symbols = ['(S)', '(P)', '(O)']
    for i in range(len(tmp)):
        item = tmp[i]
        for symbol in symbols:
            if (item.find(symbol) != -1):
                morps = item.split(symbol)
                word = morps[0]
                josa = morps[1]
                #print(word, josa)
                if (word != '') and (josa != '') and (hangul.match(word[-1]) !=
                                                      None):
                    #print('정상처리')
                    tmp[i] = tossi.postfix(word, josa)
                    #print(tmp[i])
                else:
                    #print('예외처리')
                    tmp[i] = word + josa
                    #print(tmp[i])
    output = ' '.join(tmp)
    return output
Exemplo n.º 16
0
async def body(bot, event: Message, sess, region: str, start: str, end: str):
    service_region, api_version = REGION_TABLE[region]

    try:
        db = sess.query(JSONCache).filter_by(
            name=f'subway-{service_region}-{api_version}').one()
    except NoResultFound:
        await bot.say(event.channel,
                      '아직 지하철 관련 명령어의 실행준비가 덜 되었어요. 잠시만 기다려주세요!')
        return

    data = db.body

    timestamp_url = 'http://map.naver.com/pubtrans/getSubwayTimestamp.nhn'
    async with client_session(headers=headers) as session:
        async with session.get(timestamp_url) as res:
            timestamp = ujson.loads(await res.text())

    find_start = None
    find_start_ratio = -1
    find_end = None
    find_end_ratio = -1
    for x in data[0]['realInfo']:
        start_ratio = fuzzy_korean_ratio(x['name'], start)
        end_ratio = fuzzy_korean_ratio(x['name'], end)
        if find_start_ratio < start_ratio:
            find_start = x
            find_start_ratio = start_ratio
        if find_end_ratio < end_ratio:
            find_end = x
            find_end_ratio = end_ratio

    if find_start_ratio < 40:
        await bot.say(event.channel, '출발역으로 지정하신 역 이름을 찾지 못하겠어요')
        return
    elif find_end_ratio < 40:
        await bot.say(event.channel, '도착역으로 지정하신 역 이름을 찾지 못하겠어요')
        return
    elif find_start and find_end:
        if find_start['id'] == find_end['id']:
            await bot.say(event.channel, '출발역과 도착역이 동일한 역이에요!')
            return

        ts = datetime.datetime.utcnow()
        url = 'http://map.naver.com/pubtrans/searchSubwayPath.nhn?{}'.format(
            urlencode({
                'serviceRegion': service_region,
                'fromStationID': find_start['id'],
                'toStationID': find_end['id'],
                'dayType': timestamp['result']['dateType'],
                'presetTime': '3',
                'departureDateTime': ts.strftime('%Y%m%d%H%M%S00'),
                'caller': 'naver_map',
                'output': 'json',
                'searchType': '1',
            }))

        async with client_session(headers=headers) as session:
            async with session.get(url) as res:
                result = ujson.loads(await res.text())

        text = ''

        subway_paths = result['result']['subwayPaths']

        if subway_paths:
            text += '{} {}에서 {} {} 가는 노선을 안내드릴게요!\n\n'.format(
                find_start['logicalLine']['name'],
                find_start['name'],
                find_end['logicalLine']['name'],
                tossi.postfix(find_end['name'], '(으)로'),
            )
            for subway_path in subway_paths:
                routes = subway_path['path']['routes']
                text += '\n'.join(
                    TEMPLATE.format(
                        x['stations'][0]['name'],
                        x['logicalLine']['name'],
                        x['logicalLine']['direction'],
                        '급행' if x['isExpress'] else '',
                        len(
                            list(
                                filter(lambda s: s['isNonstop'] == 0,
                                       x['stations']))) - 1,
                        x['stations'][-1]['name'],
                        ' (빠른환승 {}-{})'.format(
                            x['transfer']['exitTrainNumber'],
                            x['transfer']['exitDoorNumber'],
                        ) if 'transfer' in x else '',
                    ) for x in routes)
                text += '\n\n'

            summary = subway_path['summary']
            fare = list(
                filter(lambda f: f['paymentMethod'] == 1,
                       subway_path['fareInfos']))[0]['fare']
            text += ('소요시간: {:,}분 / 거리: {:,.2f}㎞'
                     ' / 요금(카드 기준): {:,}원').format(
                         math.ceil(
                             summary['overallTravelTimeInSecondOnAverage'] /
                             60),
                         summary['overallTravelDistanceInMeter'] / 1000,
                         fare,
                     )

            await bot.say(event.channel, text)
Exemplo n.º 17
0
async def body(bot, event: Message, region: str, start: str, end: str):
    service_region, api_version = REGION_TABLE[region]

    data = await bot.cache.get(f'SUBWAY_{service_region}_{api_version}')
    if data is None:
        await bot.say(event.channel,
                      '아직 지하철 관련 명령어의 실행준비가 덜 되었어요. 잠시만 기다려주세요!')
        return

    find_start = None
    find_start_ratio = -1
    find_end = None
    find_end_ratio = -1
    for x in data[0]['realInfo']:
        name = PARENTHESES.sub('', x['name'])
        start_ratio = ratio(name, start)
        end_ratio = ratio(name, end)
        if find_start_ratio < start_ratio:
            find_start = x
            find_start_ratio = start_ratio
        if find_end_ratio < end_ratio:
            find_end = x
            find_end_ratio = end_ratio

    if find_start_ratio < 40:
        await bot.say(event.channel, '출발역으로 지정하신 역 이름을 찾지 못하겠어요')
        return
    elif find_end_ratio < 40:
        await bot.say(event.channel, '도착역으로 지정하신 역 이름을 찾지 못하겠어요')
        return
    elif find_start and find_end:
        if find_start['id'] == find_end['id']:
            await bot.say(event.channel, '출발역과 도착역이 동일한 역이에요!')
            return

        url = 'https://map.naver.com/v5/api/subway/search?{}'.format(
            urlencode({
                'serviceRegion': service_region,
                'start': find_start['id'],
                'goal': find_end['id'],
                'departureTime': now().strftime('%Y-%m-%dT%H:%M:%S'),
            }))

        async with aiohttp.ClientSession(headers=headers) as session:
            async with session.get(url) as resp:
                result = await resp.json(loads=json.loads)

        text = ''

        paths = result['paths'][0]

        if paths:
            duration = paths['duration']
            fare = paths['fare']
            distance = paths['distance'] / 1000
            steps = paths['legs'][0]['steps']
            start_station_name = steps[0]['stations'][0]['displayName']
            start_station_line = steps[0]['routes'][0]['name']
            goal_station_name = steps[-1]['stations'][-1]['displayName']
            goal_station_line = steps[-1]['routes'][0]['name']

            text += '{} {}에서 {} {} 가는 노선을 안내드릴게요!\n\n'.format(
                start_station_line,
                start_station_name,
                goal_station_line,
                tossi.postfix(goal_station_name, '(으)로'),
            )
            for step in steps:
                if step['type'] != 'SUBWAY':
                    continue
                routes = step['routes']
                stations = step['stations']
                platform = routes[0]['platform']
                start_name = stations[0]['displayName']
                line = routes[0]['longName']
                direction = routes[0]['headsign']
                station_count = sum(1 for r in stations if r['stop']) - 1
                end_name = stations[-1]['displayName']
                doors = platform['doors']
                doors_list = ', '.join(doors) if doors else ''
                guide = ''
                if doors_list:
                    guide = f" ({platform['type']['desc']}: {doors_list})"
                text += TEMPLATE.format(
                    start_name,
                    line,
                    direction,
                    station_count,
                    end_name,
                    guide,
                )
                text += '\n'

            text += (f'\n소요시간: {duration:,}분 / 거리: {distance:,.2f}㎞'
                     f' / 요금(카드 기준): {fare:,}원')

            await bot.say(event.channel, text)
Exemplo n.º 18
0
Arquivo: subway.py Projeto: item4/yui
async def body(bot, event: Message, region: str, start: str, end: str):
    service_region, api_version = REGION_TABLE[region]

    data = await bot.cache.get(f"SUBWAY_{service_region}_{api_version}")
    if data is None:
        await bot.say(event.channel,
                      "아직 지하철 관련 명령어의 실행준비가 덜 되었어요. 잠시만 기다려주세요!")
        return

    find_start = None
    find_start_ratio = -1
    find_end = None
    find_end_ratio = -1
    for x in data[0]["realInfo"]:
        name = PARENTHESES.sub("", x["name"])
        start_ratio = ratio(name, start)
        end_ratio = ratio(name, end)
        if find_start_ratio < start_ratio:
            find_start = x
            find_start_ratio = start_ratio
        if find_end_ratio < end_ratio:
            find_end = x
            find_end_ratio = end_ratio

    if find_start_ratio < 40:
        await bot.say(event.channel, "출발역으로 지정하신 역 이름을 찾지 못하겠어요")
        return
    elif find_end_ratio < 40:
        await bot.say(event.channel, "도착역으로 지정하신 역 이름을 찾지 못하겠어요")
        return
    elif find_start and find_end:
        if find_start["id"] == find_end["id"]:
            await bot.say(event.channel, "출발역과 도착역이 동일한 역이에요!")
            return

        url = "https://map.naver.com/v5/api/subway/search?{}".format(
            urlencode({
                "serviceRegion": service_region,
                "start": find_start["id"],
                "goal": find_end["id"],
                "departureTime": now().strftime("%Y-%m-%dT%H:%M:%S"),
            }))

        async with aiohttp.ClientSession(headers=headers) as session:
            async with session.get(url) as resp:
                result = await resp.json(loads=json.loads)

        text = ""

        paths = result["paths"][0]

        if paths:
            duration = paths["duration"]
            fare = paths["fare"]
            distance = paths["distance"] / 1000
            steps = paths["legs"][0]["steps"]
            start_station_name = steps[0]["stations"][0]["displayName"]
            start_station_line = steps[0]["routes"][0]["name"]
            goal_station_name = steps[-1]["stations"][-1]["displayName"]
            goal_station_line = steps[-1]["routes"][0]["name"]

            text += "{} {}에서 {} {} 가는 노선을 안내드릴게요!\n\n".format(
                start_station_line,
                start_station_name,
                goal_station_line,
                tossi.postfix(goal_station_name, "(으)로"),
            )
            for step in steps:
                if step["type"] != "SUBWAY":
                    continue
                routes = step["routes"]
                stations = step["stations"]
                platform = routes[0]["platform"]
                start_name = stations[0]["displayName"]
                line = routes[0]["longName"]
                direction = routes[0]["headsign"]
                station_count = sum(1 for r in stations if r["stop"]) - 1
                end_name = stations[-1]["displayName"]
                doors = platform["doors"]
                doors_list = ", ".join(doors) if doors else ""
                guide = ""
                if doors_list:
                    guide = f" ({platform['type']['desc']}: {doors_list})"
                text += TEMPLATE.format(
                    start_name,
                    line,
                    direction,
                    station_count,
                    end_name,
                    guide,
                )
                text += "\n"

            text += (f"\n소요시간: {duration:,}분 / 거리: {distance:,.2f}㎞"
                     f" / 요금(카드 기준): {fare:,}원")

            await bot.say(event.channel, text)