Download backend/reader/query/http/routes.py from VoiceOfML/Search: direct link, hf CLI and curl.
- Browser
- Download file 6.45 kB
-
https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/query/http/routes.py
- Command line
-
hf download hf://spaces/VoiceOfML/Search/backend/reader/query/http/routes.py
-
curl -L -o routes.py https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/query/http/routes.py
6.45 kB
| """Reader query HTTP responses and source-content dispatch policy.""" | |
| import gzip | |
| import json | |
| import zlib | |
| from collections.abc import Awaitable, Callable, Mapping | |
| from typing import Protocol, cast | |
| from urllib.parse import ParseResult, parse_qs, unquote | |
| from fastapi import Request | |
| from fastapi.responses import JSONResponse, Response | |
| from backend.reader.bucket.domain.policy import ReaderBucketBusyError | |
| from backend.reader.catalog.domain.assets import ( | |
| READER_AVIF_DOCUMENT_PATH_RE, READER_AVIF_PAGE_PATH_RE, READER_EBOOK_BUCKET, | |
| ) | |
| from backend.reader.query.application.ocr import MissingOcrIndex, OcrAccess, search_book | |
| from backend.reader.query.application.resolution import ResolutionAccess, resolve_source | |
| class QueryStream(Protocol): | |
| def __call__(self, request: Request, target_url: str, *, | |
| max_bytes: int | None = None, media_type: str | None = None) -> Awaitable[Response]: ... | |
| class QueryHttpAccess(Protocol): | |
| def resolve(self, source_id: str) -> Awaitable[Response]: ... | |
| def parse_url(self, url: str) -> ParseResult: ... | |
| def valid_bucket_path(self, path: str) -> bool: ... | |
| def bucket_response(self, path: str, request: Request) -> Awaitable[Response]: ... | |
| def validate_source(self, url: str) -> str: ... | |
| def resource_types(self) -> Mapping[str, str]: ... | |
| def pdf_max_bytes(self) -> int: ... | |
| def stream(self) -> QueryStream: ... | |
| def busy_headers(self) -> Mapping[str, str]: ... | |
| async def reader_resolve(source_id: str, access: ResolutionAccess, *, | |
| cache_control: Callable[[dict[str, object]], str]) -> JSONResponse: | |
| if not access.valid_id(source_id): | |
| return JSONResponse({"error": "无效阅读 ID"}, status_code=400) | |
| matches, assets = await resolve_source(source_id, access) | |
| if len({access.canonical_source(cast(str, match["download"])) for match in matches}) > 1: | |
| return JSONResponse({"error": "阅读 ID 不唯一"}, status_code=409) | |
| matches = matches[:1] | |
| if matches: | |
| return JSONResponse(matches[0], headers={"Cache-Control": cache_control(assets)}) | |
| return JSONResponse({"error": "阅读文件不存在"}, status_code=404) | |
| async def reader_ocr_search(source_id: str, q: str, page: int, page_size: int, | |
| http: QueryHttpAccess, ocr: OcrAccess) -> Response: | |
| resolved = await http.resolve(source_id) | |
| if resolved.status_code != 200: | |
| return resolved | |
| try: | |
| data = json.loads(bytes(resolved.body)) | |
| manifest_url = str(data.get("ocr_manifest") or "") | |
| result = await search_book(manifest_url, q, page, page_size, ocr) | |
| return JSONResponse(result, headers={"Cache-Control": "no-store"}) | |
| except MissingOcrIndex: | |
| return JSONResponse({"error": "本书暂无 OCR 索引"}, status_code=404) | |
| except (ValueError, TypeError, KeyError, EOFError, gzip.BadGzipFile, zlib.error): | |
| return JSONResponse({"error": "OCR 索引损坏"}, status_code=502) | |
| except FileNotFoundError: | |
| return JSONResponse({"error": "OCR 索引不存在"}, status_code=404, | |
| headers={"Cache-Control": "no-store"}) | |
| except ReaderBucketBusyError: | |
| return JSONResponse({"error": "OCR 索引请求过多,请稍后重试"}, status_code=503, | |
| headers=http.busy_headers()) | |
| except Exception: | |
| return JSONResponse({"error": "OCR 索引加载失败"}, status_code=502, | |
| headers={"Cache-Control": "no-store"}) | |
| async def reader_content(request: Request, url: str | None, source_id: str | None, | |
| access: QueryHttpAccess) -> Response: | |
| if source_id and not url: | |
| resolved = await access.resolve(source_id) | |
| if resolved.status_code != 200: | |
| return resolved | |
| try: | |
| url = json.loads(bytes(resolved.body)).get("url") | |
| except (AttributeError, TypeError, ValueError): | |
| return JSONResponse({"error": "阅读文件解析失败"}, status_code=502) | |
| if not url: | |
| return JSONResponse({"error": "缺少阅读文件地址"}, status_code=400) | |
| try: | |
| parsed = access.parse_url(url) | |
| except ValueError as exc: | |
| return JSONResponse({"error": str(exc)}, status_code=403) | |
| is_bucket_proxy = ( | |
| (not parsed.scheme and not parsed.netloc) | |
| or (parsed.scheme == "https" and parsed.netloc == "voiceofml-search.hf.space") | |
| ) | |
| if is_bucket_proxy and parsed.path == "/api/reader-bucket-resource" and not parsed.fragment: | |
| parameters = parse_qs(parsed.query) | |
| if (set(parameters) != {"path"} or len(parameters["path"]) != 1): | |
| return JSONResponse({"error": "不允许的阅读资源路径"}, status_code=400) | |
| return await access.bucket_response(parameters["path"][0], request) | |
| bucket_prefix = next((prefix for prefix in ( | |
| "/buckets/vomebook/pdf-pages-v2/resolve/", | |
| "/buckets/vomebook/reader-assets-v2/resolve/", | |
| ) if parsed.path.startswith(prefix)), None) | |
| if (parsed.scheme == "https" and parsed.hostname == "huggingface.co" | |
| and parsed.netloc.lower() in {"huggingface.co", "huggingface.co:443"} | |
| and not parsed.username and not parsed.password and not parsed.query and not parsed.fragment | |
| and bucket_prefix is not None): | |
| resource_path = unquote(parsed.path[len(bucket_prefix):]) | |
| if not access.valid_bucket_path(resource_path) or ( | |
| bucket_prefix != f"/buckets/{READER_EBOOK_BUCKET}/resolve/" | |
| and (READER_AVIF_DOCUMENT_PATH_RE.fullmatch(resource_path) | |
| or READER_AVIF_PAGE_PATH_RE.fullmatch(resource_path)) | |
| ): | |
| return JSONResponse({"error": "不允许的阅读资源路径"}, status_code=400) | |
| return await access.bucket_response(resource_path, request) | |
| try: | |
| target_url = access.validate_source(url) | |
| except ValueError as exc: | |
| return JSONResponse({"error": str(exc)}, status_code=403) | |
| source_type = access.resource_types().get(unquote(access.parse_url(target_url).path).rsplit(".", 1)[-1].lower(), "") | |
| if source_type == "application/pdf": | |
| return await access.stream()(request, target_url, max_bytes=access.pdf_max_bytes()) | |
| if source_type.startswith(("audio/", "video/")): | |
| return await access.stream()(request, target_url, media_type=source_type) | |
| return await access.stream()(request, target_url) | |