q6 commited on
Commit
a5535e5
·
1 Parent(s): 94df492

Add targeted deep scans

Browse files
Files changed (4) hide show
  1. backend/app.py +151 -54
  2. frontend/app.js +22 -4
  3. frontend/index.html +8 -3
  4. frontend/style.css +6 -1
backend/app.py CHANGED
@@ -241,6 +241,7 @@ async def init_db():
241
  "ALTER TABLE pi_searches ADD COLUMN found_exif INTEGER DEFAULT 0",
242
  "ALTER TABLE pi_searches ADD COLUMN total_searched INTEGER DEFAULT 0",
243
  "ALTER TABLE pi_searches ADD COLUMN deep_scan INTEGER DEFAULT 1",
 
244
  "ALTER TABLE pi_scans ADD COLUMN deep_scanned INTEGER DEFAULT 0",
245
  "ALTER TABLE pi_scans ADD COLUMN bookmark_count INTEGER",
246
  "ALTER TABLE pi_scans ADD COLUMN view_count INTEGER",
@@ -373,17 +374,30 @@ def get_search_api_url(raw, keywords):
373
  return f"https://www.pixiv.net/ajax/search/artworks/{encoded}?{params}"
374
 
375
 
376
- async def save_search(search_id, post_ids, deep_scan=True):
 
 
 
 
 
 
 
 
 
 
377
  if not post_ids:
378
  return
379
  if task_canceled(search_id):
380
  raise TaskCanceled()
 
381
  stmt = {
382
- "sql": "INSERT OR REPLACE INTO pi_searches (id, post_ids, deep_scan) VALUES (?, ?, ?)",
 
383
  "args": [
384
  {"type": "text", "value": search_id},
385
  {"type": "text", "value": json.dumps(post_ids)},
386
  {"type": "integer", "value": "1" if deep_scan else "0"},
 
387
  ],
388
  }
389
  await turso_execute([stmt])
@@ -604,10 +618,9 @@ async def get_search_counts(search_id):
604
  resp = await turso_execute(
605
  [
606
  {
607
- "sql": "WITH ids AS ("
608
- "SELECT CAST(j.value AS TEXT) post_id FROM pi_searches p, json_each(p.post_ids) j "
609
- "WHERE p.id = ?"
610
- ") SELECT COUNT(*), COUNT(s.post_id), COUNT(s.exif_type) "
611
  "FROM ids LEFT JOIN pi_scans s ON s.post_id = ids.post_id",
612
  "args": [{"type": "text", "value": search_id}],
613
  }
@@ -666,7 +679,13 @@ async def update_search_stats_batch(search_ids):
666
  [
667
  {
668
  "sql": "WITH counts AS ("
669
- "SELECT p.id, COUNT(s.post_id) scanned, COUNT(s.exif_type) found "
 
 
 
 
 
 
670
  "FROM pi_searches p JOIN json_each(p.post_ids) j "
671
  "LEFT JOIN pi_scans s ON s.post_id = CAST(j.value AS TEXT) "
672
  f"WHERE p.id IN ({marks}) GROUP BY p.id"
@@ -699,17 +718,23 @@ async def get_unscanned_post_ids(search_id):
699
  return [cell_value(row, 0, "") for row in first_rows(resp) if cell_value(row, 0, "")]
700
 
701
 
702
- async def get_deep_scan_targets(search_id):
 
 
 
 
 
 
703
  resp = await turso_execute(
704
  [
705
  {
706
  "sql": "WITH ids AS ("
707
  "SELECT CAST(j.value AS TEXT) post_id, CAST(j.key AS INTEGER) pos "
708
  "FROM pi_searches p, json_each(p.post_ids) j WHERE p.id = ?"
709
- ") SELECT ids.post_id, COALESCE(MAX(p.page), -1) + 1 start_page FROM ids "
710
  "JOIN pi_scans s ON s.post_id = ids.post_id "
711
  "LEFT JOIN pi_scan_pages p ON p.post_id = ids.post_id "
712
- "WHERE COALESCE(s.deep_scanned, 0) = 0 AND s.exif_type IS NOT NULL "
713
  "GROUP BY ids.post_id, ids.pos ORDER BY ids.pos",
714
  "args": [{"type": "text", "value": search_id}],
715
  }
@@ -759,6 +784,19 @@ async def search_uses_deep_scan(search_id):
759
  return bool(rows and int(cell_value(rows[0], 0, "0")))
760
 
761
 
 
 
 
 
 
 
 
 
 
 
 
 
 
762
  async def get_refresh_search_ids():
763
  resp = await turso_execute(
764
  [
@@ -810,13 +848,16 @@ async def get_result_counts(search_id):
810
 
811
  RESULT_BASE_SQL = (
812
  "WITH ids AS ("
813
- "SELECT CAST(j.value AS TEXT) post_id, CAST(j.key AS INTEGER) + 1 scan_index "
 
814
  "FROM pi_searches p, json_each(p.post_ids) j WHERE p.id = ?"
815
  "), tags AS ("
816
  "SELECT p.post_id, p.exif_type FROM pi_scan_pages p JOIN ids ON ids.post_id = p.post_id "
817
- "WHERE p.exif_type IS NOT NULL UNION "
 
818
  "SELECT s.post_id, s.exif_type FROM pi_scans s JOIN ids ON ids.post_id = s.post_id "
819
- "WHERE s.exif_type IS NOT NULL) "
 
820
  )
821
 
822
 
@@ -909,7 +950,9 @@ async def get_download_targets(search_id, through, allowed):
909
  "sql": RESULT_BASE_SQL
910
  + "SELECT ids.post_id, ids.scan_index, COALESCE(p.url, s.url) "
911
  "FROM ids JOIN pi_scans s ON s.post_id = ids.post_id "
912
- "LEFT JOIN pi_scan_pages p ON p.post_id = ids.post_id "
 
 
913
  f"WHERE ids.scan_index <= ? AND {where_sql} "
914
  "ORDER BY ids.scan_index, COALESCE(p.page, 0)",
915
  "args": [
@@ -985,7 +1028,7 @@ async def get_result_page(search_id, page, allowed, sort_bookmarks=True):
985
  {
986
  "sql": RESULT_BASE_SQL
987
  + "SELECT COUNT(*), COUNT(s.post_id), "
988
- "(SELECT COUNT(DISTINCT post_id) FROM tags) "
989
  "FROM ids LEFT JOIN pi_scans s ON s.post_id = ids.post_id",
990
  "args": [id_arg],
991
  },
@@ -1030,6 +1073,7 @@ async def get_result_page(search_id, page, allowed, sort_bookmarks=True):
1030
  int(cell_value(row, 0, "0")): int(cell_value(row, 1, "0"))
1031
  for row in type_rows
1032
  }
 
1033
  result_pages = await get_result_pages([cell_value(row, 0, "") for row in item_rows])
1034
  items = []
1035
  for row in item_rows:
@@ -1038,11 +1082,17 @@ async def get_result_page(search_id, page, allowed, sort_bookmarks=True):
1038
  exif_type = cell_value(row, 3)
1039
  bookmark_count = cell_value(row, 4)
1040
  view_count = cell_value(row, 5)
1041
- page_rows = result_pages.get(pid) or []
 
 
 
 
1042
  exif_types = sorted(
1043
  {item["exif_type"] for item in page_rows if item["exif_type"]}
1044
  )
1045
- if not exif_types and exif_type:
 
 
1046
  exif_types = [int(exif_type)]
1047
  enabled = set(allowed if allowed is not None else exif_types)
1048
  visible_rows = [
@@ -1094,7 +1144,9 @@ def user_search_id(user_id):
1094
  return f"{base26_time()}_{user_id}"
1095
 
1096
 
1097
- async def pixiv_search_live(url, pages, mode, phpsessid, search_id, deep_scan=True):
 
 
1098
  keywords = get_search_keywords(url)
1099
  api_url = get_search_api_url(url, keywords)
1100
  first_url = f"{api_url}&p=1"
@@ -1141,7 +1193,9 @@ async def pixiv_search_live(url, pages, mode, phpsessid, search_id, deep_scan=Tr
1141
  if done % 25 == 0:
1142
  if task_canceled(search_id):
1143
  raise TaskCanceled()
1144
- await save_search(search_id, post_ids, deep_scan)
 
 
1145
  finally:
1146
  for task in tasks:
1147
  if not task.done():
@@ -1149,7 +1203,7 @@ async def pixiv_search_live(url, pages, mode, phpsessid, search_id, deep_scan=Tr
1149
  await asyncio.gather(*tasks, return_exceptions=True)
1150
  if task_canceled(search_id):
1151
  raise TaskCanceled()
1152
- await save_search(search_id, post_ids, deep_scan)
1153
  return post_ids, keywords, first_url
1154
 
1155
 
@@ -1656,34 +1710,42 @@ async def scan_post(post_id, session, post_sem, img_sem):
1656
  return None
1657
 
1658
 
1659
- def scan_image_data(data):
 
1660
  fallback = None
1661
  exif_type = determine_exif_type(parse_image_metadata(data))
 
1662
  if exif_type in FALLBACK_EXIF_TYPES:
1663
- fallback = EXIF_TYPE_TO_CODE.get(exif_type)
1664
- elif exif_type:
1665
- return EXIF_TYPE_TO_CODE.get(exif_type)
 
1666
  metadata, detected = parse_stealth_metadata(data)
1667
  exif_type = determine_exif_type(metadata)
 
1668
  if exif_type in FALLBACK_EXIF_TYPES:
1669
- fallback = fallback or EXIF_TYPE_TO_CODE.get(exif_type)
 
1670
  elif exif_type == "nai":
1671
- return EXIF_TYPE_TO_CODE.get("nai_stealth")
1672
- elif exif_type:
1673
- return EXIF_TYPE_TO_CODE.get(exif_type)
1674
- return EXIF_TYPE_TO_CODE.get("nai_stealth") if detected else fallback
 
 
 
1675
 
1676
 
1677
- async def scan_page_result(post_id, url, session, img_sem):
1678
  page = page_num_from_url(url)
1679
  img_data = await fetch_image(session, url, img_sem, post_id, page)
1680
  if not img_data:
1681
  return None
1682
- exif_type = await asyncio.to_thread(scan_image_data, img_data)
1683
  return post_id, url, exif_type
1684
 
1685
 
1686
- async def deep_scan_post(item, session, post_sem, img_sem):
1687
  async with post_sem:
1688
  try:
1689
  post_id = item["post_id"]
@@ -1697,7 +1759,9 @@ async def deep_scan_post(item, session, post_sem, img_sem):
1697
  for page, urls in enumerate(pages[start_page:], start_page):
1698
  url = urls["original"]
1699
  try:
1700
- result = await scan_page_result(post_id, url, session, img_sem)
 
 
1701
  except Exception:
1702
  result = None
1703
  if not result:
@@ -1791,7 +1855,7 @@ async def run_scan(post_ids, phpsessid, task_id=None, save_live=False, done_offs
1791
  return results
1792
 
1793
 
1794
- async def run_deep_scan(targets, phpsessid, task_id=None):
1795
  cookies = {"PHPSESSID": phpsessid}
1796
  completed = 0
1797
  pending = []
@@ -1809,7 +1873,9 @@ async def run_deep_scan(targets, phpsessid, task_id=None):
1809
  except StopIteration:
1810
  break
1811
  task = asyncio.create_task(
1812
- deep_scan_post(item, session, POST_SCAN_SEM, FULL_IMAGE_SEM)
 
 
1813
  )
1814
  tasks.add(task)
1815
  created.add(task)
@@ -1837,11 +1903,11 @@ async def run_deep_scan(targets, phpsessid, task_id=None):
1837
  if task_id and task_id in ACTIVE_TASKS:
1838
  ACTIVE_TASKS[task_id]["done"] = completed
1839
  if len(pending) >= 20:
1840
- await save_deep_scan_results(pending)
1841
  pending = []
1842
  fill_tasks()
1843
  if pending:
1844
- await save_deep_scan_results(pending)
1845
  finally:
1846
  for task in created:
1847
  if not task.done():
@@ -1898,11 +1964,13 @@ async def save_scan_results(results):
1898
  await turso_batch(stmts[i : i + 200])
1899
 
1900
 
1901
- async def save_deep_scan_results(results):
1902
  stmts = []
1903
  stored = await get_result_pages([str(result[0]) for result in results])
1904
  for post_id, pages, fresh, complete in results:
1905
  for _, page, url, exif_type in fresh:
 
 
1906
  short_url = url.replace(IMG_BASE, "", 1) if url else ""
1907
  stmts.append(
1908
  {
@@ -1917,10 +1985,18 @@ async def save_deep_scan_results(results):
1917
  ],
1918
  }
1919
  )
1920
- all_pages = [
1921
- (post_id, row["page"], row["url"], row["exif_type"])
1922
  for row in stored.get(str(post_id), ())
1923
- ] + pages
 
 
 
 
 
 
 
 
1924
  counts = {}
1925
  for _, _, _, exif_type in all_pages:
1926
  if not exif_type:
@@ -2265,17 +2341,24 @@ async def bg_search_task(search_id, url, pages, mode, phpsessid):
2265
  await finish_task(search_id)
2266
 
2267
 
2268
- async def deep_scan_search(search_id, phpsessid):
2269
- targets = await get_deep_scan_targets(search_id)
 
 
 
2270
  if not targets:
2271
  return
2272
  ACTIVE_TASKS[search_id].update(
2273
  {"phase": "deep scanning", "total": len(targets), "done": 0, "raw_total": 0}
2274
  )
2275
- await run_deep_scan(targets, phpsessid, task_id=search_id)
 
 
2276
 
2277
 
2278
- async def bg_user_task(search_id, user_id, phpsessid, deep_scan=True):
 
 
2279
  if not start_task(search_id, {
2280
  "type": "user_search",
2281
  "phase": "searching",
@@ -2294,7 +2377,7 @@ async def bg_user_task(search_id, user_id, phpsessid, deep_scan=True):
2294
  ACTIVE_TASKS[search_id]["done"] = 1
2295
  if not post_ids:
2296
  return
2297
- await save_search(search_id, post_ids, deep_scan)
2298
  to_scan = await get_unscanned_post_ids(search_id)
2299
  if to_scan:
2300
  ACTIVE_TASKS[search_id].update({
@@ -2303,7 +2386,7 @@ async def bg_user_task(search_id, user_id, phpsessid, deep_scan=True):
2303
  })
2304
  await run_scan(to_scan, phpsessid, task_id=search_id, save_live=True)
2305
  if deep_scan:
2306
- await deep_scan_search(search_id, phpsessid)
2307
  await cache_search_popularity(search_id)
2308
  await update_search_stats(search_id)
2309
  await patch_explorer_cache(search_id, front=True)
@@ -2315,10 +2398,12 @@ async def bg_user_task(search_id, user_id, phpsessid, deep_scan=True):
2315
  await finish_task(search_id)
2316
 
2317
 
2318
- async def bg_user_batch_task(jobs, phpsessid, deep_scan=True):
2319
  await asyncio.gather(
2320
  *(
2321
- bg_user_task(search_id, user_id, phpsessid, deep_scan)
 
 
2322
  for search_id, user_id in jobs
2323
  )
2324
  )
@@ -2353,7 +2438,7 @@ async def bg_scan_task(search_id, post_ids, phpsessid, deep_scan=True):
2353
 
2354
 
2355
  async def bg_search_and_scan_task(
2356
- search_id, url, pages, mode, phpsessid, deep_scan=True
2357
  ):
2358
  if not start_task(search_id, {
2359
  "type": "search+scan",
@@ -2366,7 +2451,7 @@ async def bg_search_and_scan_task(
2366
  completed = False
2367
  try:
2368
  await pixiv_search_live(
2369
- url, pages, mode, phpsessid, search_id, deep_scan
2370
  )
2371
  to_scan = await get_unscanned_post_ids(search_id)
2372
  if to_scan:
@@ -2376,7 +2461,7 @@ async def bg_search_and_scan_task(
2376
  })
2377
  await run_scan(to_scan, phpsessid, task_id=search_id, save_live=True)
2378
  if deep_scan:
2379
- await deep_scan_search(search_id, phpsessid)
2380
  await cache_search_popularity(search_id)
2381
  await update_search_stats(search_id)
2382
  await patch_explorer_cache(search_id, front=True)
@@ -2472,12 +2557,14 @@ class SearchRequest(BaseModel):
2472
  mode: str = "ai"
2473
  action: str = "search"
2474
  deep_scan: bool = True
 
2475
 
2476
 
2477
  class UserSearchRequest(BaseModel):
2478
  user_ids: list
2479
  action: str = "search"
2480
  deep_scan: bool = True
 
2481
 
2482
 
2483
  class PostSearchRequest(BaseModel):
@@ -2655,6 +2742,7 @@ async def submit_search(req: SearchRequest, bg: BackgroundTasks):
2655
  req.mode,
2656
  phpsessid,
2657
  req.deep_scan,
 
2658
  )
2659
  return {"id": search_id, "status": "started"}
2660
 
@@ -2664,7 +2752,13 @@ async def submit_users(req: UserSearchRequest, bg: BackgroundTasks):
2664
  phpsessid = PHPSESSID
2665
  user_ids = list(dict.fromkeys(int(u) for u in req.user_ids))
2666
  jobs = [(user_search_id(uid), uid) for uid in user_ids]
2667
- bg.add_task(bg_user_batch_task, jobs, phpsessid, req.deep_scan)
 
 
 
 
 
 
2668
  return {"ids": [search_id for search_id, _ in jobs], "status": "started"}
2669
 
2670
 
@@ -2727,7 +2821,10 @@ async def scan_search(req: ScanRequest, bg: BackgroundTasks):
2727
  ]
2728
  )
2729
  to_scan = await get_unscanned_post_ids(req.search_id)
2730
- deep_targets = await get_deep_scan_targets(req.search_id)
 
 
 
2731
  popularity_ids = await get_missing_popularity_post_ids(req.search_id)
2732
  if not to_scan and not deep_targets and not popularity_ids:
2733
  return {"status": "already_scanned", "count": counts["raw_total"]}
 
241
  "ALTER TABLE pi_searches ADD COLUMN found_exif INTEGER DEFAULT 0",
242
  "ALTER TABLE pi_searches ADD COLUMN total_searched INTEGER DEFAULT 0",
243
  "ALTER TABLE pi_searches ADD COLUMN deep_scan INTEGER DEFAULT 1",
244
+ "ALTER TABLE pi_searches ADD COLUMN deep_scan_types TEXT DEFAULT '[]'",
245
  "ALTER TABLE pi_scans ADD COLUMN deep_scanned INTEGER DEFAULT 0",
246
  "ALTER TABLE pi_scans ADD COLUMN bookmark_count INTEGER",
247
  "ALTER TABLE pi_scans ADD COLUMN view_count INTEGER",
 
374
  return f"https://www.pixiv.net/ajax/search/artworks/{encoded}?{params}"
375
 
376
 
377
+ def exif_codes(values):
378
+ return sorted(
379
+ {
380
+ int(code)
381
+ for code in values or []
382
+ if str(code).isdigit() and int(code) in EXIF_CODE_TO_TYPE
383
+ }
384
+ )
385
+
386
+
387
+ async def save_search(search_id, post_ids, deep_scan=True, deep_scan_types=None):
388
  if not post_ids:
389
  return
390
  if task_canceled(search_id):
391
  raise TaskCanceled()
392
+ deep_scan_types = exif_codes(deep_scan_types) if deep_scan else []
393
  stmt = {
394
+ "sql": "INSERT OR REPLACE INTO pi_searches "
395
+ "(id, post_ids, deep_scan, deep_scan_types) VALUES (?, ?, ?, ?)",
396
  "args": [
397
  {"type": "text", "value": search_id},
398
  {"type": "text", "value": json.dumps(post_ids)},
399
  {"type": "integer", "value": "1" if deep_scan else "0"},
400
+ {"type": "text", "value": json.dumps(deep_scan_types or [])},
401
  ],
402
  }
403
  await turso_execute([stmt])
 
618
  resp = await turso_execute(
619
  [
620
  {
621
+ "sql": RESULT_BASE_SQL
622
+ + "SELECT COUNT(*), COUNT(s.post_id), "
623
+ "(SELECT COUNT(DISTINCT post_id) FROM tags) "
 
624
  "FROM ids LEFT JOIN pi_scans s ON s.post_id = ids.post_id",
625
  "args": [{"type": "text", "value": search_id}],
626
  }
 
679
  [
680
  {
681
  "sql": "WITH counts AS ("
682
+ "SELECT p.id, COUNT(s.post_id) scanned, COUNT(CASE WHEN "
683
+ "s.exif_type IS NOT NULL AND (COALESCE(p.deep_scan_types, '[]') = '[]' "
684
+ "OR EXISTS (SELECT 1 FROM json_each(p.deep_scan_types) "
685
+ "WHERE CAST(value AS INTEGER) = s.exif_type) OR EXISTS ("
686
+ "SELECT 1 FROM pi_scan_pages sp WHERE sp.post_id = s.post_id "
687
+ "AND sp.exif_type IN (SELECT CAST(value AS INTEGER) "
688
+ "FROM json_each(p.deep_scan_types)))) THEN 1 END) found "
689
  "FROM pi_searches p JOIN json_each(p.post_ids) j "
690
  "LEFT JOIN pi_scans s ON s.post_id = CAST(j.value AS TEXT) "
691
  f"WHERE p.id IN ({marks}) GROUP BY p.id"
 
718
  return [cell_value(row, 0, "") for row in first_rows(resp) if cell_value(row, 0, "")]
719
 
720
 
721
+ async def get_deep_scan_targets(search_id, targeted=False):
722
+ start_page = "0" if targeted else "COALESCE(MAX(p.page), -1) + 1"
723
+ condition = (
724
+ "s.exif_type IS NOT NULL"
725
+ if targeted
726
+ else "COALESCE(s.deep_scanned, 0) = 0 AND s.exif_type IS NOT NULL"
727
+ )
728
  resp = await turso_execute(
729
  [
730
  {
731
  "sql": "WITH ids AS ("
732
  "SELECT CAST(j.value AS TEXT) post_id, CAST(j.key AS INTEGER) pos "
733
  "FROM pi_searches p, json_each(p.post_ids) j WHERE p.id = ?"
734
+ f") SELECT ids.post_id, {start_page} start_page FROM ids "
735
  "JOIN pi_scans s ON s.post_id = ids.post_id "
736
  "LEFT JOIN pi_scan_pages p ON p.post_id = ids.post_id "
737
+ f"WHERE {condition} "
738
  "GROUP BY ids.post_id, ids.pos ORDER BY ids.pos",
739
  "args": [{"type": "text", "value": search_id}],
740
  }
 
784
  return bool(rows and int(cell_value(rows[0], 0, "0")))
785
 
786
 
787
+ async def get_search_deep_scan_types(search_id):
788
+ resp = await turso_execute(
789
+ [
790
+ {
791
+ "sql": "SELECT deep_scan_types FROM pi_searches WHERE id = ?",
792
+ "args": [{"type": "text", "value": search_id}],
793
+ }
794
+ ]
795
+ )
796
+ rows = first_rows(resp)
797
+ return exif_codes(json.loads(cell_value(rows[0], 0, "[]"))) if rows else []
798
+
799
+
800
  async def get_refresh_search_ids():
801
  resp = await turso_execute(
802
  [
 
848
 
849
  RESULT_BASE_SQL = (
850
  "WITH ids AS ("
851
+ "SELECT CAST(j.value AS TEXT) post_id, CAST(j.key AS INTEGER) + 1 scan_index, "
852
+ "COALESCE(p.deep_scan_types, '[]') deep_scan_types "
853
  "FROM pi_searches p, json_each(p.post_ids) j WHERE p.id = ?"
854
  "), tags AS ("
855
  "SELECT p.post_id, p.exif_type FROM pi_scan_pages p JOIN ids ON ids.post_id = p.post_id "
856
+ "WHERE p.exif_type IS NOT NULL AND (ids.deep_scan_types = '[]' OR EXISTS ("
857
+ "SELECT 1 FROM json_each(ids.deep_scan_types) WHERE CAST(value AS INTEGER) = p.exif_type)) UNION "
858
  "SELECT s.post_id, s.exif_type FROM pi_scans s JOIN ids ON ids.post_id = s.post_id "
859
+ "WHERE s.exif_type IS NOT NULL AND (ids.deep_scan_types = '[]' OR EXISTS ("
860
+ "SELECT 1 FROM json_each(ids.deep_scan_types) WHERE CAST(value AS INTEGER) = s.exif_type))) "
861
  )
862
 
863
 
 
950
  "sql": RESULT_BASE_SQL
951
  + "SELECT ids.post_id, ids.scan_index, COALESCE(p.url, s.url) "
952
  "FROM ids JOIN pi_scans s ON s.post_id = ids.post_id "
953
+ "LEFT JOIN pi_scan_pages p ON p.post_id = ids.post_id AND ("
954
+ "ids.deep_scan_types = '[]' OR EXISTS (SELECT 1 FROM json_each(ids.deep_scan_types) "
955
+ "WHERE CAST(value AS INTEGER) = p.exif_type)) "
956
  f"WHERE ids.scan_index <= ? AND {where_sql} "
957
  "ORDER BY ids.scan_index, COALESCE(p.page, 0)",
958
  "args": [
 
1028
  {
1029
  "sql": RESULT_BASE_SQL
1030
  + "SELECT COUNT(*), COUNT(s.post_id), "
1031
+ "(SELECT COUNT(DISTINCT post_id) FROM tags), MAX(ids.deep_scan_types) "
1032
  "FROM ids LEFT JOIN pi_scans s ON s.post_id = ids.post_id",
1033
  "args": [id_arg],
1034
  },
 
1073
  int(cell_value(row, 0, "0")): int(cell_value(row, 1, "0"))
1074
  for row in type_rows
1075
  }
1076
+ deep_scan_types = set(json.loads(cell_value(count_rows[0], 3, "[]")))
1077
  result_pages = await get_result_pages([cell_value(row, 0, "") for row in item_rows])
1078
  items = []
1079
  for row in item_rows:
 
1082
  exif_type = cell_value(row, 3)
1083
  bookmark_count = cell_value(row, 4)
1084
  view_count = cell_value(row, 5)
1085
+ page_rows = [
1086
+ item
1087
+ for item in result_pages.get(pid) or []
1088
+ if not deep_scan_types or item["exif_type"] in deep_scan_types
1089
+ ]
1090
  exif_types = sorted(
1091
  {item["exif_type"] for item in page_rows if item["exif_type"]}
1092
  )
1093
+ if not exif_types and exif_type and (
1094
+ not deep_scan_types or int(exif_type) in deep_scan_types
1095
+ ):
1096
  exif_types = [int(exif_type)]
1097
  enabled = set(allowed if allowed is not None else exif_types)
1098
  visible_rows = [
 
1144
  return f"{base26_time()}_{user_id}"
1145
 
1146
 
1147
+ async def pixiv_search_live(
1148
+ url, pages, mode, phpsessid, search_id, deep_scan=True, deep_scan_types=None
1149
+ ):
1150
  keywords = get_search_keywords(url)
1151
  api_url = get_search_api_url(url, keywords)
1152
  first_url = f"{api_url}&p=1"
 
1193
  if done % 25 == 0:
1194
  if task_canceled(search_id):
1195
  raise TaskCanceled()
1196
+ await save_search(
1197
+ search_id, post_ids, deep_scan, deep_scan_types
1198
+ )
1199
  finally:
1200
  for task in tasks:
1201
  if not task.done():
 
1203
  await asyncio.gather(*tasks, return_exceptions=True)
1204
  if task_canceled(search_id):
1205
  raise TaskCanceled()
1206
+ await save_search(search_id, post_ids, deep_scan, deep_scan_types)
1207
  return post_ids, keywords, first_url
1208
 
1209
 
 
1710
  return None
1711
 
1712
 
1713
+ def scan_image_data(data, allowed=None):
1714
+ allowed = set(allowed) if allowed else None
1715
  fallback = None
1716
  exif_type = determine_exif_type(parse_image_metadata(data))
1717
+ code = EXIF_TYPE_TO_CODE.get(exif_type)
1718
  if exif_type in FALLBACK_EXIF_TYPES:
1719
+ if allowed is None or code in allowed:
1720
+ fallback = code
1721
+ elif code and (allowed is None or code in allowed):
1722
+ return code
1723
  metadata, detected = parse_stealth_metadata(data)
1724
  exif_type = determine_exif_type(metadata)
1725
+ code = EXIF_TYPE_TO_CODE.get(exif_type)
1726
  if exif_type in FALLBACK_EXIF_TYPES:
1727
+ if allowed is None or code in allowed:
1728
+ fallback = fallback or code
1729
  elif exif_type == "nai":
1730
+ code = EXIF_TYPE_TO_CODE.get("nai_stealth")
1731
+ if allowed is None or code in allowed:
1732
+ return code
1733
+ elif code and (allowed is None or code in allowed):
1734
+ return code
1735
+ code = EXIF_TYPE_TO_CODE.get("nai_stealth")
1736
+ return code if detected and (allowed is None or code in allowed) else fallback
1737
 
1738
 
1739
+ async def scan_page_result(post_id, url, session, img_sem, allowed=None):
1740
  page = page_num_from_url(url)
1741
  img_data = await fetch_image(session, url, img_sem, post_id, page)
1742
  if not img_data:
1743
  return None
1744
+ exif_type = await asyncio.to_thread(scan_image_data, img_data, allowed)
1745
  return post_id, url, exif_type
1746
 
1747
 
1748
+ async def deep_scan_post(item, session, post_sem, img_sem, allowed=None):
1749
  async with post_sem:
1750
  try:
1751
  post_id = item["post_id"]
 
1759
  for page, urls in enumerate(pages[start_page:], start_page):
1760
  url = urls["original"]
1761
  try:
1762
+ result = await scan_page_result(
1763
+ post_id, url, session, img_sem, allowed
1764
+ )
1765
  except Exception:
1766
  result = None
1767
  if not result:
 
1855
  return results
1856
 
1857
 
1858
+ async def run_deep_scan(targets, phpsessid, task_id=None, allowed=None):
1859
  cookies = {"PHPSESSID": phpsessid}
1860
  completed = 0
1861
  pending = []
 
1873
  except StopIteration:
1874
  break
1875
  task = asyncio.create_task(
1876
+ deep_scan_post(
1877
+ item, session, POST_SCAN_SEM, FULL_IMAGE_SEM, allowed
1878
+ )
1879
  )
1880
  tasks.add(task)
1881
  created.add(task)
 
1903
  if task_id and task_id in ACTIVE_TASKS:
1904
  ACTIVE_TASKS[task_id]["done"] = completed
1905
  if len(pending) >= 20:
1906
+ await save_deep_scan_results(pending, bool(allowed))
1907
  pending = []
1908
  fill_tasks()
1909
  if pending:
1910
+ await save_deep_scan_results(pending, bool(allowed))
1911
  finally:
1912
  for task in created:
1913
  if not task.done():
 
1964
  await turso_batch(stmts[i : i + 200])
1965
 
1966
 
1967
+ async def save_deep_scan_results(results, preserve_empty=False):
1968
  stmts = []
1969
  stored = await get_result_pages([str(result[0]) for result in results])
1970
  for post_id, pages, fresh, complete in results:
1971
  for _, page, url, exif_type in fresh:
1972
+ if preserve_empty and not exif_type:
1973
+ continue
1974
  short_url = url.replace(IMG_BASE, "", 1) if url else ""
1975
  stmts.append(
1976
  {
 
1985
  ],
1986
  }
1987
  )
1988
+ page_map = {
1989
+ row["page"]: (post_id, row["page"], row["url"], row["exif_type"])
1990
  for row in stored.get(str(post_id), ())
1991
+ }
1992
+ page_map.update(
1993
+ {
1994
+ row[1]: row
1995
+ for row in pages
1996
+ if row[3] or not preserve_empty
1997
+ }
1998
+ )
1999
+ all_pages = list(page_map.values())
2000
  counts = {}
2001
  for _, _, _, exif_type in all_pages:
2002
  if not exif_type:
 
2341
  await finish_task(search_id)
2342
 
2343
 
2344
+ async def deep_scan_search(search_id, phpsessid, deep_scan_types=None):
2345
+ allowed = exif_codes(deep_scan_types)
2346
+ if deep_scan_types is None:
2347
+ allowed = await get_search_deep_scan_types(search_id)
2348
+ targets = await get_deep_scan_targets(search_id, bool(allowed))
2349
  if not targets:
2350
  return
2351
  ACTIVE_TASKS[search_id].update(
2352
  {"phase": "deep scanning", "total": len(targets), "done": 0, "raw_total": 0}
2353
  )
2354
+ await run_deep_scan(
2355
+ targets, phpsessid, task_id=search_id, allowed=allowed or None
2356
+ )
2357
 
2358
 
2359
+ async def bg_user_task(
2360
+ search_id, user_id, phpsessid, deep_scan=True, deep_scan_types=None
2361
+ ):
2362
  if not start_task(search_id, {
2363
  "type": "user_search",
2364
  "phase": "searching",
 
2377
  ACTIVE_TASKS[search_id]["done"] = 1
2378
  if not post_ids:
2379
  return
2380
+ await save_search(search_id, post_ids, deep_scan, deep_scan_types)
2381
  to_scan = await get_unscanned_post_ids(search_id)
2382
  if to_scan:
2383
  ACTIVE_TASKS[search_id].update({
 
2386
  })
2387
  await run_scan(to_scan, phpsessid, task_id=search_id, save_live=True)
2388
  if deep_scan:
2389
+ await deep_scan_search(search_id, phpsessid, deep_scan_types)
2390
  await cache_search_popularity(search_id)
2391
  await update_search_stats(search_id)
2392
  await patch_explorer_cache(search_id, front=True)
 
2398
  await finish_task(search_id)
2399
 
2400
 
2401
+ async def bg_user_batch_task(jobs, phpsessid, deep_scan=True, deep_scan_types=None):
2402
  await asyncio.gather(
2403
  *(
2404
+ bg_user_task(
2405
+ search_id, user_id, phpsessid, deep_scan, deep_scan_types
2406
+ )
2407
  for search_id, user_id in jobs
2408
  )
2409
  )
 
2438
 
2439
 
2440
  async def bg_search_and_scan_task(
2441
+ search_id, url, pages, mode, phpsessid, deep_scan=True, deep_scan_types=None
2442
  ):
2443
  if not start_task(search_id, {
2444
  "type": "search+scan",
 
2451
  completed = False
2452
  try:
2453
  await pixiv_search_live(
2454
+ url, pages, mode, phpsessid, search_id, deep_scan, deep_scan_types
2455
  )
2456
  to_scan = await get_unscanned_post_ids(search_id)
2457
  if to_scan:
 
2461
  })
2462
  await run_scan(to_scan, phpsessid, task_id=search_id, save_live=True)
2463
  if deep_scan:
2464
+ await deep_scan_search(search_id, phpsessid, deep_scan_types)
2465
  await cache_search_popularity(search_id)
2466
  await update_search_stats(search_id)
2467
  await patch_explorer_cache(search_id, front=True)
 
2557
  mode: str = "ai"
2558
  action: str = "search"
2559
  deep_scan: bool = True
2560
+ deep_scan_types: list = []
2561
 
2562
 
2563
  class UserSearchRequest(BaseModel):
2564
  user_ids: list
2565
  action: str = "search"
2566
  deep_scan: bool = True
2567
+ deep_scan_types: list = []
2568
 
2569
 
2570
  class PostSearchRequest(BaseModel):
 
2742
  req.mode,
2743
  phpsessid,
2744
  req.deep_scan,
2745
+ req.deep_scan_types,
2746
  )
2747
  return {"id": search_id, "status": "started"}
2748
 
 
2752
  phpsessid = PHPSESSID
2753
  user_ids = list(dict.fromkeys(int(u) for u in req.user_ids))
2754
  jobs = [(user_search_id(uid), uid) for uid in user_ids]
2755
+ bg.add_task(
2756
+ bg_user_batch_task,
2757
+ jobs,
2758
+ phpsessid,
2759
+ req.deep_scan,
2760
+ req.deep_scan_types,
2761
+ )
2762
  return {"ids": [search_id for search_id, _ in jobs], "status": "started"}
2763
 
2764
 
 
2821
  ]
2822
  )
2823
  to_scan = await get_unscanned_post_ids(req.search_id)
2824
+ deep_scan_types = await get_search_deep_scan_types(req.search_id)
2825
+ deep_targets = await get_deep_scan_targets(
2826
+ req.search_id, bool(deep_scan_types)
2827
+ )
2828
  popularity_ids = await get_missing_popularity_post_ids(req.search_id)
2829
  if not to_scan and not deep_targets and not popularity_ids:
2830
  return {"status": "already_scanned", "count": counts["raw_total"]}
frontend/app.js CHANGED
@@ -42,6 +42,15 @@ let resultCardCache = new Map()
42
  let postSearchCardCache = new Map()
43
  let exifCountsCache = new Map()
44
 
 
 
 
 
 
 
 
 
 
45
 
46
  $$(".tab").forEach(tab => {
47
  tab.addEventListener("click", () => {
@@ -79,7 +88,14 @@ $("#btn-submit").addEventListener("click", async () => {
79
  const pages = parseInt($("#input-pages").value) || 30
80
  const mode = $("#input-mode").value
81
  const deepScan = $("#input-deep-scan").checked
 
 
82
  const status = $("#submit-status")
 
 
 
 
 
83
  status.textContent = "Submitting..."
84
  status.className = ""
85
 
@@ -99,13 +115,13 @@ $("#btn-submit").addEventListener("click", async () => {
99
  resp = await fetch("/api/submit_users", {
100
  method: "POST",
101
  headers: { "Content-Type": "application/json" },
102
- body: JSON.stringify({ user_ids: userIds, deep_scan: deepScan })
103
  })
104
  } else {
105
  resp = await fetch("/api/submit", {
106
  method: "POST",
107
  headers: { "Content-Type": "application/json" },
108
- body: JSON.stringify({ url, pages, mode, deep_scan: deepScan })
109
  })
110
  }
111
  const data = await resp.json()
@@ -393,8 +409,8 @@ function selectedCategoryTypes(root) {
393
  .map(el => Number(el.dataset.code))
394
  }
395
 
396
- function renderCategoryFilters(root) {
397
- const buttons = FILTER_CODES.map(code => {
398
  return `<button class="filter-btn active" data-code="${code}">${esc(CATEGORY_NAMES[code])}</button>`
399
  }).join("")
400
  $(root).innerHTML = `${buttons}
@@ -880,6 +896,8 @@ async function renameSearch(id) {
880
  }
881
 
882
  window.addEventListener("hashchange", route)
 
883
  renderCategoryFilters("#reclass-filters")
 
884
  if (!location.hash) location.hash = "#/submit"
885
  route()
 
42
  let postSearchCardCache = new Map()
43
  let exifCountsCache = new Map()
44
 
45
+ function syncDeepScanTargets() {
46
+ const enabled = $("#input-deep-scan").checked
47
+ const targeted = $("#input-targeted-deep-scan")
48
+ targeted.disabled = !enabled
49
+ $("#deep-scan-filters").classList.toggle("hidden", !enabled || !targeted.checked)
50
+ }
51
+
52
+ $("#input-deep-scan").addEventListener("change", syncDeepScanTargets)
53
+ $("#input-targeted-deep-scan").addEventListener("change", syncDeepScanTargets)
54
 
55
  $$(".tab").forEach(tab => {
56
  tab.addEventListener("click", () => {
 
88
  const pages = parseInt($("#input-pages").value) || 30
89
  const mode = $("#input-mode").value
90
  const deepScan = $("#input-deep-scan").checked
91
+ const targeted = deepScan && $("#input-targeted-deep-scan").checked
92
+ const deepScanTypes = targeted ? selectedCategoryTypes("#deep-scan-filters") : []
93
  const status = $("#submit-status")
94
+ if (targeted && !deepScanTypes.length) {
95
+ status.textContent = "Select at least one deep scan category"
96
+ status.className = "status-err"
97
+ return
98
+ }
99
  status.textContent = "Submitting..."
100
  status.className = ""
101
 
 
115
  resp = await fetch("/api/submit_users", {
116
  method: "POST",
117
  headers: { "Content-Type": "application/json" },
118
+ body: JSON.stringify({ user_ids: userIds, deep_scan: deepScan, deep_scan_types: deepScanTypes })
119
  })
120
  } else {
121
  resp = await fetch("/api/submit", {
122
  method: "POST",
123
  headers: { "Content-Type": "application/json" },
124
+ body: JSON.stringify({ url, pages, mode, deep_scan: deepScan, deep_scan_types: deepScanTypes })
125
  })
126
  }
127
  const data = await resp.json()
 
409
  .map(el => Number(el.dataset.code))
410
  }
411
 
412
+ function renderCategoryFilters(root, codes = FILTER_CODES) {
413
+ const buttons = codes.map(code => {
414
  return `<button class="filter-btn active" data-code="${code}">${esc(CATEGORY_NAMES[code])}</button>`
415
  }).join("")
416
  $(root).innerHTML = `${buttons}
 
896
  }
897
 
898
  window.addEventListener("hashchange", route)
899
+ renderCategoryFilters("#deep-scan-filters", EXIF_CODES)
900
  renderCategoryFilters("#reclass-filters")
901
+ syncDeepScanTargets()
902
  if (!location.hash) location.hash = "#/submit"
903
  route()
frontend/index.html CHANGED
@@ -3,9 +3,9 @@
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <link rel="icon" href="data:;base64,=">
7
  <title>Pixif2</title>
8
- <link rel="stylesheet" href="style.css?v=20260801-1">
9
  </head>
10
  <body>
11
  <div class="topbar">
@@ -45,8 +45,13 @@
45
  <input type="checkbox" id="input-deep-scan" checked>
46
  <span>Deep scan</span>
47
  </label>
 
 
 
 
48
  <button id="btn-submit" class="btn-primary">Submit</button>
49
  </div>
 
50
  <div id="submit-status"></div>
51
  </section>
52
 
@@ -123,6 +128,6 @@
123
  <button id="viewer-next" class="viewer-nav" aria-label="Next result page">&rsaquo;</button>
124
  </div>
125
  </div>
126
- <script src="app.js?v=20260801-1"></script>
127
  </body>
128
  </html>
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <link rel="icon" href="data:,">
7
  <title>Pixif2</title>
8
+ <link rel="stylesheet" href="style.css?v=20260803-1">
9
  </head>
10
  <body>
11
  <div class="topbar">
 
45
  <input type="checkbox" id="input-deep-scan" checked>
46
  <span>Deep scan</span>
47
  </label>
48
+ <label class="check-field">
49
+ <input type="checkbox" id="input-targeted-deep-scan">
50
+ <span>Targeted</span>
51
+ </label>
52
  <button id="btn-submit" class="btn-primary">Submit</button>
53
  </div>
54
+ <div id="deep-scan-filters" class="exif-filters deep-scan-filters hidden"></div>
55
  <div id="submit-status"></div>
56
  </section>
57
 
 
128
  <button id="viewer-next" class="viewer-nav" aria-label="Next result page">&rsaquo;</button>
129
  </div>
130
  </div>
131
+ <script src="app.js?v=20260803-1"></script>
132
  </body>
133
  </html>
frontend/style.css CHANGED
@@ -91,7 +91,7 @@ h1 {
91
  }
92
  .submit-grid {
93
  display: grid;
94
- grid-template-columns: minmax(14rem, 1fr) 6rem 8rem auto auto;
95
  gap: .75rem;
96
  align-items: end;
97
  }
@@ -309,6 +309,11 @@ input:focus, select:focus, textarea:focus { outline: none; border-color: var(--a
309
  gap: .4rem;
310
  max-width: 39rem;
311
  }
 
 
 
 
 
312
  .filter-btn, .filter-action {
313
  height: 32px;
314
  padding: 0 .65rem;
 
91
  }
92
  .submit-grid {
93
  display: grid;
94
+ grid-template-columns: minmax(14rem, 1fr) 6rem 8rem auto auto auto;
95
  gap: .75rem;
96
  align-items: end;
97
  }
 
309
  gap: .4rem;
310
  max-width: 39rem;
311
  }
312
+ .deep-scan-filters {
313
+ justify-content: start;
314
+ max-width: none;
315
+ margin-top: .75rem;
316
+ }
317
  .filter-btn, .filter-action {
318
  height: 32px;
319
  padding: 0 .65rem;