import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.tag import pos_tag
from nltk.chunk import ne_chunk
from nltk.chunk.regexp import RegexpParser

# Function to download necessary NLTK data
def download_nltk_data():
    nltk.download('punkt')
    nltk.download('stopwords')
    nltk.download('averaged_perceptron_tagger')

# Function to extract keywords from a description
def extract_keywords_from_description(description):
    words = word_tokenize(description)
    words = [word for word in words if word.lower() not in stopwords.words('english')]
    tagged_words = pos_tag(words)

    # Define a chunking grammar to group related adjectives and nouns
    grammar = r"""
        NP: {<JJ.*>*<NN.*>+}   # Grouping adjectives followed by nouns
    """
    chunk_parser = RegexpParser(grammar)
    tree = chunk_parser.parse(tagged_words)

    # Extract multi-word attributes
    multi_word_attributes = [' '.join(word for word, pos in subtree.leaves()) 
                             for subtree in tree.subtrees() 
                             if subtree.label() == 'NP']

    # Extract single word attributes
    single_word_attributes = [word for word, pos in tagged_words 
                              if pos in ['NN', 'NNS', 'NNP', 'NNPS', 'JJ', 'JJR', 'JJS'] 
                              and word.lower() not in ['design', 'piece']]
    
    # Remove single word attributes that are part of multi-word attributes
    for attribute in multi_word_attributes:
        single_word_attributes = [word for word in single_word_attributes if word not in attribute.split()]

    # Remove nested multi-word attributes
    multi_word_attributes = [attribute for attribute in multi_word_attributes if not any(other_attribute in attribute for other_attribute in multi_word_attributes if attribute != other_attribute)]

    return list(set(multi_word_attributes + single_word_attributes))

def main():
    
    download_nltk_data()

    # TODO: Change the words
    input_text = input("Enter your search query: ")

    keywords = extract_keywords_from_description('input_text')

    # TODO: Return the tags to database

if __name__ == "__main__":
    main()
