-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsummarizer.py
More file actions
359 lines (296 loc) · 11.2 KB
/
Copy pathsummarizer.py
File metadata and controls
359 lines (296 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
"""
Text summarization methods for RQ3/Objective 4.
Implements multiple summarization strategies to test information loss.
"""
import numpy as np
from typing import List, Dict
from sklearn.feature_extraction.text import TfidfVectorizer
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.text_rank import TextRankSummarizer
from sumy.summarizers.lex_rank import LexRankSummarizer
from sumy.summarizers.lsa import LsaSummarizer
import warnings
warnings.filterwarnings('ignore')
class DocumentSummarizer:
"""
Multiple text summarization methods for comparing information loss.
"""
def __init__(self, language: str = 'english'):
"""
Initialize summarizer.
Parameters:
-----------
language : str
Language for tokenization
"""
self.language = language
def _get_target_length(self, text: str, ratio: float, min_length: int = 50,
max_length: int = 512) -> int:
"""
Calculate target summary length based on ratio.
Parameters:
-----------
text : str
Original text
ratio : float
Summary ratio (0.0 - 1.0)
min_length : int
Minimum summary length
max_length : int
Maximum summary length
Returns:
--------
int
Target length in tokens
"""
words = text.split()
target = int(len(words) * ratio)
return max(min_length, min(target, max_length))
def extractive_tfidf(self, text: str, ratio: float = 0.25,
n_sentences: int = 3) -> str:
"""
Extractive summarization using TF-IDF sentence scoring.
Parameters:
-----------
text : str
Input text
ratio : float
Summary ratio
n_sentences : int
Fallback number of sentences if ratio cannot be applied
Returns:
--------
str
Summary text
"""
if not text or len(text.strip()) == 0:
return ""
# Split into sentences (simple)
sentences = [s.strip() for s in text.split('.') if len(s.strip()) > 10]
# Derive sentence count from ratio; fall back to n_sentences for very short docs
target_n = max(1, int(len(sentences) * ratio)) if len(sentences) > 0 else n_sentences
if len(sentences) <= target_n:
return text
# Vectorize sentences
try:
vectorizer = TfidfVectorizer(stop_words='english', max_features=100)
tfidf_matrix = vectorizer.fit_transform(sentences)
# Score sentences by sum of TF-IDF
sentence_scores = np.array(tfidf_matrix.sum(axis=1)).flatten()
# Get top sentences
top_indices = sentence_scores.argsort()[-target_n:][::-1]
top_indices = sorted(top_indices) # Maintain original order
summary_sentences = [sentences[i] for i in top_indices]
return '. '.join(summary_sentences) + '.'
except:
# Fallback: return first target_n sentences
return '. '.join(sentences[:target_n]) + '.'
def textrank(self, text: str, ratio: float = 0.25, n_sentences: int = 3) -> str:
"""
TextRank summarization (graph-based).
Parameters:
-----------
text : str
Input text
ratio : float
Summary ratio
n_sentences : int
Number of sentences
Returns:
--------
str
Summary text
"""
if not text or len(text.strip()) == 0:
return ""
try:
parser = PlaintextParser.from_string(text, Tokenizer(self.language))
total_sents = len(list(parser.document.sentences))
target_n = max(1, int(total_sents * ratio)) if total_sents > 0 else n_sentences
summarizer = TextRankSummarizer()
summary = summarizer(parser.document, target_n)
return ' '.join([str(sentence) for sentence in summary])
except:
# Fallback
return self.extractive_tfidf(text, ratio, n_sentences)
def lexrank(self, text: str, ratio: float = 0.25, n_sentences: int = 3) -> str:
"""
LexRank summarization (graph-based).
Parameters:
-----------
text : str
Input text
ratio : float
Summary ratio
n_sentences : int
Number of sentences
Returns:
--------
str
Summary text
"""
if not text or len(text.strip()) == 0:
return ""
try:
parser = PlaintextParser.from_string(text, Tokenizer(self.language))
total_sents = len(list(parser.document.sentences))
target_n = max(1, int(total_sents * ratio)) if total_sents > 0 else n_sentences
summarizer = LexRankSummarizer()
summary = summarizer(parser.document, target_n)
return ' '.join([str(sentence) for sentence in summary])
except:
# Fallback
return self.extractive_tfidf(text, ratio, n_sentences)
def lsa(self, text: str, ratio: float = 0.25, n_sentences: int = 3) -> str:
"""
LSA (Latent Semantic Analysis) summarization.
Parameters:
-----------
text : str
Input text
ratio : float
Summary ratio
n_sentences : int
Number of sentences
Returns:
--------
str
Summary text
"""
if not text or len(text.strip()) == 0:
return ""
try:
parser = PlaintextParser.from_string(text, Tokenizer(self.language))
total_sents = len(list(parser.document.sentences))
target_n = max(1, int(total_sents * ratio)) if total_sents > 0 else n_sentences
summarizer = LsaSummarizer()
summary = summarizer(parser.document, target_n)
return ' '.join([str(sentence) for sentence in summary])
except:
# Fallback
return self.extractive_tfidf(text, ratio, n_sentences)
def first_n_sentences(self, text: str, ratio: float = 0.25,
n_sentences: int = 3) -> str:
"""
Baseline: Extract first N sentences.
Parameters:
-----------
text : str
Input text
ratio : float
Summary ratio (ignored, using n_sentences)
n_sentences : int
Number of sentences
Returns:
--------
str
Summary text
"""
if not text or len(text.strip()) == 0:
return ""
sentences = [s.strip() for s in text.split('.') if len(s.strip()) > 10]
target_n = max(1, int(len(sentences) * ratio)) if len(sentences) > 0 else n_sentences
if len(sentences) <= target_n:
return text
return '. '.join(sentences[:target_n]) + '.'
def summarize_documents(self, docs: List[str], method: str = 'extractive_tfidf',
ratio: float = 0.25, n_sentences: int = 3) -> List[str]:
"""
Summarize a list of documents.
Parameters:
-----------
docs : List[str]
List of documents
method : str
Summarization method ('extractive_tfidf', 'textrank', 'lexrank', 'lsa', 'first_n')
ratio : float
Summary ratio
n_sentences : int
Number of sentences
Returns:
--------
List[str]
List of summaries
"""
print(f"Summarizing {len(docs)} documents using {method} (ratio={ratio})...")
summaries = []
for i, doc in enumerate(docs):
if i % 1000 == 0 and i > 0:
print(f" Processed {i}/{len(docs)} documents...")
if method == 'extractive_tfidf':
summary = self.extractive_tfidf(doc, ratio, n_sentences)
elif method == 'textrank':
summary = self.textrank(doc, ratio, n_sentences)
elif method == 'lexrank':
summary = self.lexrank(doc, ratio, n_sentences)
elif method == 'lsa':
summary = self.lsa(doc, ratio, n_sentences)
elif method == 'first_n':
summary = self.first_n_sentences(doc, ratio, n_sentences)
else:
raise ValueError(f"Unknown method: {method}")
summaries.append(summary if summary else doc) # Keep original if summary fails
print(f"Summarization complete. Generated {len(summaries)} summaries.")
return summaries
def calculate_compression_ratio(self, original_docs: List[str],
summaries: List[str]) -> Dict[str, float]:
"""
Calculate actual compression ratio achieved.
Parameters:
-----------
original_docs : List[str]
Original documents
summaries : List[str]
Summarized documents
Returns:
--------
Dict[str, float]
Compression statistics
"""
original_lengths = [len(doc.split()) for doc in original_docs]
summary_lengths = [len(summary.split()) for summary in summaries]
avg_original = np.mean(original_lengths)
avg_summary = np.mean(summary_lengths)
compression_ratio = avg_summary / avg_original if avg_original > 0 else 0
return {
'avg_original_length': avg_original,
'avg_summary_length': avg_summary,
'compression_ratio': compression_ratio,
'total_original_words': sum(original_lengths),
'total_summary_words': sum(summary_lengths)
}
def summarize_with_multiple_methods(self, docs: List[str],
methods: List[str],
ratios: List[float],
n_sentences: int = 3) -> Dict[str, Dict[float, List[str]]]:
"""
Summarize documents using multiple methods and ratios.
Parameters:
-----------
docs : List[str]
Documents to summarize
methods : List[str]
List of methods to use
ratios : List[float]
List of compression ratios to test
n_sentences : int
Number of sentences for extractive methods
Returns:
--------
Dict[str, Dict[float, List[str]]]
Nested dict: {method: {ratio: summaries}}
"""
results = {}
for method in methods:
results[method] = {}
for ratio in ratios:
print(f"\nMethod: {method}, Ratio: {ratio}")
summaries = self.summarize_documents(docs, method, ratio, n_sentences)
results[method][ratio] = summaries
# Print compression stats
stats = self.calculate_compression_ratio(docs, summaries)
print(f" Actual compression: {stats['compression_ratio']:.2%}")
print(f" Avg original: {stats['avg_original_length']:.1f} words")
print(f" Avg summary: {stats['avg_summary_length']:.1f} words")
return results