import argparse import json import os import sys import sqlite3 from typing import Dict, Any def main() -> int: ap = argparse.ArgumentParser( description="Build a JSON index from story-database.sqlite." ) ap.add_argument("--db", default="story-database.sqlite", help="Input SQLite database path") ap.add_argument( "--output", default="index.json", help="Output JSON path (default: index.json)", ) args = ap.parse_args() if not os.path.exists(args.db): print(f"Database not found: {args.db}") return 1 conn = sqlite3.connect(args.db) conn.row_factory = sqlite3.Row cursor = conn.cursor() out: Dict[str, Any] = {} # Read from stories table. Note that we will compute the correct chapter count # by joining with chapters, handling the Intro emptiness logic if needed. # However, since the sqlite database likely already has chapter_count computed # accurately or we can just fetch it, let's look at what we need. # We will get all stories. # The previous logic counted chapters and excluded "-Intro" if chapter_content was empty. # Since we're using SQLite, we can just fetch the chapter_count from stories, but # to be perfectly safe and replicate the logic, let's query chapters as well to adjust if necessary, # or just trust the stories table if it's already accurate. # The prompt says: "make this to work on story-database.sqlite (it has the same logic story-database.tsv)" # We'll calculate the chapter counts directly from chapters table for accuracy, ignoring empty intros. # Wait, fetching all chapters content might be heavy. Let's just use a query. print(f"Reading from {args.db}...") # Query to get story data cursor.execute("SELECT base_id, title, author_name, author_raw_name, synopsis, date, last_modified FROM stories") stories = cursor.fetchall() # Query to get chapter counts per base_id # We count all chapters, but we need to exclude "-Intro" if content is empty or {"html": ""} cursor.execute(''' SELECT base_id, map_id, chapter_content FROM chapters ''') chapter_count = {} for row in cursor: base_id = row['base_id'] map_id = row['map_id'] content = (row['chapter_content'] or "").strip() is_empty_intro = False if "-Intro" in map_id: if not content or content in ('{"html": ""}', '{"html":""}'): is_empty_intro = True elif content.startswith("{") and content.endswith("}"): if '"html": ""' in content or '"html":""' in content: try: obj = json.loads(content) if isinstance(obj, dict) and obj.get("html", "").strip() == "": is_empty_intro = True except: pass if not is_empty_intro: chapter_count[base_id] = chapter_count.get(base_id, 0) + 1 for row in stories: base_id = row['base_id'] if not base_id or base_id.startswith('#====') or (row['title'] and row['title'].startswith('#====')): continue c = chapter_count.get(base_id, 0) out[base_id] = { "title": row["title"] or "", "authorcutename": row["author_name"] or "", "authorid": row["author_raw_name"] or "", "synopsis": row["synopsis"] or "", "date": row["date"] or "", "creationdate": row["date"] or "", "lastmodified": row["last_modified"] or "", "chapterCount": c, "isonline": "", } conn.close() out = {k: out[k] for k in sorted(out)} with open(args.output, "w", encoding="utf-8", newline="\n") as f: json.dump( out, f, ensure_ascii=False, indent=2, separators=(",", ": "), ) f.write("\n") print(f"Saved {len(out)} stories to {args.output}") return 0 if __name__ == "__main__": sys.exit(main())