infinex commited on
Commit
6da4d9d
·
verified ·
1 Parent(s): d6e6892

Uploading dataset files from the local data folder.

Browse files
Files changed (1) hide show
  1. chunking.txt +416 -0
chunking.txt ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import uuid
4
+ import math
5
+ import os
6
+ import sys
7
+ from dataclasses import dataclass, field
8
+ from typing import List, Dict, Any, Set, Optional
9
+
10
+ # -----------------------------------------------------------------------------
11
+ # Imports & Dependency Checks
12
+ # -----------------------------------------------------------------------------
13
+ try:
14
+ import yaml
15
+ except ImportError:
16
+ print("Error: 'PyYAML' is required. Install via 'pip install pyyaml'.")
17
+ sys.exit(1)
18
+
19
+ try:
20
+ from openai import OpenAI, OpenAIError
21
+ except ImportError:
22
+ print("Error: 'openai' is required. Install via 'pip install openai'.")
23
+ sys.exit(1)
24
+
25
+ # We check for transformers inside the class to avoid crashing if
26
+ # the user wants heuristic mode but doesn't have transformers installed.
27
+ try:
28
+ from transformers import AutoTokenizer
29
+ TRANSFORMERS_AVAILABLE = True
30
+ except ImportError:
31
+ TRANSFORMERS_AVAILABLE = False
32
+
33
+ # -----------------------------------------------------------------------------
34
+ # Logging
35
+ # -----------------------------------------------------------------------------
36
+ logging.basicConfig(
37
+ level=logging.DEBUG,
38
+ format='[%(levelname)s] %(asctime)s - %(funcName)s:%(lineno)d - %(message)s',
39
+ datefmt='%H:%M:%S'
40
+ )
41
+ logger = logging.getLogger(__name__)
42
+
43
+ # -----------------------------------------------------------------------------
44
+ # Configuration
45
+ # -----------------------------------------------------------------------------
46
+
47
+ @dataclass
48
+ class ChunkingConfig:
49
+ """Configuration object loaded from YAML."""
50
+ api_key: str
51
+ llm_model_name: str
52
+ temperature: float
53
+
54
+ # Tokenization
55
+ tokenizer_method: str
56
+ hf_model_name: str
57
+ heuristic_chars_per_token: int
58
+
59
+ # Limits
60
+ llm_token_limit: int
61
+ overlap_token_count: int
62
+ model_token_limit: int
63
+
64
+ # Prompts
65
+ system_prompt_base: str
66
+
67
+ @classmethod
68
+ def from_yaml(cls, path: str) -> 'ChunkingConfig':
69
+ if not os.path.exists(path):
70
+ raise FileNotFoundError(f"Config file not found at: {path}")
71
+
72
+ logger.info(f"Loading configuration from {path}...")
73
+ with open(path, 'r') as f:
74
+ data = yaml.safe_load(f)
75
+
76
+ oa = data.get('openai', {})
77
+ tok = data.get('tokenization', {})
78
+ tok_heu = tok.get('heuristic', {})
79
+ tok_hf = tok.get('huggingface', {})
80
+ lim = data.get('limits', {})
81
+ prompts = data.get('prompts', {})
82
+
83
+ raw_key = oa.get('api_key', 'ENV')
84
+ api_key = os.getenv("OPENAI_API_KEY") if raw_key == "ENV" else raw_key
85
+
86
+ return cls(
87
+ api_key=api_key or "MISSING_KEY",
88
+ llm_model_name=oa.get('model_name', 'gpt-4o-mini'),
89
+ temperature=oa.get('temperature', 0.0),
90
+
91
+ # Tokenizer Config
92
+ tokenizer_method=tok.get('method', 'heuristic'),
93
+ hf_model_name=tok_hf.get('model_name', 'gpt2'),
94
+ heuristic_chars_per_token=tok_heu.get('chars_per_token', 4),
95
+
96
+ llm_token_limit=lim.get('llm_context_window', 300),
97
+ overlap_token_count=lim.get('window_overlap', 50),
98
+ model_token_limit=lim.get('target_chunk_size', 100),
99
+
100
+ system_prompt_base=prompts.get('system_instructions', '')
101
+ )
102
+
103
+ # -----------------------------------------------------------------------------
104
+ # Data Structures
105
+ # -----------------------------------------------------------------------------
106
+
107
+ @dataclass
108
+ class Line:
109
+ number: int
110
+ text: str
111
+ token_count: int
112
+
113
+ @dataclass
114
+ class PreChunkSegment:
115
+ lines: List[Line]
116
+ segment_id: str = field(default_factory=lambda: str(uuid.uuid4()))
117
+
118
+ @property
119
+ def formatted_text(self) -> str:
120
+ return "\n".join([f"{line.number} | {line.text}" for line in self.lines])
121
+
122
+ @dataclass
123
+ class SemanticGroup:
124
+ line_numbers: Set[int]
125
+
126
+ # -----------------------------------------------------------------------------
127
+ # Service Implementation
128
+ # -----------------------------------------------------------------------------
129
+
130
+ class DocumentChunkingService:
131
+ def __init__(self, config_path: str = "config.yaml"):
132
+ # 1. Load Config
133
+ try:
134
+ self.config = ChunkingConfig.from_yaml(config_path)
135
+ except Exception as e:
136
+ logger.critical(f"Failed to load config: {e}")
137
+ sys.exit(1)
138
+
139
+ # 2. Setup Tokenizer based on Method
140
+ self.hf_tokenizer = None
141
+
142
+ if self.config.tokenizer_method == "huggingface":
143
+ if not TRANSFORMERS_AVAILABLE:
144
+ logger.critical("Config requests 'huggingface', but library is missing. Install 'transformers'.")
145
+ sys.exit(1)
146
+
147
+ try:
148
+ logger.info(f"Initializing HuggingFace Tokenizer: {self.config.hf_model_name}")
149
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
150
+ self.hf_tokenizer = AutoTokenizer.from_pretrained(self.config.hf_model_name)
151
+ except Exception as e:
152
+ logger.critical(f"Failed to load HF Tokenizer: {e}")
153
+ sys.exit(1)
154
+
155
+ elif self.config.tokenizer_method == "heuristic":
156
+ logger.info(f"Using Heuristic Tokenizer ({self.config.heuristic_chars_per_token} chars/token)")
157
+
158
+ else:
159
+ logger.warning(f"Unknown tokenizer method '{self.config.tokenizer_method}'. Defaulting to heuristic.")
160
+
161
+ # 3. Setup OpenAI
162
+ if self.config.api_key == "MISSING_KEY":
163
+ logger.critical("No valid API Key found.")
164
+ self.client = None
165
+ else:
166
+ try:
167
+ self.client = OpenAI(api_key=self.config.api_key)
168
+ except Exception as e:
169
+ logger.error(f"Failed to initialize OpenAI Client: {e}")
170
+ sys.exit(1)
171
+
172
+ def _count_tokens(self, text: str) -> int:
173
+ """
174
+ Determines token count based on the configured method.
175
+ """
176
+ if not text:
177
+ return 0
178
+
179
+ if self.config.tokenizer_method == "huggingface" and self.hf_tokenizer:
180
+ # HuggingFace Count
181
+ return len(self.hf_tokenizer.encode(text, add_special_tokens=False))
182
+ else:
183
+ # Heuristic Count
184
+ return math.ceil(len(text) / self.config.heuristic_chars_per_token)
185
+
186
+ def _prepare_lines(self, document_text: str) -> List[Line]:
187
+ logger.debug(f"Preparing lines using {self.config.tokenizer_method} method...")
188
+ raw_lines = document_text.split('\n')
189
+ processed_lines = []
190
+
191
+ for idx, text in enumerate(raw_lines, start=1):
192
+ if not text.strip(): continue
193
+ count = self._count_tokens(text)
194
+ processed_lines.append(Line(idx, text, count))
195
+
196
+ return processed_lines
197
+
198
+ def _create_pre_chunks(self, lines: List[Line]) -> List[PreChunkSegment]:
199
+ logger.debug(f"Segmenting lines (Limit: {self.config.llm_token_limit})...")
200
+ segments = []
201
+ current_segment_lines = []
202
+ current_tokens = 0
203
+
204
+ i = 0
205
+ while i < len(lines):
206
+ line = lines[i]
207
+
208
+ if current_tokens + line.token_count > self.config.llm_token_limit and current_segment_lines:
209
+ segments.append(PreChunkSegment(list(current_segment_lines)))
210
+
211
+ # Overlap Logic
212
+ overlap_buffer = []
213
+ overlap_tokens = 0
214
+ back_idx = i - 1
215
+ while back_idx >= 0:
216
+ prev_line = lines[back_idx]
217
+ if prev_line in current_segment_lines:
218
+ overlap_buffer.insert(0, prev_line)
219
+ overlap_tokens += prev_line.token_count
220
+ if overlap_tokens >= self.config.overlap_token_count:
221
+ break
222
+ else:
223
+ break
224
+ back_idx -= 1
225
+
226
+ current_segment_lines = list(overlap_buffer)
227
+ current_tokens = overlap_tokens
228
+
229
+ current_segment_lines.append(line)
230
+ current_tokens += line.token_count
231
+ i += 1
232
+
233
+ if current_segment_lines:
234
+ segments.append(PreChunkSegment(current_segment_lines))
235
+
236
+ return segments
237
+
238
+ def _call_openai(self, segment_text: str, available_lines: List[int]) -> List[List[int]]:
239
+ runtime_constraint = f"\nCRITICAL CONSTRAINT: Only use the line numbers provided in this specific range: {available_lines}"
240
+ full_system_prompt = self.config.system_prompt_base + runtime_constraint
241
+ user_prompt = f"Input Lines:\n{segment_text}\n\nOutput JSON:"
242
+
243
+ try:
244
+ logger.debug(f"Calling OpenAI (Lines {available_lines[0]}-{available_lines[-1]})...")
245
+ response = self.client.chat.completions.create(
246
+ model=self.config.llm_model_name,
247
+ messages=[
248
+ {"role": "system", "content": full_system_prompt},
249
+ {"role": "user", "content": user_prompt}
250
+ ],
251
+ response_format={"type": "json_object"},
252
+ temperature=self.config.temperature
253
+ )
254
+ parsed = json.loads(response.choices[0].message.content)
255
+ groups = parsed.get("groups", [])
256
+
257
+ if isinstance(groups, list) and all(isinstance(g, list) for g in groups):
258
+ return groups
259
+ return [[l] for l in available_lines]
260
+ except Exception as e:
261
+ logger.error(f"OpenAI Call Failed: {e}")
262
+ return [[l] for l in available_lines]
263
+
264
+ def _get_semantic_groupings(self, segments: List[PreChunkSegment]) -> List[List[int]]:
265
+ all_raw_groups = []
266
+ for idx, seg in enumerate(segments):
267
+ available_lines = [l.number for l in seg.lines]
268
+ response_groups = self._call_openai(seg.formatted_text, available_lines)
269
+ all_raw_groups.extend(response_groups)
270
+ return all_raw_groups
271
+
272
+ def _resolve_overlaps(self, raw_groups: List[List[int]], all_lines_map: Dict[int, Line]) -> List[SemanticGroup]:
273
+ parent = {line_num: line_num for line_num in all_lines_map.keys()}
274
+ def find(i):
275
+ if parent[i] == i: return i
276
+ parent[i] = find(parent[i])
277
+ return parent[i]
278
+ def union(i, j):
279
+ root_i = find(i)
280
+ root_j = find(j)
281
+ if root_i != root_j: parent[root_j] = root_i
282
+
283
+ for group in raw_groups:
284
+ if not group: continue
285
+ valid_group = [g for g in group if g in parent]
286
+ if not valid_group: continue
287
+ first = valid_group[0]
288
+ for other in valid_group[1:]:
289
+ union(first, other)
290
+
291
+ clusters: Dict[int, Set[int]] = {}
292
+ for line_num in all_lines_map.keys():
293
+ root = find(line_num)
294
+ if root not in clusters: clusters[root] = set()
295
+ clusters[root].add(line_num)
296
+ return sorted([SemanticGroup(lines) for lines in clusters.values()], key=lambda x: min(x.line_numbers))
297
+
298
+ def _finalize_chunk(self, content: str, line_numbers: List[int], parent_id: Optional[str] = None) -> List[Dict[str, Any]]:
299
+ count = self._count_tokens(content)
300
+
301
+ if count <= self.config.model_token_limit:
302
+ return [{
303
+ "content": content,
304
+ "line_numbers": line_numbers,
305
+ "token_estimate": count,
306
+ "metadata": {"parent_id": parent_id}
307
+ }]
308
+
309
+ if len(line_numbers) <= 1:
310
+ return [{
311
+ "content": content,
312
+ "line_numbers": line_numbers,
313
+ "token_estimate": count,
314
+ "metadata": {"parent_id": parent_id, "warning": "oversized"}
315
+ }]
316
+
317
+ mid = len(line_numbers) // 2
318
+ left_lines = line_numbers[:mid]
319
+ right_lines = line_numbers[mid:]
320
+
321
+ left_text = "\n".join([self.current_doc_map[n].text for n in left_lines])
322
+ right_text = "\n".join([self.current_doc_map[n].text for n in right_lines])
323
+
324
+ cid = parent_id if parent_id else str(uuid.uuid4())[:8]
325
+ results = []
326
+ results.extend(self._finalize_chunk(left_text, left_lines, parent_id=cid))
327
+ results.extend(self._finalize_chunk(right_text, right_lines, parent_id=cid))
328
+ return results
329
+
330
+ def process_document(self, plaintext: str) -> str:
331
+ logger.info(f">>> Processing Document [Mode: {self.config.tokenizer_method.upper()}]")
332
+ lines = self._prepare_lines(plaintext)
333
+ self.current_doc_map = {l.number: l for l in lines}
334
+
335
+ pre_chunks = self._create_pre_chunks(lines)
336
+ raw_groups = self._get_semantic_groupings(pre_chunks)
337
+ merged_groups = self._resolve_overlaps(raw_groups, self.current_doc_map)
338
+
339
+ final_output = []
340
+ logger.info("Finalizing chunks...")
341
+ for group in merged_groups:
342
+ sorted_nums = sorted(list(group.line_numbers))
343
+ text_content = "\n".join([self.current_doc_map[n].text for n in sorted_nums])
344
+ chunks = self._finalize_chunk(text_content, sorted_nums)
345
+ final_output.extend(chunks)
346
+
347
+ logger.info(f"<<< Done. Generated {len(final_output)} chunks.")
348
+ return json.dumps(final_output, indent=2)
349
+
350
+ # -----------------------------------------------------------------------------
351
+ # Main Execution
352
+ # -----------------------------------------------------------------------------
353
+
354
+ if __name__ == "__main__":
355
+ sample_text = """The history of Artificial Intelligence is fascinating.
356
+ It begins with the Turing Test proposed by Alan Turing.
357
+ Early AI research focused on symbolic logic and problem solving.
358
+ However, computing power was limited in the 1950s.
359
+ Decades later, machine learning emerged as a dominant paradigm.
360
+ Neural networks, inspired by the human brain, gained popularity.
361
+ Deep learning revolutionized the field in the 2010s.
362
+ Transformers, introduced by Google, changed NLP forever.
363
+ Large Language Models like GPT-4 are now commonplace.
364
+ Retrieval Augmented Generation allows LLMs to use external data.
365
+ Chunking documents is essential for RAG systems.
366
+ It preserves semantic meaning during retrieval.
367
+ This specific code implements a rigorous chunking strategy.
368
+ It uses heuristic strategies for token estimation.
369
+ The end goal is high quality embeddings."""
370
+
371
+ service = DocumentChunkingService("config.yaml")
372
+
373
+ if service.client:
374
+ result = service.process_document(sample_text)
375
+ print("\n--- Final Output JSON ---")
376
+ print(result)
377
+
378
+
379
+
380
+
381
+ openai:
382
+ api_key: "ENV"
383
+ model_name: "gpt-4o-mini"
384
+ temperature: 0.0
385
+
386
+ tokenization:
387
+ # MASTER SWITCH: Choose "heuristic" or "huggingface"
388
+ # - "heuristic": Uses simple math (chars / chars_per_token). Fast, no dependencies.
389
+ # - "huggingface": Uses a real tokenizer (e.g., gpt2). Precise, requires 'transformers' lib.
390
+ method: "heuristic"
391
+
392
+ # Settings for "heuristic" method
393
+ heuristic:
394
+ chars_per_token: 4
395
+
396
+ # Settings for "huggingface" method
397
+ huggingface:
398
+ # "gpt2" is a standard proxy for general LLM token counting
399
+ model_name: "gpt2"
400
+
401
+ limits:
402
+ # Max tokens to send to OpenAI in one request (chunk context window)
403
+ llm_context_window: 300
404
+ # Overlap between context windows to prevent cutting sentences
405
+ window_overlap: 50
406
+ # The target max size for a final, atomic chunk
407
+ target_chunk_size: 100
408
+
409
+ prompts:
410
+ system_instructions: |
411
+ You are a document chunking assistant. Your goal is to group lines of text into semantically coherent chunks.
412
+
413
+ Strict Rules:
414
+ 1. Every line number provided in the input must appear exactly once in your output.
415
+ 2. Group line numbers that belong together conceptually.
416
+ 3. Return a JSON object with a single key 'groups' containing a list of lists of integers.