Skip to content

Commit 70a4614

Browse files
authored
Remove support for Python 2 (#233)
* remove support for python <= 3.6 * removing python2-compat future imports and utf8 declarations * version bump to 4.1.0 * formatting with black for uniformity * remove u strings, add f strings * more u strings to remove * remove 2.7 from Travis CI
1 parent 84f29f4 commit 70a4614

File tree

17 files changed

+1999
-970
lines changed

17 files changed

+1999
-970
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ group: travis_latest
22
language: python
33
cache: pip
44
python:
5-
- 2.7
65
- 3.6
6+
- 3.8
77
#- nightly
88
#- pypy
99
#- pypy3

bin/cythonize.py

Lines changed: 42 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
2626
Note: this script does not check any of the dependent C++ libraries.
2727
"""
28-
from __future__ import print_function
2928

3029
import os
3130
import sys
@@ -35,41 +34,49 @@
3534
import argparse
3635

3736

38-
HASH_FILE = 'cythonize.json'
37+
HASH_FILE = "cythonize.json"
3938

4039

4140
def process_pyx(fromfile, tofile):
42-
print('Processing %s' % fromfile)
41+
print("Processing %s" % fromfile)
4342
try:
4443
from Cython.Compiler.Version import version as cython_version
4544
from distutils.version import LooseVersion
46-
if LooseVersion(cython_version) < LooseVersion('0.19'):
47-
raise Exception('Require Cython >= 0.19')
45+
46+
if LooseVersion(cython_version) < LooseVersion("0.19"):
47+
raise Exception("Require Cython >= 0.19")
4848

4949
except ImportError:
5050
pass
5151

52-
flags = ['--fast-fail']
53-
if tofile.endswith('.cpp'):
54-
flags += ['--cplus']
52+
flags = ["--fast-fail"]
53+
if tofile.endswith(".cpp"):
54+
flags += ["--cplus"]
5555

5656
try:
5757
try:
58-
r = subprocess.call(['cython'] + flags + ['-o', tofile, fromfile],
59-
env=os.environ) # See Issue #791
58+
r = subprocess.call(
59+
["cython"] + flags + ["-o", tofile, fromfile], env=os.environ
60+
) # See Issue #791
6061
if r != 0:
61-
raise Exception('Cython failed')
62+
raise Exception("Cython failed")
6263
except OSError:
6364
# There are ways of installing Cython that don't result in a cython
6465
# executable on the path, see gh-2397.
65-
r = subprocess.call([sys.executable, '-c',
66-
'import sys; from Cython.Compiler.Main import '
67-
'setuptools_main as main; sys.exit(main())'] + flags +
68-
['-o', tofile, fromfile])
66+
r = subprocess.call(
67+
[
68+
sys.executable,
69+
"-c",
70+
"import sys; from Cython.Compiler.Main import "
71+
"setuptools_main as main; sys.exit(main())",
72+
]
73+
+ flags
74+
+ ["-o", tofile, fromfile]
75+
)
6976
if r != 0:
70-
raise Exception('Cython failed')
77+
raise Exception("Cython failed")
7178
except OSError:
72-
raise OSError('Cython needs to be installed')
79+
raise OSError("Cython needs to be installed")
7380

7481

7582
def preserve_cwd(path, func, *args):
@@ -89,12 +96,12 @@ def load_hashes(filename):
8996

9097

9198
def save_hashes(hash_db, filename):
92-
with open(filename, 'w') as f:
99+
with open(filename, "w") as f:
93100
f.write(json.dumps(hash_db))
94101

95102

96103
def get_hash(path):
97-
return hashlib.md5(open(path, 'rb').read()).hexdigest()
104+
return hashlib.md5(open(path, "rb").read()).hexdigest()
98105

99106

100107
def hash_changed(base, path, db):
@@ -109,25 +116,27 @@ def hash_add(base, path, db):
109116

110117
def process(base, filename, db):
111118
root, ext = os.path.splitext(filename)
112-
if ext in ['.pyx', '.cpp']:
113-
if hash_changed(base, filename, db) or not os.path.isfile(os.path.join(base, root + '.cpp')):
114-
preserve_cwd(base, process_pyx, root + '.pyx', root + '.cpp')
115-
hash_add(base, root + '.cpp', db)
116-
hash_add(base, root + '.pyx', db)
119+
if ext in [".pyx", ".cpp"]:
120+
if hash_changed(base, filename, db) or not os.path.isfile(
121+
os.path.join(base, root + ".cpp")
122+
):
123+
preserve_cwd(base, process_pyx, root + ".pyx", root + ".cpp")
124+
hash_add(base, root + ".cpp", db)
125+
hash_add(base, root + ".pyx", db)
117126

118127

119128
def check_changes(root, db):
120129
res = False
121130
new_db = {}
122131

123-
setup_filename = 'setup.py'
124-
hash_add('.', setup_filename, new_db)
125-
if hash_changed('.', setup_filename, db):
132+
setup_filename = "setup.py"
133+
hash_add(".", setup_filename, new_db)
134+
if hash_changed(".", setup_filename, db):
126135
res = True
127136

128137
for base, _, files in os.walk(root):
129138
for filename in files:
130-
if filename.endswith('.pxd'):
139+
if filename.endswith(".pxd"):
131140
hash_add(base, filename, new_db)
132141
if hash_changed(base, filename, db):
133142
res = True
@@ -150,8 +159,10 @@ def run(root):
150159
save_hashes(db, HASH_FILE)
151160

152161

153-
if __name__ == '__main__':
154-
parser = argparse.ArgumentParser(description='Cythonize pyx files into C++ files as needed')
155-
parser.add_argument('root', help='root directory')
162+
if __name__ == "__main__":
163+
parser = argparse.ArgumentParser(
164+
description="Cythonize pyx files into C++ files as needed"
165+
)
166+
parser.add_argument("root", help="root directory")
156167
args = parser.parse_args()
157168
run(args.root)

examples/server.py

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,21 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
32
"""Coreference resolution server example.
43
A simple server serving the coreference system.
54
"""
6-
from __future__ import unicode_literals
7-
from __future__ import print_function
85

96
import json
107
from wsgiref.simple_server import make_server
118
import falcon
129
import spacy
1310
import neuralcoref
1411

15-
try:
16-
unicode_ = unicode # Python 2
17-
except NameError:
18-
unicode_ = str # Python 3
12+
# Python 3
13+
unicode_ = str
1914

2015

2116
class AllResource(object):
2217
def __init__(self):
23-
self.nlp = spacy.load('en')
18+
self.nlp = spacy.load("en")
2419
neuralcoref.add_to_pipe(self.nlp)
2520
print("Server loaded")
2621
self.response = None
@@ -35,28 +30,34 @@ def on_get(self, req, resp):
3530
text = unicode_(text)
3631
doc = self.nlp(text)
3732
if doc._.has_coref:
38-
mentions = [{'start': mention.start_char,
39-
'end': mention.end_char,
40-
'text': mention.text,
41-
'resolved': cluster.main.text
42-
}
43-
for cluster in doc._.coref_clusters
44-
for mention in cluster.mentions]
45-
clusters = list(list(span.text for span in cluster)
46-
for cluster in doc._.coref_clusters)
33+
mentions = [
34+
{
35+
"start": mention.start_char,
36+
"end": mention.end_char,
37+
"text": mention.text,
38+
"resolved": cluster.main.text,
39+
}
40+
for cluster in doc._.coref_clusters
41+
for mention in cluster.mentions
42+
]
43+
clusters = list(
44+
list(span.text for span in cluster)
45+
for cluster in doc._.coref_clusters
46+
)
4747
resolved = doc._.coref_resolved
48-
self.response['mentions'] = mentions
49-
self.response['clusters'] = clusters
50-
self.response['resolved'] = resolved
48+
self.response["mentions"] = mentions
49+
self.response["clusters"] = clusters
50+
self.response["resolved"] = resolved
5151

5252
resp.body = json.dumps(self.response)
53-
resp.content_type = 'application/json'
54-
resp.append_header('Access-Control-Allow-Origin', "*")
53+
resp.content_type = "application/json"
54+
resp.append_header("Access-Control-Allow-Origin", "*")
5555
resp.status = falcon.HTTP_200
5656

57-
if __name__ == '__main__':
57+
58+
if __name__ == "__main__":
5859
RESSOURCE = AllResource()
5960
APP = falcon.API()
60-
APP.add_route('/', RESSOURCE)
61-
HTTPD = make_server('0.0.0.0', 8000, APP)
61+
APP.add_route("/", RESSOURCE)
62+
HTTPD = make_server("0.0.0.0", 8000, APP)
6263
HTTPD.serve_forever()

neuralcoref/__init__.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,44 @@
1-
# coding: utf8
2-
from __future__ import unicode_literals, absolute_import
3-
41
import os
5-
import shutil
62
import tarfile
7-
import tempfile
83
import logging
94

105
# Filter Cython warnings that would force everybody to re-compile from source (like https://github.com/numpy/numpy/pull/432).
116
import warnings
7+
128
warnings.filterwarnings("ignore", message="spacy.strings.StringStore size changed")
139

1410
from neuralcoref.neuralcoref import NeuralCoref
15-
from neuralcoref.file_utils import NEURALCOREF_MODEL_URL, NEURALCOREF_MODEL_PATH, NEURALCOREF_CACHE, cached_path
11+
from neuralcoref.file_utils import (
12+
NEURALCOREF_MODEL_URL,
13+
NEURALCOREF_MODEL_PATH,
14+
NEURALCOREF_CACHE,
15+
cached_path,
16+
)
1617

17-
__all__ = ['NeuralCoref', 'add_to_pipe']
18-
__version__ = "4.0.0"
18+
__all__ = ["NeuralCoref", "add_to_pipe"]
19+
__version__ = "4.1.0"
1920

2021
logger = logging.getLogger(__name__)
2122

22-
if os.path.exists(NEURALCOREF_MODEL_PATH) and os.path.exists(os.path.join(NEURALCOREF_MODEL_PATH, "cfg")):
23-
logger.info("Loading model from {}".format(NEURALCOREF_MODEL_PATH))
23+
if os.path.exists(NEURALCOREF_MODEL_PATH) and os.path.exists(
24+
os.path.join(NEURALCOREF_MODEL_PATH, "cfg")
25+
):
26+
logger.info(f"Loading model from {NEURALCOREF_MODEL_PATH}")
2427
local_model = cached_path(NEURALCOREF_MODEL_PATH)
2528
else:
2629
if not os.path.exists(NEURALCOREF_MODEL_PATH):
2730
os.makedirs(NEURALCOREF_MODEL_PATH)
28-
logger.info("Getting model from {} or cache".format(NEURALCOREF_MODEL_URL))
31+
logger.info(f"Getting model from {NEURALCOREF_MODEL_URL} or cache")
2932
downloaded_model = cached_path(NEURALCOREF_MODEL_URL)
3033

31-
logger.info("extracting archive file {} to dir {}".format(downloaded_model, NEURALCOREF_MODEL_PATH))
32-
with tarfile.open(downloaded_model, 'r:gz') as archive:
34+
logger.info(
35+
f"extracting archive file {downloaded_model} to dir {NEURALCOREF_MODEL_PATH}"
36+
)
37+
with tarfile.open(downloaded_model, "r:gz") as archive:
3338
archive.extractall(NEURALCOREF_CACHE)
3439

40+
3541
def add_to_pipe(nlp, **kwargs):
3642
coref = NeuralCoref(nlp.vocab, **kwargs)
37-
nlp.add_pipe(coref, name='neuralcoref')
43+
nlp.add_pipe(coref, name="neuralcoref")
3844
return nlp

0 commit comments

Comments
 (0)