Download backend/reader/catalog/http/random.py from VoiceOfML/Search: direct link, hf CLI and curl.
- Browser
- Download file 2.21 kB
-
https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/catalog/http/random.py
- Command line
-
hf download hf://spaces/VoiceOfML/Search/backend/reader/catalog/http/random.py
-
curl -L -o random.py https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/reader/catalog/http/random.py
2.21 kB
| """Random catalog and Reader responses over live application hooks.""" | |
| from collections.abc import Awaitable, Callable, Mapping, Sequence | |
| from dataclasses import dataclass | |
| from typing import Protocol, TypeVar | |
| from fastapi.responses import JSONResponse | |
| from backend.reader.catalog.application.pool import JsonObject, ReaderPool | |
| _T = TypeVar("_T") | |
| class Choice(Protocol): | |
| def __call__(self, seq: Sequence[_T]) -> _T: ... | |
| class RandomDependencies: | |
| records: Callable[[], list[JsonObject]] | |
| repos: Callable[[], Mapping[str, Sequence[int]]] | |
| pool: Callable[[str | None], Awaitable[ReaderPool]] | |
| choice: Choice | |
| public_record: Callable[[JsonObject], JsonObject] | |
| enrich_record: Callable[[JsonObject, JsonObject], JsonObject] | |
| clock: Callable[[], float] | |
| headers: Callable[[], Mapping[str, str]] | |
| def random_record(repo: str | None, deps: RandomDependencies) -> JSONResponse: | |
| if repo: | |
| full_repo = f"VoiceOfML/{repo}" | |
| repo_indices = deps.repos().get(full_repo, []) | |
| if not repo_indices: | |
| return JSONResponse({"error": "无可用记录"}, status_code=404) | |
| rec = deps.public_record(deps.records()[deps.choice(repo_indices)]) | |
| else: | |
| if not deps.records(): | |
| return JSONResponse({"error": "无可用记录"}, status_code=404) | |
| rec = deps.public_record(deps.choice(deps.records())) | |
| return JSONResponse(rec) | |
| async def random_reader(repo: str | None, deps: RandomDependencies) -> JSONResponse: | |
| started = deps.clock() | |
| pool, converted = await deps.pool(repo) | |
| if not pool: | |
| return JSONResponse({"error": "无可读文档"}, status_code=404) | |
| index = deps.choice(pool) | |
| rec = deps.public_record(deps.records()[index]) | |
| asset = converted.get(index) | |
| if asset: | |
| rec = deps.enrich_record(rec, asset) | |
| return JSONResponse(rec, headers={"Server-Timing": f"reader_select;dur={(deps.clock() - started) * 1000:.2f}"}) | |
| async def random_reader_status(repo: str | None, deps: RandomDependencies) -> JSONResponse: | |
| pool, _ = await deps.pool(repo) | |
| count = len(pool) | |
| return JSONResponse({"available": count > 0, "count": count}, headers=deps.headers()) | |