{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Document Corpora\n",
    "\n",
    "\n",
    "Corpora are collections of documents and in GateNLP, there are three classes which represent collections of \n",
    "documents:\n",
    "\n",
    "* Corpus: this is any object that behaves like a list or array of documents and allows to get and set the nth document via `mycorpus[n]` and `mycorpus[n] = doc`. A Python list can thus be used as a Corpus, but GateNLP provides other Corpus classes for getting and saving documents from/to a directory and other storage locations. \n",
    "* DocumentSource: this is something that can be used as an iterator over documents. Any iterable of documents can be used as DocumentSource, but GateNLP provides a number of classes to iterate over documents from other sources, like the result of a database query. \n",
    "* DocumentDestination: this is something where a document can be added to by invoking the `add` or `append` method. \n",
    "\n",
    "Corpus and DocumentSource objects can be processed by an executor (see [Processing](processing))\n",
    "\n",
    "## JsonLinesFileSource and JsonLinesFileDestination\n",
    "\n",
    "This document source reads the JSON bdoc representation of a document from each line in an input file and \n",
    "produces the corresponding documents. When a gatenlp Document is saved as \"json\", i.e. in bdoc json format,\n",
    "all json is in a single line since any newline character gets escaped in the json representation.\n",
    "\n",
    "This makes it possible to store several documents in a single text file by having one json-serialization \n",
    "per row. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from gatenlp import Document\n",
    "from gatenlp.corpora import JsonLinesFileDestination, JsonLinesFileSource\n",
    "from gatenlp.corpora import DirFilesDestination, DirFilesSource, DirFilesCorpus\n",
    "from gatenlp.corpora import TsvFileSource\n",
    "\n",
    "# all the example files will be created in \"./tmp\"\n",
    "if not os.path.exists(\"tmp\"):\n",
    "    os.mkdir(\"tmp\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "This is the third document.\n",
      "It has three lines.\n",
      "This line is the last one.\n",
      "\n",
      "{\"annotation_sets\": {}, \"text\": \"This is the third document.\\nIt has three lines.\\nThis line is the last one.\\n\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n"
     ]
    }
   ],
   "source": [
    "# lets start with a few texts to create documents from\n",
    "texts = [\n",
    "    \"This is the first text.\",\n",
    "    \"Another text.\\nThis one has two lines\",\n",
    "    \"This is the third document.\\nIt has three lines.\\nThis line is the last one.\\n\",\n",
    "    \"And another document.\"\n",
    "]\n",
    "\n",
    "docs = [Document(txt) for txt in texts]\n",
    "\n",
    "# print the text of the third document (index 2): this shows that the text has three lines:\n",
    "print(docs[2].text)\n",
    "# lets create the json representation and print it too - this only occupies one line:\n",
    "json = docs[2].save_mem(fmt=\"json\")\n",
    "print(json)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# now lets save the 4 documents to a single JsonLinesFile using the document destination:\n",
    "# IMPORTANT: the file is only complete once the destination has been closed!\n",
    "jsfile1 = os.path.join(\"tmp\",\"jsonlinesfile1.jsonl\")\n",
    "dest1 = JsonLinesFileDestination(jsfile1)\n",
    "for doc in docs:\n",
    "    dest1.append(doc)\n",
    "dest1.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "{\"annotation_sets\": {}, \"text\": \"This is the first text.\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n",
      "{\"annotation_sets\": {}, \"text\": \"Another text.\\nThis one has two lines\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n",
      "{\"annotation_sets\": {}, \"text\": \"This is the third document.\\nIt has three lines.\\nThis line is the last one.\\n\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n",
      "{\"annotation_sets\": {}, \"text\": \"And another document.\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# lets view the created file: \n",
    "with open(jsfile1, \"rt\") as infp:\n",
    "    print(infp.read())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "{\"annotation_sets\": {}, \"text\": \"This is the first text.\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n",
      "{\"annotation_sets\": {}, \"text\": \"Another text.\\nThis one has two lines\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n",
      "{\"annotation_sets\": {}, \"text\": \"This is the third document.\\nIt has three lines.\\nThis line is the last one.\\n\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n",
      "{\"annotation_sets\": {}, \"text\": \"And another document.\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Another way to use most document destinations is in a \"with\" block, which has the advantage that the \n",
    "# destination will get closed automatically:\n",
    "jsfile2 = os.path.join(\"tmp\",\"jsonlinesfile2.jsonl\")\n",
    "with JsonLinesFileDestination(jsfile2) as dest:\n",
    "    for doc in docs:\n",
    "        dest.append(doc)\n",
    "        \n",
    "with open(jsfile2, \"rt\") as infp:\n",
    "    print(infp.read())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Document(This is the first text.,features=Features({}),anns=[])\n",
      "Document(Another text.\n",
      "This one has two lines,features=Features({}),anns=[])\n",
      "Document(This is the third document.\n",
      "It has three lines.\n",
      "This line is the last one.\n",
      ",features=Features({}),anns=[])\n",
      "Document(And another document.,features=Features({}),anns=[])\n"
     ]
    }
   ],
   "source": [
    "# Now that we have create a jsonlines file, we can use a document source to iterate over the documents in it\n",
    "\n",
    "for doc in JsonLinesFileSource(jsfile2):\n",
    "    print(doc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DirFilesSource, DirFilesDestination, DirFilesCorpus\n",
    "\n",
    "The DirFilesSource is a document sorce that imports/reads files in a directory or directory tree as one \n",
    "iterates over the source. \n",
    "\n",
    "The DirFilesDestination is a destination that creates files in a directory as documents get appended to the destination. \n",
    "\n",
    "The DirFilesCorpus is a corpus that accesses stored documents in a directory or directory tree when accessing \n",
    "the corpus element and stores them back to their file when assigning the corpus element. \n",
    "\n",
    "Let's first convert the jsonlines file we have created into a directory corpus. A directory files corpus allows\n",
    "for several different ways of how to name the files or file paths within the directory. Here we simply use the \n",
    "index of the document, i.e. the running number of the document as the base name of the created file:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "['3.bdocjs', '1.bdocjs', '0.bdocjs', '2.bdocjs']\n"
     ]
    }
   ],
   "source": [
    "dir1 = os.path.join(\"tmp\", \"dir1\")\n",
    "if not os.path.exists(dir1):\n",
    "    os.mkdir(dir1)  # The directory for a DirFilesDestination must exist\n",
    "# The path_from=\"idx\" setting makes the DirFilesCorpus use the running number of the document as \n",
    "# the file base name.\n",
    "\n",
    "with DirFilesDestination(dir1, ext=\"bdocjs\", path_from=\"idx\") as dest:\n",
    "    for doc in JsonLinesFileSource(jsfile1):\n",
    "        dest.append(doc)\n",
    "    \n",
    "\n",
    "# lets see what the content of the directory is now:\n",
    "print(os.listdir(dir1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have a directory with files representing documents, we can open it as \n",
    "a document source or corpus.\n",
    "\n",
    "If we open it as a document source, we can simply iterate over all documents in it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Document(And another document.,features=Features({}),anns=[])\n",
      "Document(Another text.\n",
      "This one has two lines,features=Features({}),anns=[])\n",
      "Document(This is the first text.,features=Features({}),anns=[])\n",
      "Document(This is the third document.\n",
      "It has three lines.\n",
      "This line is the last one.\n",
      ",features=Features({}),anns=[])\n"
     ]
    }
   ],
   "source": [
    "src2 = DirFilesSource(dir1)\n",
    "for doc in src2:\n",
    "    print(doc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we open it as a document corpus, we can directly access each document as from a list or an array:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "corp1 = DirFilesCorpus(dir1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "length is: 4\n",
      "Original documents:\n",
      "Document(And another document.,features=Features({}),anns=[])\n",
      "Document(Another text.\n",
      "This one has two lines,features=Features({}),anns=[])\n",
      "Document(This is the first text.,features=Features({}),anns=[])\n",
      "Document(This is the third document.\n",
      "It has three lines.\n",
      "This line is the last one.\n",
      ",features=Features({}),anns=[])\n",
      "Updated documents:\n",
      "Document(And another document.,features=Features({'docidx': 0}),anns=['':1])\n",
      "Document(Another text.\n",
      "This one has two lines,features=Features({'docidx': 1}),anns=['':1])\n",
      "Document(This is the first text.,features=Features({'docidx': 2}),anns=['':1])\n",
      "Document(This is the third document.\n",
      "It has three lines.\n",
      "This line is the last one.\n",
      ",features=Features({'docidx': 3}),anns=['':1])\n"
     ]
    }
   ],
   "source": [
    "# we can get the length\n",
    "print(\"length is:\", len(corp1))\n",
    "\n",
    "# we can iterate over the documents in it:\n",
    "print(\"Original documents:\")\n",
    "for doc in corp1:\n",
    "    print(doc)\n",
    "    \n",
    "# but we can also update each element which will save the corresponding document to the original\n",
    "# file in the directory where it was loaded from. Here we add an annotation and document feature\n",
    "# to each document in the corpus.\n",
    "for idx, doc in enumerate(corp1):\n",
    "    doc.features[\"docidx\"] = idx\n",
    "    doc.annset().add(0,3,\"Type1\")\n",
    "    corp1[idx] = doc  # !! this is what updates the document file in the directory\n",
    "    \n",
    "# the files in the directory now contain the modified documents. lets open them again and show them \n",
    "# using a dirfiles source:\n",
    "src3 = DirFilesSource(dir1)\n",
    "print(\"Updated documents:\")\n",
    "for doc in src2:\n",
    "    print(doc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## TsvFileSource\n",
    "\n",
    "The TsvFileSource is a document source which initializes documents from the text in some column of a tsv\n",
    "file and optionally sets document features from other columns of the tsv file. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Document(Here is some text. Like with JSON, newlines are escaped:\\nHere is another line.,features=Features({'f1': 'fval1', 'f2': 'fval2\\n'}),anns=[])\n",
      "Document(Another text\\nThis one\\nhas more\\n\\nlines.,features=Features({'f1': '11', 'f2': '22\\n'}),anns=[])\n",
      "Document(And another.,features=Features({'f1': 'a', 'f2': 'b\\n'}),anns=[])\n"
     ]
    }
   ],
   "source": [
    "# Let's load documents from a tsv file on a web page. This tsv file has three columns and a header line which \n",
    "# gives the names \"text\", \"feat1\" \"feat2\" to the columns. \n",
    "# We create the documents by fetching the text from column \"text\" and creating two document features\n",
    "# with names \"f1\" and \"f2\" from the columns \"feat1\" and \"feat2\":\n",
    "tsvsrc = TsvFileSource(\"https://gatenlp.github.io/python-gatenlp/tsvcorpus_example1.tsv\",\n",
    "                      text_col=\"text\", feature_cols=dict(f1=\"feat1\", f2=\"feat2\"))\n",
    "\n",
    "\n",
    "\n",
    "for doc in tsvsrc:\n",
    "    print(doc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# clean up after ourselves\n",
    "import shutil\n",
    "shutil.rmtree(\"tmp\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
