{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"This notebook is a template on using Literal Matching + Masked Language Modeling to identify datasets in papers.\n\nThe training of the Bert model was done in another notebook: [BERT - Masked Dataset Modeling.](https://www.kaggle.com/khubchandani/bert-masked-dataset-modeling) and the trained model thus arrived at is at https://www.kaggle.com/khubchandani/bert-mlm-v6\n\nThis notebook was forked from [[Coleridge] Predict with Masked Dataset Modeling](https://www.kaggle.com/tungmphung/coleridge-predict-with-masked-dataset-modeling) during the early stages of the competition. The external dataset used is at https://www.kaggle.com/khubchandani/data-set-800-2 The dataset and the way it is used is derived from https://www.kaggle.com/mlconsult/isin-big-dataset and the datasets used therein.\n\nThe approach is:\n- Locate all the sequences of capitalized words (these sequences may contain some stopwords),\n- Replace each sequence with one of 2 special symbols (e.g. $ and #), implying if that sequence represents a dataset name or not.\n- Have the model learn the MLM task.","metadata":{}},{"cell_type":"markdown","source":"# Install packages","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"code","source":"!pip install datasets --no-index --find-links=file:///kaggle/input/coleridge-packages/packages/datasets\n!pip install ../input/coleridge-packages/seqeval-1.2.2-py3-none-any.whl\n!pip install ../input/coleridge-packages/tokenizers-0.10.1-cp37-cp37m-manylinux1_x86_64.whl\n!pip install ../input/coleridge-packages/transformers-4.5.0.dev0-py3-none-any.whl","metadata":{"_kg_hide-output":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Import","metadata":{}},{"cell_type":"code","source":"import os\nimport re\nimport json\nimport time\nimport datetime\nimport random\nimport glob\nimport importlib\n\nimport numpy as np\nimport pandas as pd\n\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport torch\nfrom datasets import load_dataset\nfrom transformers import AutoTokenizer, DataCollatorForLanguageModeling, \\\nAutoModelForMaskedLM, Trainer, TrainingArguments, pipeline\n\nimport string\n\nimport spacy\nnlp1 = spacy.load('en')\n\nsns.set()\nrandom.seed(123)\nnp.random.seed(456)\ntorch.manual_seed(2021)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load data","metadata":{}},{"cell_type":"code","source":"train_path = '../input/coleridgeinitiative-show-us-the-data/train.csv'\ntrain_data_path = '../input/coleridgeinitiative-show-us-the-data/train'\ntrain = pd.read_csv(train_path)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission_path = '../input/coleridgeinitiative-show-us-the-data/sample_submission.csv'\nsample_submission = pd.read_csv(sample_submission_path)\n\npaper_test_folder = '../input/coleridgeinitiative-show-us-the-data/test'\npapers = {}\nfor paper_id in sample_submission['Id']:\n    with open(f'{paper_test_folder}/{paper_id}.json', 'r') as f:\n        paper = json.load(f)\n        papers[paper_id] = paper","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_json_pub(filename, train_data_path=train_data_path, output='text'):\n    json_path = os.path.join(train_data_path, (filename+'.json'))\n    headings = []\n    contents = []\n    combined = []\n    with open(json_path, 'r') as f:\n        json_decode = json.load(f)\n        for data in json_decode:\n            headings.append(data.get('section_title'))\n            contents.append(data.get('text'))\n            combined.append(data.get('section_title'))\n            combined.append(data.get('text'))\n    \n    all_headings = ' '.join(headings)\n    all_contents = ' '.join(contents)\n    all_data = '. '.join(combined)\n    \n    if output == 'text':\n        return all_contents\n    elif output == 'head':\n        return all_headings\n    else:\n        return all_data","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def clean_text(txt):\n    return re.sub('[^A-Za-z0-9]+', ' ', str(txt).lower()).strip()\n\ndef totally_clean_text(txt):\n    txt = clean_text(txt)\n    txt = re.sub(' +', ' ', txt)\n    return txt\n\ndef text_cleaning(text):\n    '''\n    Converts all text to lower case, Removes special charecters, emojis and multiple spaces\n    text - Sentence that needs to be cleaned\n    '''\n    text = re.sub('[^A-Za-z0-9]+', ' ', str(text).lower()).strip()\n    text = re.sub(' +', ' ', text)\n    emoji_pattern = re.compile(\"[\"\n                               u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                               u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                               u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                               u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                               \"]+\", flags=re.UNICODE)\n    text = emoji_pattern.sub(r'', text)\n    return text","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Masked Dataset Modeling","metadata":{}},{"cell_type":"markdown","source":"### Paths and Hyperparameters","metadata":{}},{"cell_type":"code","source":"#PRETRAINED_PATH = '../input/coleridge-mlm-model/mlm-model'\n#TOKENIZER_PATH = '../input/coleridge-mlm-model/model_tokenizer'\n\nPRETRAINED_PATH = '../input/bert-mlm-v6/mlm-model'\nTOKENIZER_PATH = '../input/bert-mlm-v6/model_tokenizer'\n\n#PRETRAINED_PATH = '../input/bert-masked-dataset-modeling/mlm-model'\n#TOKENIZER_PATH = '../input/bert-masked-dataset-modeling/model_tokenizer'\n\n#PRETRAINED_PATH = '../input/k/khubchandani/bert-masked-dataset-modeling/mlm-model'\n#TOKENIZER_PATH = '../input/k/khubchandani/bert-masked-dataset-modeling/model_tokenizer'\n\nMAX_LENGTH = 64\nOVERLAP = 20\n\nPREDICT_BATCH = 32 # a higher value requires higher GPU memory usage\n\nDATASET_SYMBOL = '$' # this symbol represents a dataset name\nNONDATA_SYMBOL = '#' # this symbol represents a non-dataset name","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Transform data to MLM format","metadata":{}},{"cell_type":"markdown","source":"### Load model and tokenizer","metadata":{}},{"cell_type":"code","source":"tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, use_fast=True)\nmodel = AutoModelForMaskedLM.from_pretrained(PRETRAINED_PATH)\n\nmlm = pipeline(\n    'fill-mask', \n    model=model,\n    tokenizer=tokenizer,\n    device=0 if torch.cuda.is_available() else -1\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Auxiliary functions","metadata":{}},{"cell_type":"code","source":"def jaccard_similarity(s1, s2):\n    l1 = s1.split(\" \")\n    l2 = s2.split(\" \")    \n    intersection = len(list(set(l1).intersection(l2)))\n    union = (len(l1) + len(l2)) - intersection\n    return float(intersection) / union\n\ndef jaccard(str1, str2): \n    a = set(str1.lower().split()) \n    b = set(str2.lower().split())\n    c = a.intersection(b)\n    return float(len(c)) / (len(a) + len(b) - len(c))\n\ndef clean_paper_sentence(s):\n    \"\"\"\n    This function is essentially clean_text without lowercasing.\n    \"\"\"\n    s = re.sub('[^A-Za-z0-9]+', ' ', str(s)).strip()\n    s = re.sub(' +', ' ', s)\n    return s\n\ndef shorten_sentences(sentences):\n    \"\"\"\n    Sentences that have more than MAX_LENGTH words will be split\n    into multiple sentences with overlappings.\n    \"\"\"\n    short_sentences = []\n    for sentence in sentences:\n        words = sentence.split()\n        if len(words) > MAX_LENGTH:\n            for p in range(0, len(words), MAX_LENGTH - OVERLAP):\n                short_sentences.append(' '.join(words[p:p+MAX_LENGTH]))\n        else:\n            short_sentences.append(sentence)\n    return short_sentences\n\nconnection_tokens = {'s','of','and','in','on','for'}\n\ndef find_mask_candidates(sentence):\n    \"\"\"\n    Extract masking candidates for Masked Dataset Modeling from a given $sentence.\n    A candidate should be a continuous sequence of at least 2 words, \n    each of these words either has the first letter in uppercase or is one of\n    the connection words ($connection_tokens). Furthermore, the connection \n    tokens are not allowed to appear at the beginning and the end of the\n    sequence.\n    \"\"\"\n    def candidate_qualified(words):\n        while len(words) and words[0].lower() in connection_tokens:\n            words = words[1:]\n        while len(words) and words[-1].lower() in connection_tokens:\n            words = words[:-1]\n    \n        return len(words) >= 4 #4, 2, 3, 1, 5 VARIOUS CHOICES EXPLORED\n    \n    candidates = []\n    \n    phrase_start, phrase_end = -1, -1\n    for id in range(1, len(sentence)):\n        word = sentence[id]\n        if word[0].isupper() or word in connection_tokens:\n            if phrase_start == -1:\n                phrase_start = phrase_end = id\n            else:\n                phrase_end = id\n        else:\n            if phrase_start != -1:\n                if candidate_qualified(sentence[phrase_start:phrase_end+1]):\n                    candidates.append((phrase_start, phrase_end))\n                phrase_start = phrase_end = -1\n    \n    if phrase_start != -1:\n        if candidate_qualified(sentence[phrase_start:phrase_end+1]):\n            candidates.append((phrase_start, phrase_end))\n    \n    return candidates","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Transform","metadata":{}},{"cell_type":"code","source":"mask = mlm.tokenizer.mask_token","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_test_data = []\n\nfor paper_id in sample_submission['Id']:\n    # load paper\n    paper = papers[paper_id]\n    \n    # extract sentences\n    sentences = set([clean_paper_sentence(sentence) for section in paper \n                     for sentence in re.split(\"[,.;:]\", section['text'])\n                     #for sentence in section['text'].split('.')\n                    ])\n    sentences = shorten_sentences(sentences) # make sentences short\n    sentences = [sentence for sentence in sentences if len(sentence) > 21] # only accept sentences greater than this length\n    sentences = [sentence for sentence in sentences if any(word in sentence.lower() for word in ['survey','study','database','catalog','dataset'])]\n    sentences = [sentence.split() for sentence in sentences] # sentence = list of words\n    test_data = []\n    for sentence in sentences:\n        for phrase_start, phrase_end in find_mask_candidates(sentence):\n            dt_point = sentence[:phrase_start] + [mask] + sentence[phrase_end+1:]\n            test_data.append((' '.join(dt_point), ' '.join(sentence[phrase_start:phrase_end+1]))) # (masked text, phrase)\n    \n    all_test_data.append(test_data)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Predict","metadata":{}},{"cell_type":"code","source":"pred_mlm_labels = []\n\npbar = tqdm(total = len(all_test_data))\nfor test_data in all_test_data:\n    pred_bag = set()\n    \n    if len(test_data):\n        texts, phrases = list(zip(*test_data))\n        mlm_pred = []\n        for p_id in range(0, len(texts), PREDICT_BATCH):\n            batch_texts = texts[p_id:p_id+PREDICT_BATCH]\n            batch_pred = mlm(list(batch_texts), targets=[f' {DATASET_SYMBOL}', f' {NONDATA_SYMBOL}'])\n            \n            if len(batch_texts) == 1:\n                batch_pred = [batch_pred]\n            \n            mlm_pred.extend(batch_pred)\n        \n        for (result1, result2), phrase in zip(mlm_pred, phrases):\n            if (result1['score'] > result2['score']*1.6 and result1['token_str'] == DATASET_SYMBOL) or\\\n               (result2['score'] > result1['score']*1.6 and result2['token_str'] == NONDATA_SYMBOL):\n                pred_bag.add(clean_text(phrase))\n    \n    # filter labels by jaccard score \n    filtered_labels = []\n    \n    for label in sorted(pred_bag, key=len, reverse=True):\n        if len(filtered_labels) == 0 or all(jaccard(label, got_label) < 0.75 for got_label in filtered_labels):#0.75\n            filtered_labels.append(label)\n            \n    pred_mlm_labels.append('|'.join(filtered_labels))\n    pbar.update(1)","metadata":{"scrolled":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_mlm_labels[:5]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"start_time = time.time()\nfrom fuzzywuzzy import fuzz\ndef get_ratio(name, name1):\n    return fuzz.token_set_ratio(name, name1)\nfinal = []\nfor preds in pred_mlm_labels:\n    got_label=preds.split('|')\n    filtered=[]\n    filtered_labels = ''\n    for label in sorted(got_label, key=len, reverse=True):\n        if len(filtered) == 0 or all(get_ratio(label, got) < 100 for got in filtered):\n            filtered.append(label)\n            if filtered_labels!='':\n                filtered_labels += '|' + label\n            if filtered_labels=='':\n                filtered_labels=label\n    final.append(filtered_labels)\nprint(\"--- %s seconds ---\" % (time.time() - start_time))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_mlm_labels = final","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_mlm_labels[:5]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df2=pd.read_csv('../input/data-set-800-2/data_set_800_4.csv')","metadata":{"execution":{"iopub.status.busy":"2021-05-25T23:37:55.58018Z","iopub.execute_input":"2021-05-25T23:37:55.580582Z","iopub.status.idle":"2021-05-25T23:37:55.676704Z","shell.execute_reply.started":"2021-05-25T23:37:55.580475Z","shell.execute_reply":"2021-05-25T23:37:55.676009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def is_in_big(to_append):\n    large_string = str(read_json_pub(to_append[0],path))\n    clean_string=text_cleaning(large_string)\n    for index, row2 in df2.iterrows():\n        query_string = str(row2['title'])\n        if query_string in clean_string:\n            if to_append[1]!='' and clean_text(query_string) not in to_append[1]:\n                to_append[1] += '|' + clean_text(query_string)\n            if to_append[1]=='':\n                to_append[1]= clean_text(query_string)\n    got_label=to_append[1].split('|')\n    filtered=[]\n    filtered_labels = ''\n    for label in sorted(got_label, key=len):\n        if len(filtered) == 0 or all(jaccard(label, got) < 1.0 for got in filtered):\n            filtered.append(label)\n            if filtered_labels!='':\n                filtered_labels += '|' + label\n            if filtered_labels=='':\n                filtered_labels=label\n    to_append[1] = filtered_labels     \n    return to_append\n\ndef submit(chunk):\n    chunk_sub = pd.DataFrame(columns = column_names)\n    for index, row in chunk.iterrows():\n        to_append=[row['Id'],'']\n        to_append = is_in_big(to_append)\n        df_length = len(chunk_sub)\n        chunk_sub.loc[df_length] = to_append\n    return chunk_sub\n\ndef literals(chunk):\n    chunk_preds = []\n    for index, row in chunk.iterrows():\n        to_append=[row['Id'],'']\n        to_append = is_in_big(to_append)\n        chunk_preds.append(to_append[1])\n    return chunk_preds","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import multiprocessing as mp\nnum_processes = mp.cpu_count()\nprint(num_processes)\nchunk_size = int(sample_submission.shape[0]/num_processes)\nprint(chunk_size)\nchunks = [sample_submission.iloc[i:i + chunk_size,:] for i in range(0, sample_submission.shape[0], chunk_size)]\npath = paper_test_folder\ncolumn_names = [\"Id\", \"PredictionString\"]\n\nstart_time = time.time()\npool = mp.Pool(processes=num_processes)\nsubmission = pd.concat(pool.map(submit, chunks))\npool.close()\npool.join()\nliteral_preds = submission[\"PredictionString\"].tolist()\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\nsubmission","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Aggregate final predictions and write submission file","metadata":{}},{"cell_type":"code","source":"final_predictions = []\nfor literal_match, mlm_pred in zip(literal_preds, pred_mlm_labels):\n    if literal_match:\n        final_predictions.append(literal_match)\n    else:\n        final_predictions.append(mlm_pred)\n#final_predictions = pred_mlm_labels # when string matching solution is to be omitted","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_predictions[:5]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission['PredictionString'] = final_predictions\nsample_submission.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}