Skip to content

xpuz.utils ¤

General/specialised utility functions.

BlockUtils ¤

Methods to help with manipulating block objects in both pages/editor.py and pages/browser.py.

_config_selectors classmethod ¤

_config_selectors(**kwargs: Dict[str, Any]) -> None

Enable or disable all the radiobutton selectors in cls.blocks.

Parameters:

Name Type Description Default
**kwargs Dict[str, Any]

Configuration parameters.

{}
Source code in src/xpuz/utils.py
378
379
380
381
382
383
384
385
386
@classmethod
def _config_selectors(cls, **kwargs: Dict[str, Any]) -> None:
    """Enable or disable all the radiobutton selectors in ``cls.blocks``.

    Args:
        **kwargs: Configuration parameters.
    """
    for block in cls.blocks:
        block.rb_selector.configure(**kwargs)

_match_block_query staticmethod ¤

_match_block_query(
    query: str, block_name: str, category: str
) -> bool

Return True if any part of block_name (split into the words that it consists of) starts with query, or if category starts with query. All comparisons are caseless and do not regard whitespace (except the category, which keeps its whitespace).

Parameters:

Name Type Description Default
query str

A query entered by the user.

required
block_name str

The current block name that is being queried.

required
category str

The category of the current block name that is being queried.

required

Returns:

Type Description
bool

Whether the query was found in the category or block name, or not.

Source code in src/xpuz/utils.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
@staticmethod
def _match_block_query(query: str, block_name: str, category: str) -> bool:
    """Return True if any part of ``block_name`` (split into the words that
    it consists of) starts with ``query``, or if ``category`` starts with
    ``query``. All comparisons are caseless and do not regard whitespace
    (except the category, which keeps its whitespace).

    Args:
        query: A query entered by the user.
        block_name: The current block name that is being queried.
        category: The category of the current block name that is being queried.

    Returns:
        Whether the query was found in the category or block name, or not.
    """
    formatted_query = query.strip().casefold()
    return any(
        block_name_segment.strip().casefold().startswith(formatted_query)
        for block_name_segment in block_name.split(" ")
    ) or category.casefold().startswith(formatted_query)

_put_block classmethod ¤

_put_block(block: CTkFrame, side: str = 'left') -> None

Pack block in its parent container and append it to the available blocks in cls.

Parameters:

Name Type Description Default
block CTkFrame

The block instance to be packed.

required
side str

The side to pack the block. "top" for the crossword editor panes, and "left" for the crossword browser container.

'left'
Source code in src/xpuz/utils.py
336
337
338
339
340
341
342
343
344
345
346
347
@classmethod
def _put_block(cls, block: CTkFrame, side: str = "left") -> None:
    """Pack ``block`` in its parent container and append it to the available
    blocks in ``cls``.

    Args:
        block: The block instance to be packed.
        side: The side to pack the block. `"top"` for the crossword editor
              panes, and `"left"` for the crossword browser container.
    """
    block.pack(side=side, padx=5, pady=(5, 0))
    cls.blocks.append(block)

_remove_block classmethod ¤

_remove_block(block: CTkFrame) -> None

Remove block from its parent container and the available blocks in cls.

Parameters:

Name Type Description Default
block CTkFrame

The block to remove.

required
Source code in src/xpuz/utils.py
349
350
351
352
353
354
355
356
357
358
@classmethod
def _remove_block(cls, block: CTkFrame) -> None:
    """Remove ``block`` from its parent container and the available blocks
    in ``cls``.

    Args:
        block: The block to remove.
    """
    block.pack_forget()
    cls.blocks.remove(block)

_set_all classmethod ¤

_set_all(func: Callable) -> None

Call func, passing each block in cls.blocks as parameters. Most often used to put or remove all of the blocks in cls.blocks.

Parameters:

Name Type Description Default
func Callable

The function to perform on the block.

required
Source code in src/xpuz/utils.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
@classmethod
def _set_all(
    cls,
    func: Callable,
) -> None:
    """Call ``func``, passing each block in ``cls.blocks`` as parameters.
    Most often used to put or remove all of the blocks in ``cls.blocks``.

    Args:
        func: The function to perform on the block.
    """
    for block in [
        *cls.blocks
    ]:  # Must iterate over a shallow copy here, as
        # you cannot modify an array you iterate
        # over (with ``func``)
        func(block)

GUIHelper ¤

_install_translations staticmethod ¤

_install_translations(locale: Locale) -> None

Install translations from locale.language with gettext.

Parameters:

Name Type Description Default
locale Locale

The current locale object.

required
Source code in src/xpuz/utils.py
59
60
61
62
63
64
65
66
67
68
69
70
71
@staticmethod
def _install_translations(locale: Locale) -> None:
    """Install translations from ``locale.language`` with gettext.

    Args:
        locale: The current locale object.
    """
    translation(
        "messages",
        localedir=LOCALES_PATH,
        languages=[locale.language],
        fallback=True,
    ).install()

confirm_with_messagebox staticmethod ¤

confirm_with_messagebox(
    *args: Tuple[str], **kwargs: Dict[str, str]
) -> bool

Provide confirmations to the user with tkinter messageboxes.

Parameters:

Name Type Description Default
*args Tuple[str]

Optional info messages to be included with specific messagebox calls.

()
**kwargs Dict[str, str]

The specific messagebox name, selected by this method's if statements.

{}

Returns:

Type Description
bool

Whether the user confirmed/pressed yes on the messagebox or not.

Source code in src/xpuz/utils.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
@staticmethod
def confirm_with_messagebox(
    *args: Tuple[str], **kwargs: Dict[str, str]
) -> bool:
    """Provide confirmations to the user with tkinter messageboxes.

    Args:
        *args: Optional info messages to be included with specific messagebox
               calls.
        **kwargs: The specific messagebox name, selected by this method's
                  `if` statements.

    Returns:
        Whether the user confirmed/pressed yes on the messagebox or not.
    """
    if "delete_cword_or_word" in kwargs:
        return messagebox.askyesno(
            _("Remove"),
            _("Are you sure you want to delete this")
            + f" {args[0]}? "
            + _("It will be lost forever!"),
        )

    if "confirm_cword_or_word_add" in kwargs:
        return messagebox.askyesno(
            _("Add or select"),
            _("Are you sure you want to add/select a")
            + f" {args[0]}? "
            + _("Your modified fields will be reset!"),
        )

    if "exiting_with_nondefault_fields" in kwargs:
        return messagebox.askyesno(
            _("Back to home"),
            _(
                "Are you sure you want to go back to the home screen? Your "
                "modified fields will be reset!"
            ),
        )

    if "importing_with_nondefault_fields" in kwargs:
        return messagebox.askyesno(
            _("Info"),
            _(
                "Are you sure you want to import crosswords? Your modified "
                "fields will be reset!"
            ),
        )

    if "exit_" in kwargs and "restart" not in kwargs:
        return messagebox.askyesno(
            _("Restart"), _("Are you sure you want to restart the app?")
        )

    if "exit_" in kwargs and "restart" in kwargs:
        return messagebox.askyesno(
            _("Exit"),
            _(
                "Are you sure you want to exit the app? If the web app is "
                "running, it will be terminated."
            ),
        )

    if "close" in kwargs:
        return messagebox.askyesno(
            _("Back to home"),
            _(
                "Are you sure you want to go back to the home screen? The web "
                "app will be terminated."
            ),
        )

show_messagebox staticmethod ¤

show_messagebox(
    *args: Tuple[str], **kwargs: Dict[str, str]
) -> None

Show an error/info messagebox

Parameters:

Name Type Description Default
*args Tuple[str]

Optional error messages/details to be included with specific messagebox calls.

()
**kwargs Dict[str, str]

The specific messagebox name, selected by this method's if statements.

{}
Source code in src/xpuz/utils.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
@staticmethod
def show_messagebox(*args: Tuple[str], **kwargs: Dict[str, str]) -> None:
    """Show an error/info messagebox

    Args:
        *args: Optional error messages/details to be included with specific
               messagebox calls.
        **kwargs: The specific messagebox name, selected by this method's
                  `if` statements.
    """
    if "same_lang" in kwargs:
        return messagebox.showerror(
            _("Error"), _("This language is already selected.")
        )

    if "same_scale" in kwargs:
        return messagebox.showerror(
            _("Error"), _("This size is already selected.")
        )

    if "same_appearance" in kwargs:
        return messagebox.showerror(
            _("Error"), _("This appearance is already selected.")
        )

    if "same_quality" in kwargs:
        return messagebox.showerror(
            _("Error"), _("This quality is already selected.")
        )

    if "crossword_exists_err" in kwargs:
        return messagebox.showerror(
            _("Error"),
            _(
                "A crossword with this name and difficulty already exists. "
                "Please choose a new name and/or a new difficulty."
            ),
        )

    if "no_crosswords_to_export_err" in kwargs:
        return messagebox.showerror(
            _("Error"),
            _(
                "You have no crosswords to export. Please make some and try again."
            ),
        )

    if "export_success" in kwargs:
        return messagebox.showinfo(
            _("Info"), _("Successfully exported your crosswords.")
        )

    if "export_failure" in kwargs:
        return messagebox.showerror(
            _("Error"), _("Your crosswords could not be exported, sorry.")
        )

    if "import_success" in kwargs:
        return messagebox.showinfo(
            _("Info"),
            _("All of your crosswords were successfully imported."),
        )

    if "partial_import_success" in kwargs:
        return messagebox.showinfo(
            _("Info"),
            _("Your import could not be fully completed.")
            + "\n\n"
            + _(
                "Crosswords with duplicate names and difficulties that were "
                "not imported: "
            )
            + f"[{', '.join(args[0])}]."
            + "\n\n"
            + _("Invalid crosswords that were not imported: ")
            + f"[{', '.join(args[1])}].",
        )

    if "import_failure" in kwargs:
        return messagebox.showerror(
            _("Error"),
            _(
                "The specified JSON file is invalid and cannot be processed."
            ),
        )

    if "word_exists_err" in kwargs:
        return messagebox.showerror(
            _("Error"),
            _("This word already exists. Please choose a new word."),
        )

    if "pdf_write_err" in kwargs:
        return messagebox.showerror(
            _("Error"),
            _(
                "An error occurred while creating your PDF. Please try again."
            ),
        )

    if "pdf_write_success" in kwargs:
        if not args:
            fails_msg = ""
        else:
            disclaimer_str = _(
                "words that could not be inserted during crossword "
                "generation will not be included in this PDF, sorry."
            )
            fails_msg = f" {args[0]} {disclaimer_str}"
        return messagebox.showinfo(
            _("Info"),
            _("Successfully wrote PDF.") + fails_msg,
        )

    if "pdf_missing_dep" in kwargs:
        return messagebox.showerror(
            _("Error"),
            _(
                "You are missing pycairo, which is required to perform this "
                "operation. Please run"
            )
            + " pip install pycairo "
            + _(
                "and install the headers for pycairo if you are not on "
                "Windows using pycairo's Getting Started guide"
            )
            + ": https://pycairo.readthedocs.io/en/latest/getting_started.html",
        )

    if "ipuz_write_success" in kwargs:
        return messagebox.showinfo(_("Info"), _("Successfully wrote ipuz"))

    if "first_time_browser" in kwargs:
        return messagebox.showinfo(
            _("Info"),
            _(
                "First time launch, please read: Once you have loaded a "
                "crossword, and wish to load another one, you must first "
                "terminate the web app. IMPORTANT: If you are on macOS, force "
                "quitting the application (using cmd+q) while the web app is "
                "running will prevent it from properly terminating. If you "
                "mistakenly do this, the program will run new web apps with a "
                "different port. Alternatively, you can manually change the "
                "port in the program's config file. All app processes that "
                "have not been properly terminated can be terminated through "
                "Activity Monitor on MacOS, or, simply restart your computer "
                "to terminate them."
            ),
        )

    if "cword_or_def_err" in kwargs:
        return messagebox.showerror(_("Error"), f"{args[0]}({args[1]})")

    if "other_gen_err" in kwargs:
        return messagebox.showerror(
            _("Error"),
            f"{args[0]}({args[1]}) - "
            + _(
                "An unexpected error occured. Please try reinstalling the "
                "application with"
            )
            + " pip install --force-reinstall xpuz",
        )

_check_doc_cfg_is_up_to_date ¤

_check_doc_cfg_is_up_to_date() -> bool

Check if the all the sections (and values of those sections) are present in the document config.ini file.

Returns:

Type Description
bool

Whether the config.ini in the system's documents directory is up-to-date

bool

or not.

Source code in src/xpuz/utils.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
def _check_doc_cfg_is_up_to_date() -> bool:
    """Check if the all the sections (and values of those sections) are present
    in the document config.ini file.

    Returns:
        Whether the config.ini in the system's documents directory is up-to-date
        or not.
    """
    template_cfg, doc_cfg = ConfigParser(), ConfigParser()
    template_cfg.read(TEMPLATE_CFG_PATH)
    doc_cfg.read(DOC_CFG_PATH)
    for section in template_cfg:
        if section != "DEFAULT":  # Ignore this, all keys are sectioned
            template_items = template_cfg.items(section)
            try:  # Missing section, can immediately return False
                doc_items = doc_cfg.items(section)
            except NoSectionError:
                return False
            for (
                item
            ) in template_items:  # Iterate through all template section items
                if any(  # template_item[0] or item[0] refers to the key here
                    template_item[0] not in [item[0] for item in doc_items]
                    for template_item in template_items
                ):  # This means not all sections are identical
                    return False

    return (
        True  # All checks passed, tell the caller not to update the config.ini
    )

_check_version ¤

_check_version() -> Union[None, str]

Find latest remote GitHub release if it is higher than the local release using the urllib module.

Returns:

Type Description
Union[None, str]

The latest release, if it was found. Otherwise, returns None.

Source code in src/xpuz/utils.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def _check_version() -> Union[None, str]:
    """Find latest remote GitHub release if it is higher than the local
    release using the ``urllib`` module.

    Returns:
        The latest release, if it was found. Otherwise, returns `None`.
    """
    try:
        request = req.Request(RELEASE_API_URL)
        response = req.urlopen(request)
    except URLError:  # URL doesn't exist
        return None

    if response.status == 200:  # Request success
        data = loads(response.read().decode())
        local_ver = __version__.split(".")
        remote_ver = data["name"].split(".")

        # Any component of the remote semver'd tag is greater than that of the
        # local tag (MAJOR or MINOR or PATCH), meaning a new version has been
        # made, so, return the remote version.
        if any(
            int(item[0]) > int(item[1])
            for item in list(zip(remote_ver, local_ver))
        ):
            return data["name"]

    return None  # ``response.status`` wasn't 200, meaning some error occurred.

_doc_data_routine ¤

_doc_data_routine(
    doc_callback: Optional[Callable] = None,
    local_callback: Optional[Callable] = None,
    toplevel: PathLike = DOC_PATH,
    datalevel: PathLike = DOC_DATA_PATH,
    sublevel: PathLike = DOC_CFG_PATH,
) -> bool

Scan through both the package and system document directories, making the required folders if needed.

Parameters:

Name Type Description Default
doc_callback Optional[Callable]

A function to execute if possible when scanning the system's document directory to make missing files.

None
local_callback Optional[Callable]

A function to execute if possible when scanning the local data of the xpuz package to make missing files.

None
toplevel PathLike

The path of the system's document directory.

DOC_PATH
datalevel PathLike

The path to the data files within toplevel

DOC_DATA_PATH
sublevel PathLike

The path to config.ini within toplevel.

DOC_CFG_PATH

Returns:

Type Description
bool

Whether the document data has been successfully made or not.

Source code in src/xpuz/utils.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def _doc_data_routine(
    doc_callback: Optional[Callable] = None,
    local_callback: Optional[Callable] = None,
    toplevel: PathLike = DOC_PATH,
    datalevel: PathLike = DOC_DATA_PATH,
    sublevel: PathLike = DOC_CFG_PATH,
) -> bool:
    """Scan through both the package and system document directories, making
    the required folders if needed.

    Args:
        doc_callback: A function to execute if possible when scanning the system's
                      document directory to make missing files.
        local_callback: A function to execute if possible when scanning the
                        local data of the `xpuz` package to make missing files.
        toplevel: The path of the system's document directory.
        datalevel: The path to the data files within `toplevel`
        sublevel: The path to `config.ini` within `toplevel`.

    Returns:
        Whether the document data has been successfully made or not.
    """
    if not path.exists(toplevel):
        # No documents folder available. The caller might have added a func to
        # run if this happens, which will make the required folder in the package
        if local_callback:
            try:
                local_callback()  # Attempt to make the required package files
            except OSError:
                pass
        return False  # Cannot continue, as Documents do not exist

    # If the code reached this point, it means a Documents folder must exist
    if not path.exists(datalevel):  # Attempt to make the ``xpuz`` dir in Documents
        mkdir(DOC_DATA_PATH)

    if not path.exists(sublevel):  # The required sub-directory doesn't exist 
                                   # yet in Documents
        if doc_callback:
            try:
                doc_callback()  # Attempt to make the required sub-directory
                                # eg ``xpuz/user`` for user crosswords
            except OSError:
                pass

    return True  # Success, as the doc data has been made

_find_best_crossword ¤

_find_best_crossword(
    crossword: Crossword, cls: Crossword
) -> Crossword

Determine the best crossword out of a amount of instantiated crosswords based on the largest amount of total intersections and smallest amount of fails.

Parameters:

Name Type Description Default
crossword Crossword

The Crossword instance to perform the optimised creation on.

required
cls Crossword

The Crossword class.

required

Returns:

Type Description
Crossword

The best Crossword instance that was found.

Source code in src/xpuz/utils.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
def _find_best_crossword(
    crossword: "Crossword", cls: "Crossword"
) -> "Crossword":
    """Determine the best crossword out of a amount of instantiated
    crosswords based on the largest amount of total intersections and
    smallest amount of fails.

    Args:
        crossword: The `Crossword` instance to perform the optimised creation on.
        cls: The `Crossword` class.

    Returns:
        The best `Crossword` instance that was found.
    """
    cfg: ConfigParser = ConfigParser()
    _read_cfg(cfg)
    name: str = crossword.name
    word_count: int = crossword.word_count

    attempts_db: Dict[str, int] = _load_attempts_db()
    try:
        max_attempts: int = attempts_db[str(word_count)]  # Get amount of attempts 
                                                          # based on word count
        max_attempts *= (
            QUALITY_MAP[  # Scale max attempts based on crossword quality
                cfg.get("m", "cword_quality")
            ]
        )
        max_attempts = int(ceil(max_attempts))
    except KeyError:  # Fallback to only a single generation attempt
        max_attempts = 1
    attempts: int = 0  # Track current amount of attempts
    dimensions_incremented = False

    definitions: Dict[str, str] = crossword.definitions
    dimensions: int = crossword.dimensions
    crossword.generate()
    best_crossword = (
        crossword  # Assume the best crossword is the first crossword
    )

    while attempts <= max_attempts:
        # Set ``via_find_best_crossword`` to True so dimensions are not
        # recalculated and new definitions are not sampled; only the existing
        # ones are randomised
        crossword = cls(
            name=name,
            definitions=definitions,
            word_count=word_count,
            via_find_best_crossword=True,
            dimensions=dimensions,
        )
        crossword.generate()

        # Update the new best crossword if it has more intersections than
        # the current crossword and its fails are less than or equal to the
        # current crossword's fails. Changing the fails comparison to simply
        # "less than" is too strict and results in a poor "best" crossword.
        if crossword.total_intersections > best_crossword.total_intersections:
            if crossword.fails <= best_crossword.fails:
                best_crossword = crossword

        # Increment the dimensions by 1 if there is a fail present in the current
        # crossword to minimise the chance another fail happens in the remaining
        # crosswords.
        if not dimensions_incremented and crossword.fails > 0:
            dimensions += 1
            dimensions_incremented = True

        attempts += 1

    assert best_crossword.generated
    return best_crossword

_format_definitions ¤

_format_definitions(
    definitions: Dict[str, str], word_count: int
) -> Dict[str, str]

Randomly pick definitions from a larger sample, then prune everything except the language characters from the words (the keys of the definitions).

Parameters:

Name Type Description Default
definitions Dict[str, str]

The crossword's definitions.

required
word_count int

The crossword's word count.

required

Returns:

Type Description
Dict[str, str]

The formatted crossword definitions.

Source code in src/xpuz/utils.py
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
def _format_definitions(
    definitions: Dict[str, str], word_count: int
) -> Dict[str, str]:
    """Randomly pick definitions from a larger sample, then prune
    everything except the language characters from the words (the keys of
    the definitions).

    Args:
        definitions: The crossword's definitions.
        word_count: The crossword's word count.

    Returns:
        The formatted crossword definitions.
    """
    # Randomly sample ``word_count`` amount of definitions
    randomly_sampled_definitions = dict(
        sample(list(definitions.items()), word_count)
    )

    # Remove all non language chars from the keys of
    # ``randomly_sampled_definitions``` (the words) and capitalise its values
    # (the clues/definitions)
    formatted_definitions = {
        sub(NONLANGUAGE_PATTERN, "", k).upper(): v
        for k, v in randomly_sampled_definitions.items()
    }

    return formatted_definitions

_get_base_categories ¤

_get_base_categories() -> Iterable[DirEntry]

Get all the available crossword categories sorted alphabetically.

Returns:

Type Description
Iterable[DirEntry]

All the directory entries to the available crossword categories. They

Iterable[DirEntry]

can be sourced from both the package and the system's data.

Source code in src/xpuz/utils.py
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def _get_base_categories() -> Iterable[DirEntry]:
    """Get all the available crossword categories sorted alphabetically.

    Returns:
        All the directory entries to the available crossword categories. They
        can be sourced from both the package and the system's data.
    """
    if _doc_data_routine() and "user" in listdir(DOC_DATA_PATH):
        # It is safe to say the user category is in the Document data, so
        # retrieve all package categories except for the user category
        scanned_cats = [
            cat
            for cat in scandir(BASE_CWORDS_PATH)
            if cat.is_dir() and cat.name != "user"
        ]
        # Add on the user category direntry from the document data
        scanned_cats += [cat for cat in scandir(DOC_DATA_PATH) if cat.is_dir()]

    else:  # Retrieve ALL categories from the package data
        scanned_cats = [
            cat for cat in scandir(BASE_CWORDS_PATH) if cat.is_dir()
        ]

    return sorted(
        scanned_cats, key=lambda cat: cat.name if cat.name != "user" else "!"
    )

_get_base_crosswords ¤

_get_base_crosswords(
    category: Union[DirEntry, PathLike],
    sort: bool = True,
    allow_empty_defs: bool = False,
) -> Iterable[DirEntry]

Get all the available crosswords from the base crossword directory if they have valid definitions.json files.

Parameters:

Name Type Description Default
category Union[DirEntry, PathLike]

The path/directory entry to the category.

required
sort bool

Whether to sort the obtained crosswords or not.

True
allow_empty_defs bool

Consider a crossword with no definitions to be valid if it is user made.

False

Returns:

Type Description
Iterable[DirEntry]

The acquired crosswords, sorted or unsorted, based on if any errors

Iterable[DirEntry]

occurred during the sorting process.

Source code in src/xpuz/utils.py
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
def _get_base_crosswords(
    category: Union[DirEntry, PathLike],
    sort: bool = True,
    allow_empty_defs: bool = False,
) -> Iterable[DirEntry]:
    """Get all the available crosswords from the base crossword directory if
    they have valid ``definitions.json`` files.

    Args:
        category: The path/directory entry to the category.
        sort: Whether to sort the obtained crosswords or not.
        allow_empty_defs: Consider a crossword with no definitions to be valid
                          if it is user made.

    Returns:
        The acquired crosswords, sorted or unsorted, based on if any errors
        occurred during the sorting process.
    """
    fp: PathLike = getattr(category, "path", category)
    # Actual path can either be ``fp`` or the document category path if the requested
    # category is user and it is present in the system document data
    actual_path: PathLike = (
        DOC_CAT_PATH
        if _doc_data_routine()
        and "user" in listdir(DOC_DATA_PATH)
        and fp.endswith("user")
        else fp
    )
    crosswords = [
        cword
        for cword in scandir(actual_path)
        if cword.is_dir()
        and "definitions.json" in listdir(cword.path)
        and path.getsize(path.join(cword.path, "definitions.json")) > 0
        or (allow_empty_defs and category.endswith("user") and cword.is_dir())
    ]
    return _sort_crosswords_by_suffix(crosswords) if sort else crosswords

_get_colour_palette ¤

_get_colour_palette(
    appearance_mode: Union[
        Literal["Light"], Literal["Dark"], Literal["System"]
    ]
) -> Dict[str, str]

Create a dictionary based on constants.Colour for the web app.

Parameters:

Name Type Description Default
appearance_mode Union[Literal['Light'], Literal['Dark'], Literal['System']]

The current tkinter appearance mode.

required

Returns:

Type Description
Dict[str, str]

A colour code dictionary.

Source code in src/xpuz/utils.py
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
def _get_colour_palette(
    appearance_mode: Union[
        Literal["Light"], Literal["Dark"], Literal["System"]
    ],
) -> Dict[str, str]:
    """Create a dictionary based on ``constants.Colour`` for the web app.

    Args:
        appearance_mode: The current tkinter appearance mode.

    Returns:
        A colour code dictionary.
    """
    sub_class = Colour.Light if appearance_mode == "Light" else Colour.Dark
    return {
        key: value
        for attr in [sub_class.__dict__, Colour.Global.__dict__]
        for key, value in attr.items()
        if key[0] != "_" or key.startswith("BUTTON")
    }

_get_english_string ¤

_get_english_string(
    eng_arr: List[str],
    localised_arr: List[str],
    index_value: Union[str, int],
) -> str

Find the english version of index_value by finding its index in localised_arr, then using the resulting integer to index eng_arr. This function assumes both arrays have the same relative order.

Parameters:

Name Type Description Default
eng_arr List[str]

The default english values.

required
localised_arr List[str]

The localised values.

required
index_value Union[str, int]

The position of the localised string within localised_arr.

required

Returns:

Type Description
str

The english string that was indexed.

Source code in src/xpuz/utils.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
def _get_english_string(
    eng_arr: List[str], localised_arr: List[str], index_value: Union[str, int]
) -> str:
    """Find the english version of ``index_value`` by finding its index in
    ``localised_arr``, then using the resulting integer to index ``eng_arr``.
    This function assumes both arrays have the same relative order.

    Args:
        eng_arr: The default english values.
        localised_arr: The localised values.
        index_value: The position of the localised string within `localised_arr`.

    Returns:
        The english string that was indexed.
    """
    return eng_arr[localised_arr.index(index_value)]

_get_language_options ¤

_get_language_options() -> Tuple[Dict[str, str], List[str]]

Gather a dictionary that maps each localised language name to its english acronym, and a list that contains all of the localised language names. This data is derived from LOCALES_PATH.

Returns:

Type Description
Tuple[Dict[str, str], List[str]]

The localised language dictionary and the localised languages list.

Source code in src/xpuz/utils.py
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
def _get_language_options() -> Tuple[Dict[str, str], List[str]]:
    """Gather a dictionary that maps each localised language name to its
    english acronym, and a list that contains all of the localised language
    names. This data is derived from ``LOCALES_PATH``.

    Returns:
        The localised language dictionary and the localised languages list.
    """
    localised_lang_db: Dict[str, str] = {}  # Used to retrieve the language
    # code for the selected language
    # e.x. {"አማርኛ": "am",}
    localised_langs: List[str] = []  # Used in the language selection
    # optionmenu
    # e.x. ["አማርኛ", "عربي"]

    i: int = 0
    for locale in sorted(
        [
            f.name
            for f in scandir(LOCALES_PATH)
            if f.is_dir() and "LC_MESSAGES" in listdir(f.path)
        ]
    ):
        try:
            localised_langs.append(Locale.parse(locale).language_name)
            localised_lang_db[localised_langs[i]] = locale
            i += 1
        except UnknownLocaleError:
            pass

    return [localised_lang_db, localised_langs]

_get_open_filename ¤

_get_open_filename(
    title: str, filetypes: List[Tuple[str]]
) -> Union[str, PathLike]

Get user input for the location to a file that is to be opened.

Parameters:

Name Type Description Default
title str

The file explorer's titlebar text.

required
filetypes List[Tuple[str]]

Available filetypes to display.

required
Source code in src/xpuz/utils.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def _get_open_filename(
    title: str, filetypes: List[Tuple[str]]
) -> Union[str, PathLike]:
    """Get user input for the location to a file that is to be opened.

    Args:
        title: The file explorer's titlebar text.
        filetypes: Available filetypes to display.
    """
    return filedialog.askopenfilename(
        title=title,
        initialdir=user_downloads_dir(),
        filetypes=filetypes,
    )

_get_saveas_filename ¤

_get_saveas_filename(
    title: str,
    name: str,
    extension: str,
    filetypes: List[Tuple[str]],
) -> Union[str, PathLike]

Get user input for a file save location.

Parameters:

Name Type Description Default
title str

The file explorer's titlebar text.

required
name str

The default file name.

required
extension str

The file extension.

required
filetypes List[Tuple[str]]

Available filetypes to save the file as.

required
Source code in src/xpuz/utils.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def _get_saveas_filename(
    title: str, name: str, extension: str, filetypes: List[Tuple[str]]
) -> Union[str, PathLike]:
    """Get user input for a file save location.

    Args:
        title: The file explorer's titlebar text.
        name: The default file name.
        extension: The file extension.
        filetypes: Available filetypes to save the file as.
    """
    return filedialog.asksaveasfilename(
        title=title,
        defaultextension=extension,
        filetypes=filetypes,
        initialfile=name + extension,
        initialdir=user_downloads_dir(),
    )

_interpret_cword_data ¤

_interpret_cword_data(
    crossword: Crossword,
) -> Tuple[
    List[Tuple[int]],
    List[Dict[int, Tuple[str]]],
    List[List[int]],
]

Gather data to help with the templated creation of the crossword web application.

Parameters:

Name Type Description Default
crossword Crossword

The Crossword instance to gather data on.

required

Returns:

Type Description
List[Tuple[int]]

The interpreted crossword data. Please view the source code below for

List[Dict[int, Tuple[str]]]

more information.

Source code in src/xpuz/utils.py
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
def _interpret_cword_data(
    crossword: "Crossword",
) -> Tuple[List[Tuple[int]], List[Dict[int, Tuple[str]]], List[List[int]]]:
    """Gather data to help with the templated creation of the crossword
    web application.

    Args:
        crossword: The `Crossword` instance to gather data on.

    Returns:
        The interpreted crossword data. Please view the source code below for
        more information.
    """
    starting_word_positions: List[Tuple[int]] = list(crossword.data.keys())
    # e.x. [(1, 2), (4, 6)]

    definitions_a: List[Dict[int, Tuple[str]]] = []
    definitions_d: List[Dict[int, Tuple[str]]] = []
    # e.x. [{1: ("hello", "a standard english greeting")}]"""

    starting_word_matrix: List[List[int]] = deepcopy(crossword.grid)
    # e.x.: [[1, 0, 0, 0], [[0, 0, 2, 0]] ... and so on; Each incremented
    # number is the start of a new word.

    num_label: int = (
        1  # Incremented whenever the start of a word is found;
        # used to create ``starting_word_matrix``.
    )
    for row in range(crossword.dimensions):
        for column in range(crossword.dimensions):
            if (row, column) in starting_word_positions:
                current_cword_data = crossword.data[(row, column)]

                if current_cword_data["direction"] == ACROSS:
                    definitions_a.append(
                        {
                            num_label: (
                                current_cword_data["word"],
                                current_cword_data["definition"],
                            )
                        }
                    )

                elif current_cword_data["direction"] == DOWN:
                    definitions_d.append(
                        {
                            num_label: (
                                current_cword_data["word"],
                                current_cword_data["definition"],
                            )
                        }
                    )

                starting_word_matrix[row][column] = num_label
                num_label += 1

            else:
                if crossword.grid[row][column] == EMPTY:
                    starting_word_matrix[row][column] = None
                else:
                    starting_word_matrix[row][column] = 0

    return (
        starting_word_positions,
        starting_word_matrix,
        definitions_a,
        definitions_d,
    )

_load_attempts_db ¤

_load_attempts_db() -> Dict[str, int]

Load attempts_db.json, which specifies how many generation attempts should be conducted for a crossword based on its word count. This is integral to the crossword optimisation process, as crossword generation time scales logarithmically with word count.

Returns:

Type Description
Dict[str, int]

The attempts dictionary.

Source code in src/xpuz/utils.py
799
800
801
802
803
804
805
806
807
808
809
810
def _load_attempts_db() -> Dict[str, int]:
    """Load ``attempts_db.json``, which specifies how many generation attempts
    should be conducted for a crossword based on its word count. This is
    integral to the crossword optimisation process, as crossword generation
    time scales logarithmically with word count.

    Returns:
        The attempts dictionary.
    """

    with open(ATTEMPTS_DB_PATH) as file:
        return load(file)

_make_category_info_json ¤

_make_category_info_json(
    fp: PathLike, hex_: str = None
) -> None

Write a new info.json to a category since it does not exist in the a category's directory.

Parameters:

Name Type Description Default
fp PathLike

The path to write the category's info.json file to.

required
hex_ str

A hexadecimal colour value stored in a string, which represents the colour of the category's bottom tag colour.

None
Source code in src/xpuz/utils.py
784
785
786
787
788
789
790
791
792
793
794
795
796
def _make_category_info_json(fp: PathLike, hex_: str = None) -> None:
    """Write a new info.json to a category since it does not exist in the a
    category's directory.

    Args:
        fp: The path to write the category's `info.json` file to.
        hex_: A hexadecimal colour value stored in a string, which represents
              the colour of the category's bottom tag colour.
    """
    if not hex_:
        hex_: str = "#%06X" % randint(0, 0xFFFFFF)
    with open(path.join(fp, "info.json"), "w") as f:
        return dump({"bottom_tag_colour": hex_}, f, indent=4)

_make_cword_info_json ¤

_make_cword_info_json(
    fp: PathLike, cword_name: str, category: str
) -> None

Make an info.json file for a given crossword, since it doesn't exist. Infer any required information that is not passed by the caller.

Parameters:

Name Type Description Default
fp PathLike

The path to write the info to.

required
cword_name str

The name of the crossword.

required
category str

The crossword's category.

required
Source code in src/xpuz/utils.py
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
def _make_cword_info_json(
    fp: PathLike, cword_name: str, category: str
) -> None:
    """Make an info.json file for a given crossword, since it doesn't exist.
    Infer any required information that is not passed by the caller.

    Args:
        fp: The path to write the info to.
        cword_name: The name of the crossword.
        category: The crossword's category.
    """

    with open(path.join(fp, "info.json"), "w") as info_obj, open(
        path.join(fp, "definitions.json"), "r"
    ) as def_obj:
        total_definitions: int = len(load(def_obj))

        # Infer the difficulty and crossword name if possible
        try:
            parsed_cword_name_components: List[str] = path.basename(fp).split(
                "-"
            )
            difficulty: int = DIFFICULTIES.index(
                parsed_cword_name_components[-1].title()
            )
            adjusted_cword_name: str = " ".join(
                parsed_cword_name_components[0:-1]
            ).title()
        except Exception:
            difficulty: int = 0
            adjusted_cword_name: str = cword_name

        return dump(
            CrosswordInfo(
                total_definitions=total_definitions,
                difficulty=difficulty,
                symbol="0x2717",
                name=adjusted_cword_name,
                translated_name="",
                category=category,
            ),
            info_obj,
            indent=4,
        )

_make_doc_cfg ¤

_make_doc_cfg() -> None

Write the contents of template.config.ini into config.ini, located in the system's document directory.

Source code in src/xpuz/utils.py
573
574
575
576
577
578
579
580
def _make_doc_cfg() -> None:
    """Write the contents of ``template.config.ini`` into ``config.ini``, located
    in the system's document directory.
    """
    with open(TEMPLATE_CFG_PATH) as template_cfg, open(
        path.join(DOC_CFG_PATH), "w"
    ) as dest_cfg:
        dest_cfg.write(template_cfg.read())

_open_file ¤

_open_file(fp: PathLike) -> None

Open fp (directory) in the OS' default file explorer.

Parameters:

Name Type Description Default
fp PathLike

The filepath to open.

required
Source code in src/xpuz/utils.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def _open_file(fp: PathLike) -> None:
    """Open ``fp`` (directory) in the OS' default file explorer.

    Args:
        fp: The filepath to open.
    """
    plat: str = system()
    if plat == "Windows":
        from os import startfile

        startfile(fp)
    else:
        from os import system as os_system

        if plat == "Darwin":
            os_system("open %s" % fp)
        elif plat == "Linux":
            os_system("xdg-open %s" % fp)

_randomise_definitions ¤

_randomise_definitions(
    definitions: Dict[str, str]
) -> Dict[str, str]

Randomises the existing definitions when attempting reinsertion, which prevents _find_best_crossword from favouring certain word groups with intrinsically higher intersections.

Parameters:

Name Type Description Default
definitions Dict[str, str]

The crossword's definitions.

required

Returns:

Type Description
Dict[str, str]

The randomised crossword definitions.

Source code in src/xpuz/utils.py
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
def _randomise_definitions(definitions: Dict[str, str]) -> Dict[str, str]:
    """Randomises the existing definitions when attempting reinsertion,
    which prevents ``_find_best_crossword`` from favouring certain word
    groups with intrinsically higher intersections.

    Args:
        definitions: The crossword's definitions.

    Returns:
        The randomised crossword definitions.
    """
    return dict(sample(list(definitions.items()), len(definitions)))

_read_cfg ¤

_read_cfg(cfg: ConfigParser) -> None

Determine which config file to access (whether it is template.config.ini in the package or config.ini in the system documents directory), and write its contents to cfg.

Parameters:

Name Type Description Default
cfg ConfigParser

The config parser instance.

required
Source code in src/xpuz/utils.py
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
def _read_cfg(cfg: ConfigParser) -> None:
    """Determine which config file to access (whether it is
    ``template.config.ini`` in the package or ``config.ini`` in the system
    documents directory), and write its contents to ``cfg``.

    Args:
        cfg: The config parser instance.
    """
    # Documents directory unavailable
    if not _doc_data_routine(doc_callback=_make_doc_cfg):
        return cfg.read(TEMPLATE_CFG_PATH)
    else:
        if not _check_doc_cfg_is_up_to_date():
            _make_doc_cfg()
        return cfg.read(DOC_CFG_PATH)

_sort_crosswords_by_suffix ¤

_sort_crosswords_by_suffix(
    cwords: Union[
        List[DirEntry], List[Tuple[DirEntry, DirEntry]]
    ]
) -> Union[List[DirEntry], List[Tuple[DirEntry, DirEntry]]]

Sort an iterable container with crossword directory entries based on the crossword's suffix (from -easy to -extreme, if possible).

Parameters:

Name Type Description Default
cwords Union[List[DirEntry], List[Tuple[DirEntry, DirEntry]]]

A list of directory entries of crosswords, or an array of tuples with lists of both category entries and crossword entries, if sorting all available crosswords.

required

Returns:

Type Description
Union[List[DirEntry], List[Tuple[DirEntry, DirEntry]]]

The unsorted crosswords if any one of them is missing a suffix, or the

Union[List[DirEntry], List[Tuple[DirEntry, DirEntry]]]

sorted crosswords in the same structure they were passed to the function.

Source code in src/xpuz/utils.py
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
def _sort_crosswords_by_suffix(
    cwords: Union[List[DirEntry], List[Tuple[DirEntry, DirEntry]]],
) -> Union[List[DirEntry], List[Tuple[DirEntry, DirEntry]]]:
    """Sort an iterable container with crossword directory entries based on
    the crossword's suffix (from -easy to -extreme, if possible).

    Args:
        cwords: A list of directory entries of crosswords, or an array of
                tuples with lists of both category entries **and** crossword
                entries, if sorting all available crosswords.

    Returns:
        The unsorted crosswords if any one of them is missing a suffix, or the
        sorted crosswords in the same structure they were passed to the function.
    """
    try:
        return sorted(
            cwords,
            key=lambda cword: DIFFICULTIES.index(
                cword.name.split("-")[-1].capitalize()
                if not isinstance(cwords[0], tuple)
                # Handling an array of tuples, where tup[1] is the crossword name
                else cword[1].name.split("-")[-1].capitalize()
            ),
        )
    except ValueError:  # Don't sort ("-<difficulty>" suffix wasn't found)
        return cwords

_update_cfg ¤

_update_cfg(
    cfg: ConfigParser, section: str, option: str, value: str
) -> None

Update cfg at the given section, option and value, then write it to an available config path.

Parameters:

Name Type Description Default
section str

The section to update.

required
option str

The option to update.

required
value str

The value to write to cfg[section][option].

required
Source code in src/xpuz/utils.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def _update_cfg(
    cfg: ConfigParser, section: str, option: str, value: str
) -> None:
    """Update ``cfg`` at the given section, option and value, then write it
    to an available config path.

    Args:
        section: The section to update.
        option: The option to update.
        value: The value to write to `cfg[section][option]`.
    """
    cfg[section][option] = value

    fp = (
        TEMPLATE_CFG_PATH
        # If ``_doc_data_routine`` returned False, we must use the package
        # config, as the Document config doesn't exist.
        if not _doc_data_routine(doc_callback=_make_doc_cfg)
        else DOC_CFG_PATH
    )

    with open(fp, "w") as f:
        cfg.write(f)

_update_cword_info_word_count ¤

_update_cword_info_word_count(
    fp: PathLike,
    info: CrosswordInfo,
    total_definitions: int,
) -> None

Update the word count in a crossword's info.json file if it is inconsistent with the amount of key-pair values in its definitions.json file.

Parameters:

Name Type Description Default
fp PathLike

The toplevel of the crossword.

required
info CrosswordInfo

The existing info of the crossword.

required
total_definitions int

The "definitions" key as defined in info.

required
Source code in src/xpuz/utils.py
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
def _update_cword_info_word_count(
    fp: PathLike, info: CrosswordInfo, total_definitions: int
) -> None:
    """Update the word count in a crossword's `info.json` file if it is
    inconsistent with the amount of key-pair values in its `definitions.json`
    file.

    Args:
        fp: The toplevel of the crossword.
        info: The existing info of the crossword.
        total_definitions: The `"definitions"` key as defined in `info`.
    """
    with open(path.join(fp, "info.json"), "w") as f:
        info["total_definitions"]: int = total_definitions
        return dump(info, f, indent=4)

_verify_definitions ¤

_verify_definitions(
    definitions: Dict[str, str], word_count: int
) -> None

Process a dictionary of definitions through statements to raise errors for particular edge cases in a definitions dictionary. This function also uses _format_definitions to randomly sample a specified amount of definitions from the definitions dictionary, then format those definitions appropriately.

Parameters:

Name Type Description Default
definitions Dict[str, str]

The crossword's definitions.

required
word_count int

The crossword's word count.

required

Raises:

Type Description
DefinitionsParsingError

If the definitions are invalid. Please view the source code below for more information.

Source code in src/xpuz/utils.py
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
def _verify_definitions(definitions: Dict[str, str], word_count: int) -> None:
    """Process a dictionary of definitions through statements to raise
    errors for particular edge cases in a definitions dictionary. This
    function also uses ``_format_definitions`` to randomly sample a specified
    amount of definitions from the definitions dictionary, then format
    those definitions appropriately.

    Args:
        definitions: The crossword's definitions.
        word_count: The crossword's word count.

    Raises:
        DefinitionsParsingError: If the definitions are invalid. Please view the
                                 source code below for more information.
    """
    # Required error checking
    if not definitions:
        raise DefinitionsParsingError(_("Definitions are empty"))
    if len(definitions) < 3 or word_count < 3:
        raise DefinitionsParsingError(
            _("The word count or definitions are less than 3 in length")
        )
    if len(definitions) < word_count:
        raise DefinitionsParsingError(
            _("Length of the word count is greater than the definitions")
        )
    if any("\\" in word for word in definitions.keys()):
        raise DefinitionsParsingError(_("Escape character present in word"))