# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# + colab={"base_uri": "https://localhost:8080/"} id="y3HMENFx9vMe" outputId="049e5bcd-82c9-4b04-b921-98824cf5dccb"
# connect to google colab
from google.colab import drive
drive.mount("/content/drive")

# + [markdown] id="Bt5YjtFl-fUA"
# # Named Entity Recognition

# + [markdown] id="Ej5WjFt3_Sdp"
# ### Do necessary imports

# + colab={"base_uri": "https://localhost:8080/"} id="FjrIL3uD94uA" outputId="d910f2e1-8350-431d-8bd8-ffbfab2525da"
# %matplotlib inline
### INSTALL GHOSTSCRIPT (Required to display NLTK trees) ###
# !apt install ghostscript python3-tk

### CREATE VIRTUAL DISPLAY ###
# !apt-get install -y xvfb # Install X Virtual Frame Buffer
import os
os.system('Xvfb :1 -screen 0 1600x1200x16  &')    # create virtual display with size 1600x1200 and 16 bit color. Color can be changed to 24 or 8
os.environ['DISPLAY']=':1.0'    # tell X clients to use our virtual DISPLAY :1.0.

# + colab={"base_uri": "https://localhost:8080/"} id="i1-B0_cm-NcV" outputId="f0f15470-770b-4548-8966-a69b84b1f778"
import nltk
from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet
from nltk.corpus import stopwords   
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet')
nltk.download('stopwords')

from IPython.display import display
lemmatizer = nltk.WordNetLemmatizer()
from tqdm import tqdm
import re 

import pandas as pd
import numpy as np

from nltk.chunk import conlltags2tree, tree2conlltags
from pprint import pprint
import spacy
from spacy import displacy
from collections import Counter
import en_core_web_sm
nlp = en_core_web_sm.load()

# + id="KqS93kZJ-Y7d"
# COLAB CONFIG
# change colab flag to false if train using jupyter notebook
COLAB_FLAG = True
COLAB_FILEPATH = './drive/My Drive/4034-amazon-review-classification/' if COLAB_FLAG == True else './'
pd.options.mode.chained_assignment = None  # default='warn'
# %matplotlib inline

# + [markdown] id="vrvj2nA7_NNe"
# ### Loading of data

# + colab={"base_uri": "https://localhost:8080/", "height": 259} id="cbYkXRyU-atN" outputId="49681075-c024-417a-e852-16f85e465dd5"
# read the crawled data
data_ = pd.read_csv(COLAB_FILEPATH+'data/trip-advisor-comments.csv')
print(f'Shape of the dataset:{data_.shape}')
data_.head()

# + colab={"base_uri": "https://localhost:8080/"} id="DKGfug0X-cF9" outputId="e1f1f7bd-8ae6-4571-8578-f6d4ccb80da6"
# filtering the test data by removing duplicates
data=data_.drop_duplicates(subset={"Reviewer\'s Name","Comment"}, 
                                             keep='first', inplace=False)
print(f'Shape of the dataset:{data.shape}')

# + colab={"base_uri": "https://localhost:8080/", "height": 225} id="D18WfkfO-ryV" outputId="4017280c-e90c-4c0f-f7f1-efa504004767"
data_comment_ = data['Comment']
data_comment = data_comment_.to_frame()
print(data_comment.shape)
data_comment.head()

# + id="ZY0cwV8b-upl"
# convert data into a list
data_comment_list = list(data_comment_)

# + colab={"base_uri": "https://localhost:8080/", "height": 54} id="XnSX96yE-wX1" outputId="c498c929-9406-4749-de56-bb4d0d58daf3"
data_comment_list[1]

# + id="VbBtkFdI_CtF"


# + [markdown] id="0Z5_tci-_XzO"
# ### Text Preprocessing to check POS and IOB

# + [markdown] id="DLxnWMWK__Xp"
# Chunking pattern consists of one rule, that a noun phrase, NP, should be formed whenever the chunker finds an optional determiner, DT, followed by any number of adjectives, JJ, and then a noun, NN.

# + colab={"base_uri": "https://localhost:8080/"} id="-z2Srd1o_gxc" outputId="ba8ec8c3-216c-4cf6-f35f-e223428391eb"
def preprocess(sent):
    sent = nltk.word_tokenize(sent)
    sent = nltk.pos_tag(sent)
    return sent

selected_list = [5,7,88,777,1000]

for i in selected_list:
    sent = preprocess(data_comment_list[i])

    pattern = 'NP: {<DT>?<JJ>*<NN>}'

    cp = nltk.RegexpParser(pattern)
    cs = cp.parse(sent)
    #print(cs)

    # NER Portion
    # look at the IOB tagged
    iob_tagged = tree2conlltags(cs)
    pprint(iob_tagged)
    print()

# + id="yEHY3p4nALyl"


# + [markdown] id="T45Zz-UtBz-9"
# ## Some examples of named entity recognition

# + colab={"base_uri": "https://localhost:8080/", "height": 87} id="o9nlB7QsArX8" outputId="6cc81600-69c7-4a7e-eee8-06bf2a8c7352"
doc = nlp(data_comment_list[5])
displacy.render(doc, jupyter=True, style='ent')

# + colab={"base_uri": "https://localhost:8080/", "height": 192} id="FEcP3IEKBeu8" outputId="a451dd75-88fd-447f-8f99-2e9a7eaa6f1b"
doc = nlp(data_comment_list[7])
displacy.render(doc, jupyter=True, style='ent')

# + colab={"base_uri": "https://localhost:8080/", "height": 122} id="qogyRbZ_BuMm" outputId="101464fe-be66-4451-8894-cea34547538d"
doc = nlp(data_comment_list[88])
displacy.render(doc, jupyter=True, style='ent')

# + colab={"base_uri": "https://localhost:8080/", "height": 227} id="FA-jq2h8Bik1" outputId="64b9d3aa-e279-4a23-ad70-5d62360455ee"
doc = nlp(data_comment_list[777])
displacy.render(doc, jupyter=True, style='ent')

# + colab={"base_uri": "https://localhost:8080/", "height": 87} id="ZWeXN26eBCAU" outputId="78df5ce5-7392-44ad-b7cd-029830a10223"
doc = nlp(data_comment_list[1000])
displacy.render(doc, jupyter=True, style='ent')

# + id="VbCyIYV8Dwms"


StarcoderdataJupyterScriptsDedupFiltered