Skip to content

Commit 1509e88

Browse files
authored
Merge pull request andiwand#3 from keachi/master
PEP8 and Python library stuff
2 parents f669f89 + c47a50a commit 1509e88

7 files changed

+214
-100
lines changed

.pre-commit-config.yaml

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
3+
repos:
4+
- repo: local
5+
hooks:
6+
- id: isort
7+
name: isort
8+
entry: isort
9+
language: system
10+
types: [python]

leo.py

-85
This file was deleted.

leo/__init__.py

Whitespace-only changes.

leo/leo.py

+132
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
import argparse
5+
import difflib
6+
import sys
7+
import time
8+
9+
import requests
10+
from bs4 import BeautifulSoup
11+
12+
COUNTRY_CODES = {
13+
'en',
14+
'de',
15+
'fr',
16+
'es',
17+
}
18+
LANGUAGES = {
19+
'en': 'English',
20+
'de': 'German',
21+
'fr': 'French',
22+
'es': 'Spanish',
23+
}
24+
25+
URL = "http://dict.leo.org/dictQuery/m-vocab/{0}/query.xml" \
26+
"?tolerMode=nof&lp={0}&lang=de&rmWords=off&rmSearch=on" \
27+
"&search={1}&searchLoc=0&resultOrder=basic" \
28+
"&multiwordShowSingle=on"
29+
URL_PRONOUNCE = 'http://dict.leo.org/media/audio/{0}.mp3'
30+
31+
32+
def similarity(s1, s2):
33+
return difflib.SequenceMatcher(a=s1.lower(), b=s2.lower()).ratio()
34+
35+
36+
def fetch(phrase, lang):
37+
url = URL.format(lang, phrase)
38+
r = requests.get(url)
39+
soup = BeautifulSoup(r.text, 'xml')
40+
return soup.find_all('entry')
41+
42+
43+
def pronounce(phrase, lang):
44+
entries = fetch(phrase, lang)
45+
if not entries:
46+
return None
47+
result = []
48+
for entry in entries:
49+
for side in entry.find_all('side', lang='en'):
50+
word = side.find('word').get_text()
51+
if not side.find('pron'):
52+
continue
53+
url = side.find('pron')['url']
54+
result.append((word, url))
55+
if not result:
56+
return False
57+
result = [x for x in result if phrase in x[0]]
58+
result.sort(key=lambda x: similarity(x[0], phrase), reverse=True)
59+
pid = result[0][1]
60+
url = URL_PRONOUNCE.format(pid)
61+
play(url)
62+
return True
63+
64+
65+
def translate(phrase, lang):
66+
entries = fetch(phrase, lang)
67+
if not entries:
68+
return None
69+
70+
return [tuple([side.find('word').get_text()
71+
for side in entry.find_all('side')])
72+
for entry in entries]
73+
74+
75+
def play(url):
76+
try:
77+
import vlc
78+
player = vlc.MediaPlayer(url)
79+
player.play()
80+
while player.get_state() not in (
81+
vlc.State.Stopped,
82+
vlc.State.Ended,
83+
vlc.State.Error,
84+
):
85+
time.sleep(0.1)
86+
player.stop()
87+
except ImportError:
88+
sys.stderr.write("Python library vlc not found")
89+
90+
91+
def main(argv=None):
92+
parser = argparse.ArgumentParser(
93+
description='leo dict cli',
94+
)
95+
parser.add_argument(
96+
'-l',
97+
'--language',
98+
help='destination language (default is "%(default)s")',
99+
default='en',
100+
)
101+
parser.add_argument(
102+
'-p',
103+
'--pronounce',
104+
help='pronounce phrase',
105+
action='store_true',
106+
)
107+
parser.add_argument('phrase', help='phrase to translate')
108+
args = parser.parse_args(argv)
109+
110+
phrase, lang = args.phrase, args.language + 'de'
111+
112+
if args.pronounce:
113+
result = pronounce(phrase, lang)
114+
return 0 if result else 1
115+
116+
translations = translate(phrase, lang)
117+
if not translations:
118+
print('no translation found')
119+
return 1
120+
121+
for trans in translations:
122+
print('%s\t\t%s' % trans)
123+
124+
return 0
125+
126+
127+
if __name__ == '__main__':
128+
rcode = main()
129+
sys.exit(rcode)
130+
131+
132+
# vim: set ft=python sw=4 ts=4 et wrap tw=76:

train.py leo/train.py

+35-14
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,49 @@
1-
#!/usr/bin/env python3
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
23

4+
import argparse
5+
import random
36
import sys
47
import time
5-
import random
6-
import argparse
8+
79
import leo
810

11+
912
def main(argv=None):
10-
parser = argparse.ArgumentParser(description='pronunciation training')
11-
parser.add_argument('-s', '--sequential', help='sequential order', action='store_true')
12-
parser.add_argument('-p', '--pronounce', help='pronounce word', action='store_true')
13+
parser = argparse.ArgumentParser(
14+
description='pronunciation training',
15+
)
16+
parser.add_argument(
17+
'-s',
18+
'--sequential',
19+
help='sequential order',
20+
action='store_true',
21+
)
22+
parser.add_argument(
23+
'-p',
24+
'--pronounce',
25+
help='pronounce word',
26+
action='store_true',
27+
)
1328
parser.add_argument('file', help='word list')
1429
args = parser.parse_args(argv)
15-
30+
1631
lang = 'ende'
17-
32+
1833
with open(args.file, 'r') as f:
1934
words = [line.strip() for line in f.readlines() if line.strip()]
20-
if not args.sequential: random.shuffle(words)
21-
35+
if not args.sequential:
36+
random.shuffle(words)
37+
2238
for word in words:
23-
print(word, end='')
39+
sys.stdout.write(word)
2440
input()
25-
41+
2642
subs = [sub.strip() for sub in word.split('/')]
2743
for sub in subs:
28-
if len(subs) > 1: print("%s:" % sub)
44+
subs_len = len(subs)
45+
if subs_len > 1:
46+
print("%s:" % sub)
2947
translations = leo.translate(sub, lang)
3048
if not translations:
3149
print("\tnot found")
@@ -37,10 +55,13 @@ def main(argv=None):
3755
for sub in subs[1:]:
3856
time.sleep(0.3)
3957
leo.pronounce(sub, lang)
40-
58+
4159
return 0
4260

61+
4362
if __name__ == '__main__':
4463
exit = main()
4564
sys.exit(exit)
4665

66+
67+
# vim: set ft=python sw=4 ts=4 et wrap tw=76:

requirements.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
beautifulsoup4>=4.3.0
22
requests>=1.2.3
3-
python-vlc>=1.1.2
3+
lxml>=4.2.4
4+
pre-commit>=1.10.5

setup.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from setuptools import find_packages, setup
2+
3+
setup(
4+
name='leo',
5+
version='1.1',
6+
description='dict.leo.org',
7+
long_description='Leo Dictionary',
8+
classifiers=[
9+
'Development Status :: 4 - Beta',
10+
'License :: OSI Approved :: Apache Software License',
11+
'Operating System :: POSIX :: Linux',
12+
'Programming Language :: Python :: 2.7',
13+
'Programming Language :: Python :: 3.4',
14+
'Programming Language :: Python :: 3.5',
15+
'Programming Language :: Python :: 3.6'
16+
],
17+
keywords='leo',
18+
author='Tobias Rueetschi',
19+
author_email='[email protected]',
20+
url='https://github.com/keachi/pyleo',
21+
license='GPLv3',
22+
packages=find_packages(),
23+
install_requires=[
24+
'beautifulsoup4>=4.3.0',
25+
'requests>=1.2.3',
26+
'lxml>=4.1.1',
27+
],
28+
extras_require={
29+
},
30+
entry_points="""
31+
[console_scripts]
32+
leo=leo.leo:main
33+
train=leo.train:main
34+
"""
35+
)

0 commit comments

Comments
 (0)