Peach: Local-first video metadata scraper and media manager.
chore(scripts): UA 与按主机限速收口到 peach.scripting
longmeidao80b04d28643d
diff --git a/scripts/audit_performer_portraits.py b/scripts/audit_performer_portraits.pyindex 31c345d7d..648b37d7f 100644--- a/scripts/audit_performer_portraits.py+++ b/scripts/audit_performer_portraits.py@@ -61,15 +61,12 @@ from peach.catalog_rules import is_jav_codefrom peach.config import DATABASE_PATH, GENERATED_DIRfrom peach.http import HttpRequest, HttpTransport, HttpxTransportfrom peach.review_csv import read_rows, write_rows+from peach.scripting import USER_AGENT, HostLimiterGFRIENDS_RAW = "https://raw.githubusercontent.com/gfriends/gfriends/master/"# 目录名首字符即质量档位;0 最优,z(DMM 官方小图)最次。QUALITY_ORDER = "0123456789abcdefghijklmnopqrstuvwxyz"AVATAR_FILE_RE = re.compile(r"^performer-(\d+)\.img$")-BROWSER_UA = (- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "- "(KHTML, like Gecko) Chrome/125.0 Safari/537.36"-)_LIMITER: "HostLimiter | None" = NoneFIELDS = (@@ -269,34 +266,6 @@ def quality_key(category: str, filename: str) -> tuple[int, str, str]:return (rank if rank >= 0 else len(QUALITY_ORDER), category, filename)-class HostLimiter:- """按主机分别限速:每个主机一把锁、一个下次可发时刻。"""-- def __init__(self, intervals: dict[str, float]):- self._intervals = intervals- self._locks = {host: threading.Lock() for host in intervals}- self._next: dict[str, float] = {host: 0.0 for host in intervals}-- def _key(self, url: str) -> str | None:- hostname = urllib.parse.urlsplit(url).hostname or ""- for host in self._intervals:- if host in hostname:- return host- return None-- def wait(self, url: str) -> None:- key = self._key(url)- if key is None:- return- with self._locks[key]:- now = time.monotonic()- delay = self._next[key] - now- if delay > 0:- time.sleep(delay)- now = time.monotonic()- self._next[key] = now + self._intervals[key]--def fetch(transport: HttpTransport, url: str, accept: str,timeout: float = 30, max_bytes: int = 4 * 1024 * 1024):"""联网取一次;任何网络层异常都降级为 None,不让单条 TLS 抖动打断整批。"""@@ -305,7 +274,7 @@ def fetch(transport: HttpTransport, url: str, accept: str,active.wait(url)try:return transport(- HttpRequest("GET", url, {"Accept": accept, "User-Agent": BROWSER_UA}),+ HttpRequest("GET", url, {"Accept": accept, "User-Agent": USER_AGENT}),timeout, max_bytes)except Exception:return Nonediff --git a/scripts/fetch_fc2_metadata.py b/scripts/fetch_fc2_metadata.pyindex dc22b67f2..e1a7b95e6 100644--- a/scripts/fetch_fc2_metadata.py+++ b/scripts/fetch_fc2_metadata.py@@ -53,10 +53,9 @@ if str(SRC_DIR) not in sys.path:from peach.catalog_rules import normalise_code_keyfrom peach.review_csv import read_rows, write_rows+from peach.scripting import USER_AGENTfrom peach.config import DATABASE_PATH, GENERATED_DIR-UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "- "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")ARTICLE_URL = "https://fc2cmadb.com/articles/{video_id}"FC2_COVER_WIDTH = 1200#: Inertia 把整个 props 树放在这个 script 标签里,正文 HTML 反而是空壳。@@ -469,7 +468,7 @@ def run(args: argparse.Namespace) -> int:args.raw.parent.mkdir(parents=True, exist_ok=True)raw_log = args.raw.open("w", encoding="utf-8")print(f"待抓 {len(todo)} 个 FC2 作品", flush=True)- with httpx.Client(cookies=jar, headers={"User-Agent": UA},+ with httpx.Client(cookies=jar, headers={"User-Agent": USER_AGENT},follow_redirects=True) as client:for index, (code, video_id) in enumerate(todo, 1):try:diff --git a/scripts/fetch_jav_covers.py b/scripts/fetch_jav_covers.pyindex ea3800909..b8960b3e6 100644--- a/scripts/fetch_jav_covers.py+++ b/scripts/fetch_jav_covers.py@@ -58,14 +58,13 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.review_csv import ENCODING, read_rows, write_rows+from peach.scripting import USER_AGENTfrom peach.config import COVER_DIR, DATABASE_PATH, GENERATED_DIR, SOURCES_DIRfrom peach.http import HttpRequest, HttpTransport, HttpxTransportfrom peach.jobs import DiskGuard, JobPolicyErrorfrom peach.platform import system_volumefrom peach.catalog_rules import is_jav_code, normalise_code_key-UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "- "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")AWS_LEGACY_DIGITAL = ("https://awsimgsrc.dmm.co.jp/pics_dig/digital/video/{cid}/{cid}pl.jpg")@@ -168,7 +167,7 @@ class _MGSDetailParser(HTMLParser):def _fetch(transport: HttpTransport, url: str, *, referer: str,limit: int, ranged: bool = False,extra_headers: dict[str, str] | None = None) -> bytes:- headers = {"User-Agent": UA, "Referer": referer,+ headers = {"User-Agent": USER_AGENT, "Referer": referer,"Accept-Language": "ja,en;q=0.9"}if extra_headers:headers.update(extra_headers)diff --git a/scripts/fetch_studio_avatar_candidates.py b/scripts/fetch_studio_avatar_candidates.pyindex 67a1332b2..db5f43d1e 100644--- a/scripts/fetch_studio_avatar_candidates.py+++ b/scripts/fetch_studio_avatar_candidates.py@@ -35,9 +35,9 @@ from peach.logo_provider import ( # noqa: E402from peach.config import GENERATED_DIR # noqa: E402from peach.social_links import twimg_tiers # noqa: E402from peach.review_csv import read_rows, write_rows+from peach.scripting import USER_AGENTRESOLVER = "https://unavatar.io/{platform}/{handle}?json"-USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Peach/0.6"FIELDS = ("studio", "handle", "platform", "resolver_url", "resolved_url", "width","height", "aspect", "verdict", "saved", "accepted", "confirmation",diff --git a/scripts/find_studio_socials.py b/scripts/find_studio_socials.pyindex 52dd98c09..4a1f69bdf 100644--- a/scripts/find_studio_socials.py+++ b/scripts/find_studio_socials.py@@ -20,8 +20,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from peach.http import HttpRequest, HttpxTransport # noqa: E402from peach.review_csv import read_rows, write_rows+from peach.scripting import USER_AGENT-USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Peach/0.6"SOCIAL = re.compile(r'https?://(?:www\.)?(twitter\.com|x\.com)/([A-Za-z0-9_]{2,30})', re.I)# 平台自身的功能路径,不是账号。NOT_A_HANDLE = {"share", "intent", "home", "hashtag", "explore", "search", "i", "privacy", "tos"}diff --git a/scripts/harvest_performer_links.py b/scripts/harvest_performer_links.pyindex 767630a7e..5f5f1ba16 100644--- a/scripts/harvest_performer_links.py+++ b/scripts/harvest_performer_links.py@@ -30,12 +30,11 @@ from peach.entities import name_chain # noqa: E402,F401 测试从本模块取from peach.http import HttpRequest, HttpxTransport # noqa: E402from peach.jobs import job_main # noqa: E402from peach.review_csv import write_rows # noqa: E402+from peach.scripting import USER_AGENT # noqa: E402# 平台判据与选人规则和目录型采集器共用,定义在 peach.social_links;这里只保留 minnano-av 的解析。from peach.social_links import classify, load_performers, under # noqa: E402,F401SEARCH = "https://www.minnano-av.com/search_result.php?search_scope=actress&search_word="-USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "- "(KHTML, like Gecko) Chrome/128.0 Safari/537.36")ACTRESS_PAGE = re.compile(r"/actress(\d+)\.html")FIELD = re.compile(r"<td[^>]*>\s*<span[^>]*>(.*?)</span>(.*?)</td>", re.S)HREF = re.compile(r'href=["\']([^"\']+)["\']')diff --git a/scripts/harvest_social_avatars.py b/scripts/harvest_social_avatars.pyindex ee893fe35..7fc159e65 100644--- a/scripts/harvest_social_avatars.py+++ b/scripts/harvest_social_avatars.py@@ -43,7 +43,6 @@ import osimport reimport sqlite3import sys-import threadingimport timeimport urllib.parseimport uuid@@ -60,10 +59,11 @@ from peach.avatar_provider import ( # noqa: E402from peach.config import DATABASE_PATH, GENERATED_DIR, STATE_DIR # noqa: E402from peach.http import HttpRequest, HttpTransport, HttpxTransport # noqa: E402from peach.review_csv import read_rows, write_rows # noqa: E402+from peach.scripting import ( # noqa: E402+ USER_AGENT, HostLimiter, host_under, hostname_of,+)from peach.social_links import twimg_tiers # noqa: E402-BROWSER_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "- "(KHTML, like Gecko) Chrome/125.0 Safari/537.36")X_HOSTS = ("x.com", "twitter.com", "mobile.twitter.com")AGGREGATOR_HOSTS = ("lit.link", "linktr.ee", "allmylinks.com", "twpf.jp")@@ -133,44 +133,12 @@ CANDIDATE_FIELDS = ()-def under(host: str, domains: tuple[str, ...]) -> bool:- """host 是否就是这些域名之一或其子域;后缀匹配必须落在点边界上。"""- return any(host == domain or host.endswith("." + domain) for domain in domains)---def hostname(url: str) -> str:- return (urllib.parse.urlsplit(url).hostname or "").casefold().removeprefix("www.")---class HostLimiter:- """按主机限速。键匹配必须落在点边界上——`"x.com" in "netflix.com"` 是真的,- 子串匹配会把无关主机按 X 的节拍限速;方向上只是慢,但错了就是错了。"""-- def __init__(self, intervals: dict[str, float]):- self._intervals = intervals- self._locks = {host: threading.Lock() for host in intervals}- self._next = {host: 0.0 for host in intervals}-- def wait(self, url: str) -> None:- host = hostname(url)- key = next((h for h in self._intervals if under(host, (h,))), None)- if key is None:- return- with self._locks[key]:- now = time.monotonic()- delay = self._next[key] - now- if delay > 0:- time.sleep(delay)- now = time.monotonic()- self._next[key] = now + self._intervals[key]--def fetch(http: HttpTransport, url: str, timeout: float, limiter: HostLimiter,accept: str = "text/html,application/xhtml+xml,*/*;q=0.8"):"""取一次;网络层异常降级为 None,单个来源的 TLS 抖动不拖垮整批。"""limiter.wait(url)try:- return http(HttpRequest("GET", url, {"User-Agent": BROWSER_UA, "Accept": accept}),+ return http(HttpRequest("GET", url, {"User-Agent": USER_AGENT, "Accept": accept}),timeout, 16 * 1024 * 1024)except Exception:return None@@ -220,20 +188,20 @@ def identity_match(names: list[str], text: str) -> str:def classify(url: str) -> tuple[str, str]:"""(link_kind, label)。label 要让人在资料页上不点就知道去的是什么。"""- host = hostname(url)- if under(host, X_HOSTS):+ host = hostname_of(url)+ if host_under(host, X_HOSTS):handle = urllib.parse.urlsplit(url).path.strip("/").split("?")[0]return "social", (f"X @{handle}" if handle and HANDLE.match(handle) else "X")for hosts, platform in SOCIAL_LABELS.items():- if under(host, hosts):+ if host_under(host, hosts):handle = urllib.parse.urlsplit(url).path.strip("/").lstrip("@")return "social", (f"{platform} @{handle}" if handle else platform)- if under(host, AGGREGATOR_HOSTS):+ if host_under(host, AGGREGATOR_HOSTS):return "social", f"链接集({host})"- if under(host, BLOG_HOSTS):+ if host_under(host, BLOG_HOSTS):return "social", "博客"for hosts, label in CATALOG_LABELS.items():- if under(host, hosts):+ if host_under(host, hosts):return "catalog", labelreturn "official", "官方网站"@@ -245,19 +213,19 @@ def profile_shaped(url: str) -> bool:平台而不是这个人。X 域内只认「单段 handle 形」路径——X 的页脚与帮助页全是单段或两段真锚点,靠枚举保留字加单段约束一起拦;youtu.be 没有个人主页形态。"""- host = hostname(url)+ host = hostname_of(url)path = urllib.parse.urlsplit(url).path- if under(host, X_HOSTS):+ if host_under(host, X_HOSTS):segments = path.strip("/").split("/")return (len(segments) == 1 and HANDLE.match(segments[0])and segments[0].lower() not in X_RESERVED)- if under(host, ("instagram.com",)):+ if host_under(host, ("instagram.com",)):return not re.search(r"^/(p|reel|reels|explore|stories)(\b|/)", path)- if under(host, ("youtube.com",)):+ if host_under(host, ("youtube.com",)):return path.startswith(("/@", "/channel/", "/c/", "/user/"))- if under(host, ("youtu.be",)):+ if host_under(host, ("youtu.be",)):return False- if under(host, ("tiktok.com",)):+ if host_under(host, ("tiktok.com",)):return path.startswith("/@")return True@@ -317,11 +285,11 @@ def parse_link_page(url: str, body: str) -> dict:og = OG_IMAGE.search(body)if og:icon = html_mod.unescape(og.group(1))- self_host = hostname(url)+ self_host = hostname_of(url)anchors: list[str] = []for href in ANCHOR_HREF.findall(body):href = html_mod.unescape(href).strip()- if href.startswith("http") and hostname(href) != self_host:+ if href.startswith("http") and hostname_of(href) != self_host:anchors.append(href)return {"title": title, "icon": icon, "anchors": anchors}@@ -465,7 +433,7 @@ def harvest_entity(record: dict, http: HttpTransport, limiter: HostLimiter,# 集链页:X 简介里给的入口。闸门用集链页自己的标题/正文再验一遍——# 就算 X 一跳过了,聚合页也可能被别人注册同 handle 抢走。aggregator_urls = [link["url"] for link in links- if under(hostname(link["url"]), AGGREGATOR_HOSTS)]+ if host_under(hostname_of(link["url"]), AGGREGATOR_HOSTS)]for agg_url in list(dict.fromkeys(u.rstrip("/") for u in aggregator_urls))[:3]:response = fetch(http, agg_url, timeout, limiter)if response is None or response.status != 200:@@ -484,9 +452,9 @@ def harvest_entity(record: dict, http: HttpTransport, limiter: HostLimiter,if kind == "official":# 集链页上的不明外链不进 official——那是给事务所这类已核实来源的;# 用主机名当标签让人一眼看清它其实是什么。- kind, label = "social", hostname(href)+ kind, label = "social", hostname_of(href)links.append({"link_kind": kind, "label": label, "url": href,- "evidence": (f"{hostname(agg_url)} 页面锚点"+ "evidence": (f"{hostname_of(agg_url)} 页面锚点"+ (f",标题「{page['title'][:40]}」"if page["title"] else "")),"gated": bool(agg_identity)})@@ -498,12 +466,12 @@ def harvest_entity(record: dict, http: HttpTransport, limiter: HostLimiter,candidates.append({"provider": "social-web", "source_kind": "official_profile","source_url": page["icon"],- "external_id": hostname(agg_url),+ "external_id": hostname_of(agg_url),"width": inspected.width, "height": inspected.height,"mime_type": inspected.mime_type, "sha256": inspected.sha256,"object_path": object_path,"matched": agg_identity, "name_source": "social_identity_gate",- "evidence": f"{hostname(agg_url)} 头像 "+ "evidence": f"{hostname_of(agg_url)} 头像 "f"{inspected.width}×{inspected.height}",})diff --git a/scripts/harvest_studio_sites.py b/scripts/harvest_studio_sites.pyindex f3feb9386..3e6354563 100644--- a/scripts/harvest_studio_sites.py+++ b/scripts/harvest_studio_sites.py@@ -29,9 +29,8 @@ from peach.config import STATE_DIR # noqa: E402from peach.http import HttpRequest, HttpxTransport # noqa: E402from peach.jobs import job_main # noqa: E402from peach.review_csv import read_rows, write_rows # noqa: E402+from peach.scripting import USER_AGENT # noqa: E402-USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "- "(KHTML, like Gecko) Chrome/128.0 Safari/537.36")TITLE = re.compile(r"<title[^>]*>(.*?)</title>", re.S | re.I)# 抢注页与停放页的自述。它们同样会 200,也同样会在标题里回显域名,# 只有这些词能把它们和真站区分开。diff --git a/scripts/import_stash_entities.py b/scripts/import_stash_entities.pyindex caf45dfb0..00d9fd661 100644--- a/scripts/import_stash_entities.py+++ b/scripts/import_stash_entities.py@@ -27,6 +27,7 @@ if str(SRC_DIR) not in sys.path:from peach.config import DATABASE_PATH, GENERATED_DIRfrom peach.http import HttpRequest, HttpTransport, HttpxTransportfrom peach.migrations import sqlite_backup+from peach.scripting import host_underfrom peach.stash import StashClient@@ -42,18 +43,9 @@ def normalized(value: str) -> str:SOCIAL_HOSTS = ("x.com", "twitter.com", "instagram.com", "youtube.com", "tiktok.com")-def under(host: str, domains: tuple[str, ...]) -> bool:- """host 是否就是这些域名之一或它们的子域。-- 直接用 `endswith` 会把 `notx.com` 判成 x.com——后缀匹配必须落在点边界上,- 否则任何人注册一个以平台名结尾的域名就能让链接在资料页上显示成官方社交账号。- """- return any(host == domain or host.endswith("." + domain) for domain in domains)--def link_kind(url: str) -> str:host = (urlsplit(url).hostname or "").casefold()- if under(host, SOCIAL_HOSTS):+ if host_under(host, SOCIAL_HOSTS):return "social"return "catalog"diff --git a/scripts/install_entity_links.py b/scripts/install_entity_links.pyindex e0f567cd3..6e7ca1e51 100644--- a/scripts/install_entity_links.py+++ b/scripts/install_entity_links.py@@ -26,9 +26,8 @@ import httpxsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from peach.review_csv import read_rows # noqa: E402+from peach.scripting import USER_AGENT # noqa: E402-USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "- "(KHTML, like Gecko) Chrome/128.0 Safari/537.36")LINK_KINDS = {"official", "social", "catalog", "source_reference"}FIELDS = ("entity_id", "kind", "name", "link_kind", "label", "url", "evidence")diff --git a/scripts/match_babepedia_creators.py b/scripts/match_babepedia_creators.pyindex e1407ff5f..694d0b40b 100644--- a/scripts/match_babepedia_creators.py+++ b/scripts/match_babepedia_creators.py@@ -50,10 +50,9 @@ if str(SRC_DIR) not in sys.path:from peach.config import DATABASE_PATH, GENERATED_DIRfrom peach.http import HttpRequest, HttpTransport, HttpxTransportfrom peach.review_csv import read_rows, write_rows+from peach.scripting import USER_AGENTBASE = "https://www.babepedia.com/babe/"-UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "- "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")#: 档案页标题。`nude` 可有可无——两种写法都是真实档案。PROFILE_TITLE = re.compile(@@ -117,7 +116,7 @@ def fetch_title(transport: HttpTransport, query: str, timeout: int = 30) -> str"""返回档案名;查无此人返回 None;被限流抛 RateLimited。"""url = BASE + urllib.parse.quote(query)response = transport(- HttpRequest("GET", url, {"User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"}),+ HttpRequest("GET", url, {"User-Agent": USER_AGENT, "Accept-Language": "en-US,en;q=0.9"}),timeout, 4 * 1024 * 1024,)body = response.body.decode("utf-8", "ignore")diff --git a/scripts/rediscover_entity_links.py b/scripts/rediscover_entity_links.pyindex bc4e78c27..ce5b701f7 100644--- a/scripts/rediscover_entity_links.py+++ b/scripts/rediscover_entity_links.py@@ -31,9 +31,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from peach.entities import name_chain # noqa: E402from peach.review_csv import write_rows # noqa: E402+from peach.scripting import USER_AGENT # noqa: E402-USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "- "(KHTML, like Gecko) Chrome/128.0 Safari/537.36")ANCHOR = re.compile(r'<a\s[^>]*href=["\']([^"\']+)["\']([^>]*)>(.*?)</a>', re.S | re.I)TITLE = re.compile(r"<title[^>]*>(.*?)</title>", re.S | re.I)FIELDS = ("entity_id", "kind", "name", "link_kind", "label", "url", "evidence",