import os
import re
import csv
import argparse
import logging
import nltk
import pandas as pd
from collections import defaultdict, Counter
from nltk.stem import WordNetLemmatizer
from sklearn.cluster import AgglomerativeClustering
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords
import spacy
import torch
def download_nltk_data():
"""
Ensures that required NLTK data packages are downloaded.
"""
logging.info("Downloading necessary NLTK data packages...")
nltk_data_packages = ['wordnet', 'stopwords']
for package in nltk_data_packages:
try:
nltk.data.find(f'corpora/{package}')
logging.info(f"NLTK package '{package}' is already downloaded.")
except LookupError:
logging.info(f"Downloading NLTK package '{package}'...")
nltk.download(package)
logging.info("All necessary NLTK data packages are downloaded.")
def parse_arguments():
"""
Parses command-line arguments.
"""
parser = argparse.ArgumentParser(description='Process and cluster keywords from a CSV file.')
parser.add_argument('--input_file', type=str, required=True, help='Path to the input CSV file.')
parser.add_argument('--save_lemmatized', action='store_true', help='Save lemmatized keywords and counts.')
parser.add_argument('--frequency_threshold', type=int, default=10,
help='Frequency threshold for keywords. Default is 10.')
parser.add_argument('--num_clusters', type=int, default=50,
help='Number of clusters for infrequent keywords. Default is 50.')
parser.add_argument('--distance_threshold', type=float, default=None,
help='Distance threshold for clustering. Overrides num_clusters if set.')
parser.add_argument('--category_limit', type=int, default=100,
help='Limit of top N keywords per category. Default is 100.')
parser.add_argument('--remove_duplicates', action='store_true',
help='Remove duplicates in clustered keywords per row.')
parser.add_argument('--use_gpu', action='store_true',
help='Use GPU for processing if available.')
return parser.parse_args()
def setup_logging(processed_dir, input_name_no_ext):
"""
Sets up logging configuration.
"""
log_file = os.path.join(processed_dir, f'log_{input_name_no_ext}.log')
logging.basicConfig(filename=log_file, level=logging.INFO,
format='%(asctime)s %(levelname)s:%(message)s')
# Also log to stdout
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_formatter = logging.Formatter('%(asctime)s %(levelname)s:%(message)s')
console_handler.setFormatter(console_formatter)
logging.getLogger().addHandler(console_handler)
logging.info(f"Logging initialized. Log file at '{log_file}'.")
def load_spacy_model(use_gpu):
"""
Loads the SpaCy transformer model with GPU support if available.
"""
logging.info("Loading SpaCy transformer model...")
try:
nlp = spacy.load("en_core_web_trf")
logging.info("SpaCy 'en_core_web_trf' model loaded successfully.")
except OSError:
logging.error("SpaCy model 'en_core_web_trf' not found. Please install it using:")
logging.error("python -m spacy download en_core_web_trf")
raise
if use_gpu and torch.cuda.is_available():
logging.info("GPU detected. Enabling GPU for SpaCy.")
spacy.require_gpu()
else:
if use_gpu:
logging.warning("GPU flag is set but no GPU detected. Running on CPU.")
logging.info("Running SpaCy on CPU.")
return nlp
def main():
# Parse command-line arguments
args = parse_arguments()
input_file = args.input_file
save_lemmatized = args.save_lemmatized
frequency_threshold = args.frequency_threshold
num_clusters = args.num_clusters
distance_threshold = args.distance_threshold
category_limit = args.category_limit
remove_duplicates = args.remove_duplicates
use_gpu = args.use_gpu
# Check if input file exists
if not os.path.exists(input_file):
raise FileNotFoundError(f"Input file '{input_file}' does not exist.")
# Set up directories and logging
input_dir = os.path.dirname(os.path.abspath(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)
setup_logging(processed_dir, input_name_no_ext)
logging.info(f"Processing input file: {input_file}")
# Download NLTK data if necessary
download_nltk_data()
# Initialize the lemmatizer
lemmatizer = WordNetLemmatizer()
# Set of stopwords to filter out
stop_words = set(stopwords.words('english'))
# Labels (customizable)
labels = ['Type', 'Color', 'Wear Location', 'Material', 'Style'] # Modify as needed
# Define 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, f'lemmatized_keyword_counts.csv')
# Load SpaCy model
nlp = load_spacy_model(use_gpu)
# ------------------------------#
# Step 1: Cleaning #
# ------------------------------#
logging.info("Step 1: Starting CSV cleaning...")
df_clean, cleaning_summary = clean_csv(input_file, labels)
logging.info("Step 1: CSV cleaning completed.")
log_summary("CSV Cleaning Summary", cleaning_summary)
# ------------------------------#
# Step 2: Lemmatization #
# ------------------------------#
logging.info("Step 2: Starting lemmatization...")
if save_lemmatized:
per_row_df, keyword_counts, lemmatization_summary = lemmatize_keywords(df_clean, lemmatized_counts_output_file, lemmatizer, nlp)
else:
per_row_df, keyword_counts, lemmatization_summary = lemmatize_keywords(df_clean, None, lemmatizer, nlp)
# Check if per_row_df is None
if per_row_df is None:
logging.error("Error in lemmatization.")
return
logging.info("Step 2: Lemmatization completed.")
log_summary("Lemmatization Summary", lemmatization_summary)
# ------------------------------#
# Step 3: Load Model #
# ------------------------------#
logging.info("Step 3: Loading SpaCy model for embeddings completed.")
# ------------------------------#
# Step 4: Clustering #
# ------------------------------#
logging.info("Step 4: Starting clustering of keywords...")
clustered_keyword_mapping, clustering_summary = perform_clustering_with_threshold(
keyword_counts, nlp, threshold=frequency_threshold, num_clusters=num_clusters,
distance_threshold=distance_threshold
)
logging.info("Step 4: Clustering completed.")
log_summary("Clustering Summary", clustering_summary)
# ------------------------------#
# Step 5: Clustered Keywords #
# ------------------------------#
logging.info("Step 5: Assigning clustered keywords to rows...")
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(', ')])
)
logging.info("Step 5: Clustered keywords assigned.")
# ------------------------------#
# Step 6: Categorization #
# ------------------------------#
logging.info("Step 6: Starting categorization of clustered keywords...")
category_keyword_counts, categorization_summary = categorize_and_count_clustered_keywords(
per_row_df, labels=labels, category_limit=category_limit
)
logging.info("Step 6: Categorization completed.")
log_summary("Categorization Summary", categorization_summary)
# ------------------------------#
# Step 7: Final Processing #
# ------------------------------#
logging.info("Step 7: Starting final processing and category assignments...")
per_row_df, final_processing_summary = generate_clustered_keywords_and_categories(
per_row_df, clustered_keyword_mapping, category_keyword_counts, labels=labels,
remove_duplicates=remove_duplicates
)
logging.info("Step 7: Final processing completed.")
log_summary("Final Processing Summary", final_processing_summary)
# Optionally, write category counts to CSV files
if save_lemmatized:
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)
logging.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)
logging.info(f"Step 8: Process completed. Output saved to '{output_file}'.")
# ------------------------------#
# Step 9: One-Hot Encoding #
# ------------------------------#
logging.info("Step 9: Starting one-hot encoding of categorical features...")
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
)
logging.info(f"Step 9: One-hot encoded features saved to '{one_hot_encoded_file}'.")
logging.info("All processing steps completed successfully.")
def log_summary(title, summary_dict):
"""
Logs the summary of a processing step.
"""
logging.info(f"\n{title}:")
for key, value in summary_dict.items():
logging.info(f" - {key}: {value}")
logging.info("")
def clean_csv(input_file, labels):
"""
Cleans the input CSV file and returns a DataFrame along with a summary.
"""
logging.info("Cleaning CSV data...")
total_row_count = 0
empty_row_count = 0
na_count = 0
no_comma_count = 0
no_comma_rows = []
cleaned_data = []
cleaning_summary = {}
# Read the entire content of the file
try:
with open(input_file, 'r', newline='', encoding='utf-8') as infile:
content = infile.read()
logging.info("Input file read successfully.")
except Exception as e:
logging.error(f"Error reading input file: {e}")
return None, cleaning_summary
# Remove newline characters inside quoted strings
content = re.sub(r'("\[.*?")\n', r'\1 ', content)
logging.info("Newline characters inside quoted strings removed.")
# Use StringIO to read the cleaned content as a CSV
import io
temp_file = io.StringIO(content)
reader = csv.reader(temp_file)
# Skip the first line (header)
try:
header = next(reader)
logging.info(f"Header extracted: {header}")
except StopIteration:
logging.error("Input file is empty.")
return None, cleaning_summary
# Process each row
for row in reader:
total_row_count += 1
if not row:
continue
jpg_file = row[0]
if len(row) < 2:
logging.warning(f"Row {total_row_count} doesn't have enough columns: {row}")
keywords = []
else:
keywords = extract_keywords(row[1], labels)
# Count occurrences of "N/A" and empty spaces
na_count += keywords.count("N/A")
na_count += sum(1 for k in keywords if k.strip() == "")
# Check if the row is empty or contains only "N/A" or empty spaces
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
# Concatenate the keywords into a single string
keywords_str = ', '.join(keywords)
# Replace multiple spaces with a comma and a single space
keywords_str = re.sub(r'\s{2,}', ', ', keywords_str)
# Check if the row has no commas
if ',' not in keywords_str:
no_comma_count += 1
no_comma_rows.append(f'{jpg_file},{keywords_str}')
# Add to cleaned data
cleaned_data.append({'Image Name': jpg_file, 'Keywords': keywords_str})
# Now, create a DataFrame from the cleaned_data
df = pd.DataFrame(cleaned_data)
# Clean the 'Keywords' column further
df = clean_keywords_in_df(df, labels)
# Prepare cleaning summary
cleaning_summary['Total Rows Processed'] = total_row_count
cleaning_summary['Empty or N/A Rows'] = empty_row_count
cleaning_summary['Occurrences of N/A (including empty spaces)'] = na_count
cleaning_summary['Rows without Commas'] = no_comma_count
if no_comma_rows:
cleaning_summary['Sample Rows without Commas'] = '; '.join(no_comma_rows[:5]) + ("..." if len(no_comma_rows) > 5 else "")
logging.info("CSV cleaning completed.")
return df, cleaning_summary
def extract_keywords(line, labels):
"""
Extracts keywords from a line.
"""
# First, try to extract keywords between curly braces
keywords = re.findall(r'\{([^}]+)\}', line)
if keywords:
# Further split if multiple keywords are within braces
return [kw.strip() for group in keywords for kw in group.split(',')]
# Remove newline characters from the keywords section
line = line.replace('\n', ' ')
# Remove the labels using word boundaries and considering possible formats
for label in labels:
# Patterns like "Label:", "Label -", "[Label]:", etc.
pattern = rf'\b{re.escape(label)}\b[: -]?'
line = re.sub(pattern, '', line, flags=re.IGNORECASE)
# Remove any '- ' (dash and space) using exact string replacement
line = line.replace('- ', '')
# Remove single quotes around keywords using regex
line = re.sub(r"'([^']+)'", r'\1', line)
# Remove any remaining brackets
line = line.replace('[', '').replace(']', '').replace('{', '').replace('}', '')
# Split keywords by commas and strip whitespace
keywords = [keyword.strip() for keyword in line.split(',')]
return keywords
def clean_keywords_in_df(df, labels):
"""
Cleans the 'Keywords' column in the DataFrame.
"""
logging.info("Cleaning 'Keywords' column in DataFrame...")
# Construct a regex pattern from the labels with word boundaries
labels_pattern = r'\b(' + '|'.join(map(re.escape, labels)) + r')\b\s*'
# Replace labels with an empty string using regex
df['Keywords'] = df['Keywords'].str.replace(labels_pattern, '', regex=True)
# Remove any '- ' (dash and space)
df['Keywords'] = df['Keywords'].str.replace('- ', '', regex=False)
# Remove single quotes around keywords
df['Keywords'] = df['Keywords'].str.replace(r"'([^']+)'", r'\1', regex=True)
# Replace multiple spaces with a comma and a single space
df['Keywords'] = df['Keywords'].str.replace(r'\s{2,}', ', ', regex=True)
# Remove leading/trailing commas and spaces
df['Keywords'] = df['Keywords'].str.strip(' ,')
logging.info("'Keywords' column cleaned.")
return df
def lemmatize_keywords(df, lemmatized_counts_output_file, lemmatizer, nlp):
"""
Lemmatizes the keywords in the DataFrame and returns a DataFrame with lemmatized keywords,
keyword counts, and a summary.
"""
logging.info("Lemmatizing keywords...")
per_row_data = []
keyword_counts = Counter()
lemmatization_summary = {}
# Extract unique keywords to minimize SpaCy processing
unique_keywords = set()
for keywords_str in df['Keywords']:
if pd.isna(keywords_str):
continue
extracted_keywords = [kw.strip() for kw in keywords_str.split(',')]
unique_keywords.update(extracted_keywords)
logging.info(f"Unique keywords extracted for lemmatization: {len(unique_keywords)}")
# Process keywords in batches using SpaCy for efficiency
batch_size = 1000
keyword_to_lemmatized = {}
keywords_list = list(unique_keywords)
for i in range(0, len(keywords_list), batch_size):
batch = keywords_list[i:i + batch_size]
docs = list(nlp.pipe(batch, disable=["parser", "ner"]))
for doc, original_kw in zip(docs, batch):
lemmatized = lemmatizer.lemmatize(doc.text.lower())
keyword_to_lemmatized[original_kw] = lemmatized
logging.info(f"Lemmatized batch {i // batch_size + 1} / {((len(keywords_list)-1) // batch_size) +1}")
# Now, iterate through each row and apply lemmatization
for index, row in df.iterrows():
image_name = row.get('Image Name', '')
keywords_str = row.get('Keywords', '')
if pd.isna(keywords_str):
keywords_str = ''
# Split keywords by comma and strip whitespace
extracted_keywords = [kw.strip() for kw in keywords_str.split(',')]
# Lemmatize keywords using the preprocessed mapping
lemmatized_keywords = [keyword_to_lemmatized.get(kw, kw.lower()) for kw in extracted_keywords if kw]
# Update global counts
keyword_counts.update(lemmatized_keywords)
# Store per-row data
per_row_data.append({
'Image Name': image_name,
'Keywords': ', '.join(extracted_keywords),
'Lemmatized Keywords': ', '.join(lemmatized_keywords)
})
# Create a DataFrame from per_row_data
per_row_df = pd.DataFrame(per_row_data)
if lemmatized_counts_output_file:
# Write the lemmatized keyword counts to CSV
lemmatized_counts = [{'Lemmatized Keyword': kw, 'Count': count}
for kw, count in keyword_counts.items()]
lemmatized_counts_df = pd.DataFrame(lemmatized_counts)
# Sort by Count in descending order
lemmatized_counts_df = lemmatized_counts_df.sort_values(by='Count', ascending=False)
# Write to CSV
lemmatized_counts_df.to_csv(lemmatized_counts_output_file, index=False)
logging.info(f"Lemmatized keyword counts saved to '{lemmatized_counts_output_file}'.")
# Prepare lemmatization summary
lemmatization_summary['Total Unique Keywords'] = len(unique_keywords)
lemmatization_summary['Total Lemmatized Keywords'] = len(keyword_counts)
lemmatization_summary['Top 5 Lemmatized Keywords'] = '; '.join([f"{kw} ({cnt})" for kw, cnt in keyword_counts.most_common(5)])
logging.info("Lemmatization completed.")
return per_row_df, keyword_counts, lemmatization_summary
def perform_clustering_with_threshold(keyword_counts, nlp, threshold=5, num_clusters=5, distance_threshold=None):
"""
Clusters infrequent keywords using hierarchical clustering and SpaCy embeddings.
Returns a mapping from keyword to cluster representative and a summary.
"""
logging.info("Performing clustering on keywords...")
# 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]
logging.info(f"Number of frequent keywords (> {threshold}): {len(frequent_keywords)}")
logging.info(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
clustering_summary = {}
if infrequent_keywords:
logging.info("Clustering infrequent keywords...")
mapping = cluster_infrequent_keywords(
infrequent_keywords, keyword_counts, nlp,
num_clusters=num_clusters, distance_threshold=distance_threshold
)
clustered.update(mapping)
unique_representatives = set(mapping.values())
clustering_summary['Number of Clusters'] = len(unique_representatives)
clustering_summary['Frequent Keywords'] = len(frequent_keywords)
clustering_summary['Infrequent Keywords'] = len(infrequent_keywords)
else:
logging.info("No infrequent keywords to cluster.")
clustering_summary['Number of Clusters'] = 0
clustering_summary['Frequent Keywords'] = len(frequent_keywords)
clustering_summary['Infrequent Keywords'] = 0
return clustered, clustering_summary
def cluster_infrequent_keywords(keywords, keyword_counts, nlp, num_clusters=5, distance_threshold=None):
"""
Clusters infrequent keywords and maps them to cluster representatives using SpaCy embeddings.
"""
logging.info("Extracting embeddings for infrequent keywords...")
vectors = []
valid_keywords = []
for keyword in keywords:
doc = nlp(keyword)
if doc.vector_norm:
vectors.append(doc.vector)
valid_keywords.append(keyword)
else:
logging.warning(f"Vector not found for keyword: '{keyword}'")
if not vectors:
logging.warning("No valid vectors found for clustering.")
return {}
vectors = np.array(vectors)
logging.info(f"Number of keywords with valid vectors: {len(valid_keywords)}")
# Perform Hierarchical Clustering
if distance_threshold is not None:
logging.info(f"Clustering with distance_threshold={distance_threshold}")
clustering_model = AgglomerativeClustering(n_clusters=None, distance_threshold=distance_threshold, affinity='cosine', linkage='average')
else:
logging.info(f"Clustering with num_clusters={num_clusters}")
clustering_model = AgglomerativeClustering(n_clusters=num_clusters, affinity='cosine', linkage='average')
labels = clustering_model.fit_predict(vectors)
logging.info("Clustering algorithm fitted.")
# 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
logging.debug(f"Cluster {label}: Representative='{most_frequent}', Members={words}")
# 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
logging.info("Clustering of infrequent keywords completed.")
return keyword_to_representative
def categorize_and_count_clustered_keywords(per_row_df, labels, category_limit=50):
"""
Categorizes clustered keywords and counts them per category.
Returns category keyword counts and a summary.
"""
logging.info("Categorizing clustered keywords...")
category_keyword_counts = {label: Counter() for label in labels}
categorization_summary = {}
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:
original_count = len(category_keyword_counts[label])
category_keyword_counts[label] = Counter(dict(category_keyword_counts[label].most_common(category_limit)))
logging.info(f"Category '{label}': Reduced from {original_count} to {len(category_keyword_counts[label])} keywords (top {category_limit})")
# Prepare categorization summary
for label, counter in category_keyword_counts.items():
categorization_summary[label] = f"Top {len(counter)} keywords"
logging.info("Categorization of clustered keywords completed.")
return category_keyword_counts, categorization_summary
def generate_clustered_keywords_and_categories(per_row_df, clustered_keyword_mapping, category_keyword_counts, labels, remove_duplicates=False):
"""
Generates the final DataFrame with clustered keywords and category assignments.
Returns the updated DataFrame and a summary.
"""
logging.info("Generating final clustered keywords and assigning categories...")
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)
other_summary = {}
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:
# Remove duplicates while preserving order
clustered_keywords = list(dict.fromkeys(clustered_keywords))
clustered_keywords_list.append(', '.join(clustered_keywords))
# Initialize "Other" counter for each row
row_other_count = 0
# Assign keywords to categories based on positions
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
if row_other_count <= max_other_count:
other_count_rows[row_other_count] += 1
per_row_df['Clustered Keywords'] = clustered_keywords_list
# Add the category columns to per_row_df
for label in labels:
per_row_df[label] = category_keywords_list[label]
# Prepare "Other" summary
other_summary['Other Counts per Category'] = {label: sum(1 for kw in category_keywords_list[label] if kw == 'Other') for label in labels}
other_summary['Rows with Specific "Other" Counts'] = other_count_rows
logging.info("Final clustered keywords and category assignments completed.")
return per_row_df, other_summary
def encode_categorical_features(input_df, output_tsv_path, id_column='Image Name', remove_extension='.jpg', labels=None, sep='\t', header=False, index=False):
"""
Encodes categorical features using One-Hot Encoding and saves them to a TSV file.
"""
if labels is None:
raise ValueError("Labels for encoding must be provided.")
logging.info("Encoding categorical features using One-Hot Encoding...")
# Read only the necessary columns
columns_to_encode = labels
columns_to_read = [id_column] + columns_to_encode
df = input_df[columns_to_read]
# Initialize OneHotEncoder
enc = OneHotEncoder(handle_unknown='ignore', dtype=np.int8)
# Fit and transform the categorical columns
emb = enc.fit_transform(df[columns_to_encode])
logging.info("One-Hot Encoding completed.")
# Retrieve the names of the one-hot encoded features
feature_names = enc.get_feature_names_out(columns_to_encode)
# Create a DataFrame with the encoded features
emb_df = pd.DataFrame(emb.toarray(), columns=feature_names, dtype=np.int8)
# Concatenate the id_column with the one-hot encoded features
result_df = pd.concat([df[[id_column]].reset_index(drop=True), emb_df.reset_index(drop=True)], axis=1)
# Remove specified extension from id_column
if remove_extension:
result_df[id_column] = result_df[id_column].str.replace(remove_extension, '', regex=False)
# Save to TSV file
result_df.to_csv(output_tsv_path, index=index, header=header, sep=sep)
logging.info(f"One-Hot Encoded features saved to '{output_tsv_path}'.")
if __name__ == "__main__":
main()