File size: 11,846 Bytes
379c0ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sqlite3
import json
import time
import sys
import os
import argparse

def create_db(db_path):
    if os.path.exists(db_path):
        print(f"Removing existing {db_path} to ensure fresh schema...")
        os.remove(db_path)

    print("Creating database and tables...")
    conn = sqlite3.connect(db_path)
    
    # Crucial for large databases: increase page size BEFORE any tables are created
    conn.execute("PRAGMA page_size = 32768;")
    
    c = conn.cursor()
    
    # Table for top-level stories
    c.execute("""
        CREATE TABLE stories (
            id INTEGER PRIMARY KEY,
            base_id TEXT UNIQUE,
            url_backup TEXT,
            title TEXT,
            author_name TEXT,
            author_raw_name TEXT,
            date TEXT,
            url TEXT,
            image TEXT,
            synopsis TEXT,
            extra_url TEXT,
            notations TEXT,
            chapter_count INTEGER DEFAULT 0,
            last_modified TEXT,
            timestamp INTEGER DEFAULT 0
        )
    """)
    
    # Table for individual chapters - Use INTEGER PRIMARY KEY for fast FTS mapping
    c.execute("""
        CREATE TABLE chapters (
            id INTEGER PRIMARY KEY,
            map_id TEXT UNIQUE,
            base_id TEXT,
            chapter_title TEXT,
            author_name TEXT,
            author_raw_name TEXT,
            chapter_content TEXT,
            choices TEXT,
            date TEXT,
            timestamp INTEGER DEFAULT 0,
            FOREIGN KEY (base_id) REFERENCES stories(base_id)
        )
    """)
    
    # Full Text Search virtual table using EXTERNAL CONTENT
    # This prevents duplicating 5GB of text data, making the DB smaller and faster
    c.execute("""
        CREATE VIRTUAL TABLE chapters_fts USING fts5(
            chapter_title,
            chapter_content,
            author_name,
            content='chapters',
            content_rowid='id',
            tokenize='porter'
        )
    """)

    # Commit initial schema
    conn.commit()

    # Indexes for fast lookups
    print("Creating indexes...")
    c.execute("CREATE INDEX idx_chapters_base_id ON chapters(base_id);")
    c.execute("CREATE INDEX idx_chapters_author ON chapters(author_raw_name);")
    c.execute("CREATE INDEX idx_stories_author ON stories(author_raw_name);")
    
    conn.commit()
    return conn

def parse_tsv(tsv_path, conn):
    print("Beginning TSV ingestion... this may take a while.")
    c = conn.cursor()
    
    # For batch inserts
    batch_size = 100000
    stories_batch = {}
    chapters_batch = {}

    # Global tracker for story prioritization: base_id -> (is_intro, timestamp)
    story_best_scores = {}
    
    start_time = time.time()
    count = 0
    
    with open(tsv_path, 'r', encoding='utf-8-sig', errors='replace') as f:
        # Skip the header line if it exists
        first_line = True
        
        for line in f:
            if first_line:
                first_line = False
                if line.startswith("URL_BACKUP"):
                    continue
                    
            count += 1
            if count % 100000 == 0:
                print(f"Processed {count} lines in {time.time() - start_time:.2f} seconds...")
                
            parts = line.split('\t')
            # Pad parts to 15 columns in case some are missing at the end of the line
            while len(parts) < 15:
                parts.append("")
                
            url_backup = parts[0].strip()
            title = parts[1].strip()
            chapter_title = parts[2].strip()
            author_name = parts[3].strip()
            author_raw_name = parts[4].strip()
            chapter_content = parts[5].strip()
            choices = parts[6].strip()
            date = parts[7].strip()
            map_id = parts[8].strip()
            url = parts[9].strip()
            image = parts[10].strip()
            synopsis = parts[11].strip()
            extra_url = parts[13].strip()
            notations = parts[14].strip()
            
            map_id_raw = map_id
            if not map_id_raw:
                continue
                
            # Handle map_id format: STORY_ID-CHAPTER_ID-TIMESTAMP
            # Prioritize the version with the highest timestamp.
            map_bits = map_id_raw.split('-')
            timestamp = 0
            logical_map_id = map_id_raw
            _SQLITE_MAX_INT = 9223372036854775807  # 2^63 - 1
            if len(map_bits) >= 3 and map_bits[-1].isdigit():
                try:
                    raw_ts = int(map_bits[-1])
                    if raw_ts > _SQLITE_MAX_INT:
                        print(f"  [WARNING] Timestamp overflow on line {count}: map_id={map_id_raw!r}, raw_ts={raw_ts} — clamped to {_SQLITE_MAX_INT}", file=sys.stderr)
                    # Clamp to SQLite's signed 64-bit integer range to prevent OverflowError
                    timestamp = min(raw_ts, _SQLITE_MAX_INT)
                    logical_map_id = "-".join(map_bits[:-1])
                except ValueError:
                    pass

            base_id = map_bits[0]

            # Save story metadata
            is_intro = "-Intro" in logical_map_id
            # Score logic: Intro info is better than non-intro for metadata. Then newer timestamp is better.
            story_score = (1 if is_intro else 0, timestamp)

            if base_id not in story_best_scores or story_score >= story_best_scores[base_id]:
                story_best_scores[base_id] = story_score
                stories_batch[base_id] = (
                    base_id, url_backup, title, author_name, author_raw_name, date, 
                    url, image, synopsis, extra_url, notations, timestamp
                )

            # Save chapter data
            # Deduplicate within batch based on timestamp
            if logical_map_id not in chapters_batch or timestamp >= chapters_batch.get(logical_map_id, (None,)*9)[-1]:
                chapters_batch[logical_map_id] = (
                    logical_map_id, base_id, chapter_title, author_name, author_raw_name, 
                    chapter_content, choices, date, timestamp
                )

            if len(chapters_batch) >= batch_size:
                flush_batches(c, stories_batch, chapters_batch)
                conn.commit()
                stories_batch.clear()
                chapters_batch.clear()
                
    if chapters_batch:
        flush_batches(c, stories_batch, chapters_batch)
        conn.commit()
        
    print(f"Done! Processed {count} lines in {time.time() - start_time:.2f} seconds.")

def flush_batches(cursor, stories, chapters):
    if stories:
        cursor.executemany("""
            INSERT INTO stories (
                base_id, url_backup, title, author_name, author_raw_name, date, 
                url, image, synopsis, extra_url, notations, timestamp
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(base_id) DO UPDATE SET 
                url_backup=excluded.url_backup,
                title=excluded.title,
                author_name=excluded.author_name,
                author_raw_name=excluded.author_raw_name,
                date=excluded.date,
                url=excluded.url,
                image=excluded.image,
                synopsis=excluded.synopsis,
                extra_url=excluded.extra_url,
                notations=excluded.notations,
                timestamp=excluded.timestamp
            WHERE excluded.timestamp >= stories.timestamp
        """, list(stories.values()))
        
    if chapters:
        cursor.executemany("""
            INSERT INTO chapters (
                map_id, base_id, chapter_title, author_name, author_raw_name, chapter_content, choices, date, timestamp
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(map_id) DO UPDATE SET
                chapter_title=excluded.chapter_title,
                author_name=excluded.author_name,
                author_raw_name=excluded.author_raw_name,
                chapter_content=excluded.chapter_content,
                choices=excluded.choices,
                date=excluded.date,
                timestamp=excluded.timestamp
            WHERE excluded.timestamp >= chapters.timestamp
        """, list(chapters.values()))

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Ingest Writing.com TSV data into SQLite.")
    parser.add_argument("input_pos", nargs="?", help="Path to the source TSV file (positional).")
    parser.add_argument("-i", "--input", help="Path to the source TSV file.")
    parser.add_argument("-o", "--output", help="Path to the output SQLite database.")
    args = parser.parse_args()

    # Priority: --input flag > positional argument > default filename > interactive input
    tsv_path = args.input or args.input_pos

    if not tsv_path:
        # Check for the default filename next to this script
        default_tsv = os.path.join(os.path.dirname(os.path.abspath(__file__)), "story-database.tsv")
        if os.path.exists(default_tsv):
            tsv_path = default_tsv
            print(f"No input specified — using default: {tsv_path}")
        else:
            print("--- TSV to SQLite Converter ---")
            tsv_path = input("Please enter the path to the .tsv file: ").strip().strip('"')

    if not tsv_path or not os.path.exists(tsv_path):
        if tsv_path:
            print(f"Error: File not found at: {tsv_path}")
        else:
            print("Error: No input file specified.")
        sys.exit(1)

    # Derive output path if not provided
    if args.output:
        db_path = args.output
    else:
        # story.tsv -> story.sqlite
        base_name, _ = os.path.splitext(tsv_path)
        db_path = base_name + ".sqlite"

    print(f"Ingesting: {tsv_path}")
    print(f"Database:  {db_path}")

    total_start_time = time.time()
    conn = create_db(db_path)
    
    # Pragmas for ultra-fast bulk insert
    conn.execute("PRAGMA journal_mode = OFF;")
    conn.execute("PRAGMA synchronous = 0;")
    conn.execute("PRAGMA cache_size = 100000;")
    conn.execute("PRAGMA locking_mode = EXCLUSIVE;")
    conn.execute("PRAGMA temp_store = MEMORY;")
    conn.execute("PRAGMA mmap_size = 4294967296;") # 4GB mmap for speed
    
    parse_tsv(tsv_path, conn)
    
    print("Building FTS index (fast bulk index)...")
    conn.execute("""
        INSERT INTO chapters_fts(rowid, chapter_title, chapter_content, author_name)
        SELECT id, chapter_title, chapter_content, author_name FROM chapters
    """)

    print("Updating story chapter counts and last_modified dates (O(N) operation)...")
    conn.execute("""
        UPDATE stories 
        SET 
            chapter_count = c.count_val,
            last_modified = (
                SELECT date FROM chapters 
                WHERE base_id = stories.base_id 
                ORDER BY timestamp DESC, 
                         substr(date, 7, 4) || substr(date, 1, 2) || substr(date, 4, 2) DESC 
                LIMIT 1
            )
        FROM (
            SELECT base_id, COUNT(*) as count_val
            FROM chapters 
            GROUP BY base_id
        ) AS c
        WHERE stories.base_id = c.base_id
    """)
    
    conn.commit()
    print("Optimizing database (this may take a while)...")
    conn.execute("PRAGMA journal_mode = WAL;")
    conn.execute("PRAGMA synchronous = NORMAL;")
    conn.execute("INSERT INTO chapters_fts(chapters_fts) VALUES('optimize');")
    conn.commit()
    conn.close()

    total_elapsed = time.time() - total_start_time
    hours, rem = divmod(total_elapsed, 3600)
    minutes, seconds = divmod(rem, 60)
    print(f"\nAll done! Total time: {int(hours):02d}h {int(minutes):02d}m {seconds:05.2f}s")
    print("Database creation complete.")