import os import nltk import string import pandas as pd from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from data_loading import DataLoading from nltk.data import find # Function to check and download NLTK resources if not already downloaded def download_nltk_resources(): try: # Try to find 'punkt' and 'stopwords' locally to avoid downloading find('tokenizers/punkt') find('corpora/stopwords') except LookupError: # Only download if not found nltk.download('punkt', quiet=True) nltk.download('stopwords', quiet=True) # Call the function to ensure resources are available without repeating printing messages download_nltk_resources() class PreProcess: def __init__(self): self.dataLoad = DataLoading() self.stop_words = set(stopwords.words('english')) # Convert to set for faster lookup def clean_text(self, text): """Cleans text: lowercase, remove punctuation, tokenize, and remove stopwords.""" if pd.isna(text): return "" text = text.lower() # Convert to lowercase text = text.translate(str.maketrans('', '', string.punctuation)) # Remove punctuation tokens = word_tokenize(text) # Tokenize return " ".join(word for word in tokens if word not in self.stop_words) def pre_processing(self): """Fetches data and applies text preprocessing.""" data = self.dataLoad.fetch() if data is None: print("No data loaded!") return None # Apply preprocessing to all text columns in a single step using `apply()` text_cols = ['book_name', 'summaries', 'categories'] data[text_cols] = data[text_cols].apply(lambda x: x.astype(str).apply(self.clean_text)) # Create 'processed_summary' column data['processed_summary'] = data['summaries'].apply(self.clean_text) return data # if __name__ == "__main__": # processor = PreProcess() # processed_data = processor.pre_processing()