haystack-tutorials

Форк
0
/
13_Question_generation.ipynb 
363 строки · 12.3 Кб
1
{
2
 "cells": [
3
  {
4
   "attachments": {},
5
   "cell_type": "markdown",
6
   "metadata": {
7
    "collapsed": true
8
   },
9
   "source": [
10
    "# Question Generation\n",
11
    "\n",
12
    "This is a bare bones tutorial showing what is possible with the QuestionGenerator Nodes and Pipelines which automatically\n",
13
    "generate questions which the question generation model thinks can be answered by a given document."
14
   ]
15
  },
16
  {
17
   "attachments": {},
18
   "cell_type": "markdown",
19
   "metadata": {
20
    "id": "yaaKv3_ZN-gb"
21
   },
22
   "source": [
23
    "\n",
24
    "## Preparing the Colab Environment\n",
25
    "\n",
26
    "- [Enable GPU Runtime](https://docs.haystack.deepset.ai/docs/enabling-gpu-acceleration#enabling-the-gpu-in-colab)\n"
27
   ]
28
  },
29
  {
30
   "attachments": {},
31
   "cell_type": "markdown",
32
   "metadata": {},
33
   "source": [
34
    "## Installing Haystack\n",
35
    "\n",
36
    "To start, let's install the latest release of Haystack with `pip`:"
37
   ]
38
  },
39
  {
40
   "cell_type": "code",
41
   "execution_count": null,
42
   "metadata": {
43
    "collapsed": false
44
   },
45
   "outputs": [],
46
   "source": [
47
    "%%bash\n",
48
    "\n",
49
    "pip install --upgrade pip\n",
50
    "pip install farm-haystack[colab,elasticsearch,inference]"
51
   ]
52
  },
53
  {
54
   "attachments": {},
55
   "cell_type": "markdown",
56
   "metadata": {},
57
   "source": [
58
    "### Enabling Telemetry \n",
59
    "Knowing you're using this tutorial helps us decide where to invest our efforts to build a better product but you can always opt out by commenting the following line. See [Telemetry](https://docs.haystack.deepset.ai/docs/telemetry) for more details."
60
   ]
61
  },
62
  {
63
   "cell_type": "code",
64
   "execution_count": null,
65
   "metadata": {},
66
   "outputs": [],
67
   "source": [
68
    "from haystack.telemetry import tutorial_running\n",
69
    "\n",
70
    "tutorial_running(13)"
71
   ]
72
  },
73
  {
74
   "attachments": {},
75
   "cell_type": "markdown",
76
   "metadata": {
77
    "collapsed": false
78
   },
79
   "source": [
80
    "## Logging\n",
81
    "\n",
82
    "We configure how logging messages should be displayed and which log level should be used before importing Haystack.\n",
83
    "Example log message:\n",
84
    "INFO - haystack.utils.preprocessing -  Converting data/tutorial1/218_Olenna_Tyrell.txt\n",
85
    "Default log level in basicConfig is WARNING so the explicit parameter is not necessary but can be changed easily:"
86
   ]
87
  },
88
  {
89
   "cell_type": "code",
90
   "execution_count": null,
91
   "metadata": {
92
    "collapsed": false
93
   },
94
   "outputs": [],
95
   "source": [
96
    "import logging\n",
97
    "\n",
98
    "logging.basicConfig(format=\"%(levelname)s - %(name)s -  %(message)s\", level=logging.WARNING)\n",
99
    "logging.getLogger(\"haystack\").setLevel(logging.INFO)"
100
   ]
101
  },
102
  {
103
   "cell_type": "code",
104
   "execution_count": null,
105
   "metadata": {
106
    "collapsed": false
107
   },
108
   "outputs": [],
109
   "source": [
110
    "# Imports needed to run this notebook\n",
111
    "\n",
112
    "from pprint import pprint\n",
113
    "from tqdm.auto import tqdm\n",
114
    "from haystack.nodes import QuestionGenerator, BM25Retriever, FARMReader\n",
115
    "from haystack.document_stores import ElasticsearchDocumentStore\n",
116
    "from haystack.pipelines import (\n",
117
    "    QuestionGenerationPipeline,\n",
118
    "    RetrieverQuestionGenerationPipeline,\n",
119
    "    QuestionAnswerGenerationPipeline,\n",
120
    ")\n",
121
    "from haystack.utils import launch_es, print_questions"
122
   ]
123
  },
124
  {
125
   "attachments": {},
126
   "cell_type": "markdown",
127
   "metadata": {
128
    "collapsed": false
129
   },
130
   "source": [
131
    "Let's start an Elasticsearch instance with one of the options below:"
132
   ]
133
  },
134
  {
135
   "cell_type": "code",
136
   "execution_count": null,
137
   "metadata": {
138
    "collapsed": false
139
   },
140
   "outputs": [],
141
   "source": [
142
    "# Option 1: Start Elasticsearch service via Docker\n",
143
    "launch_es()"
144
   ]
145
  },
146
  {
147
   "cell_type": "code",
148
   "execution_count": null,
149
   "metadata": {
150
    "collapsed": false,
151
    "pycharm": {
152
     "name": "#%% \n"
153
    }
154
   },
155
   "outputs": [],
156
   "source": [
157
    "# Option 2: In Colab / No Docker environments: Start Elasticsearch from source\n",
158
    "! wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.2-linux-x86_64.tar.gz -q\n",
159
    "! tar -xzf elasticsearch-7.9.2-linux-x86_64.tar.gz\n",
160
    "! chown -R daemon:daemon elasticsearch-7.9.2\n",
161
    "\n",
162
    "import os\n",
163
    "from subprocess import Popen, PIPE, STDOUT\n",
164
    "\n",
165
    "es_server = Popen(\n",
166
    "    [\"elasticsearch-7.9.2/bin/elasticsearch\"], stdout=PIPE, stderr=STDOUT, preexec_fn=lambda: os.setuid(1)  # as daemon\n",
167
    ")\n",
168
    "# wait until ES has started\n",
169
    "! sleep 30"
170
   ]
171
  },
172
  {
173
   "attachments": {},
174
   "cell_type": "markdown",
175
   "metadata": {
176
    "collapsed": false
177
   },
178
   "source": [
179
    "Let's initialize some core components"
180
   ]
181
  },
182
  {
183
   "cell_type": "code",
184
   "execution_count": null,
185
   "metadata": {
186
    "collapsed": false
187
   },
188
   "outputs": [],
189
   "source": [
190
    "text1 = \"Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace.\"\n",
191
    "text2 = \"Princess Arya Stark is the third child and second daughter of Lord Eddard Stark and his wife, Lady Catelyn Stark. She is the sister of the incumbent Westerosi monarchs, Sansa, Queen in the North, and Brandon, King of the Andals and the First Men. After narrowly escaping the persecution of House Stark by House Lannister, Arya is trained as a Faceless Man at the House of Black and White in Braavos, using her abilities to avenge her family. Upon her return to Westeros, she exacts retribution for the Red Wedding by exterminating the Frey male line.\"\n",
192
    "text3 = \"Dry Cleaning are an English post-punk band who formed in South London in 2018.[3] The band is composed of vocalist Florence Shaw, guitarist Tom Dowse, bassist Lewis Maynard and drummer Nick Buxton. They are noted for their use of spoken word primarily in lieu of sung vocals, as well as their unconventional lyrics. Their musical stylings have been compared to Wire, Magazine and Joy Division.[4] The band released their debut single, 'Magic of Meghan' in 2019. Shaw wrote the song after going through a break-up and moving out of her former partner's apartment the same day that Meghan Markle and Prince Harry announced they were engaged.[5] This was followed by the release of two EPs that year: Sweet Princess in August and Boundary Road Snacks and Drinks in October. The band were included as part of the NME 100 of 2020,[6] as well as DIY magazine's Class of 2020.[7] The band signed to 4AD in late 2020 and shared a new single, 'Scratchcard Lanyard'.[8] In February 2021, the band shared details of their debut studio album, New Long Leg. They also shared the single 'Strong Feelings'.[9] The album, which was produced by John Parish, was released on 2 April 2021.[10]\"\n",
193
    "\n",
194
    "docs = [{\"content\": text1}, {\"content\": text2}, {\"content\": text3}]\n",
195
    "\n",
196
    "# Initialize document store and write in the documents\n",
197
    "document_store = ElasticsearchDocumentStore()\n",
198
    "document_store.write_documents(docs)\n",
199
    "\n",
200
    "# Initialize Question Generator\n",
201
    "question_generator = QuestionGenerator()"
202
   ]
203
  },
204
  {
205
   "attachments": {},
206
   "cell_type": "markdown",
207
   "metadata": {
208
    "collapsed": false
209
   },
210
   "source": [
211
    "## Question Generation Pipeline\n",
212
    "\n",
213
    "The most basic version of a question generator pipeline takes a document as input and outputs generated questions\n",
214
    "which the the document can answer."
215
   ]
216
  },
217
  {
218
   "cell_type": "code",
219
   "execution_count": null,
220
   "metadata": {
221
    "collapsed": false
222
   },
223
   "outputs": [],
224
   "source": [
225
    "question_generation_pipeline = QuestionGenerationPipeline(question_generator)\n",
226
    "for idx, document in enumerate(document_store):\n",
227
    "\n",
228
    "    print(f\"\\n * Generating questions for document {idx}: {document.content[:100]}...\\n\")\n",
229
    "    result = question_generation_pipeline.run(documents=[document])\n",
230
    "    print_questions(result)"
231
   ]
232
  },
233
  {
234
   "attachments": {},
235
   "cell_type": "markdown",
236
   "metadata": {
237
    "collapsed": false
238
   },
239
   "source": [
240
    "## Retriever Question Generation Pipeline\n",
241
    "\n",
242
    "This pipeline takes a query as input. It retrieves relevant documents and then generates questions based on these."
243
   ]
244
  },
245
  {
246
   "cell_type": "code",
247
   "execution_count": null,
248
   "metadata": {
249
    "collapsed": false
250
   },
251
   "outputs": [],
252
   "source": [
253
    "retriever = BM25Retriever(document_store=document_store)\n",
254
    "rqg_pipeline = RetrieverQuestionGenerationPipeline(retriever, question_generator)\n",
255
    "\n",
256
    "print(f\"\\n * Generating questions for documents matching the query 'Arya Stark'\\n\")\n",
257
    "result = rqg_pipeline.run(query=\"Arya Stark\")\n",
258
    "print_questions(result)"
259
   ]
260
  },
261
  {
262
   "attachments": {},
263
   "cell_type": "markdown",
264
   "metadata": {
265
    "collapsed": false
266
   },
267
   "source": [
268
    "## Question Answer Generation Pipeline\n",
269
    "\n",
270
    "This pipeline takes a document as input, generates questions on it, and attempts to answer these questions using\n",
271
    "a Reader model"
272
   ]
273
  },
274
  {
275
   "cell_type": "code",
276
   "execution_count": null,
277
   "metadata": {
278
    "collapsed": false,
279
    "pycharm": {
280
     "is_executing": true
281
    }
282
   },
283
   "outputs": [],
284
   "source": [
285
    "reader = FARMReader(\"deepset/roberta-base-squad2\")\n",
286
    "qag_pipeline = QuestionAnswerGenerationPipeline(question_generator, reader)\n",
287
    "for idx, document in enumerate(tqdm(document_store)):\n",
288
    "\n",
289
    "    print(f\"\\n * Generating questions and answers for document {idx}: {document.content[:100]}...\\n\")\n",
290
    "    result = qag_pipeline.run(documents=[document])\n",
291
    "    print_questions(result)"
292
   ]
293
  },
294
  {
295
   "attachments": {},
296
   "cell_type": "markdown",
297
   "metadata": {
298
    "collapsed": false
299
   },
300
   "source": [
301
    "## Translated Question Answer Generation Pipeline\n",
302
    "Trained models for Question Answer Generation are not available in many languages other than English. Haystack\n",
303
    "provides a workaround for that issue by machine-translating a pipeline's inputs and outputs with the\n",
304
    "TranslationWrapperPipeline. The following example generates German questions and answers on a German text\n",
305
    "document - by using an English model for Question Answer Generation."
306
   ]
307
  },
308
  {
309
   "cell_type": "code",
310
   "execution_count": null,
311
   "metadata": {
312
    "collapsed": false
313
   },
314
   "outputs": [],
315
   "source": [
316
    "# Fill the document store with a German document.\n",
317
    "text1 = \"Python ist eine interpretierte Hochsprachenprogrammiersprache für allgemeine Zwecke. Sie wurde von Guido van Rossum entwickelt und 1991 erstmals veröffentlicht. Die Design-Philosophie von Python legt den Schwerpunkt auf die Lesbarkeit des Codes und die Verwendung von viel Leerraum (Whitespace).\"\n",
318
    "docs = [{\"content\": text1}]\n",
319
    "document_store.delete_documents()\n",
320
    "document_store.write_documents(docs)\n",
321
    "\n",
322
    "# Load machine translation models\n",
323
    "from haystack.nodes import TransformersTranslator\n",
324
    "\n",
325
    "in_translator = TransformersTranslator(model_name_or_path=\"Helsinki-NLP/opus-mt-de-en\")\n",
326
    "out_translator = TransformersTranslator(model_name_or_path=\"Helsinki-NLP/opus-mt-en-de\")\n",
327
    "\n",
328
    "# Wrap the previously defined QuestionAnswerGenerationPipeline\n",
329
    "from haystack.pipelines import TranslationWrapperPipeline\n",
330
    "\n",
331
    "pipeline_with_translation = TranslationWrapperPipeline(\n",
332
    "    input_translator=in_translator, output_translator=out_translator, pipeline=qag_pipeline\n",
333
    ")\n",
334
    "\n",
335
    "for idx, document in enumerate(tqdm(document_store)):\n",
336
    "    print(f\"\\n * Generating questions and answers for document {idx}: {document.content[:100]}...\\n\")\n",
337
    "    result = pipeline_with_translation.run(documents=[document])\n",
338
    "    print_questions(result)"
339
   ]
340
  }
341
 ],
342
 "metadata": {
343
  "kernelspec": {
344
   "display_name": "Python 3",
345
   "language": "python",
346
   "name": "python3"
347
  },
348
  "language_info": {
349
   "codemirror_mode": {
350
    "name": "ipython",
351
    "version": 2
352
   },
353
   "file_extension": ".py",
354
   "mimetype": "text/x-python",
355
   "name": "python",
356
   "nbconvert_exporter": "python",
357
   "pygments_lexer": "ipython2",
358
   "version": "2.7.6"
359
  }
360
 },
361
 "nbformat": 4,
362
 "nbformat_minor": 2
363
}
364

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.