File size: 5,758 Bytes
968e24d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# """Create SQLite index for fast paragraph lookup"""

# import sqlite3
# import json
# from pathlib import Path
# from tqdm import tqdm

# def create_sqlite_index():
#     print("Creating SQLite index...")
    
#     db_path = Path("data/processed/indexed/paragraphs.db")
#     db_path.parent.mkdir(parents=True, exist_ok=True)
    
#     # Create database
#     conn = sqlite3.connect(db_path)
#     cursor = conn.cursor()
    
#     # Create table
#     cursor.execute("""
#         CREATE TABLE IF NOT EXISTS paragraphs (
#             id TEXT PRIMARY KEY,
#             judgment_id TEXT,
#             page_no INTEGER,
#             text TEXT,
#             char_count INTEGER,
#             word_count INTEGER
#         )
#     """)
    
#     cursor.execute("CREATE INDEX IF NOT EXISTS idx_judgment ON paragraphs(judgment_id)")
    
#     # Load data
#     index_file = Path("data/processed/indexed/paragraph_index.jsonl")
    
#     with open(index_file, 'r', encoding='utf-8') as f:
#         total = sum(1 for _ in f)
    
#     with open(index_file, 'r', encoding='utf-8') as f:
#         batch = []
#         for line in tqdm(f, total=total, desc="Inserting"):
#             p = json.loads(line)
#             batch.append((
#                 p['id'], p['judgment_id'], p['page_no'],
#                 p['text'], p['char_count'], p['word_count']
#             ))
            
#             if len(batch) >= 1000:
#                 cursor.executemany(
#                     "INSERT OR REPLACE INTO paragraphs VALUES (?,?,?,?,?,?)",
#                     batch
#                 )
#                 batch = []
        
#         if batch:
#             cursor.executemany(
#                 "INSERT OR REPLACE INTO paragraphs VALUES (?,?,?,?,?,?)",
#                 batch
#             )
    
#     conn.commit()
#     conn.close()
    
#     print(f"βœ“ SQLite index created: {db_path}")

# if __name__ == "__main__":
#     create_sqlite_index()
"""
Create SQLite index with section annotations
Source: paragraph_index_with_sections.jsonl
"""

import sqlite3
import json
from pathlib import Path
from tqdm import tqdm


INPUT_INDEX = Path("data/processed/indexed/paragraph_index_with_sections.jsonl")
DB_PATH = Path("data/processed/indexed/paragraphs.db")


def create_sqlite_index():
    print("=" * 70)
    print("NyayLens – Creating SQLite Index (with Sections)")
    print("=" * 70)

    DB_PATH.parent.mkdir(parents=True, exist_ok=True)

    # Connect to SQLite
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    # Drop existing table (derived data β†’ safe to rebuild)
    cursor.execute("DROP TABLE IF EXISTS paragraphs")

    # Create table
    cursor.execute("""
        CREATE TABLE paragraphs (
            id TEXT PRIMARY KEY,
            judgment_id TEXT,
            page_no INTEGER,
            text TEXT,
            char_count INTEGER,
            word_count INTEGER,
            section TEXT,
            section_conf REAL
        )
    """)

    # Create FTS5 virtual table for fast full-text search (BM25)
    cursor.execute("DROP TABLE IF EXISTS paragraphs_fts")
    cursor.execute("""
        CREATE VIRTUAL TABLE paragraphs_fts USING fts5(
            id UNINDEXED,
            text,
            tokenize='porter unicode61'
        )
    """)

    # Indexes for fast lookup
    cursor.execute("CREATE INDEX idx_judgment_id ON paragraphs(judgment_id)")
    cursor.execute("CREATE INDEX idx_section ON paragraphs(section)")
    cursor.execute("CREATE INDEX idx_judgment_section ON paragraphs(judgment_id, section)")

    conn.commit()

    # Count total records
    with open(INPUT_INDEX, "r", encoding="utf-8") as f:
        total = sum(1 for _ in f)

    print(f"βœ“ Inserting {total:,} paragraphs")

    # Insert data in batches
    batch = []
    BATCH_SIZE = 1000

    with open(INPUT_INDEX, "r", encoding="utf-8") as f:
        for line in tqdm(f, total=total, desc="Inserting"):
            p = json.loads(line)

            batch.append((
                p["id"],
                p["judgment_id"],
                p.get("page_no", -1),
                p["text"],
                p.get("char_count", len(p["text"])),
                p.get("word_count", len(p["text"].split())),
                p.get("section", "unknown"),
                p.get("section_conf", 0.0),
            ))

            if len(batch) >= BATCH_SIZE:
                cursor.executemany(
                    """
                    INSERT INTO paragraphs
                    (id, judgment_id, page_no, text, char_count, word_count, section, section_conf)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    batch
                )
                
                # Insert into FTS5 table
                fts_batch = [(b[0], b[3]) for b in batch]
                cursor.executemany(
                    "INSERT INTO paragraphs_fts (id, text) VALUES (?, ?)",
                    fts_batch
                )
                
                batch.clear()

        if batch:
            cursor.executemany(
                """
                INSERT INTO paragraphs
                (id, judgment_id, page_no, text, char_count, word_count, section, section_conf)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                """,
                batch
            )
            
            fts_batch = [(b[0], b[3]) for b in batch]
            cursor.executemany(
                "INSERT INTO paragraphs_fts (id, text) VALUES (?, ?)",
                fts_batch
            )

    conn.commit()
    conn.close()

    print("\nβœ“ SQLite index created successfully")
    print(f"βœ“ Database path: {DB_PATH}")
    print("=" * 70)


if __name__ == "__main__":
    create_sqlite_index()