vomebook commited on
Commit ·
df22592
1
Parent(s): dfeda50
feat(seo): add search metadata and isolated catalog navigation mirror
Browse files- backend/app.py +43 -2
- backend/seo.py +285 -0
- static/index.html +17 -1
- tests/test_seo_catalog.py +154 -0
- tests/test_seo_routes.py +48 -0
backend/app.py
CHANGED
|
@@ -25,7 +25,7 @@ import aiohttp
|
|
| 25 |
from huggingface_hub import HfFileSystem
|
| 26 |
import jieba
|
| 27 |
from fastapi import FastAPI, HTTPException, Query, Request
|
| 28 |
-
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse, Response
|
| 29 |
from fastapi.staticfiles import StaticFiles
|
| 30 |
from fastapi.middleware.cors import CORSMiddleware
|
| 31 |
from fastapi.middleware.gzip import GZipMiddleware
|
|
@@ -42,6 +42,7 @@ from backend.reader_assets import (
|
|
| 42 |
READER_ASSET_FILENAMES, READER_BUCKET_PATH_RE, decode_reader_assets,
|
| 43 |
)
|
| 44 |
from backend.reader_v3_catalog import load_reading_catalog, merge_sidecar as merge_v3_sidecar
|
|
|
|
| 45 |
from backend.data_formats import (
|
| 46 |
decode_browser_entry, decode_folder_browser_data, decode_folder_tree_data,
|
| 47 |
decode_search_payload, decode_tree_node,
|
|
@@ -913,7 +914,13 @@ def build_initial_payloads():
|
|
| 913 |
}
|
| 914 |
|
| 915 |
def precompute_injected_html():
|
| 916 |
-
global injected_html_cache
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 917 |
index_path = Path("static/index.html")
|
| 918 |
if not index_path.exists():
|
| 919 |
injected_html_cache = {}
|
|
@@ -943,6 +950,7 @@ def build_global_bootstrap():
|
|
| 943 |
|
| 944 |
def inject_initial_payload(html: str, repo_short: str | None = None) -> str:
|
| 945 |
repo = f"VoiceOfML/{repo_short}" if repo_short else None
|
|
|
|
| 946 |
payload = initial_payload_by_repo.get(repo) if repo else initial_payload_global
|
| 947 |
if not payload:
|
| 948 |
return html
|
|
@@ -2812,6 +2820,39 @@ def serve_sidebar_repo(repo_name: str):
|
|
| 2812 |
def serve_sidebar_manifest():
|
| 2813 |
return read_sidebar_json(SIDEBAR_DATA_PATH / "manifest.json")
|
| 2814 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2815 |
@app.get("/")
|
| 2816 |
async def serve_root():
|
| 2817 |
html = injected_html_cache.get(None)
|
|
|
|
| 25 |
from huggingface_hub import HfFileSystem
|
| 26 |
import jieba
|
| 27 |
from fastapi import FastAPI, HTTPException, Query, Request
|
| 28 |
+
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response
|
| 29 |
from fastapi.staticfiles import StaticFiles
|
| 30 |
from fastapi.middleware.cors import CORSMiddleware
|
| 31 |
from fastapi.middleware.gzip import GZipMiddleware
|
|
|
|
| 42 |
READER_ASSET_FILENAMES, READER_BUCKET_PATH_RE, decode_reader_assets,
|
| 43 |
)
|
| 44 |
from backend.reader_v3_catalog import load_reading_catalog, merge_sidecar as merge_v3_sidecar
|
| 45 |
+
from backend.seo import build_catalog as build_seo_catalog, enrich_search_shell
|
| 46 |
from backend.data_formats import (
|
| 47 |
decode_browser_entry, decode_folder_browser_data, decode_folder_tree_data,
|
| 48 |
decode_search_payload, decode_tree_node,
|
|
|
|
| 914 |
}
|
| 915 |
|
| 916 |
def precompute_injected_html():
|
| 917 |
+
global injected_html_cache, seo_catalog_cache
|
| 918 |
+
try:
|
| 919 |
+
seo_catalog_cache = build_seo_catalog(records, project="hf", corpus_identity=search_generation())
|
| 920 |
+
except ValueError:
|
| 921 |
+
# SEO failure must not replace search data or publish a partial catalog.
|
| 922 |
+
seo_catalog_cache = None
|
| 923 |
+
print("seo_catalog=unavailable reason=source_contract", flush=True)
|
| 924 |
index_path = Path("static/index.html")
|
| 925 |
if not index_path.exists():
|
| 926 |
injected_html_cache = {}
|
|
|
|
| 950 |
|
| 951 |
def inject_initial_payload(html: str, repo_short: str | None = None) -> str:
|
| 952 |
repo = f"VoiceOfML/{repo_short}" if repo_short else None
|
| 953 |
+
html = enrich_search_shell(html, repo, repo_counts.get(repo) if repo else None)
|
| 954 |
payload = initial_payload_by_repo.get(repo) if repo else initial_payload_global
|
| 955 |
if not payload:
|
| 956 |
return html
|
|
|
|
| 2820 |
def serve_sidebar_manifest():
|
| 2821 |
return read_sidebar_json(SIDEBAR_DATA_PATH / "manifest.json")
|
| 2822 |
|
| 2823 |
+
seo_catalog_cache = None
|
| 2824 |
+
|
| 2825 |
+
|
| 2826 |
+
@app.get("/robots.txt")
|
| 2827 |
+
def serve_robots():
|
| 2828 |
+
# The indexable catalog lives on Pages. Do not advertise a conflicting HF sitemap.
|
| 2829 |
+
return PlainTextResponse("User-agent: *\nAllow: /\n", headers={"Cache-Control": "public, max-age=3600"})
|
| 2830 |
+
|
| 2831 |
+
|
| 2832 |
+
@app.get("/catalog")
|
| 2833 |
+
def redirect_catalog():
|
| 2834 |
+
return RedirectResponse("/catalog/", status_code=308)
|
| 2835 |
+
|
| 2836 |
+
|
| 2837 |
+
@app.get("/catalog/")
|
| 2838 |
+
@app.get("/catalog/{catalog_path:path}")
|
| 2839 |
+
def serve_seo_catalog(catalog_path: str = ""):
|
| 2840 |
+
if seo_catalog_cache is None:
|
| 2841 |
+
return PlainTextResponse("Catalog temporarily unavailable", status_code=503,
|
| 2842 |
+
headers={"Cache-Control": "no-store", "X-Robots-Tag": "noindex"})
|
| 2843 |
+
headers = {"X-Robots-Tag": "noindex, follow"}
|
| 2844 |
+
if catalog_path == "publication.json":
|
| 2845 |
+
return JSONResponse(seo_catalog_cache["manifest"], headers={**headers, "Cache-Control": "no-store"})
|
| 2846 |
+
key = "catalog/" + catalog_path.rstrip("/")
|
| 2847 |
+
key = key.rstrip("/") + "/index.html"
|
| 2848 |
+
body = seo_catalog_cache["files"].get(key)
|
| 2849 |
+
if body is None:
|
| 2850 |
+
return PlainTextResponse("Catalog page not found", status_code=404, headers=headers)
|
| 2851 |
+
if catalog_path and not catalog_path.endswith("/"):
|
| 2852 |
+
return RedirectResponse("/catalog/" + quote(catalog_path, safe="/") + "/", status_code=308)
|
| 2853 |
+
return HTMLResponse(body, headers={**headers, "Cache-Control": "public, max-age=300"})
|
| 2854 |
+
|
| 2855 |
+
|
| 2856 |
@app.get("/")
|
| 2857 |
async def serve_root():
|
| 2858 |
html = injected_html_cache.get(None)
|
backend/seo.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, deterministic metadata catalog; no source-body downloads or search changes.
|
| 2 |
+
|
| 3 |
+
The same file is copied to Pages' scripts/build/seo.py. Pages owns the indexable
|
| 4 |
+
catalog; new HF catalog pages are noindex mirrors because HF appends a Hub canonical.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
from collections import Counter, defaultdict
|
| 10 |
+
import gzip
|
| 11 |
+
import hashlib
|
| 12 |
+
from html import escape
|
| 13 |
+
import json
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import re
|
| 16 |
+
from urllib.parse import quote, urlencode
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
PAGES = "https://vomebook.github.io/search/"
|
| 20 |
+
HF = "https://voiceofml-search.hf.space/"
|
| 21 |
+
DESCRIPTION = "检索 VoiceOfML 公开资料的文件名、路径和格式,浏览文库目录,在线阅读或下载原始文件。"
|
| 22 |
+
PILOT = {
|
| 23 |
+
"samples": [
|
| 24 |
+
["VoiceOfML/VOMEBOOK", "马列之声ebook小组第二批成果集成赞助部分/jiang/中国社会主义时代的教育革命 研究资料集成pdf(近800种)/工农兵大学生/工农兵学员的优秀代表----曹谊林.txt"],
|
| 25 |
+
["VoiceOfML/SovMaterials", "重要中文文献/斯大林著作各种/斯大林语录.txt"],
|
| 26 |
+
["VoiceOfML/GPCREducation", "化学/简明化学手册.pdf"],
|
| 27 |
+
["VoiceOfML/Teachers", "其他/李达/李达传记.pdf"],
|
| 28 |
+
["VoiceOfML/MLMRL-Library", "历史/中国近代史1.pdf"],
|
| 29 |
+
["VoiceOfML/Japanese-Materials", "极端派的时代.pdf"],
|
| 30 |
+
["VoiceOfML/A-Historical-Learning-Data", "无产阶级政党/列宁《怎么办?》.pdf"],
|
| 31 |
+
["VoiceOfML/MLMRL-Hub", "001643/学点逻辑.pdf"],
|
| 32 |
+
["VoiceOfML/Omnibus", "幻の大連.pdf"],
|
| 33 |
+
],
|
| 34 |
+
"folder": ["VoiceOfML/SovMaterials", "俄苏史/苏联史"],
|
| 35 |
+
}
|
| 36 |
+
CATALOG_CSS = """body{font:17px/1.7 system-ui,sans-serif;margin:0;background:#fafafa;color:#202124}
|
| 37 |
+
main{max-width:900px;margin:auto;padding:24px 18px}a{color:#1558a6}a:focus-visible{outline:3px solid #1558a6;outline-offset:3px}
|
| 38 |
+
h1{font-size:1.65rem;line-height:1.4;overflow-wrap:anywhere}h2{font-size:1.2rem;margin-top:1.8em}
|
| 39 |
+
nav,footer{margin:18px 0}li{margin:9px 0}p{margin:12px 0}dl{display:grid;grid-template-columns:5em 1fr;gap:8px}
|
| 40 |
+
dt{font-weight:600}dd{margin:0;overflow-wrap:anywhere}code{white-space:pre-wrap;overflow-wrap:anywhere}
|
| 41 |
+
.note{padding:12px;background:#edf3fa;border-radius:8px}.muted{color:#555}img{max-width:100%}
|
| 42 |
+
@media(prefers-color-scheme:dark){body{background:#181a1d;color:#e2e2e6}a{color:#9ec5ff}.muted{color:#bfc5cf}.note{background:#242f40}}
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def json_script(value: object) -> str:
|
| 47 |
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":")).replace("<", "\\u003c").replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def metadata(title: str, description: str, url: str, *, canonical: bool, noindex: bool = False) -> str:
|
| 51 |
+
image = (PAGES if url.startswith(PAGES) else HF) + "icons/icon-512.png"
|
| 52 |
+
values = [f"<title>{escape(title)}</title>",
|
| 53 |
+
f'<meta name="description" content="{escape(description, quote=True)}">']
|
| 54 |
+
if canonical:
|
| 55 |
+
values.append(f'<link rel="canonical" href="{escape(url, quote=True)}">')
|
| 56 |
+
if noindex:
|
| 57 |
+
values.append('<meta name="robots" content="noindex,follow">')
|
| 58 |
+
for key, value in [("og:type", "website"), ("og:site_name", "VoiceOfML"),
|
| 59 |
+
("og:title", title), ("og:description", description), ("og:url", url),
|
| 60 |
+
("og:image", image), ("og:image:alt", "VoiceOfML 文库"), ("og:locale", "zh_CN")]:
|
| 61 |
+
values.append(f'<meta property="{key}" content="{escape(value, quote=True)}">')
|
| 62 |
+
for key, value in [("twitter:card", "summary"), ("twitter:title", title),
|
| 63 |
+
("twitter:description", description), ("twitter:image", image),
|
| 64 |
+
("twitter:image:alt", "VoiceOfML 文库")]:
|
| 65 |
+
values.append(f'<meta name="{key}" content="{escape(value, quote=True)}">')
|
| 66 |
+
return "\n".join(values)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def enrich_search_shell(html: str, repo: str | None = None, count: int | None = None) -> str:
|
| 70 |
+
"""HF-only: retain the platform's single HTTP canonical, never add a rival."""
|
| 71 |
+
title = f"{repo} 资料检索 — VoiceOfML Search" if repo else "VoiceOfML Search — 资料检索与文库目录"
|
| 72 |
+
description = (f"检索 {repo} 的 {count:,} 条资料记录,按文件名、路径和格式查找,在线阅读或下载。"
|
| 73 |
+
if repo and count is not None else DESCRIPTION)
|
| 74 |
+
url = HF + (quote(repo.split("/")[-1], safe="") + "/" if repo else "")
|
| 75 |
+
start, end = "<!-- SEO:HEAD -->", "<!-- /SEO:HEAD -->"
|
| 76 |
+
if start in html and end in html:
|
| 77 |
+
head = metadata(title, description, url, canonical=False)
|
| 78 |
+
head += '\n<script type="application/ld+json">' + json_script({
|
| 79 |
+
"@context": "https://schema.org", "@type": "WebSite", "name": "VoiceOfML",
|
| 80 |
+
"url": HF, "description": DESCRIPTION, "inLanguage": "zh-CN",
|
| 81 |
+
}) + '</script>'
|
| 82 |
+
html = html.split(start, 1)[0] + start + "\n" + head + "\n" + end + html.split(end, 1)[1]
|
| 83 |
+
return html
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def decode_corpus(payload: object) -> list[dict]:
|
| 87 |
+
if not isinstance(payload, dict) or payload.get("v") != 2:
|
| 88 |
+
raise ValueError("SEO requires the current compact-v2 corpus")
|
| 89 |
+
repos, folders, rows = payload.get("rp"), payload.get("fd"), payload.get("rc")
|
| 90 |
+
if not all(isinstance(value, list) for value in (repos, folders, rows)):
|
| 91 |
+
raise ValueError("Invalid compact tables")
|
| 92 |
+
result = []
|
| 93 |
+
for row in rows:
|
| 94 |
+
if (not isinstance(row, list) or len(row) < 6 or type(row[0]) is not int
|
| 95 |
+
or not 0 <= row[0] < len(repos) or type(row[3]) is not int or not 0 <= row[3] < len(folders)):
|
| 96 |
+
raise ValueError("Invalid compact record reference")
|
| 97 |
+
record = dict(Repo=repos[row[0]], File=row[1], Extension=row[2], Folder=folders[row[3]], Size=row[4])
|
| 98 |
+
if (not isinstance(record["Repo"], str) or not re.fullmatch(r"VoiceOfML/[A-Za-z0-9._-]+", record["Repo"])
|
| 99 |
+
or not all(isinstance(record[key], str) for key in ("File", "Extension"))
|
| 100 |
+
or not isinstance(record["Folder"], list)
|
| 101 |
+
or not all(isinstance(part, str) for part in record["Folder"])):
|
| 102 |
+
raise ValueError("Invalid compact record fields")
|
| 103 |
+
result.append(record)
|
| 104 |
+
return result
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def relative_path(record: dict) -> str:
|
| 108 |
+
name = record["File"] + ("." + record["Extension"] if record["Extension"] else "")
|
| 109 |
+
path = "/".join([*record["Folder"], name])
|
| 110 |
+
if any(part in (".", "..") for part in path.split("/")) or "\x00" in path or "\\" in path:
|
| 111 |
+
raise ValueError("Unsafe source path")
|
| 112 |
+
return path
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def source_url(record: dict, action: str = "resolve") -> str:
|
| 116 |
+
return f'https://huggingface.co/datasets/{record["Repo"]}/{action}/main/{quote(relative_path(record), safe="/")}'
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def source_id(record: dict) -> str:
|
| 120 |
+
value = 1469598103934665603
|
| 121 |
+
for byte in source_url(record).encode("utf-8"):
|
| 122 |
+
value = ((value ^ byte) * 1099511628211) & ((1 << 64) - 1)
|
| 123 |
+
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
|
| 124 |
+
result = ""
|
| 125 |
+
while value:
|
| 126 |
+
value, digit = divmod(value, 36)
|
| 127 |
+
result = digits[digit] + result
|
| 128 |
+
return result.rjust(13, "0")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def build_catalog(records: list[dict], *, project: str, corpus_identity: str, pilot: dict | None = None) -> dict:
|
| 132 |
+
if project not in ("pages", "hf"):
|
| 133 |
+
raise ValueError("Unknown project")
|
| 134 |
+
pilot = PILOT if pilot is None else pilot
|
| 135 |
+
primary = project == "pages"
|
| 136 |
+
origin = PAGES if primary else HF
|
| 137 |
+
catalog = "catalog/"
|
| 138 |
+
repo_prefix = "" if primary else catalog
|
| 139 |
+
book_prefix = "book/" if primary else catalog + "book/"
|
| 140 |
+
grouped = defaultdict(list)
|
| 141 |
+
by_key = {}
|
| 142 |
+
for record in records:
|
| 143 |
+
grouped[record["Repo"]].append(record)
|
| 144 |
+
key = (record["Repo"], relative_path(record))
|
| 145 |
+
if key in by_key and any(by_key[key].get(field) != record.get(field) for field in ("File", "Extension", "Folder", "Size")):
|
| 146 |
+
raise ValueError("Conflicting source identity")
|
| 147 |
+
by_key[key] = record
|
| 148 |
+
selected = {}
|
| 149 |
+
for repo, path in pilot["samples"]:
|
| 150 |
+
record = by_key.get((repo, path))
|
| 151 |
+
if record is None:
|
| 152 |
+
raise ValueError(f"Missing configured SEO pilot source: {repo}/{path}")
|
| 153 |
+
selected[(repo, path)] = record
|
| 154 |
+
folder_repo, folder_path = pilot["folder"]
|
| 155 |
+
folder_records = [record for record in grouped[folder_repo] if "/".join(record["Folder"]) == folder_path]
|
| 156 |
+
descendants = [record for record in grouped[folder_repo]
|
| 157 |
+
if "/".join(record["Folder"]).startswith(folder_path + "/")]
|
| 158 |
+
if not folder_records or descendants or len(folder_records) > 64:
|
| 159 |
+
raise ValueError("SEO pilot must be a complete leaf folder of 1–64 files; never truncate it")
|
| 160 |
+
for record in folder_records:
|
| 161 |
+
selected[(record["Repo"], relative_path(record))] = record
|
| 162 |
+
selected_records = sorted(selected.values(), key=lambda record: (record["Repo"], relative_path(record)))
|
| 163 |
+
ids = [source_id(record) for record in selected_records]
|
| 164 |
+
if len(set(ids)) != len(ids):
|
| 165 |
+
raise ValueError("SEO source-ID collision")
|
| 166 |
+
folder_id = hashlib.sha256((folder_repo + "\0" + folder_path).encode()).hexdigest()[:16]
|
| 167 |
+
folder_route = catalog + "folders/" + folder_id + "/"
|
| 168 |
+
pages = {}
|
| 169 |
+
page_urls = []
|
| 170 |
+
|
| 171 |
+
def anchor(route, label):
|
| 172 |
+
return f'<a href="{escape(origin + route, quote=True)}">{escape(label)}</a>'
|
| 173 |
+
|
| 174 |
+
def search_link(repo, folder=""):
|
| 175 |
+
short = quote(repo.split("/")[-1], safe="")
|
| 176 |
+
return origin + ("#/" + short if primary else short + "/") + ("?" + urlencode({"path": folder}) if folder else "")
|
| 177 |
+
|
| 178 |
+
def entries(values):
|
| 179 |
+
return "<ul>" + "".join("<li>" + anchor(book_prefix + source_id(record) + "/", record["File"])
|
| 180 |
+
+ " — " + escape(record["Extension"].upper()) + "</li>" for record in values) + "</ul>"
|
| 181 |
+
|
| 182 |
+
def page(route, title, description, body, entity):
|
| 183 |
+
url = origin + route
|
| 184 |
+
graph = {"@context": "https://schema.org", "@graph": [
|
| 185 |
+
{"@type": "WebSite", "@id": origin + "#website", "name": "VoiceOfML", "url": origin},
|
| 186 |
+
{"@type": "WebPage", "@id": url, "url": url, "name": title, "description": description,
|
| 187 |
+
"inLanguage": "zh-CN", "isPartOf": {"@id": origin + "#website"}, "mainEntity": entity},
|
| 188 |
+
]}
|
| 189 |
+
mirror = ""
|
| 190 |
+
# Mirror links use explicit route correspondence, not title-derived guesses.
|
| 191 |
+
if not primary:
|
| 192 |
+
main_route = route.removeprefix(catalog) if route.startswith(catalog + "book/") or route in {catalog + repo.split("/")[-1] + "/" for repo in grouped} else route
|
| 193 |
+
mirror = '<p class="note">这是 HF 导航镜像;<a href="' + escape(PAGES + main_route, quote=True) + '">打开对应的主目录页</a>。</p>'
|
| 194 |
+
html = ('<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
|
| 195 |
+
'<meta name="viewport" content="width=device-width,initial-scale=1">'
|
| 196 |
+
+ metadata(title, description, url, canonical=primary, noindex=not primary)
|
| 197 |
+
+ '<script type="application/ld+json">' + json_script(graph) + '</script>'
|
| 198 |
+
+ '<style>' + CATALOG_CSS + '</style></head><body><main>'
|
| 199 |
+
+ '<nav aria-label="主导航">' + anchor("", "资料检索") + " · " + anchor(catalog, "文库目录") + '</nav>'
|
| 200 |
+
+ '<h1>' + escape(title) + '</h1>' + mirror + body
|
| 201 |
+
+ '<footer class="muted">本页仅整理公开文件元数据,不代表已核实作者、出版或 OCR 准确性。'
|
| 202 |
+
'如资料信息或来源有误,请通过原始仓库反馈。目录试点不限制站内完整搜索。</footer>'
|
| 203 |
+
+ '</main></body></html>')
|
| 204 |
+
pages[route + "index.html"] = html
|
| 205 |
+
page_urls.append(url)
|
| 206 |
+
|
| 207 |
+
repo_links = '<ul>' + ''.join('<li>' + anchor(repo_prefix + repo.split('/')[-1] + '/', repo.split('/')[-1])
|
| 208 |
+
+ f' — {len(grouped[repo]):,} 条记录</li>' for repo in sorted(grouped)) + '</ul>'
|
| 209 |
+
page(catalog, "VoiceOfML 文库目录", DESCRIPTION,
|
| 210 |
+
'<p>按来源仓库浏览公开资料。下列数量是文件元数据记录数,不是去重后的书籍数。</p>' + repo_links
|
| 211 |
+
+ f'<h2>目录试点</h2><p>本批提供 {len(selected_records)} 个资源详情和一个完整叶目录;其余资料仍可通过站内搜索查找。</p>'
|
| 212 |
+
+ '<p>' + anchor(folder_route, folder_repo.split('/')[-1] + '/' + folder_path) + '</p>' + entries(selected_records),
|
| 213 |
+
{"@type": "ItemList", "numberOfItems": len(grouped)})
|
| 214 |
+
for repo in sorted(grouped):
|
| 215 |
+
formats = Counter(record["Extension"] for record in grouped[repo])
|
| 216 |
+
top = Counter(record["Folder"][0] if record["Folder"] else "(根目录)" for record in grouped[repo])
|
| 217 |
+
sample = [record for record in selected_records if record["Repo"] == repo]
|
| 218 |
+
body = f'<p>{escape(repo)} 包含 {len(grouped[repo]):,} 条文件记录,可按文件名、路径和格式检索。</p>'
|
| 219 |
+
body += '<p><a href="' + escape(search_link(repo), quote=True) + '">进入此仓库的完整搜索</a> · <a href="https://huggingface.co/datasets/' + quote(repo, safe='/') + '/tree/main">原始数据仓库</a></p>'
|
| 220 |
+
body += '<h2>文件格式</h2><p>' + ';'.join(escape(ext.upper() or '无扩展名') + f' {count:,}' for ext, count in sorted(formats.items())) + '</p>'
|
| 221 |
+
body += '<h2>路径概览</h2><p>以下为条目最多的至多 12 个顶层路径示例;完整目录见仓库搜索。</p><ul>'
|
| 222 |
+
body += ''.join('<li>' + escape(name) + f' — {count:,} 条</li>' for name, count in sorted(top.items(), key=lambda item: (-item[1], item[0]))[:12]) + '</ul>'
|
| 223 |
+
body += '<h2>本批资源详情</h2>' + entries(sample)
|
| 224 |
+
if repo == folder_repo:
|
| 225 |
+
body += '<p>' + anchor(folder_route, '浏览完整试点目录:' + folder_path) + '</p>'
|
| 226 |
+
page(repo_prefix + repo.split('/')[-1] + '/', repo.split('/')[-1] + ' 资料目录 — VoiceOfML',
|
| 227 |
+
f'{repo} 的文件目录、格式分布与来源路径;共 {len(grouped[repo]):,} 条元数据记录,支持在线检索、阅读和原始文件下载。',
|
| 228 |
+
body, {"@type": "CollectionPage", "name": repo})
|
| 229 |
+
page(folder_route, folder_path + ' — ' + folder_repo.split('/')[-1],
|
| 230 |
+
f'{folder_repo}/{folder_path} 的完整叶目录,包含 {len(folder_records)} 个文件。',
|
| 231 |
+
'<p>' + anchor(repo_prefix + folder_repo.split('/')[-1] + '/', folder_repo) + '</p><p>原始目录:<code>'
|
| 232 |
+
+ escape(folder_path) + f'</code>;本页完整列出该叶目录的 {len(folder_records)} 个文件。</p>'
|
| 233 |
+
+ entries(sorted(folder_records, key=relative_path)), {"@type": "ItemList", "numberOfItems": len(folder_records)})
|
| 234 |
+
for record in selected_records:
|
| 235 |
+
repo, path, identifier = record['Repo'], relative_path(record), source_id(record)
|
| 236 |
+
size = str(record.get('Size', '未知')) + (' bytes' if type(record.get('Size')) in (int, float) else '')
|
| 237 |
+
body = '<p>' + anchor(repo_prefix + repo.split('/')[-1] + '/', repo) + '</p><dl>'
|
| 238 |
+
for label, value in [('文件名', record['File']), ('仓库', repo), ('原始路径', path),
|
| 239 |
+
('格式', record['Extension'].upper()), ('文件大小', size)]:
|
| 240 |
+
body += '<dt>' + label + '</dt><dd>' + escape(value) + '</dd>'
|
| 241 |
+
body += '</dl><p><a href="' + escape(origin + 'static/reader.html?id=' + identifier, quote=True) + '">在线阅读</a> · '
|
| 242 |
+
body += '<a href="' + escape(source_url(record), quote=True) + '">下载原始文件</a> · <a href="' + escape(source_url(record, 'blob'), quote=True) + '">查看原始文件页面</a></p>'
|
| 243 |
+
body += '<p>资料说明:此条目按原始文件名和仓库路径登记;请以原文件及来源页面核对内容、版本与权利信息。本页不推测作者、ISBN 或出版日期。</p>'
|
| 244 |
+
page(book_prefix + identifier + '/', record['File'] + ' — VoiceOfML 资源详情',
|
| 245 |
+
f'{record["File"]},{record["Extension"].upper()} 文件,来源 {repo};查看路径、在线阅读与原始下载入口。', body,
|
| 246 |
+
{"@type": "DigitalDocument", "name": record['File'], "encodingFormat": record['Extension'],
|
| 247 |
+
"isBasedOn": source_url(record, 'blob')})
|
| 248 |
+
sitemap_urls = [PAGES, *page_urls] if primary else []
|
| 249 |
+
if primary:
|
| 250 |
+
pages['sitemap.xml'] = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + ''.join('<url><loc>' + escape(url) + '</loc></url>' for url in sitemap_urls) + '</urlset>'
|
| 251 |
+
manifest = {'version': 1, 'profile': 'metadata-catalog-pilot-v1', 'project': project,
|
| 252 |
+
'corpus_identity': corpus_identity, 'record_count': len(records),
|
| 253 |
+
'repo_counts': {repo: len(grouped[repo]) for repo in sorted(grouped)},
|
| 254 |
+
'detail_count': len(selected_records), 'folder_count': 1, 'urls': page_urls,
|
| 255 |
+
'sitemap_urls': sitemap_urls, 'details': [dict(id=source_id(record), repo=record['Repo'],
|
| 256 |
+
path=relative_path(record), source=source_url(record)) for record in selected_records],
|
| 257 |
+
'files': {path: hashlib.sha256(body.encode()).hexdigest() for path, body in sorted(pages.items())}}
|
| 258 |
+
return {'files': pages, 'manifest': manifest}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def main() -> int:
|
| 262 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 263 |
+
parser.add_argument('--project', choices=('pages', 'hf'), required=True)
|
| 264 |
+
parser.add_argument('--corpus', default='data/search_data.json.gz')
|
| 265 |
+
parser.add_argument('--output', required=True)
|
| 266 |
+
args = parser.parse_args()
|
| 267 |
+
source = Path(args.corpus).read_bytes()
|
| 268 |
+
result = build_catalog(decode_corpus(json.loads(gzip.decompress(source))), project=args.project,
|
| 269 |
+
corpus_identity=hashlib.sha256(source).hexdigest())
|
| 270 |
+
output = Path(args.output)
|
| 271 |
+
if (output / 'seo-publication.json').exists():
|
| 272 |
+
raise ValueError('Use a fresh build output; refusing stale catalog artifacts')
|
| 273 |
+
if any((output / relative).exists() for relative in result['files']):
|
| 274 |
+
raise ValueError('Refusing to overwrite existing catalog or sitemap files')
|
| 275 |
+
for relative, body in result['files'].items():
|
| 276 |
+
target = output / relative
|
| 277 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 278 |
+
target.write_text(body, encoding='utf-8')
|
| 279 |
+
(output / 'seo-publication.json').write_text(json.dumps(result['manifest'], ensure_ascii=False, indent=2), encoding='utf-8')
|
| 280 |
+
print(json.dumps({key: result['manifest'][key] for key in ('project', 'record_count', 'detail_count', 'folder_count')}))
|
| 281 |
+
return 0
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
if __name__ == '__main__':
|
| 285 |
+
raise SystemExit(main())
|
static/index.html
CHANGED
|
@@ -4,7 +4,22 @@
|
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
<script>if (matchMedia("(max-width: 768px)").matches && localStorage.getItem("mobileMode") !== "desktop") document.documentElement.classList.add("mobile-boot");</script>
|
| 7 |
-
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
<link rel="manifest" href="/manifest.json">
|
| 9 |
<meta name="theme-color" content="#1a1c1e">
|
| 10 |
<meta name="mobile-web-app-capable" content="yes">
|
|
@@ -110,6 +125,7 @@
|
|
| 110 |
</aside>
|
| 111 |
|
| 112 |
<main id="main-content" class="main-content">
|
|
|
|
| 113 |
<div id="status-bar" class="status-bar">
|
| 114 |
<div class="status-left">
|
| 115 |
<span id="result-count" class="result-count"></span>
|
|
|
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
<script>if (matchMedia("(max-width: 768px)").matches && localStorage.getItem("mobileMode") !== "desktop") document.documentElement.classList.add("mobile-boot");</script>
|
| 7 |
+
<!-- SEO:HEAD -->
|
| 8 |
+
<title>VoiceOfML Search — 资料检索与文库目录</title>
|
| 9 |
+
<meta name="description" content="检索 VoiceOfML 公开资料的文件名、路径和格式,浏览文库目录,在线阅读或下载原始文件。">
|
| 10 |
+
<meta property="og:type" content="website">
|
| 11 |
+
<meta property="og:site_name" content="VoiceOfML">
|
| 12 |
+
<meta property="og:title" content="VoiceOfML Search — 资料检索与文库目录">
|
| 13 |
+
<meta property="og:description" content="检索公开资料的文件名、路径和格式,浏览文库目录,在线阅读或下载原始文件。">
|
| 14 |
+
<meta property="og:url" content="https://voiceofml-search.hf.space/">
|
| 15 |
+
<meta property="og:image" content="https://voiceofml-search.hf.space/icons/icon-512.png">
|
| 16 |
+
<meta name="twitter:card" content="summary">
|
| 17 |
+
<meta name="twitter:title" content="VoiceOfML Search — 资料检索与文库目录">
|
| 18 |
+
<meta name="twitter:description" content="检索公开资料的文件名、路径和格式,浏览目录与原始文件。">
|
| 19 |
+
<meta name="twitter:image" content="https://voiceofml-search.hf.space/icons/icon-512.png">
|
| 20 |
+
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebSite","name":"VoiceOfML","url":"https://voiceofml-search.hf.space/","description":"公开资料的文件名与路径检索、目录浏览和在线阅读。","inLanguage":"zh-CN"}</script>
|
| 21 |
+
<!-- HF supplies the HTTP canonical; do not add a conflicting HTML canonical. -->
|
| 22 |
+
<!-- /SEO:HEAD -->
|
| 23 |
<link rel="manifest" href="/manifest.json">
|
| 24 |
<meta name="theme-color" content="#1a1c1e">
|
| 25 |
<meta name="mobile-web-app-capable" content="yes">
|
|
|
|
| 125 |
</aside>
|
| 126 |
|
| 127 |
<main id="main-content" class="main-content">
|
| 128 |
+
<div id="site-summary" style="flex:none;padding:2px 12px;font-size:12px;color:var(--on-surface-variant)">检索文件名与路径 · <a href="/catalog/">浏览文库目录</a></div>
|
| 129 |
<div id="status-bar" class="status-bar">
|
| 130 |
<div class="status-left">
|
| 131 |
<span id="result-count" class="result-count"></span>
|
tests/test_seo_catalog.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline fixtures for the small catalog, URL identity and indexing policy."""
|
| 2 |
+
import copy
|
| 3 |
+
from html.parser import HTMLParser
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import unittest
|
| 8 |
+
from xml.etree import ElementTree
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).parents[1]
|
| 12 |
+
MODULE = ROOT / ("backend/seo.py" if (ROOT / "backend").exists() else "scripts/build/seo.py")
|
| 13 |
+
spec = importlib.util.spec_from_file_location("seo_catalog_under_test", MODULE)
|
| 14 |
+
seo = importlib.util.module_from_spec(spec)
|
| 15 |
+
spec.loader.exec_module(seo)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Facts(HTMLParser):
|
| 19 |
+
def __init__(self, text):
|
| 20 |
+
super().__init__()
|
| 21 |
+
self.canonicals = []
|
| 22 |
+
self.links = []
|
| 23 |
+
self.robots = []
|
| 24 |
+
self.feed(text)
|
| 25 |
+
|
| 26 |
+
def handle_starttag(self, tag, attrs):
|
| 27 |
+
attrs = dict(attrs)
|
| 28 |
+
if tag == "link" and attrs.get("rel") == "canonical": self.canonicals.append(attrs["href"])
|
| 29 |
+
if tag == "a" and attrs.get("href"): self.links.append(attrs["href"])
|
| 30 |
+
if tag == "meta" and attrs.get("name") == "robots": self.robots.append(attrs["content"])
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class CatalogTests(unittest.TestCase):
|
| 34 |
+
def setUp(self):
|
| 35 |
+
self.payload = {"v": 2, "rp": ["VoiceOfML/Alpha", "VoiceOfML/Beta"], "fd": [["资料"], []],
|
| 36 |
+
"rc": [[0, "书一", "pdf", 0, 10, 0], [0, '坏&标题"<', "txt", 0, 20, 1],
|
| 37 |
+
[1, "readme", "md", 1, 30, 1]]}
|
| 38 |
+
self.records = seo.decode_corpus(self.payload)
|
| 39 |
+
self.pilot = {"samples": [["VoiceOfML/Alpha", "资料/书一.pdf"], ["VoiceOfML/Beta", "readme.md"]],
|
| 40 |
+
"folder": ["VoiceOfML/Alpha", "资料"]}
|
| 41 |
+
|
| 42 |
+
def build(self, project="pages", records=None, pilot=None):
|
| 43 |
+
return seo.build_catalog(self.records if records is None else records, project=project,
|
| 44 |
+
corpus_identity="fixture-generation", pilot=self.pilot if pilot is None else pilot)
|
| 45 |
+
|
| 46 |
+
def test_compact_schema_and_record_references_are_validated(self):
|
| 47 |
+
self.assertEqual(len(self.records), 3)
|
| 48 |
+
self.assertEqual(self.records[0]["Folder"], ["资料"])
|
| 49 |
+
for broken in ({}, {**self.payload, "v": 3}, {**self.payload, "rc": [[99, "bad", "pdf", 0, 1, 0]]}):
|
| 50 |
+
with self.subTest(broken=broken), self.assertRaises(ValueError): seo.decode_corpus(broken)
|
| 51 |
+
|
| 52 |
+
def test_all_counts_and_complete_leaf_are_preserved(self):
|
| 53 |
+
result = self.build()
|
| 54 |
+
self.assertEqual(result["manifest"]["record_count"], 3)
|
| 55 |
+
self.assertEqual(result["manifest"]["repo_counts"], {"VoiceOfML/Alpha": 2, "VoiceOfML/Beta": 1})
|
| 56 |
+
self.assertEqual(result["manifest"]["detail_count"], 3)
|
| 57 |
+
folder = next(body for path, body in result["files"].items() if path.startswith("catalog/folders/"))
|
| 58 |
+
self.assertIn("完整列出该叶目录的 2 个文件", folder)
|
| 59 |
+
self.assertIn("书一", folder)
|
| 60 |
+
self.assertIn("坏&标题", folder)
|
| 61 |
+
|
| 62 |
+
def test_pages_has_real_repo_paths_and_exact_self_canonicals(self):
|
| 63 |
+
result = self.build()
|
| 64 |
+
self.assertIn("Alpha/index.html", result["files"])
|
| 65 |
+
for path, body in result["files"].items():
|
| 66 |
+
if not path.endswith(".html"): continue
|
| 67 |
+
facts = Facts(body)
|
| 68 |
+
self.assertEqual(facts.canonicals, [seo.PAGES + path.removesuffix("index.html")])
|
| 69 |
+
self.assertEqual(facts.robots, [])
|
| 70 |
+
self.assertIn("<h1>", body)
|
| 71 |
+
|
| 72 |
+
def test_hf_new_mirrors_do_not_add_a_second_canonical(self):
|
| 73 |
+
result = self.build("hf")
|
| 74 |
+
self.assertNotIn("sitemap.xml", result["files"])
|
| 75 |
+
self.assertEqual(result["manifest"]["sitemap_urls"], [])
|
| 76 |
+
for body in result["files"].values():
|
| 77 |
+
facts = Facts(body)
|
| 78 |
+
self.assertEqual(facts.canonicals, [])
|
| 79 |
+
self.assertEqual(facts.robots, ["noindex,follow"])
|
| 80 |
+
self.assertTrue(any(link.startswith(seo.PAGES) for link in facts.links))
|
| 81 |
+
book = next(body for path, body in result["files"].items() if path.startswith("catalog/book/"))
|
| 82 |
+
self.assertIn('href="' + seo.PAGES + 'book/', book)
|
| 83 |
+
|
| 84 |
+
def test_sitemap_contains_only_exact_indexable_page_set(self):
|
| 85 |
+
result = self.build()
|
| 86 |
+
root = ElementTree.fromstring(result["files"]["sitemap.xml"])
|
| 87 |
+
urls = [element.text for element in root.findall("{*}url/{*}loc")]
|
| 88 |
+
self.assertEqual(urls, result["manifest"]["sitemap_urls"])
|
| 89 |
+
self.assertEqual(len(urls), len(set(urls)))
|
| 90 |
+
self.assertNotIn("lastmod", result["files"]["sitemap.xml"])
|
| 91 |
+
for url in urls:
|
| 92 |
+
self.assertTrue(url.startswith(seo.PAGES))
|
| 93 |
+
self.assertNotIn("?", url)
|
| 94 |
+
self.assertNotIn("#", url)
|
| 95 |
+
self.assertNotIn("reader.html", url)
|
| 96 |
+
|
| 97 |
+
def test_directory_links_reach_every_pilot_detail_without_javascript(self):
|
| 98 |
+
result = self.build()
|
| 99 |
+
facts = Facts(result["files"]["catalog/index.html"])
|
| 100 |
+
for detail in result["manifest"]["details"]:
|
| 101 |
+
self.assertIn(seo.PAGES + "book/" + detail["id"] + "/", facts.links)
|
| 102 |
+
self.assertNotIn("<script src=", result["files"]["catalog/index.html"])
|
| 103 |
+
self.assertIn("#/Alpha", result["files"]["Alpha/index.html"])
|
| 104 |
+
|
| 105 |
+
def test_text_attributes_and_json_ld_are_escaped(self):
|
| 106 |
+
result = self.build()
|
| 107 |
+
body = next(body for path, body in result["files"].items() if path.startswith("book/") and "坏&" in body)
|
| 108 |
+
self.assertIn("坏&标题"<", body)
|
| 109 |
+
self.assertNotIn('坏&标题"<', body)
|
| 110 |
+
self.assertNotIn("</script><img", seo.json_script({"name": "</script><img src=x>"}))
|
| 111 |
+
self.assertEqual(json.loads(seo.json_script({"name": "</script>"}))["name"], "</script>")
|
| 112 |
+
self.assertNotIn('"author"', body)
|
| 113 |
+
self.assertNotIn('"isbn"', body)
|
| 114 |
+
|
| 115 |
+
def test_reader_ids_match_existing_published_contract_vectors(self):
|
| 116 |
+
record = dict(Repo="VoiceOfML/Test", Folder=[], File="book29", Extension="txt")
|
| 117 |
+
self.assertEqual(seo.source_id(record), "0ym7e7wbcxau0")
|
| 118 |
+
self.assertEqual(seo.source_id({**record, "File": "a b"}), "1ckyy8f8m7pim")
|
| 119 |
+
vectors = json.loads((ROOT / "tests/reader-contract-vectors.json").read_text())
|
| 120 |
+
parts = vectors["reportedBook"]["path"].split("/")
|
| 121 |
+
record = dict(Repo="VoiceOfML/VOMEBOOK", Folder=parts[:-1], File=parts[-1][:-4], Extension="pdf")
|
| 122 |
+
self.assertEqual(seo.source_id(record), vectors["reportedBook"]["id"])
|
| 123 |
+
|
| 124 |
+
def test_missing_or_growing_pilot_never_silently_truncates(self):
|
| 125 |
+
pilot = copy.deepcopy(self.pilot)
|
| 126 |
+
pilot["samples"][0][1] = "missing.pdf"
|
| 127 |
+
with self.assertRaises(ValueError): self.build(pilot=pilot)
|
| 128 |
+
child = {**self.records[0], "Folder": ["资料", "新增子目录"]}
|
| 129 |
+
with self.assertRaises(ValueError): self.build(records=[*self.records, child])
|
| 130 |
+
many = [{**self.records[0], "File": f"book{i}"} for i in range(65)]
|
| 131 |
+
with self.assertRaises(ValueError): self.build(records=[*self.records, *many])
|
| 132 |
+
|
| 133 |
+
def test_paths_and_conflicting_identity_fail_closed(self):
|
| 134 |
+
with self.assertRaises(ValueError): seo.relative_path({**self.records[0], "Folder": [".."]})
|
| 135 |
+
conflict = {**self.records[0], "Size": 999}
|
| 136 |
+
with self.assertRaises(ValueError): self.build(records=[*self.records, conflict])
|
| 137 |
+
|
| 138 |
+
def test_output_is_deterministic_and_does_not_mutate_search_records(self):
|
| 139 |
+
before = copy.deepcopy(self.records)
|
| 140 |
+
self.assertEqual(self.build(), self.build())
|
| 141 |
+
self.assertEqual(self.records, before)
|
| 142 |
+
|
| 143 |
+
def test_hf_shell_metadata_is_scoped_and_not_a_canonical_override(self):
|
| 144 |
+
template = '<head><!-- SEO:HEAD --><title>old</title><!-- /SEO:HEAD --></head><body>unchanged</body>'
|
| 145 |
+
html = seo.enrich_search_shell(template, "VoiceOfML/Alpha", 23)
|
| 146 |
+
self.assertIn("Alpha 资料检索", html)
|
| 147 |
+
self.assertIn("23 条资料记录", html)
|
| 148 |
+
self.assertEqual(Facts(html).canonicals, [])
|
| 149 |
+
self.assertIn("<body>unchanged</body>", html)
|
| 150 |
+
self.assertEqual(html.count("<title>"), 1)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
unittest.main()
|
tests/test_seo_routes.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline TestClient checks for isolated HF catalog and robots routes."""
|
| 2 |
+
import unittest
|
| 3 |
+
from unittest.mock import patch
|
| 4 |
+
|
| 5 |
+
from backend import app, seo
|
| 6 |
+
from fastapi.testclient import TestClient
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class SeoRoutesTests(unittest.TestCase):
|
| 10 |
+
def setUp(self):
|
| 11 |
+
records = [dict(Repo="VoiceOfML/Test", Folder=["docs"], File="book", Extension="pdf", Size=12)]
|
| 12 |
+
self.catalog = seo.build_catalog(records, project="hf", corpus_identity="fixture", pilot={
|
| 13 |
+
"samples": [["VoiceOfML/Test", "docs/book.pdf"]], "folder": ["VoiceOfML/Test", "docs"]})
|
| 14 |
+
self.client = TestClient(app.app)
|
| 15 |
+
|
| 16 |
+
def test_root_robots_is_plain_text_and_not_an_spa_shell(self):
|
| 17 |
+
response = self.client.get("/robots.txt")
|
| 18 |
+
self.assertEqual(response.status_code, 200)
|
| 19 |
+
self.assertIn("text/plain", response.headers["content-type"])
|
| 20 |
+
self.assertEqual(response.text, "User-agent: *\nAllow: /\n")
|
| 21 |
+
|
| 22 |
+
def test_catalog_is_html_and_only_the_new_mirror_is_noindex(self):
|
| 23 |
+
with patch.object(app, "seo_catalog_cache", self.catalog):
|
| 24 |
+
response = self.client.get("/catalog/")
|
| 25 |
+
self.assertEqual(response.status_code, 200)
|
| 26 |
+
self.assertEqual(response.headers["x-robots-tag"], "noindex, follow")
|
| 27 |
+
self.assertIn("VoiceOfML 文库目录", response.text)
|
| 28 |
+
publication = self.client.get("/catalog/publication.json")
|
| 29 |
+
self.assertEqual(publication.json()["detail_count"], 1)
|
| 30 |
+
self.assertEqual(publication.headers["cache-control"], "no-store")
|
| 31 |
+
self.assertNotIn("x-robots-tag", self.client.get("/static/reader.html").headers)
|
| 32 |
+
|
| 33 |
+
def test_catalog_unknown_paths_are_404_and_slash_aliases_redirect(self):
|
| 34 |
+
with patch.object(app, "seo_catalog_cache", self.catalog):
|
| 35 |
+
self.assertEqual(self.client.get("/catalog/not-real/").status_code, 404)
|
| 36 |
+
self.assertEqual(self.client.get("/catalog", follow_redirects=False).status_code, 308)
|
| 37 |
+
self.assertEqual(self.client.get("/catalog/Test", follow_redirects=False).status_code, 308)
|
| 38 |
+
self.assertEqual(self.client.get("/catalog/Test/").status_code, 200)
|
| 39 |
+
|
| 40 |
+
def test_unready_catalog_does_not_return_a_false_200(self):
|
| 41 |
+
with patch.object(app, "seo_catalog_cache", None):
|
| 42 |
+
response = self.client.get("/catalog/")
|
| 43 |
+
self.assertEqual(response.status_code, 503)
|
| 44 |
+
self.assertEqual(response.headers["cache-control"], "no-store")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
unittest.main()
|