File size: 2,062 Bytes
916ac73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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()