{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "003ecb55", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "from typing import Dict, List\n", "from tqdm import tqdm\n", "\n", "import pandas as pd\n", "import srsly\n", "import spacy\n", "from spacy.training.iob_utils import biluo_to_iob\n", "from spacy.training import offsets_to_biluo_tags\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d43fd200", "metadata": {}, "outputs": [], "source": [ "dataset_path = Path(\"promises-elections-pl-twitter-1-reviewed-fixed-case.jsonl\")" ] }, { "cell_type": "code", "execution_count": null, "id": "f2ffadfc", "metadata": {}, "outputs": [], "source": [ "data = list(srsly.read_jsonl(dataset_path.as_posix()))" ] }, { "cell_type": "code", "execution_count": null, "id": "e89bde09", "metadata": {}, "outputs": [], "source": [ "import uuid\n", "from IPython.display import display_javascript, display_html\n", "import json\n", "\n", "class RenderJSON(object):\n", " def __init__(self, json_data):\n", " if isinstance(json_data, dict):\n", " self.json_str = json.dumps(json_data)\n", " else:\n", " self.json_str = json\n", " self.uuid = str(uuid.uuid4())\n", " \n", " def _ipython_display_(self):\n", " display_html('
'.format(self.uuid),\n", " raw=True\n", " )\n", " display_javascript(\"\"\"\n", " require([\"https://rawgit.com/caldwell/renderjson/master/renderjson.js\"], function() {\n", " document.getElementById('%s').appendChild(renderjson(%s))\n", " });\n", " \"\"\" % (self.uuid, self.json_str), raw=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "fed644a9", "metadata": {}, "outputs": [], "source": [ "RenderJSON(data[0])" ] }, { "cell_type": "code", "execution_count": null, "id": "4fad229b", "metadata": {}, "outputs": [], "source": [ "data_df = pd.DataFrame(data)" ] }, { "cell_type": "code", "execution_count": null, "id": "9f75c8b5", "metadata": {}, "outputs": [], "source": [ "data[0][\"text\"]" ] }, { "cell_type": "code", "execution_count": null, "id": "eadb23f1", "metadata": {}, "outputs": [], "source": [ "data_df = data_df[data_df.answer == \"accept\"]" ] }, { "cell_type": "code", "execution_count": null, "id": "261e6a8c", "metadata": {}, "outputs": [], "source": [ "data_df.text[1]" ] }, { "cell_type": "code", "execution_count": null, "id": "cbe9e877", "metadata": {}, "outputs": [], "source": [ "data_df.text[1][202:224]" ] }, { "cell_type": "code", "execution_count": null, "id": "5583aa66", "metadata": {}, "outputs": [], "source": [ "data_df.spans[1]" ] }, { "cell_type": "code", "execution_count": null, "id": "cedd7c42", "metadata": {}, "outputs": [], "source": [ "def convert_spacy_to_iob(text: str, spans: List[Dict], nlp: spacy.language.Language) -> str:\n", " doc = nlp(text)\n", " entities = [(span[\"start\"], span[\"end\"], span[\"label\"].upper()) for span in spans]\n", " if entities:\n", " main_entity = list(set(span[\"label\"].upper() for span in spans))[0]\n", " else:\n", " main_entity = None\n", " tags = offsets_to_biluo_tags(doc, entities)\n", " # then convert L->I and U->B to have IOB tags for the tokens in the doc\n", " # tags_corrected = [tag.replace(\"L-\", \"I-\").replace(\"U-\", \"B-\") for tag in tags]\n", " tags_corrected = biluo_to_iob(tags)\n", " tokens = [token.text for token in doc]\n", " return {\n", " \"tokens\": tokens, \n", " \"tags\": tags_corrected,\n", " \"label\": main_entity or \"\"\n", " }" ] }, { "cell_type": "code", "execution_count": null, "id": "c7d3aa1c", "metadata": {}, "outputs": [], "source": [ "from spacy.lang import pl\n", "\n", "nlp = pl.Language()" ] }, { "cell_type": "code", "execution_count": null, "id": "a0449216", "metadata": {}, "outputs": [], "source": [ "from pprint import pprint" ] }, { "cell_type": "code", "execution_count": null, "id": "4edc0665", "metadata": {}, "outputs": [], "source": [ "tokens, tags, label = convert_spacy_to_iob(data_df.text[0], data_df.spans[0], nlp)" ] }, { "cell_type": "code", "execution_count": null, "id": "db5c6b07", "metadata": {}, "outputs": [], "source": [ "tokens" ] }, { "cell_type": "code", "execution_count": null, "id": "dee2cf4f", "metadata": {}, "outputs": [], "source": [ "tags" ] }, { "cell_type": "code", "execution_count": null, "id": "656c39a8", "metadata": {}, "outputs": [], "source": [ "label" ] }, { "cell_type": "code", "execution_count": null, "id": "37e46df4", "metadata": {}, "outputs": [], "source": [ "iob_dataset = pd.DataFrame([\n", " {\n", " **convert_spacy_to_iob(row[\"text\"], row[\"spans\"], nlp),\n", " # \"url\": row[\"url\"],\n", " # \"tweet_id\": row[\"url\"].split(\"/\")[-1],\n", " }\n", " for _, row\n", " in tqdm(data_df.iterrows())\n", "])" ] }, { "cell_type": "code", "execution_count": null, "id": "74c3d161", "metadata": {}, "outputs": [], "source": [ "iob_dataset" ] }, { "cell_type": "code", "execution_count": null, "id": "0caa005a", "metadata": {}, "outputs": [], "source": [ "iob_dataset.label.value_counts()" ] }, { "cell_type": "code", "execution_count": null, "id": "d121b8fd", "metadata": {}, "outputs": [], "source": [ "from more_itertools import flatten " ] }, { "cell_type": "code", "execution_count": null, "id": "55212d38", "metadata": {}, "outputs": [], "source": [ "sorted(set(flatten(iob_dataset.tags)))" ] }, { "cell_type": "code", "execution_count": null, "id": "8063ab0f", "metadata": {}, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split" ] }, { "cell_type": "code", "execution_count": null, "id": "9787243d", "metadata": {}, "outputs": [], "source": [ "train, test = train_test_split(iob_dataset, test_size=0.4)\n", "dev, test = train_test_split(test, test_size=0.5)" ] }, { "cell_type": "code", "execution_count": null, "id": "bcb323fc", "metadata": {}, "outputs": [], "source": [ "train.label.value_counts()" ] }, { "cell_type": "code", "execution_count": null, "id": "f11f7de6", "metadata": {}, "outputs": [], "source": [ "train.reset_index(inplace=True, drop=True)\n", "train.drop(columns=[\"label\"], inplace=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "459dad3c", "metadata": {}, "outputs": [], "source": [ "train" ] }, { "cell_type": "code", "execution_count": null, "id": "9bdcab49", "metadata": {}, "outputs": [], "source": [ "len(train)" ] }, { "cell_type": "code", "execution_count": null, "id": "aeff2557", "metadata": {}, "outputs": [], "source": [ "len(test)" ] }, { "cell_type": "code", "execution_count": null, "id": "d1301717", "metadata": {}, "outputs": [], "source": [ "len(dev)" ] }, { "cell_type": "code", "execution_count": null, "id": "d55c9edc", "metadata": {}, "outputs": [], "source": [ "test" ] }, { "cell_type": "code", "execution_count": null, "id": "636e9268", "metadata": {}, "outputs": [], "source": [ "test.label.value_counts()" ] }, { "cell_type": "code", "execution_count": null, "id": "f5486e11", "metadata": {}, "outputs": [], "source": [ "test.reset_index(inplace=True, drop=True)\n", "test.drop(columns=[\"label\"], inplace=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "34aa63ef", "metadata": {}, "outputs": [], "source": [ "test" ] }, { "cell_type": "code", "execution_count": null, "id": "c1bc32c4", "metadata": {}, "outputs": [], "source": [ "dev" ] }, { "cell_type": "code", "execution_count": null, "id": "c8ad5315", "metadata": {}, "outputs": [], "source": [ "dev.label.value_counts()" ] }, { "cell_type": "code", "execution_count": null, "id": "5591dea4", "metadata": {}, "outputs": [], "source": [ "dev.reset_index(inplace=True, drop=True)\n", "dev.drop(columns=[\"label\"], inplace=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "53f0c791", "metadata": {}, "outputs": [], "source": [ "dev" ] }, { "cell_type": "code", "execution_count": null, "id": "fdb29857", "metadata": {}, "outputs": [], "source": [ "train.to_parquet(\"../train.parquet\")\n", "test.to_parquet(\"../test.parquet\")\n", "dev.to_parquet(\"../dev.parquet\")" ] }, { "cell_type": "code", "execution_count": null, "id": "c5b20f97", "metadata": {}, "outputs": [], "source": [ "df = pd.read_parquet(\"../train.parquet\")" ] }, { "cell_type": "code", "execution_count": null, "id": "e05e0d83", "metadata": {}, "outputs": [], "source": [ "df" ] } ], "metadata": { "interpreter": { "hash": "97bd981c6355438647fbd6d64b9445f9e50a1f8ddfec47bd063c9ea6e8fe3e87" }, "kernelspec": { "display_name": "Python 3.9.5 ('embeddings')", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.5" } }, "nbformat": 4, "nbformat_minor": 5 }