File size: 1,085 Bytes
043267b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from __future__ import annotations

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from . import __version__
from .backends import Backend, get_backend
from .spec import ClassifyRequest, ClassifyResponse


def create_app(backend: Backend | None = None) -> FastAPI:
    app = FastAPI(title="X Addons classifier", version=__version__)
    # Only browser extensions (and local tools) may call this local service.
    app.add_middleware(
        CORSMiddleware,
        allow_origin_regex=r"^(chrome-extension|moz-extension|safari-web-extension)://.*$",
        allow_methods=["POST", "GET"],
        allow_headers=["content-type"],
    )
    app.state.backend = backend or get_backend("rules")

    @app.get("/health")
    async def health():
        return {"ok": True, "backend": app.state.backend.name, "version": __version__}

    @app.post("/v1/classify", response_model=ClassifyResponse)
    async def classify(req: ClassifyRequest):
        return ClassifyResponse(results=await app.state.backend.classify(req.labelset, req.posts))

    return app