businesslawrag / src /chunker.py
veltrixcode's picture
Upload 54 files
c49440d verified
Raw History Blame Contribute Delete
5.04 kB
import re
from typing import List, Dict, Any
# Regex patterns to detect legal headings and structural landmarks in ICAI Business Law modules
LEGAL_HEADER_PATTERNS = [
r'^(?:CHAPTER|UNIT)\s+\d+',
r'^(?:\d+\.\d+|\d+)\s+[A-Z\s]{3,}',
r'^(?:SECTION|Sec\.)\s+\d+',
r'^(?:Definition|Essential Elements|Rules regarding|Exceptions|Doctrine of|Types of|Rights of|Duties of)',
r'^(?:Example|Illustration|Leading Case|Case Law|Analysis|Summary):?',
]
COMBINED_HEADER_REGEX = re.compile("|".join(f"(?:{p})" for p in LEGAL_HEADER_PATTERNS), re.IGNORECASE)
def extract_semantic_legal_sections(text: str) -> List[Dict[str, str]]:
"""
Parses full text into logical legal blocks (by Sections, Definitions, Case Laws, Doctrines)
instead of arbitrary character cuts.
"""
paragraphs = text.split("\n\n")
sections = []
current_title = "General Overview"
current_content = []
for para in paragraphs:
para_clean = para.strip()
if not para_clean:
continue
# Check if this paragraph starts with or is a legal header
first_line = para_clean.split("\n")[0].strip()
if len(first_line) < 120 and (COMBINED_HEADER_REGEX.search(first_line) or first_line.isupper()):
# If we already have content collected, save current section
if current_content:
sections.append({
"section_title": current_title,
"content": "\n\n".join(current_content)
})
current_content = []
current_title = first_line
current_content.append(para_clean)
if current_content:
sections.append({
"section_title": current_title,
"content": "\n\n".join(current_content)
})
return sections
def split_section_into_coherent_chunks(
section_title: str,
section_content: str,
max_chunk_size: int = 850,
overlap_size: int = 150
) -> List[str]:
"""
Ensures a single legal unit/section stays unbroken if < max_chunk_size,
or splits smoothly at sentence boundaries.
"""
if len(section_content) <= max_chunk_size:
return [f"### {section_title}\n{section_content}"]
# Split into sentences / bullet points
sentences = re.split(r'(?<=[.?!])\s+(?=[A-Z0-9\(])|\n(?=[0-9ivx\(\)\-\β€’])', section_content)
chunks = []
current_chunk = []
current_len = 0
for sent in sentences:
sent = sent.strip()
if not sent:
continue
sent_len = len(sent)
if current_len + sent_len > max_chunk_size and current_chunk:
chunk_body = " ".join(current_chunk)
chunks.append(f"### {section_title}\n{chunk_body}")
# Create overlap
overlap_words = chunk_body.split()[-30:] # ~150 chars
current_chunk = [" ".join(overlap_words), sent]
current_len = len(current_chunk[0]) + sent_len
else:
current_chunk.append(sent)
current_len += sent_len
if current_chunk:
chunks.append(f"### {section_title}\n{' '.join(current_chunk)}")
return chunks
def build_contextual_chunks(pages_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Builds meaningful, semantically complete chunks with book, chapter, unit, and section context.
"""
enriched_chunks = []
for page in pages_data:
text = page["text"]
sections = extract_semantic_legal_sections(text)
for sec in sections:
sec_chunks = split_section_into_coherent_chunks(
section_title=sec["section_title"],
section_content=sec["content"],
max_chunk_size=850,
overlap_size=150
)
for c_idx, chk_text in enumerate(sec_chunks):
chunk_id = f"{page['pdf_filename']}_p{page['page_number']}_s{len(enriched_chunks)}"
# Meaningful legal header context prepended to every chunk
header_context = (
f"πŸ“– Book: ICAI CA Foundation Business Laws\n"
f"πŸ›οΈ Act/Chapter: {page['chapter']}\n"
f"πŸ“‘ Unit/Topic: {page['title']}\n"
f"πŸ“„ Official Book Page: {page['page_number']}\n"
)
full_chunk_text = f"{header_context}\n{chk_text}"
enriched_chunks.append({
"chunk_id": chunk_id,
"text": full_chunk_text,
"raw_text": chk_text,
"pdf_filename": page["pdf_filename"],
"title": page["title"],
"chapter": page["chapter"],
"page_number": page["page_number"],
"total_pages": page["total_pages"],
"section_title": sec["section_title"]
})
return enriched_chunks