making it professional, efficient and production ready.
require only the path for input file
3 the clustered csv file and onehot file can be saved in a subfolder of the original input path e.g. /processed/clustered_{originalname}.csv and /processed/onehot_{originalname}.tsv
the lemmatized csv and labels counting csv can be saved just if required by used. always in the /processed/lemmatized.csv path
the cli print should also be saved in a /processed/log_{originalname}.log
this is the code:
import os
import re
import csv
import nltk
import pandas as pd
from collections import defaultdict, Counter
from nltk.stem import WordNetLemmatizer
from gensim.models import KeyedVectors, FastText
from sklearn.cluster import AgglomerativeClustering
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from nltk import pos_tag
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
def load_model(model_type, model_path):
if model_type == 'word2vec':
print("Loading Word2Vec model. This may take a few minutes...")
model = KeyedVectors.load_word2vec_format(model_path, binary=True)
print("Word2Vec model loaded successfully.")
elif model_type == 'glove':
print("Loading GloVe model. This may take a few minutes...")
model = {}
with open(model_path, 'r', encoding='utf-8') as f:
for line in f:
values = line.split()
word = values[0]
vector = np.asarray(values[1:], dtype='float32')
model[word] = vector
print("GloVe model loaded successfully.")
elif model_type == 'fasttext':
print("Loading FastText model. This may take a few minutes...")
model = FastText.load_fasttext_format(model_path)
print("FastText model loaded successfully.")
else:
raise ValueError(f"Unsupported model type: {model_type}")
return model
def get_word_vector(word, model, model_type):
if model_type in ['word2vec', 'fasttext']:
if word in model:
return model[word]
elif model_type == 'glove':
if word in model:
return model[word]
Handle multi-word phrases by averaging their word vectors
words = word.split()
vectors = []
for w in words:
if model_type in ['word2vec', 'fasttext'] and w in model:
vectors.append(model[w])
elif model_type == 'glove' and w in model:
vectors.append(model[w])
if vectors:
return np.mean(vectors, axis=0)
else:
return None
def cluster_infrequent_keywords(keywords, keyword_counts, model, model_type, num_clusters=5, distance_threshold=None):
vectors = []
valid_keywords = []
for keyword in keywords:
vector = get_word_vector(keyword, model, model_type)
if vector is not None:
vectors.append(vector)
valid_keywords.append(keyword)
else:
print(f"Vector not found for keyword: '{keyword}'")
if not vectors:
print("No valid vectors found for clustering.")
return {}
vectors = np.array(vectors)
Perform Hierarchical Clustering with distance threshold
if distance_threshold is not None:
print(f"Performing Agglomerative Clustering with distance_threshold={distance_threshold}")
clustering_model = AgglomerativeClustering(n_clusters=None, distance_threshold=distance_threshold)
else:
print(f"Performing Agglomerative Clustering with n_clusters={num_clusters}")
clustering_model = AgglomerativeClustering(n_clusters=num_clusters)
labels = clustering_model.fit_predict(vectors)
Organize keywords by clusters
clusters = defaultdict(list)
for label, keyword in zip(labels, valid_keywords):
clusters[label].append(keyword)
Select the most frequent keyword in each cluster as the representative
representative_keywords = {}
for label, words in clusters.items():
most_frequent = max(words, key=lambda w: keyword_counts[w])
representative_keywords[label] = most_frequent
Create a mapping from keyword to representative
keyword_to_representative = {}
for label, words in clusters.items():
rep = representative_keywords[label]
for word in words:
keyword_to_representative[word] = rep
return keyword_to_representative
def perform_clustering_with_threshold(keyword_counts, model, model_type, threshold=5, num_clusters=5, distance_threshold=None):
Separate frequent and infrequent keywords
frequent_keywords = [kw for kw, count in keyword_counts.items() if count > threshold]
infrequent_keywords = [kw for kw, count in keyword_counts.items() if count <= threshold]
print(f"Number of frequent keywords (> {threshold}): {len(frequent_keywords)}")
print(f"Number of infrequent keywords (<= {threshold}): {len(infrequent_keywords)}")
Keep frequent keywords as-is
clustered = {kw: kw for kw in frequent_keywords}
Cluster infrequent keywords and map them to their representatives
if infrequent_keywords:
mapping = cluster_infrequent_keywords(
infrequent_keywords, keyword_counts, model, model_type,
num_clusters=num_clusters, distance_threshold=distance_threshold
)
clustered.update(mapping)
print(f"Number of cluster representatives: {len(set(mapping.values()))}")
else:
print("No infrequent keywords to cluster.")
return clustered
------------------------------#
Processing Clustered Data
------------------------------#
def categorize_and_count_clustered_keywords(per_row_df, labels, Category_Limit=50):
category_keyword_counts = {label: Counter() for label in labels}
for idx, row in per_row_df.iterrows():
clustered_keywords = row['Clustered Keywords'].split(', ')
for i, label in enumerate(labels):
if i < len(clustered_keywords):
keyword = clustered_keywords[i]
category_keyword_counts[label][keyword] += 1
Limit to top N keywords per category
for label in labels:
category_keyword_counts[label] = Counter(dict(category_keyword_counts[label].most_common(Category_Limit)))
return category_keyword_counts
def generate_clustered_keywords_and_categories(per_row_df, clustered_keyword_mapping, category_keyword_counts, labels, remove_duplicates=False):
top_keywords_per_category = {label: set(counts.keys()) for label, counts in category_keyword_counts.items()}
Initialize lists for categories and counters for "Other"
category_keywords_list = {label: [] for label in labels}
clustered_keywords_list = []
Initialize a counter for the number of rows with specific "Other" counts
max_other_count = len(labels)
other_count_rows = {i: 0 for i in range(max_other_count + 1)} # from 0 to len(labels)
for idx, row in per_row_df.iterrows():
lemmatized_keywords = row['Lemmatized Keywords'].split(', ')
clustered_keywords = [clustered_keyword_mapping.get(kw, kw) for kw in lemmatized_keywords]
if remove_duplicates:
for i, label in enumerate(labels):
if i < len(clustered_keywords):
keyword = clustered_keywords[i]
Map to 'Other' if not in top keywords
if keyword not in top_keywords_per_category[label]:
keyword = 'Other'
row_other_count += 1 # Increase the row counter for "Other"
category_keywords_list[label].append(keyword)
else:
category_keywords_list[label].append('') # or 'Other'
Count the number of rows with the specific number of "Other" keywords
for label in labels:
per_row_df[label] = category_keywords_list[label]
Optional: Print summary of "Other" counts per category
other_count = {label: 0 for label in labels} # Counter for "Other" per category
print("\nSummary of 'Other' counts per category:")
for label in labels:
other_count[label] = sum(1 for keyword in category_keywords_list[label] if keyword == 'Other')
print(f"{label}: {other_count[label]}")
Print the summary of rows having specific "Other" counts
print("\nSummary of 'Other' count rows:")
for count in range(max_other_count + 1):
print(f"Rows with {count} 'Other' keywords: {other_count_rows[count]}")
return per_row_df
------------------------------#
One-Hot Encoding
------------------------------#
def encode_categorical_features(input_df, output_tsv_path, id_column='Image Name', remove_extension='.jpg', labels=[], sep='\t', header=False, index=False):
"""
Encodes categorical features using One-Hot Encoding and saves them to a TSV file.
"""
if not labels:
raise ValueError("Labels for encoding must be provided.")
Read only the necessary columns to improve efficiency
input_file = '/home/danilo/Projects/IR_MD/utils/_testing_publication_cleaned_code/clothing_qwen_original.csv' # Replace with your actual input file path
Since we are not writing cleaned output to a file, we no longer have 'cleaned_output_file'
The lemmatized_counts_output_file can be saved in the same location as the input file
model_type = 'glove' # Choose from 'word2vec', 'glove', 'fasttext'
model_path = '/home/danilo/Projects/IR_MD/models/glove.6B.300d.word2vec.txt' # Path to your model file
frequency_threshold = 10 # Keywords with count > threshold are kept as-is
num_clusters = 50 # Number of clusters for infrequent keywords
Category_Limit = 100 # Limit to top N keywords per category
distance_threshold = None # Set distance threshold for clustering
remove_duplicates = False # Set to True to remove duplicates in clustered keywords per row
print("Starting lemmatization...")
per_row_df, keyword_counts = lemmatize_keywords(df_clean, lemmatized_counts_output_file)
if per_row_df is None:
return # Exit if there was an error
for category, counts in category_keyword_counts.items():
category_counts_df = pd.DataFrame({'Keyword': list(counts.keys()), 'Count': list(counts.values())})
category_counts_df = category_counts_df.sort_values(by='Count', ascending=False)
category_counts_output_file = os.path.join(input_dir, f'{category}_keywords_counts.csv')
category_counts_df.to_csv(category_counts_output_file, index=False)
print(f"{category} keyword counts saved to '{category_counts_output_file}'.")
------------------------------#
Step 8: Save Results
------------------------------#
per_row_df.to_csv(output_file, index=False)
print(f"\nProcess completed. Output saved to '{output_file}'.")
------------------------------#
Step 9: One-Hot Encoding
------------------------------#
encode_categorical_features(
per_row_df, one_hot_encoded_file,
id_column='Image Name', remove_extension='.jpg',
labels=labels,
sep='\t', header=False, index=False
)
print(f"One-hot encoded features saved to '{one_hot_encoded_file}'.")
if name == "main":
main()
Certainly! Below is the refactored version of your script, enhanced for professionalism, efficiency, and production readiness. This version incorporates all your requested features, including command-line interface (CLI) support, organized logging, structured output directories, and optional saving of intermediate files.
Key Enhancements:
Command-Line Interface (CLI): Utilizes the argparse module to accept the input file path and optional flags for saving intermediate files.
Logging: Implements the logging module to log messages both to the console and a log file within the processed subdirectory.
Output Directory Management: Automatically creates a processed subfolder relative to the input file path to store all output files.
Modular Structure: Organizes the code into functions for better readability and maintenance.
Error Handling: Includes comprehensive error handling to manage exceptions gracefully.
Optional Saving of Intermediate Files: Allows users to decide whether to save the lemmatized CSV and labels counting CSV via command-line flags.
Refactored Code:
python
#!/usr/bin/env python3
"""
Professional Data Processing Pipeline
This script processes a CSV file containing image names and keywords, performing the following steps:
1. Cleans the CSV data.
2. Lemmatizes keywords and counts their occurrences.
3. Loads a pre-trained word embedding model.
4. Clusters infrequent keywords.
5. Categorizes clustered keywords.
6. One-hot encodes categorical features.
7. Saves outputs to a designated 'processed' subdirectory.
Usage:
python data_processing_pipeline.py /path/to/input_file.csv [--save-lemmas] [--save-labels]
Options:
--save-lemmas Save the lemmatized CSV and keyword counts.
--save-labels Save category-specific keyword counts.
"""
import os
import re
import csv
import argparse
import logging
import sys
import io
from collections import defaultdict, Counter
import nltk
import pandas as pd
import numpy as np
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet as wn, stopwords
from nltk import pos_tag
from gensim.models import KeyedVectors, FastText
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import OneHotEncoder
# ------------------------------#
# Setup Logging #
# ------------------------------#
def setup_logging(log_file):
"""
Sets up logging to output messages to both console and a log file.
Args:
log_file (str): Path to the log file.
"""
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# File Handler
fh = logging.FileHandler(log_file, mode='w')
fh.setLevel(logging.INFO)
fh.setFormatter(formatter)
logger.addHandler(fh)
# Console Handler
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
logger.addHandler(ch)
# ------------------------------#
# Download NLTK Data #
# ------------------------------#
def download_nltk_dependencies():
"""
Downloads necessary NLTK data files.
"""
nltk_packages = ['wordnet', 'stopwords', 'averaged_perceptron_tagger']
for package in nltk_packages:
nltk.download(package, quiet=True)
# ------------------------------#
# Cleaning Functions #
# ------------------------------#
def clean_csv(input_file: str, labels: list, logger: logging.Logger) -> pd.DataFrame:
"""
Cleans the input CSV file by processing keywords and removing unwanted rows.
Args:
input_file (str): Path to the input CSV file.
labels (list): List of labels to remove from keywords.
logger (logging.Logger): Logger for logging messages.
Returns:
pd.DataFrame: Cleaned DataFrame with 'Image Name' and 'Keywords'.
"""
logger.info("Starting CSV cleaning...")
total_row_count = 0
empty_row_count = 0
na_count = 0
no_comma_count = 0
no_comma_rows = []
cleaned_data = []
if not os.path.exists(input_file):
logger.error(f"The input file '{input_file}' does not exist.")
raise FileNotFoundError(f"The input file '{input_file}' does not exist.")
with open(input_file, 'r', newline='', encoding='utf-8') as infile:
content = infile.read()
# Remove newline characters inside quoted strings
content = re.sub(r'("\[.*?")\n', r'\1 ', content)
temp_file = io.StringIO(content)
reader = csv.reader(temp_file)
try:
header = next(reader)
except StopIteration:
logger.error("Input CSV is empty.")
raise ValueError("Input CSV is empty.")
for row in reader:
total_row_count += 1
try:
jpg_file, keyword_line = row[0], row[1]
except IndexError:
logger.warning(f"Row {total_row_count} is malformed: {row}")
continue
keywords = extract_keywords(keyword_line, labels)
na_count += keywords.count("N/A")
na_count += sum(1 for k in keywords if k.strip() == "")
if not keywords or all(k.strip().upper() == 'N/A' or k.strip() == '' for k in keywords):
empty_row_count += 1
continue # Skip this row
keywords_str = ', '.join(keywords)
keywords_str = re.sub(r'\s{2,}', ', ', keywords_str)
if ',' not in keywords_str:
no_comma_count += 1
no_comma_rows.append(f'{jpg_file},{keywords_str}')
cleaned_data.append({'Image Name': jpg_file, 'Keywords': keywords_str})
df = pd.DataFrame(cleaned_data)
df = clean_keywords_in_df(df, labels)
logger.info(f"Total rows processed: {total_row_count}")
logger.info(f"Number of empty or N/A rows skipped: {empty_row_count}")
logger.info(f"Occurrences of 'N/A' (including empty spaces): {na_count}")
logger.info(f"Number of rows without commas: {no_comma_count}")
if no_comma_rows:
logger.info("Rows without commas:")
for row in no_comma_rows:
logger.info(row)
logger.info("CSV cleaning completed.")
return df
def clean_keywords_in_df(df: pd.DataFrame, labels: list) -> pd.DataFrame:
"""
Cleans the 'Keywords' column in the DataFrame.
Args:
df (pd.DataFrame): DataFrame with 'Keywords' column.
labels (list): List of labels to remove.
Returns:
pd.DataFrame: DataFrame with cleaned 'Keywords'.
"""
labels_pattern = r'\b(' + '|'.join(map(re.escape, labels)) + r')\b\s*'
df['Keywords'] = df['Keywords'].str.replace(labels_pattern, '', regex=True)
df['Keywords'] = df['Keywords'].str.replace('- ', '', regex=False)
df['Keywords'] = df['Keywords'].str.replace(r"'([^']+)'", r'\1', regex=True)
df['Keywords'] = df['Keywords'].str.replace(r'\s{2,}', ', ', regex=True)
df['Keywords'] = df['Keywords'].str.strip(' ,')
return df
def extract_keywords(line: str, labels: list) -> list:
"""
Extracts keywords from a given line.
Args:
line (str): The keyword line from the CSV.
labels (list): List of labels to remove.
Returns:
list: List of extracted keywords.
"""
keywords = re.findall(r'\{([^}]+)\}', line)
if keywords:
return [kw.strip() for group in keywords for kw in group.split(',')]
line = line.replace('\n', ' ')
for label in labels:
pattern = rf'\b{re.escape(label)}\b[: -]?'
line = re.sub(pattern, '', line, flags=re.IGNORECASE)
line = line.replace('- ', '')
line = re.sub(r"'([^']+)'", r'\1', line)
line = line.replace('[', '').replace(']', '').replace('{', '').replace('}', '')
keywords = [keyword.strip() for keyword in line.split(',')]
return keywords
# ------------------------------#
# Lemmatization Functions #
# ------------------------------#
lemmatizer = WordNetLemmatizer()
stop_words = set(stopwords.words('english'))
def lemmatize_keyword(keyword: str) -> str:
"""
Lemmatizes a single keyword.
Args:
keyword (str): The keyword to lemmatize.
Returns:
str: Lemmatized keyword.
"""
return lemmatizer.lemmatize(keyword.lower())
def get_wordnet_pos(treebank_tag: str):
"""
Maps POS tag to WordNet POS.
Args:
treebank_tag (str): POS tag.
Returns:
wordnet constant or None.
"""
if treebank_tag.startswith('J'):
return wn.ADJ
elif treebank_tag.startswith('V'):
return wn.VERB
elif treebank_tag.startswith('N'):
return wn.NOUN
elif treebank_tag.startswith('R'):
return wn.ADV
else:
return None
def lemmatize_keywords(df: pd.DataFrame, lemmatized_counts_output_file: str, save_lemmas: bool, logger: logging.Logger):
"""
Lemmatizes keywords and counts their occurrences.
Args:
df (pd.DataFrame): DataFrame with 'Image Name' and 'Keywords'.
lemmatized_counts_output_file (str): Path to save lemmatized keyword counts.
save_lemmas (bool): Flag to save lemmatized CSV.
logger (logging.Logger): Logger for logging messages.
Returns:
tuple: (per_row DataFrame with lemmatized keywords, keyword counts)
"""
logger.info("Starting lemmatization...")
per_row_data = []
keyword_counts = Counter()
for index, row in df.iterrows():
image_name = row.get('Image Name', '')
keywords_str = row.get('Keywords', '') or ''
extracted_keywords = [kw.strip() for kw in keywords_str.split(',')]
lemmatized_keywords = [lemmatize_keyword(kw) for kw in extracted_keywords if kw]
keyword_counts.update(lemmatized_keywords)
per_row_data.append({
'Image Name': image_name,
'Keywords': ', '.join(extracted_keywords),
'Lemmatized Keywords': ', '.join(lemmatized_keywords)
})
per_row_df = pd.DataFrame(per_row_data)
if save_lemmas:
lemmatized_counts = [{'Lemmatized Keyword': kw, 'Count': count} for kw, count in keyword_counts.items()]
lemmatized_counts_df = pd.DataFrame(lemmatized_counts)
lemmatized_counts_df = lemmatized_counts_df.sort_values(by='Count', ascending=False)
per_row_df.to_csv(lemmatized_counts_output_file, index=False)
logger.info(f"Lemmatized keyword counts saved to '{lemmatized_counts_output_file}'.")
logger.info("Lemmatization completed.")
return per_row_df, keyword_counts
# ------------------------------#
# Model Loading Functions #
# ------------------------------#
def load_model(model_type: str, model_path: str, logger: logging.Logger):
"""
Loads the specified word embedding model.
Args:
model_type (str): Type of the model ('word2vec', 'glove', 'fasttext').
model_path (str): Path to the model file.
logger (logging.Logger): Logger for logging messages.
Returns:
Model object.
"""
logger.info(f"Loading {model_type} model from '{model_path}'...")
if model_type == 'word2vec':
model = KeyedVectors.load_word2vec_format(model_path, binary=True)
elif model_type == 'glove':
model = {}
with open(model_path, 'r', encoding='utf-8') as f:
for line in f:
values = line.split()
word = values[0]
vector = np.asarray(values[1:], dtype='float32')
model[word] = vector
elif model_type == 'fasttext':
model = FastText.load_fasttext_format(model_path)
else:
logger.error(f"Unsupported model type: {model_type}")
raise ValueError(f"Unsupported model type: {model_type}")
logger.info(f"{model_type.capitalize()} model loaded successfully.")
return model
def get_word_vector(word: str, model, model_type: str, logger: logging.Logger):
"""
Retrieves the vector for a given word from the model.
Args:
word (str): The word to retrieve.
model: The loaded word embedding model.
model_type (str): Type of the model.
Returns:
np.ndarray or None: Word vector or None if not found.
"""
if model_type in ['word2vec', 'fasttext']:
if word in model:
return model[word]
elif model_type == 'glove':
return model.get(word)
# Handle multi-word phrases by averaging their word vectors
words = word.split()
vectors = []
for w in words:
vector = get_word_vector(w, model, model_type, logger)
if vector is not None:
vectors.append(vector)
if vectors:
return np.mean(vectors, axis=0)
else:
logger.debug(f"Vector not found for keyword: '{word}'")
return None
# ------------------------------#
# Clustering Functions #
# ------------------------------#
def cluster_infrequent_keywords(keywords: list, keyword_counts: Counter, model, model_type: str, num_clusters: int, distance_threshold: float, logger: logging.Logger):
"""
Clusters infrequent keywords using hierarchical clustering.
Args:
keywords (list): List of infrequent keywords.
keyword_counts (Counter): Counter of keyword occurrences.
model: Word embedding model.
model_type (str): Type of the model.
num_clusters (int): Number of clusters.
distance_threshold (float): Distance threshold for clustering.
logger (logging.Logger): Logger for logging messages.
Returns:
dict: Mapping from keyword to its cluster representative.
"""
vectors = []
valid_keywords = []
for keyword in keywords:
vector = get_word_vector(keyword, model, model_type, logger)
if vector is not None:
vectors.append(vector)
valid_keywords.append(keyword)
else:
logger.warning(f"Vector not found for keyword: '{keyword}'")
if not vectors:
logger.warning("No valid vectors found for clustering.")
return {}
vectors = np.array(vectors)
if distance_threshold:
logger.info(f"Performing Agglomerative Clustering with distance_threshold={distance_threshold}")
clustering_model = AgglomerativeClustering(n_clusters=None, distance_threshold=distance_threshold)
else:
logger.info(f"Performing Agglomerative Clustering with n_clusters={num_clusters}")
clustering_model = AgglomerativeClustering(n_clusters=num_clusters)
labels = clustering_model.fit_predict(vectors)
clusters = defaultdict(list)
for label, keyword in zip(labels, valid_keywords):
clusters[label].append(keyword)
representative_keywords = {}
for label, words in clusters.items():
most_frequent = max(words, key=lambda w: keyword_counts[w])
representative_keywords[label] = most_frequent
keyword_to_representative = {}
for label, words in clusters.items():
rep = representative_keywords[label]
for word in words:
keyword_to_representative[word] = rep
logger.info(f"Number of cluster representatives: {len(set(representative_keywords.values()))}")
return keyword_to_representative
def perform_clustering_with_threshold(keyword_counts: Counter, model, model_type: str, threshold: int, num_clusters: int, distance_threshold: float, logger: logging.Logger):
"""
Clusters infrequent keywords and maps them to their representatives.
Args:
keyword_counts (Counter): Counter of keyword occurrences.
model: Word embedding model.
model_type (str): Type of the model.
threshold (int): Frequency threshold to distinguish frequent and infrequent keywords.
num_clusters (int): Number of clusters for infrequent keywords.
distance_threshold (float): Distance threshold for clustering.
logger (logging.Logger): Logger for logging messages.
Returns:
dict: Mapping from keyword to its representative.
"""
frequent_keywords = [kw for kw, count in keyword_counts.items() if count > threshold]
infrequent_keywords = [kw for kw, count in keyword_counts.items() if count <= threshold]
logger.info(f"Number of frequent keywords (> {threshold}): {len(frequent_keywords)}")
logger.info(f"Number of infrequent keywords (<= {threshold}): {len(infrequent_keywords)}")
clustered = {kw: kw for kw in frequent_keywords}
if infrequent_keywords:
mapping = cluster_infrequent_keywords(
infrequent_keywords, keyword_counts, model, model_type,
num_clusters=num_clusters, distance_threshold=distance_threshold, logger=logger
)
clustered.update(mapping)
else:
logger.info("No infrequent keywords to cluster.")
return clustered
# ------------------------------#
# Categorization Functions #
# ------------------------------#
def categorize_and_count_clustered_keywords(per_row_df: pd.DataFrame, labels: list, Category_Limit: int, logger: logging.Logger):
"""
Counts clustered keywords per category with a limit on the number of top keywords.
Args:
per_row_df (pd.DataFrame): DataFrame with 'Clustered Keywords'.
labels (list): List of category labels.
Category_Limit (int): Limit on the number of top keywords per category.
logger (logging.Logger): Logger for logging messages.
Returns:
dict: Dictionary with category as key and Counter of keywords as value.
"""
category_keyword_counts = {label: Counter() for label in labels}
for idx, row in per_row_df.iterrows():
clustered_keywords = row['Clustered Keywords'].split(', ')
for i, label in enumerate(labels):
if i < len(clustered_keywords):
keyword = clustered_keywords[i]
category_keyword_counts[label][keyword] += 1
for label in labels:
original_count = len(category_keyword_counts[label])
category_keyword_counts[label] = Counter(dict(category_keyword_counts[label].most_common(Category_Limit)))
logger.info(f"Category '{label}': Reduced from {original_count} to {len(category_keyword_counts[label])} keywords (top {Category_Limit})")
return category_keyword_counts
def generate_clustered_keywords_and_categories(per_row_df: pd.DataFrame, clustered_keyword_mapping: dict, category_keyword_counts: dict, labels: list, remove_duplicates: bool, logger: logging.Logger):
"""
Assigns clustered keywords to categories and handles 'Other' classifications.
Args:
per_row_df (pd.DataFrame): DataFrame with 'Lemmatized Keywords'.
clustered_keyword_mapping (dict): Mapping from keyword to representative.
category_keyword_counts (dict): Counter of keywords per category.
labels (list): List of category labels.
remove_duplicates (bool): Flag to remove duplicates in clustered keywords.
logger (logging.Logger): Logger for logging messages.
Returns:
pd.DataFrame: Updated DataFrame with category columns.
"""
top_keywords_per_category = {label: set(counts.keys()) for label, counts in category_keyword_counts.items()}
category_keywords_list = {label: [] for label in labels}
clustered_keywords_list = []
max_other_count = len(labels)
other_count_rows = {i: 0 for i in range(max_other_count + 1)}
for idx, row in per_row_df.iterrows():
lemmatized_keywords = row['Lemmatized Keywords'].split(', ')
clustered_keywords = [clustered_keyword_mapping.get(kw, kw) for kw in lemmatized_keywords]
if remove_duplicates:
clustered_keywords = list(dict.fromkeys(clustered_keywords))
clustered_keywords_list.append(', '.join(clustered_keywords))
row_other_count = 0
for i, label in enumerate(labels):
if i < len(clustered_keywords):
keyword = clustered_keywords[i]
if keyword not in top_keywords_per_category[label]:
keyword = 'Other'
row_other_count += 1
category_keywords_list[label].append(keyword)
else:
category_keywords_list[label].append('')
if row_other_count <= max_other_count:
other_count_rows[row_other_count] += 1
per_row_df['Clustered Keywords'] = clustered_keywords_list
for label in labels:
per_row_df[label] = category_keywords_list[label]
# Logging summary
logger.info("\nSummary of 'Other' counts per category:")
for label in labels:
other_count = sum(1 for keyword in category_keywords_list[label] if keyword == 'Other')
logger.info(f"{label}: {other_count}")
logger.info("\nSummary of 'Other' count rows:")
for count in range(max_other_count + 1):
logger.info(f"Rows with {count} 'Other' keywords: {other_count_rows[count]}")
return per_row_df
# ------------------------------#
# One-Hot Encoding #
# ------------------------------#
def encode_categorical_features(input_df: pd.DataFrame, output_tsv_path: str, id_column: str, remove_extension: str, labels: list, sep: str, header: bool, index: bool, logger: logging.Logger):
"""
Encodes categorical features using One-Hot Encoding and saves them to a TSV file.
Args:
input_df (pd.DataFrame): DataFrame with categorical features.
output_tsv_path (str): Path to save the encoded TSV file.
id_column (str): Column to be used as identifier.
remove_extension (str): Extension to remove from the identifier.
labels (list): List of labels to encode.
sep (str): Separator for the TSV file.
header (bool): Whether to include headers.
index (bool): Whether to include index.
logger (logging.Logger): Logger for logging messages.
"""
logger.info("Starting One-Hot Encoding...")
if not labels:
logger.error("Labels for encoding must be provided.")
raise ValueError("Labels for encoding must be provided.")
columns_to_encode = labels
columns_to_read = [id_column] + columns_to_encode
df = input_df[columns_to_read]
enc = OneHotEncoder(handle_unknown='ignore', dtype=np.int8)
emb = enc.fit_transform(df[columns_to_encode])
feature_names = enc.get_feature_names_out(columns_to_encode)
emb_df = pd.DataFrame(emb.toarray(), columns=feature_names, dtype=np.int8)
result_df = pd.concat([df[[id_column]].reset_index(drop=True), emb_df.reset_index(drop=True)], axis=1)
if remove_extension:
result_df[id_column] = result_df[id_column].str.replace(remove_extension, '', regex=False)
result_df.to_csv(output_tsv_path, index=index, header=header, sep=sep)
logger.info(f"One-hot encoded features saved to '{output_tsv_path}'.")
# ------------------------------#
# Main Function #
# ------------------------------#
def main():
# ------------------------------#
# Argument Parsing #
# ------------------------------#
parser = argparse.ArgumentParser(description="Professional Data Processing Pipeline")
parser.add_argument("input_file", help="Path to the input CSV file.")
parser.add_argument("--save-lemmas", action="store_true", help="Save the lemmatized CSV and keyword counts.")
parser.add_argument("--save-labels", action="store_true", help="Save category-specific keyword counts.")
args = parser.parse_args()
# ------------------------------#
# Setup Paths #
# ------------------------------#
input_file = os.path.abspath(args.input_file)
input_dir = os.path.dirname(input_file)
input_filename = os.path.basename(input_file)
input_name_no_ext = os.path.splitext(input_filename)[0]
processed_dir = os.path.join(input_dir, 'processed')
os.makedirs(processed_dir, exist_ok=True)
# Output file paths
output_file = os.path.join(processed_dir, f'clustered_{input_filename}')
one_hot_encoded_file = os.path.join(processed_dir, f'onehot_{input_name_no_ext}.tsv')
lemmatized_counts_output_file = os.path.join(processed_dir, 'lemmatized_keyword_counts.csv')
log_file = os.path.join(processed_dir, f'log_{input_name_no_ext}.log')
# ------------------------------#
# Setup Logging #
# ------------------------------#
setup_logging(log_file)
logger = logging.getLogger()
try:
# ------------------------------#
# Download NLTK Data #
# ------------------------------#
download_nltk_dependencies()
# ------------------------------#
# File Paths & Params #
# ------------------------------#
# Clustering parameters
model_type = 'glove' # Choose from 'word2vec', 'glove', 'fasttext'
model_path = '/home/danilo/Projects/IR_MD/models/glove.6B.300d.word2vec.txt' # Update as needed
frequency_threshold = 10 # Keywords with count > threshold are kept as-is
num_clusters = 50 # Number of clusters for infrequent keywords
Category_Limit = 100 # Limit to top N keywords per category
distance_threshold = None # Set distance threshold for clustering
remove_duplicates = False # Set to True to remove duplicates in clustered keywords per row
# Labels (customizable)
labels = ['Type', 'Color', 'Wear Location', 'Material', 'Style'] # Modify as needed
# ------------------------------#
# Step 1: Cleaning #
# ------------------------------#
df_clean = clean_csv(input_file, labels, logger)
# ------------------------------#
# Step 2: Lemmatization #
# ------------------------------#
per_row_df, keyword_counts = lemmatize_keywords(
df_clean, lemmatized_counts_output_file, args.save_lemmas, logger
)
# ------------------------------#
# Step 3: Load Model #
# ------------------------------#
model = load_model(model_type, model_path, logger)
# ------------------------------#
# Step 4: Clustering #
# ------------------------------#
clustered_keyword_mapping = perform_clustering_with_threshold(
keyword_counts, model, model_type,
threshold=frequency_threshold, num_clusters=num_clusters,
distance_threshold=distance_threshold,
logger=logger
)
# ------------------------------#
# Step 5: Clustered Keywords #
# ------------------------------#
per_row_df['Clustered Keywords'] = per_row_df['Lemmatized Keywords'].apply(
lambda kws: ', '.join([clustered_keyword_mapping.get(kw, kw) for kw in kws.split(', ')])
)
# ------------------------------#
# Step 6: Categorization #
# ------------------------------#
category_keyword_counts = categorize_and_count_clustered_keywords(
per_row_df, labels=labels, Category_Limit=Category_Limit, logger=logger
)
# ------------------------------#
# Step 7: Final Processing #
# ------------------------------#
per_row_df = generate_clustered_keywords_and_categories(
per_row_df, clustered_keyword_mapping, category_keyword_counts, labels=labels,
remove_duplicates=remove_duplicates, logger=logger
)
# Optionally, write category counts to CSV files
if args.save_labels:
for category, counts in category_keyword_counts.items():
category_counts_df = pd.DataFrame({'Keyword': list(counts.keys()), 'Count': list(counts.values())})
category_counts_df = category_counts_df.sort_values(by='Count', ascending=False)
category_counts_output_file = os.path.join(processed_dir, f'{category}_keywords_counts.csv')
category_counts_df.to_csv(category_counts_output_file, index=False)
logger.info(f"Category '{category}' keyword counts saved to '{category_counts_output_file}'.")
# ------------------------------#
# Step 8: Save Results #
# ------------------------------#
per_row_df.to_csv(output_file, index=False)
logger.info(f"\nProcess completed. Clustered output saved to '{output_file}'.")
# ------------------------------#
# Step 9: One-Hot Encoding #
# ------------------------------#
encode_categorical_features(
per_row_df, one_hot_encoded_file,
id_column='Image Name', remove_extension='.jpg',
labels=labels,
sep='\t', header=False, index=False, logger=logger
)
except Exception as e:
logger.exception(f"An error occurred: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
Usage Instructions:
Save the Script:
Save the above script to a file, e.g., data_processing_pipeline.py.
Make the Script Executable (Optional):
If you're on a Unix-like system, you can make the script executable:
{category}_keywords_counts.csv: (Optional) Keyword counts per category.
log_{originalname}.log: Log file capturing all CLI print messages.
Additional Notes:
Model Path Configuration:
Ensure that the model_path variable in the script points to the correct location of your pre-trained word embedding model (e.g., GloVe). Update this path as needed:
python
model_path = '/home/danilo/Projects/IR_MD/models/glove.6B.300d.word2vec.txt' # Update as needed
Dependencies:
The script relies on several Python libraries. It's recommended to create a virtual environment and install the required packages:
The script automatically downloads necessary NLTK data packages (wordnet, stopwords, averaged_perceptron_tagger). Ensure you have an active internet connection when running the script for the first time.
Error Handling:
The script includes comprehensive error handling. In case of any errors during processing, detailed stack traces will be logged to both the console and the log file.
Logging:
All significant steps and warnings are logged. You can review the log_{originalname}.log file in the processed directory for a detailed execution trace.
Customization:
Labels: You can modify the labels list in the script to suit your categorization needs:
Clustering Parameters: Adjust frequency_threshold, num_clusters, Category_Limit, and other clustering parameters to fine-tune the clustering behavior.
Performance Considerations:
Loading large word embedding models (like GloVe) can be memory-intensive. Ensure your system has sufficient resources or consider using more efficient model formats or embeddings.
By following the above instructions and utilizing the refactored script, you should have a robust, efficient, and production-ready data processing pipeline tailored to your specific requirements.