Skip to content

Commit 2c9bbc8

Browse files
committed
A logger file has been added for log management.
1 parent dc0ca5c commit 2c9bbc8

File tree

4 files changed

+34
-44
lines changed

4 files changed

+34
-44
lines changed

tasnif/calculations.py

+5-13
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,8 @@
1-
import logging
2-
31
import numpy as np
42
from img2vec_pytorch import Img2Vec
5-
from rich.logging import RichHandler
63
from scipy.cluster.vq import kmeans2
74
from sklearn.decomposition import PCA
8-
9-
# Configure logging
10-
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
11-
logging.basicConfig(
12-
level="INFO", format=LOG_FORMAT, datefmt="[%X]", handlers=[RichHandler()]
13-
)
5+
from .logger import info
146

157

168
def get_embeddings(use_gpu=False, images=None):
@@ -19,7 +11,7 @@ def get_embeddings(use_gpu=False, images=None):
1911
image embeddings.
2012
"""
2113

22-
logging.info(f"Img2Vec is running on {'GPU' if use_gpu else 'CPU'}...")
14+
info(f"Img2Vec is running on {'GPU' if use_gpu else 'CPU'}...")
2315
img2vec = Img2Vec(cuda=use_gpu)
2416

2517
embeddings = img2vec.get_vec(images, tensor=False)
@@ -44,7 +36,7 @@ def calculate_pca(embeddings, pca_dim):
4436
n_samples, _ = embeddings.shape
4537
if n_samples < pca_dim:
4638
n_components = min(n_samples, pca_dim)
47-
logging.info(
39+
info(
4840
f"Number of samples is less than the desired dimension. Setting n_components to {n_components}"
4941
)
5042

@@ -53,7 +45,7 @@ def calculate_pca(embeddings, pca_dim):
5345

5446
pca = PCA(n_components=n_components)
5547
pca_embeddings = pca.fit_transform(embeddings.squeeze())
56-
logging.info("PCA calculated.")
48+
info("PCA calculated.")
5749
return pca_embeddings
5850

5951

@@ -74,7 +66,7 @@ def calculate_kmeans(pca_embeddings, num_classes):
7466
try:
7567
centroid, labels = kmeans2(data=pca_embeddings, k=num_classes, minit="points")
7668
counts = np.bincount(labels)
77-
logging.info("KMeans calculated.")
69+
info("KMeans calculated.")
7870
return centroid, labels, counts
7971

8072
except Exception as e:

tasnif/logger.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import logging
2+
from rich.logging import RichHandler
3+
4+
log_format = "%(asctime)s - %(levelname)s - %(message)s"
5+
logging.basicConfig(
6+
level="INFO", format=log_format, datefmt="[%X]", handlers=[RichHandler(show_time=False, show_level=False)]
7+
)
8+
9+
10+
def info(msg):
11+
logging.info(msg)
12+
13+
14+
def error(msg):
15+
logging.error(msg)
16+
17+
18+
if __name__ == '__main__':
19+
info("info message")
20+
error("error message")

tasnif/tasnif.py

+6-20
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,21 @@
1-
import logging
21
import os
32
import shutil
43
import warnings
54
from itertools import compress
65
import numpy as np
7-
8-
from rich.logging import RichHandler
96
from tqdm import tqdm
10-
117
from .calculations import calculate_kmeans, calculate_pca, get_embeddings
128
from .utils import (
139
create_dir,
1410
create_image_grid,
1511
read_images_from_directory,
1612
read_with_pil,
1713
)
14+
from .logger import info, error
1815

1916
warnings.filterwarnings("ignore")
2017

2118

22-
# Configure logging
23-
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
24-
logging.basicConfig(
25-
level="INFO", format=LOG_FORMAT, datefmt="[%X]", handlers=[RichHandler()]
26-
)
27-
28-
2919
class Tasnif:
3020
def __init__(self, num_classes, pca_dim=16, use_gpu=False):
3121
self.num_classes = num_classes
@@ -93,16 +83,13 @@ def export(self, output_folder="./"):
9383
try:
9484
shutil.copy2(img_path, target_directory)
9585
except Exception as e:
96-
logging.error(
97-
f"Error copying {img_path} to {target_directory}: {e}"
98-
)
86+
error(f"Error copying {img_path} to {target_directory}: {e}")
9987

10088
# Create an image grid for the current label
10189
label_images = list(compress(self.images, label_mask))
10290
create_image_grid(label_images, project_path, label_number)
10391

104-
logging.info(f"Exported images and grids to {project_path}")
105-
92+
info(f"Exported images and grids to {project_path}")
10693

10794
def export_embeddings(self, output_folder="./"):
10895
"""
@@ -111,11 +98,10 @@ def export_embeddings(self, output_folder="./"):
11198
Parameters:
11299
- output_folder (str): The directory to export the embeddings into.
113100
"""
114-
101+
115102
if self.embeddings is None:
116103
raise ValueError("Embeddings can not be empty. Please call the calculate method first.")
117-
118-
104+
119105
embeddings_path = os.path.join(output_folder, f"{self.project_name}_embeddings.npy")
120106
np.save(embeddings_path, self.embeddings)
121-
logging.info(f"Embeddings have been saved to {embeddings_path}")
107+
info(f"Embeddings have been saved to {embeddings_path}")

tasnif/utils.py

+3-11
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,10 @@
11
import glob
2-
import logging
32
import os
43
from pathlib import Path
5-
64
import matplotlib.pyplot as plt
75
from PIL import Image
8-
from rich.logging import RichHandler
96
from tqdm import tqdm
10-
11-
# Configure logging
12-
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
13-
logging.basicConfig(
14-
level="INFO", format=LOG_FORMAT, datefmt="[%X]", handlers=[RichHandler()]
15-
)
7+
from .logger import info
168

179

1810
def read_images_from_directory(image_directory: str) -> list:
@@ -25,7 +17,7 @@ def read_images_from_directory(image_directory: str) -> list:
2517
image_extensions = ("*.gif", "*.png", "*.jpg", "*.jpeg")
2618
for ext in image_extensions:
2719
list_of_images.extend(glob.glob(os.path.join(image_directory, ext)))
28-
logging.info(f"Images found: {len(list_of_images)}")
20+
info(f"Images found: {len(list_of_images)}")
2921
return list_of_images
3022

3123

@@ -42,7 +34,7 @@ def read_with_pil(list_of_images: list, resize=True) -> list:
4234
if resize:
4335
img.thumbnail((512, 512))
4436
pil_images.append(img)
45-
logging.info("Image reading done!")
37+
info("Image reading done!")
4638
return pil_images
4739

4840

0 commit comments

Comments
 (0)