Skip to content

Commit bc75aca

Browse files
authored
Code reformat and lint enforcing (#197)
* refactor: reformat code for consistency and readability * correct version
1 parent e4da8bb commit bc75aca

53 files changed

Lines changed: 5801 additions & 4047 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.github/workflows/ci-build-unstable.yml

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,20 +31,18 @@ jobs:
3131
if: runner.os == 'Linux'
3232
run: |
3333
python -m pip install --upgrade pip
34-
pip install flake8
34+
pip install ruff
3535
pip install -e ".[dev,gpu]" --extra-index-url https://download.pytorch.org/whl/cu121
3636
- name: Install dependencies (macOS)
3737
if: runner.os == 'macOS'
3838
run: |
3939
python -m pip install --upgrade pip
40-
pip install flake8
40+
pip install ruff
4141
pip install -e ".[dev]"
42-
- name: Lint with flake8
42+
- name: Lint with ruff
4343
run: |
44-
# stop the build if there are Python syntax errors or undefined names
45-
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
46-
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
47-
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
44+
ruff check .
45+
ruff format --check .
4846
- name: Test with pytest
4947
run: |
5048
pytest

.github/workflows/ci-release.yml

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,20 +29,18 @@ jobs:
2929
if: runner.os == 'Linux'
3030
run: |
3131
python -m pip install --upgrade pip
32-
pip install flake8
32+
pip install ruff
3333
pip install -e ".[dev,gpu]" --extra-index-url https://download.pytorch.org/whl/cu121
3434
- name: Install dependencies (macOS)
3535
if: runner.os == 'macOS'
3636
run: |
3737
python -m pip install --upgrade pip
38-
pip install flake8
38+
pip install ruff
3939
pip install -e ".[dev]"
40-
- name: Lint with flake8
40+
- name: Lint with ruff
4141
run: |
42-
# stop the build if there are Python syntax errors or undefined names
43-
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
44-
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
45-
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
42+
ruff check .
43+
ruff format --check .
4644
- name: Test with pytest
4745
run: |
4846
pytest

delft/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
import os
22

3-
DELFT_PROJECT_DIR = os.path.dirname(__file__)
3+
DELFT_PROJECT_DIR = os.path.dirname(__file__)
Lines changed: 88 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,16 @@
1-
import json
2-
from delft.utilities.Utilities import split_data_and_labels
3-
from delft.textClassification.reader import load_citation_sentiment_corpus
4-
from delft.textClassification import Classifier
51
import argparse
2+
import json
63
import time
4+
5+
from delft.textClassification import Classifier
76
from delft.textClassification.models import architectures
7+
from delft.textClassification.reader import load_citation_sentiment_corpus
8+
from delft.utilities.Utilities import split_data_and_labels
9+
10+
list_classes = ["negative", "neutral", "positive"]
811

9-
list_classes = [
10-
"negative",
11-
"neutral",
12-
"positive"
13-
]
12+
class_weights = {0: 25.0, 1: 1.0, 2: 9.0}
1413

15-
class_weights = {
16-
0: 25.,
17-
1: 1.,
18-
2: 9.
19-
}
2014

2115
def configure(architecture):
2216
batch_size = 256
@@ -37,11 +31,23 @@ def configure(architecture):
3731
def train(embeddings_name, fold_count, architecture="gru", transformer=None):
3832
batch_size, maxlen, patience, early_stop, max_epoch = configure(architecture)
3933

40-
model = Classifier('citations_'+architecture, architecture=architecture, list_classes=list_classes, max_epoch=max_epoch, fold_number=fold_count,
41-
use_roc_auc=True, embeddings_name=embeddings_name, batch_size=batch_size, maxlen=maxlen, patience=patience, early_stop=early_stop,
42-
class_weights=class_weights, transformer_name=transformer)
34+
model = Classifier(
35+
"citations_" + architecture,
36+
architecture=architecture,
37+
list_classes=list_classes,
38+
max_epoch=max_epoch,
39+
fold_number=fold_count,
40+
use_roc_auc=True,
41+
embeddings_name=embeddings_name,
42+
batch_size=batch_size,
43+
maxlen=maxlen,
44+
patience=patience,
45+
early_stop=early_stop,
46+
class_weights=class_weights,
47+
transformer_name=transformer,
48+
)
4349

44-
print('loading citation sentiment corpus...')
50+
print("loading citation sentiment corpus...")
4551
xtr, y = load_citation_sentiment_corpus("data/textClassification/citations/citation_sentiment_corpus.txt")
4652

4753
if fold_count == 1:
@@ -52,14 +58,26 @@ def train(embeddings_name, fold_count, architecture="gru", transformer=None):
5258
model.save()
5359

5460

55-
def train_and_eval(embeddings_name, fold_count, architecture="gru", transformer=None):
61+
def train_and_eval(embeddings_name, fold_count, architecture="gru", transformer=None):
5662
batch_size, maxlen, patience, early_stop, max_epoch = configure(architecture)
5763

58-
model = Classifier('citations_'+architecture, architecture=architecture, list_classes=list_classes, max_epoch=max_epoch, fold_number=fold_count,
59-
use_roc_auc=True, embeddings_name=embeddings_name, batch_size=batch_size, maxlen=maxlen, patience=patience, early_stop=early_stop,
60-
class_weights=class_weights, transformer_name=transformer)
64+
model = Classifier(
65+
"citations_" + architecture,
66+
architecture=architecture,
67+
list_classes=list_classes,
68+
max_epoch=max_epoch,
69+
fold_number=fold_count,
70+
use_roc_auc=True,
71+
embeddings_name=embeddings_name,
72+
batch_size=batch_size,
73+
maxlen=maxlen,
74+
patience=patience,
75+
early_stop=early_stop,
76+
class_weights=class_weights,
77+
transformer_name=transformer,
78+
)
6179

62-
print('loading citation sentiment corpus...')
80+
print("loading citation sentiment corpus...")
6381
xtr, y = load_citation_sentiment_corpus("data/textClassification/citations/citation_sentiment_corpus.txt")
6482

6583
# segment train and eval sets
@@ -69,87 +87,100 @@ def train_and_eval(embeddings_name, fold_count, architecture="gru", transformer=
6987
model.train(x_train, y_train)
7088
else:
7189
model.train_nfold(x_train, y_train)
72-
90+
7391
# saving the model
7492
model.save()
7593

7694
model.eval(x_test, y_test)
7795

78-
96+
7997
# classify a list of texts
8098
def classify(texts, output_format, architecture="gru", embeddings_name=None, transformer=None):
8199
# load model
82-
model = Classifier('citations_'+architecture, architecture=architecture, list_classes=list_classes, embeddings_name=embeddings_name, transformer_name=transformer)
100+
model = Classifier(
101+
"citations_" + architecture,
102+
architecture=architecture,
103+
list_classes=list_classes,
104+
embeddings_name=embeddings_name,
105+
transformer_name=transformer,
106+
)
83107
model.load()
84108
start_time = time.time()
85109
result = model.predict(texts, output_format)
86110
runtime = round(time.time() - start_time, 3)
87-
if output_format == 'json':
111+
if output_format == "json":
88112
result["runtime"] = runtime
89113
else:
90114
print("runtime: %s seconds " % (runtime))
91115
return result
92116

93117

94118
if __name__ == "__main__":
95-
parser = argparse.ArgumentParser(description = "Sentiment classification of citation contexts based on DeLFT")
119+
parser = argparse.ArgumentParser(description="Sentiment classification of citation contexts based on DeLFT")
96120

97-
word_embeddings_examples = ['glove-840B', 'fasttext-crawl', 'word2vec']
98-
pretrained_transformers_examples = [ 'bert-base-cased', 'bert-large-cased', 'allenai/scibert_scivocab_cased' ]
121+
word_embeddings_examples = ["glove-840B", "fasttext-crawl", "word2vec"]
122+
pretrained_transformers_examples = ["bert-base-cased", "bert-large-cased", "allenai/scibert_scivocab_cased"]
99123

100124
parser.add_argument("action", help="one of [train, train_eval, classify]")
101125
parser.add_argument("--fold-count", type=int, default=1)
102-
parser.add_argument("--architecture",default='gru', help="type of model architecture to be used, one of "+str(architectures))
103126
parser.add_argument(
104-
"--embedding",
127+
"--architecture", default="gru", help="type of model architecture to be used, one of " + str(architectures)
128+
)
129+
parser.add_argument(
130+
"--embedding",
105131
default=None,
106-
help="The desired pre-trained word embeddings using their descriptions in the file. " + \
107-
"For local loading, use delft/resources-registry.json. " + \
108-
"Be sure to use here the same name as in the registry, e.g. " + str(word_embeddings_examples) + \
109-
" and that the path in the registry to the embedding file is correct on your system."
132+
help="The desired pre-trained word embeddings using their descriptions in the file. "
133+
+ "For local loading, use delft/resources-registry.json. "
134+
+ "Be sure to use here the same name as in the registry, e.g. "
135+
+ str(word_embeddings_examples)
136+
+ " and that the path in the registry to the embedding file is correct on your system.",
110137
)
111138
parser.add_argument(
112-
"--transformer",
139+
"--transformer",
113140
default=None,
114-
help="The desired pre-trained transformer to be used in the selected architecture. " + \
115-
"For local loading use, delft/resources-registry.json, and be sure to use here the same name as in the registry, e.g. " + \
116-
str(pretrained_transformers_examples) + \
117-
" and that the path in the registry to the model path is correct on your system. " + \
118-
"HuggingFace transformers hub will be used otherwise to fetch the model, see https://huggingface.co/models " + \
119-
"for model names"
141+
help="The desired pre-trained transformer to be used in the selected architecture. "
142+
+ "For local loading use, delft/resources-registry.json, and be sure to use here the same name as in the registry, e.g. "
143+
+ str(pretrained_transformers_examples)
144+
+ " and that the path in the registry to the model path is correct on your system. "
145+
+ "HuggingFace transformers hub will be used otherwise to fetch the model, see https://huggingface.co/models "
146+
+ "for model names",
120147
)
121148

122149
args = parser.parse_args()
123150

124-
if args.action not in ('train', 'train_eval', 'classify'):
125-
print('action not specifed, must be one of [train,train_eval,classify]')
151+
if args.action not in ("train", "train_eval", "classify"):
152+
print("action not specifed, must be one of [train,train_eval,classify]")
126153

127154
embeddings_name = args.embedding
128155
transformer = args.transformer
129-
156+
130157
architecture = args.architecture
131158
if architecture not in architectures:
132-
print('unknown model architecture, must be one of '+str(architectures))
159+
print("unknown model architecture, must be one of " + str(architectures))
133160

134-
if transformer == None and embeddings_name == None:
161+
if transformer is None and embeddings_name is None:
135162
# default word embeddings
136163
embeddings_name = "glove-840B"
137164

138-
if args.action == 'train':
165+
if args.action == "train":
139166
if args.fold_count < 1:
140167
raise ValueError("fold-count should be equal or more than 1")
141168

142169
train(embeddings_name, args.fold_count, architecture=architecture, transformer=transformer)
143170

144-
if args.action == 'train_eval':
171+
if args.action == "train_eval":
145172
if args.fold_count < 1:
146173
raise ValueError("fold-count should be equal or more than 1")
147174

148-
y_test = train_and_eval(embeddings_name, args.fold_count, architecture=architecture, transformer=transformer)
149-
150-
if args.action == 'classify':
151-
someTexts = ['One successful strategy [15] computes the set-similarity involving (multi-word) keyphrases about the mentions and the entities, collected from the KG.',
152-
'Unfortunately, fewer than half of the OCs in the DAML02 OC catalog (Dias et al. 2002) are suitable for use with the isochrone-fitting method because of the lack of a prominent main sequence, in addition to an absence of radial velocity and proper-motion data.',
153-
'However, we found that the pairwise approach LambdaMART [41] achieved the best performance on our datasets among most learning to rank algorithms.']
154-
result = classify(someTexts, "json", architecture=architecture, embeddings_name=embeddings_name, transformer=transformer)
175+
y_test = train_and_eval(embeddings_name, args.fold_count, architecture=architecture, transformer=transformer)
176+
177+
if args.action == "classify":
178+
someTexts = [
179+
"One successful strategy [15] computes the set-similarity involving (multi-word) keyphrases about the mentions and the entities, collected from the KG.",
180+
"Unfortunately, fewer than half of the OCs in the DAML02 OC catalog (Dias et al. 2002) are suitable for use with the isochrone-fitting method because of the lack of a prominent main sequence, in addition to an absence of radial velocity and proper-motion data.",
181+
"However, we found that the pairwise approach LambdaMART [41] achieved the best performance on our datasets among most learning to rank algorithms.",
182+
]
183+
result = classify(
184+
someTexts, "json", architecture=architecture, embeddings_name=embeddings_name, transformer=transformer
185+
)
155186
print(json.dumps(result, sort_keys=False, indent=4, ensure_ascii=False))

0 commit comments

Comments
 (0)