Update Readme and cleanup

This commit is contained in:
Oliver Schütz authored and GitHub committed 2025-06-01 17:32:50 +02:00
1 parent 52d087ce90
commit b6789cb5f7
34 files changed
+104 -471

No files matched your search

@@ -3,18 +3,13 @@ import importlib
__all__ = []
# Iterate over all modules in this package
for finder, module_name, is_pkg in pkgutil.iter_modules(__path__):
# import the sub-module
module = importlib.import_module(f"{__name__}.{module_name}")
# decide which names to re-export:
# use module.__all__ if it exists, otherwise every non-private attribute
public_names = getattr(
module, "__all__", [n for n in dir(module) if not n.startswith("_")]
)
# bring each name into the package namespace
for name in public_names:
globals()[name] = getattr(module, name)
__all__.append(name) # type: ignore
@@ -1,6 +1,3 @@
# ------------------------------------------------------ #
# Workers have to be imported here to be discovered by the worker loader
# ------------------------------------------------------ #
from librarian_chunker.chunker import Chunker
from librarian_extractor.ai_sanitizer import AISanitizer
from librarian_extractor.extractor import Extractor
@@ -32,12 +32,9 @@ from atlas_librarian.stores.workers import WORKERS
router = APIRouter(tags=["recipes"])
# --------------------------------------------------------------------------- #
# Pydantic models #
# --------------------------------------------------------------------------- #
class RecipeRequest(BaseModel):
workers: List[str] = Field(min_length=1)
payload: dict # input of the first worker
payload: dict
class RecipeMetadata(BaseModel):
@@ -47,17 +44,11 @@ class RecipeMetadata(BaseModel):
flow_run_id: str | None = None
# in-memory “DB”
_RECIPES: dict[str, RecipeMetadata] = {}
# --------------------------------------------------------------------------- #
# routes #
# --------------------------------------------------------------------------- #
@router.post("/run", status_code=202, response_model=list[FlowArtifact])
def run_recipe(req: RecipeRequest) -> list[FlowArtifact]:
# validation of worker chain
for w in req.workers:
if w not in WORKERS:
raise HTTPException(400, f"Unknown worker: {w}")
@@ -71,7 +62,6 @@ def run_recipe(req: RecipeRequest) -> list[FlowArtifact]:
async def _run_worker(worker: type[Worker], art: FlowArtifact) -> FlowArtifact:
return await worker.flow()(art)
# Kick off the first worker
art: FlowArtifact = anyio.run(_run_worker, start_worker, FlowArtifact(data=payload, run_id=str(uuid.uuid4()), dir=Path(".")))
artifacts.append(art)
@@ -16,9 +16,6 @@ from pydantic import BaseModel
router = APIRouter(tags=["runs"])
# --------------------------------------------------------------------------- #
# response model #
# --------------------------------------------------------------------------- #
class RunInfo(BaseModel):
run_id: str
worker: str
@@ -27,9 +24,6 @@ class RunInfo(BaseModel):
data: dict | None = None
# --------------------------------------------------------------------------- #
# helper #
# --------------------------------------------------------------------------- #
def _open_store(run_id: str) -> WorkerStore:
try:
return WorkerStore.open(run_id)
@@ -37,16 +31,11 @@ def _open_store(run_id: str) -> WorkerStore:
raise HTTPException(status_code=404, detail="Run-id not found") from exc
# --------------------------------------------------------------------------- #
# routes #
# --------------------------------------------------------------------------- #
@router.get("/{run_id}", response_model=RunInfo)
def get_run(run_id: str) -> RunInfo:
"""
Return coarse-grained information about a single flow run.
For the web-UI we expose only minimal metadata plus the local directory
where files were written; clients can read further details from disk.
Returns coarse-grained info for a flow run, including local data directory.
Web UI uses this for minimal metadata display.
"""
store = _open_store(run_id)
meta = store.metadata # {'worker_name': …, 'state': …, …}
@@ -79,7 +68,6 @@ def get_latest_run(worker_name: str) -> RunInfo | None:
@router.get("/{run_id}/artifact")
def get_artifact(run_id: str) -> str:
store = _open_store(run_id)
# Check if the artifact.md file exists
if not store._run_dir.joinpath("artifact.md").exists():
raise HTTPException(status_code=404, detail="Artifact not found")
return store._run_dir.joinpath("artifact.md").read_text()
@@ -22,21 +22,15 @@ from atlas_librarian.stores.workers import WORKERS
router = APIRouter(tags=["workers"])
# --------------------------------------------------------------------------- #
# response schema #
# --------------------------------------------------------------------------- #
class Order(BaseModel):
order_id: str
worker_name: str
payload: dict
# Job is accepted and will be moved in the Job Pool
def accept(self):
_ORDER_POOL[self.order_id] = self
return self.order_id
# Job is completed and will be removed from the Job Pool
def complete(self):
del _ORDER_POOL[self.order_id]
@@ -44,9 +38,6 @@ class Order(BaseModel):
_ORDER_POOL: dict[str, Order] = {}
# --------------------------------------------------------------------------- #
# helpers #
# --------------------------------------------------------------------------- #
def _get_worker_or_404(name: str):
cls = WORKERS.get(name)
if cls is None:
@@ -60,13 +51,8 @@ def _get_artifact_from_payload(
run_id = payload.get("run_id") or None
input_data = cls.input_model.model_validate(payload["data"])
# Making sure the payload is valid
return FlowArtifact.new(data=input_data, dir=dir, run_id=run_id)
# --------------------------------------------------------------------------- #
# GET Routes #
# --------------------------------------------------------------------------- #
class WorkerMeta(BaseModel):
name: str
input: str
@@ -89,11 +75,6 @@ def list_orders() -> list[Order]:
return list(_ORDER_POOL.values())
# --------------------------------------------------------------------------- #
# POST Routes #
# --------------------------------------------------------------------------- #
# ---------- Submit and get the result ----------------------------------------
@router.post("/{worker_name}/submit", response_model=FlowArtifact, status_code=202)
def submit_worker(worker_name: str, payload: dict[str, Any]) -> FlowArtifact:
cls = _get_worker_or_404(worker_name)
@@ -108,7 +89,6 @@ def submit_worker(worker_name: str, payload: dict[str, Any]) -> FlowArtifact:
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Submit on existing run ----------------------------------------------
@router.post(
"/{worker_name}/submit/{prev_run_id}/chain",
response_model=FlowArtifact,
@@ -136,7 +116,6 @@ def submit_chain(worker_name: str, prev_run_id: str) -> FlowArtifact:
raise HTTPException(status_code=500, detail=str(e))
# Submit and chain, with the latest output of a worker
@router.post(
"/{worker_name}/submit/{prev_worker_name}/chain/latest",
response_model=FlowArtifact | None,
@@ -162,14 +141,12 @@ def submit_chain_latest(worker_name: str, prev_worker_name: str) -> FlowArtifact
return cls.submit(art)
# ---------- Place an Order and get a receipt ----------------------------------------------------
@router.post("/{worker_name}/order", response_model=Order, status_code=202)
def place_order(worker_name: str, payload: dict[str, Any]) -> Order:
cls = _get_worker_or_404(worker_name)
try:
art = _get_artifact_from_payload(payload, cls)
# order_id = str(uuid.uuid4())
order_id = "731ce6ef-ccdc-44bd-b152-da126f104db1"
order = Order(order_id=order_id, worker_name=worker_name, payload=art.model_dump())
order.accept()
@@ -1,4 +1,3 @@
# atlas_librarian/app.py
import logging
from fastapi import FastAPI
@@ -8,7 +7,6 @@ from librarian_core.utils.secrets_loader import load_env
from atlas_librarian.api import recipes_router, runs_router, worker_router
from atlas_librarian.stores import discover_workers
# Application description for OpenAPI docs
APP_DESCRIPTION = """
Atlas Librarian API Gateway 🚀
@@ -32,11 +30,10 @@ def create_app() -> FastAPI:
app = FastAPI(
title="Atlas Librarian API",
version="0.1.0", # Use semantic versioning
version="0.1.0",
description=APP_DESCRIPTION,
)
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
@@ -45,23 +42,18 @@ def create_app() -> FastAPI:
allow_headers=["*"],
)
# Include all API routers
app.include_router(worker_router, prefix=f"{API_PREFIX}/worker")
app.include_router(runs_router, prefix=f"{API_PREFIX}/runs")
app.include_router(recipes_router, prefix=f"{API_PREFIX}/recipes")
return app
# Create the app instance
app = create_app()
@app.get("/", tags=["Root"], summary="API Root/Health Check")
async def read_root():
"""
Provides a basic health check endpoint.
Returns a welcome message indicating the API is running.
"""
"""Basic health check endpoint."""
return {"message": "Welcome to Atlas Librarian API"}
@@ -71,14 +71,12 @@ recipes = [
# "download",
"extract",
],
# Default-Parameters
"parameters": {
"crawl": example_study_program,
"download": example_moodle_index,
"extract": example_downloaded_courses,
},
},
# All steps in one go
{
"name": "quick-all",
"steps": ["crawl", "download", "extract"],
@@ -1,4 +1,3 @@
# atlas_librarian/stores/worker_store.py
"""
Auto-discovers every third-party Worker package that exposes an entry-point
@@ -26,32 +25,24 @@ except ImportError: # Py < 3.10 → fall back to back-port
from librarian_core.workers.base import Worker
# --------------------------------------------------------------------------------------
WORKERS: Dict[str, Type[Worker]] = {} # key = Worker.worker_name
WORKERS: Dict[str, Type[Worker]] = {}
# --------------------------------------------------------------------------------------
def _register_worker_class(obj: object) -> None:
"""
Inspect *obj* and register it if it looks like a Worker subclass
produced by the metaclass in *librarian_core*.
"""
"""Registers valid Worker subclasses."""
if (
inspect.isclass(obj)
and issubclass(obj, Worker)
and obj is not Worker # not the abstract base
and obj is not Worker
):
WORKERS[obj.worker_name] = obj # type: ignore[arg-type]
# --------------------------------------------------------------------------------------
def _import_ep(ep: EntryPoint):
"""Load the object referenced by an entry-point."""
return ep.load()
# --------------------------------------------------------------------------------------
def discover_workers(group: str = "librarian.worker") -> None:
"""
Discover all entry-points of *group* and populate ``WORKERS``.
@@ -70,13 +61,11 @@ def discover_workers(group: str = "librarian.worker") -> None:
print(f"[Worker-Loader] Failed to load entry-point {ep!r}: {exc}")
continue
# If a module was loaded, inspect its attributes; else try registering directly
if isinstance(loaded, ModuleType):
for attr in loaded.__dict__.values():
_register_worker_class(attr)
else:
_register_worker_class(loaded)
# Register any Worker subclasses imported directly (e.g., loaded via atlas_librarian/api/__init__)
for cls in Worker.__subclasses__():
_register_worker_class(cls)