File size: 14,360 Bytes
22ae78a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
360
361
362
363
364
365
366
367
#!/usr/bin/env python3
"""
Comprehensive Data Processor
============================
Processes all available data sources: PDFs, documents, existing training data,
and generates comprehensive training datasets for the enhanced tokenizer system.
"""

import json
import os
import re
from pathlib import Path
from typing import Dict, List, Any
from datetime import datetime

# PDF processing
try:
    import PyPDF2
    PDF_AVAILABLE = True
except ImportError:
    PDF_AVAILABLE = False

try:
    import pdfplumber
    PDFPLUMBER_AVAILABLE = True
except ImportError:
    PDFPLUMBER_AVAILABLE = False

class ComprehensiveDataProcessor:
    """Processes all available data sources for training."""
    
    def __init__(self):
        self.all_training_data = []
        self.processing_stats = {
            "files_processed": 0,
            "total_entries": 0,
            "sources": {}
        }
    
    def extract_pdf_text(self, pdf_path: str) -> str:
        """Extract text from PDF."""
        try:
            if PDFPLUMBER_AVAILABLE:
                text = ""
                with pdfplumber.open(pdf_path) as pdf:
                    for page in pdf.pages:
                        page_text = page.extract_text()
                        if page_text:
                            text += page_text + "\n"
                return text.strip()
            elif PDF_AVAILABLE:
                text = ""
                with open(pdf_path, 'rb') as file:
                    pdf_reader = PyPDF2.PdfReader(file)
                    for page in pdf_reader.pages:
                        text += page.extract_text() + "\n"
                return text.strip()
        except Exception as e:
            print(f"❌ PDF extraction failed for {pdf_path}: {e}")
            return ""
    
    def process_existing_jsonl(self, file_path: str) -> List[Dict[str, Any]]:
        """Process existing JSONL training files."""
        entries = []
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                for line_num, line in enumerate(f, 1):
                    line = line.strip()
                    if line:
                        try:
                            data = json.loads(line)
                            # Standardize format
                            entry = {
                                "id": f"{Path(file_path).stem}_{line_num}",
                                "source": "existing_jsonl",
                                "source_file": file_path,
                                "prompt": data.get("prompt", ""),
                                "completion": data.get("completion", ""),
                                "content": f"{data.get('prompt', '')} {data.get('completion', '')}",
                                "metadata": data.get("metadata", {}),
                                "processed_at": datetime.now().isoformat()
                            }
                            entries.append(entry)
                        except json.JSONDecodeError as e:
                            print(f"⚠️  JSON decode error in {file_path} line {line_num}: {e}")
        except Exception as e:
            print(f"❌ Error processing {file_path}: {e}")
        
        print(f"✅ Processed {len(entries)} entries from {file_path}")
        return entries
    
    def process_text_file(self, file_path: str) -> List[Dict[str, Any]]:
        """Process text/markdown files."""
        entries = []
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # Clean content
            content = re.sub(r'\s+', ' ', content).strip()
            
            # Split into chunks
            chunks = self.chunk_text(content, chunk_size=512)
            
            for i, chunk in enumerate(chunks):
                entry = {
                    "id": f"{Path(file_path).stem}_{i+1}",
                    "source": "text_file",
                    "source_file": file_path,
                    "content": chunk,
                    "metadata": {
                        "file_type": Path(file_path).suffix,
                        "chunk_id": i + 1,
                        "total_chunks": len(chunks)
                    },
                    "processed_at": datetime.now().isoformat()
                }
                entries.append(entry)
        
        except Exception as e:
            print(f"❌ Error processing {file_path}: {e}")
        
        print(f"✅ Processed {len(entries)} entries from {file_path}")
        return entries
    
    def process_pdf_file(self, file_path: str) -> List[Dict[str, Any]]:
        """Process PDF files."""
        entries = []
        try:
            text = self.extract_pdf_text(file_path)
            if text:
                # Clean and chunk text
                text = re.sub(r'\s+', ' ', text).strip()
                chunks = self.chunk_text(text, chunk_size=512)
                
                for i, chunk in enumerate(chunks):
                    entry = {
                        "id": f"{Path(file_path).stem}_{i+1}",
                        "source": "pdf_file",
                        "source_file": file_path,
                        "content": chunk,
                        "metadata": {
                            "file_type": "pdf",
                            "chunk_id": i + 1,
                            "total_chunks": len(chunks),
                            "extracted_length": len(text)
                        },
                        "processed_at": datetime.now().isoformat()
                    }
                    entries.append(entry)
        except Exception as e:
            print(f"❌ Error processing {file_path}: {e}")
        
        print(f"✅ Processed {len(entries)} entries from {file_path}")
        return entries
    
    def chunk_text(self, text: str, chunk_size: int = 512) -> List[str]:
        """Chunk text into manageable pieces."""
        words = text.split()
        chunks = []
        
        for i in range(0, len(words), chunk_size):
            chunk = ' '.join(words[i:i + chunk_size])
            if len(chunk.strip()) > 50:  # Only keep substantial chunks
                chunks.append(chunk.strip())
        
        return chunks
    
    def analyze_content_type(self, content: str) -> str:
        """Analyze content type."""
        content_lower = content.lower()
        
        # Check for code
        if any(keyword in content_lower for keyword in ['def ', 'class ', 'import ', 'function', 'var ', 'const ']):
            return "code"
        
        # Check for mathematical content
        if re.search(r'[\$\^\+\-\*\/\=\<\>\(\)]', content):
            return "mathematical"
        
        # Check for SQL
        if any(keyword in content_lower for keyword in ['select', 'from', 'where', 'join', 'sql']):
            return "sql"
        
        # Check for academic/research content
        if any(keyword in content_lower for keyword in ['research', 'study', 'analysis', 'methodology', 'results']):
            return "academic"
        
        return "general"
    
    def enhance_training_entries(self, entries: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """Enhance training entries with additional metadata."""
        enhanced_entries = []
        
        for entry in entries:
            content = entry.get("content", "")
            content_type = self.analyze_content_type(content)
            
            # Add enhanced metadata
            enhanced_entry = entry.copy()
            enhanced_entry["enhanced_metadata"] = {
                "content_type": content_type,
                "word_count": len(content.split()),
                "char_count": len(content),
                "has_code": "code" in content_type,
                "has_math": "mathematical" in content_type or "$" in content,
                "has_sql": "sql" in content_type,
                "complexity_score": len(content.split()) / 100.0,
                "unique_words": len(set(content.lower().split())),
                "avg_word_length": sum(len(word) for word in content.split()) / len(content.split()) if content.split() else 0
            }
            
            enhanced_entries.append(enhanced_entry)
        
        return enhanced_entries
    
    def process_all_data_sources(self) -> Dict[str, Any]:
        """Process all available data sources."""
        print("🚀 Comprehensive Data Processing")
        print("=" * 40)
        
        # Define data sources
        jsonl_files = [
            "matrix_training_data.jsonl",
            "training_data_emergent.jsonl",
            "comprehensive_training_data.jsonl"
        ]
        
        text_files = [
            "README.md",
            "COMPLETE_INTEGRATION_SUMMARY.md",
            "THE_BLOOM_IS_COMPLETE.md",
            "COMPLETE_ACHIEVEMENT_REPORT.md",
            "BENCHMARK_ANALYSIS.md"
        ]
        
        pdf_files = [
            "LOOM_OF_EMERGENCE.pdf"
        ]
        
        all_entries = []
        
        # Process JSONL files
        print("\n📄 Processing JSONL training files...")
        for file_path in jsonl_files:
            if Path(file_path).exists():
                entries = self.process_existing_jsonl(file_path)
                all_entries.extend(entries)
                self.processing_stats["sources"][file_path] = len(entries)
                self.processing_stats["files_processed"] += 1
            else:
                print(f"⚠️  File not found: {file_path}")
        
        # Process text files
        print("\n📝 Processing text/markdown files...")
        for file_path in text_files:
            if Path(file_path).exists():
                entries = self.process_text_file(file_path)
                all_entries.extend(entries)
                self.processing_stats["sources"][file_path] = len(entries)
                self.processing_stats["files_processed"] += 1
            else:
                print(f"⚠️  File not found: {file_path}")
        
        # Process PDF files
        print("\n📄 Processing PDF files...")
        for file_path in pdf_files:
            if Path(file_path).exists():
                entries = self.process_pdf_file(file_path)
                all_entries.extend(entries)
                self.processing_stats["sources"][file_path] = len(entries)
                self.processing_stats["files_processed"] += 1
            else:
                print(f"⚠️  File not found: {file_path}")
        
        # Enhance entries
        print("\n🔧 Enhancing training entries...")
        enhanced_entries = self.enhance_training_entries(all_entries)
        
        self.processing_stats["total_entries"] = len(enhanced_entries)
        
        # Analyze content types
        content_types = {}
        for entry in enhanced_entries:
            content_type = entry["enhanced_metadata"]["content_type"]
            content_types[content_type] = content_types.get(content_type, 0) + 1
        
        results = {
            "processing_stats": self.processing_stats,
            "content_type_distribution": content_types,
            "total_entries": len(enhanced_entries),
            "timestamp": datetime.now().isoformat(),
            "sources_summary": {
                "jsonl_files": len([f for f in jsonl_files if Path(f).exists()]),
                "text_files": len([f for f in text_files if Path(f).exists()]),
                "pdf_files": len([f for f in pdf_files if Path(f).exists()])
            }
        }
        
        return results, enhanced_entries
    
    def save_comprehensive_training_data(self, entries: List[Dict[str, Any]], results: Dict[str, Any]):
        """Save comprehensive training data."""
        print(f"\n💾 Saving {len(entries)} training entries...")
        
        # Save as JSONL
        with open("comprehensive_training_data.jsonl", 'w', encoding='utf-8') as f:
            for entry in entries:
                f.write(json.dumps(entry, ensure_ascii=False) + '\n')
        
        # Save detailed results
        with open("comprehensive_processing_results.json", 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=2, ensure_ascii=False)
        
        # Save summary statistics
        summary = {
            "total_entries": len(entries),
            "content_types": results["content_type_distribution"],
            "sources": results["processing_stats"]["sources"],
            "files_processed": results["processing_stats"]["files_processed"],
            "timestamp": results["timestamp"]
        }
        
        with open("training_data_summary.json", 'w', encoding='utf-8') as f:
            json.dump(summary, f, indent=2, ensure_ascii=False)
        
        print("✅ Training data saved:")
        print("  📁 comprehensive_training_data.jsonl")
        print("  📁 comprehensive_processing_results.json")
        print("  📁 training_data_summary.json")
    
    def print_processing_summary(self, results: Dict[str, Any], entries: List[Dict[str, Any]]):
        """Print processing summary."""
        print("\n📊 Processing Summary")
        print("=" * 30)
        print(f"✅ Files processed: {results['processing_stats']['files_processed']}")
        print(f"📝 Total entries: {len(entries)}")
        
        print(f"\n📋 Content Type Distribution:")
        for content_type, count in results["content_type_distribution"].items():
            percentage = (count / len(entries)) * 100
            print(f"  {content_type}: {count} entries ({percentage:.1f}%)")
        
        print(f"\n📁 Sources:")
        for source, count in results["processing_stats"]["sources"].items():
            print(f"  {Path(source).name}: {count} entries")
        
        print(f"\n🎯 Ready for training with {len(entries)} comprehensive entries!")

def main():
    """Main processing function."""
    processor = ComprehensiveDataProcessor()
    
    # Process all data sources
    results, entries = processor.process_all_data_sources()
    
    # Save results
    processor.save_comprehensive_training_data(entries, results)
    
    # Print summary
    processor.print_processing_summary(results, entries)
    
    return results, entries

if __name__ == "__main__":
    main()