def add(pair): deck = client.find_deck_by_title(os.environ['TC_CURRENT_DECK']) if deck is None: deck = Deck(os.environ['TC_CURRENT_DECK']) deck = client.create_deck(deck) if not deck_has_duplicates(deck, pair[0]): deck.add_card(pair) client.update_deck(deck)
def test_cards_from_csv(self): test_deck = Deck('Test Deck') csv_data = StringIO('front,back\nfront word,back word') test_deck.add_cards_from_csv(csv_data) first_card = test_deck.cards[0] self.assertEqual('front word', first_card.front.concepts[0].fact.text) self.assertEqual('back word', first_card.back.concepts[0].fact.text)
def test_shareable_link(self): self.assertEqual('', Deck('Public deck').shareable_link) self.assertEqual('', Deck('Private deck', private=True).shareable_link) self.assertEqual( 'https://tiny.cards/decks/LEbBQJFU/test', Deck('Shareable deck', private=True, shareable=True, compact_id='LEbBQJFU', slug='test').shareable_link)
def _test_create_empty_deck(self): """Create a new empty deck.""" new_deck = Deck('Test Deck', self.tinycards.user_id) created_deck = self.tinycards.create_deck(new_deck) self.assertTrue(isinstance(created_deck, Deck)) num_decks = len(self.tinycards.get_decks()) self.assertEqual(1, num_decks)
class JsonConverterTest(unittest.TestCase): _TEST_USER_ID = 'UserID' _TEST_FACT = Fact(text='Fact: This is a test.') _TEST_CONCEPT = Concept(_TEST_FACT, _TEST_USER_ID) _TEST_SIDE = Side(_TEST_USER_ID, concepts=[_TEST_CONCEPT]) _TEST_CARD = Card(_TEST_SIDE, _TEST_SIDE) _TEST_DECK = Deck('Deckx', deck_id='DeckID', cards=[_TEST_CARD]) _TEST_FAVORITE = Favorite('Favorite', _TEST_DECK) def setUp(self): super(JsonConverterTest, self).setUp() def tearDown(self): super(JsonConverterTest, self).tearDown() def test_json_dict_to_user(self): json_input = { 'creationDate': 1547906391, 'email': '*****@*****.**', 'fullname': 'Test McTesterson', 'id': 1000, 'learningLanguage': 'fr', 'picture': 'www.example.com/avatar.jpg', 'subscribed': False, 'subscriberCount': 42, 'subscriptionCount': 84, 'uiLanguage': 'en', 'username': '******' } user_obj = json_converter.json_to_user(json_input) self.assertTrue(isinstance(user_obj, User)) self.assertEqual(user_obj.ui_language, 'en') def test_json_to_trendable_error(self): json_value_error_input = {'test': 0} json_key_error_input = {'data': {'blacklistedQuestionTypes': 'blah'}} with self.assertRaisesRegex(ValueError, r'.+ontains no \'data\' field'): json_converter.json_to_trendable(json_value_error_input) with self.assertRaises(KeyError): json_converter.json_to_trendable(json_key_error_input) def test_json_to_searchable_error(self): json_value_error_input = {'test': 0} json_key_error_input = {'data': {'id': 123}} with self.assertRaisesRegex(ValueError, r'.+ontains no \'data\' field'): json_converter.json_to_searchable(json_value_error_input) with self.assertRaises(KeyError): json_converter.json_to_searchable(json_key_error_input) def test_json_to_favorite(self): fav_json = json_converter.favorite_to_json(self._TEST_FAVORITE) self.assertEqual(str(json_converter.json_to_favorite(fav_json)), str(self._TEST_FAVORITE))
def _test_create_advanced_deck(self): """Create a new empty deck, with advanced options.""" deck = Deck( 'Test advanced Deck', self.tinycards.user_id, # Only test knowledge with back side of cards. blacklisted_side_indices=[0], # Only test knowledge with questions which do not require any # typing. blacklisted_question_types=NO_TYPING, # Stricter evaluation of answers. grading_modes=NO_TYPOS, # Text-to-speech for both front (English) and back (Japanese) # sides. tts_languages=['en', 'ja'], ) deck = self.tinycards.create_deck(deck) self._assert_advanced_options_are_set(deck) # Add a few tests cards and update the deck, in order to test PATCH # with an application/json content-type: deck.add_card(('one', 'いち')) deck.add_card(('two', 'に')) deck = self.tinycards.update_deck(deck) self._assert_advanced_options_are_set(deck) # Set a cover on the deck and update it, in order to test PATCH with a # multipart-form content-type: deck.cover = path_to('test_logo_blue.jpg') deck = self.tinycards.update_deck(deck) self._assert_advanced_options_are_set(deck) self._delete_deck(deck.id) # Clean up after ourselves.
def _test_create_deck_with_cover_from_file(self): """Create a new empty deck, with a cover using a local file.""" blue_cover_filepath = path_to('test_logo_blue.jpg') deck = Deck('Test Deck with cover', cover=blue_cover_filepath) deck = self.tinycards.create_deck(deck) self.assertTrue(isinstance(deck, Deck)) self._assert_cover_was_updated_with_file(blue_cover_filepath, deck.image_url) self._assert_cover_was_updated_with_file(blue_cover_filepath, deck.cover_image_url) # Add a few tests cards (to pass server-side validation) & update the deck's cover: deck.add_card(('front test 1', 'back test 1')) deck.add_card(('front test 2', 'back test 2')) red_cover_filepath = path_to('test_logo_red.png') deck.cover = red_cover_filepath deck = self.tinycards.update_deck(deck) self.assertTrue(isinstance(deck, Deck)) self._assert_cover_was_updated_with_file(red_cover_filepath, deck.image_url) self._assert_cover_was_updated_with_file(red_cover_filepath, deck.cover_image_url) self._delete_deck(deck.id) # Clean up after ourselves.
def _test_create_deck_with_cover_from_url(self): """Create a new empty deck, with a cover using an image available online.""" url = 'https://d9np3dj86nsu2.cloudfront.net/thumb/5bd5092200f7fe41e1d926158b5e8243/350_403' deck = Deck('Test Deck with cover', cover=url) deck = self.tinycards.create_deck(deck) self.assertTrue(isinstance(deck, Deck)) self._assert_cover_was_updated_with_url(url, deck.image_url) self._assert_cover_was_updated_with_url(url, deck.cover_image_url) # Add a few tests cards (to pass server-side validation) & update the deck's cover: deck.add_card(('front test 1', 'back test 1')) deck.add_card(('front test 2', 'back test 2')) url = 'https://d9np3dj86nsu2.cloudfront.net/thumb/8aaa075410df4c562bdd6c42659f02e2/350_403' deck.cover = url deck = self.tinycards.update_deck(deck) self.assertTrue(isinstance(deck, Deck)) self._assert_cover_was_updated_with_url(url, deck.image_url) self._assert_cover_was_updated_with_url(url, deck.cover_image_url) self._delete_deck(deck.id) # Clean up after ourselves.
def _test_create_shareable_deck(self): """Create a new empty, shareable deck.""" new_deck = Deck('Test shareable Deck', private=True, shareable=True) created_deck = self.tinycards.create_deck(new_deck) self.assertTrue(isinstance(created_deck, Deck)) self.assertNotEqual('', created_deck.shareable_link) resp = requests.get(created_deck.shareable_link) self.assertEqual(200, resp.status_code) self._delete_deck(created_deck.id) # Clean up after ourselves.
def json_to_deck(json_data): """Convert a JSON dict into a Deck object.""" deck = Deck( title=json_data['name'], description=json_data['description'], deck_id=json_data['id'], compact_id=json_data['compactId'], slug=json_data['slug'], cards=([json_to_card(c) for c in json_data['cards']] if 'cards' in json_data else []), private=bool(json_data['private']), shareable=bool(json_data['shareable']), blacklisted_side_indices=json_data['blacklistedSideIndices'], blacklisted_question_types=json_data['blacklistedQuestionTypes'], grading_modes=json_data['gradingModes'], tts_languages=json_data['ttsLanguages'], ) deck.image_url = json_data['imageUrl'] deck.cover_image_url = json_data['coverImageUrl'] return deck
def json_to_deck(json_data): """Convert a JSON dict into a Deck object.""" deck_obj = Deck( title=json_data['name'], description=json_data['description'], deck_id=json_data['id'], cover=json_data['imageUrl'], cards=([json_to_card(c) for c in json_data['cards']] if 'cards' in json_data else [])) return deck_obj
def _test_create_empty_deck(self): """Create a new empty deck.""" new_deck = Deck('Test Deck') created_deck = self.tinycards.create_deck(new_deck) self.assertTrue(isinstance(created_deck, Deck)) self.assertEqual('', created_deck.shareable_link) self.assertEqual(DEFAULT_COVER_URL, created_deck.image_url) self.assertIsNone(created_deck.cover_image_url) num_decks = len(self.tinycards.get_decks()) self.assertEqual(1, num_decks)
def generate_deck(id_of_first_word, target_lang, words_to_be_excluded): tinycards = Tinycards("frequencyl", "Uktuzugo_55") cards_to_be_added = [] db = sqlite3.connect("databases/words.db") cursor = db.cursor() origin_table = cursor.execute("SELECT * FROM words").fetchall() translation_table = cursor.execute(f"SELECT * FROM {target_lang}").fetchall() for i in range(id_of_first_word - 1, 6318): if origin_table[i][1] not in words_to_be_excluded: cards_to_be_added.append((origin_table[i][1], translation_table[i][2])) deck_no = 1 speech_lang_list = ["en", ""] if target_lang in tinycards_speech_langs: speech_lang_list[1] = tinycards_speech_langs[f"{target_lang}"] links = {} while len(cards_to_be_added) > 150: deck_name = f"Deck no: {deck_no}" deck = Deck(deck_name, private=True, shareable=True, tts_languages=speech_lang_list) created_deck = tinycards.create_deck(deck) for i in range(150): created_deck.add_card(cards_to_be_added[i]) del cards_to_be_added[:150] tinycards.update_deck(created_deck) links[deck_no] = created_deck.shareable_link deck_no += 1 deck_name = f"Deck no: {deck_no}" deck = Deck(deck_name, private=True, shareable=True, tts_languages=speech_lang_list) created_deck = tinycards.create_deck(deck) for i in range(len(cards_to_be_added)): created_deck.add_card(cards_to_be_added[i]) tinycards.update_deck(created_deck) links[deck_no] = created_deck.shareable_link return links
def csv_to_deck(csv_path): """Creates a Tinycards deck from a CSV file. The CSV file is expected to have two columns named 'front' and 'back'. """ # Create new deck. tinycards = Tinycards(user_identifier, user_password) deck = Deck('French Words') deck = tinycards.create_deck(deck) # Extract data from CSV file. word_pairs = [] with open(csv_path, 'r') as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: current_word_pair = (row['front'], row['back']) word_pairs.append(current_word_pair) # Populate deck with cards from CSV data. for pair in word_pairs: deck.add_card(pair) # Save changes to Tinycards. tinycards.update_deck(deck)
def test_cards_to_csv(self): test_deck = Deck('Test Deck') test_deck.add_card(('front word', 'back word')) file_buffer = StringIO() test_deck.save_cards_to_csv(file_buffer) # Excel-generated CSV files use Windows-style line terminator. line_terminator = '\r\n' expected_output = 'front,back' + line_terminator \ + 'front word,back word' + line_terminator self.assertEqual(expected_output, file_buffer.getvalue())
from tinycards import Tinycards from tinycards.model import Deck from PyDictionary import PyDictionary import yaml, json, sys import config dictionary = PyDictionary() tinycards = Tinycards(config.TINY_CARDS_CREDENTIALS['email'], config.TINY_CARDS_CREDENTIALS['password']) deck = Deck('12 Rules Of Life') deck = tinycards.create_deck(deck) fh = open('words.txt') for word in fh: meaning = str(dictionary.meaning(word)) translation_table = dict.fromkeys(map(ord, '{}[]\''), None) meaning = meaning.translate(translation_table) print(meaning) deck.add_card((word, meaning)) fh.close() tinycards.update_deck(deck)
def csv_to_deck(csv_path, deck_base_name): """ Creates a Tinycards deck from a CSV file. The CSV file is expected to have two columns """ # Extract data from CSV file. word_pairs = [] pairs_amount = 0 with open(csv_path, 'r') as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: word_pairs.append((row[1], row[0])) pairs_amount = len(word_pairs) if not DEBUG: client_tinycards = Tinycards(user_identifier, user_password) if pairs_amount == 0: print('No word pairs were found in CSV') sys.exit() decks = math.ceil(pairs_amount / DECK_CARDS_PER_UNIT) for index, deck in enumerate(range(decks)): # Get deck by name. If doesn't exist - create new subdeck_name = f'{deck_base_name} - {index}' if not DEBUG: deck = client_tinycards.find_deck_by_title(subdeck_name) if not deck: deck = Deck(subdeck_name) deck = client_tinycards.create_deck(deck) elif DECK_REMOVE_EXISTING: deck.cards = [] # Customize deck deck.cover = DECK_COVER_PATH deck.description = ( f'{DECK_DESC}. ' f'Last updated on {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}') deck.tts_languages = DECK_TTS_LANGUAGES # Populate deck with cards from CSV data for pair in range(DECK_CARDS_PER_UNIT): try: deck.add_card(word_pairs.pop()) except IndexError: pass # Save changes to Tinycards if not DEBUG: client_tinycards.update_deck(deck) print(f'Successfully created "{subdeck_name}"') if not DEBUG: print( f'Successfully created {decks} decks from {pairs_amount} word pairs' ) else: print('Dry run. No Tinycard decks were created') print( f'{decks} decks from {pairs_amount} word pairs are ready to be uploaded' )
def _create_deck(deck_name: str): client = Tinycards(silent=True) client.create_deck(Deck(deck_name))