Add targeted deep scans
Browse filesFiles changed (4)
- backend/app.py+151-54
- frontend/app.js+22-4
- frontend/index.html+8-3
- frontend/style.css+6-1
240 unmodified lines241242243244245246126 unmodified lines373374375376377378379380381382383384385386387388389214 unmodified lines60460560660760860961061161261352 unmodified lines66666766866967067167226 unmodified lines69970070170270370470570670770870971071171271371471543 unmodified lines75976076176276376445 unmodified lines81081181281381481581681781881982082182286 unmodified lines90991091191291391491569 unmodified lines98598698798898999099138 unmodified lines1030103110321033103410352 unmodified lines1038103910401041104210431044104510461047104845 unmodified lines109410951096109710981099110040 unmodified lines11411142114311441145114611471 unmodified line1149115011511152115311541155500 unmodified lines16561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816897 unmodified lines169716981699170017011702170387 unmodified lines179117921793179417951796179711 unmodified lines180918101811181218131814181521 unmodified lines1837183818391840184118421843184418451846184750 unmodified lines189818991900190119021903190419051906190719088 unmodified lines1917191819191920192119221923192419251926338 unmodified lines2265226622672268226922702271227222732274227522762277227822792280228112 unmodified lines22942295229622972298229923002 unmodified lines23032304230523062307230823095 unmodified lines231523162317231823192320232123222323232428 unmodified lines23532354235523562357235823596 unmodified lines23662367236823692370237123723 unmodified lines237623772378237923802381238289 unmodified lines247224732474247524762477247824792480248124822483171 unmodified lines2655265626572658265926603 unmodified lines266426652666266726682669267056 unmodified lines2727272827292730273127322733240 unmodified lines"ALTER TABLE pi_searches ADD COLUMN found_exif INTEGER DEFAULT 0","ALTER TABLE pi_searches ADD COLUMN total_searched INTEGER DEFAULT 0","ALTER TABLE pi_searches ADD COLUMN deep_scan INTEGER DEFAULT 1","ALTER TABLE pi_scans ADD COLUMN deep_scanned INTEGER DEFAULT 0","ALTER TABLE pi_scans ADD COLUMN bookmark_count INTEGER","ALTER TABLE pi_scans ADD COLUMN view_count INTEGER",126 unmodified linesreturn f"https://www.pixiv.net/ajax/search/artworks/{encoded}?{params}"async def save_search(search_id, post_ids, deep_scan=True):if not post_ids:returnif task_canceled(search_id):raise TaskCanceled()stmt = {"sql": "INSERT OR REPLACE INTO pi_searches (id, post_ids, deep_scan) VALUES (?, ?, ?)","args": [{"type": "text", "value": search_id},{"type": "text", "value": json.dumps(post_ids)},{"type": "integer", "value": "1" if deep_scan else "0"},],}await turso_execute([stmt])214 unmodified linesresp = await turso_execute([{"sql": "WITH ids AS (""SELECT CAST(j.value AS TEXT) post_id FROM pi_searches p, json_each(p.post_ids) j ""WHERE p.id = ?"") SELECT COUNT(*), COUNT(s.post_id), COUNT(s.exif_type) ""FROM ids LEFT JOIN pi_scans s ON s.post_id = ids.post_id","args": [{"type": "text", "value": search_id}],}52 unmodified lines[{"sql": "WITH counts AS (""SELECT p.id, COUNT(s.post_id) scanned, COUNT(s.exif_type) found ""FROM pi_searches p JOIN json_each(p.post_ids) j ""LEFT JOIN pi_scans s ON s.post_id = CAST(j.value AS TEXT) "f"WHERE p.id IN ({marks}) GROUP BY p.id"26 unmodified linesreturn [cell_value(row, 0, "") for row in first_rows(resp) if cell_value(row, 0, "")]async def get_deep_scan_targets(search_id):resp = await turso_execute([{"sql": "WITH ids AS (""SELECT CAST(j.value AS TEXT) post_id, CAST(j.key AS INTEGER) pos ""FROM pi_searches p, json_each(p.post_ids) j WHERE p.id = ?"") SELECT ids.post_id, COALESCE(MAX(p.page), -1) + 1 start_page FROM ids ""JOIN pi_scans s ON s.post_id = ids.post_id ""LEFT JOIN pi_scan_pages p ON p.post_id = ids.post_id ""WHERE COALESCE(s.deep_scanned, 0) = 0 AND s.exif_type IS NOT NULL ""GROUP BY ids.post_id, ids.pos ORDER BY ids.pos","args": [{"type": "text", "value": search_id}],}43 unmodified linesreturn bool(rows and int(cell_value(rows[0], 0, "0")))async def get_refresh_search_ids():resp = await turso_execute([45 unmodified linesRESULT_BASE_SQL = ("WITH ids AS (""SELECT CAST(j.value AS TEXT) post_id, CAST(j.key AS INTEGER) + 1 scan_index ""FROM pi_searches p, json_each(p.post_ids) j WHERE p.id = ?""), tags AS (""SELECT p.post_id, p.exif_type FROM pi_scan_pages p JOIN ids ON ids.post_id = p.post_id ""WHERE p.exif_type IS NOT NULL UNION ""SELECT s.post_id, s.exif_type FROM pi_scans s JOIN ids ON ids.post_id = s.post_id ""WHERE s.exif_type IS NOT NULL) ")86 unmodified lines"sql": RESULT_BASE_SQL+ "SELECT ids.post_id, ids.scan_index, COALESCE(p.url, s.url) ""FROM ids JOIN pi_scans s ON s.post_id = ids.post_id ""LEFT JOIN pi_scan_pages p ON p.post_id = ids.post_id "f"WHERE ids.scan_index <= ? AND {where_sql} ""ORDER BY ids.scan_index, COALESCE(p.page, 0)","args": [69 unmodified lines{"sql": RESULT_BASE_SQL+ "SELECT COUNT(*), COUNT(s.post_id), ""(SELECT COUNT(DISTINCT post_id) FROM tags) ""FROM ids LEFT JOIN pi_scans s ON s.post_id = ids.post_id","args": [id_arg],},38 unmodified linesint(cell_value(row, 0, "0")): int(cell_value(row, 1, "0"))for row in type_rows}result_pages = await get_result_pages([cell_value(row, 0, "") for row in item_rows])items = []for row in item_rows:2 unmodified linesexif_type = cell_value(row, 3)bookmark_count = cell_value(row, 4)view_count = cell_value(row, 5)page_rows = result_pages.get(pid) or []exif_types = sorted({item["exif_type"] for item in page_rows if item["exif_type"]})if not exif_types and exif_type:exif_types = [int(exif_type)]enabled = set(allowed if allowed is not None else exif_types)visible_rows = [45 unmodified linesreturn f"{base26_time()}_{user_id}"async def pixiv_search_live(url, pages, mode, phpsessid, search_id, deep_scan=True):keywords = get_search_keywords(url)api_url = get_search_api_url(url, keywords)first_url = f"{api_url}&p=1"40 unmodified linesif done % 25 == 0:if task_canceled(search_id):raise TaskCanceled()await save_search(search_id, post_ids, deep_scan)finally:for task in tasks:if not task.done():1 unmodified lineawait asyncio.gather(*tasks, return_exceptions=True)if task_canceled(search_id):raise TaskCanceled()await save_search(search_id, post_ids, deep_scan)return post_ids, keywords, first_url500 unmodified linesreturn Nonedef scan_image_data(data):fallback = Noneexif_type = determine_exif_type(parse_image_metadata(data))if exif_type in FALLBACK_EXIF_TYPES:fallback = EXIF_TYPE_TO_CODE.get(exif_type)elif exif_type:return EXIF_TYPE_TO_CODE.get(exif_type)metadata, detected = parse_stealth_metadata(data)exif_type = determine_exif_type(metadata)if exif_type in FALLBACK_EXIF_TYPES:fallback = fallback or EXIF_TYPE_TO_CODE.get(exif_type)elif exif_type == "nai":return EXIF_TYPE_TO_CODE.get("nai_stealth")elif exif_type:return EXIF_TYPE_TO_CODE.get(exif_type)return EXIF_TYPE_TO_CODE.get("nai_stealth") if detected else fallbackasync def scan_page_result(post_id, url, session, img_sem):page = page_num_from_url(url)img_data = await fetch_image(session, url, img_sem, post_id, page)if not img_data:return Noneexif_type = await asyncio.to_thread(scan_image_data, img_data)return post_id, url, exif_typeasync def deep_scan_post(item, session, post_sem, img_sem):async with post_sem:try:post_id = item["post_id"]7 unmodified linesfor page, urls in enumerate(pages[start_page:], start_page):url = urls["original"]try:result = await scan_page_result(post_id, url, session, img_sem)except Exception:result = Noneif not result:87 unmodified linesreturn resultsasync def run_deep_scan(targets, phpsessid, task_id=None):cookies = {"PHPSESSID": phpsessid}completed = 0pending = []11 unmodified linesexcept StopIteration:breaktask = asyncio.create_task(deep_scan_post(item, session, POST_SCAN_SEM, FULL_IMAGE_SEM))tasks.add(task)created.add(task)21 unmodified linesif task_id and task_id in ACTIVE_TASKS:ACTIVE_TASKS[task_id]["done"] = completedif len(pending) >= 20:await save_deep_scan_results(pending)pending = []fill_tasks()if pending:await save_deep_scan_results(pending)finally:for task in created:if not task.done():50 unmodified linesawait turso_batch(stmts[i : i + 200])async def save_deep_scan_results(results):stmts = []stored = await get_result_pages([str(result[0]) for result in results])for post_id, pages, fresh, complete in results:for _, page, url, exif_type in fresh:short_url = url.replace(IMG_BASE, "", 1) if url else ""stmts.append({8 unmodified lines],})all_pages = [(post_id, row["page"], row["url"], row["exif_type"])for row in stored.get(str(post_id), ())] + pagescounts = {}for _, _, _, exif_type in all_pages:if not exif_type:338 unmodified linesawait finish_task(search_id)async def deep_scan_search(search_id, phpsessid):targets = await get_deep_scan_targets(search_id)if not targets:returnACTIVE_TASKS[search_id].update({"phase": "deep scanning", "total": len(targets), "done": 0, "raw_total": 0})await run_deep_scan(targets, phpsessid, task_id=search_id)async def bg_user_task(search_id, user_id, phpsessid, deep_scan=True):if not start_task(search_id, {"type": "user_search","phase": "searching",12 unmodified linesACTIVE_TASKS[search_id]["done"] = 1if not post_ids:returnawait save_search(search_id, post_ids, deep_scan)to_scan = await get_unscanned_post_ids(search_id)if to_scan:ACTIVE_TASKS[search_id].update({2 unmodified lines})await run_scan(to_scan, phpsessid, task_id=search_id, save_live=True)if deep_scan:await deep_scan_search(search_id, phpsessid)await cache_search_popularity(search_id)await update_search_stats(search_id)await patch_explorer_cache(search_id, front=True)5 unmodified linesawait finish_task(search_id)async def bg_user_batch_task(jobs, phpsessid, deep_scan=True):await asyncio.gather(*(bg_user_task(search_id, user_id, phpsessid, deep_scan)for search_id, user_id in jobs))28 unmodified linesasync def bg_search_and_scan_task(search_id, url, pages, mode, phpsessid, deep_scan=True):if not start_task(search_id, {"type": "search+scan",6 unmodified linescompleted = Falsetry:await pixiv_search_live(url, pages, mode, phpsessid, search_id, deep_scan)to_scan = await get_unscanned_post_ids(search_id)if to_scan:3 unmodified lines})await run_scan(to_scan, phpsessid, task_id=search_id, save_live=True)if deep_scan:await deep_scan_search(search_id, phpsessid)await cache_search_popularity(search_id)await update_search_stats(search_id)await patch_explorer_cache(search_id, front=True)89 unmodified linesmode: str = "ai"action: str = "search"deep_scan: bool = Trueclass UserSearchRequest(BaseModel):user_ids: listaction: str = "search"deep_scan: bool = Trueclass PostSearchRequest(BaseModel):171 unmodified linesreq.mode,phpsessid,req.deep_scan,)return {"id": search_id, "status": "started"}3 unmodified linesphpsessid = PHPSESSIDuser_ids = list(dict.fromkeys(int(u) for u in req.user_ids))jobs = [(user_search_id(uid), uid) for uid in user_ids]bg.add_task(bg_user_batch_task, jobs, phpsessid, req.deep_scan)return {"ids": [search_id for search_id, _ in jobs], "status": "started"}56 unmodified lines])to_scan = await get_unscanned_post_ids(req.search_id)deep_targets = await get_deep_scan_targets(req.search_id)popularity_ids = await get_missing_popularity_post_ids(req.search_id)if not to_scan and not deep_targets and not popularity_ids:return {"status": "already_scanned", "count": counts["raw_total"]}240 unmodified lines241242243244245246247126 unmodified lines374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403214 unmodified lines61861962062162262362462562652 unmodified lines67968068168268368468568668768868969069126 unmodified lines71871972072172272372472572672772872973073173273373473573673773873974043 unmodified lines78478578678778878979079179279379479579679779879980080180245 unmodified lines84884985085185285385485585685785885986086186286386 unmodified lines95095195295395495595695795869 unmodified lines102810291030103110321033103438 unmodified lines10731074107510761077107810792 unmodified lines1082108310841085108610871088108910901091109210931094109510961097109845 unmodified lines11441145114611471148114911501151115240 unmodified lines1193119411951196119711981199120012011 unmodified line1203120412051206120712081209500 unmodified lines1710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017517 unmodified lines17591760176117621763176417651766176787 unmodified lines185518561857185818591860186111 unmodified lines18731874187518761877187818791880188121 unmodified lines1903190419051906190719081909191019111912191350 unmodified lines19641965196619671968196919701971197219731974197519768 unmodified lines198519861987198819891990199119921993199419951996199719981999200020012002338 unmodified lines23412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236412 unmodified lines23772378237923802381238223832 unmodified lines23862387238823892390239123925 unmodified lines23982399240024012402240324042405240624072408240928 unmodified lines24382439244024412442244324446 unmodified lines24512452245324542455245624573 unmodified lines246124622463246424652466246789 unmodified lines25572558255925602561256225632564256525662567256825692570171 unmodified lines27422743274427452746274727483 unmodified lines275227532754275527562757275827592760276127622763276456 unmodified lines2821282228232824282528262827282828292830240 unmodified lines"ALTER TABLE pi_searches ADD COLUMN found_exif INTEGER DEFAULT 0","ALTER TABLE pi_searches ADD COLUMN total_searched INTEGER DEFAULT 0","ALTER TABLE pi_searches ADD COLUMN deep_scan INTEGER DEFAULT 1","ALTER TABLE pi_searches ADD COLUMN deep_scan_types TEXT DEFAULT '[]'","ALTER TABLE pi_scans ADD COLUMN deep_scanned INTEGER DEFAULT 0","ALTER TABLE pi_scans ADD COLUMN bookmark_count INTEGER","ALTER TABLE pi_scans ADD COLUMN view_count INTEGER",126 unmodified linesreturn f"https://www.pixiv.net/ajax/search/artworks/{encoded}?{params}"def exif_codes(values):return sorted({int(code)for code in values or []if str(code).isdigit() and int(code) in EXIF_CODE_TO_TYPE})async def save_search(search_id, post_ids, deep_scan=True, deep_scan_types=None):if not post_ids:returnif task_canceled(search_id):raise TaskCanceled()deep_scan_types = exif_codes(deep_scan_types) if deep_scan else []stmt = {"sql": "INSERT OR REPLACE INTO pi_searches ""(id, post_ids, deep_scan, deep_scan_types) VALUES (?, ?, ?, ?)","args": [{"type": "text", "value": search_id},{"type": "text", "value": json.dumps(post_ids)},{"type": "integer", "value": "1" if deep_scan else "0"},{"type": "text", "value": json.dumps(deep_scan_types or [])},],}await turso_execute([stmt])214 unmodified linesresp = await turso_execute([{"sql": RESULT_BASE_SQL+ "SELECT COUNT(*), COUNT(s.post_id), ""(SELECT COUNT(DISTINCT post_id) FROM tags) ""FROM ids LEFT JOIN pi_scans s ON s.post_id = ids.post_id","args": [{"type": "text", "value": search_id}],}52 unmodified lines[{"sql": "WITH counts AS (""SELECT p.id, COUNT(s.post_id) scanned, COUNT(CASE WHEN ""s.exif_type IS NOT NULL AND (COALESCE(p.deep_scan_types, '[]') = '[]' ""OR EXISTS (SELECT 1 FROM json_each(p.deep_scan_types) ""WHERE CAST(value AS INTEGER) = s.exif_type) OR EXISTS (""SELECT 1 FROM pi_scan_pages sp WHERE sp.post_id = s.post_id ""AND sp.exif_type IN (SELECT CAST(value AS INTEGER) ""FROM json_each(p.deep_scan_types)))) THEN 1 END) found ""FROM pi_searches p JOIN json_each(p.post_ids) j ""LEFT JOIN pi_scans s ON s.post_id = CAST(j.value AS TEXT) "f"WHERE p.id IN ({marks}) GROUP BY p.id"26 unmodified linesreturn [cell_value(row, 0, "") for row in first_rows(resp) if cell_value(row, 0, "")]async def get_deep_scan_targets(search_id, targeted=False):start_page = "0" if targeted else "COALESCE(MAX(p.page), -1) + 1"condition = ("s.exif_type IS NOT NULL"if targetedelse "COALESCE(s.deep_scanned, 0) = 0 AND s.exif_type IS NOT NULL")resp = await turso_execute([{"sql": "WITH ids AS (""SELECT CAST(j.value AS TEXT) post_id, CAST(j.key AS INTEGER) pos ""FROM pi_searches p, json_each(p.post_ids) j WHERE p.id = ?"f") SELECT ids.post_id, {start_page} start_page FROM ids ""JOIN pi_scans s ON s.post_id = ids.post_id ""LEFT JOIN pi_scan_pages p ON p.post_id = ids.post_id "f"WHERE {condition} ""GROUP BY ids.post_id, ids.pos ORDER BY ids.pos","args": [{"type": "text", "value": search_id}],}43 unmodified linesreturn bool(rows and int(cell_value(rows[0], 0, "0")))async def get_search_deep_scan_types(search_id):resp = await turso_execute([{"sql": "SELECT deep_scan_types FROM pi_searches WHERE id = ?","args": [{"type": "text", "value": search_id}],}])rows = first_rows(resp)return exif_codes(json.loads(cell_value(rows[0], 0, "[]"))) if rows else []async def get_refresh_search_ids():resp = await turso_execute([45 unmodified linesRESULT_BASE_SQL = ("WITH ids AS (""SELECT CAST(j.value AS TEXT) post_id, CAST(j.key AS INTEGER) + 1 scan_index, ""COALESCE(p.deep_scan_types, '[]') deep_scan_types ""FROM pi_searches p, json_each(p.post_ids) j WHERE p.id = ?""), tags AS (""SELECT p.post_id, p.exif_type FROM pi_scan_pages p JOIN ids ON ids.post_id = p.post_id ""WHERE p.exif_type IS NOT NULL AND (ids.deep_scan_types = '[]' OR EXISTS (""SELECT 1 FROM json_each(ids.deep_scan_types) WHERE CAST(value AS INTEGER) = p.exif_type)) UNION ""SELECT s.post_id, s.exif_type FROM pi_scans s JOIN ids ON ids.post_id = s.post_id ""WHERE s.exif_type IS NOT NULL AND (ids.deep_scan_types = '[]' OR EXISTS (""SELECT 1 FROM json_each(ids.deep_scan_types) WHERE CAST(value AS INTEGER) = s.exif_type))) ")86 unmodified lines"sql": RESULT_BASE_SQL+ "SELECT ids.post_id, ids.scan_index, COALESCE(p.url, s.url) ""FROM ids JOIN pi_scans s ON s.post_id = ids.post_id ""LEFT JOIN pi_scan_pages p ON p.post_id = ids.post_id AND (""ids.deep_scan_types = '[]' OR EXISTS (SELECT 1 FROM json_each(ids.deep_scan_types) ""WHERE CAST(value AS INTEGER) = p.exif_type)) "f"WHERE ids.scan_index <= ? AND {where_sql} ""ORDER BY ids.scan_index, COALESCE(p.page, 0)","args": [69 unmodified lines{"sql": RESULT_BASE_SQL+ "SELECT COUNT(*), COUNT(s.post_id), ""(SELECT COUNT(DISTINCT post_id) FROM tags), MAX(ids.deep_scan_types) ""FROM ids LEFT JOIN pi_scans s ON s.post_id = ids.post_id","args": [id_arg],},38 unmodified linesint(cell_value(row, 0, "0")): int(cell_value(row, 1, "0"))for row in type_rows}deep_scan_types = set(json.loads(cell_value(count_rows[0], 3, "[]")))result_pages = await get_result_pages([cell_value(row, 0, "") for row in item_rows])items = []for row in item_rows:2 unmodified linesexif_type = cell_value(row, 3)bookmark_count = cell_value(row, 4)view_count = cell_value(row, 5)page_rows = [itemfor item in result_pages.get(pid) or []if not deep_scan_types or item["exif_type"] in deep_scan_types]exif_types = sorted({item["exif_type"] for item in page_rows if item["exif_type"]})if not exif_types and exif_type and (not deep_scan_types or int(exif_type) in deep_scan_types):exif_types = [int(exif_type)]enabled = set(allowed if allowed is not None else exif_types)visible_rows = [45 unmodified linesreturn f"{base26_time()}_{user_id}"async def pixiv_search_live(url, pages, mode, phpsessid, search_id, deep_scan=True, deep_scan_types=None):keywords = get_search_keywords(url)api_url = get_search_api_url(url, keywords)first_url = f"{api_url}&p=1"40 unmodified linesif done % 25 == 0:if task_canceled(search_id):raise TaskCanceled()await save_search(search_id, post_ids, deep_scan, deep_scan_types)finally:for task in tasks:if not task.done():1 unmodified lineawait asyncio.gather(*tasks, return_exceptions=True)if task_canceled(search_id):raise TaskCanceled()await save_search(search_id, post_ids, deep_scan, deep_scan_types)return post_ids, keywords, first_url500 unmodified linesreturn Nonedef scan_image_data(data, allowed=None):allowed = set(allowed) if allowed else Nonefallback = Noneexif_type = determine_exif_type(parse_image_metadata(data))code = EXIF_TYPE_TO_CODE.get(exif_type)if exif_type in FALLBACK_EXIF_TYPES:if allowed is None or code in allowed:fallback = codeelif code and (allowed is None or code in allowed):return codemetadata, detected = parse_stealth_metadata(data)exif_type = determine_exif_type(metadata)code = EXIF_TYPE_TO_CODE.get(exif_type)if exif_type in FALLBACK_EXIF_TYPES:if allowed is None or code in allowed:fallback = fallback or codeelif exif_type == "nai":code = EXIF_TYPE_TO_CODE.get("nai_stealth")if allowed is None or code in allowed:return codeelif code and (allowed is None or code in allowed):return codecode = EXIF_TYPE_TO_CODE.get("nai_stealth")return code if detected and (allowed is None or code in allowed) else fallbackasync def scan_page_result(post_id, url, session, img_sem, allowed=None):page = page_num_from_url(url)img_data = await fetch_image(session, url, img_sem, post_id, page)if not img_data:return Noneexif_type = await asyncio.to_thread(scan_image_data, img_data, allowed)return post_id, url, exif_typeasync def deep_scan_post(item, session, post_sem, img_sem, allowed=None):async with post_sem:try:post_id = item["post_id"]7 unmodified linesfor page, urls in enumerate(pages[start_page:], start_page):url = urls["original"]try:result = await scan_page_result(post_id, url, session, img_sem, allowed)except Exception:result = Noneif not result:87 unmodified linesreturn resultsasync def run_deep_scan(targets, phpsessid, task_id=None, allowed=None):cookies = {"PHPSESSID": phpsessid}completed = 0pending = []11 unmodified linesexcept StopIteration:breaktask = asyncio.create_task(deep_scan_post(item, session, POST_SCAN_SEM, FULL_IMAGE_SEM, allowed))tasks.add(task)created.add(task)21 unmodified linesif task_id and task_id in ACTIVE_TASKS:ACTIVE_TASKS[task_id]["done"] = completedif len(pending) >= 20:await save_deep_scan_results(pending, bool(allowed))pending = []fill_tasks()if pending:await save_deep_scan_results(pending, bool(allowed))finally:for task in created:if not task.done():50 unmodified linesawait turso_batch(stmts[i : i + 200])async def save_deep_scan_results(results, preserve_empty=False):stmts = []stored = await get_result_pages([str(result[0]) for result in results])for post_id, pages, fresh, complete in results:for _, page, url, exif_type in fresh:if preserve_empty and not exif_type:continueshort_url = url.replace(IMG_BASE, "", 1) if url else ""stmts.append({8 unmodified lines],})page_map = {row["page"]: (post_id, row["page"], row["url"], row["exif_type"])for row in stored.get(str(post_id), ())}page_map.update({row[1]: rowfor row in pagesif row[3] or not preserve_empty})all_pages = list(page_map.values())counts = {}for _, _, _, exif_type in all_pages:if not exif_type:338 unmodified linesawait finish_task(search_id)async def deep_scan_search(search_id, phpsessid, deep_scan_types=None):allowed = exif_codes(deep_scan_types)if deep_scan_types is None:allowed = await get_search_deep_scan_types(search_id)targets = await get_deep_scan_targets(search_id, bool(allowed))if not targets:returnACTIVE_TASKS[search_id].update({"phase": "deep scanning", "total": len(targets), "done": 0, "raw_total": 0})await run_deep_scan(targets, phpsessid, task_id=search_id, allowed=allowed or None)async def bg_user_task(search_id, user_id, phpsessid, deep_scan=True, deep_scan_types=None):if not start_task(search_id, {"type": "user_search","phase": "searching",12 unmodified linesACTIVE_TASKS[search_id]["done"] = 1if not post_ids:returnawait save_search(search_id, post_ids, deep_scan, deep_scan_types)to_scan = await get_unscanned_post_ids(search_id)if to_scan:ACTIVE_TASKS[search_id].update({2 unmodified lines})await run_scan(to_scan, phpsessid, task_id=search_id, save_live=True)if deep_scan:await deep_scan_search(search_id, phpsessid, deep_scan_types)await cache_search_popularity(search_id)await update_search_stats(search_id)await patch_explorer_cache(search_id, front=True)5 unmodified linesawait finish_task(search_id)async def bg_user_batch_task(jobs, phpsessid, deep_scan=True, deep_scan_types=None):await asyncio.gather(*(bg_user_task(search_id, user_id, phpsessid, deep_scan, deep_scan_types)for search_id, user_id in jobs))28 unmodified linesasync def bg_search_and_scan_task(search_id, url, pages, mode, phpsessid, deep_scan=True, deep_scan_types=None):if not start_task(search_id, {"type": "search+scan",6 unmodified linescompleted = Falsetry:await pixiv_search_live(url, pages, mode, phpsessid, search_id, deep_scan, deep_scan_types)to_scan = await get_unscanned_post_ids(search_id)if to_scan:3 unmodified lines})await run_scan(to_scan, phpsessid, task_id=search_id, save_live=True)if deep_scan:await deep_scan_search(search_id, phpsessid, deep_scan_types)await cache_search_popularity(search_id)await update_search_stats(search_id)await patch_explorer_cache(search_id, front=True)89 unmodified linesmode: str = "ai"action: str = "search"deep_scan: bool = Truedeep_scan_types: list = []class UserSearchRequest(BaseModel):user_ids: listaction: str = "search"deep_scan: bool = Truedeep_scan_types: list = []class PostSearchRequest(BaseModel):171 unmodified linesreq.mode,phpsessid,req.deep_scan,req.deep_scan_types,)return {"id": search_id, "status": "started"}3 unmodified linesphpsessid = PHPSESSIDuser_ids = list(dict.fromkeys(int(u) for u in req.user_ids))jobs = [(user_search_id(uid), uid) for uid in user_ids]bg.add_task(bg_user_batch_task,jobs,phpsessid,req.deep_scan,req.deep_scan_types,)return {"ids": [search_id for search_id, _ in jobs], "status": "started"}56 unmodified lines])to_scan = await get_unscanned_post_ids(req.search_id)deep_scan_types = await get_search_deep_scan_types(req.search_id)deep_targets = await get_deep_scan_targets(req.search_id, bool(deep_scan_types))popularity_ids = await get_missing_popularity_post_ids(req.search_id)if not to_scan and not deep_targets and not popularity_ids:return {"status": "already_scanned", "count": counts["raw_total"]}
41 unmodified lines42434445464731 unmodified lines7980818283848513 unmodified lines99100101102103104105106107108109110111281 unmodified lines393394395396397398399400479 unmodified lines88088188288388488541 unmodified lineslet postSearchCardCache = new Map()let exifCountsCache = new Map()$$(".tab").forEach(tab => {tab.addEventListener("click", () => {31 unmodified linesconst pages = parseInt($("#input-pages").value) || 30const mode = $("#input-mode").valueconst deepScan = $("#input-deep-scan").checkedconst status = $("#submit-status")status.textContent = "Submitting..."status.className = ""13 unmodified linesresp = await fetch("/api/submit_users", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ user_ids: userIds, deep_scan: deepScan })})} else {resp = await fetch("/api/submit", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ url, pages, mode, deep_scan: deepScan })})}const data = await resp.json()281 unmodified lines.map(el => Number(el.dataset.code))}function renderCategoryFilters(root) {const buttons = FILTER_CODES.map(code => {return `<button class="filter-btn active" data-code="${code}">${esc(CATEGORY_NAMES[code])}</button>`}).join("")$(root).innerHTML = `${buttons}479 unmodified lines}window.addEventListener("hashchange", route)renderCategoryFilters("#reclass-filters")if (!location.hash) location.hash = "#/submit"route()41 unmodified lines42434445464748495051525354555631 unmodified lines88899091929394959697989910010113 unmodified lines115116117118119120121122123124125126127281 unmodified lines409410411412413414415416479 unmodified lines89689789889990090190290341 unmodified lineslet postSearchCardCache = new Map()let exifCountsCache = new Map()function syncDeepScanTargets() {const enabled = $("#input-deep-scan").checkedconst targeted = $("#input-targeted-deep-scan")targeted.disabled = !enabled$("#deep-scan-filters").classList.toggle("hidden", !enabled || !targeted.checked)}$("#input-deep-scan").addEventListener("change", syncDeepScanTargets)$("#input-targeted-deep-scan").addEventListener("change", syncDeepScanTargets)$$(".tab").forEach(tab => {tab.addEventListener("click", () => {31 unmodified linesconst pages = parseInt($("#input-pages").value) || 30const mode = $("#input-mode").valueconst deepScan = $("#input-deep-scan").checkedconst targeted = deepScan && $("#input-targeted-deep-scan").checkedconst deepScanTypes = targeted ? selectedCategoryTypes("#deep-scan-filters") : []const status = $("#submit-status")if (targeted && !deepScanTypes.length) {status.textContent = "Select at least one deep scan category"status.className = "status-err"return}status.textContent = "Submitting..."status.className = ""13 unmodified linesresp = await fetch("/api/submit_users", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ user_ids: userIds, deep_scan: deepScan, deep_scan_types: deepScanTypes })})} else {resp = await fetch("/api/submit", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ url, pages, mode, deep_scan: deepScan, deep_scan_types: deepScanTypes })})}const data = await resp.json()281 unmodified lines.map(el => Number(el.dataset.code))}function renderCategoryFilters(root, codes = FILTER_CODES) {const buttons = codes.map(code => {return `<button class="filter-btn active" data-code="${code}">${esc(CATEGORY_NAMES[code])}</button>`}).join("")$(root).innerHTML = `${buttons}479 unmodified lines}window.addEventListener("hashchange", route)renderCategoryFilters("#deep-scan-filters", EXIF_CODES)renderCategoryFilters("#reclass-filters")syncDeepScanTargets()if (!location.hash) location.hash = "#/submit"route()
2 unmodified lines3456789101133 unmodified lines454647484950515270 unmodified lines1231241251261271282 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="icon" href="data:;base64,="><title>Pixif2</title><link rel="stylesheet" href="style.css?v=20260801-1"></head><body><div class="topbar">33 unmodified lines<input type="checkbox" id="input-deep-scan" checked><span>Deep scan</span></label><button id="btn-submit" class="btn-primary">Submit</button></div><div id="submit-status"></div></section>70 unmodified lines<button id="viewer-next" class="viewer-nav" aria-label="Next result page">›</button></div></div><script src="app.js?v=20260801-1"></script></body></html>2 unmodified lines3456789101133 unmodified lines4546474849505152535455565770 unmodified lines1281291301311321332 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="icon" href="data:,"><title>Pixif2</title><link rel="stylesheet" href="style.css?v=20260803-1"></head><body><div class="topbar">33 unmodified lines<input type="checkbox" id="input-deep-scan" checked><span>Deep scan</span></label><label class="check-field"><input type="checkbox" id="input-targeted-deep-scan"><span>Targeted</span></label><button id="btn-submit" class="btn-primary">Submit</button></div><div id="deep-scan-filters" class="exif-filters deep-scan-filters hidden"></div><div id="submit-status"></div></section>70 unmodified lines<button id="viewer-next" class="viewer-nav" aria-label="Next result page">›</button></div></div><script src="app.js?v=20260803-1"></script></body></html>
90 unmodified lines91929394959697211 unmodified lines30931031131231331490 unmodified lines}.submit-grid {display: grid;grid-template-columns: minmax(14rem, 1fr) 6rem 8rem auto auto;gap: .75rem;align-items: end;}211 unmodified linesgap: .4rem;max-width: 39rem;}.filter-btn, .filter-action {height: 32px;padding: 0 .65rem;90 unmodified lines91929394959697211 unmodified lines30931031131231331431531631731831990 unmodified lines}.submit-grid {display: grid;grid-template-columns: minmax(14rem, 1fr) 6rem 8rem auto auto auto;gap: .75rem;align-items: end;}211 unmodified linesgap: .4rem;max-width: 39rem;}.deep-scan-filters {justify-content: start;max-width: none;margin-top: .75rem;}.filter-btn, .filter-action {height: 32px;padding: 0 .65rem;
backend/app.py+151-54
frontend/app.js+22-4
frontend/index.html+8-3
frontend/style.css+6-1