-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
164 lines (130 loc) · 6.27 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""
encoding=utf8
author: ashutosh
MIT License
Copyright (c) 2020 Ashutosh
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Notes:
- The dictionary_compact_with_words.json file used in this project is modified
form of dictionary_compact.json file sourced from
https://github.com/matthewreagan/WebstersEnglishDictionary that in turn depends
upon Project Gutenberg's Webster's Unabridged English Dictionary
https://www.gutenberg.org/ebooks/29765.
- The spell.py file used in this project is sourced from Peter Norvig's website
norvig.com http://norvig.com/spell-correct.html. The file is modified for the
current use case.
- Wox documentation on how to create a plugin:
http://doc.wox.one/en/plugin/python_plugin.html
"""
from json import load
from typing import Dict, List
from zipfile import ZipFile
from lib.src.pyperclip import copy
from spell import SpellCorrect
# Wox already contains a python env with `wox` library pre-installed
from wox import Wox
ICON_PATH = "icons\\edict.ico"
DICTIONARY_ZIP_FILE = "dictionary_compact_with_words.zip"
DICTIONARY_JSON_FILE = "dictionary_compact_with_words.json"
MAXIMUM_RESULTS = 4
class EDict(Wox):
"""Easy Dictionary Class used by Wox"""
def __init__(self, *args, **kwargs) -> None:
"""Initializer for `EDict` class"""
with ZipFile(DICTIONARY_ZIP_FILE, "r") as zip_file:
with zip_file.open(DICTIONARY_JSON_FILE) as edict_file:
self._edict = load(edict_file)
# Key "cb2b20da-9168-4e8e-8e8f-9b54e7d42214" gives a list of all words
words = self._edict["cb2b20da-9168-4e8e-8e8f-9b54e7d42214"]
self._spell_correct = SpellCorrect(words)
super().__init__(*args, **kwargs)
def _format_result(self, definitions: str, key: str, max_results: int, correction_flag: bool) -> List[Dict[str, str]]:
"""Adds `max_results` number of definitions from `definitions` formatted for Wox
Args:
definitions (str): String containing all definitions separated by ";"
key (str): Word for which definitions are passed
max_results (int): Maximum number of results to be returned
correction_flag (bool): Whether the key is corrected
Returns:
List[Dict[str, str]]: Returns list of results where each result is a
dictionary containing `Title`, `SubTitle` and `IcoPath`
"""
results: List[Dict[str, str]] = []
for definition in definitions.split(";")[:max_results]:
if definition[0].isdigit():
definition = definition[3:]
try:
definition = definition[: definition.index(".")]
except ValueError:
pass
try:
definition.strip()[0].upper() + definition.strip()[1:]
except IndexError:
pass
# Creating result
result = {
"Title": definition,
"IcoPath": ICON_PATH,
"SubTitle": "Press Enter to Copy",
"JsonRPCAction": {"method": "copy_to_clipboard", "parameters": [definition], "dontHideAfterAction": False},
}
# Showing whether the key has been auto-corrected or not
if correction_flag:
result["SubTitle"] = f"Showing results for '{key}' (auto-corrected)"
else:
result["SubTitle"] = f"Showing results for '{key}'"
results.append(result)
return results
# A function named query is necessary, we will automatically invoke this function
# when user query this plugin
def query(self, key: str) -> List[Dict[str, str]]:
"""Overrides Wox query function to capture user input
Args:
key (str): User search input
Returns:
List[Dict[str, str]]: Returns list of results where each result is a
dictionary.
"""
results: List[Dict[str, str]] = []
key = key.strip().lower()
if not key:
# Avoid looking for empty key
return results
try:
# Look for the given key
definitions = self._edict[key]
results = self._format_result(definitions, key, MAXIMUM_RESULTS, False)
except KeyError:
# Try correcting the key and looking again with the corrected key
try:
corrected_key = self._spell_correct.correction(key)
definitions = self._edict[corrected_key]
results = self._format_result(definitions, corrected_key, MAXIMUM_RESULTS, True)
except KeyError:
# Word doesn't exist in our dictionary
pass
return results
def copy_to_clipboard(self, data: str) -> None:
"""Copies data to Windows clipboard using `pyperclip.copy` command
Args:
data (str): Data that needs to be copied to clipboard
"""
# No viable and safe option as of now
copy(data)
# Following statement is necessary by Wox
if __name__ == "__main__":
EDict()