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.")