tgdatasets commited on
Commit
379c0ff
·
verified ·
1 Parent(s): 8bbfc03

Upload 4 files

Browse files
convert_SQLITE_index_stories.bashpy ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import sys
5
+ import sqlite3
6
+ from typing import Dict, Any
7
+
8
+ def main() -> int:
9
+ ap = argparse.ArgumentParser(
10
+ description="Build a JSON index from story-database.sqlite."
11
+ )
12
+ ap.add_argument("--db", default="story-database.sqlite", help="Input SQLite database path")
13
+ ap.add_argument(
14
+ "--output",
15
+ default="index.json",
16
+ help="Output JSON path (default: index.json)",
17
+ )
18
+ args = ap.parse_args()
19
+
20
+ if not os.path.exists(args.db):
21
+ print(f"Database not found: {args.db}")
22
+ return 1
23
+
24
+ conn = sqlite3.connect(args.db)
25
+ conn.row_factory = sqlite3.Row
26
+ cursor = conn.cursor()
27
+
28
+ out: Dict[str, Any] = {}
29
+
30
+ # Read from stories table. Note that we will compute the correct chapter count
31
+ # by joining with chapters, handling the Intro emptiness logic if needed.
32
+ # However, since the sqlite database likely already has chapter_count computed
33
+ # accurately or we can just fetch it, let's look at what we need.
34
+
35
+ # We will get all stories.
36
+ # The previous logic counted chapters and excluded "-Intro" if chapter_content was empty.
37
+ # Since we're using SQLite, we can just fetch the chapter_count from stories, but
38
+ # to be perfectly safe and replicate the logic, let's query chapters as well to adjust if necessary,
39
+ # or just trust the stories table if it's already accurate.
40
+ # The prompt says: "make this to work on story-database.sqlite (it has the same logic story-database.tsv)"
41
+ # We'll calculate the chapter counts directly from chapters table for accuracy, ignoring empty intros.
42
+
43
+ # Wait, fetching all chapters content might be heavy. Let's just use a query.
44
+ print(f"Reading from {args.db}...")
45
+
46
+ # Query to get story data
47
+ cursor.execute("SELECT base_id, title, author_name, author_raw_name, synopsis, date, last_modified FROM stories")
48
+ stories = cursor.fetchall()
49
+
50
+ # Query to get chapter counts per base_id
51
+ # We count all chapters, but we need to exclude "-Intro" if content is empty or {"html": ""}
52
+ cursor.execute('''
53
+ SELECT base_id, map_id, chapter_content FROM chapters
54
+ ''')
55
+
56
+ chapter_count = {}
57
+ for row in cursor:
58
+ base_id = row['base_id']
59
+ map_id = row['map_id']
60
+ content = (row['chapter_content'] or "").strip()
61
+
62
+ is_empty_intro = False
63
+ if "-Intro" in map_id:
64
+ if not content or content in ('{"html": ""}', '{"html":""}'):
65
+ is_empty_intro = True
66
+ elif content.startswith("{") and content.endswith("}"):
67
+ if '"html": ""' in content or '"html":""' in content:
68
+ try:
69
+ obj = json.loads(content)
70
+ if isinstance(obj, dict) and obj.get("html", "").strip() == "":
71
+ is_empty_intro = True
72
+ except:
73
+ pass
74
+
75
+ if not is_empty_intro:
76
+ chapter_count[base_id] = chapter_count.get(base_id, 0) + 1
77
+
78
+ for row in stories:
79
+ base_id = row['base_id']
80
+ if not base_id or base_id.startswith('#====') or (row['title'] and row['title'].startswith('#====')):
81
+ continue
82
+
83
+ c = chapter_count.get(base_id, 0)
84
+
85
+ out[base_id] = {
86
+ "title": row["title"] or "",
87
+ "authorcutename": row["author_name"] or "",
88
+ "authorid": row["author_raw_name"] or "",
89
+ "synopsis": row["synopsis"] or "",
90
+ "date": row["date"] or "",
91
+ "creationdate": row["date"] or "",
92
+ "lastmodified": row["last_modified"] or "",
93
+ "chapterCount": c,
94
+ "isonline": "",
95
+ }
96
+
97
+ conn.close()
98
+
99
+ out = {k: out[k] for k in sorted(out)}
100
+
101
+ with open(args.output, "w", encoding="utf-8", newline="\n") as f:
102
+ json.dump(
103
+ out,
104
+ f,
105
+ ensure_ascii=False,
106
+ indent=2,
107
+ separators=(",", ": "),
108
+ )
109
+ f.write("\n")
110
+
111
+ print(f"Saved {len(out)} stories to {args.output}")
112
+
113
+ return 0
114
+
115
+ if __name__ == "__main__":
116
+ sys.exit(main())
convert_SQLITE_to_HTML.bashpy ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Export stories from SQLite to standalone HTML files.
3
+
4
+ Usage:
5
+ 1. Export a single story:
6
+ python export_story.py <STORY_ID>
7
+ Example: python convert_SQLITE_to_HTML.bashpy 1974707
8
+
9
+ 2. Export ALL stories in the database:
10
+ python convert_SQLITE_to_HTML.bashpy --all
11
+
12
+ 3. Export only stories modified in the current or previous month:
13
+ python convert_SQLITE_to_HTML.bashpy --recent
14
+
15
+ All exported files are saved in the 'storyhtml/' folder.
16
+
17
+ Changes applied to every exported file vs. live reader.html:
18
+ - The story JSON is embedded directly in a <script id="embedded-story-data"> tag
19
+ so the file works offline / without the local Flask server.
20
+ - Author links are rewritten from the in-app view
21
+ reader.html#author=<id> (with onclick=fetchAuthorStories)
22
+ to the original Writing.com profile URL:
23
+ https://www.writing.com/main/view_item/action/show_chapters/user_id/<id>
24
+ - The "Load Story" modal (#initial-load-container) is removed because the
25
+ story loads directly from the embedded JSON.
26
+ """
27
+
28
+ import sqlite3
29
+ import json
30
+ import os
31
+ import re
32
+ import argparse
33
+ import time
34
+ import zipfile
35
+ from datetime import datetime, timedelta
36
+
37
+ DB_PATH = "story-database.sqlite"
38
+ READER_HTML_PATH = "reader.html"
39
+ OUTPUT_FILE = "stories-database.zip"
40
+
41
+ # ── Tag inserted into reader.html to hold the embedded JSON.
42
+ # The export_story() regex searches for this exact id.
43
+ EMBEDDED_TAG_ID = "embedded-story-data"
44
+
45
+ # Placeholder tag written at the end of <body> in reader.html so the regex
46
+ # always finds it even if no story has been exported yet.
47
+ EMBEDDED_TAG_PLACEHOLDER = f'<script id="{EMBEDDED_TAG_ID}" type="application/json"></script>'
48
+
49
+
50
+ def get_db_connection():
51
+ conn = sqlite3.connect(DB_PATH)
52
+ conn.row_factory = sqlite3.Row
53
+ return conn
54
+
55
+
56
+ def parse_date(date_str):
57
+ """Parse MM-DD-YYYY → datetime, return None on failure."""
58
+ if not date_str:
59
+ return None
60
+ date_str = date_str.strip()
61
+ try:
62
+ return datetime.strptime(date_str, "%m-%d-%Y")
63
+ except Exception:
64
+ return None
65
+
66
+
67
+ def parse_date_to_timestamp(date_str):
68
+ dt = parse_date(date_str)
69
+ return int(dt.timestamp()) if dt else 0
70
+
71
+
72
+ def resolve_public_story_id(story_row):
73
+ """Prefer the canonical Writing.com item_id over internal/archive-only ids."""
74
+ for key in ("url", "url_backup", "extra_url"):
75
+ value = story_row[key] if key in story_row.keys() else ""
76
+ if not value:
77
+ continue
78
+ match = re.search(r'item_id/(\d+)', value)
79
+ if match:
80
+ return match.group(1)
81
+
82
+ base_id = str(story_row["base_id"])
83
+ leading_digits = re.match(r'^(\d+)', base_id)
84
+ return leading_digits.group(1) if leading_digits else base_id
85
+
86
+
87
+ def get_story_data(base_id, conn=None):
88
+ """Fetch story + chapters from SQLite and return the JSON-ready dict."""
89
+ close_conn = False
90
+ if conn is None:
91
+ conn = get_db_connection()
92
+ close_conn = True
93
+
94
+ story = conn.execute(
95
+ "SELECT * FROM stories WHERE base_id = ?", (base_id,)
96
+ ).fetchone()
97
+
98
+ if not story:
99
+ if close_conn:
100
+ conn.close()
101
+ print(f" [SKIP] Story {base_id} not found in database.")
102
+ return None
103
+
104
+ chapters_raw = conn.execute(
105
+ "SELECT * FROM chapters WHERE base_id = ?", (base_id,)
106
+ ).fetchall()
107
+ if close_conn:
108
+ conn.close()
109
+
110
+ public_story_id = resolve_public_story_id(story)
111
+
112
+ story_data = {
113
+ "info": {
114
+ "id": public_story_id,
115
+ "pretty_title": story["title"],
116
+ "description": story["synopsis"],
117
+ "author_name": (
118
+ story["author_name"]
119
+ if "author_name" in story.keys()
120
+ else story["authorcutename"]
121
+ ),
122
+ "author_id": (
123
+ story["author_raw_name"]
124
+ if "author_raw_name" in story.keys()
125
+ else story["authorid"]
126
+ ),
127
+ "created": parse_date_to_timestamp(story["date"]),
128
+ "source_url": story["url"] if "url" in story.keys() else "",
129
+ "image_url": story["image_url"] if "image_url" in story.keys() else "",
130
+ },
131
+ "chapters": {},
132
+ }
133
+
134
+ for c in chapters_raw:
135
+ full_map_id = c["map_id"]
136
+ parts = full_map_id.split("-", 1)
137
+ suffix = parts[1] if len(parts) > 1 else full_map_id
138
+
139
+ choices_list = []
140
+ if c["choices"]:
141
+ for choice_str in c["choices"].split("||||"):
142
+ cleaned = re.sub(r"^\d+\.\s*", "", choice_str.strip())
143
+ if cleaned:
144
+ choices_list.append(cleaned)
145
+
146
+ html_content = c["chapter_content"]
147
+ if html_content and html_content.strip().startswith("{"):
148
+ try:
149
+ # Try to parse as JSON to extract actual content if it's wrapped or encoded
150
+ curr = html_content
151
+ # Attempt up to 2 levels of decoding for double-encoded strings
152
+ for _ in range(2):
153
+ if not isinstance(curr, str) or not curr.strip().startswith("{"):
154
+ break
155
+ parsed = json.loads(curr)
156
+ if isinstance(parsed, dict):
157
+ # Writing.com API sometimes returns content in "html" or "content" keys
158
+ extracted = parsed.get("html") or parsed.get("content") or parsed.get("chapter_content")
159
+ if extracted is not None:
160
+ curr = extracted
161
+ else:
162
+ break # No known content key
163
+ elif isinstance(parsed, str):
164
+ curr = parsed
165
+ else:
166
+ break
167
+ html_content = curr
168
+ except Exception:
169
+ pass
170
+
171
+ if isinstance(html_content, str):
172
+ html_content = re.sub(r'(?i)<br\s*/?>\s*[\n\r]+', '<br>', html_content)
173
+ html_content = re.sub(r'(?i)[\n\r]+\s*<br\s*/?>', '<br>', html_content)
174
+
175
+ story_data["chapters"][suffix] = {
176
+ "id": c["map_id"],
177
+ "title": c["chapter_title"],
178
+ "content": html_content,
179
+ "created": parse_date_to_timestamp(c["date"]),
180
+ "choices": choices_list,
181
+ "author_name": (
182
+ c["author_name"]
183
+ if "author_name" in c.keys()
184
+ else story["authorcutename"]
185
+ ),
186
+ "author_id": (
187
+ c["author_raw_name"]
188
+ if "author_raw_name" in c.keys()
189
+ else story["authorid"]
190
+ ),
191
+ }
192
+
193
+ return story_data
194
+
195
+
196
+ # ────────────────────────────────────────────────────────────────────────────
197
+ # HTML post-processing helpers
198
+ # ────────────────────────────────────────────────────────────────────────────
199
+
200
+ def rewrite_author_links(html):
201
+ """
202
+ Replace every in-app author link:
203
+ <a href="reader.html#author=<id>" onclick="fetchAuthorStories(...)" ...>NAME</a>
204
+ with a plain Writing.com profile link:
205
+ <a href="https://www.writing.com/main/view_item/action/show_chapters/user_id/<id>"
206
+ title="View author profile on Writing.com">NAME</a>
207
+
208
+ Also handles the "author:<id>" href variant and JS template literals.
209
+ """
210
+ # Pattern 1: href="(reader.html)#author=ID" with optional onclick
211
+ html = re.sub(
212
+ r'<a\s+href="(?:reader\.html)?#author=([^"]+)"(?:\s+onclick="fetchAuthorStories\([^)]*\);\s*return false;")?\s+title="([^"]*)">',
213
+ lambda m: (
214
+ f'<a href="https://www.writing.com/main/view_item/action/show_chapters/user_id/{m.group(1)}"'
215
+ f' title="{m.group(2) if m.group(2) else "View author profile on Writing.com"}" target="_blank">'
216
+ ),
217
+ html,
218
+ )
219
+
220
+ # Pattern 2: href="author:<id>" (used in story info panel)
221
+ html = re.sub(
222
+ r'href="author:([^"]+)"',
223
+ lambda m: (
224
+ f'href="https://www.writing.com/main/view_item/action/show_chapters/user_id/{m.group(1)}"'
225
+ f' target="_blank"'
226
+ ),
227
+ html,
228
+ )
229
+
230
+ # Pattern 3: JS template literals like href="#author=${...}"
231
+ html = re.sub(
232
+ r'href="#author=\${([^}]+)}"',
233
+ r'href="https://www.writing.com/main/view_item/action/show_chapters/user_id/${\1}" target="_blank"',
234
+ html,
235
+ )
236
+
237
+ # Update title in JS strings for consistency
238
+ html = html.replace(
239
+ 'title="Click to view all stories by this author"',
240
+ 'title="View author profile on Writing.com"'
241
+ )
242
+
243
+ return html
244
+
245
+
246
+ def remove_initial_load_container(html):
247
+ """
248
+ Remove the entire #initial-load-container <div> block from the HTML.
249
+ The exported file loads the story directly from embedded JSON, so the
250
+ modal is never needed and just adds visual noise on first paint.
251
+ """
252
+ html = re.sub(
253
+ r'\s*<div id="initial-load-container">.*?</div>\s*(?=\n?\s*<script)',
254
+ "\n",
255
+ html,
256
+ flags=re.DOTALL,
257
+ )
258
+ return html
259
+
260
+
261
+ def remove_search_button(html):
262
+ """
263
+ Remove the search button from the header.
264
+ Target: .story-header-sticky > .search-container > a.search-btn
265
+ """
266
+ # Matches the search button by its href ("search.html") or class ("search-btn")
267
+ # to ensure it is removed from the standalone HTML export.
268
+ pattern = r'<a\s+[^>]*?(?:href="search\.html"|class="search-btn")[^>]*?>.*?</a>'
269
+ return re.sub(pattern, '', html, flags=re.DOTALL)
270
+
271
+
272
+ def rewrite_index_links(html):
273
+ """
274
+ Replace the Library index link:
275
+ <a href="index.html" class="index-btn" title="Back to Library Index">Library</a>
276
+ with the online archive URL:
277
+ https://writingarchive.neocities.org/index
278
+ """
279
+ pattern = r'<a href="index\.html" class="index-btn" title="Back to Library Index">Library</a>'
280
+ replacement = r'<a href="https://writingarchive.neocities.org/index" class="index-btn" title="Back to Library Index">Library</a>'
281
+ return re.sub(pattern, replacement, html)
282
+
283
+
284
+ def inject_embedded_json(html, json_str):
285
+ """
286
+ Find the <script id="embedded-story-data"> placeholder and fill it with
287
+ the story JSON. If the placeholder is absent (older reader.html without
288
+ it), append it just before </body>.
289
+ """
290
+ pattern = (
291
+ r'(<script\s+id="embedded-story-data"[^>]*>)(.*?)(</script>)'
292
+ )
293
+
294
+ escaped_json = json_str.replace("</script>", "<\\/script>")
295
+
296
+ if re.search(pattern, html, flags=re.DOTALL):
297
+ def _replace(m):
298
+ return f"{m.group(1)}\n{escaped_json}\n{m.group(3)}"
299
+ return re.sub(pattern, _replace, html, flags=re.DOTALL)
300
+ else:
301
+ # Fallback: inject before </body>
302
+ tag = f'<script id="embedded-story-data" type="application/json">\n{escaped_json}\n</script>\n'
303
+ return html.replace("</body>", tag + "</body>", 1)
304
+
305
+
306
+ # ────────────────────────────────────────────────────────────────────────────
307
+
308
+ def export_story(base_id, reader_html_content, conn=None, zf=None):
309
+ """Build and save a standalone HTML file for one story."""
310
+ story_data = get_story_data(base_id, conn)
311
+ if not story_data:
312
+ return False
313
+
314
+ json_str = json.dumps(story_data, ensure_ascii=False, separators=(",", ":"))
315
+
316
+ html = reader_html_content
317
+
318
+ # 1. Embed the JSON
319
+ html = inject_embedded_json(html, json_str)
320
+
321
+ # 2. Rewrite author links → Writing.com profile URLs
322
+ html = rewrite_author_links(html)
323
+
324
+ # 3. Remove the "Load Story" modal
325
+ html = remove_initial_load_container(html)
326
+
327
+ # 4. Remove the search button
328
+ html = remove_search_button(html)
329
+
330
+ # 5. Rewrite Library index link
331
+ html = rewrite_index_links(html)
332
+
333
+ if zf is not None:
334
+ zf.writestr(f"{base_id}.html", html)
335
+ else:
336
+ output_path = os.path.join("stories-database(temp)", f"{base_id}.html")
337
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
338
+ with open(output_path, "w", encoding="utf-8") as f:
339
+ f.write(html)
340
+ return True
341
+
342
+
343
+ def main():
344
+ start_time = time.time()
345
+ parser = argparse.ArgumentParser(
346
+ description="Export stories from SQLite to standalone HTML files.",
347
+ formatter_class=argparse.RawDescriptionHelpFormatter,
348
+ epilog=__doc__,
349
+ )
350
+ parser.add_argument("story_id", nargs="?", help="Specific story ID to export.")
351
+ parser.add_argument("--all", action="store_true", help="Export all stories.")
352
+ parser.add_argument(
353
+ "--recent",
354
+ action="store_true",
355
+ help="Export only stories modified in the current or previous calendar month.",
356
+ )
357
+ args = parser.parse_args()
358
+
359
+ if not os.path.exists(READER_HTML_PATH):
360
+ print(f"Error: {READER_HTML_PATH} not found. Run this script from the same folder as reader.html.")
361
+ return
362
+
363
+ with open(READER_HTML_PATH, "r", encoding="utf-8") as f:
364
+ reader_html_content = f.read()
365
+
366
+ # Warn if the embedded-story-data placeholder is missing
367
+ if EMBEDDED_TAG_ID not in reader_html_content:
368
+ print(
369
+ f"[WARNING] reader.html does not contain an element with id='{EMBEDDED_TAG_ID}'.\n"
370
+ " The JSON will be injected before </body> as a fallback.\n"
371
+ f" Consider adding: {EMBEDDED_TAG_PLACEHOLDER}\n"
372
+ " just before </body> in reader.html for cleaner exports."
373
+ )
374
+
375
+ conn = get_db_connection()
376
+ stories_to_export = []
377
+
378
+ # Default to --all when no arguments are provided (e.g. when the script is clicked/run directly)
379
+ if not (args.story_id or args.recent):
380
+ args.all = True
381
+
382
+ if args.all:
383
+ print("No arguments provided or --all specified. Fetching all stories from database...")
384
+ rows = conn.execute("SELECT base_id FROM stories ORDER BY base_id").fetchall()
385
+ stories_to_export = [r["base_id"] for r in rows]
386
+
387
+ elif args.recent:
388
+ # Current month + previous month
389
+ now = datetime.now()
390
+ # First day of the previous month
391
+ if now.month == 1:
392
+ cutoff = datetime(now.year - 1, 12, 1)
393
+ else:
394
+ cutoff = datetime(now.year, now.month - 1, 1)
395
+
396
+ print(
397
+ f"Fetching stories modified since {cutoff.strftime('%Y-%m-%d')} "
398
+ f"(current month + previous month)..."
399
+ )
400
+ rows = conn.execute("SELECT base_id, last_modified FROM stories").fetchall()
401
+ for r in rows:
402
+ lm = parse_date(r["last_modified"])
403
+ if lm and lm >= cutoff:
404
+ stories_to_export.append(r["base_id"])
405
+
406
+ elif args.story_id:
407
+ stories_to_export = [args.story_id]
408
+
409
+ total = len(stories_to_export)
410
+ print(f"Found {total} stor{'y' if total == 1 else 'ies'} to export -> {OUTPUT_FILE}")
411
+
412
+ success_count = 0
413
+ fail_count = 0
414
+
415
+ # We append if we're not doing a full export and the file exists
416
+ mode = "w" if args.all or not os.path.exists(OUTPUT_FILE) else "a"
417
+
418
+ with zipfile.ZipFile(OUTPUT_FILE, mode, compression=zipfile.ZIP_DEFLATED) as zf:
419
+ for i, base_id in enumerate(stories_to_export, 1):
420
+ if i % 50 == 0 or i == 1 or i == total:
421
+ print(f" [{i}/{total}] {base_id}")
422
+ if export_story(base_id, reader_html_content, conn, zf):
423
+ success_count += 1
424
+ else:
425
+ fail_count += 1
426
+
427
+ conn.close()
428
+ print(
429
+ f"\nDone! Exported {success_count}/{total} stories to '{OUTPUT_FILE}'."
430
+ + (f" ({fail_count} failed/skipped)" if fail_count else "")
431
+ )
432
+
433
+ elapsed = time.time() - start_time
434
+ duration = str(timedelta(seconds=int(elapsed)))
435
+ print(f"\nTotal time: {duration}")
436
+
437
+ if __name__ == "__main__":
438
+ main()
convert_TSV_to_SQLITE.bashpy ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ import json
3
+ import time
4
+ import sys
5
+ import os
6
+ import argparse
7
+
8
+ def create_db(db_path):
9
+ if os.path.exists(db_path):
10
+ print(f"Removing existing {db_path} to ensure fresh schema...")
11
+ os.remove(db_path)
12
+
13
+ print("Creating database and tables...")
14
+ conn = sqlite3.connect(db_path)
15
+
16
+ # Crucial for large databases: increase page size BEFORE any tables are created
17
+ conn.execute("PRAGMA page_size = 32768;")
18
+
19
+ c = conn.cursor()
20
+
21
+ # Table for top-level stories
22
+ c.execute("""
23
+ CREATE TABLE stories (
24
+ id INTEGER PRIMARY KEY,
25
+ base_id TEXT UNIQUE,
26
+ url_backup TEXT,
27
+ title TEXT,
28
+ author_name TEXT,
29
+ author_raw_name TEXT,
30
+ date TEXT,
31
+ url TEXT,
32
+ image TEXT,
33
+ synopsis TEXT,
34
+ extra_url TEXT,
35
+ notations TEXT,
36
+ chapter_count INTEGER DEFAULT 0,
37
+ last_modified TEXT,
38
+ timestamp INTEGER DEFAULT 0
39
+ )
40
+ """)
41
+
42
+ # Table for individual chapters - Use INTEGER PRIMARY KEY for fast FTS mapping
43
+ c.execute("""
44
+ CREATE TABLE chapters (
45
+ id INTEGER PRIMARY KEY,
46
+ map_id TEXT UNIQUE,
47
+ base_id TEXT,
48
+ chapter_title TEXT,
49
+ author_name TEXT,
50
+ author_raw_name TEXT,
51
+ chapter_content TEXT,
52
+ choices TEXT,
53
+ date TEXT,
54
+ timestamp INTEGER DEFAULT 0,
55
+ FOREIGN KEY (base_id) REFERENCES stories(base_id)
56
+ )
57
+ """)
58
+
59
+ # Full Text Search virtual table using EXTERNAL CONTENT
60
+ # This prevents duplicating 5GB of text data, making the DB smaller and faster
61
+ c.execute("""
62
+ CREATE VIRTUAL TABLE chapters_fts USING fts5(
63
+ chapter_title,
64
+ chapter_content,
65
+ author_name,
66
+ content='chapters',
67
+ content_rowid='id',
68
+ tokenize='porter'
69
+ )
70
+ """)
71
+
72
+ # Commit initial schema
73
+ conn.commit()
74
+
75
+ # Indexes for fast lookups
76
+ print("Creating indexes...")
77
+ c.execute("CREATE INDEX idx_chapters_base_id ON chapters(base_id);")
78
+ c.execute("CREATE INDEX idx_chapters_author ON chapters(author_raw_name);")
79
+ c.execute("CREATE INDEX idx_stories_author ON stories(author_raw_name);")
80
+
81
+ conn.commit()
82
+ return conn
83
+
84
+ def parse_tsv(tsv_path, conn):
85
+ print("Beginning TSV ingestion... this may take a while.")
86
+ c = conn.cursor()
87
+
88
+ # For batch inserts
89
+ batch_size = 100000
90
+ stories_batch = {}
91
+ chapters_batch = {}
92
+
93
+ # Global tracker for story prioritization: base_id -> (is_intro, timestamp)
94
+ story_best_scores = {}
95
+
96
+ start_time = time.time()
97
+ count = 0
98
+
99
+ with open(tsv_path, 'r', encoding='utf-8-sig', errors='replace') as f:
100
+ # Skip the header line if it exists
101
+ first_line = True
102
+
103
+ for line in f:
104
+ if first_line:
105
+ first_line = False
106
+ if line.startswith("URL_BACKUP"):
107
+ continue
108
+
109
+ count += 1
110
+ if count % 100000 == 0:
111
+ print(f"Processed {count} lines in {time.time() - start_time:.2f} seconds...")
112
+
113
+ parts = line.split('\t')
114
+ # Pad parts to 15 columns in case some are missing at the end of the line
115
+ while len(parts) < 15:
116
+ parts.append("")
117
+
118
+ url_backup = parts[0].strip()
119
+ title = parts[1].strip()
120
+ chapter_title = parts[2].strip()
121
+ author_name = parts[3].strip()
122
+ author_raw_name = parts[4].strip()
123
+ chapter_content = parts[5].strip()
124
+ choices = parts[6].strip()
125
+ date = parts[7].strip()
126
+ map_id = parts[8].strip()
127
+ url = parts[9].strip()
128
+ image = parts[10].strip()
129
+ synopsis = parts[11].strip()
130
+ extra_url = parts[13].strip()
131
+ notations = parts[14].strip()
132
+
133
+ map_id_raw = map_id
134
+ if not map_id_raw:
135
+ continue
136
+
137
+ # Handle map_id format: STORY_ID-CHAPTER_ID-TIMESTAMP
138
+ # Prioritize the version with the highest timestamp.
139
+ map_bits = map_id_raw.split('-')
140
+ timestamp = 0
141
+ logical_map_id = map_id_raw
142
+ _SQLITE_MAX_INT = 9223372036854775807 # 2^63 - 1
143
+ if len(map_bits) >= 3 and map_bits[-1].isdigit():
144
+ try:
145
+ raw_ts = int(map_bits[-1])
146
+ if raw_ts > _SQLITE_MAX_INT:
147
+ 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)
148
+ # Clamp to SQLite's signed 64-bit integer range to prevent OverflowError
149
+ timestamp = min(raw_ts, _SQLITE_MAX_INT)
150
+ logical_map_id = "-".join(map_bits[:-1])
151
+ except ValueError:
152
+ pass
153
+
154
+ base_id = map_bits[0]
155
+
156
+ # Save story metadata
157
+ is_intro = "-Intro" in logical_map_id
158
+ # Score logic: Intro info is better than non-intro for metadata. Then newer timestamp is better.
159
+ story_score = (1 if is_intro else 0, timestamp)
160
+
161
+ if base_id not in story_best_scores or story_score >= story_best_scores[base_id]:
162
+ story_best_scores[base_id] = story_score
163
+ stories_batch[base_id] = (
164
+ base_id, url_backup, title, author_name, author_raw_name, date,
165
+ url, image, synopsis, extra_url, notations, timestamp
166
+ )
167
+
168
+ # Save chapter data
169
+ # Deduplicate within batch based on timestamp
170
+ if logical_map_id not in chapters_batch or timestamp >= chapters_batch.get(logical_map_id, (None,)*9)[-1]:
171
+ chapters_batch[logical_map_id] = (
172
+ logical_map_id, base_id, chapter_title, author_name, author_raw_name,
173
+ chapter_content, choices, date, timestamp
174
+ )
175
+
176
+ if len(chapters_batch) >= batch_size:
177
+ flush_batches(c, stories_batch, chapters_batch)
178
+ conn.commit()
179
+ stories_batch.clear()
180
+ chapters_batch.clear()
181
+
182
+ if chapters_batch:
183
+ flush_batches(c, stories_batch, chapters_batch)
184
+ conn.commit()
185
+
186
+ print(f"Done! Processed {count} lines in {time.time() - start_time:.2f} seconds.")
187
+
188
+ def flush_batches(cursor, stories, chapters):
189
+ if stories:
190
+ cursor.executemany("""
191
+ INSERT INTO stories (
192
+ base_id, url_backup, title, author_name, author_raw_name, date,
193
+ url, image, synopsis, extra_url, notations, timestamp
194
+ )
195
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
196
+ ON CONFLICT(base_id) DO UPDATE SET
197
+ url_backup=excluded.url_backup,
198
+ title=excluded.title,
199
+ author_name=excluded.author_name,
200
+ author_raw_name=excluded.author_raw_name,
201
+ date=excluded.date,
202
+ url=excluded.url,
203
+ image=excluded.image,
204
+ synopsis=excluded.synopsis,
205
+ extra_url=excluded.extra_url,
206
+ notations=excluded.notations,
207
+ timestamp=excluded.timestamp
208
+ WHERE excluded.timestamp >= stories.timestamp
209
+ """, list(stories.values()))
210
+
211
+ if chapters:
212
+ cursor.executemany("""
213
+ INSERT INTO chapters (
214
+ map_id, base_id, chapter_title, author_name, author_raw_name, chapter_content, choices, date, timestamp
215
+ )
216
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
217
+ ON CONFLICT(map_id) DO UPDATE SET
218
+ chapter_title=excluded.chapter_title,
219
+ author_name=excluded.author_name,
220
+ author_raw_name=excluded.author_raw_name,
221
+ chapter_content=excluded.chapter_content,
222
+ choices=excluded.choices,
223
+ date=excluded.date,
224
+ timestamp=excluded.timestamp
225
+ WHERE excluded.timestamp >= chapters.timestamp
226
+ """, list(chapters.values()))
227
+
228
+ if __name__ == "__main__":
229
+ parser = argparse.ArgumentParser(description="Ingest Writing.com TSV data into SQLite.")
230
+ parser.add_argument("input_pos", nargs="?", help="Path to the source TSV file (positional).")
231
+ parser.add_argument("-i", "--input", help="Path to the source TSV file.")
232
+ parser.add_argument("-o", "--output", help="Path to the output SQLite database.")
233
+ args = parser.parse_args()
234
+
235
+ # Priority: --input flag > positional argument > default filename > interactive input
236
+ tsv_path = args.input or args.input_pos
237
+
238
+ if not tsv_path:
239
+ # Check for the default filename next to this script
240
+ default_tsv = os.path.join(os.path.dirname(os.path.abspath(__file__)), "story-database.tsv")
241
+ if os.path.exists(default_tsv):
242
+ tsv_path = default_tsv
243
+ print(f"No input specified — using default: {tsv_path}")
244
+ else:
245
+ print("--- TSV to SQLite Converter ---")
246
+ tsv_path = input("Please enter the path to the .tsv file: ").strip().strip('"')
247
+
248
+ if not tsv_path or not os.path.exists(tsv_path):
249
+ if tsv_path:
250
+ print(f"Error: File not found at: {tsv_path}")
251
+ else:
252
+ print("Error: No input file specified.")
253
+ sys.exit(1)
254
+
255
+ # Derive output path if not provided
256
+ if args.output:
257
+ db_path = args.output
258
+ else:
259
+ # story.tsv -> story.sqlite
260
+ base_name, _ = os.path.splitext(tsv_path)
261
+ db_path = base_name + ".sqlite"
262
+
263
+ print(f"Ingesting: {tsv_path}")
264
+ print(f"Database: {db_path}")
265
+
266
+ total_start_time = time.time()
267
+ conn = create_db(db_path)
268
+
269
+ # Pragmas for ultra-fast bulk insert
270
+ conn.execute("PRAGMA journal_mode = OFF;")
271
+ conn.execute("PRAGMA synchronous = 0;")
272
+ conn.execute("PRAGMA cache_size = 100000;")
273
+ conn.execute("PRAGMA locking_mode = EXCLUSIVE;")
274
+ conn.execute("PRAGMA temp_store = MEMORY;")
275
+ conn.execute("PRAGMA mmap_size = 4294967296;") # 4GB mmap for speed
276
+
277
+ parse_tsv(tsv_path, conn)
278
+
279
+ print("Building FTS index (fast bulk index)...")
280
+ conn.execute("""
281
+ INSERT INTO chapters_fts(rowid, chapter_title, chapter_content, author_name)
282
+ SELECT id, chapter_title, chapter_content, author_name FROM chapters
283
+ """)
284
+
285
+ print("Updating story chapter counts and last_modified dates (O(N) operation)...")
286
+ conn.execute("""
287
+ UPDATE stories
288
+ SET
289
+ chapter_count = c.count_val,
290
+ last_modified = (
291
+ SELECT date FROM chapters
292
+ WHERE base_id = stories.base_id
293
+ ORDER BY timestamp DESC,
294
+ substr(date, 7, 4) || substr(date, 1, 2) || substr(date, 4, 2) DESC
295
+ LIMIT 1
296
+ )
297
+ FROM (
298
+ SELECT base_id, COUNT(*) as count_val
299
+ FROM chapters
300
+ GROUP BY base_id
301
+ ) AS c
302
+ WHERE stories.base_id = c.base_id
303
+ """)
304
+
305
+ conn.commit()
306
+ print("Optimizing database (this may take a while)...")
307
+ conn.execute("PRAGMA journal_mode = WAL;")
308
+ conn.execute("PRAGMA synchronous = NORMAL;")
309
+ conn.execute("INSERT INTO chapters_fts(chapters_fts) VALUES('optimize');")
310
+ conn.commit()
311
+ conn.close()
312
+
313
+ total_elapsed = time.time() - total_start_time
314
+ hours, rem = divmod(total_elapsed, 3600)
315
+ minutes, seconds = divmod(rem, 60)
316
+ print(f"\nAll done! Total time: {int(hours):02d}h {int(minutes):02d}m {seconds:05.2f}s")
317
+ print("Database creation complete.")
writing.com_server.py ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, send_file
2
+ import sqlite3
3
+ import json
4
+ import html
5
+ from datetime import datetime
6
+ import sys
7
+ import re
8
+ import time
9
+ from flask_cors import CORS
10
+
11
+ app = Flask(__name__, static_folder='.', static_url_path='')
12
+ CORS(app)
13
+
14
+ @app.route('/')
15
+ def index():
16
+ return send_file('index.html')
17
+
18
+ @app.route('/reader')
19
+ def reader():
20
+ return send_file('reader.html')
21
+
22
+ DB_PATH = "story-database.sqlite"
23
+
24
+ FTS_SPECIAL_PATTERN = re.compile(r'[()*:+|]|\b(AND|OR|NOT|NEAR)\b', re.IGNORECASE)
25
+ # Note: '-' is NOT special here. Hyphenated queries like "The-Golden-Mind-Control"
26
+ # are routed through the safe word-splitting path in _build_fts_unit, which treats
27
+ # '-' and '_' as word separators so they behave like "The Golden Mind Control".
28
+
29
+ def get_db_connection():
30
+ conn = sqlite3.connect(DB_PATH)
31
+ conn.row_factory = sqlite3.Row
32
+ # Performance pragmas for the server
33
+ conn.execute("PRAGMA mmap_size = 4294967296;") # 4GB mmap
34
+ conn.execute("PRAGMA cache_size = 20000;") # Increase cache
35
+
36
+ # Add REGEXP support
37
+ def regexp(expr, item):
38
+ if item is None:
39
+ return False
40
+ reg = re.compile(expr, re.IGNORECASE)
41
+ return reg.search(item) is not None
42
+
43
+ conn.create_function("REGEXP", 2, regexp)
44
+ return conn
45
+
46
+ # Internal Settings
47
+ USE_SYNOPSIS_FALLBACK = False # If True, use story["synopsis"] if Intro chapter is missing
48
+
49
+ def parse_date_to_timestamp(date_str):
50
+ if not date_str:
51
+ return 0
52
+ date_str = date_str.strip()
53
+ try:
54
+ dt = datetime.strptime(date_str, "%m-%d-%Y")
55
+ return int(dt.timestamp())
56
+ except:
57
+ return 0
58
+
59
+ def normalize_date_for_sql(date_str, is_before=False):
60
+ if not date_str: return None
61
+ date_str = date_str.strip('"() ')
62
+ if re.match(r'^\d{4}$', date_str):
63
+ return f"{date_str}1231" if is_before else f"{date_str}0101"
64
+ m = re.match(r'^(\d{1,2})-(\d{1,2})-(\d{4})$', date_str)
65
+ if m:
66
+ mm = m.group(1).zfill(2)
67
+ dd = m.group(2).zfill(2)
68
+ yyyy = m.group(3)
69
+ return f"{yyyy}{mm}{dd}"
70
+ m = re.match(r'^(\d{4})-(\d{1,2})-(\d{1,2})$', date_str)
71
+ if m:
72
+ yyyy = m.group(1)
73
+ mm = m.group(2).zfill(2)
74
+ dd = m.group(3).zfill(2)
75
+ return f"{yyyy}{mm}{dd}"
76
+ return None
77
+
78
+ def resolve_public_story_id(story_row):
79
+ for key in ("url", "url_backup", "extra_url"):
80
+ value = story_row[key] if key in story_row.keys() else ""
81
+ if not value: continue
82
+ match = re.search(r'item_id/(\d+)', value)
83
+ if match: return match.group(1)
84
+ base_id = str(story_row["base_id"])
85
+ leading_digits = re.match(r'^(\d+)', base_id)
86
+ return leading_digits.group(1) if leading_digits else base_id
87
+
88
+ def parse_query_to_groups(raw_query):
89
+ if not raw_query: return []
90
+ tokens = re.findall(r'"[^"]+"|[^\s|]+|\|', raw_query)
91
+ expanded_tokens = []
92
+ for t in tokens:
93
+ if t == '|':
94
+ expanded_tokens.append(t)
95
+ continue
96
+ is_quoted = t.startswith('"') and t.endswith('"')
97
+ inner = t[1:-1] if is_quoted else t
98
+ if '|' in inner:
99
+ branches = [b.strip() for b in inner.split('|') if b.strip()]
100
+ if is_quoted: expanded_tokens.append([f'"{b}"' for b in branches])
101
+ else: expanded_tokens.append(branches)
102
+ else:
103
+ expanded_tokens.append(t)
104
+ final_groups = []
105
+ i = 0
106
+ while i < len(expanded_tokens):
107
+ t = expanded_tokens[i]
108
+ if t == '|':
109
+ i += 1
110
+ continue
111
+ current_group = t if isinstance(t, list) else [t]
112
+ while i + 1 < len(expanded_tokens) and expanded_tokens[i+1] == '|':
113
+ i += 2
114
+ if i < len(expanded_tokens):
115
+ next_t = expanded_tokens[i]
116
+ if isinstance(next_t, list): current_group.extend(next_t)
117
+ elif next_t != '|': current_group.append(next_t)
118
+ else: break
119
+ final_groups.append(current_group)
120
+ i += 1
121
+ return final_groups
122
+
123
+ def build_fts_query(raw_query):
124
+ raw_query = (raw_query or '').strip()
125
+ if not raw_query: return ''
126
+ if re.search(r'\bAND\b', raw_query, re.IGNORECASE):
127
+ tokens = re.findall(r'"[^"]+"|\S+', raw_query)
128
+ parts = []
129
+ current_part = []
130
+ for token in tokens:
131
+ if token.upper() == 'AND':
132
+ if current_part:
133
+ parts.append(" ".join(current_part))
134
+ current_part = []
135
+ else: current_part.append(token)
136
+ if current_part: parts.append(" ".join(current_part))
137
+ if len(parts) > 1:
138
+ branches = []
139
+ for p in parts:
140
+ unit = _build_fts_unit(p)
141
+ if unit: branches.append(f"({unit})")
142
+ if branches: return " AND ".join(branches)
143
+ return _build_fts_unit(raw_query)
144
+
145
+ def _build_fts_unit(raw_query):
146
+ raw_query = raw_query.strip()
147
+ if not raw_query: return ''
148
+ if FTS_SPECIAL_PATTERN.search(raw_query) and '|' not in raw_query: return raw_query
149
+ groups = parse_query_to_groups(raw_query)
150
+ if not groups: return ''
151
+ safe_terms = []
152
+ for group in groups:
153
+ unit_branches = []
154
+ for term in group:
155
+ if term.startswith('"') and term.endswith('"') and len(term) >= 2:
156
+ phrase = term[1:-1].strip()
157
+ if phrase: unit_branches.append(f'"{phrase}"')
158
+ continue
159
+ cleaned = re.sub(r'[^0-9A-Za-z]+', ' ', term).strip() # '-' and '_' become word separators
160
+ if not cleaned: continue
161
+ parts = [f'{piece}*' for piece in cleaned.split()]
162
+ if parts: unit_branches.append(" ".join(parts))
163
+ if unit_branches:
164
+ if len(unit_branches) > 1: safe_terms.append("(" + " OR ".join(unit_branches) + ")")
165
+ else: safe_terms.append(unit_branches[0])
166
+ return ' AND '.join(safe_terms)
167
+
168
+ def build_like_clause_groups(raw_query):
169
+ raw_query = (raw_query or '').strip()
170
+ if not raw_query: return []
171
+ if re.search(r'\bAND\b', raw_query, re.IGNORECASE):
172
+ tokens = re.findall(r'"[^"]+"|\S+', raw_query)
173
+ parts = []
174
+ current_part = []
175
+ for token in tokens:
176
+ if token.upper() == 'AND':
177
+ if current_part:
178
+ parts.append(" ".join(current_part))
179
+ current_part = []
180
+ else: current_part.append(token)
181
+ if current_part: parts.append(" ".join(current_part))
182
+ if len(parts) > 1:
183
+ res = []
184
+ for p in parts: res.extend(parse_query_to_groups(p))
185
+ return res
186
+ return parse_query_to_groups(raw_query)
187
+
188
+ def build_like_clause_main(raw_query):
189
+ groups = build_like_clause_groups(raw_query)
190
+ res = []
191
+ for g in groups:
192
+ for t in g: res.append(t.strip('"'))
193
+ for t in g: res.append(t) # Keep original term, including quotes if present
194
+ return list(set(res))
195
+
196
+ def build_term_pattern(term, prefix_match=False):
197
+ """Compile a regex for a single query term.
198
+
199
+ Runs of spaces, hyphens ('-') and underscores ('_') are treated as
200
+ equivalent separators, so queries typed as "The-Golden-Mind-Control"
201
+ or "The_Golden_Mind_Control" match text containing "The Golden Mind
202
+ Control" (and any mix of spaces/hyphens/underscores in between).
203
+ """
204
+ words = [w for w in re.split(r'[\s_\-]+', term) if w]
205
+ if not words: return None
206
+ gap = r'[\s_\-]+'
207
+ body = gap.join(re.escape(w) for w in words)
208
+ pattern = (r'\b' if words[0][0].isalnum() else '') + body
209
+ if prefix_match:
210
+ pattern += r'\w*' # Prefix match for unquoted terms (aligns with FTS 'word*')
211
+ elif words[-1][-1].isalnum():
212
+ pattern += r'\b'
213
+ return re.compile(pattern, re.IGNORECASE)
214
+
215
+ def compile_logic(groups):
216
+ """Turn parsed query groups into regexes: one list of patterns per OR group."""
217
+ res = []
218
+ for group in groups:
219
+ pats = []
220
+ for p in group:
221
+ term = p.strip().lower().strip('"')
222
+ if not term: continue
223
+ quoted = p.startswith('"') and p.endswith('"')
224
+ pat = build_term_pattern(term, prefix_match=not quoted)
225
+ if pat: pats.append(pat)
226
+ res.append(pats)
227
+ return res
228
+
229
+ def clean_chapter_content(content):
230
+ if not content: return ''
231
+ text = str(content).strip()
232
+ def extract_raw(raw):
233
+ if not raw or not isinstance(raw, str): return raw
234
+ raw = raw.strip()
235
+ if not (raw.startswith('{') or '"html"' in raw):
236
+ return raw.replace('\\n', '\n').replace('\\r', '\r')
237
+ try:
238
+ parsed = json.loads(raw)
239
+ if isinstance(parsed, dict) and 'html' in parsed: return extract_raw(parsed['html'])
240
+ except: pass
241
+ m = re.search(r'"html"\s*:\s*"(.*?)"(?=\s*[,}])', raw, re.DOTALL)
242
+ if m:
243
+ val = m.group(1).replace('\\"', '"').replace('\\n', '\n').replace('\\r', '\r').replace('\\t', '\t')
244
+ return extract_raw(val)
245
+ return raw
246
+ cleaned = extract_raw(text)
247
+ if '<' in cleaned and '>' in cleaned:
248
+ cleaned = re.sub(r'(?i)(<br\s*/?>)[\n\r]+', r'\1', cleaned)
249
+ cleaned = re.sub(r'(?i)[\n\r]+(<br\s*/?>)', r'\1', cleaned)
250
+ block_tags = 'div|p|h[1-6]|ul|ol|li|section|article|blockquote'
251
+ cleaned = re.sub(rf'(?i)(</?(?:{block_tags})[^>]*>)[\n\r]+', r'\1', cleaned)
252
+ cleaned = re.sub(rf'(?i)[\n\r]+(</?(?:{block_tags})[^>]*>)', r'\1', cleaned)
253
+ return cleaned
254
+
255
+ def extract_search_operator(query_text, operator_name):
256
+ pattern = re.compile(rf'{re.escape(operator_name)}(?:\[([^\]]+)\])?:\s*("[^"]+"|\([^)]+\)|\S+)', re.IGNORECASE)
257
+ match = pattern.search(query_text or '')
258
+ if not match: return None, None, query_text
259
+ arg = match.group(1)
260
+ value = match.group(2).strip()
261
+ cleaned = pattern.sub(' ', query_text, count=1)
262
+ cleaned = re.sub(r'\s+', ' ', cleaned).strip()
263
+ return value or None, arg, cleaned
264
+
265
+ def normalize_snippet_text(content):
266
+ if not content: return ''
267
+ text = clean_chapter_content(content)
268
+ text = html.unescape(text)
269
+ text = text.replace('\\n', ' ').replace('\\r', ' ').replace('\n', ' ').replace('\r', ' ')
270
+ text = re.sub(r'(?i)<br\s*/?>', ' ', text)
271
+ text = re.sub(r'(?i)</p\s*>', ' ', text)
272
+ text = re.sub(r'(?i)<p[^>]*>', ' ', text)
273
+ text = re.sub(r'(?i)</?(i|em|b|strong|u|span|div)[^>]*>', '', text)
274
+ text = re.sub(r'<[^>]+>', ' ', text)
275
+ text = re.sub(r'\s+', ' ', text).strip()
276
+ return text
277
+
278
+ def highlight_query_terms(snippet, query_parts):
279
+ if not snippet: return ''
280
+ highlighted = snippet
281
+ unique_parts = []
282
+ seen = set()
283
+ for part in sorted(query_parts or [], key=len, reverse=True):
284
+ normalized = part.strip().lower()
285
+ if not normalized or normalized in seen: continue
286
+ seen.add(normalized)
287
+ unique_parts.append(part.strip())
288
+ for part in unique_parts:
289
+ pattern = build_term_pattern(part, prefix_match=False)
290
+ if pattern:
291
+ highlighted = pattern.sub(lambda m: f'<mark>{m.group(0)}</mark>', highlighted)
292
+ return highlighted
293
+
294
+ def build_text_match_sql(alias, groups, include_story_fields=False):
295
+ if not groups: return "1=1", []
296
+ if groups and not isinstance(groups[0], list): groups = [[t] for t in groups]
297
+ group_clauses = []
298
+ params = []
299
+ for group in groups[:8]:
300
+ branch_clauses = []
301
+ for part in group[:8]:
302
+ like_value = f"%{part.strip('\"')}%"
303
+ current = [f"{alias}.chapter_title LIKE ?", f"{alias}.chapter_content LIKE ?"]
304
+ current_params = [like_value, like_value]
305
+ if include_story_fields:
306
+ current.extend(["s.title LIKE ?", "s.synopsis LIKE ?"])
307
+ current_params.extend([like_value, like_value])
308
+ branch_clauses.append("(" + " OR ".join(current) + ")")
309
+ params.extend(current_params)
310
+ group_clauses.append("(" + " OR ".join(branch_clauses) + ")")
311
+ return " AND ".join(group_clauses), params
312
+
313
+ def make_like_snippet(content, query_parts, radius=200):
314
+ if not content: return 'No text preview available.'
315
+ text = normalize_snippet_text(content)
316
+ unique_parts = sorted(list(set(p.lower().strip('"') for p in query_parts if p.strip())), key=len, reverse=True)
317
+ if not unique_parts: return (text[:radius].strip() + "...") if len(text) > radius else text
318
+ all_matches = []
319
+ for part in unique_parts:
320
+ pattern = build_term_pattern(part, prefix_match=False)
321
+ if not pattern: continue
322
+ for m in pattern.finditer(text):
323
+ all_matches.append({'start': m.start(), 'end': m.end(), 'term': part})
324
+ if len(all_matches) > 100: break
325
+ if not all_matches: return (text[:radius].strip() + "...") if len(text) > radius else text
326
+ all_matches.sort(key=lambda x: x['start'])
327
+ clusters = []
328
+ if all_matches:
329
+ curr = {'start': all_matches[0]['start'], 'end': all_matches[0]['end'], 'terms': {all_matches[0]['term']}}
330
+ for m in all_matches[1:]:
331
+ if m['start'] <= curr['end'] + 60:
332
+ curr['end'] = max(curr['end'], m['end'])
333
+ curr['terms'].add(m['term'])
334
+ else:
335
+ clusters.append(curr)
336
+ curr = {'start': m['start'], 'end': m['end'], 'terms': {m['term']}}
337
+ clusters.append(curr)
338
+ for c in clusters:
339
+ c['score'] = len(c['terms'])
340
+ c['bonus'] = 1.0 / (1.0 + c['start'] / 1000.0)
341
+ selected_clusters = []
342
+ actual_terms = set(m['term'] for m in all_matches)
343
+ remaining_terms = set(unique_parts).intersection(actual_terms)
344
+ pool = list(clusters)
345
+ while remaining_terms and pool:
346
+ best_c = None
347
+ max_new_terms = -1
348
+ for c in pool:
349
+ new_terms = len(c['terms'].intersection(remaining_terms))
350
+ if new_terms > max_new_terms:
351
+ max_new_terms = new_terms
352
+ best_c = c
353
+ elif new_terms == max_new_terms and best_c and (c['score'] + c['bonus'] > best_c['score'] + best_c['bonus']):
354
+ best_c = c
355
+ if best_c and max_new_terms > 0:
356
+ selected_clusters.append(best_c)
357
+ remaining_terms -= best_c['terms']
358
+ pool.remove(best_c)
359
+ else: break
360
+ if len(selected_clusters) < 4:
361
+ clusters.sort(key=lambda x: x['score'] + x['bonus'], reverse=True)
362
+ for c in clusters:
363
+ if len(selected_clusters) >= 4: break
364
+ if any(abs(c['start'] - s['start']) < 80 for s in selected_clusters): continue
365
+ selected_clusters.append(c)
366
+ selected_clusters.sort(key=lambda x: x['start'])
367
+ pieces = []
368
+ context_radius = max(20, radius // 8)
369
+ for i, c in enumerate(selected_clusters):
370
+ w_start = max(0, c['start'] - context_radius)
371
+ w_end = min(len(text), c['end'] + context_radius)
372
+ if w_start > 0:
373
+ space_idx = text.find(' ', w_start, c['start'])
374
+ if space_idx != -1: w_start = space_idx + 1
375
+ else:
376
+ back_space = text.rfind(' ', max(0, w_start - 20), w_start)
377
+ if back_space != -1: w_start = back_space + 1
378
+ if w_end < len(text):
379
+ space_idx = text.rfind(' ', c['end'], w_end)
380
+ if space_idx != -1: w_end = space_idx
381
+ else:
382
+ fwd_space = text.find(' ', w_end, min(len(text), w_end + 20))
383
+ if fwd_space != -1: w_end = fwd_space
384
+ if i > 0 and w_start < selected_clusters[i-1]['end_display']: w_start = selected_clusters[i-1]['end_display']
385
+ if w_start >= w_end: continue
386
+ piece = text[w_start:w_end]
387
+ prefix = "... " if w_start > 0 else ""
388
+ suffix = " ..." if w_end < len(text) else ""
389
+ pieces.append(f"{prefix}{piece.strip()}{suffix}")
390
+ c['end_display'] = w_end
391
+ snippet = "".join(pieces)
392
+ snippet = re.sub(r'\.\.\.\s*\.\.\.', '...', snippet)
393
+ snippet = re.sub(r'\.\.\.\.\.\.', '...', snippet)
394
+ snippet = re.sub(r'\s+', ' ', snippet)
395
+ return highlight_query_terms(snippet.strip(), query_parts)
396
+
397
+ @app.route('/api/story/<base_id>', methods=['GET'])
398
+ def get_story(base_id):
399
+ if base_id.endswith('.html'): base_id = base_id[:-5]
400
+ conn = get_db_connection()
401
+ story = conn.execute("SELECT * FROM stories WHERE base_id = ?", (base_id,)).fetchone()
402
+ actual_chapter_id = None
403
+ if not story:
404
+ cid_match = conn.execute("SELECT base_id, map_id FROM chapters WHERE map_id LIKE ?", (f"%-{base_id}",)).fetchone()
405
+ if cid_match:
406
+ actual_story_id = cid_match["base_id"]
407
+ actual_chapter_id = cid_match["map_id"].split("-", 1)[1] if "-" in cid_match["map_id"] else cid_match["map_id"]
408
+ story = conn.execute("SELECT * FROM stories WHERE base_id = ?", (actual_story_id,)).fetchone()
409
+ if not story:
410
+ cid_search = f"%{base_id}%"
411
+ story_match = conn.execute("SELECT * FROM stories WHERE url LIKE ? OR image LIKE ?", (cid_search, cid_search)).fetchone()
412
+ if story_match: story = story_match
413
+ if not story:
414
+ conn.close()
415
+ return jsonify({'error': 'Story not found'}), 404
416
+ base_id = story["base_id"]
417
+ chapters_raw = conn.execute("SELECT * FROM chapters WHERE base_id = ?", (base_id,)).fetchall()
418
+ conn.close()
419
+ public_story_id = resolve_public_story_id(story)
420
+ story_data = {
421
+ "info": {
422
+ "id": public_story_id, "pretty_title": story["title"], "description": story["synopsis"] if USE_SYNOPSIS_FALLBACK else "",
423
+ "author_name": story["author_name"] if "author_name" in story.keys() else story["authorcutename"],
424
+ "author_id": story["author_raw_name"] if "author_raw_name" in story.keys() else story["authorid"],
425
+ "created": parse_date_to_timestamp(story["date"]), "source_url": story["url"] if "url" in story.keys() else "",
426
+ "resolved_chapter_id": actual_chapter_id
427
+ }, "chapters": {}
428
+ }
429
+ for c in chapters_raw:
430
+ full_map_id = c["map_id"]
431
+ parts = full_map_id.split("-", 1)
432
+ suffix = parts[1] if len(parts) > 1 else full_map_id
433
+ choices_list = []
434
+ if c["choices"]:
435
+ for choice_str in c["choices"].split("||||"):
436
+ cleaned = re.sub(r'^\d+\.\s*', '', choice_str.strip())
437
+ if cleaned: choices_list.append(cleaned)
438
+ html_content = clean_chapter_content(c["chapter_content"])
439
+ if suffix == 'Intro': story_data["info"]["description"] = html_content
440
+ story_data["chapters"][suffix] = {
441
+ "id": c["map_id"], "title": c["chapter_title"], "content": html_content,
442
+ "created": parse_date_to_timestamp(c["date"]), "choices": choices_list,
443
+ "author_name": c["author_name"] if "author_name" in c.keys() else story["authorcutename"],
444
+ "author_id": c["author_raw_name"] if "author_raw_name" in c.keys() else story["authorid"]
445
+ }
446
+ return jsonify(story_data)
447
+
448
+ @app.route('/api/author/<authorid>', methods=['GET'])
449
+ def get_by_author(authorid):
450
+ conn = get_db_connection()
451
+ try: stories = conn.execute("SELECT * FROM stories WHERE author_raw_name = ?", (authorid,)).fetchall()
452
+ except sqlite3.OperationalError: stories = conn.execute("SELECT * FROM stories WHERE authorid = ?", (authorid,)).fetchall()
453
+ conn.close()
454
+ return jsonify([dict(s) for s in stories])
455
+
456
+ @app.route('/api/author_chapters/<authorid>', methods=['GET'])
457
+ def get_author_chapters(authorid):
458
+ page, limit = int(request.args.get('page', 1)), int(request.args.get('limit', 500))
459
+ query, offset = request.args.get('q', '').strip(), (page - 1) * limit
460
+ sort = request.args.get('sort', 'date-desc')
461
+ date_sort_expr = "substr(c.date, 7, 4) || substr(c.date, 1, 2) || substr(c.date, 4, 2)"
462
+ order_map = {'date-asc': f"{date_sort_expr} ASC", 'title-asc': "c.chapter_title ASC", 'title-desc': "c.chapter_title DESC"}
463
+ order_by = order_map.get(sort, f"{date_sort_expr} DESC")
464
+ conn = get_db_connection()
465
+ try:
466
+ if query:
467
+ count_res = conn.execute("SELECT COUNT(*) FROM chapters_fts f JOIN chapters c ON f.rowid = c.id WHERE c.author_raw_name = ? AND chapters_fts MATCH ?", (authorid, query)).fetchone()
468
+ total_count = count_res[0]
469
+ results = conn.execute(f"SELECT c.map_id, c.base_id, c.chapter_title, c.chapter_content, c.date as created, s.title as story_title, c.author_name as author_name FROM chapters_fts f JOIN chapters c ON f.rowid = c.id JOIN stories s ON c.base_id = s.base_id WHERE c.author_raw_name = ? AND chapters_fts MATCH ? ORDER BY (c.chapter_content IS NULL OR c.chapter_content = '' OR c.chapter_content = '{{}}') ASC, {order_by} LIMIT ? OFFSET ?", (authorid, query, limit, offset)).fetchall()
470
+ else:
471
+ count_res = conn.execute("SELECT COUNT(*) FROM chapters WHERE author_raw_name = ?", (authorid,)).fetchone()
472
+ total_count = count_res[0]
473
+ results = conn.execute(f"SELECT c.map_id, c.base_id, c.chapter_title, c.chapter_content, c.date as created, s.title as story_title, c.author_name as author_name FROM chapters c JOIN stories s ON c.base_id = s.base_id WHERE c.author_raw_name = ? ORDER BY (c.chapter_content IS NULL OR c.chapter_content = '' OR c.chapter_content = '{{}}') ASC, {order_by} LIMIT ? OFFSET ?", (authorid, limit, offset)).fetchall()
474
+ except:
475
+ count_res = conn.execute("SELECT COUNT(*) FROM stories WHERE authorid = ?", (authorid,)).fetchone()
476
+ total_count = count_res[0]
477
+ results = conn.execute("SELECT c.map_id, c.base_id, c.chapter_title, c.chapter_content, c.date as created, s.title as story_title, s.authorcutename as author_name FROM chapters c JOIN stories s ON c.base_id = s.base_id WHERE s.authorid = ? ORDER BY c.date DESC LIMIT ? OFFSET ?", (authorid, limit, offset)).fetchall()
478
+ conn.close()
479
+ return jsonify({'chapters': [{**dict(r), 'chapter_content': clean_chapter_content(r['chapter_content'])} for r in results], 'total': total_count, 'page': page, 'limit': limit, 'query': query})
480
+
481
+ CATEGORIES = {
482
+ "Fanfic Stories": {"title_only": "Isekai|Konosuba|Kanto's Ghost|Scooby-Doo|Genshin Impact|Assassin's Creed|The Highschool|Persona|Yugi Moto|Yu-Yi-Yh|My hero academia|X-Men|VTubers|Disney|X Men|Lion King|Ace Attorney|Fanfic Stories|Tails|My little pony|TV Series Change/Transform|Anime", "general_search": "Tomb Raider|Code Geass|Dinotopia|Dragon Quest|Big Bang Theory|dragonball Z|Ace Attorney|Super Smash Bros|Yaoi Cartoon|Ben 10|Alex Russo|Isekai|KirbyKnights|NRDD|Zootopia|Simpson's|Sakura Wars|Ranma|Ben & Gwen|Yu Gi Oh|Simpsons|Ranma 1/2|Sailor Moon|Naruto|Power Rangers|Heroes|Sonic|Rugrats|RWBY|My Little Poney|dragon ball|digimon|hentai|Harry Potter|Scooby doo|Wonder Woman|Mass Effect|Family Guy|Wizards of Waverly Place|Pokegirls|Pokemorph|pokémon|pokemon|poke-dex|pokéflute|pokemons|pokémons|pikachu|pokechange|mario|wario|Zelda|Princess Zelda|Maburaho|Yu-gi-oh|yugioh|Yu-Gi-Oh|DC cinematic universe|Marvel|Marvel's|superhero|super heroine|Star Fox|Batman|Spider-Man|X-Men Evolution|Final Fantasy|Star Trek|Star Wars|icarly|Sherlock Holmes"},
483
+ "Role Swap": {"title_only": "", "general_search": "trading places|gender swap|role swap|life swap|switch roles|switched roles|swaps roles|swapped roles|swapped places|trade lives|switch lives|trade palces|trading places|swapping places|swapping roles|switching places|role reversal|swap roles"},
484
+ "Body Parts Swap": {"title_only": "", "general_search": "head swap|head swapping"},
485
+ "Body Swap": {"title_only": "", "general_search": "swapping bodies|transplant|bodyswap|body swap|body switch|switch bodies|switched bodies|swaps bodies|swap bodies|swapped bodies"},
486
+ "Giant/Expanasion/Growth Fetish": {"title_only": "Colossal|Growing Boy|titans|Muscle|Big Little Girls|Giantess|BIG GIRLS|Fatties|Growth|Expansion|Growth|Grew|Giant|Male Giant|Weight|Fat|Expansion|Size|Expansions|Big Girls|GTS|Big Boys|giant animals|get fat|muscle growth|expansion stories|fat girls", "general_search": "muscle growth|expansion stories|Macrophiles|Giantess Island|giant-ess|giant guys|giantess|amazonian|amazonians|Amazon Invasion|Female Growth |giants|giant's house|female expansion|female expansions|male expansions|women gain weight|fat disney|gts|weight gaining|women expand|wwe|weight gain|gts|gt/wg|weight gaining|weighty women|fatties|growing girls|size story|big fat|feet growth|size ray|giant kids|giant men"},
487
+ "Shrink Fetish": {"title_only": "Short Life|Tiny|Shrink|Shrunk", "general_search": "Small Town Swaps|shrinkgrowth|shrinking|shrunken|shruken|shrink ray|tiny life"},
488
+ "Feet Fetish": {"title_only": "Foot|Feet", "general_search": "teen feet|feet growth|foot fetish|footslave|teen feet|girl feet|female feet"},
489
+ "Vore": {"title_only": "", "general_search": "vore|vorarephilia|cannibal|cockvore|cartoon vore"},
490
+ "Tights/Pantyhose Fetish": {"title_only": "", "general_search": "tights|pantyhose|nylon|stockings|hosery|nylons"},
491
+ "Adult Baby": {"title_only": "", "general_search": "ABDL|ab-dl|adult baby|adult babies|diapers|diaper|diaperpalooza"},
492
+ "Ticklish": {"title_only": "", "general_search": "Tickling Women|ticklish|tickle|tickles|tickle feetish"},
493
+ "Fart": {"title_only": "fart|smelly", "general_search": ""},
494
+ "Furry": {"title_only": "", "general_search": "furry|furries|Zootopia|muscle growth|expansion stories"},
495
+ "Gay": {"title_only": "Gay|LGBTQ+", "general_search": ""}
496
+ }
497
+
498
+ @app.route('/api/stories', methods=['GET'])
499
+ def get_stories():
500
+ page, limit = int(request.args.get('page', 1)), int(request.args.get('limit', 100))
501
+ offset, q = (page - 1) * limit, request.args.get('q', '').strip()
502
+ sort = request.args.get('sort', 'created_desc')
503
+ include_cats = [c for c in request.args.get('categories', '').split(',') if c]
504
+ exclude_cats = [c for c in request.args.get('exclude_categories', '').split(',') if c]
505
+ conn = get_db_connection()
506
+ where_clauses, params = [], []
507
+ if q:
508
+ where_clauses.append("(base_id LIKE ? OR title LIKE ? OR synopsis LIKE ? OR author_name LIKE ? OR author_raw_name LIKE ?)")
509
+ lq = f"%{q}%"
510
+ params.extend([lq, lq, lq, lq, lq])
511
+ for cat_name in include_cats:
512
+ if cat_name in CATEGORIES:
513
+ cat = CATEGORIES[cat_name]
514
+ clauses = []
515
+ if cat["title_only"]: clauses.append("title REGEXP ?"); params.append(cat["title_only"])
516
+ if cat["general_search"]: clauses.append("(title REGEXP ? OR synopsis REGEXP ?)"); params.extend([cat["general_search"], cat["general_search"]])
517
+ if clauses: where_clauses.append("(" + " OR ".join(clauses) + ")")
518
+ for cat_name in exclude_cats:
519
+ if cat_name in CATEGORIES:
520
+ cat = CATEGORIES[cat_name]
521
+ if cat["title_only"]: where_clauses.append("NOT (title REGEXP ?)"); params.append(cat["title_only"])
522
+ if cat["general_search"]: where_clauses.append("NOT (title REGEXP ? OR synopsis REGEXP ?)"); params.extend([cat["general_search"], cat["general_search"]])
523
+ where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""
524
+ count_res = conn.execute(f"SELECT COUNT(*) FROM stories {where_sql}", params).fetchone()
525
+ total_count = count_res[0]
526
+ sort_map = {'title_asc': 'title ASC', 'title_desc': 'title DESC', 'chapters_desc': 'chapter_count DESC', 'chapters_asc': 'chapter_count ASC', 'created_desc': 'date DESC', 'created_asc': 'date ASC', 'modified_desc': 'last_modified DESC', 'modified_asc': 'last_modified ASC'}
527
+ order_by = sort_map.get(sort, 'date DESC')
528
+ results = conn.execute(f"SELECT base_id as id, title, author_name as authorcutename, author_raw_name as authorid, synopsis, date, chapter_count as chapterCount, last_modified as lastmodified FROM stories {where_sql} ORDER BY {order_by} LIMIT ? OFFSET ?", params + [limit, offset]).fetchall()
529
+ conn.close()
530
+ return jsonify({'stories': [dict(r) for r in results], 'total': total_count, 'page': page, 'limit': limit})
531
+
532
+ @app.route('/api/author_contributions/<authorid>', methods=['GET'])
533
+ def get_author_contributions(authorid):
534
+ page, limit = int(request.args.get('page', 1)), int(request.args.get('limit', 100))
535
+ sort = request.args.get('sort', 'date-desc')
536
+ offset = (page - 1) * limit
537
+ conn = get_db_connection()
538
+
539
+ # Sort mapping
540
+ date_sort_expr = "substr(s.date, 7, 4) || substr(s.date, 1, 2) || substr(s.date, 4, 2)"
541
+ sort_map = {
542
+ 'date-desc': f"{date_sort_expr} DESC",
543
+ 'date-asc': f"{date_sort_expr} ASC",
544
+ 'contrib-desc': "contribution_count DESC, " + date_sort_expr + " DESC",
545
+ 'contrib-asc': "contribution_count ASC, " + date_sort_expr + " DESC"
546
+ }
547
+ order_by = sort_map.get(sort, f"{date_sort_expr} DESC")
548
+
549
+ # Find unique base_ids where author wrote a chapter, and join with stories metadata
550
+ query = f"""
551
+ SELECT s.base_id as id, s.title, s.author_name as authorcutename, s.author_raw_name as authorid,
552
+ s.synopsis, s.date, s.chapter_count as chapterCount, s.last_modified as lastmodified,
553
+ COUNT(c.map_id) as contribution_count
554
+ FROM stories s
555
+ JOIN chapters c ON s.base_id = c.base_id
556
+ WHERE c.author_raw_name = ?
557
+ GROUP BY s.base_id
558
+ ORDER BY {order_by}
559
+ LIMIT ? OFFSET ?
560
+ """
561
+ results = conn.execute(query, (authorid, limit, offset)).fetchall()
562
+
563
+ count_query = "SELECT COUNT(DISTINCT base_id) FROM chapters WHERE author_raw_name = ?"
564
+ total_count = conn.execute(count_query, (authorid,)).fetchone()[0]
565
+
566
+ conn.close()
567
+ return jsonify({'stories': [dict(r) for r in results], 'total': total_count, 'page': page, 'limit': limit})
568
+
569
+ @app.route('/api/related_authors/<authorid>', methods=['GET'])
570
+ def get_related_authors(authorid):
571
+ filter_type, limit = request.args.get('filter', 'general'), int(request.args.get('limit', 50))
572
+ conn = get_db_connection()
573
+ where_clause = "WHERE c1.author_raw_name = ? AND c2.author_raw_name != ? AND c2.author_raw_name IS NOT NULL AND c2.author_raw_name != '' AND c2.author_name IS NOT NULL AND c2.author_name != '' AND LOWER(c2.author_name) != 'unknown' AND LOWER(c2.author_raw_name) != 'unknown' AND c2.map_id LIKE c1.map_id || '%'"
574
+ if filter_type == 'recent':
575
+ one_year_ago = (datetime.now().year - 1) * 10000 + datetime.now().month * 100 + datetime.now().day
576
+ where_clause += f" AND (substr(c1.base_id, 1, 0) || (SELECT (substr(s.date, 7, 4) || substr(s.date, 1, 2) || substr(s.date, 4, 2)) FROM stories s WHERE s.base_id = c1.base_id)) >= '{one_year_ago}'"
577
+ results = conn.execute(f"SELECT c2.author_name as name, c2.author_raw_name as id, COUNT(*) as follow_ups FROM chapters c1 JOIN chapters c2 ON c1.base_id = c2.base_id {where_clause} GROUP BY c2.author_raw_name ORDER BY follow_ups DESC LIMIT ?", (authorid, authorid, limit)).fetchall()
578
+ conn.close()
579
+ return jsonify([dict(r) for r in results])
580
+
581
+ @app.route('/api/search', methods=['GET'])
582
+ def search():
583
+ start_time = time.time()
584
+ q = request.args.get('q', '')
585
+ if not q: return jsonify([])
586
+ page, limit = max(1, int(request.args.get('page', 1))), max(1, min(1000, int(request.args.get('limit', 100))))
587
+ offset = (page - 1) * limit
588
+ include_cats = [c for c in request.args.get('categories', '').split(',') if c]
589
+ exclude_cats = [c for c in request.args.get('exclude_categories', '').split(',') if c]
590
+ snippet_limit = max(50, min(5000, int(request.args.get('snippet_limit', 300))))
591
+ related_snippet_limit = max(50, min(5000, int(request.args.get('related_snippet_limit', 300))))
592
+ clean_query = q
593
+ author_filter, _, clean_query = extract_search_operator(clean_query, 'author')
594
+ if author_filter: author_filter = author_filter.strip('"()')
595
+ story_filter, _, clean_query = extract_search_operator(clean_query, 'storyID')
596
+ if story_filter: story_filter = story_filter.strip('"()')
597
+ related_filter, related_depth_str, clean_query = extract_search_operator(clean_query, 'relatedsearch')
598
+ related_depth_limit = int(related_depth_str) if related_depth_str and related_depth_str.isdigit() else None
599
+ before_filter, _, clean_query = extract_search_operator(clean_query, 'before')
600
+ after_filter, _, clean_query = extract_search_operator(clean_query, 'after')
601
+ date_sort_expr = "substr(c.date, 7, 4) || substr(c.date, 1, 2) || substr(c.date, 4, 2)"
602
+ before_val, after_val = normalize_date_for_sql(before_filter, True), normalize_date_for_sql(after_filter, False)
603
+ fts_query = build_fts_query(clean_query)
604
+ query_parts, query_groups = build_like_clause_main(clean_query), parse_query_to_groups(clean_query)
605
+ related_parts, related_groups = build_like_clause_main(related_filter or ''), parse_query_to_groups(related_filter or '')
606
+
607
+ # Category optimization
608
+ comb_inc_t = "|".join([CATEGORIES[c]["title_only"] for c in include_cats if c in CATEGORIES and CATEGORIES[c]["title_only"]])
609
+ comb_inc_g = "|".join([CATEGORIES[c]["general_search"] for c in include_cats if c in CATEGORIES and CATEGORIES[c]["general_search"]])
610
+ comb_exc_t = "|".join([CATEGORIES[c]["title_only"] for c in exclude_cats if c in CATEGORIES and CATEGORIES[c]["title_only"]])
611
+ comb_exc_g = "|".join([CATEGORIES[c]["general_search"] for c in exclude_cats if c in CATEGORIES and CATEGORIES[c]["general_search"]])
612
+
613
+ conn = get_db_connection()
614
+ all_matching_results, current_search_offset, max_scan_total, rows_scanned, total = [], 0, 100000, 0, 0
615
+ results_to_skip, target_limit = offset, limit
616
+
617
+ if fts_query:
618
+ try:
619
+ where_clauses, params = ["chapters_fts MATCH ?"], [fts_query]
620
+ if comb_inc_t: where_clauses.append("(s.title REGEXP ? OR c.chapter_title REGEXP ?)"); params.extend([comb_inc_t, comb_inc_t])
621
+ if comb_inc_g: where_clauses.append("(s.title REGEXP ? OR c.chapter_title REGEXP ? OR s.synopsis REGEXP ?)"); params.extend([comb_inc_g, comb_inc_g, comb_inc_g])
622
+ if comb_exc_t: where_clauses.append("NOT (s.title REGEXP ? OR c.chapter_title REGEXP ?)"); params.extend([comb_exc_t, comb_exc_t])
623
+ if comb_exc_g: where_clauses.append("NOT (s.title REGEXP ? OR c.chapter_title REGEXP ? OR s.synopsis REGEXP ?)"); params.extend([comb_exc_g, comb_exc_g, comb_exc_g])
624
+ if author_filter: where_clauses.append("(c.author_raw_name LIKE ? OR c.author_name LIKE ?)"); params.extend([f"%{author_filter}%", f"%{author_filter}%"])
625
+ if story_filter: where_clauses.append("c.base_id = ?"); params.append(story_filter)
626
+ if before_val: where_clauses.append(f"{date_sort_expr} <= ?"); params.append(before_val)
627
+ if after_val: where_clauses.append(f"{date_sort_expr} >= ?"); params.append(after_val)
628
+ if related_groups:
629
+ related_fts = build_fts_query(related_filter)
630
+ where_clauses.append("c.base_id IN (SELECT DISTINCT c_rel.base_id FROM chapters_fts f_rel JOIN chapters c_rel ON f_rel.rowid = c_rel.id WHERE f_rel.chapters_fts MATCH ?)")
631
+ params.append(related_fts)
632
+ where_sql = " AND ".join(where_clauses)
633
+
634
+ count_start = time.time()
635
+ total = conn.execute(f"SELECT COUNT(*) FROM chapters_fts JOIN chapters c ON chapters_fts.rowid = c.id JOIN stories s ON c.base_id = s.base_id WHERE {where_sql}", params).fetchone()[0]
636
+ print(f"[*] Incoming Search: '{q}'")
637
+ print(f"[*] FTS matches to verify: {total} (Count took {time.time()-count_start:.2f}s)")
638
+
639
+ compiled_patterns = compile_logic(query_groups)
640
+ rel_compiled_patterns = compile_logic(related_groups)
641
+ related_cache = {}
642
+
643
+ # Pre-calculate related FTS query once to avoid overhead in the loop
644
+ rel_fts_val = build_fts_query(related_filter) if related_filter else None
645
+
646
+ while len(all_matching_results) < target_limit and rows_scanned < max_scan_total:
647
+ # Increase batch size if hit rate is low to reduce SQL roundtrips
648
+ fetch_batch_size = 500 if rows_scanned > 1000 and not all_matching_results else max(target_limit, 200)
649
+
650
+ if rows_scanned % 200 == 0 or rows_scanned == 0:
651
+ print(f"[*] Progress: {rows_scanned}/{total} scanned | {len(all_matching_results)} hits | {len(related_cache)} stories cached")
652
+
653
+ batch = conn.execute(f"SELECT c.map_id, c.base_id, c.chapter_title, c.chapter_content, s.title as story_title, s.synopsis, c.author_name, c.author_raw_name, c.date as created, (SELECT MAX(LENGTH(c2.map_id)) - LENGTH(c.map_id) FROM chapters c2 WHERE c2.base_id = c.base_id AND c2.map_id LIKE c.map_id || '%') as ldfh FROM chapters_fts JOIN chapters c ON chapters_fts.rowid = c.id JOIN stories s ON c.base_id = s.base_id WHERE {where_sql} ORDER BY rank, c.id DESC LIMIT ? OFFSET ?", params + [fetch_batch_size, current_search_offset]).fetchall()
654
+ if not batch: break
655
+ for row in batch:
656
+ rows_scanned += 1
657
+ row_dict = dict(row)
658
+ meta_text = f"{row_dict.get('chapter_title') or ''} {row_dict.get('story_title') or ''} {row_dict.get('synopsis') or ''}".lower()
659
+ match_all, unmatched = True, []
660
+ for group_pats in compiled_patterns:
661
+ if not any(pat.search(meta_text) for pat in group_pats): unmatched.append(group_pats)
662
+ if unmatched:
663
+ clean_content = clean_chapter_content(row_dict.get('chapter_content'))
664
+ content_low = html.unescape(re.sub(r'<[^>]+>', ' ', clean_content)).lower()
665
+ for group_pats in unmatched:
666
+ if not any(pat.search(content_low) for pat in group_pats): match_all = False; break
667
+ else: clean_content = None
668
+
669
+ if match_all and related_filter:
670
+ bid = row_dict['base_id']
671
+ if bid not in related_cache:
672
+ try:
673
+ rel_rows = conn.execute(f"SELECT c.base_id, c.map_id, c.chapter_title, c.chapter_content, c.author_name, c.author_raw_name, c.date as created, (SELECT MAX(LENGTH(c2.map_id)) - LENGTH(c.map_id) FROM chapters c2 WHERE c2.base_id = c.base_id AND c2.map_id LIKE c.map_id || '%') as ldfh FROM chapters_fts f JOIN chapters c ON f.rowid = c.id WHERE c.base_id = ? AND f.chapters_fts MATCH ?", (bid, rel_fts_val)).fetchall()
674
+ processed_rel = []
675
+ for rr in rel_rows:
676
+ rd = dict(rr)
677
+ # Lightweight cleaning for search text: just strip HTML tags and unescape
678
+ raw_text = f"{rd.get('chapter_title') or ''} {rd.get('chapter_content') or ''}"
679
+ rd['_search_text'] = html.unescape(re.sub(r'<[^>]+>', ' ', raw_text)).lower()
680
+ processed_rel.append(rd)
681
+ related_cache[bid] = processed_rel
682
+ except: related_cache[bid] = []
683
+
684
+ m_map, m_suf = row_dict['map_id'], (row_dict['map_id'].split('-')[1] if '-' in row_dict['map_id'] else "").replace("Intro", "")
685
+ valid_related = []
686
+ for rr in related_cache[bid]:
687
+ r_suf = (rr['map_id'].split('-')[1] if '-' in rr['map_id'] else "").replace("Intro", "")
688
+ if related_depth_limit is not None and (not (r_suf.startswith(m_suf) or m_suf.startswith(r_suf)) or abs(len(r_suf)-len(m_suf)) > related_depth_limit): continue
689
+
690
+ rr_txt = rr['_search_text']
691
+ rel_match_all, matched_terms = True, []
692
+ for grp_idx, grp_pats in enumerate(rel_compiled_patterns):
693
+ grp_matched = False
694
+ for pat_idx, pat in enumerate(grp_pats):
695
+ if pat.search(rr_txt):
696
+ grp_matched = True
697
+ matched_terms.append(related_groups[grp_idx][pat_idx].strip('"'))
698
+ if not grp_matched:
699
+ rel_match_all = False
700
+ break
701
+ if not rel_match_all: continue
702
+
703
+ rr_copy = dict(rr)
704
+ rr_copy['matched_terms_found'] = list(set(matched_terms))
705
+ valid_related.append(rr_copy)
706
+
707
+ if not valid_related: match_all = False
708
+ else: row_dict['related_matches_pre'] = valid_related[:20]
709
+
710
+ if match_all:
711
+ if results_to_skip > 0: results_to_skip -= 1
712
+ else:
713
+ if clean_content is None: clean_content = clean_chapter_content(row_dict.get('chapter_content'))
714
+ row_dict['chapter_content_clean'] = clean_content
715
+ row_dict['content_text'] = normalize_snippet_text(clean_content)
716
+ all_matching_results.append(row_dict)
717
+ if len(all_matching_results) >= target_limit: break
718
+ current_search_offset += fetch_batch_size
719
+ if len(batch) < fetch_batch_size: break
720
+
721
+ scanned_all = (len(all_matching_results) < target_limit) and (rows_scanned < max_scan_total)
722
+ if scanned_all:
723
+ total = (offset - results_to_skip) + len(all_matching_results)
724
+ except Exception as e:
725
+ print(f"Error during search: {e}")
726
+ all_matching_results, total = [], 0
727
+ final_results = []
728
+ def part_in_text(part, text):
729
+ if not text: return False
730
+ pat = build_term_pattern(part.strip('"'), prefix_match=False)
731
+ return bool(pat and pat.search(text))
732
+ for row_dict in all_matching_results[:limit]:
733
+ content, synopsis = row_dict.get('chapter_content_clean') or "", row_dict.get('synopsis') or ""
734
+ text_source = content if any(part_in_text(p, row_dict.get('content_text') or "") for p in query_parts) else (synopsis if any(part_in_text(p, synopsis) for p in query_parts) else (content or synopsis))
735
+ row_dict['snippet'] = make_like_snippet(text_source, query_parts, radius=snippet_limit)
736
+ row_dict['chapter_title'] = highlight_query_terms(row_dict.get('chapter_title') or "", query_parts)
737
+ row_dict['story_title'] = highlight_query_terms(row_dict.get('story_title') or "", query_parts)
738
+ for k in ['chapter_content', 'chapter_content_clean', 'content_text', 'synopsis']: row_dict.pop(k, None)
739
+ final_results.append(row_dict)
740
+
741
+ if final_results and related_filter:
742
+ for res in final_results:
743
+ pre_matches = res.pop('related_matches_pre', [])
744
+ res['related_matches'] = []
745
+ for rr in pre_matches:
746
+ res['related_matches'].append({
747
+ "map_id": rr["map_id"], "title": rr["chapter_title"],
748
+ "snippet": make_like_snippet(rr["chapter_content"], related_parts, radius=related_snippet_limit),
749
+ "author_name": rr["author_name"], "author_raw_name": rr["author_raw_name"],
750
+ "created": rr["created"], "matched_terms": rr.get('matched_terms_found', []), "ldfh": rr["ldfh"]
751
+ })
752
+ conn.close()
753
+ duration = time.time() - start_time
754
+ print(f"[*] Search complete in {duration:.2f}s. Results found: {len(final_results)}.")
755
+ return jsonify({'results': final_results, 'total': total, 'page': page, 'limit': limit, 'query': q, 'duration': duration})
756
+
757
+ if __name__ == '__main__': app.run(host='0.0.0.0', port=9999, debug=True)