Skip to content

Commit 5d1f466

Browse files
committed
⚡️ reduce import scopes; simplify Path joining and fix variable names
1 parent 2fae861 commit 5d1f466

File tree

4 files changed

+58
-62
lines changed

4 files changed

+58
-62
lines changed

src/moodle_to_vikwikiquiz/main.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22
import logging
33
from pathlib import Path
44
from platform import system
5-
import time
5+
from sys import version_info
6+
from time import sleep
67
from urllib.parse import quote, urlencode
7-
import webbrowser
8+
from webbrowser import open_new_tab
89

910
# future: delete the comment below when stubs for the package below are available
10-
import pyperclip # type: ignore
11+
from pyperclip import copy # type: ignore
1112
from send2trash import send2trash # type: ignore
1213

1314
from .quiz.illustrations.state_of_illustrations import StateOfIllustrations # type: ignore
@@ -35,7 +36,7 @@ def main() -> None:
3536
)
3637
absolute_source_path: Path = args.source_path.resolve()
3738
quiz.import_file_or_files(
38-
path=absolute_source_path,
39+
source_path=absolute_source_path,
3940
recursively=args.recursive,
4041
)
4142
wiki_domain = "https://vik.wiki"
@@ -91,7 +92,7 @@ def get_article_instructions(
9192
• click on 'Fájlok kiválasztása...'"""
9293
)
9394
if operating_system == "Darwin" or operating_system == "Linux":
94-
pyperclip.copy(str(upload_directory))
95+
copy(str(upload_directory))
9596
print(
9697
f""" • press {go_to_folder_keyboard_shortcuts[operating_system]}
9798
• paste the content of the clipboard
@@ -105,7 +106,7 @@ def get_article_instructions(
105106
• return here."""
106107
)
107108
input("\nPlease press Enter then follow these instructions...")
108-
webbrowser.open_new_tab(
109+
open_new_tab(
109110
f"{wiki_domain}/Speciális:TömegesFeltöltés/moodle-to-vikwikiquiz"
110111
)
111112
input("Please press Enter if you're done with uploading...")
@@ -153,7 +154,7 @@ def log_in_to_wiki(wiki_domain: str) -> None:
153154
154155
Please press Enter to open the login page..."""
155156
)
156-
webbrowser.open_new_tab(f"{wiki_domain}/index.php?title=Speciális:Belépés")
157+
open_new_tab(f"{wiki_domain}/index.php?title=Speciális:Belépés")
157158
input("Please press Enter if you've logged in...")
158159
clear_terminal()
159160

@@ -280,7 +281,7 @@ def create_article(
280281
else:
281282
del parameters_for_opening_edit["preload"]
282283
del parameters_for_opening_edit["preloadparams[]"]
283-
pyperclip.copy(quiz_wikitext)
284+
copy(quiz_wikitext)
284285
print("\nThe wikitext of the quiz has been copied to the clipboard!")
285286
url = f"{wiki_domain}/{quote(quiz_title)}?{urlencode(parameters_for_opening_edit)}"
286287
if not args.new:
@@ -295,7 +296,7 @@ def create_article(
295296
• click on the 'Lap mentése' button ({wiki_modifier_keys[operating_system]}-{wiki_editor_keys["Publish page"]})"""
296297
)
297298
input("\nPlease press Enter then follow these instructions...")
298-
webbrowser.open_new_tab(url)
299+
open_new_tab(url)
299300
print(
300301
"\nThe edit page of the quiz article has been opened in your browser!", end=" "
301302
)
@@ -304,16 +305,16 @@ def create_article(
304305

305306

306307
def open_article_paste_text(args: Namespace, quiz_wikitext: str, url: str) -> None:
307-
pyperclip.copy(quiz_wikitext)
308+
copy(quiz_wikitext)
308309
print(
309310
"\nThe wikitext of the quiz has been copied to the clipboard! "
310311
"This will be overwritten but you may recall it later if you use an app like Pastebot."
311312
)
312313
wait_for_pastebot_to_recognize_copy()
313314
if args.verbose:
314-
pyperclip.copy(url)
315+
copy(url)
315316
print("The URL has been copied to the clipboard!")
316-
webbrowser.open_new_tab(url)
317+
open_new_tab(url)
317318
print(
318319
"\nThe edit page of the new quiz article has been opened in your browser with the wikitext pre-filled! "
319320
"Please upload illustrations manually, if there are any."
@@ -329,7 +330,7 @@ def open_article(
329330
"because the URL would be too long for some browsers (or the server)."
330331
)
331332
if args.verbose:
332-
pyperclip.copy(url)
333+
copy(url)
333334
print(
334335
"\nThis URL has been copied to the clipboard! "
335336
"It will be overwritten but you may recall it later if you use an app like Pastebot."
@@ -342,7 +343,7 @@ def open_article(
342343

343344
def wait_for_pastebot_to_recognize_copy() -> None:
344345
print("Waiting 2 seconds for Pastebot to recognize it...")
345-
time.sleep(2)
346+
sleep(2)
346347
print("...done!")
347348

348349

src/moodle_to_vikwikiquiz/quiz/illustrations/illustration.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
from pathlib import Path
2-
import re
2+
from re import sub
33

44
from .state_of_illustrations import StateOfIllustrations # type: ignore
55

66

77
def remove_wiki_unsafe_characters(upload_filename) -> str:
8-
upload_filename = re.sub(r"[{\[]", "(", upload_filename)
9-
upload_filename = re.sub(r"[}\]]", ")", upload_filename)
8+
upload_filename = sub(r"[{\[]", "(", upload_filename)
9+
upload_filename = sub(r"[}\]]", ")", upload_filename)
1010
return upload_filename
1111

1212

src/moodle_to_vikwikiquiz/quiz/quiz.py

Lines changed: 23 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
1-
import contextlib
1+
from contextlib import suppress
22

33
# future: report false positive to JetBrains developers
44
# noinspection PyUnresolvedReferences
5-
import os
5+
from os import getcwd, makedirs, path, rename, walk
66

77
# noinspection PyUnresolvedReferences
88
from pathlib import Path
99

10-
# noinspection PyUnresolvedReferences
11-
import re
12-
import shutil
10+
from re import compile
11+
from shutil import copy
1312

1413
# noinspection PyUnresolvedReferences
1514
from bs4 import BeautifulSoup, Tag
@@ -28,17 +27,13 @@ def move_illustration_to_upload_folder(
2827
quiz_element: QuizElement, upload_directory: Path
2928
) -> None:
3029
if illustration := quiz_element.illustration:
31-
if not os.path.exists(upload_directory):
32-
os.makedirs(upload_directory)
30+
if not path.exists(upload_directory):
31+
makedirs(upload_directory)
3332
original_file_path = illustration.original_file_path.resolve()
34-
shutil.copy(original_file_path, upload_directory)
35-
current_file_path = Path(
36-
os.path.join(upload_directory, illustration.original_file_path.name)
37-
)
38-
new_file_path = os.path.join(
39-
current_file_path.parent, illustration.upload_filename
40-
)
41-
os.rename(current_file_path, new_file_path)
33+
copy(original_file_path, upload_directory)
34+
current_file_path = upload_directory / illustration.original_file_path.name
35+
new_file_path = current_file_path.parent / illustration.upload_filename
36+
rename(current_file_path, new_file_path)
4237

4338

4439
class Quiz:
@@ -78,31 +73,31 @@ def __str__(self) -> str:
7873
text += "\n"
7974
return text
8075

81-
def import_file_or_files(self, path: Path, recursively: bool) -> None:
82-
if not os.path.exists(path):
76+
def import_file_or_files(self, source_path: Path, recursively: bool) -> None:
77+
if not path.exists(source_path):
8378
raise FileNotFoundError(f"'{path}' does not exist!")
84-
elif os.path.isfile(path):
85-
self.import_questions(path, path.parent)
79+
elif path.isfile(source_path):
80+
self.import_questions(source_path, source_path.parent)
8681
else:
87-
self.import_files(path, recursively)
82+
self.import_files(source_path, recursively)
8883

8984
if not self.questions:
9085
raise ValueError(f"No questions were imported from '{path}'!")
9186

92-
def import_files(self, path: Path, recursively: bool) -> None:
93-
for directory, subdirectories, files in os.walk(path):
87+
def import_files(self, source_path: Path, recursively: bool) -> None:
88+
for directory, subdirectories, files in walk(source_path):
9489
for file in files:
9590
self.import_questions(Path(file), Path(directory))
9691
if not recursively:
9792
break
9893

9994
def import_questions(self, file: Path, directory: Path) -> None:
100-
file_path = os.path.join(directory, file)
95+
file_path = path.join(directory, file)
10196
with open(file_path, "rb") as source_file:
10297
webpage = BeautifulSoup(source_file, "html.parser")
10398

10499
accepted_questions = webpage.find_all(
105-
"div", class_=re.compile(r"multichoice|calculatedmulti|truefalse")
100+
"div", class_=compile(r"multichoice|calculatedmulti|truefalse")
106101
)
107102
for question in accepted_questions:
108103
self.import_question(question, Path(file_path), directory, file)
@@ -117,7 +112,7 @@ def import_question(
117112
) -> None:
118113
if self.state_of_illustrations == StateOfIllustrations.Nil:
119114
self.state_of_illustrations = get_if_has_illustration(question, directory, file) # type: ignore
120-
with contextlib.suppress(NotImplementedError):
115+
with suppress(NotImplementedError):
121116
question_type = get_question_type(question) # type: ignore
122117
correctly_answered, grade, maximum_points = get_grading_of_question(question) # type: ignore
123118
# noinspection PyTypeChecker
@@ -138,7 +133,7 @@ def import_question(
138133
maximum_points,
139134
question_text,
140135
question_type,
141-
os.path.basename(file_path),
136+
path.basename(file_path),
142137
)
143138
self.add_question_if_new(
144139
question_type,
@@ -257,13 +252,13 @@ def add_question(
257252
)
258253

259254
def get_illustrations_ready_for_upload(self) -> Path | None:
260-
upload_directory = Path(os.path.join(os.getcwd(), "to_upload"))
255+
upload_directory = Path(path.join(getcwd(), "to_upload"))
261256
for question in self.questions:
262257
move_illustration_to_upload_folder(question, upload_directory)
263258
for answer in question.answers:
264259
if answer.illustration:
265260
move_illustration_to_upload_folder(answer, upload_directory)
266-
if os.path.exists(upload_directory):
261+
if path.exists(upload_directory):
267262
return upload_directory
268263
else:
269264
return None

src/moodle_to_vikwikiquiz/quiz/quiz_helpers.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import os
1+
from os import path, system
22
from pathlib import Path
3-
import re
3+
from re import findall, sub
44
from urllib.parse import unquote, urlparse
5-
import uuid
5+
from uuid import uuid4
66

77
from bs4 import Tag
88

@@ -34,7 +34,7 @@ def get_grading_of_question(question: Tag) -> tuple[bool, float | None, float]:
3434
assert isinstance(found_tag, Tag)
3535

3636
grading_text = found_tag.text
37-
numbers_in_capture_groups: list[tuple[str, str]] = re.findall(
37+
numbers_in_capture_groups: list[tuple[str, str]] = findall(
3838
r"(\d+)([.,]\d+)?", grading_text
3939
)
4040
numbers = [
@@ -158,7 +158,7 @@ def prettify(text: str) -> str:
158158

159159
def strip_whitespaces(text: str) -> str:
160160
text = text.strip("., \n")
161-
text = re.sub(r" \n|\r\n|\s{2}", " ", text)
161+
text = sub(r" \n|\r\n|\s{2}", " ", text)
162162
return text
163163

164164

@@ -249,7 +249,7 @@ def get_question_data(
249249

250250
def get_question_text(found_tag: Tag) -> str:
251251
assert isinstance(found_tag, Tag)
252-
text = re.sub(r"\s?\r?\n\s?", " ", found_tag.text)
252+
text = sub(r"\s?\r?\n\s?", " ", found_tag.text)
253253
text = text.rstrip()
254254
text = format_latex_as_wikitext(text)
255255
return text
@@ -273,7 +273,7 @@ def get_element_illustration(
273273
illustration_url_string = illustration_url_parsed.geturl()
274274
illustration_path_string = unquote(illustration_url_string)
275275
illustration_path = Path(illustration_path_string)
276-
original_file_path_string = os.path.join(current_folder, illustration_path)
276+
original_file_path_string = current_folder / illustration_path
277277
original_file_path = Path(original_file_path_string)
278278
extension = original_file_path.suffix
279279

@@ -341,7 +341,7 @@ def create_upload_filename(
341341
) -> str:
342342
upload_filename = f'"{name_of_illustration}"'
343343
if make_unique:
344-
random_hash = uuid.uuid4().hex[:6]
344+
random_hash = uuid4().hex[:6]
345345
upload_filename += f" – válaszlehetőség {random_hash}"
346346
upload_filename += f" ({quiz_name}){extension}"
347347
return upload_filename
@@ -358,17 +358,17 @@ def format_latex_as_wikitext(latex: Tag) -> str:
358358

359359
@dispatch # type: ignore
360360
def format_latex_as_wikitext(latex: str) -> str:
361-
if re.findall(latex_start_anchored := r"^\s?\\?\\\(\s?(\s?\\(?=\\))?", latex):
362-
wikitext = re.sub(latex_start_anchored, "<math>", latex)
361+
if findall(latex_start_anchored := r"^\s?\\?\\\(\s?(\s?\\(?=\\))?", latex):
362+
wikitext = sub(latex_start_anchored, "<math>", latex)
363363
else:
364364
latex_start = latex_start_anchored.replace(r"^\s?", "")
365-
wikitext = re.sub(latex_start, "<math>", latex)
365+
wikitext = sub(latex_start, "<math>", latex)
366366

367-
if re.findall(latex_end_anchored := r"\s*\\?\\\)\s?$", wikitext):
368-
wikitext = re.sub(latex_end_anchored, "</math>", wikitext)
367+
if findall(latex_end_anchored := r"\s*\\?\\\)\s?$", wikitext):
368+
wikitext = sub(latex_end_anchored, "</math>", wikitext)
369369
else:
370370
latex_end = latex_end_anchored.replace(r"\s?$", "")
371-
wikitext = re.sub(latex_end, "</math>", wikitext)
371+
wikitext = sub(latex_end, "</math>", wikitext)
372372
return wikitext
373373

374374

@@ -396,12 +396,12 @@ def get_if_has_illustration(
396396

397397

398398
def get_if_illustrations_available(directory: Path, file: Path) -> StateOfIllustrations:
399-
asset_folder = os.path.join(directory, f"{file.stem}_files")
400-
if os.path.exists(asset_folder):
399+
asset_folder = directory / f"{file.stem}_files"
400+
if path.exists(asset_folder):
401401
return StateOfIllustrations.YesAndAvailable
402402
else:
403403
return StateOfIllustrations.YesButUnavailable
404404

405405

406406
def clear_terminal() -> None:
407-
os.system("clear||cls")
407+
system("clear||cls")

0 commit comments

Comments
 (0)