LoginSignup
3
2

More than 1 year has passed since last update.

長文テキストを自動要約しよう(その2.1) 〜pysummarization(英文要約)〜

Last updated at Posted at 2021-11-23

はじめに

前の記事で紹介したテキストを自動で要約ライブラリ pysummarization のコードを英文要約用に弄った、備忘を兼ねた記事です。

image.png

pysummarizationについて

  • pysummarizationは、自然言語処理とニューラルネットワーク言語モデルを用いたPythonのテキスト自動要約ライブラリです。
  • テキストのフィルタリングとクラスタリングを「教師あり学習」を必要とすることなく、対象テキストの概要が要約できます。
  • 制作者 Accel Brain社曰く「LSTMをベースとしたSequence-to-Sequence(Seq2Seq)の学習を実現するニューラルネットワーク言語モデルの基礎的なモデルをre-seq2seqの学習モデルや再構成モデルに応用することで、文書自動要約器を実装したもの」とあります。

実行条件&やってみたこと

  • Google colabで実行
  • トランプ氏受諾演説(英語全文)2016年7月23日の内容を要約した。
  • パソコン内の任意のファイルを選択するダイアログが表示されるGoogle colabの機能を使用(対象ファイルはtxtファイルのみ) -類似性フィルターカットオフ設定をGoogle colabの機能(フォーム:スライドバー)で対応 ※設定幅: min:0.05, max:0.5, step:0.05, Default=0.25

ライブラリインストール&インポート

pysummarizationインストール
pip install pysummarization
Python-docxインストール
#Python-docxのインストール
pip install python-docx
ライブラリインポート
import pandas as pd
import re
from docx import Document
from docx.shared import RGBColor
from docx.shared import Inches
from docx.shared import Pt
from pysummarization.nlpbase.auto_abstractor import AutoAbstractor
from pysummarization.abstractabledoc.top_n_rank_abstractor import TopNRankAbstractor
from pysummarization.nlp_base import NlpBase
from pysummarization.similarityfilter.tfidf_cosine import TfIdfCosine
from pysummarization.tokenizabledoc.simple_tokenizer import SimpleTokenizer

テキスト読込み

Google‗colabファイル読込みダイアログ
from google.colab import files
print('txtファイル(UTF-8)を指定してください')
uploaded = files.upload()

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))

※以下は「trump.text」というファイル読込み後の表示をキャプチャしたものです。
image.png

類似性フィルターカットオフ設定
#@title 類似性フィルターカットオフ設定(Defalt = 0.25) { run: "auto" }
similarity_limit = 0.25 #@param {type:"slider", min:0.05, max:0.5, step:0.05}

※上記記述で以下のフォームが表示されます。
image.png

テキスト要約処理

原文書の処理
if len(uploaded.keys()) != 1:
    print("アップロードは1ファイルにのみ限ります")
else:
    target = list(uploaded.keys())[0]

with open(target) as f:
    contents = f.readlines()

document = ''.join(contents)
要約処理
print(u'[source]')
print(document)

# Object of automatic summarization.
auto_abstractor = AutoAbstractor()
# Set tokenizer.
auto_abstractor.tokenizable_doc = SimpleTokenizer()
# Set delimiter for making a list of sentence.
auto_abstractor.delimiter_list = [".", "\n"]
# Object of abstracting and filtering document.
abstractable_doc = TopNRankAbstractor()
# Summarize document.
result_dict1 = auto_abstractor.summarize(document, abstractable_doc)

# Output result.
print(u'[result summary]')
for sentence in result_dict1["summarize_result"]:
    print(sentence)

# NLPオブジェクト
nlp_base = NlpBase()
# トークナイザー設定
nlp_base.tokenizable_doc = SimpleTokenizer()
# 類似性フィルター
similarity_filter = TfIdfCosine()
# NLPオブジェクト設定
similarity_filter.nlp_base = nlp_base
# 類似性limit:limit超える文は切り捨て
similarity_filter.similarity_limit = similarity_limit

# Object of automatic summarization.
auto_abstractor = AutoAbstractor()
# Set tokenizer.
auto_abstractor.tokenizable_doc = SimpleTokenizer()
# Set delimiter for making a list of sentence.
auto_abstractor.delimiter_list = [".", "\n"]
# Object of abstracting and filtering document.
abstractable_doc = TopNRankAbstractor()
# Summarize document.
result_dict2 = auto_abstractor.summarize(document, abstractable_doc, similarity_filter)

# Output result.
print(u'[result summary:SL]')
for sentence in result_dict2["summarize_result"]:
    print(sentence)
データフレーム化
doc0 = ''.join(s for s in document)
doc1 = result_dict1["summarize_result"]
doc2 = result_dict2["summarize_result"]
doc1 = ''.join(s for s in doc1)
doc2 = ''.join(s for s in doc2)
lst1 = ["source","result summary","result summary:SL"]
lst2 = [doc0,doc1,doc2]
df = pd.DataFrame(list(zip(lst1,lst2)), columns = ['Class.','Content'])
df = df.replace( '\n', '', regex=True)

with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.colheader_justify','light', 'display.width', 2000, 'display.max_colwidth', 500):
    df = df.stack().str.lstrip().unstack()
    df = df.style.set_properties(**{'text-align': 'left'})
txt&docx_output
#要約結果出力(txt & docx)
result = '[result_summary]' +'\n'+ doc1 +'\n'+ '[result_summary:similarity_limit]' +'\n'+ doc2
with open("result_summary.txt", "w") as text_file:
    text_file.write("String Variable: %s" % result)

docx = Document() 
docx.add_paragraph(result)
docx.save('result_summary.docx')

テキスト要約結果

データフレーム表示
df

※見やすいかな思い、こうしただけです。
image.png

要約結果

pysummarizationによる要約結果のあとに、DeepL翻訳による日本語訳もつけています。

要約結果

Friends, delegates and fellow Americans: I humbly and gratefully accept your nomination for the presidency of the United States.
Who would have believed that when we started this journey on June 16th of last year, we – and I say we because we are a team – would have received almost 14 million votes, the most in the history of the Republican Party, and that the Republican Party would get 60 percent more votes than it received eight years ago.
Who would have believed this? Who would have believed this? The Democrats, on the other hand, received 20 percent fewer votes than they got four years ago.
Together, we will lead our party back to the White House, and we will lead our country back to safety, prosperity, and peace.
We will be a country of generosity and warmth.
But we will also be a country of law and order.
Our Convention occurs at a moment of crisis for our nation.
Millions of Democrats will join our movement because we are going to fix the system so it works fairly, and justly, for each and every American.
We will completely rebuild our depleted military, and the countries that we are protecting, at a massive cost to us, will be asked to pay their fair share.
I'm asking for your support tonight so that I can be your champion in the White House.

DeepL翻訳による日訳

友人、代表者、そして仲間のアメリカ人。私は謙虚に、そして感謝の気持ちを込めて、皆様からの米国大統領選へのご指名をお受けします。
昨年6月16日に私たちがこの旅を始めたとき、私たち-私たちはチームですから私たちと言います-が、共和党史上最多の約1,400万票を獲得し、共和党が8年前よりも60%多くの票を獲得することになると、誰が信じたでしょうか。 これを誰が信じたでしょうか?誰がこんなことを信じただろうか?一方、民主党は、4年前よりも20%少ない票しか獲得できませんでした。
私たちは共に、我が党をホワイトハウスに戻し、国を安全、繁栄、平和に導くでしょう。 私たちは、寛大さと暖かさを持つ国になるでしょう。
しかし、私たちは法と秩序の国でもあります。
私たちの大会は、わが国の危機的状況の中で開催されます。
何百万人もの民主党員が我々の運動に参加するだろう。なぜなら、我々はシステムを修正して、アメリカ人一人ひとりのために公平かつ公正に機能するようにするつもりだからである。
私たちは枯渇した軍隊を完全に再建し、多額の費用をかけて保護している国々に、公平な負担を求めることになります。
私がホワイトハウスで皆さんの支持者になれるよう、今夜は皆さんのご支援をお願いします。

要約結果:SF(0.25)

Friends, delegates and fellow Americans: I humbly and gratefully accept your nomination for the presidency of the United States.
Who would have believed that when we started this journey on June 16th of last year, we – and I say we because we are a team – would have received almost 14 million votes, the most in the history of the Republican Party, and that the Republican Party would get 60 percent more votes than it received eight years ago.
We will be a country of generosity and warmth.
But we will also be a country of law and order.
I have a message for all of you: the crime and violence that today afflicts our nation will soon, and I mean very soon, come to an end.
Again, I will tell you the plain facts that have been edited out of your nightly news and your morning newspaper: Nearly Four in 10 African-American children are living in poverty, while 58% of African-American youth are now not employed.
This was just prior to the signing of the Iran deal, which gave back to Iran 150 billion dollars and gave us absolutely nothing – it will go down in history as one of the worst deals ever negotiated.
On the economy, I will outline reforms to add millions of new jobs and trillions in new wealth that can be used to rebuild America.
We will completely rebuild our depleted military, and the countries that we are protecting, at a massive cost to us, will be asked to pay their fair share.
We can accomplish these great things, and so much more – all we need to do is start believing in ourselves and in our country again.

DeepL翻訳による日訳

友人、代議員、そしてアメリカ国民の皆さん。私は謙虚に、そして感謝の気持ちを込めて、皆様からの米国大統領選へのご指名をお受けします。
昨年6月16日に私たちがこの旅を始めたとき、私たち、そして私たちがチームであることから私たちと言いますが、共和党史上最多の約1,400万票を獲得し、共和党が8年前よりも60%多くの票を獲得することになるとは、誰が信じたでしょうか。
私たちは、寛大さと温かさを持つ国になるでしょう。
しかし、私たちは法と秩序の国にもなります。
今日、私たちの国を苦しめている犯罪や暴力は、まもなく、つまり非常にまもなく終焉を迎えます。
繰り返しになりますが、毎晩のニュースや朝刊では編集されてしまった明白な事実をお伝えします。アフリカ系アメリカ人の子どもたちの10人に4人が貧困状態にあり、アフリカ系アメリカ人の若者の58%が失業しています。
これは、イランに1,500億ドルを返し、私たちには何も与えないというイランとの取引に署名する直前のことで、これまでに交渉された中で最悪の取引として歴史に残るでしょう。
経済面では、何百万もの新規雇用と何兆もの富を創出し、米国の再建に役立てるための改革の概要を説明します。
枯渇した軍隊を完全に再建し、多額の費用をかけて保護している国々には、相応の負担を求めます。
私たちに必要なのは、自分自身とこの国を再び信じることだけです。

最後に

pysummarizationは英文要約もすごいです。
英文要約~その後の日本語訳までPythonでやり切れればよかったですが、googletransがうまくいかず断念し、割り切ってtxtとdocxを出力する仕様にしました。

今回の記事はここまでです。最後まで読んでいただき、ありがとうございました。

参考サイト

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2