kahoot-to-anki 1.0.0__py3-none-any.whl → 1.2.0__py3-none-any.whl

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.
@@ -1 +1 @@
1
- """CLI tool to convert Kahoot quiz reports into Anki flashcards."""
1
+ __version__ = "1.2.0"
kahoot_to_anki/cli.py ADDED
@@ -0,0 +1,127 @@
1
+ # Standard library imports
2
+ import argparse
3
+ from dataclasses import dataclass
4
+ import logging
5
+ import os
6
+ import glob
7
+
8
+ from kahoot_to_anki import __version__
9
+
10
+
11
+ # Constants
12
+ DEFAULT_INPUT_DIRECTORY = "./data"
13
+ DEFAULT_OUTPUT_DIRECTORY = "./"
14
+ DEFAULT_DECK_TITLE = "Kahoot"
15
+ KAHOOT_EXCEL_SHEET_NAME_RAW_DATA = "RawReportData Data"
16
+
17
+ # Dataclass to hold CLI arguments
18
+ @dataclass
19
+ class CLIArgs:
20
+ input_path: str
21
+ output_path: str
22
+ sheet: str
23
+ export_csv: bool
24
+ deck_title: str
25
+
26
+
27
+ def get_commandline_arguments() -> CLIArgs:
28
+ """
29
+ Parses the command line arguments and returns a CLIArgs dataclass instance.
30
+
31
+ :return: A CLIArgs dataclass instance
32
+ :rtype: CLIArgs
33
+ """
34
+ parser = argparse.ArgumentParser(description="Create Anki Deck from Kahoot answer")
35
+ parser.add_argument(
36
+ "-i",
37
+ "--inp",
38
+ default=DEFAULT_INPUT_DIRECTORY,
39
+ help=f"Path to the directory containing input Excel files or a single input Excel file. If a directory is "
40
+ f"provided, all Excel files in the directory will be processed. Default: {DEFAULT_INPUT_DIRECTORY}",
41
+ type=str,
42
+ )
43
+ parser.add_argument(
44
+ "-o",
45
+ "--out",
46
+ default=DEFAULT_OUTPUT_DIRECTORY,
47
+ help="Path to the directory where the Anki flashcards package will be generated. "
48
+ "If not specified, the package will be created in the current working directory.",
49
+ type=str,
50
+ )
51
+ parser.add_argument(
52
+ "--sheet",
53
+ default=KAHOOT_EXCEL_SHEET_NAME_RAW_DATA,
54
+ help=f"The Excel Sheet Name with the Kahoot Raw Data. Default {KAHOOT_EXCEL_SHEET_NAME_RAW_DATA}",
55
+ type=str,
56
+ )
57
+ parser.add_argument(
58
+ "--csv",
59
+ action=argparse.BooleanOptionalAction,
60
+ default=False,
61
+ help="Enable or disable CSV export of question data (default: disabled).",
62
+ )
63
+ parser.add_argument(
64
+ "-t",
65
+ "--title",
66
+ default=DEFAULT_DECK_TITLE,
67
+ help="Name of the Anki deck to be created. "
68
+ f"If not specified, the default deck name '{DEFAULT_DECK_TITLE}' will be used.",
69
+ type=str,
70
+ )
71
+ parser.add_argument(
72
+ "--version",
73
+ action="version",
74
+ version=f"%(prog)s {__version__}",
75
+ help="Show the version number and exit.",
76
+ )
77
+ args = parser.parse_args()
78
+
79
+ return CLIArgs(
80
+ input_path=os.path.abspath(args.inp),
81
+ output_path=os.path.abspath(args.out),
82
+ sheet=args.sheet,
83
+ export_csv=args.csv,
84
+ deck_title=args.title
85
+ )
86
+
87
+
88
+ def validation(input_directory: str, output_directory: str) -> None:
89
+ """
90
+ This function validates the command line arguments, checking if the input path is a valid Excel file or directory
91
+ and if the output path is a valid directory.
92
+ The input path needs to be an Excel file or a directory that contains Excel files.
93
+ The output path needs to be a directory and not a file.
94
+
95
+ :param input_directory: The path of the input Excel or directory
96
+ :param output_directory: The path of the output directory
97
+ :return: None
98
+ :rtype: None
99
+ """
100
+ # Check if input is a file
101
+ if not os.path.exists(input_directory):
102
+ logging.error(f"Input directory {input_directory} does not exist!")
103
+ raise FileNotFoundError(f"Input directory {input_directory} does not exist!")
104
+ elif (
105
+ os.path.isfile(input_directory)
106
+ and os.path.splitext(input_directory)[-1] != ".xlsx"
107
+ ):
108
+ logging.error("Input file is not an excel file!")
109
+ raise ValueError("Input file is not an excel file!")
110
+ elif os.path.isdir(input_directory):
111
+ input_excels = os.path.join(input_directory, "*.xlsx")
112
+ if not glob.glob(input_excels):
113
+ logging.error("Input directory does not contain any excel files!")
114
+ raise FileNotFoundError("Input directory does not contain any excel files!")
115
+
116
+ # Check output directory and create when not existing
117
+ if not os.path.isdir(output_directory):
118
+ logging.error("Output is not a directory!")
119
+ raise ValueError("Output is not a directory!")
120
+ if not os.path.exists(output_directory):
121
+ try:
122
+ os.makedirs(output_directory)
123
+ except OSError as e:
124
+ logging.error(
125
+ "Failed to create output directory '%s': %s", output_directory, str(e)
126
+ )
127
+ raise
kahoot_to_anki/main.py ADDED
@@ -0,0 +1,40 @@
1
+ import os
2
+ import logging
3
+ import sys
4
+
5
+ from kahoot_to_anki.cli import get_commandline_arguments, validation
6
+ from kahoot_to_anki.processing import get_questions, make_anki
7
+
8
+ # Configure logging settings
9
+ logging.basicConfig(level=logging.INFO)
10
+
11
+
12
+ def main() -> None:
13
+ # Check command line arguments
14
+ args = get_commandline_arguments()
15
+
16
+ validation(args.input_path, args.output_path)
17
+
18
+ df = get_questions(input_directory=args.input_path, sheet_name=args.sheet)
19
+
20
+ if df.empty:
21
+ logging.warning("No Kahoot questions found to process. Exiting.")
22
+ sys.exit(0)
23
+
24
+ if args.export_csv:
25
+ df.to_csv(
26
+ os.path.join(args.output_path, "kahoot.csv"),
27
+ sep=";",
28
+ index=False,
29
+ encoding="utf-8-sig",
30
+ )
31
+
32
+ make_anki(df, args.output_path, args.deck_title)
33
+
34
+
35
+ if __name__ == "__main__":
36
+ main()
37
+
38
+
39
+
40
+
@@ -0,0 +1,143 @@
1
+ # Standard library imports
2
+ import logging
3
+ import os
4
+ import glob
5
+ from typing import Iterator, Optional
6
+
7
+ # Third-party library imports
8
+ import genanki
9
+ import pandas as pd
10
+
11
+
12
+ def get_questions(input_directory: str, sheet_name: str) -> pd.DataFrame:
13
+ """
14
+ Extracts all the kahoot questions out of the Excel file(s)
15
+
16
+ :param input_directory: The path to the input directory or Excel file
17
+ :param sheet_name: The Excel sheet name with the Kahoot Answers
18
+ :return: All the questions with the possible answers and the solution
19
+ :rtype: pd.DataFrame
20
+ """
21
+
22
+ out = pd.DataFrame(columns=["Question", "Possible Answers", "Correct Answers"])
23
+
24
+ questions_cnt = 0
25
+ files_cnt = 0
26
+
27
+ for file in get_excels(input_directory):
28
+ df = get_excel_data(excel_file=file, sheet_name=sheet_name)
29
+ if df is None:
30
+ continue
31
+ files_cnt += 1
32
+
33
+ df = df_processing(df)
34
+
35
+ # add to out dataframe
36
+ out = pd.concat([out, df], axis=0, ignore_index=True)
37
+
38
+ questions_cnt += len(df)
39
+
40
+ logging.info("Read input files: %d", files_cnt)
41
+ logging.info("Read questions: %d", questions_cnt)
42
+ out = out.drop_duplicates(subset=["Question"])
43
+ return out
44
+
45
+
46
+ def get_excels(path: str) -> Iterator[str]:
47
+ """
48
+ Returns a generator with all Excel files in the given path.
49
+ :param path: the path to an Excel file or a directory with Excel files
50
+ :return: a generator of Excel file paths
51
+ """
52
+ if os.path.isfile(path):
53
+ yield path
54
+ else:
55
+ yield from glob.glob(os.path.join(path, "*.xlsx"))
56
+
57
+
58
+ def get_excel_data(excel_file: str, sheet_name:str) -> Optional[pd.DataFrame]:
59
+ """
60
+ Returns a pd.DataFrame with the kahoot raw data
61
+ :param excel_file: an Excel file with Kahoot raw data
62
+ :param sheet_name: the Excel sheet name with the Kahoot answers
63
+ :return: a DataFrame with the data
64
+ """
65
+ try:
66
+ # read file
67
+ return pd.read_excel(
68
+ excel_file, sheet_name=sheet_name
69
+ )
70
+ except ValueError:
71
+ logging.warning(
72
+ "Skipping file '%s' as it is not a valid Excel file.", excel_file
73
+ )
74
+ return None
75
+ except Exception as e:
76
+ logging.error("Failed to read file '%s': %s", excel_file, str(e))
77
+ return None
78
+
79
+
80
+ def df_processing(data: pd.DataFrame) -> pd.DataFrame:
81
+ """
82
+ Processes the Kahoot question data.
83
+ :param data: DataFrame with Kahoot question data
84
+ :return: Processed DataFrame
85
+ """
86
+ if data.empty:
87
+ return pd.DataFrame(columns=["Question", "Possible Answers", "Correct Answers"])
88
+
89
+ # delete duplicated questions
90
+ data = data.drop_duplicates(subset=["Question Number"])
91
+ data = data.fillna("")
92
+
93
+ data["Possible Answers"] = data[
94
+ ["Answer 1", "Answer 2", "Answer 3", "Answer 4", "Answer 5", "Answer 6"]
95
+ ].astype(str).agg("<br>".join, axis=1)
96
+
97
+ # keep only needed columns
98
+ data = data[["Question", "Possible Answers", "Correct Answers"]]
99
+
100
+ return data
101
+
102
+
103
+ def make_anki(df: pd.DataFrame, out: str, title: str) -> None:
104
+ """
105
+ Creates an Anki deck from the given Kahoot questions
106
+
107
+ :param df: The kahoot questions in a pd.DataFrame
108
+ :param out: The path to the output directory
109
+ :param title: The title of the Anki deck
110
+ :return: None
111
+ """
112
+ my_model = genanki.Model(
113
+ 1607392319,
114
+ "Simple Model",
115
+ fields=[
116
+ {"name": "Question"},
117
+ {"name": "Answer"},
118
+ {"name": "selects"},
119
+ ],
120
+ templates=[
121
+ {
122
+ "name": "Card 1",
123
+ "qfmt": "{{Question}}<br><br>{{selects}}",
124
+ "afmt": '{{FrontSide}}<hr id="answer">{{Answer}}',
125
+ },
126
+ ],
127
+ )
128
+
129
+ my_deck = genanki.Deck(2059400110, title)
130
+
131
+ for index, row in df.iterrows():
132
+ my_note = genanki.Note(
133
+ model=my_model,
134
+ fields=[row["Question"], row["Correct Answers"], row["Possible Answers"]],
135
+ )
136
+ my_deck.add_note(my_note)
137
+
138
+ try:
139
+ genanki.Package(my_deck).write_to_file(
140
+ os.path.join(out, "anki.apkg"),
141
+ )
142
+ except Exception as e:
143
+ logging.error("Failed to write Anki package file: %s", str(e))
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: kahoot-to-anki
3
+ Version: 1.2.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.9
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](https://img.shields.io/badge/python-3.9+-blue.svg)](#installation)
17
+ [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
18
+
19
+ <br>
20
+
21
+ **kahoot-to-anki** is a command‑line tool that converts exported Kahoot quiz reports (Excel Files) into Anki flashcard decks (.apkg format).<br>
22
+ Designed for educators, students, and any self-learners to easily turn quiz results into effective spaced‑repetition decks.
23
+
24
+ ## Installation & Usage
25
+ ### Option 1: Install via pip
26
+ ```
27
+ pip install kahoot-to-anki
28
+ ```
29
+ Then run:
30
+ ```
31
+ kahoot-to-anki --help
32
+ ```
33
+ Example: Process all Kahoot Exports in the `./exports/` folder and write the flashcard deck and CSV file to `./data/`:
34
+ ```
35
+ kahoot-to-anki --inp "./exports" --out "./data" --csv
36
+ ```
37
+
38
+ ### Option 2: Run with Docker
39
+ ```
40
+ # Clone Repository
41
+ git clone https://github.com/SimonHRD/kahoot-to-anki.git
42
+
43
+ # Move into Repository
44
+ cd kahoot-to-anki
45
+
46
+ # Build docker image with the kahoot-to-anki tag
47
+ docker build -t kahoot-to-anki .
48
+
49
+ # Check help command
50
+ docker run --rm kahoot-to-anki --help
51
+
52
+ # Run with local data
53
+ docker run --rm -v "$(pwd)/data:/app/data" kahoot-to-anki --out "./data" --csv
54
+ ```
55
+
56
+ On PowerShell:
57
+ ```
58
+ docker run --rm -v ${PWD}\data:/app/data kahoot-to-anki --out "./data" --csv
59
+ ```
60
+
61
+ ## CLI Arguments
62
+ You can provide either a single Kahoot Excel file or a directory containing multiple `.xlsx` files as input.<br>
63
+ All valid Excel files in the directory will be processed.
64
+
65
+ | Argument | Description |
66
+ |----------------------|--------------------------------------------------------------------------------|
67
+ | `-i`, `--inp` | Path to the input Excel file or directory (default: `./data`) |
68
+ | `-o`, `--out` | Path to the output directory for the Anki deck (default: `./`) |
69
+ | `--sheet` | The Excel Sheet with the raw Kahoot quiz data (default: `RawReportData Data`) |
70
+ | `--csv`, `--no-csv` | Enable or disable CSV export of the questions (default: disabled) |
71
+ | `-t`, `--title` | Title of the generated Anki deck (default: `"Kahoot"`) |
72
+ | `--version` | Show the version of the installed kahoot-to-anki package |
73
+
74
+
75
+ ## Example
76
+ An example Kahoot export file is available in `data/`. The generated deck will be saved as `anki.apkg` in the specified `--out` directory (default: `./`).
77
+
78
+ ## License
79
+ MIT — see [LICENSE](./LICENSE)
@@ -0,0 +1,13 @@
1
+ kahoot_to_anki/__init__.py,sha256=Btl_98iBIXFtvGx47MqpfbaEVYoOMPBQn9bao7UASkQ,21
2
+ kahoot_to_anki/cli.py,sha256=2tRiIcnbcrPXVPQ8mdeUOHXYP3LO9ExNfp3Uy1FSaFk,4484
3
+ kahoot_to_anki/main.py,sha256=oVmOLqXUnzy1Q0Xnn4Dzr65bFf8Jaw4vYRwvDTSd_ro,936
4
+ kahoot_to_anki/processing.py,sha256=Ku8nFhgWpprmYWdLL6f-T8P7J_SmMuQD2NLVCQQErCs,4346
5
+ kahoot_to_anki-1.2.0.dist-info/licenses/LICENSE,sha256=HxPBlT4sSfEgRBrX0jZd8WTfM0c31VFgnLaCEWzGMZc,1122
6
+ tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ tests/test_cli.py,sha256=SL1WEJoA59-G7hRdWg5wOUyCPrjzZvsgPJxAZMPXpWg,3195
8
+ tests/test_processing.py,sha256=swLG2gkcwWm1ZG0T5u6izlhV-2AIsaMKdg174jp3za8,10951
9
+ kahoot_to_anki-1.2.0.dist-info/METADATA,sha256=I8iBo7bvvBQMyMticSKPHsILRASFMaB0VRi45EWhv3E,2953
10
+ kahoot_to_anki-1.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
11
+ kahoot_to_anki-1.2.0.dist-info/entry_points.txt,sha256=VqCk_PPVpGFgnGCBIlEnz8Y0qUqYV8J2tYNZZa8IRWA,60
12
+ kahoot_to_anki-1.2.0.dist-info/top_level.txt,sha256=aTMCk83rMZjWFZ556EHLIxVOgEawIWsMZzRpR3IPQ1w,21
13
+ kahoot_to_anki-1.2.0.dist-info/RECORD,,
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ kahoot-to-anki = kahoot_to_anki.main:main
tests/test_cli.py ADDED
@@ -0,0 +1,111 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ from kahoot_to_anki.cli import get_commandline_arguments, validation
7
+
8
+
9
+ # --- get_commandline_arguments ---
10
+ def test_get_commandline_arguments(monkeypatch):
11
+ """Test that CLI arguments are correctly parsed."""
12
+
13
+ test_args = [
14
+ "kahoot-to-anki",
15
+ "-i", "tests/data",
16
+ "-o", "output_dir",
17
+ "--csv",
18
+ "--sheet", "CustomSheet",
19
+ "--title", "My Deck"
20
+ ]
21
+
22
+ monkeypatch.setattr(sys, "argv", test_args)
23
+
24
+ args = get_commandline_arguments()
25
+
26
+ assert Path(args.input_path).name == "data"
27
+ assert Path(args.output_path).name == "output_dir"
28
+ assert args.export_csv is True
29
+ assert args.sheet == "CustomSheet"
30
+ assert args.deck_title == "My Deck"
31
+
32
+
33
+ def test_get_commandline_arguments_no_csv(monkeypatch):
34
+ """Test that --no-csv CLI argument is correctly parsed."""
35
+
36
+ test_args = [
37
+ "kahoot-to-anki",
38
+ "--no-csv",
39
+ ]
40
+
41
+ monkeypatch.setattr(sys, "argv", test_args)
42
+ args = get_commandline_arguments()
43
+
44
+ assert args.export_csv is False
45
+
46
+
47
+ # --- validation ---
48
+ def test_validation_valid_excel_file(tmp_path):
49
+ # Create dummy Excel file
50
+ excel_file = tmp_path / "valid.xlsx"
51
+ excel_file.write_text("Excel content")
52
+
53
+ # Create output directory
54
+ output_dir = tmp_path / "output"
55
+ output_dir.mkdir()
56
+
57
+ # Should not raise
58
+ validation(str(excel_file), str(output_dir))
59
+
60
+
61
+ def test_validation_valid_input_directory_with_excel(tmp_path):
62
+ input_dir = tmp_path / "input"
63
+ input_dir.mkdir()
64
+ (input_dir / "file1.xlsx").write_text("Excel content")
65
+
66
+ output_dir = tmp_path / "output"
67
+ output_dir.mkdir()
68
+
69
+ # Should not raise
70
+ validation(str(input_dir), str(output_dir))
71
+
72
+
73
+ def test_validation_input_path_does_not_exist(tmp_path):
74
+ output_dir = tmp_path / "output"
75
+ output_dir.mkdir()
76
+
77
+ with pytest.raises(FileNotFoundError):
78
+ validation(str(tmp_path / "missing.xlsx"), str(output_dir))
79
+
80
+
81
+ def test_validation_input_not_excel_file(tmp_path):
82
+ file = tmp_path / "file.txt"
83
+ file.write_text("Not Excel")
84
+ output_dir = tmp_path / "output"
85
+ output_dir.mkdir()
86
+
87
+ with pytest.raises(ValueError, match="Input file is not an excel file"):
88
+ validation(str(file), str(output_dir))
89
+
90
+
91
+ def test_validation_input_directory_no_excel_files(tmp_path):
92
+ input_dir = tmp_path / "input"
93
+ input_dir.mkdir()
94
+ (input_dir / "file.txt").write_text("Just text")
95
+
96
+ output_dir = tmp_path / "output"
97
+ output_dir.mkdir()
98
+
99
+ with pytest.raises(FileNotFoundError, match="does not contain any excel files"):
100
+ validation(str(input_dir), str(output_dir))
101
+
102
+
103
+ def test_validation_output_not_a_directory(tmp_path):
104
+ excel_file = tmp_path / "valid.xlsx"
105
+ excel_file.write_text("Excel content")
106
+
107
+ output_path = tmp_path / "output.txt"
108
+ output_path.write_text("Not a directory")
109
+
110
+ with pytest.raises(ValueError, match="Output is not a directory"):
111
+ validation(str(excel_file), str(output_path))