Download tools/search_server.py from Shangy/DR-256-backup: direct link, hf CLI and curl.
- Browser
- Download file 5.21 kB
-
https://huggingface.co/datasets/Shangy/DR-256-backup/resolve/main/tools/search_server.py
- Command line
-
hf download hf://datasets/Shangy/DR-256-backup/tools/search_server.py
-
curl -L -o search_server.py https://huggingface.co/datasets/Shangy/DR-256-backup/resolve/main/tools/search_server.py
5.21 kB
| #!/usr/bin/env python3 | |
| """Serve the local DeepResearch-9K SQLite corpus with the Miles search API.""" | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| import sqlite3 | |
| import time | |
| from contextlib import asynccontextmanager | |
| from pathlib import Path | |
| from typing import Any | |
| import uvicorn | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, Field | |
| try: | |
| from .corpus_db import connect, fts_counts, fts_exists, open_document, search, status_counts | |
| except ImportError: # direct script execution | |
| from corpus_db import connect, fts_counts, fts_exists, open_document, search, status_counts | |
| class QueryRequest(BaseModel): | |
| query: str = Field(..., min_length=1) | |
| k: int = Field(20, ge=1, le=100) | |
| class OpenRequest(BaseModel): | |
| docid: str | None = None | |
| url: str | None = None | |
| class QueryResponse(BaseModel): | |
| results: list[dict[str, Any]] | |
| took_ms: float | |
| connection: sqlite3.Connection | None = None | |
| blocked_docids: frozenset[str] = frozenset() | |
| async def lifespan(_app: FastAPI): | |
| global blocked_docids, connection | |
| database = Path(os.environ.get("DEEPRESEARCH9K_CORPUS_DB", "deepresearch9k_corpus.sqlite3")) | |
| if not database.exists(): | |
| raise RuntimeError(f"corpus database does not exist: {database}") | |
| blocked_path_value = os.environ.get("DEEPRESEARCH9K_BLOCKED_DOCIDS_FILE", "").strip() | |
| if blocked_path_value: | |
| blocked_path = Path(blocked_path_value) | |
| if not blocked_path.exists(): | |
| raise RuntimeError(f"blocked-docids file does not exist: {blocked_path}") | |
| blocked_docids = frozenset( | |
| line.strip() for line in blocked_path.read_text().splitlines() if line.strip() | |
| ) | |
| else: | |
| blocked_docids = frozenset() | |
| connection = connect(database, readonly=True) | |
| try: | |
| if not fts_exists(connection): | |
| raise RuntimeError(f"FTS index is missing in {database}; run build_index.py") | |
| yield | |
| finally: | |
| connection.close() | |
| connection = None | |
| app = FastAPI(title="DeepResearch-9K local FTS search", lifespan=lifespan) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| def get_connection() -> sqlite3.Connection: | |
| if connection is None: | |
| raise HTTPException(status_code=503, detail="search database is not initialized") | |
| return connection | |
| async def search_endpoint(request: QueryRequest) -> QueryResponse: | |
| started = time.perf_counter() | |
| if not request.query.strip(): | |
| raise HTTPException(status_code=400, detail="query must be a non-empty string") | |
| try: | |
| results = search( | |
| get_connection(), request.query, request.k, excluded_docids=blocked_docids | |
| ) | |
| except ValueError as exc: | |
| raise HTTPException(status_code=400, detail=str(exc)) from exc | |
| return QueryResponse(results=results, took_ms=(time.perf_counter() - started) * 1000) | |
| async def open_endpoint(request: OpenRequest) -> QueryResponse: | |
| started = time.perf_counter() | |
| if not request.docid and not request.url: | |
| raise HTTPException(status_code=400, detail="docid or url is required") | |
| result = open_document(get_connection(), docid=request.docid, url=request.url) | |
| if result is not None and result["docid"] in blocked_docids: | |
| result = None | |
| if result is None: | |
| lookup = request.docid or request.url or "" | |
| result = { | |
| "docid": request.docid or "", | |
| "url": request.url or "", | |
| "text": f"document not indexed: {lookup}", | |
| } | |
| else: | |
| title = result.pop("title", "").strip() | |
| result["text"] = f"{title}\n\n{result['text']}".strip() | |
| return QueryResponse(results=[result], took_ms=(time.perf_counter() - started) * 1000) | |
| async def health() -> dict[str, Any]: | |
| current = get_connection() | |
| indexed = fts_counts(current) | |
| return { | |
| "status": "healthy", | |
| "retrieval_mode": "sqlite_fts5_bm25_chunked", | |
| "indexed_documents": indexed["documents"], | |
| "indexed_chunks": indexed["chunks"], | |
| "blocked_documents": len(blocked_docids), | |
| } | |
| async def stats() -> dict[str, Any]: | |
| current = get_connection() | |
| indexed = fts_counts(current) | |
| return { | |
| "retrieval_mode": "sqlite_fts5_bm25_chunked", | |
| "indexed_documents": indexed["documents"], | |
| "indexed_chunks": indexed["chunks"], | |
| "fetch_status": status_counts(current), | |
| "blocked_documents": len(blocked_docids), | |
| } | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--database", type=Path, required=True) | |
| parser.add_argument("--host", default="0.0.0.0") | |
| parser.add_argument("--port", type=int, default=8011) | |
| args = parser.parse_args() | |
| os.environ["DEEPRESEARCH9K_CORPUS_DB"] = str(args.database.resolve()) | |
| uvicorn.run(app, host=args.host, port=args.port) | |
| if __name__ == "__main__": | |
| main() | |