Spaces:
Sleeping
Sleeping
oceansweep
commited on
Commit
•
9c56866
1
Parent(s):
21f6a30
Upload Chunk_Lib.py
Browse files- App_Function_Libraries/Chunk_Lib.py +848 -598
App_Function_Libraries/Chunk_Lib.py
CHANGED
@@ -1,599 +1,849 @@
|
|
1 |
-
# Chunk_Lib.py
|
2 |
-
#########################################
|
3 |
-
# Chunking Library
|
4 |
-
# This library is used to perform chunking of input files.
|
5 |
-
# Currently, uses naive approaches. Nothing fancy.
|
6 |
-
#
|
7 |
-
####
|
8 |
-
# Import necessary libraries
|
9 |
-
import
|
10 |
-
import
|
11 |
-
|
12 |
-
from typing import
|
13 |
-
|
14 |
-
|
15 |
-
from
|
16 |
-
|
17 |
-
|
18 |
-
from transformers import GPT2Tokenizer
|
19 |
-
import nltk
|
20 |
-
from nltk.tokenize import sent_tokenize, word_tokenize
|
21 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
22 |
-
from sklearn.metrics.pairwise import cosine_similarity
|
23 |
-
#
|
24 |
-
# Import Local
|
25 |
-
from App_Function_Libraries.Tokenization_Methods_Lib import openai_tokenize
|
26 |
-
from App_Function_Libraries.Utils.Utils import load_comprehensive_config
|
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 |
-
return
|
118 |
-
|
119 |
-
|
120 |
-
def
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
def
|
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 |
-
nltk.
|
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 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
#
|
496 |
-
#
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
#
|
530 |
-
|
531 |
-
for
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
#
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
#
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
599 |
#######################################################################################################################
|
|
|
1 |
+
# Chunk_Lib.py
|
2 |
+
#########################################
|
3 |
+
# Chunking Library
|
4 |
+
# This library is used to perform chunking of input files.
|
5 |
+
# Currently, uses naive approaches. Nothing fancy.
|
6 |
+
#
|
7 |
+
####
|
8 |
+
# Import necessary libraries
|
9 |
+
import hashlib
|
10 |
+
import logging
|
11 |
+
import re
|
12 |
+
from typing import Any, Dict, List, Optional, Tuple
|
13 |
+
#
|
14 |
+
# Import 3rd party
|
15 |
+
from openai import OpenAI
|
16 |
+
from tqdm import tqdm
|
17 |
+
from langdetect import detect
|
18 |
+
from transformers import GPT2Tokenizer
|
19 |
+
import nltk
|
20 |
+
from nltk.tokenize import sent_tokenize, word_tokenize
|
21 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
22 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
23 |
+
#
|
24 |
+
# Import Local
|
25 |
+
from App_Function_Libraries.Tokenization_Methods_Lib import openai_tokenize
|
26 |
+
from App_Function_Libraries.Utils.Utils import load_comprehensive_config
|
27 |
+
#
|
28 |
+
#######################################################################################################################
|
29 |
+
# Config Settings
|
30 |
+
#
|
31 |
+
#
|
32 |
+
# FIXME - Make sure it only downloads if it already exists, and does a check first.
|
33 |
+
# Ensure NLTK data is downloaded
|
34 |
+
def ntlk_prep():
|
35 |
+
nltk.download('punkt')
|
36 |
+
#
|
37 |
+
# Load GPT2 tokenizer
|
38 |
+
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
39 |
+
#
|
40 |
+
# Load configuration
|
41 |
+
config = load_comprehensive_config()
|
42 |
+
# Embedding Chunking options
|
43 |
+
chunk_options = {
|
44 |
+
'method': config.get('Chunking', 'method', fallback='words'),
|
45 |
+
'max_size': config.getint('Chunking', 'max_size', fallback=400),
|
46 |
+
'overlap': config.getint('Chunking', 'overlap', fallback=200),
|
47 |
+
'adaptive': config.getboolean('Chunking', 'adaptive', fallback=False),
|
48 |
+
'multi_level': config.getboolean('Chunking', 'multi_level', fallback=False),
|
49 |
+
'language': config.get('Chunking', 'language', fallback='english')
|
50 |
+
}
|
51 |
+
|
52 |
+
openai_api_key = config.get('API', 'openai_api_key')
|
53 |
+
#
|
54 |
+
# End of settings
|
55 |
+
#######################################################################################################################
|
56 |
+
#
|
57 |
+
# Functions:
|
58 |
+
|
59 |
+
def detect_language(text: str) -> str:
|
60 |
+
try:
|
61 |
+
return detect(text)
|
62 |
+
except:
|
63 |
+
# Default to English if detection fails
|
64 |
+
return 'en'
|
65 |
+
|
66 |
+
|
67 |
+
def load_document(file_path):
|
68 |
+
with open(file_path, 'r') as file:
|
69 |
+
text = file.read()
|
70 |
+
return re.sub('\\s+', ' ', text).strip()
|
71 |
+
|
72 |
+
|
73 |
+
def improved_chunking_process(text: str, custom_chunk_options: Dict[str, Any] = None) -> List[Dict[str, Any]]:
|
74 |
+
logging.debug("Improved chunking process started...")
|
75 |
+
options = chunk_options.copy()
|
76 |
+
if custom_chunk_options:
|
77 |
+
options.update(custom_chunk_options)
|
78 |
+
|
79 |
+
chunk_method = options.get('method', 'words')
|
80 |
+
base_size = options.get('base_size', 1000)
|
81 |
+
min_size = options.get('min_size', 100)
|
82 |
+
max_size = options.get('max_size', 2000)
|
83 |
+
overlap = options.get('overlap', 0)
|
84 |
+
language = options.get('language', None)
|
85 |
+
adaptive = options.get('adaptive', False)
|
86 |
+
multi_level = options.get('multi_level', False)
|
87 |
+
|
88 |
+
if language is None:
|
89 |
+
language = detect_language(text)
|
90 |
+
|
91 |
+
if adaptive:
|
92 |
+
max_chunk_size = adaptive_chunk_size(text, base_size, min_size, max_size)
|
93 |
+
else:
|
94 |
+
max_chunk_size = base_size
|
95 |
+
|
96 |
+
if multi_level:
|
97 |
+
chunks = multi_level_chunking(text, chunk_method, max_chunk_size, overlap, language)
|
98 |
+
else:
|
99 |
+
chunks = chunk_text(text, chunk_method, max_chunk_size, overlap, language)
|
100 |
+
|
101 |
+
chunks_with_metadata = []
|
102 |
+
for i, chunk in enumerate(chunks):
|
103 |
+
metadata = get_chunk_metadata(
|
104 |
+
chunk,
|
105 |
+
text,
|
106 |
+
chunk_type=chunk_method,
|
107 |
+
language=language
|
108 |
+
)
|
109 |
+
metadata['chunk_index'] = i
|
110 |
+
metadata['total_chunks'] = len(chunks)
|
111 |
+
|
112 |
+
chunks_with_metadata.append({
|
113 |
+
'text': chunk,
|
114 |
+
'metadata': metadata
|
115 |
+
})
|
116 |
+
|
117 |
+
return chunks_with_metadata
|
118 |
+
|
119 |
+
|
120 |
+
def multi_level_chunking(text: str, method: str, max_size: int, overlap: int, language: str) -> List[str]:
|
121 |
+
logging.debug("Multi-level chunking process started...")
|
122 |
+
# First level: chunk by paragraphs
|
123 |
+
paragraphs = chunk_text_by_paragraphs(text, max_size * 2, overlap)
|
124 |
+
|
125 |
+
# Second level: chunk each paragraph further
|
126 |
+
chunks = []
|
127 |
+
for para in paragraphs:
|
128 |
+
if method == 'words':
|
129 |
+
chunks.extend(chunk_text_by_words(para, max_size, overlap, language))
|
130 |
+
elif method == 'sentences':
|
131 |
+
chunks.extend(chunk_text_by_sentences(para, max_size, overlap, language))
|
132 |
+
else:
|
133 |
+
chunks.append(para)
|
134 |
+
|
135 |
+
return chunks
|
136 |
+
|
137 |
+
|
138 |
+
|
139 |
+
# FIXME - ensure language detection occurs in each chunk function
|
140 |
+
def chunk_text(text: str, method: str, max_size: int, overlap: int, language: str=None) -> List[str]:
|
141 |
+
|
142 |
+
if method == 'words':
|
143 |
+
logging.debug("Chunking by words...")
|
144 |
+
return chunk_text_by_words(text, max_size, overlap, language)
|
145 |
+
elif method == 'sentences':
|
146 |
+
logging.debug("Chunking by sentences...")
|
147 |
+
return chunk_text_by_sentences(text, max_size, overlap, language)
|
148 |
+
elif method == 'paragraphs':
|
149 |
+
logging.debug("Chunking by paragraphs...")
|
150 |
+
return chunk_text_by_paragraphs(text, max_size, overlap)
|
151 |
+
elif method == 'tokens':
|
152 |
+
logging.debug("Chunking by tokens...")
|
153 |
+
return chunk_text_by_tokens(text, max_size, overlap)
|
154 |
+
elif method == 'semantic':
|
155 |
+
logging.debug("Chunking by semantic similarity...")
|
156 |
+
return semantic_chunking(text, max_size)
|
157 |
+
else:
|
158 |
+
return [text]
|
159 |
+
|
160 |
+
def determine_chunk_position(relative_position: float) -> str:
|
161 |
+
if relative_position < 0.33:
|
162 |
+
return "This chunk is from the beginning of the document"
|
163 |
+
elif relative_position < 0.66:
|
164 |
+
return "This chunk is from the middle of the document"
|
165 |
+
else:
|
166 |
+
return "This chunk is from the end of the document"
|
167 |
+
|
168 |
+
|
169 |
+
def chunk_text_by_words(text: str, max_words: int = 300, overlap: int = 0, language: str = None) -> List[str]:
|
170 |
+
logging.debug("chunk_text_by_words...")
|
171 |
+
if language is None:
|
172 |
+
language = detect_language(text)
|
173 |
+
|
174 |
+
if language.startswith('zh'): # Chinese
|
175 |
+
import jieba
|
176 |
+
words = list(jieba.cut(text))
|
177 |
+
elif language == 'ja': # Japanese
|
178 |
+
import fugashi
|
179 |
+
tagger = fugashi.Tagger()
|
180 |
+
words = [word.surface for word in tagger(text)]
|
181 |
+
else: # Default to simple splitting for other languages
|
182 |
+
words = text.split()
|
183 |
+
|
184 |
+
chunks = []
|
185 |
+
for i in range(0, len(words), max_words - overlap):
|
186 |
+
chunk = ' '.join(words[i:i + max_words])
|
187 |
+
chunks.append(chunk)
|
188 |
+
return post_process_chunks(chunks)
|
189 |
+
|
190 |
+
|
191 |
+
def chunk_text_by_sentences(text: str, max_sentences: int = 10, overlap: int = 0, language: str = None) -> List[str]:
|
192 |
+
logging.debug("chunk_text_by_sentences...")
|
193 |
+
if language is None:
|
194 |
+
language = detect_language(text)
|
195 |
+
|
196 |
+
nltk.download('punkt', quiet=True)
|
197 |
+
|
198 |
+
if language.startswith('zh'): # Chinese
|
199 |
+
import jieba
|
200 |
+
sentences = list(jieba.cut(text, cut_all=False))
|
201 |
+
elif language == 'ja': # Japanese
|
202 |
+
import fugashi
|
203 |
+
tagger = fugashi.Tagger()
|
204 |
+
sentences = [word.surface for word in tagger(text) if word.feature.pos1 in ['記号', '補助記号'] and word.surface.strip()]
|
205 |
+
else: # Default to NLTK for other languages
|
206 |
+
sentences = sent_tokenize(text, language=language)
|
207 |
+
|
208 |
+
chunks = []
|
209 |
+
for i in range(0, len(sentences), max_sentences - overlap):
|
210 |
+
chunk = ' '.join(sentences[i:i + max_sentences])
|
211 |
+
chunks.append(chunk)
|
212 |
+
return post_process_chunks(chunks)
|
213 |
+
|
214 |
+
|
215 |
+
def chunk_text_by_paragraphs(text: str, max_paragraphs: int = 5, overlap: int = 0) -> List[str]:
|
216 |
+
logging.debug("chunk_text_by_paragraphs...")
|
217 |
+
paragraphs = re.split(r'\n\s*\n', text)
|
218 |
+
chunks = []
|
219 |
+
for i in range(0, len(paragraphs), max_paragraphs - overlap):
|
220 |
+
chunk = '\n\n'.join(paragraphs[i:i + max_paragraphs])
|
221 |
+
chunks.append(chunk)
|
222 |
+
return post_process_chunks(chunks)
|
223 |
+
|
224 |
+
|
225 |
+
def chunk_text_by_tokens(text: str, max_tokens: int = 1000, overlap: int = 0) -> List[str]:
|
226 |
+
logging.debug("chunk_text_by_tokens...")
|
227 |
+
# This is a simplified token-based chunking. For more accurate tokenization,
|
228 |
+
# consider using a proper tokenizer like GPT-2 TokenizerFast
|
229 |
+
words = text.split()
|
230 |
+
chunks = []
|
231 |
+
current_chunk = []
|
232 |
+
current_token_count = 0
|
233 |
+
|
234 |
+
for word in words:
|
235 |
+
word_token_count = len(word) // 4 + 1 # Rough estimate of token count
|
236 |
+
if current_token_count + word_token_count > max_tokens and current_chunk:
|
237 |
+
chunks.append(' '.join(current_chunk))
|
238 |
+
current_chunk = current_chunk[-overlap:] if overlap > 0 else []
|
239 |
+
current_token_count = sum(len(w) // 4 + 1 for w in current_chunk)
|
240 |
+
|
241 |
+
current_chunk.append(word)
|
242 |
+
current_token_count += word_token_count
|
243 |
+
|
244 |
+
if current_chunk:
|
245 |
+
chunks.append(' '.join(current_chunk))
|
246 |
+
|
247 |
+
return post_process_chunks(chunks)
|
248 |
+
|
249 |
+
|
250 |
+
def post_process_chunks(chunks: List[str]) -> List[str]:
|
251 |
+
return [chunk.strip() for chunk in chunks if chunk.strip()]
|
252 |
+
|
253 |
+
|
254 |
+
# FIXME - F
|
255 |
+
def get_chunk_metadata(chunk: str, full_text: str, chunk_type: str = "generic",
|
256 |
+
chapter_number: Optional[int] = None,
|
257 |
+
chapter_pattern: Optional[str] = None,
|
258 |
+
language: str = None) -> Dict[str, Any]:
|
259 |
+
try:
|
260 |
+
logging.debug("get_chunk_metadata...")
|
261 |
+
start_index = full_text.index(chunk)
|
262 |
+
end_index = start_index + len(chunk)
|
263 |
+
# Calculate a hash for the chunk
|
264 |
+
chunk_hash = hashlib.md5(chunk.encode()).hexdigest()
|
265 |
+
|
266 |
+
metadata = {
|
267 |
+
'start_index': start_index,
|
268 |
+
'end_index': end_index,
|
269 |
+
'word_count': len(chunk.split()),
|
270 |
+
'char_count': len(chunk),
|
271 |
+
'chunk_type': chunk_type,
|
272 |
+
'language': language,
|
273 |
+
'chunk_hash': chunk_hash,
|
274 |
+
'relative_position': start_index / len(full_text)
|
275 |
+
}
|
276 |
+
|
277 |
+
if chunk_type == "chapter":
|
278 |
+
metadata['chapter_number'] = chapter_number
|
279 |
+
metadata['chapter_pattern'] = chapter_pattern
|
280 |
+
|
281 |
+
return metadata
|
282 |
+
except ValueError as e:
|
283 |
+
logging.error(f"Chunk not found in full_text: {chunk[:50]}... Full text length: {len(full_text)}")
|
284 |
+
raise
|
285 |
+
|
286 |
+
|
287 |
+
def process_document_with_metadata(text: str, chunk_options: Dict[str, Any],
|
288 |
+
document_metadata: Dict[str, Any]) -> Dict[str, Any]:
|
289 |
+
chunks = improved_chunking_process(text, chunk_options)
|
290 |
+
|
291 |
+
return {
|
292 |
+
'document_metadata': document_metadata,
|
293 |
+
'chunks': chunks
|
294 |
+
}
|
295 |
+
|
296 |
+
|
297 |
+
# Hybrid approach, chunk each sentence while ensuring total token size does not exceed a maximum number
|
298 |
+
def chunk_text_hybrid(text, max_tokens=1000):
|
299 |
+
logging.debug("chunk_text_hybrid...")
|
300 |
+
sentences = nltk.tokenize.sent_tokenize(text)
|
301 |
+
chunks = []
|
302 |
+
current_chunk = []
|
303 |
+
current_length = 0
|
304 |
+
|
305 |
+
for sentence in sentences:
|
306 |
+
tokens = tokenizer.encode(sentence)
|
307 |
+
if current_length + len(tokens) <= max_tokens:
|
308 |
+
current_chunk.append(sentence)
|
309 |
+
current_length += len(tokens)
|
310 |
+
else:
|
311 |
+
chunks.append(' '.join(current_chunk))
|
312 |
+
current_chunk = [sentence]
|
313 |
+
current_length = len(tokens)
|
314 |
+
|
315 |
+
if current_chunk:
|
316 |
+
chunks.append(' '.join(current_chunk))
|
317 |
+
|
318 |
+
return chunks
|
319 |
+
|
320 |
+
|
321 |
+
# Thanks openai
|
322 |
+
def chunk_on_delimiter(input_string: str,
|
323 |
+
max_tokens: int,
|
324 |
+
delimiter: str) -> List[str]:
|
325 |
+
logging.debug("chunk_on_delimiter...")
|
326 |
+
chunks = input_string.split(delimiter)
|
327 |
+
combined_chunks, _, dropped_chunk_count = combine_chunks_with_no_minimum(
|
328 |
+
chunks, max_tokens, chunk_delimiter=delimiter, add_ellipsis_for_overflow=True)
|
329 |
+
if dropped_chunk_count > 0:
|
330 |
+
print(f"Warning: {dropped_chunk_count} chunks were dropped due to exceeding the token limit.")
|
331 |
+
combined_chunks = [f"{chunk}{delimiter}" for chunk in combined_chunks]
|
332 |
+
return combined_chunks
|
333 |
+
|
334 |
+
|
335 |
+
|
336 |
+
|
337 |
+
# ????FIXME
|
338 |
+
def recursive_summarize_chunks(chunks, summarize_func, custom_prompt, temp=None, system_prompt=None):
|
339 |
+
logging.debug("recursive_summarize_chunks...")
|
340 |
+
summarized_chunks = []
|
341 |
+
current_summary = ""
|
342 |
+
|
343 |
+
logging.debug(f"recursive_summarize_chunks: Summarizing {len(chunks)} chunks recursively...")
|
344 |
+
logging.debug(f"recursive_summarize_chunks: temperature is @ {temp}")
|
345 |
+
for i, chunk in enumerate(chunks):
|
346 |
+
if i == 0:
|
347 |
+
current_summary = summarize_func(chunk, custom_prompt, temp, system_prompt)
|
348 |
+
else:
|
349 |
+
combined_text = current_summary + "\n\n" + chunk
|
350 |
+
current_summary = summarize_func(combined_text, custom_prompt, temp, system_prompt)
|
351 |
+
|
352 |
+
summarized_chunks.append(current_summary)
|
353 |
+
|
354 |
+
return summarized_chunks
|
355 |
+
|
356 |
+
|
357 |
+
# Sample text for testing
|
358 |
+
sample_text = """
|
359 |
+
Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence
|
360 |
+
concerned with the interactions between computers and human language, in particular how to program computers
|
361 |
+
to process and analyze large amounts of natural language data. The result is a computer capable of "understanding"
|
362 |
+
the contents of documents, including the contextual nuances of the language within them. The technology can then
|
363 |
+
accurately extract information and insights contained in the documents as well as categorize and organize the documents themselves.
|
364 |
+
|
365 |
+
Challenges in natural language processing frequently involve speech recognition, natural language understanding,
|
366 |
+
and natural language generation.
|
367 |
+
|
368 |
+
Natural language processing has its roots in the 1950s. Already in 1950, Alan Turing published an article titled
|
369 |
+
"Computing Machinery and Intelligence" which proposed what is now called the Turing test as a criterion of intelligence.
|
370 |
+
"""
|
371 |
+
|
372 |
+
# Example usage of different chunking methods
|
373 |
+
# print("Chunking by words:")
|
374 |
+
# print(chunk_text_by_words(sample_text, max_words=50))
|
375 |
+
#
|
376 |
+
# print("\nChunking by sentences:")
|
377 |
+
# print(chunk_text_by_sentences(sample_text, max_sentences=2))
|
378 |
+
#
|
379 |
+
# print("\nChunking by paragraphs:")
|
380 |
+
# print(chunk_text_by_paragraphs(sample_text, max_paragraphs=1))
|
381 |
+
#
|
382 |
+
# print("\nChunking by tokens:")
|
383 |
+
# print(chunk_text_by_tokens(sample_text, max_tokens=50))
|
384 |
+
#
|
385 |
+
# print("\nHybrid chunking:")
|
386 |
+
# print(chunk_text_hybrid(sample_text, max_tokens=50))
|
387 |
+
|
388 |
+
|
389 |
+
|
390 |
+
#######################################################################################################################
|
391 |
+
#
|
392 |
+
# Experimental Semantic Chunking
|
393 |
+
#
|
394 |
+
|
395 |
+
# Chunk text into segments based on semantic similarity
|
396 |
+
def count_units(text, unit='words'):
|
397 |
+
if unit == 'words':
|
398 |
+
return len(text.split())
|
399 |
+
elif unit == 'tokens':
|
400 |
+
return len(word_tokenize(text))
|
401 |
+
elif unit == 'characters':
|
402 |
+
return len(text)
|
403 |
+
else:
|
404 |
+
raise ValueError("Invalid unit. Choose 'words', 'tokens', or 'characters'.")
|
405 |
+
|
406 |
+
|
407 |
+
def semantic_chunking(text, max_chunk_size=2000, unit='words'):
|
408 |
+
logging.debug("semantic_chunking...")
|
409 |
+
nltk.download('punkt', quiet=True)
|
410 |
+
sentences = sent_tokenize(text)
|
411 |
+
vectorizer = TfidfVectorizer()
|
412 |
+
sentence_vectors = vectorizer.fit_transform(sentences)
|
413 |
+
|
414 |
+
chunks = []
|
415 |
+
current_chunk = []
|
416 |
+
current_size = 0
|
417 |
+
|
418 |
+
for i, sentence in enumerate(sentences):
|
419 |
+
sentence_size = count_units(sentence, unit)
|
420 |
+
if current_size + sentence_size > max_chunk_size and current_chunk:
|
421 |
+
chunks.append(' '.join(current_chunk))
|
422 |
+
overlap_size = count_units(' '.join(current_chunk[-3:]), unit) # Use last 3 sentences for overlap
|
423 |
+
current_chunk = current_chunk[-3:] # Keep last 3 sentences for overlap
|
424 |
+
current_size = overlap_size
|
425 |
+
|
426 |
+
current_chunk.append(sentence)
|
427 |
+
current_size += sentence_size
|
428 |
+
|
429 |
+
if i + 1 < len(sentences):
|
430 |
+
current_vector = sentence_vectors[i]
|
431 |
+
next_vector = sentence_vectors[i + 1]
|
432 |
+
similarity = cosine_similarity(current_vector, next_vector)[0][0]
|
433 |
+
if similarity < 0.5 and current_size >= max_chunk_size // 2:
|
434 |
+
chunks.append(' '.join(current_chunk))
|
435 |
+
overlap_size = count_units(' '.join(current_chunk[-3:]), unit)
|
436 |
+
current_chunk = current_chunk[-3:]
|
437 |
+
current_size = overlap_size
|
438 |
+
|
439 |
+
if current_chunk:
|
440 |
+
chunks.append(' '.join(current_chunk))
|
441 |
+
|
442 |
+
return chunks
|
443 |
+
|
444 |
+
|
445 |
+
def semantic_chunk_long_file(file_path, max_chunk_size=1000, overlap=100, unit='words'):
|
446 |
+
logging.debug("semantic_chunk_long_file...")
|
447 |
+
try:
|
448 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
449 |
+
content = file.read()
|
450 |
+
|
451 |
+
chunks = semantic_chunking(content, max_chunk_size, unit)
|
452 |
+
return chunks
|
453 |
+
except Exception as e:
|
454 |
+
logging.error(f"Error chunking text file: {str(e)}")
|
455 |
+
return None
|
456 |
+
|
457 |
+
#
|
458 |
+
#
|
459 |
+
#######################################################################################################################
|
460 |
+
|
461 |
+
|
462 |
+
#######################################################################################################################
|
463 |
+
#
|
464 |
+
# Embedding Chunking
|
465 |
+
|
466 |
+
def chunk_for_embedding(text: str, file_name: str, full_summary: str, custom_chunk_options: Dict[str, Any] = None) -> List[Dict[str, Any]]:
|
467 |
+
options = chunk_options.copy()
|
468 |
+
if custom_chunk_options:
|
469 |
+
options.update(custom_chunk_options)
|
470 |
+
|
471 |
+
chunks = improved_chunking_process(text, options)
|
472 |
+
total_chunks = len(chunks)
|
473 |
+
|
474 |
+
chunked_text_with_headers = []
|
475 |
+
for i, chunk in enumerate(chunks, 1):
|
476 |
+
chunk_text = chunk['text']
|
477 |
+
chunk_position = determine_chunk_position(chunk['metadata']['relative_position'])
|
478 |
+
|
479 |
+
chunk_header = f"""
|
480 |
+
Original Document: {file_name}
|
481 |
+
Full Document Summary: {full_summary or "Full document summary not available."}
|
482 |
+
Chunk: {i} of {total_chunks}
|
483 |
+
Position: {chunk_position}
|
484 |
+
|
485 |
+
--- Chunk Content ---
|
486 |
+
"""
|
487 |
+
|
488 |
+
full_chunk_text = chunk_header + chunk_text
|
489 |
+
chunk['text'] = full_chunk_text
|
490 |
+
chunk['metadata']['file_name'] = file_name
|
491 |
+
chunked_text_with_headers.append(chunk)
|
492 |
+
|
493 |
+
return chunked_text_with_headers
|
494 |
+
|
495 |
+
#
|
496 |
+
# End of Embedding Chunking
|
497 |
+
#######################################################################################################################
|
498 |
+
|
499 |
+
|
500 |
+
#######################################################################################################################
|
501 |
+
#
|
502 |
+
# OpenAI Rolling Summarization
|
503 |
+
#
|
504 |
+
|
505 |
+
client = OpenAI(api_key=openai_api_key)
|
506 |
+
def get_chat_completion(messages, model='gpt-4-turbo'):
|
507 |
+
response = client.chat.completions.create(
|
508 |
+
model=model,
|
509 |
+
messages=messages,
|
510 |
+
temperature=0,
|
511 |
+
)
|
512 |
+
return response.choices[0].message.content
|
513 |
+
|
514 |
+
|
515 |
+
# This function combines text chunks into larger blocks without exceeding a specified token count.
|
516 |
+
# It returns the combined chunks, their original indices, and the number of dropped chunks due to overflow.
|
517 |
+
def combine_chunks_with_no_minimum(
|
518 |
+
chunks: List[str],
|
519 |
+
max_tokens: int,
|
520 |
+
chunk_delimiter="\n\n",
|
521 |
+
header: Optional[str] = None,
|
522 |
+
add_ellipsis_for_overflow=False,
|
523 |
+
) -> Tuple[List[str], List[List[int]], int]:
|
524 |
+
dropped_chunk_count = 0
|
525 |
+
output = [] # list to hold the final combined chunks
|
526 |
+
output_indices = [] # list to hold the indices of the final combined chunks
|
527 |
+
candidate = (
|
528 |
+
[] if header is None else [header]
|
529 |
+
) # list to hold the current combined chunk candidate
|
530 |
+
candidate_indices = []
|
531 |
+
for chunk_i, chunk in enumerate(chunks):
|
532 |
+
chunk_with_header = [chunk] if header is None else [header, chunk]
|
533 |
+
# FIXME MAKE NOT OPENAI SPECIFIC
|
534 |
+
if len(openai_tokenize(chunk_delimiter.join(chunk_with_header))) > max_tokens:
|
535 |
+
print(f"warning: chunk overflow")
|
536 |
+
if (
|
537 |
+
add_ellipsis_for_overflow
|
538 |
+
# FIXME MAKE NOT OPENAI SPECIFIC
|
539 |
+
and len(openai_tokenize(chunk_delimiter.join(candidate + ["..."]))) <= max_tokens
|
540 |
+
):
|
541 |
+
candidate.append("...")
|
542 |
+
dropped_chunk_count += 1
|
543 |
+
continue # this case would break downstream assumptions
|
544 |
+
# estimate token count with the current chunk added
|
545 |
+
# FIXME MAKE NOT OPENAI SPECIFIC
|
546 |
+
extended_candidate_token_count = len(openai_tokenize(chunk_delimiter.join(candidate + [chunk])))
|
547 |
+
# If the token count exceeds max_tokens, add the current candidate to output and start a new candidate
|
548 |
+
if extended_candidate_token_count > max_tokens:
|
549 |
+
output.append(chunk_delimiter.join(candidate))
|
550 |
+
output_indices.append(candidate_indices)
|
551 |
+
candidate = chunk_with_header # re-initialize candidate
|
552 |
+
candidate_indices = [chunk_i]
|
553 |
+
# otherwise keep extending the candidate
|
554 |
+
else:
|
555 |
+
candidate.append(chunk)
|
556 |
+
candidate_indices.append(chunk_i)
|
557 |
+
# add the remaining candidate to output if it's not empty
|
558 |
+
if (header is not None and len(candidate) > 1) or (header is None and len(candidate) > 0):
|
559 |
+
output.append(chunk_delimiter.join(candidate))
|
560 |
+
output_indices.append(candidate_indices)
|
561 |
+
return output, output_indices, dropped_chunk_count
|
562 |
+
|
563 |
+
|
564 |
+
def rolling_summarize(text: str,
|
565 |
+
detail: float = 0,
|
566 |
+
model: str = 'gpt-4-turbo',
|
567 |
+
additional_instructions: Optional[str] = None,
|
568 |
+
minimum_chunk_size: Optional[int] = 500,
|
569 |
+
chunk_delimiter: str = ".",
|
570 |
+
summarize_recursively=False,
|
571 |
+
verbose=False):
|
572 |
+
"""
|
573 |
+
Summarizes a given text by splitting it into chunks, each of which is summarized individually.
|
574 |
+
The level of detail in the summary can be adjusted, and the process can optionally be made recursive.
|
575 |
+
|
576 |
+
Parameters:
|
577 |
+
- text (str): The text to be summarized.
|
578 |
+
- detail (float, optional): A value between 0 and 1
|
579 |
+
indicating the desired level of detail in the summary. 0 leads to a higher level summary, and 1 results in a more
|
580 |
+
detailed summary. Defaults to 0.
|
581 |
+
- additional_instructions (Optional[str], optional): Additional instructions to provide to the
|
582 |
+
model for customizing summaries. - minimum_chunk_size (Optional[int], optional): The minimum size for text
|
583 |
+
chunks. Defaults to 500.
|
584 |
+
- chunk_delimiter (str, optional): The delimiter used to split the text into chunks. Defaults to ".".
|
585 |
+
- summarize_recursively (bool, optional): If True, summaries are generated recursively, using previous summaries for context.
|
586 |
+
- verbose (bool, optional): If True, prints detailed information about the chunking process.
|
587 |
+
Returns:
|
588 |
+
- str: The final compiled summary of the text.
|
589 |
+
|
590 |
+
The function first determines the number of chunks by interpolating between a minimum and a maximum chunk count
|
591 |
+
based on the `detail` parameter. It then splits the text into chunks and summarizes each chunk. If
|
592 |
+
`summarize_recursively` is True, each summary is based on the previous summaries, adding more context to the
|
593 |
+
summarization process. The function returns a compiled summary of all chunks.
|
594 |
+
"""
|
595 |
+
|
596 |
+
# check detail is set correctly
|
597 |
+
assert 0 <= detail <= 1
|
598 |
+
|
599 |
+
# interpolate the number of chunks based to get specified level of detail
|
600 |
+
max_chunks = len(chunk_on_delimiter(text, minimum_chunk_size, chunk_delimiter))
|
601 |
+
min_chunks = 1
|
602 |
+
num_chunks = int(min_chunks + detail * (max_chunks - min_chunks))
|
603 |
+
|
604 |
+
# adjust chunk_size based on interpolated number of chunks
|
605 |
+
# FIXME MAKE NOT OPENAI SPECIFIC
|
606 |
+
document_length = len(openai_tokenize(text))
|
607 |
+
chunk_size = max(minimum_chunk_size, document_length // num_chunks)
|
608 |
+
text_chunks = chunk_on_delimiter(text, chunk_size, chunk_delimiter)
|
609 |
+
if verbose:
|
610 |
+
print(f"Splitting the text into {len(text_chunks)} chunks to be summarized.")
|
611 |
+
# FIXME MAKE NOT OPENAI SPECIFIC
|
612 |
+
print(f"Chunk lengths are {[len(openai_tokenize(x)) for x in text_chunks]}")
|
613 |
+
|
614 |
+
# set system message - FIXME
|
615 |
+
system_message_content = "Rewrite this text in summarized form."
|
616 |
+
if additional_instructions is not None:
|
617 |
+
system_message_content += f"\n\n{additional_instructions}"
|
618 |
+
|
619 |
+
accumulated_summaries = []
|
620 |
+
for i, chunk in enumerate(tqdm(text_chunks)):
|
621 |
+
if summarize_recursively and accumulated_summaries:
|
622 |
+
# Combine previous summary with current chunk for recursive summarization
|
623 |
+
combined_text = accumulated_summaries[-1] + "\n\n" + chunk
|
624 |
+
user_message_content = f"Previous summary and new content to summarize:\n\n{combined_text}"
|
625 |
+
else:
|
626 |
+
user_message_content = chunk
|
627 |
+
|
628 |
+
messages = [
|
629 |
+
{"role": "system", "content": system_message_content},
|
630 |
+
{"role": "user", "content": user_message_content}
|
631 |
+
]
|
632 |
+
|
633 |
+
response = get_chat_completion(messages, model=model)
|
634 |
+
accumulated_summaries.append(response)
|
635 |
+
|
636 |
+
final_summary = '\n\n'.join(accumulated_summaries)
|
637 |
+
return final_summary
|
638 |
+
|
639 |
+
#
|
640 |
+
#
|
641 |
+
#######################################################################################################################
|
642 |
+
#
|
643 |
+
# Ebook Chapter Chunking
|
644 |
+
|
645 |
+
|
646 |
+
def chunk_ebook_by_chapters(text: str, chunk_options: Dict[str, Any]) -> List[Dict[str, Any]]:
|
647 |
+
logging.debug("chunk_ebook_by_chapters")
|
648 |
+
max_chunk_size = chunk_options.get('max_size', 300)
|
649 |
+
overlap = chunk_options.get('overlap', 0)
|
650 |
+
custom_pattern = chunk_options.get('custom_chapter_pattern', None)
|
651 |
+
|
652 |
+
# List of chapter heading patterns to try, in order
|
653 |
+
chapter_patterns = [
|
654 |
+
custom_pattern,
|
655 |
+
r'^#{1,2}\s+', # Markdown style: '# ' or '## '
|
656 |
+
r'^Chapter\s+\d+', # 'Chapter ' followed by numbers
|
657 |
+
r'^\d+\.\s+', # Numbered chapters: '1. ', '2. ', etc.
|
658 |
+
r'^[A-Z\s]+$' # All caps headings
|
659 |
+
]
|
660 |
+
|
661 |
+
chapter_positions = []
|
662 |
+
used_pattern = None
|
663 |
+
|
664 |
+
for pattern in chapter_patterns:
|
665 |
+
if pattern is None:
|
666 |
+
continue
|
667 |
+
chapter_regex = re.compile(pattern, re.MULTILINE | re.IGNORECASE)
|
668 |
+
chapter_positions = [match.start() for match in chapter_regex.finditer(text)]
|
669 |
+
if chapter_positions:
|
670 |
+
used_pattern = pattern
|
671 |
+
break
|
672 |
+
|
673 |
+
# If no chapters found, return the entire content as one chunk
|
674 |
+
if not chapter_positions:
|
675 |
+
return [{'text': text, 'metadata': get_chunk_metadata(text, text, chunk_type="whole_document")}]
|
676 |
+
|
677 |
+
# Split content into chapters
|
678 |
+
chunks = []
|
679 |
+
for i in range(len(chapter_positions)):
|
680 |
+
start = chapter_positions[i]
|
681 |
+
end = chapter_positions[i + 1] if i + 1 < len(chapter_positions) else None
|
682 |
+
chapter = text[start:end]
|
683 |
+
|
684 |
+
# Apply overlap if specified
|
685 |
+
if overlap > 0 and i > 0:
|
686 |
+
overlap_start = max(0, start - overlap)
|
687 |
+
chapter = text[overlap_start:end]
|
688 |
+
|
689 |
+
chunks.append(chapter)
|
690 |
+
|
691 |
+
# Post-process chunks
|
692 |
+
processed_chunks = post_process_chunks(chunks)
|
693 |
+
|
694 |
+
# Add metadata to chunks
|
695 |
+
return [{'text': chunk, 'metadata': get_chunk_metadata(chunk, text, chunk_type="chapter", chapter_number=i + 1,
|
696 |
+
chapter_pattern=used_pattern)}
|
697 |
+
for i, chunk in enumerate(processed_chunks)]
|
698 |
+
|
699 |
+
|
700 |
+
# # Example usage
|
701 |
+
# if __name__ == "__main__":
|
702 |
+
# sample_ebook_content = """
|
703 |
+
# # Chapter 1: Introduction
|
704 |
+
#
|
705 |
+
# This is the introduction.
|
706 |
+
#
|
707 |
+
# ## Section 1.1
|
708 |
+
#
|
709 |
+
# Some content here.
|
710 |
+
#
|
711 |
+
# # Chapter 2: Main Content
|
712 |
+
#
|
713 |
+
# This is the main content.
|
714 |
+
#
|
715 |
+
# ## Section 2.1
|
716 |
+
#
|
717 |
+
# More content here.
|
718 |
+
#
|
719 |
+
# CHAPTER THREE
|
720 |
+
#
|
721 |
+
# This is the third chapter.
|
722 |
+
#
|
723 |
+
# 4. Fourth Chapter
|
724 |
+
#
|
725 |
+
# This is the fourth chapter.
|
726 |
+
# """
|
727 |
+
#
|
728 |
+
# chunk_options = {
|
729 |
+
# 'method': 'chapters',
|
730 |
+
# 'max_size': 500,
|
731 |
+
# 'overlap': 50,
|
732 |
+
# 'custom_chapter_pattern': r'^CHAPTER\s+[A-Z]+' # Custom pattern for 'CHAPTER THREE' style
|
733 |
+
# }
|
734 |
+
#
|
735 |
+
# chunked_chapters = improved_chunking_process(sample_ebook_content, chunk_options)
|
736 |
+
#
|
737 |
+
# for i, chunk in enumerate(chunked_chapters, 1):
|
738 |
+
# print(f"Chunk {i}:")
|
739 |
+
# print(chunk['text'])
|
740 |
+
# print(f"Metadata: {chunk['metadata']}\n")
|
741 |
+
|
742 |
+
#
|
743 |
+
# End of ebook chapter chunking
|
744 |
+
#######################################################################################################################
|
745 |
+
|
746 |
+
#######################################################################################################################
|
747 |
+
#
|
748 |
+
# Functions for adapative chunking:
|
749 |
+
|
750 |
+
# FIXME - punkt
|
751 |
+
def adaptive_chunk_size(text: str, base_size: int = 1000, min_size: int = 500, max_size: int = 2000) -> int:
|
752 |
+
# Ensure NLTK data is downloaded
|
753 |
+
nltk.download('punkt', quiet=True)
|
754 |
+
|
755 |
+
# Tokenize the text into sentences
|
756 |
+
sentences = sent_tokenize(text)
|
757 |
+
|
758 |
+
# Calculate average sentence length
|
759 |
+
avg_sentence_length = sum(len(s.split()) for s in sentences) / len(sentences)
|
760 |
+
|
761 |
+
# Adjust chunk size based on average sentence length
|
762 |
+
if avg_sentence_length < 10:
|
763 |
+
size_factor = 1.2 # Increase chunk size for short sentences
|
764 |
+
elif avg_sentence_length > 20:
|
765 |
+
size_factor = 0.8 # Decrease chunk size for long sentences
|
766 |
+
else:
|
767 |
+
size_factor = 1.0
|
768 |
+
|
769 |
+
# Calculate adaptive chunk size
|
770 |
+
adaptive_size = int(base_size * size_factor)
|
771 |
+
|
772 |
+
# Ensure chunk size is within bounds
|
773 |
+
return max(min_size, min(adaptive_size, max_size))
|
774 |
+
|
775 |
+
|
776 |
+
def adaptive_chunk_size_non_punkt(text: str, base_size: int, min_size: int = 100, max_size: int = 2000) -> int:
|
777 |
+
# Adaptive logic: adjust chunk size based on text complexity
|
778 |
+
words = text.split()
|
779 |
+
if not words:
|
780 |
+
return base_size # Return base_size if text is empty
|
781 |
+
|
782 |
+
avg_word_length = sum(len(word) for word in words) / len(words)
|
783 |
+
|
784 |
+
if avg_word_length > 6: # Threshold for "complex" text
|
785 |
+
adjusted_size = int(base_size * 0.8) # Reduce chunk size for complex text
|
786 |
+
elif avg_word_length < 4: # Threshold for "simple" text
|
787 |
+
adjusted_size = int(base_size * 1.2) # Increase chunk size for simple text
|
788 |
+
else:
|
789 |
+
adjusted_size = base_size
|
790 |
+
|
791 |
+
# Ensure the chunk size is within the specified range
|
792 |
+
return max(min_size, min(adjusted_size, max_size))
|
793 |
+
|
794 |
+
|
795 |
+
def adaptive_chunking(text: str, base_size: int = 1000, min_size: int = 500, max_size: int = 2000) -> List[str]:
|
796 |
+
logging.debug("adaptive_chunking...")
|
797 |
+
chunk_size = adaptive_chunk_size(text, base_size, min_size, max_size)
|
798 |
+
words = text.split()
|
799 |
+
chunks = []
|
800 |
+
current_chunk = []
|
801 |
+
current_length = 0
|
802 |
+
|
803 |
+
for word in words:
|
804 |
+
if current_length + len(word) > chunk_size and current_chunk:
|
805 |
+
chunks.append(' '.join(current_chunk))
|
806 |
+
current_chunk = []
|
807 |
+
current_length = 0
|
808 |
+
current_chunk.append(word)
|
809 |
+
current_length += len(word) + 1 # +1 for space
|
810 |
+
|
811 |
+
if current_chunk:
|
812 |
+
chunks.append(' '.join(current_chunk))
|
813 |
+
|
814 |
+
return chunks
|
815 |
+
|
816 |
+
# FIXME - usage example
|
817 |
+
# chunk_options = {
|
818 |
+
# 'method': 'words', # or any other method
|
819 |
+
# 'base_size': 1000,
|
820 |
+
# 'min_size': 100,
|
821 |
+
# 'max_size': 2000,
|
822 |
+
# 'adaptive': True,
|
823 |
+
# 'language': 'en'
|
824 |
+
# }
|
825 |
+
#chunks = improved_chunking_process(your_text, chunk_options)
|
826 |
+
|
827 |
+
|
828 |
+
# Example of chunking a document with metadata
|
829 |
+
# document_metadata = {
|
830 |
+
# 'title': 'Example Document',
|
831 |
+
# 'author': 'John Doe',
|
832 |
+
# 'creation_date': '2023-06-14',
|
833 |
+
# 'source': 'https://example.com/document',
|
834 |
+
# 'document_type': 'article'
|
835 |
+
# }
|
836 |
+
#
|
837 |
+
# chunk_options = {
|
838 |
+
# 'method': 'sentences',
|
839 |
+
# 'base_size': 1000,
|
840 |
+
# 'adaptive': True,
|
841 |
+
# 'language': 'en'
|
842 |
+
# }
|
843 |
+
#
|
844 |
+
# processed_document = process_document_with_metadata(your_text, chunk_options, document_metadata)
|
845 |
+
|
846 |
+
|
847 |
+
#
|
848 |
+
# End of Chunking Library
|
849 |
#######################################################################################################################
|