File size: 9,174 Bytes
76d540d | 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 | """
AI Research Paper Helper - Text Processor
Handles text cleaning, section segmentation, and chunking.
"""
import re
from typing import List, Dict, Optional
from dataclasses import dataclass
import logging
from config import settings
logger = logging.getLogger(__name__)
@dataclass
class TextChunk:
"""Represents a chunk of text with metadata."""
id: str
text: str
section: Optional[str]
start_idx: int
end_idx: int
token_count: int
@dataclass
class Section:
"""Represents a document section."""
title: str
content: str
section_type: str # 'abstract', 'introduction', 'methods', 'results', 'discussion', 'conclusion', 'other'
level: int
class TextProcessor:
"""Handles all text processing operations."""
# Section title patterns for academic papers
SECTION_PATTERNS = {
'abstract': r'^abstract\s*$',
'introduction': r'^(1\.?\s*)?introduction\s*$',
'related_work': r'^(2\.?\s*)?(related\s+work|background|literature\s+review)\s*$',
'methods': r'^(3\.?\s*)?(method(s|ology)?|approach|model)\s*$',
'experiments': r'^(4\.?\s*)?(experiment(s)?|evaluation|results)\s*$',
'results': r'^(5\.?\s*)?(result(s)?|finding(s)?)\s*$',
'discussion': r'^(6\.?\s*)?discussion\s*$',
'conclusion': r'^(7\.?\s*)?(conclusion(s)?|summary)\s*$',
'references': r'^references?\s*$',
'appendix': r'^appendix\s*'
}
def __init__(self):
self.chunk_size = settings.chunk_size
self.chunk_overlap = settings.chunk_overlap
def clean_text(self, text: str) -> str:
"""Clean and normalize text."""
if not text:
return ""
# Remove excessive whitespace
text = re.sub(r'\s+', ' ', text)
# Remove control characters
text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]', '', text)
# Normalize quotes
text = text.replace('"', '"').replace('"', '"')
text = text.replace(''', "'").replace(''', "'")
# Remove multiple spaces
text = re.sub(r' {2,}', ' ', text)
return text.strip()
def extract_sections(self, content: str, sections_data: List[Dict] = None) -> List[Section]:
"""Extract sections from document content."""
if sections_data:
# Use pre-extracted section data
return [
Section(
title=s.get('title', ''),
content=self.clean_text(s.get('content', '')),
section_type=self._classify_section(s.get('title', '')),
level=s.get('level', 2)
)
for s in sections_data
]
# Try to parse sections from raw content
sections = []
lines = content.split('\n')
current_section = None
current_content = []
for line in lines:
line = line.strip()
if not line:
continue
# Check if this line is a section header
section_type = self._classify_section(line)
if section_type != 'other' and len(line) < 100:
# Save previous section
if current_section is not None:
sections.append(Section(
title=current_section,
content=self.clean_text(' '.join(current_content)),
section_type=self._classify_section(current_section),
level=2
))
current_section = line
current_content = []
else:
current_content.append(line)
# Don't forget the last section
if current_section is not None:
sections.append(Section(
title=current_section,
content=self.clean_text(' '.join(current_content)),
section_type=self._classify_section(current_section),
level=2
))
return sections
def _classify_section(self, title: str) -> str:
"""Classify a section based on its title."""
title_lower = title.lower().strip()
for section_type, pattern in self.SECTION_PATTERNS.items():
if re.match(pattern, title_lower, re.IGNORECASE):
return section_type
return 'other'
def chunk_text(
self,
text: str,
section: Optional[str] = None,
chunk_id_prefix: str = "chunk"
) -> List[TextChunk]:
"""
Split text into overlapping chunks.
Uses word-based chunking to respect word boundaries.
Overlap ensures context is preserved across chunks.
"""
if not text:
return []
text = self.clean_text(text)
words = text.split()
if not words:
return []
chunks = []
chunk_idx = 0
word_idx = 0
# Approximate tokens as words (rough estimate)
words_per_chunk = self.chunk_size
overlap_words = self.chunk_overlap
while word_idx < len(words):
# Get chunk words
end_idx = min(word_idx + words_per_chunk, len(words))
chunk_words = words[word_idx:end_idx]
chunk_text = ' '.join(chunk_words)
# Calculate character positions (approximate)
start_char = len(' '.join(words[:word_idx])) + (1 if word_idx > 0 else 0)
end_char = start_char + len(chunk_text)
chunks.append(TextChunk(
id=f"{chunk_id_prefix}_{chunk_idx}",
text=chunk_text,
section=section,
start_idx=start_char,
end_idx=end_char,
token_count=len(chunk_words)
))
chunk_idx += 1
word_idx = end_idx - overlap_words
# Prevent infinite loop
if word_idx >= len(words) or end_idx >= len(words):
break
if word_idx <= end_idx - words_per_chunk:
word_idx = end_idx
return chunks
def chunk_document(
self,
content: str,
abstract: Optional[str] = None,
sections: List[Dict] = None
) -> List[TextChunk]:
"""
Chunk an entire document, respecting section boundaries.
Strategy:
1. Abstract gets its own chunk(s)
2. Each section is chunked separately
3. If no sections, chunk the entire content
"""
all_chunks = []
chunk_counter = 0
# Handle abstract separately
if abstract:
abstract_chunks = self.chunk_text(
abstract,
section="abstract",
chunk_id_prefix=f"chunk_{chunk_counter}"
)
all_chunks.extend(abstract_chunks)
chunk_counter += len(abstract_chunks)
# Process sections
if sections:
parsed_sections = self.extract_sections(content, sections)
for section in parsed_sections:
if section.section_type == 'references':
continue # Skip references
section_chunks = self.chunk_text(
section.content,
section=section.title,
chunk_id_prefix=f"chunk_{chunk_counter}"
)
all_chunks.extend(section_chunks)
chunk_counter += len(section_chunks)
else:
# Chunk entire content
content_chunks = self.chunk_text(
content,
section=None,
chunk_id_prefix=f"chunk_{chunk_counter}"
)
all_chunks.extend(content_chunks)
return all_chunks
def extract_sentences(self, text: str) -> List[str]:
"""Extract sentences from text."""
# Simple sentence splitting
sentences = re.split(r'(?<=[.!?])\s+', text)
return [s.strip() for s in sentences if s.strip()]
def truncate_to_limit(self, text: str, max_words: int = 500) -> str:
"""Truncate text to a maximum number of words."""
words = text.split()
if len(words) <= max_words:
return text
return ' '.join(words[:max_words]) + '...'
# Singleton instance
_text_processor = None
def get_text_processor() -> TextProcessor:
"""Get the singleton text processor instance."""
global _text_processor
if _text_processor is None:
_text_processor = TextProcessor()
return _text_processor
|