💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add notebook showing how to index/search Hugging Face Datasets, addresses #26
davidmezzetti6b03186f4e7b
diff --git a/README.md b/README.mdindex 4531f5be..6bcabaa8 100644--- a/README.md+++ b/README.md@@ -98,6 +98,7 @@ The examples directory has a series of examples and notebooks giving an overview| [Extractive QA with Elasticsearch](https://github.com/neuml/txtai/blob/master/examples/04_Extractive_QA_with_Elasticsearch.ipynb) | Extractive question-answering with Elasticsearch | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/04_Extractive_QA_with_Elasticsearch.ipynb) || [Labeling with zero-shot classification](https://github.com/neuml/txtai/blob/master/examples/05_Labeling_with_zero_shot_classification.ipynb) | Labeling with zero-shot classification | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/05_Labeling_with_zero_shot_classification.ipynb) || [API Gallery](https://github.com/neuml/txtai/blob/master/examples/06_API_Gallery.ipynb) | Using txtai in JavaScript, Java, Rust and Go | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/06_API_Gallery.ipynb) |+| [Integrate with Hugging Face Datasets](https://github.com/neuml/txtai/blob/master/examples/07_Integrate_with_Hugging_Face_Datasets.ipynb) | Index and search Hugging Face Datasets | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/07_Integrate_with_Hugging_Face_Datasets) |## Configurationdiff --git a/examples/07_Integrate_with_Hugging_Face_Datasets.ipynb b/examples/07_Integrate_with_Hugging_Face_Datasets.ipynbnew file mode 100644index 00000000..069e552f--- /dev/null+++ b/examples/07_Integrate_with_Hugging_Face_Datasets.ipynb@@ -0,0 +1,310 @@+{+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "colab": {+ "name": "07 - Integrate with Hugging Face Datasets",+ "provenance": [],+ "collapsed_sections": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "accelerator": "GPU"+ },+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "LjmhJ4ad9kBL"+ },+ "source": [+ "# Part 7: Integrate with Hugging Face Datasets\n",+ "\n",+ "This notebook shows how txtai can integrate with Hugging Face's [Datasets](https://github.com/huggingface/datasets) library. Datasets opens access to a large and growing list of publicly available datasets. Datasets has functionality to select, transform and filter data stored in each dataset.\n",+ "\n",+ "In this example, txtai will be used to index and query a dataset."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "8tLWvo9v-Q0u"+ },+ "source": [+ "# Install dependencies\n",+ "\n",+ "Install `txtai` and all dependencies. Also install `datasets` and a specific [sentence-transformers](https://github.com/UKPLab/sentence-transformers) model that does well with general information retrieval tasks. "+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "Fa5BCjMFqVKE"+ },+ "source": [+ "%%capture\n",+ "!pip install git+https://github.com/neuml/txtai\n",+ "!pip install datasets\n",+ "\n",+ "# Download sentence-transformer models not on Hugging Face model hub\n",+ "!wget https://public.ukp.informatik.tu-darmstadt.de/reimers/sentence-transformers/v0.2/msmarco-distilroberta-base-v2.zip\n",+ "!unzip -o msmarco-distilroberta-base-v2.zip\n",+ "!mv 0_Transformer/ msmarco-distilroberta-base-v2"+ ],+ "execution_count": 1,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "hOdEv8MH-e5h"+ },+ "source": [+ "# Load dataset and build a txtai index\n",+ "\n",+ "In this example, we'll load the `ag_news` dataset, which is a collection of news article headlines. This only takes a single line of code!\n",+ "\n",+ "Next, txtai will index the first 10,000 rows of the dataset. A model trained on msmarco is used to compute sentence embeddings. sentence-transformers has a number of [pre-trained models](https://www.sbert.net/docs/pretrained_models.html) that can be swapped in.\n",+ "\n",+ "In addition to the embeddings index, we'll also create a Similarity instance to re-rank search hits for relevancy. "+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "3hYRk9JnsM0J"+ },+ "source": [+ "%%capture\n",+ "import numpy as np\n",+ "\n",+ "from datasets import load_dataset\n",+ "\n",+ "from txtai.embeddings import Embeddings\n",+ "from txtai.pipeline import Similarity\n",+ "\n",+ "def stream(dataset, field, limit):\n",+ " index = 0\n",+ " for row in dataset:\n",+ " yield (index, row[field], None)\n",+ " index += 1\n",+ "\n",+ " if index >= limit:\n",+ " break\n",+ "\n",+ "def search(query):\n",+ " return [(score, dataset[uid][\"text\"]) for uid, score in embeddings.search(query, limit=50)]\n",+ "\n",+ "def ranksearch(query):\n",+ " results = [text for _, text in search(query)]\n",+ " scores = similarity(query, results)\n",+ " return [(scores[x], results[x]) for x in reversed(np.argsort(scores))]\n",+ "\n",+ "# Load HF dataset\n",+ "dataset = load_dataset(\"ag_news\", split=\"train\")\n",+ "\n",+ "# Create embeddings model, backed by sentence-transformers & transformers\n",+ "embeddings = Embeddings({\"method\": \"transformers\", \"path\": \"msmarco-distilroberta-base-v2\"})\n",+ "embeddings.index(stream(dataset, \"text\", 10000))\n",+ "\n",+ "# Create similarity instance for re-ranking\n",+ "similarity = Similarity(\"valhalla/distilbart-mnli-12-3\")"+ ],+ "execution_count": 2,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "LBhHcX6eFmGI"+ },+ "source": [+ "# Search the dataset\n",+ "\n",+ "Now that an index is ready, let's search the data! The following section runs a series of queries and show the results. Like basic search engines, txtai finds token matches. But the real power of txtai is finding semantically similar results.\n",+ "\n",+ "sentence-transformers has a great overview on [information retrieval](https://github.com/UKPLab/sentence-transformers/tree/master/examples/applications/information-retrieval) that is well worth a read. "+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/",+ "height": 1000+ },+ "id": "YVmbiY92vxEO",+ "outputId": "095982b7-08df-455a-dbc8-93f770b1185f"+ },+ "source": [+ "from IPython.core.display import display, HTML\n",+ "\n",+ "def table(query, rows):\n",+ " html = \"\"\"\n",+ " <style type='text/css'>\n",+ " @import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');\n",+ " table {\n",+ " border-collapse: collapse;\n",+ " width: 900px;\n",+ " }\n",+ " th, td {\n",+ " border: 1px solid #9e9e9e;\n",+ " padding: 10px;\n",+ " font: 15px Oswald;\n",+ " }\n",+ " </style>\n",+ " \"\"\"\n",+ "\n",+ " html += \"<h3>%s</h3><table><thead><tr><th>Score</th><th>Text</th></tr></thead>\" % (query)\n",+ " for score, text in rows:\n",+ " html += \"<tr><td>%.4f</td><td>%s</td></tr>\" % (score, text)\n",+ " html += \"</table>\"\n",+ "\n",+ " display(HTML(html))\n",+ "\n",+ "for query in [\"Positive Apple reports\", \"Negative Apple reports\", \"Best planets to explore for life\", \"LA Dodgers good news\", \"LA Dodgers bad news\"]:\n",+ " table(query, ranksearch(query)[:2])\n"+ ],+ "execution_count": 3,+ "outputs": [+ {+ "output_type": "display_data",+ "data": {+ "text/html": [+ "\n",+ " <style type='text/css'>\n",+ " @import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');\n",+ " table {\n",+ " border-collapse: collapse;\n",+ " width: 900px;\n",+ " }\n",+ " th, td {\n",+ " border: 1px solid #9e9e9e;\n",+ " padding: 10px;\n",+ " font: 15px Oswald;\n",+ " }\n",+ " </style>\n",+ " <h3>Positive Apple reports</h3><table><thead><tr><th>Score</th><th>Text</th></tr></thead><tr><td>0.9886</td><td>Apple tops US consumer satisfaction Recent data published by the American Customer Satisfaction Index (ACSI) shows Apple leading the consumer computer industry with the the highest customer satisfaction.</td></tr><tr><td>0.9876</td><td>Apple Remote Desktop 2 Reviewing Apple Remote Desktop 2 in Computerworld, Yuval Kossovsky writes, #147;I liked what I found. #148; He concludes, #147;I am happy to say that ARD 2 is an excellent upgrade and well worth the money. #148; Aug 19</td></tr></table>"+ ],+ "text/plain": [+ "<IPython.core.display.HTML object>"+ ]+ },+ "metadata": {+ "tags": []+ }+ },+ {+ "output_type": "display_data",+ "data": {+ "text/html": [+ "\n",+ " <style type='text/css'>\n",+ " @import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');\n",+ " table {\n",+ " border-collapse: collapse;\n",+ " width: 900px;\n",+ " }\n",+ " th, td {\n",+ " border: 1px solid #9e9e9e;\n",+ " padding: 10px;\n",+ " font: 15px Oswald;\n",+ " }\n",+ " </style>\n",+ " <h3>Negative Apple reports</h3><table><thead><tr><th>Score</th><th>Text</th></tr></thead><tr><td>0.9847</td><td>Apple Recalls 28,000 Faulty Batteries Sold with 15-inch PowerBook Apple has had to recall up to 28,000 notebook batteries that were sold for use with their 15-inch PowerBook. Apple reports that faulty batteries sold between January 2004 and August 2004 can overheat and pose a fire hazard.</td></tr><tr><td>0.9733</td><td>Apple warns about bad batteries Apple is recalling 28,000 faulty batteries for its 15-inch Powerbook G4 laptops.</td></tr></table>"+ ],+ "text/plain": [+ "<IPython.core.display.HTML object>"+ ]+ },+ "metadata": {+ "tags": []+ }+ },+ {+ "output_type": "display_data",+ "data": {+ "text/html": [+ "\n",+ " <style type='text/css'>\n",+ " @import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');\n",+ " table {\n",+ " border-collapse: collapse;\n",+ " width: 900px;\n",+ " }\n",+ " th, td {\n",+ " border: 1px solid #9e9e9e;\n",+ " padding: 10px;\n",+ " font: 15px Oswald;\n",+ " }\n",+ " </style>\n",+ " <h3>Best planets to explore for life</h3><table><thead><tr><th>Score</th><th>Text</th></tr></thead><tr><td>0.9110</td><td>Tiny 'David' Telescope Finds 'Goliath' Planet A newfound planet detected by a small, 4-inch-diameter telescope demonstrates that we are at the cusp of a new age of planet discovery. Soon, new worlds may be located at an accelerating pace, bringing the detection of the first Earth-sized world one step closer.</td></tr><tr><td>0.8705</td><td>Life on Mars Likely, Scientist Claims (SPACE.com) SPACE.com - DENVER, COLORADO -- Those twin robots hard at work on Mars have transmitted teasing views that reinforce the prospect that microbial life may exist on the red planet.</td></tr></table>"+ ],+ "text/plain": [+ "<IPython.core.display.HTML object>"+ ]+ },+ "metadata": {+ "tags": []+ }+ },+ {+ "output_type": "display_data",+ "data": {+ "text/html": [+ "\n",+ " <style type='text/css'>\n",+ " @import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');\n",+ " table {\n",+ " border-collapse: collapse;\n",+ " width: 900px;\n",+ " }\n",+ " th, td {\n",+ " border: 1px solid #9e9e9e;\n",+ " padding: 10px;\n",+ " font: 15px Oswald;\n",+ " }\n",+ " </style>\n",+ " <h3>LA Dodgers good news</h3><table><thead><tr><th>Score</th><th>Text</th></tr></thead><tr><td>0.9990</td><td>Green's Slam Lifts L.A. Shawn Green connects on a grand slam and a solo homer to lead the Los Angeles Dodgers past the Atlanta Braves 7-4 on Saturday.</td></tr><tr><td>0.9961</td><td>Dodgers 7, Braves 4 Los Angeles, Ca. -- Shawn Green belted a grand slam and a solo homer as Los Angeles beat Mike Hampton and the Atlanta Braves 7-to-4 Saturday afternoon.</td></tr></table>"+ ],+ "text/plain": [+ "<IPython.core.display.HTML object>"+ ]+ },+ "metadata": {+ "tags": []+ }+ },+ {+ "output_type": "display_data",+ "data": {+ "text/html": [+ "\n",+ " <style type='text/css'>\n",+ " @import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');\n",+ " table {\n",+ " border-collapse: collapse;\n",+ " width: 900px;\n",+ " }\n",+ " th, td {\n",+ " border: 1px solid #9e9e9e;\n",+ " padding: 10px;\n",+ " font: 15px Oswald;\n",+ " }\n",+ " </style>\n",+ " <h3>LA Dodgers bad news</h3><table><thead><tr><th>Score</th><th>Text</th></tr></thead><tr><td>0.9880</td><td>Expos Keep Dodgers at Bay With 8-7 Win (AP) AP - Giovanni Carrara walked Juan Rivera with the bases loaded and two outs in the ninth inning Monday night, spoiling Los Angeles' six-run comeback and handing the Montreal Expos an 8-7 victory over the Dodgers.</td></tr><tr><td>0.9671</td><td>Gagne blows his 2d save Pinch-hitter Lenny Harris delivered a three-run double off Eric Gagne with two outs in the ninth, rallying the Florida Marlins past the Dodgers, 6-4, last night in Los Angeles.</td></tr></table>"+ ],+ "text/plain": [+ "<IPython.core.display.HTML object>"+ ]+ },+ "metadata": {+ "tags": []+ }+ }+ ]+ }+ ]+}\ No newline at end of file