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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"id": "22da4371",
|
6 |
+
"metadata": {},
|
7 |
+
"source": [
|
8 |
+
"# Summarizer\n",
|
9 |
+
"This script is used for summarizing Czech news texts as well as for generating news headlines or abstracts. It can be considered as a demonstration for the application of our summarization models.\n"
|
10 |
+
]
|
11 |
+
},
|
12 |
+
{
|
13 |
+
"cell_type": "code",
|
14 |
+
"execution_count": 1,
|
15 |
+
"id": "99dc0be0",
|
16 |
+
"metadata": {},
|
17 |
+
"outputs": [],
|
18 |
+
"source": [
|
19 |
+
"#dependencies\n",
|
20 |
+
"import torch as pt\n",
|
21 |
+
"import numpy as np\n",
|
22 |
+
"\n",
|
23 |
+
"from collections import OrderedDict\n",
|
24 |
+
"\n",
|
25 |
+
"from transformers import AutoModelForSeq2SeqLM\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"\n",
|
28 |
+
"from sentence_splitter import SentenceSplitter, split_text_into_sentences\n",
|
29 |
+
"\n",
|
30 |
+
"#init Summarizer\n",
|
31 |
+
"#comment cuda and delete .to(cuda) if using cpuUse\n",
|
32 |
+
"class Summarizer:\n",
|
33 |
+
" def __init__(self,model, tokenizer, inference_cfg):\n",
|
34 |
+
" self.model = model\n",
|
35 |
+
" self.model.cuda()\n",
|
36 |
+
" self.tokenizer = tokenizer\n",
|
37 |
+
" self.inference_cfg = inference_cfg\n",
|
38 |
+
" self.enc_max_len = 512\n",
|
39 |
+
" \n",
|
40 |
+
" #tokenize & summarize input texts\n",
|
41 |
+
" def __call__(self, texts, inference_cfg=None):\n",
|
42 |
+
" if type(texts) == str:\n",
|
43 |
+
" texts = [texts]\n",
|
44 |
+
" assert type(texts) == list and type(texts[0]) == str, \"Expected string or list of strings\"\n",
|
45 |
+
" summaries = []\n",
|
46 |
+
" self.inference_cfg = inference_cfg if inference_cfg is not None else self.inference_cfg\n",
|
47 |
+
" for text in texts:\n",
|
48 |
+
" text = self.tokenizer.eos_token.join(SentenceSplitter(language='cs').split(text))\n",
|
49 |
+
" ttext = self.tokenizer(text,max_length = self.enc_max_len, truncation=True, padding=\"max_length\",return_tensors=\"pt\")\n",
|
50 |
+
" summaries.append(self._summarize(ttext,**self.inference_cfg)[0])\n",
|
51 |
+
" return summaries\n",
|
52 |
+
" \n",
|
53 |
+
" #summarize batch of data\n",
|
54 |
+
" def _summarize(self, data, num_beams=1, do_sample=False, \n",
|
55 |
+
" top_k=50, \n",
|
56 |
+
" top_p=1.0,\n",
|
57 |
+
" temperature=1.0,\n",
|
58 |
+
" repetition_penalty=1.0,\n",
|
59 |
+
" no_repeat_ngram_size = None,\n",
|
60 |
+
" max_length=1024,\n",
|
61 |
+
" min_length=10,\n",
|
62 |
+
" decode_decoder_ids = False,\n",
|
63 |
+
" early_stopping = False,**kwargs):\n",
|
64 |
+
" summary = model.generate(input_ids=data[\"input_ids\"].to(\"cuda\"),attention_mask=data[\"attention_mask\"].to(\"cuda\"),\n",
|
65 |
+
" num_beams= num_beams,\n",
|
66 |
+
" do_sample= do_sample,\n",
|
67 |
+
" top_k=top_k,\n",
|
68 |
+
" top_p=top_p,\n",
|
69 |
+
" temperature=temperature,\n",
|
70 |
+
" repetition_penalty=repetition_penalty,\n",
|
71 |
+
" max_length=max_length,\n",
|
72 |
+
" min_length=min_length,\n",
|
73 |
+
" early_stopping=early_stopping,\n",
|
74 |
+
" forced_bos_token_id=tokenizer.lang_code_to_id['cs_CZ'])\n",
|
75 |
+
" return self.tokenizer.batch_decode(summary,skip_special_tokens=True)\n",
|
76 |
+
"\n",
|
77 |
+
"\n"
|
78 |
+
]
|
79 |
+
},
|
80 |
+
{
|
81 |
+
"cell_type": "markdown",
|
82 |
+
"id": "24195d3c",
|
83 |
+
"metadata": {},
|
84 |
+
"source": [
|
85 |
+
"# Use\n",
|
86 |
+
"- Load Czech summarization model from https://huggingface.co/krotima1\n",
|
87 |
+
"- Summarize Czech news texts\n",
|
88 |
+
"- Play with summarization parameters"
|
89 |
+
]
|
90 |
+
},
|
91 |
+
{
|
92 |
+
"cell_type": "code",
|
93 |
+
"execution_count": 2,
|
94 |
+
"id": "343ddf97",
|
95 |
+
"metadata": {},
|
96 |
+
"outputs": [
|
97 |
+
{
|
98 |
+
"data": {
|
99 |
+
"application/vnd.jupyter.widget-view+json": {
|
100 |
+
"model_id": "915f91449a8a43458945118791b2654a",
|
101 |
+
"version_major": 2,
|
102 |
+
"version_minor": 0
|
103 |
+
},
|
104 |
+
"text/plain": [
|
105 |
+
"Downloading: 0%| | 0.00/480 [00:00<?, ?B/s]"
|
106 |
+
]
|
107 |
+
},
|
108 |
+
"metadata": {},
|
109 |
+
"output_type": "display_data"
|
110 |
+
},
|
111 |
+
{
|
112 |
+
"data": {
|
113 |
+
"application/vnd.jupyter.widget-view+json": {
|
114 |
+
"model_id": "432868a8c6164fe8b681d999a5fef236",
|
115 |
+
"version_major": 2,
|
116 |
+
"version_minor": 0
|
117 |
+
},
|
118 |
+
"text/plain": [
|
119 |
+
"Downloading: 0%| | 0.00/8.66M [00:00<?, ?B/s]"
|
120 |
+
]
|
121 |
+
},
|
122 |
+
"metadata": {},
|
123 |
+
"output_type": "display_data"
|
124 |
+
},
|
125 |
+
{
|
126 |
+
"data": {
|
127 |
+
"application/vnd.jupyter.widget-view+json": {
|
128 |
+
"model_id": "819f555f4bce4fdea3db21fe6c298975",
|
129 |
+
"version_major": 2,
|
130 |
+
"version_minor": 0
|
131 |
+
},
|
132 |
+
"text/plain": [
|
133 |
+
"Downloading: 0%| | 0.00/495 [00:00<?, ?B/s]"
|
134 |
+
]
|
135 |
+
},
|
136 |
+
"metadata": {},
|
137 |
+
"output_type": "display_data"
|
138 |
+
},
|
139 |
+
{
|
140 |
+
"name": "stderr",
|
141 |
+
"output_type": "stream",
|
142 |
+
"text": [
|
143 |
+
"/home/krotima1/projects/python/environment/venv/lib64/python3.6/site-packages/transformers/generation_utils.py:2142: UserWarning: __floordiv__ is deprecated, and its behavior will change in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values. To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor').\n",
|
144 |
+
" next_indices = next_tokens // vocab_size\n"
|
145 |
+
]
|
146 |
+
},
|
147 |
+
{
|
148 |
+
"data": {
|
149 |
+
"text/plain": [
|
150 |
+
"['Czech text Input your Czech text Komentář']"
|
151 |
+
]
|
152 |
+
},
|
153 |
+
"execution_count": 2,
|
154 |
+
"metadata": {},
|
155 |
+
"output_type": "execute_result"
|
156 |
+
}
|
157 |
+
],
|
158 |
+
"source": [
|
159 |
+
"# Summarization config, setting up hyperparameters of inference methods used during summarization\n",
|
160 |
+
"def summ_config():\n",
|
161 |
+
" cfg = OrderedDict([\n",
|
162 |
+
" # summarization model - checkpoint from website https://huggingface.co/krotima1\n",
|
163 |
+
" (\"model_name\", \"krotima1/mbart-at2h-c\"),\n",
|
164 |
+
" \n",
|
165 |
+
" #inference configuration of summ parameters\n",
|
166 |
+
" (\"inference_cfg\", OrderedDict([\n",
|
167 |
+
" (\"num_beams\", 4),\n",
|
168 |
+
" (\"top_k\", 40),\n",
|
169 |
+
" (\"top_p\", 0.92),\n",
|
170 |
+
" (\"do_sample\", True),\n",
|
171 |
+
" (\"temperature\", 0.89),\n",
|
172 |
+
" (\"repetition_penalty\", 1.2),\n",
|
173 |
+
" (\"no_repeat_ngram_size\", None),\n",
|
174 |
+
" (\"early_stopping\", True),\n",
|
175 |
+
" # (\"max_length\", 96),\n",
|
176 |
+
" (\"min_length\", 10),\n",
|
177 |
+
" ])),\n",
|
178 |
+
" #texts to summarize\n",
|
179 |
+
" (\"text\",\n",
|
180 |
+
" [\n",
|
181 |
+
" \"Input your Czech text\",\n",
|
182 |
+
" ]\n",
|
183 |
+
" ),\n",
|
184 |
+
" ])\n",
|
185 |
+
" return cfg\n",
|
186 |
+
"cfg = summ_config()\n",
|
187 |
+
"#load model & tokenizer\n",
|
188 |
+
"model = AutoModelForSeq2SeqLM.from_pretrained(cfg[\"model_name\"])\n",
|
189 |
+
"tokenizer = AutoTokenizer.from_pretrained(cfg[\"model_name\"])\n",
|
190 |
+
"#init summarizer\n",
|
191 |
+
"summarize = Summarizer(model, tokenizer, cfg[\"inference_cfg\"])\n",
|
192 |
+
"#summarize Czech texts - jdem na to\n",
|
193 |
+
"#cfg[\"text\"]=...\n",
|
194 |
+
"summarize(cfg[\"text\"])"
|
195 |
+
]
|
196 |
+
},
|
197 |
+
{
|
198 |
+
"cell_type": "markdown",
|
199 |
+
"id": "3f1ff982",
|
200 |
+
"metadata": {},
|
201 |
+
"source": [
|
202 |
+
"#### Change text to summarize"
|
203 |
+
]
|
204 |
+
},
|
205 |
+
{
|
206 |
+
"cell_type": "code",
|
207 |
+
"execution_count": 3,
|
208 |
+
"id": "2f698b53",
|
209 |
+
"metadata": {},
|
210 |
+
"outputs": [],
|
211 |
+
"source": [
|
212 |
+
"cfg[\"text\"] = \"Nováčci, které stvořila soutěž Česko hledá SuperStar, vstoupí do konkurence s osvědčenými jmény domácího trhu. Jedním z nich je Lucie Bílá, která vydá kolekci hitů nazvanou Láska je láska. Naopak její kolegyně Anna K. bude mít zbrusu nové písně. Styl alba Anna K.: Noc na zemi prý připomíná rockový nářez s místy až mrazivým soundem.\\nDo společnosti hvězd se vypracoval drsný zpěvák Daniel Landa, jehož album Neofolk vyjde začátkem října. \\\"Na desce jsou písničky, které zdáli folk připomínají. Více než dříve kladu důraz na jejich texty. Neofolk mi přijde jako větší vykřičník a jistě i zlobivější název. Jinak je to bigbít i folk. Po obsahu,\\\" míní Landa, který pracuje na dvou muzikálech. Navíc v listopadu vydá záznam z vyšehradského koncertu, na kterém zpíval písně Karla Kryla.\\nKarel Plíhal si zase oblíbil básníka Josefa Kainara, jemuž vzdává hold na desce Nebe na zemi. Práce na tomto dlouho odkládaném a několikrát ohlašovaném albu se protáhly na šest let. Za tu dobu Plíhal nastudoval Kainarovu tvorbu a našel způsob, kterým by ji nejlépe vyjádřil. Stačí mu k tomu kytara, hlas a hostující zpěvačka Zuzana Navarová.\\nPetr Muk si vybral jiné oblíbence: britskou kapelu Erasure, se kterou kdysi jako vokalista kapely Oceán odehrál 27 koncertů ve Velké Británii a Irsku. Na minialbu Oh L\\\"Amour chce Muk představit některé jejich písně.\\nKoncem září se objeví novinka kapely Kryštof. Třetí album Mikrokosmos vznikalo pod dohledem Jana P. Muchowa, který si přál, aby kryštofovská muzika zněla maximálně živě, bez elektronických či jiných efektů. Hit Srdce, který se dostal do vysílání hudební televize MTV, byl vybrán jako propagační píseň.\\nŘíká se, že třetí album je rozhodující. Přesvědčí se o tom i kapela MIG 21, soustředěná kolem herce a zpěváka Jiřího Macháčka. Jejich nová deska Pop Pop Pop ukazuje směr, kterým MIG 21 poletí. Méně se ví o listopadovém albu Midlife skupiny Support Lesbiens, která letos propustila kytaristu a skladatele Yardu Helešice a buduje nový hudební profil.\\nRuku v ruce s nástupem hudebních DVD přibudou tituly bratří Ebenů, kapel Divokej Bill, Monkey Business nebo Kabát. Teplická formace se chce ohlédnout za dvěma masivními turné let 2003 a 2004, která jí zajistila postavení nejžádanější skupiny v Česku.\""
|
213 |
+
]
|
214 |
+
},
|
215 |
+
{
|
216 |
+
"cell_type": "markdown",
|
217 |
+
"id": "bf0ed831",
|
218 |
+
"metadata": {},
|
219 |
+
"source": [
|
220 |
+
"#### summarize"
|
221 |
+
]
|
222 |
+
},
|
223 |
+
{
|
224 |
+
"cell_type": "code",
|
225 |
+
"execution_count": 9,
|
226 |
+
"id": "ec0a0cbd",
|
227 |
+
"metadata": {},
|
228 |
+
"outputs": [
|
229 |
+
{
|
230 |
+
"data": {
|
231 |
+
"text/plain": [
|
232 |
+
"['Hvězdy SuperStar míří do konkurence: Bílá chystá kolekci hitů, Anna K. nové album']"
|
233 |
+
]
|
234 |
+
},
|
235 |
+
"execution_count": 9,
|
236 |
+
"metadata": {},
|
237 |
+
"output_type": "execute_result"
|
238 |
+
}
|
239 |
+
],
|
240 |
+
"source": [
|
241 |
+
"summarize(cfg[\"text\"])"
|
242 |
+
]
|
243 |
+
},
|
244 |
+
{
|
245 |
+
"cell_type": "code",
|
246 |
+
"execution_count": null,
|
247 |
+
"id": "28cce280",
|
248 |
+
"metadata": {},
|
249 |
+
"outputs": [],
|
250 |
+
"source": []
|
251 |
+
}
|
252 |
+
],
|
253 |
+
"metadata": {
|
254 |
+
"kernelspec": {
|
255 |
+
"display_name": "Python 3",
|
256 |
+
"language": "python",
|
257 |
+
"name": "python3"
|
258 |
+
},
|
259 |
+
"language_info": {
|
260 |
+
"codemirror_mode": {
|
261 |
+
"name": "ipython",
|
262 |
+
"version": 3
|
263 |
+
},
|
264 |
+
"file_extension": ".py",
|
265 |
+
"mimetype": "text/x-python",
|
266 |
+
"name": "python",
|
267 |
+
"nbconvert_exporter": "python",
|
268 |
+
"pygments_lexer": "ipython3",
|
269 |
+
"version": "3.6.8"
|
270 |
+
}
|
271 |
+
},
|
272 |
+
"nbformat": 4,
|
273 |
+
"nbformat_minor": 5
|
274 |
+
}
|