kahoot-to-anki 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Simon Hardmeier
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice (including the next paragraph) shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: kahoot-to-anki
3
+ Version: 1.0.0
4
+ Summary: CLI tool to convert Kahoot quiz reports into Anki flashcards
5
+ Author: Simon Hardmeier
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: genanki
11
+ Requires-Dist: pandas
12
+ Requires-Dist: openpyxl
13
+ Dynamic: license-file
14
+
15
+ # kahoot-to-anki
16
+ > python cli program to convert Kahoot quiz results to Anki flashcards
@@ -0,0 +1,2 @@
1
+ # kahoot-to-anki
2
+ > python cli program to convert Kahoot quiz results to Anki flashcards
@@ -0,0 +1 @@
1
+ """CLI tool to convert Kahoot quiz reports into Anki flashcards."""
@@ -0,0 +1,254 @@
1
+ # Standard library imports
2
+ import argparse
3
+ import logging
4
+ import os
5
+ import glob
6
+
7
+ # Third-party library imports
8
+ import genanki
9
+ import pandas as pd
10
+
11
+ # Configure logging settings
12
+ logging.basicConfig(level=logging.INFO)
13
+
14
+ # Constants
15
+ DEFAULT_INPUT_DIRECTORY = "./data"
16
+ DEFAULT_OUTPUT_DIRECTORY = "./"
17
+ DEFAULT_DECK_TITLE = "Kahoot"
18
+ KAHOOT_EXCEL_SHEET_NAME_RAW_DATA = "RawReportData Data"
19
+
20
+
21
+ def main():
22
+ # Check command line arguments
23
+ inp, out, csv, title = get_commandline_arguments()
24
+
25
+ validation(inp, out)
26
+
27
+ df = get_questions(inp)
28
+
29
+ if csv:
30
+ df.to_csv(
31
+ os.path.join(out, "kahoot.csv"),
32
+ sep=";",
33
+ index=False,
34
+ encoding="utf-8-sig",
35
+ )
36
+
37
+ make_anki(df, out, title)
38
+
39
+
40
+ def get_commandline_arguments() -> tuple:
41
+ """
42
+ Parses the command line arguments and returns a tuple with the input path, output path, CSV option, and deck title.
43
+
44
+ :return: A tuple with the input path, the output path, the csv and the title of the anki deck
45
+ :rtype: tuple
46
+ """
47
+ parser = argparse.ArgumentParser(description="Create Anki Deck from Kahoot answer")
48
+ parser.add_argument(
49
+ "-i",
50
+ "--inp",
51
+ default=DEFAULT_INPUT_DIRECTORY,
52
+ help=f"Path to the directory containing input Excel files or a single input Excel file. If a directory is "
53
+ f"provided, all Excel files in the directory will be processed. Default: {DEFAULT_INPUT_DIRECTORY}",
54
+ type=str,
55
+ )
56
+ parser.add_argument(
57
+ "-o",
58
+ "--out",
59
+ default=DEFAULT_OUTPUT_DIRECTORY,
60
+ help="Path to the directory where the Anki flashcards package will be generated. "
61
+ "If not specified, the package will be created in the current working directory.",
62
+ type=str,
63
+ )
64
+ parser.add_argument(
65
+ "--csv",
66
+ action="store_true",
67
+ help="Generate a CSV file with the question data.",
68
+ )
69
+ parser.add_argument(
70
+ "-t",
71
+ "--title",
72
+ default=DEFAULT_DECK_TITLE,
73
+ help="Name of the Anki deck to be created. "
74
+ f"If not specified, the default deck name '{DEFAULT_DECK_TITLE}' will be used.",
75
+ type=str,
76
+ )
77
+ args = parser.parse_args()
78
+
79
+ # return absolute paths
80
+ return os.path.abspath(args.inp), os.path.abspath(args.out), args.csv, args.title
81
+
82
+
83
+ def validation(input_directory: str, output_directory: str) -> None:
84
+ """
85
+ This function validates the command line arguments, checking if the input path is a valid Excel file or directory
86
+ and if the output path is a valid directory.
87
+ The input path needs to be an Excel file or a directory that contains Excel files.
88
+ The output path needs to be a directory and not a file.
89
+
90
+ :param input_directory: The path of the input Excel or directory
91
+ :param output_directory: The path of the output directory
92
+ :return: None
93
+ :rtype: None
94
+ """
95
+ # Check if input is a file
96
+ if not os.path.exists(input_directory):
97
+ logging.error(f"Input directory {input_directory} does not exist!")
98
+ raise FileNotFoundError(f"Input directory {input_directory} does not exist!")
99
+ elif (
100
+ os.path.isfile(input_directory)
101
+ and os.path.splitext(input_directory)[-1] != ".xlsx"
102
+ ):
103
+ logging.error("Input file is not an excel file!")
104
+ raise ValueError("Input file is not an excel file!")
105
+ elif os.path.isdir(input_directory):
106
+ input_excels = os.path.join(input_directory, "*.xlsx")
107
+ if not glob.glob(input_excels):
108
+ logging.error("Input directory does not contain any excel files!")
109
+ raise FileNotFoundError("Input directory does not contain any excel files!")
110
+
111
+ # Check output directory and create when not existing
112
+ if not os.path.isdir(output_directory):
113
+ logging.error("Output is not a directory!")
114
+ raise ValueError("Output is not a directory!")
115
+ if not os.path.exists(output_directory):
116
+ try:
117
+ os.makedirs(output_directory)
118
+ except OSError as e:
119
+ logging.error(
120
+ "Failed to create output directory '%s': %s", output_directory, str(e)
121
+ )
122
+ raise
123
+
124
+
125
+ def get_questions(input_directory: str) -> pd.DataFrame:
126
+ """
127
+ Extracts all the kahoot questions out of the Excel file(s)
128
+
129
+ :param input_directory: The path to the input directory or Excel file
130
+ :return: All the questions with the possible answers and the solution
131
+ :rtype: pd.DataFrame
132
+ """
133
+
134
+ def get_excels(path):
135
+ """
136
+ Returns a list with all Excels in the given path
137
+ :param path: the path to an Excel file or a directory with Excel files
138
+ :return: a list with all excels
139
+ """
140
+ if os.path.isfile(path):
141
+ yield path
142
+ else:
143
+ yield from glob.glob(os.path.join(input_directory, "*.xlsx"))
144
+ return [f for f in glob.glob(os.path.join(path, "*.xlsx"))]
145
+
146
+ def get_excel_data(excel_file: str) -> pd.DataFrame:
147
+ """
148
+ Returns a pd.DataFrame with the kahoot raw data
149
+ :param excel_file: an Excel file with Kahoot raw data
150
+ :return: a DataFrame with the data
151
+ """
152
+ try:
153
+ # read file
154
+ return pd.read_excel(
155
+ excel_file, sheet_name=KAHOOT_EXCEL_SHEET_NAME_RAW_DATA
156
+ )
157
+ except ValueError:
158
+ logging.warning(
159
+ "Skipping file '%s' as it is not a valid Excel file.", excel_file
160
+ )
161
+ return None
162
+ except Exception as e:
163
+ logging.error("Failed to read file '%s': %s", excel_file, str(e))
164
+ return None
165
+
166
+ def df_processing(data: pd.DataFrame) -> pd.DataFrame:
167
+ """
168
+ Processes the Kahoot question data.
169
+ :param data: DataFrame with Kahoot question data
170
+ :return: Processed DataFrame
171
+ """
172
+ # delete duplicated questions
173
+ data = data.drop_duplicates(subset=["Question Number"])
174
+
175
+ data = data.fillna("")
176
+
177
+ data["Possible Answers"] = data[
178
+ ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5", "Answer 6"]
179
+ ].agg("<br>".join, axis=1)
180
+
181
+ # keep only needed columns
182
+ data = data[["Question", "Possible Answers", "Correct Answers"]]
183
+
184
+ return data
185
+
186
+ out = pd.DataFrame(columns=["Question", "Possible Answers", "Correct Answers"])
187
+
188
+ questions_cnt = 0
189
+ files_cnt = 0
190
+
191
+ for file in get_excels(input_directory):
192
+ df = get_excel_data(file)
193
+ if df is None:
194
+ continue
195
+ files_cnt += 1
196
+
197
+ df = df_processing(df)
198
+
199
+ # add to out dataframe
200
+ out = pd.concat([out, df], axis=0, ignore_index=True)
201
+
202
+ questions_cnt += len(df)
203
+
204
+ logging.info("Read input files: %d", files_cnt)
205
+ logging.info("Read questions: %d", questions_cnt)
206
+ out = out.drop_duplicates(subset=["Question"])
207
+ return out
208
+
209
+
210
+ def make_anki(df: pd.DataFrame, out: str, title: str) -> None:
211
+ """
212
+ Creates an Anki deck from the given Kahoot questions
213
+
214
+ :param df: The kahoot questions in a pd.DataFrame
215
+ :param out: The path to the output directory
216
+ :param title: The title of the Anki deck
217
+ :return: None
218
+ """
219
+ my_model = genanki.Model(
220
+ 1607392319,
221
+ "Simple Model",
222
+ fields=[
223
+ {"name": "Question"},
224
+ {"name": "Answer"},
225
+ {"name": "selects"},
226
+ ],
227
+ templates=[
228
+ {
229
+ "name": "Card 1",
230
+ "qfmt": "{{Question}}<br><br>{{selects}}",
231
+ "afmt": '{{FrontSide}}<hr id="answer">{{Answer}}',
232
+ },
233
+ ],
234
+ )
235
+
236
+ my_deck = genanki.Deck(2059400110, title)
237
+
238
+ for index, row in df.iterrows():
239
+ my_note = genanki.Note(
240
+ model=my_model,
241
+ fields=[row["Question"], row["Correct Answers"], row["Possible Answers"]],
242
+ )
243
+ my_deck.add_note(my_note)
244
+
245
+ try:
246
+ genanki.Package(my_deck).write_to_file(
247
+ os.path.join(out, "anki.apkg"),
248
+ )
249
+ except Exception as e:
250
+ logging.error("Failed to write Anki package file: %s", str(e))
251
+
252
+
253
+ if __name__ == "__main__":
254
+ main()
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: kahoot-to-anki
3
+ Version: 1.0.0
4
+ Summary: CLI tool to convert Kahoot quiz reports into Anki flashcards
5
+ Author: Simon Hardmeier
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: genanki
11
+ Requires-Dist: pandas
12
+ Requires-Dist: openpyxl
13
+ Dynamic: license-file
14
+
15
+ # kahoot-to-anki
16
+ > python cli program to convert Kahoot quiz results to Anki flashcards
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ kahoot_to_anki/__init__.py
5
+ kahoot_to_anki/converter.py
6
+ kahoot_to_anki.egg-info/PKG-INFO
7
+ kahoot_to_anki.egg-info/SOURCES.txt
8
+ kahoot_to_anki.egg-info/dependency_links.txt
9
+ kahoot_to_anki.egg-info/entry_points.txt
10
+ kahoot_to_anki.egg-info/requires.txt
11
+ kahoot_to_anki.egg-info/top_level.txt
12
+ tests/__init__.py
13
+ tests/test_project.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ kahoot-to-anki = kahoot_to_anki.converter:main
@@ -0,0 +1,3 @@
1
+ genanki
2
+ pandas
3
+ openpyxl
@@ -0,0 +1,3 @@
1
+ dist
2
+ kahoot_to_anki
3
+ tests
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kahoot-to-anki"
7
+ version = "1.0.0"
8
+ description = "CLI tool to convert Kahoot quiz reports into Anki flashcards"
9
+ authors = [{ name = "Simon Hardmeier" }]
10
+ license = "MIT"
11
+ readme = "README.md"
12
+ requires-python = ">=3.8"
13
+ dependencies = [
14
+ "genanki",
15
+ "pandas",
16
+ "openpyxl"
17
+ ]
18
+
19
+ [project.scripts]
20
+ kahoot-to-anki = "kahoot_to_anki.converter:main"
21
+
22
+ [tool.setuptools.packages.find]
23
+ where = ["."]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,226 @@
1
+ # Standard library imports
2
+ import shutil
3
+ import os
4
+
5
+ # Third-party library imports
6
+ import numpy as np
7
+ import pandas as pd
8
+ import pytest
9
+
10
+ # Local application/library imports
11
+ import converter
12
+
13
+
14
+ def generate_test_data():
15
+ # Create multiple lists
16
+ question_number = [
17
+ "Question 1",
18
+ "Question 1",
19
+ "Question 1",
20
+ "Question 2",
21
+ "Question 2",
22
+ "Question 2",
23
+ ]
24
+ question = [
25
+ "How is a code block indicated in Python?",
26
+ "How is a code block indicated in Python?",
27
+ "How is a code block indicated in Python?",
28
+ "Which of the following concepts is not a part of Python?",
29
+ "Which of the following concepts is not a part of Python?",
30
+ "Which of the following concepts is not a part of Python?",
31
+ ]
32
+ answer_1 = [
33
+ "Brackets",
34
+ "Brackets",
35
+ "Brackets",
36
+ "Pointers",
37
+ "Pointers",
38
+ "Pointers",
39
+ ]
40
+ answer_2 = [
41
+ "Indentation",
42
+ "Indentation",
43
+ "Indentation",
44
+ "Loops",
45
+ "Loops",
46
+ "Loops",
47
+ ]
48
+ answer_3 = [
49
+ "Key",
50
+ "Key",
51
+ "Key",
52
+ "Dynamic Typing",
53
+ "Dynamic Typing",
54
+ "Dynamic Typing",
55
+ ]
56
+ answer_4 = [
57
+ np.nan,
58
+ np.nan,
59
+ np.nan,
60
+ np.nan,
61
+ np.nan,
62
+ np.nan,
63
+ ]
64
+ answer_5 = [
65
+ np.nan,
66
+ np.nan,
67
+ np.nan,
68
+ np.nan,
69
+ np.nan,
70
+ np.nan,
71
+ ]
72
+ answer_6 = [
73
+ np.nan,
74
+ np.nan,
75
+ np.nan,
76
+ np.nan,
77
+ np.nan,
78
+ np.nan,
79
+ ]
80
+ correct_answers = [
81
+ "Indentation",
82
+ "Indentation",
83
+ "Indentation",
84
+ "Pointers",
85
+ "Pointers",
86
+ "Pointers",
87
+ ]
88
+ time_to_answer = [
89
+ "10",
90
+ "10",
91
+ "10",
92
+ "10",
93
+ "10",
94
+ "10",
95
+ ]
96
+ player = [
97
+ "Harry",
98
+ "Hermione ",
99
+ "Ron",
100
+ "Harry",
101
+ "Hermione ",
102
+ "Ron",
103
+ ]
104
+ answer = [
105
+ "Indentation",
106
+ "Indentation",
107
+ "Brackets",
108
+ "Dynamic Typing",
109
+ "Pointers",
110
+ "Dynamic Typing",
111
+ ]
112
+ correct_incorrect = [
113
+ True,
114
+ True,
115
+ False,
116
+ False,
117
+ True,
118
+ False,
119
+ ]
120
+ columns = [
121
+ "Question Number",
122
+ "Question",
123
+ "Answer 1",
124
+ "Answer 2",
125
+ "Answer 3",
126
+ "Answer 4",
127
+ "Answer 5",
128
+ "Answer 6",
129
+ "Correct Answers",
130
+ "Time Allotted to Answer (seconds)",
131
+ "Player",
132
+ "Answer",
133
+ "Correct / Incorrect",
134
+ ]
135
+
136
+ # Create DataFrame from multiple lists
137
+ df = pd.DataFrame(
138
+ list(
139
+ zip(
140
+ question_number,
141
+ question,
142
+ answer_1,
143
+ answer_2,
144
+ answer_3,
145
+ answer_4,
146
+ answer_5,
147
+ answer_6,
148
+ correct_answers,
149
+ time_to_answer,
150
+ player,
151
+ answer,
152
+ correct_incorrect,
153
+ )
154
+ ),
155
+ columns=columns,
156
+ )
157
+ return df
158
+
159
+
160
+ @pytest.fixture(scope="session", autouse=True)
161
+ def setup_and_teardown():
162
+ test_data_dir = "test_data"
163
+ test_data_dir_empty = "test_data_empty"
164
+ input_file_name = "input.xlsx"
165
+ empty_file_name = "empty.xlsx"
166
+
167
+ input_file_path = os.path.join(test_data_dir, input_file_name)
168
+ empty_file_path = os.path.join(test_data_dir, empty_file_name)
169
+
170
+ df = generate_test_data()
171
+
172
+ os.makedirs(test_data_dir, exist_ok=True)
173
+ df.to_excel(input_file_path, sheet_name="RawReportData Data", index=False)
174
+
175
+ os.makedirs(test_data_dir_empty, exist_ok=True)
176
+
177
+ # create empty excel
178
+ df_empty = pd.DataFrame()
179
+ df_empty.to_excel(empty_file_path)
180
+
181
+ # Yield to allow the test to run
182
+ yield
183
+
184
+ # Teardown: Cleanup the created files
185
+ if os.path.exists(test_data_dir):
186
+ shutil.rmtree(test_data_dir)
187
+ if os.path.exists(test_data_dir_empty):
188
+ shutil.rmtree(test_data_dir_empty)
189
+
190
+
191
+ def test_validation_wrong_output():
192
+ with pytest.raises(ValueError):
193
+ assert converter.validation("test_data/", "test_data/input.xlsx")
194
+
195
+
196
+ def test_validation_wrong_input_file():
197
+ with pytest.raises(FileNotFoundError):
198
+ assert converter.validation("test_data/in.txt", "test_data/")
199
+
200
+
201
+ def test_validation_empty_input_directory():
202
+ with pytest.raises(FileNotFoundError):
203
+ assert converter.validation("test_data_empty/", "./output")
204
+
205
+
206
+ def test_validation():
207
+ assert converter.validation('./test_data/', "./test_data/") is None
208
+
209
+
210
+ def test_get_questions_wrong_excel():
211
+ assert converter.get_questions("test_data/empty.xlsx").shape[0] == 0
212
+
213
+
214
+ def test_get_questions_file():
215
+ assert converter.get_questions("test_data/input.xlsx").shape[0] == 2
216
+
217
+
218
+ def test_get_questions_directory():
219
+ assert converter.get_questions("test_data/").shape[0] == 2
220
+
221
+
222
+ def test_make_anki():
223
+ df = converter.get_questions("test_data/input.xlsx")
224
+ converter.make_anki(df, "test_data/", "test")
225
+ # Check if output file exists
226
+ assert os.path.exists("test_data/anki.apkg") is True