Skip to content

Commit 9612776

Browse files
committed
chore: ruff formatting
1 parent 693c56d commit 9612776

9 files changed

Lines changed: 94 additions & 63 deletions

File tree

delft/applications/dataseerClassifier.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,14 @@ def configure(
5353
if learning_rate is not None:
5454
o_learning_rate = learning_rate
5555

56-
return o_batch_size, o_maxlen, o_patience, o_early_stop, o_max_epoch, o_learning_rate
56+
return (
57+
o_batch_size,
58+
o_maxlen,
59+
o_patience,
60+
o_early_stop,
61+
o_max_epoch,
62+
o_learning_rate,
63+
)
5764

5865

5966
def train(

delft/applications/licenseClassifier.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,14 @@ def configure(
8888
if learning_rate is not None:
8989
o_learning_rate = learning_rate
9090

91-
return o_batch_size, o_maxlen, o_patience, o_early_stop, o_max_epoch, o_learning_rate
91+
return (
92+
o_batch_size,
93+
o_maxlen,
94+
o_patience,
95+
o_early_stop,
96+
o_max_epoch,
97+
o_learning_rate,
98+
)
9299

93100

94101
def train(

delft/applications/onnx_export.py

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ class TransformerEncoderWrapper(torch.nn.Module):
9191
def __init__(self, model):
9292
super().__init__()
9393
self.model = model
94-
self.accepts_token_type_ids = getattr(model, 'accepts_token_type_ids', True)
94+
self.accepts_token_type_ids = getattr(model, "accepts_token_type_ids", True)
9595

9696
def forward(self, input_ids, attention_mask, token_type_ids=None):
9797
"""Run transformer encoder to get emissions.
@@ -130,7 +130,7 @@ def export_crf_params(model, output_path: str):
130130
# Handle different CRF implementations
131131
# Standard Contract: crf_params.json MUST contain "transitions" in [from_tag][to_tag] orientation.
132132
# Java Code (CRFDecoder.java) iterates as transitions[prevTag][currentTag].
133-
133+
134134
if hasattr(crf, "crf"):
135135
# Using pytorch-crf wrapper (standard CRF class)
136136
# pytorch-crf stores transitions as [from_tag, to_tag]
@@ -254,15 +254,18 @@ def export_classification_config(model_config, output_path: str):
254254
print(f"Exported classification config to {output_path}")
255255

256256

257-
258257
def export_class_labels(model_config, output_path: str):
259258
"""
260259
Export class labels for text classification model.
261260
"""
262261
labels = {
263262
"labels": model_config.list_classes,
264-
"labelToIndex": {label: idx for idx, label in enumerate(model_config.list_classes)},
265-
"indexToLabel": {idx: label for idx, label in enumerate(model_config.list_classes)},
263+
"labelToIndex": {
264+
label: idx for idx, label in enumerate(model_config.list_classes)
265+
},
266+
"indexToLabel": {
267+
idx: label for idx, label in enumerate(model_config.list_classes)
268+
},
266269
}
267270

268271
with open(output_path, "w") as f:
@@ -288,13 +291,15 @@ def export_tokenizer(tokenizer, output_dir: str):
288291
os.makedirs(output_dir, exist_ok=True)
289292
tokenizer.save_pretrained(output_dir)
290293
print(f"Exported tokenizer to {output_dir}")
291-
294+
292295
# List exported files
293296
for f in os.listdir(output_dir):
294297
print(f" - {f}")
295298

296299

297-
def export_transformer_config(model_config, preprocessor, accepts_token_type_ids: bool, output_path: str):
300+
def export_transformer_config(
301+
model_config, preprocessor, accepts_token_type_ids: bool, output_path: str
302+
):
298303
"""
299304
Export transformer model configuration for Java runtime.
300305
@@ -309,15 +314,16 @@ def export_transformer_config(model_config, preprocessor, accepts_token_type_ids
309314
"architecture": model_config.architecture,
310315
"transformerName": model_config.transformer_name,
311316
"maxSequenceLength": model_config.max_sequence_length,
312-
"useCRF": "CRF" in model_config.architecture or "ChainCRF" in model_config.architecture,
317+
"useCRF": "CRF" in model_config.architecture
318+
or "ChainCRF" in model_config.architecture,
313319
"useChainCRF": "ChainCRF" in model_config.architecture,
314320
"useFeatures": "FEATURES" in model_config.architecture,
315321
"useChar": "CHAR" in model_config.architecture,
316322
"acceptsTokenTypeIds": accepts_token_type_ids,
317323
}
318324

319325
# Add label mappings
320-
if hasattr(preprocessor, 'vocab_tag'):
326+
if hasattr(preprocessor, "vocab_tag"):
321327
config["labelVocab"] = preprocessor.vocab_tag
322328
config["labelIndex"] = {str(k): v for k, v in preprocessor.indice_tag.items()}
323329
config["numLabels"] = len(preprocessor.vocab_tag)
@@ -723,7 +729,7 @@ def export_transformer_to_onnx(
723729
seq_len = max_seq_length
724730
dummy_input_ids = torch.zeros(batch_size, seq_len, dtype=torch.long)
725731
dummy_attention_mask = torch.ones(batch_size, seq_len, dtype=torch.long)
726-
732+
727733
# Prepare inputs and names based on model requirements
728734
if accepts_token_type_ids:
729735
dummy_token_type_ids = torch.zeros(batch_size, seq_len, dtype=torch.long)
@@ -768,23 +774,27 @@ def export_transformer_to_onnx(
768774
print("ONNX transformer model exported successfully")
769775

770776
# Export CRF params if applicable
771-
if hasattr(model, 'crf'):
777+
if hasattr(model, "crf"):
772778
crf_path = os.path.join(output_dir, "crf_params.json")
773779
export_crf_params(model, crf_path)
774780
else:
775781
print("No CRF layer found (softmax output model)")
776782

777783
# Export tokenizer
778784
tokenizer_dir = os.path.join(output_dir, "tokenizer")
779-
if hasattr(preprocessor, 'tokenizer') and preprocessor.tokenizer is not None:
785+
if hasattr(preprocessor, "tokenizer") and preprocessor.tokenizer is not None:
780786
export_tokenizer(preprocessor.tokenizer, tokenizer_dir)
781787
else:
782788
print("Warning: No tokenizer found in preprocessor, skipping tokenizer export")
783-
print(" You may need to load the tokenizer separately using the transformer name")
789+
print(
790+
" You may need to load the tokenizer separately using the transformer name"
791+
)
784792

785793
# Export config
786794
config_path = os.path.join(output_dir, "config.json")
787-
export_transformer_config(model_config, preprocessor, accepts_token_type_ids, config_path)
795+
export_transformer_config(
796+
model_config, preprocessor, accepts_token_type_ids, config_path
797+
)
788798

789799
# Verify ONNX model
790800
try:
@@ -807,7 +817,7 @@ def export_transformer_to_onnx(
807817
print(f" - {sub_item}")
808818
else:
809819
# Show file size for ONNX file
810-
if item.endswith('.onnx'):
820+
if item.endswith(".onnx"):
811821
size_mb = os.path.getsize(item_path) / (1024 * 1024)
812822
print(f" - {item} ({size_mb:.1f} MB)")
813823
else:
@@ -887,7 +897,9 @@ def export_transformer_to_onnx(
887897

888898
def main():
889899
parser = argparse.ArgumentParser(description="Export DeLFT model to ONNX format")
890-
parser.add_argument("model", help="Name of the model (e.g., header, date, dataseer-binary)")
900+
parser.add_argument(
901+
"model", help="Name of the model (e.g., header, date, dataseer-binary)"
902+
)
891903
parser.add_argument(
892904
"--architecture",
893905
required=True,

delft/sequenceLabelling/data_loader.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,7 @@ def create_dataloader(
448448
num_batches = max(1, len(dataset) // batch_size)
449449
if num_workers > num_batches:
450450
import logging
451+
451452
logging.getLogger(__name__).warning(
452453
f"Reducing num_workers from {num_workers} to {num_batches} "
453454
f"(dataset has {len(dataset)} samples, {num_batches} batches)"
@@ -465,14 +466,16 @@ def create_dataloader(
465466
# Each worker must reopen the LMDB environment to get its own handle.
466467
worker_init = None
467468
if embeddings is not None and num_workers > 0:
469+
468470
def lmdb_worker_init_fn(worker_id):
469471
"""Reopen LMDB environment in each worker process for fork safety."""
470472
# Get the dataset from the worker's DataLoader
471473
worker_info = torch.utils.data.get_worker_info()
472474
if worker_info is not None:
473475
dataset = worker_info.dataset
474-
if hasattr(dataset, 'embeddings') and dataset.embeddings is not None:
476+
if hasattr(dataset, "embeddings") and dataset.embeddings is not None:
475477
dataset.embeddings.reopen_lmdb()
478+
476479
worker_init = lmdb_worker_init_fn
477480

478481
return DataLoader(

delft/textClassification/data_loader.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ def create_dataloader(
130130
num_batches = max(1, len(dataset) // batch_size)
131131
if num_workers > num_batches:
132132
import logging
133+
133134
logging.getLogger(__name__).warning(
134135
f"Reducing num_workers from {num_workers} to {num_batches} "
135136
f"(dataset has {len(dataset)} samples, {num_batches} batches)"
@@ -141,13 +142,15 @@ def create_dataloader(
141142
# Each worker must reopen the LMDB environment to get its own handle.
142143
worker_init = None
143144
if embeddings is not None and num_workers > 0:
145+
144146
def lmdb_worker_init_fn(worker_id):
145147
"""Reopen LMDB environment in each worker process for fork safety."""
146148
worker_info = torch.utils.data.get_worker_info()
147149
if worker_info is not None:
148150
dataset = worker_info.dataset
149-
if hasattr(dataset, 'embeddings') and dataset.embeddings is not None:
151+
if hasattr(dataset, "embeddings") and dataset.embeddings is not None:
150152
dataset.embeddings.reopen_lmdb()
153+
151154
worker_init = lmdb_worker_init_fn
152155

153156
loader = DataLoader(

delft/textClassification/trainer.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def evaluate(self, dataloader):
137137
# Calculate ROC-AUC per class with fallback for classes with single label value
138138
total_roc_auc = 0.0
139139
num_classes = y_true.shape[1]
140-
140+
141141
for j in range(num_classes):
142142
if len(np.unique(y_true[:, j])) == 1:
143143
# roc_auc_score sklearn implementation doesn't work when a class has only one label value
@@ -151,8 +151,7 @@ def evaluate(self, dataloader):
151151
except ValueError:
152152
class_roc_auc = 0.0
153153
total_roc_auc += class_roc_auc
154-
154+
155155
roc_auc = total_roc_auc / num_classes
156156

157157
return {"loss": avg_val_loss, "roc_auc": roc_auc}
158-

delft/textClassification/wrapper.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ def train_single(
177177
indices = np.random.permutation(len(x_train))
178178
x_train = x_train[indices]
179179
y_train = y_train[indices]
180-
180+
181181
split_idx = int(len(x_train) * 0.9)
182182
x_valid = x_train[split_idx:]
183183
y_valid = y_train[split_idx:]
@@ -481,12 +481,14 @@ def save(self, dir_path="data/models/textClassification/"):
481481

482482
# Save PyTorch model
483483
torch.save(self.model.state_dict(), os.path.join(directory, self.weight_file))
484-
484+
485485
# Remove the best model checkpoint if it exists
486-
best_model_checkpoint = os.path.join(directory, f"{self.model_config.model_name}_best_model.pth")
486+
best_model_checkpoint = os.path.join(
487+
directory, f"{self.model_config.model_name}_best_model.pth"
488+
)
487489
if os.path.exists(best_model_checkpoint):
488490
os.remove(best_model_checkpoint)
489-
491+
490492
print(f"Model saved to {directory}")
491493

492494
def load(self, dir_path="data/models/textClassification/"):

delft/utilities/Embeddings.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -369,22 +369,22 @@ def get_word_vector_in_memory(self, word):
369369
def reopen_lmdb(self):
370370
"""
371371
Reopen the LMDB environment. This is required for fork-safe multiprocessing.
372-
372+
373373
LMDB environments opened before fork() cannot be safely used in child processes.
374374
Call this method in each worker process (e.g., via DataLoader's worker_init_fn)
375375
to create a fresh LMDB environment handle for the worker.
376-
376+
377377
This is a no-op if embeddings are not using LMDB (e.g., in-memory or bin format).
378378
"""
379379
if self.env is None or self.embedding_lmdb_path is None:
380380
# Not using LMDB, nothing to do
381381
return
382-
382+
383383
try:
384384
self.env.close()
385385
except:
386386
pass # May already be closed or invalid after fork
387-
387+
388388
envFilePath = os.path.join(self.embedding_lmdb_path, self.name)
389389
self.env = lmdb.open(
390390
envFilePath,

0 commit comments

Comments
 (0)