Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import random
- import pandas as pd
- import asyncio
- import lyricsgenius as lg
- import pickle as pkl
- import wordcloud
- from aiogram import Bot, Dispatcher, types
- from aiogram.filters import Command, StateFilter
- from aiogram.types import Message, FSInputFile
- from aiogram.enums import ParseMode
- from aiogram import F
- from aiogram.fsm.context import FSMContext
- from aiogram.fsm.state import State, StatesGroup
- class UserContext(StatesGroup):
- is_guessed = State()
- is_true = State()
- id = 'Ve-cqnQoF0XkGOoV5Bd7ffVXIi9S38GbEwpwKCB98A-GrGPI1_qkn3EgCq5aaDKX'
- secret = 'zIXKeKxY2DEQ7_Vyn7uOF1okwGX4JUYRor-KRmHGxuZpZrMY_hKwWf6GxB2j-ub4itvJB7oZCjcrTnwg3vPZTA'
- access_token = 'F--CA-E5kwN2nCHZzGgxZ6pwFufhXsnwd4YiFLdWXsyJJOd6JT6MeXD2_vSuzOX_'
- bot = Bot(token='7130759964:AAF8l9aX9zeCvQLFAtN_yzVVo7Nu-Ws_Zzs')
- dp = Dispatcher()
- data = pd.read_csv('data.csv')
- genius = lg.Genius(access_token, skip_non_songs=True, remove_section_headers=True)
- async def check_answer(guess, actual_name, artist):
- async_search = asyncio.to_thread(genius.search_song, guess)
- guess_search = await async_search
- if guess_search is not None:
- if guess_search.title == actual_name:
- return True
- else:
- async_search = asyncio.to_thread(genius.search_song, guess, artist)
- guess_search = await async_search
- if guess_search is not None:
- return guess_search.title == actual_name
- else:
- return False
- return False
- with open ('vectorizer.pkl', 'rb') as f:
- vectorizer = pkl.load(f)
- def create_wordcloud(song):
- vecs = vectorizer.transform([song['lyrics']])
- dense = vecs.todense()
- lst1 = dense.tolist()
- df = pd.DataFrame(lst1, columns=vectorizer.get_feature_names_out())
- cloud = wordcloud.WordCloud(max_font_size=80, max_words=100, background_color="white").fit_words({word: freq for word, freq in zip(df.columns, df.loc[0])})
- return cloud
- def generate_trial(data):
- idx = random.randint(0, len(data) - 1)
- song = data.loc[idx]
- cloud = create_wordcloud(song)
- params = {'title': song['title'],
- 'artist': song['artist'],
- 'url': song['url'],
- 'index_in_data': idx
- }
- if song['album'] is not None:
- params['album'] = song['album']
- return cloud, params
- @dp.message(StateFilter(None), Command('play'))
- async def send_play(message: Message, state: FSMContext):
- cloud, params = generate_trial(data)
- img_path = 'img/{0}.png'.format(params['index_in_data'])
- if not os.path.exists(img_path):
- cloud.to_file(img_path)
- await message.answer_photo(
- FSInputFile(img_path),
- caption="Угадай название трека и напиши его"
- )
- await state.update_data(guessed_song=params['title'])
- await state.update_data(song_artist=params['artist'])
- await state.update_data(song_url=params['url'])
- await state.set_state(UserContext.is_guessed)
- ctx = await state.get_data()
- print(ctx)
- # TODO: маршрутизатор
- # async def hint(message: Message, state: FSMContext):
- # ctx = await state.get_data()
- # message.answer('Подсказка!\n Исполнитель: {0}'.format(ctx['song_artist']))
- @dp.message(UserContext.is_guessed) # F.text
- async def guess_song(message: Message, state: FSMContext):
- ctx = await state.get_data()
- if await check_answer(message.text, ctx['guessed_song'], ctx['song_artist']):
- await message.answer('Ты угадал! Это {0} - {1}\nПослушай: {2}'.format(ctx['guessed_song'], ctx['song_artist'], ctx['song_url']))
- else:
- await message.answer('Тебя постигла неудача, правильный ответ: {0} - {1}\nПослушай: {2}'.format(ctx['guessed_song'], ctx['song_artist'], ctx['song_url']))
- await state.clear()
- @dp.message(Command('start'))
- async def send_welcome(message: Message):
- welcome_text = (
- "<b>Тебя приветсвует Угадай Трек бот!</b>\n"
- "Тебе будут показаны наиболее часто встречающиеся в песне слова, а ты должен будешь отгадать название трека.\n\n"
- "<b>Команды:</b>\n"
- "/start - Начать взаимодействие с ботом.\n"
- "/play - Играть.\n"
- "/help - Показать список доступных команд.\n"
- "/stats - Посмотреть процент угаданных треков.\n\n"
- "Удачи тебе иии... Погнали!"
- )
- kb = [[types.KeyboardButton(text='Играть!')]]
- keyboard = types.ReplyKeyboardMarkup(
- keyboard=kb,
- resize_keyboard=True,
- one_time_keyboard=True
- )
- await message.reply(welcome_text, parse_mode=ParseMode.HTML, reply_markup=keyboard)
- async def help(message: Message):
- help_text = (
- "Потерялся? Сейчас помогу!\n\n"
- "<b>Команды:</b>\n"
- "/start - Начать взаимодействие с ботом.\n"
- "/play - Играть.\n"
- "/stats - Посмотреть процент угаданных треков."
- )
- await message.reply(help_text, parse_mode=ParseMode.HTML)
- dp.message.register(help, Command('help'))
- @dp.message(StateFilter(None), F.text)
- async def unknown_message(message: Message, state: FSMContext):
- if message.text == 'Играть!':
- await send_play(message, state)
- else:
- await help(message)
- async def main():
- await dp.start_polling(bot)
- if __name__ == "__main__":
- asyncio.run(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement