File size: 5,040 Bytes
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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