This is my current code. i need you to make it more professional and remove unnecessary…
- User
This is my current code. i need you to make it more professional and remove unnecessary steps. i need can you help me making it better? what could i do to improve it?you to add more logging info
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 gensim.models import KeyedVectors, FastText 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
def download_nltk_data(): """ Ensures that required NLTK data packages are downloaded. """ nltk_data_packages = ['wordnet', 'stopwords'] for package in nltk_data_packages: try: nltk.data.find(f'corpora/{package}') except LookupError: nltk.download(package)
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, help='Path to the input CSV file.') parser.add_argument('--save_lemmatized', action='store_true', help='Save lemmatized keywords and counts.') parser.add_argument('--model_type', type=str, choices=['word2vec', 'glove', 'fasttext'], default='glove', help='Type of model to use for clustering. Default is "glove".') parser.add_argument('--model_path', type=str, default='/home/danilo/Projects/IR_MD/models/glove.6B.300d.word2vec.txt', required=False, help='Path to the word embedding model file.') 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.') return parser.parse_args()
def main(): # Parse command-line arguments args = parse_arguments() input_file = args.input_file save_lemmatized = args.save_lemmatized model_type = args.model_type model_path = args.model_path 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
# Check if input file exists if not os.path.exists(input_file): raise FileNotFoundError(f"Input file '{input_file}' does not exist.") # Set up 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) 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"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') # ------------------------------# # Step 1: Cleaning # # ------------------------------# logging.info("Starting CSV cleaning...") df_clean = clean_csv(input_file, labels) logging.info("CSV cleaning completed.") # ------------------------------# # Step 2: Lemmatization # # ------------------------------# logging.info("Starting lemmatization...") if save_lemmatized: per_row_df, keyword_counts = lemmatize_keywords(df_clean, lemmatized_counts_output_file, lemmatizer) else: per_row_df, keyword_counts = lemmatize_keywords(df_clean, None, lemmatizer) # Check if per_row_df is None if per_row_df is None: logging.error("Error in lemmatization.") return # ------------------------------# # Step 3: Load Model # # ------------------------------# model = load_model(model_type, model_path) # ------------------------------# # 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 ) # ------------------------------# # 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 ) # ------------------------------# # 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 ) # 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} keyword counts saved to '{category_counts_output_file}'.") # ------------------------------# # Step 8: Save Results # # ------------------------------# per_row_df.to_csv(output_file, index=False) logging.info(f"Process 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 ) logging.info(f"One-hot encoded features saved to '{one_hot_encoded_file}'.") - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.