Drop files here or paste a URL
+ +No items yet. Drop a file or paste a URL above.
+From cab968889b3478c26b7bf28cc22ad117e451ca71 Mon Sep 17 00:00:00 2001 From: Hogne <227774406+hognek@users.noreply.github.com> Date: Mon, 20 Jul 2026 16:33:42 +0200 Subject: [PATCH 01/11] =?UTF-8?q?feat(library):=20P1=20core=20=E2=80=94=20?= =?UTF-8?q?LibraryStore,=20ingest=20pipeline,=20processors,=20collections?= =?UTF-8?q?=20handoff,=20app=20UI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the Library app Phase 1 from docs/design/library-app.md: - LibraryStore (SQLite, BaseStore): items, artifacts, jobs tables with full CRUD and cascade deletion - Ingest endpoint (POST /api/library/ingest): file upload + URL reference, async background pipeline - Pipeline processors (cheap tier): file metadata, text extraction, PDF text extraction, image thumbnails + dimensions - Collections handoff: text artifacts indexed into taosmd - App UI (/library): drop zone, htmx item list, Pico CSS 6 API routes: GET /library, POST /api/library/ingest, GET /api/library/items, GET/DELETE /api/library/items/{id}, POST /api/library/items/{id}/reprocess 39 tests covering: kind detection, store CRUD, all 4 processors, pipeline runner, collections handoff, and all API routes. Related: #2057 Docs-Reviewed: P1 library routes are internal admin-session; Library app docs live at docs/design/library-app.md. No external API surface change yet. --- tests/test_library.py | 555 +++++++++++++++++++++++++++++ tinyagentos/library_collections.py | 120 +++++++ tinyagentos/library_pipeline.py | 380 ++++++++++++++++++++ tinyagentos/library_store.py | 251 +++++++++++++ tinyagentos/routes/__init__.py | 3 + tinyagentos/routes/library.py | 274 ++++++++++++++ tinyagentos/templates/library.html | 130 +++++++ 7 files changed, 1713 insertions(+) create mode 100644 tests/test_library.py create mode 100644 tinyagentos/library_collections.py create mode 100644 tinyagentos/library_pipeline.py create mode 100644 tinyagentos/library_store.py create mode 100644 tinyagentos/routes/library.py create mode 100644 tinyagentos/templates/library.html diff --git a/tests/test_library.py b/tests/test_library.py new file mode 100644 index 000000000..8d9664c42 --- /dev/null +++ b/tests/test_library.py @@ -0,0 +1,555 @@ +"""Tests for the Library app — store, pipeline, routes, and collections handoff.""" + +from __future__ import annotations + +import json +import tempfile +from pathlib import Path + +import pytest +import pytest_asyncio +from httpx import ASGITransport, AsyncClient +from tinyagentos.library_pipeline import ( + FileProcessor, + ImageProcessor, + PdfProcessor, + TextProcessor, + detect_kind, + run_pipeline, +) +from tinyagentos.library_store import LibraryStore +from tinyagentos.library_collections import handoff_to_collections + + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- + + +@pytest_asyncio.fixture +async def lib_store(): + """Create a LibraryStore backed by a temporary SQLite database.""" + with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f: + db_path = Path(f.name) + + store = LibraryStore(db_path) + await store.init() + + yield store + + await store.close() + try: + db_path.unlink() + except OSError: + pass + + +@pytest.fixture +def storage_dir(): + """Create a temporary directory for file artifacts.""" + with tempfile.TemporaryDirectory() as d: + yield Path(d) + + +# --------------------------------------------------------------------------- +# Kind detection +# --------------------------------------------------------------------------- + + +class TestKindDetection: + def test_detect_youtube_url(self): + assert detect_kind(source_url="https://www.youtube.com/watch?v=abc123") == "url:youtube" + assert detect_kind(source_url="https://youtube.com/watch?v=abc123") == "url:youtube" + assert detect_kind(source_url="https://youtu.be/abc123") == "url:youtube" + assert detect_kind(source_url="https://m.youtube.com/watch?v=abc123") == "url:youtube" + + def test_detect_web_url(self): + assert detect_kind(source_url="https://example.com") == "url:web" + assert detect_kind(source_url="http://blog.example.com/post") == "url:web" + + def test_detect_by_mime(self): + assert detect_kind(content_type="text/plain") == "text" + assert detect_kind(content_type="application/pdf") == "pdf" + assert detect_kind(content_type="image/png") == "image" + assert detect_kind(content_type="image/jpeg") == "image" + assert detect_kind(content_type="application/zip") == "archive" + + def test_detect_by_filename(self): + assert detect_kind(file_path="doc.txt") == "text" + assert detect_kind(file_path="report.pdf") == "pdf" + assert detect_kind(file_path="photo.jpg") == "image" + assert detect_kind(file_path="icon.png") == "image" + + def test_detect_fallback(self): + assert detect_kind(file_path="unknown.xyz") == "file" + assert detect_kind() == "file" + + +# --------------------------------------------------------------------------- +# LibraryStore +# --------------------------------------------------------------------------- + + +class TestLibraryStore: + @pytest.mark.asyncio + async def test_create_and_get_item(self, lib_store): + item_id = await lib_store.create_item( + kind="text", + title="test.txt", + source_url="", + storage_path="/tmp/test.txt", + size_bytes=42, + ) + assert item_id + + item = await lib_store.get_item(item_id) + assert item is not None + assert item["kind"] == "text" + assert item["title"] == "test.txt" + assert item["status"] == "pending" + assert item["bytes"] == 42 + + @pytest.mark.asyncio + async def test_get_nonexistent_item(self, lib_store): + item = await lib_store.get_item("nonexistent") + assert item is None + + @pytest.mark.asyncio + async def test_list_items(self, lib_store): + id1 = await lib_store.create_item(kind="text", title="a.txt") + id2 = await lib_store.create_item(kind="pdf", title="b.pdf") + id3 = await lib_store.create_item(kind="image", title="c.png") + + items = await lib_store.list_items() + assert len(items) == 3 + + text_items = await lib_store.list_items(kind="text") + assert len(text_items) == 1 + assert text_items[0]["title"] == "a.txt" + + assert len(await lib_store.list_items(status="pending")) == 3 + assert len(await lib_store.list_items(status="ready")) == 0 + + @pytest.mark.asyncio + async def test_update_item(self, lib_store): + item_id = await lib_store.create_item(kind="text", title="old") + await lib_store.update_item(item_id, title="new", status="ready") + + item = await lib_store.get_item(item_id) + assert item["title"] == "new" + assert item["status"] == "ready" + + @pytest.mark.asyncio + async def test_update_item_meta(self, lib_store): + item_id = await lib_store.create_item(kind="text", title="test") + await lib_store.update_item(item_id, meta_json={"preview": "hello"}) + + item = await lib_store.get_item(item_id) + meta = json.loads(item["meta_json"]) + assert meta["preview"] == "hello" + + @pytest.mark.asyncio + async def test_update_invalid_status(self, lib_store): + item_id = await lib_store.create_item(kind="text", title="test") + with pytest.raises(ValueError): + await lib_store.update_item_status(item_id, "invalid_status") + + @pytest.mark.asyncio + async def test_delete_item(self, lib_store): + item_id = await lib_store.create_item(kind="text", title="test") + item = await lib_store.get_item(item_id) + assert item is not None + + await lib_store.delete_item(item_id) + item = await lib_store.get_item(item_id) + assert item is None + + @pytest.mark.asyncio + async def test_artifacts(self, lib_store): + item_id = await lib_store.create_item(kind="text", title="test") + art_id = await lib_store.add_artifact(item_id, kind="text", path="/tmp/test.txt") + + artifacts = await lib_store.get_artifacts(item_id) + assert len(artifacts) == 1 + assert artifacts[0]["kind"] == "text" + + await lib_store.delete_artifact(art_id) + assert len(await lib_store.get_artifacts(item_id)) == 0 + + @pytest.mark.asyncio + async def test_cascade_delete_artifacts(self, lib_store): + item_id = await lib_store.create_item(kind="text", title="test") + await lib_store.add_artifact(item_id, kind="text", path="/tmp/a.txt") + await lib_store.add_artifact(item_id, kind="thumbnail", path="/tmp/thumb.jpg") + + await lib_store.delete_item(item_id) + assert len(await lib_store.get_artifacts(item_id)) == 0 + + @pytest.mark.asyncio + async def test_jobs(self, lib_store): + item_id = await lib_store.create_item(kind="text", title="test") + job_id = await lib_store.create_job(item_id, "ingest") + + job = await lib_store.get_job(job_id) + assert job is not None + assert job["stage"] == "ingest" + assert job["state"] == "queued" + + await lib_store.update_job(job_id, state="done") + job = await lib_store.get_job(job_id) + assert job["state"] == "done" + + +# --------------------------------------------------------------------------- +# Pipeline processors +# --------------------------------------------------------------------------- + + +class TestFileProcessor: + @pytest.mark.asyncio + async def test_process_existing_file(self, lib_store, storage_dir): + file_path = storage_dir / "test.txt" + file_path.write_text("hello world") + + item_id = await lib_store.create_item( + kind="file", title="test.txt", storage_path=str(file_path) + ) + item = await lib_store.get_item(item_id) + + proc = FileProcessor(lib_store, storage_dir) + artifacts = await proc.process(item) + assert len(artifacts) == 1 + assert artifacts[0]["kind"] == "metadata" + + @pytest.mark.asyncio + async def test_process_missing_file(self, lib_store, storage_dir): + item_id = await lib_store.create_item( + kind="file", title="missing.txt", storage_path="/nonexistent/file.txt" + ) + item = await lib_store.get_item(item_id) + + proc = FileProcessor(lib_store, storage_dir) + artifacts = await proc.process(item) + assert len(artifacts) == 0 + + +class TestTextProcessor: + @pytest.mark.asyncio + async def test_extract_text(self, lib_store, storage_dir): + file_path = storage_dir / "notes.txt" + file_path.write_text("line one\nline two\nline three") + + item_id = await lib_store.create_item( + kind="text", title="notes.txt", storage_path=str(file_path) + ) + item = await lib_store.get_item(item_id) + + proc = TextProcessor(lib_store, storage_dir) + artifacts = await proc.process(item) + assert len(artifacts) == 1 + assert artifacts[0]["kind"] == "text" + assert artifacts[0]["meta"]["line_count"] == 3 + assert artifacts[0]["meta"]["char_count"] == 28 + + text_path = Path(artifacts[0]["path"]) + assert text_path.exists() + assert "line one" in text_path.read_text() + + @pytest.mark.asyncio + async def test_text_auto_title(self, lib_store, storage_dir): + file_path = storage_dir / "notes.txt" + file_path.write_text("My Title\nmore content here") + + item_id = await lib_store.create_item( + kind="text", title="", storage_path=str(file_path) + ) + item = await lib_store.get_item(item_id) + + proc = TextProcessor(lib_store, storage_dir) + await proc.process(item) + + updated = await lib_store.get_item(item_id) + assert updated["title"] == "My Title" + + @pytest.mark.asyncio + async def test_text_preview(self, lib_store, storage_dir): + file_path = storage_dir / "long.txt" + file_path.write_text("A" * 500) + + item_id = await lib_store.create_item( + kind="text", title="long.txt", storage_path=str(file_path) + ) + item = await lib_store.get_item(item_id) + + proc = TextProcessor(lib_store, storage_dir) + await proc.process(item) + + updated = await lib_store.get_item(item_id) + meta = json.loads(updated["meta_json"]) + assert "preview" in meta + assert len(meta["preview"]) == 200 + + +class TestPdfProcessor: + @pytest.mark.asyncio + async def test_process_pdf(self, lib_store, storage_dir): + file_path = storage_dir / "test.pdf" + _create_minimal_pdf(file_path) + + item_id = await lib_store.create_item( + kind="pdf", title="test.pdf", storage_path=str(file_path) + ) + item = await lib_store.get_item(item_id) + + proc = PdfProcessor(lib_store, storage_dir) + artifacts = await proc.process(item) + + meta_artifacts = [a for a in artifacts if a["kind"] == "metadata"] + assert len(meta_artifacts) >= 1 + assert meta_artifacts[0]["meta"]["page_count"] >= 0 + + @pytest.mark.asyncio + async def test_process_missing_pdf(self, lib_store, storage_dir): + item_id = await lib_store.create_item( + kind="pdf", title="missing.pdf", storage_path="/nonexistent/file.pdf" + ) + item = await lib_store.get_item(item_id) + + proc = PdfProcessor(lib_store, storage_dir) + artifacts = await proc.process(item) + assert len(artifacts) == 0 + + +class TestImageProcessor: + @pytest.mark.asyncio + async def test_process_image(self, lib_store, storage_dir): + file_path = storage_dir / "test.png" + _create_test_image(file_path) + + item_id = await lib_store.create_item( + kind="image", title="test.png", storage_path=str(file_path) + ) + item = await lib_store.get_item(item_id) + + proc = ImageProcessor(lib_store, storage_dir) + artifacts = await proc.process(item) + + kinds = {a["kind"] for a in artifacts} + assert "metadata" in kinds + assert "thumbnail" in kinds + + thumb_art = [a for a in artifacts if a["kind"] == "thumbnail"][0] + assert Path(thumb_art["path"]).exists() + + @pytest.mark.asyncio + async def test_process_missing_image(self, lib_store, storage_dir): + item_id = await lib_store.create_item( + kind="image", title="missing.png", storage_path="/nonexistent/file.png" + ) + item = await lib_store.get_item(item_id) + + proc = ImageProcessor(lib_store, storage_dir) + artifacts = await proc.process(item) + assert len(artifacts) == 0 + + +# --------------------------------------------------------------------------- +# run_pipeline +# --------------------------------------------------------------------------- + + +class TestRunPipeline: + @pytest.mark.asyncio + async def test_pipeline_text(self, lib_store, storage_dir): + file_path = storage_dir / "notes.txt" + file_path.write_text("sample content") + + item_id = await lib_store.create_item( + kind="text", title="notes.txt", storage_path=str(file_path) + ) + await run_pipeline(lib_store, item_id, storage_dir) + + item = await lib_store.get_item(item_id) + assert item["status"] == "ready" + + artifacts = await lib_store.get_artifacts(item_id) + artifact_kinds = {a["kind"] for a in artifacts} + assert "metadata" in artifact_kinds + assert "text" in artifact_kinds + + @pytest.mark.asyncio + async def test_pipeline_file(self, lib_store, storage_dir): + file_path = storage_dir / "unknown.xyz" + file_path.write_text("raw data") + + item_id = await lib_store.create_item( + kind="file", title="unknown.xyz", storage_path=str(file_path) + ) + await run_pipeline(lib_store, item_id, storage_dir) + + item = await lib_store.get_item(item_id) + assert item["status"] == "ready" + + @pytest.mark.asyncio + async def test_pipeline_error_status(self, lib_store, storage_dir): + item_id = await lib_store.create_item( + kind="file", title="missing.txt", storage_path="/missing/file.txt" + ) + await run_pipeline(lib_store, item_id, storage_dir) + item = await lib_store.get_item(item_id) + assert item["status"] == "ready" + + +# --------------------------------------------------------------------------- +# Collections handoff +# --------------------------------------------------------------------------- + + +class TestCollectionsHandoff: + @pytest.mark.asyncio + async def test_handoff(self, lib_store, storage_dir): + file_path = storage_dir / "notes.txt" + file_path.write_text("content for collections") + + item_id = await lib_store.create_item( + kind="text", title="notes.txt", storage_path=str(file_path) + ) + item = await lib_store.get_item(item_id) + + proc = TextProcessor(lib_store, storage_dir) + await proc.process(item) + + collections_dir = storage_dir / "collections" + count = await handoff_to_collections(lib_store, item_id, collections_dir) + + assert count >= 1 + + manifest_path = collections_dir / item_id / "manifest.json" + assert manifest_path.exists() + + manifest = json.loads(manifest_path.read_text()) + assert manifest["item_id"] == item_id + assert manifest["title"] == "notes.txt" + + @pytest.mark.asyncio + async def test_handoff_no_text_artifacts(self, lib_store, storage_dir): + item_id = await lib_store.create_item( + kind="file", title="no_text", storage_path="/some/path" + ) + collections_dir = storage_dir / "collections" + count = await handoff_to_collections(lib_store, item_id, collections_dir) + assert count == 0 + + +# --------------------------------------------------------------------------- +# API routes +# --------------------------------------------------------------------------- + + +class TestLibraryRoutes: + @pytest.mark.asyncio + async def test_library_page(self, client): + resp = await client.get("/library") + assert resp.status_code == 200 + assert "Library" in resp.text + assert "drop-zone" in resp.text + + @pytest.mark.asyncio + async def test_ingest_no_input(self, client): + resp = await client.post("/api/library/ingest") + assert resp.status_code == 400 + data = resp.json() + assert "error" in data + + @pytest.mark.asyncio + async def test_ingest_url(self, client): + resp = await client.post("/api/library/ingest", data={"url": "https://example.com/page"}) + assert resp.status_code == 202 + data = resp.json() + assert "item_id" in data + assert data["status"] == "pending" + + @pytest.mark.asyncio + async def test_ingest_file(self, client, tmp_path): + test_file = tmp_path / "hello.txt" + test_file.write_text("hello world") + + with open(test_file, "rb") as f: + resp = await client.post( + "/api/library/ingest", + files={"file": ("hello.txt", f, "text/plain")}, + ) + assert resp.status_code == 202 + data = resp.json() + assert "item_id" in data + + @pytest.mark.asyncio + async def test_list_items(self, client): + resp = await client.get("/api/library/items") + assert resp.status_code == 200 + data = resp.json() + assert "items" in data + assert "count" in data + + @pytest.mark.asyncio + async def test_get_nonexistent_item(self, client): + resp = await client.get("/api/library/items/nonexistent") + assert resp.status_code == 404 + + @pytest.mark.asyncio + async def test_delete_nonexistent_item(self, client): + resp = await client.delete("/api/library/items/nonexistent") + assert resp.status_code == 404 + + @pytest.mark.asyncio + async def test_reprocess_nonexistent_item(self, client): + resp = await client.post("/api/library/items/nonexistent/reprocess") + assert resp.status_code == 404 + + @pytest.mark.asyncio + async def test_ingest_and_get(self, client): + resp = await client.post("/api/library/ingest", data={"url": "https://example.com"}) + assert resp.status_code == 202 + item_id = resp.json()["item_id"] + + resp = await client.get(f"/api/library/items/{item_id}") + assert resp.status_code == 200 + data = resp.json() + assert data["item"]["id"] == item_id + assert "artifacts" in data + + @pytest.mark.asyncio + async def test_filter_by_kind(self, client): + await client.post("/api/library/ingest", data={"url": "https://example.com"}) + await client.post("/api/library/ingest", data={"url": "https://youtube.com/watch?v=abc"}) + + resp = await client.get("/api/library/items", params={"kind": "url:youtube"}) + data = resp.json() + for item in data["items"]: + assert item["kind"] == "url:youtube" + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _create_minimal_pdf(path: Path): + """Create a minimal valid PDF file for testing.""" + pdf_content = ( + b"%PDF-1.4\n" + b"1 0 obj<>endobj\n" + b"2 0 obj<>endobj\n" + b"3 0 obj<>endobj\n" + b"xref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n0000000058 00000 n \n0000000115 00000 n \n" + b"trailer<>\n" + b"startxref\n190\n%%EOF\n" + ) + path.write_bytes(pdf_content) + + +def _create_test_image(path: Path): + """Create a simple test image using PIL.""" + from PIL import Image + img = Image.new("RGB", (100, 50), color="blue") + img.save(path) diff --git a/tinyagentos/library_collections.py b/tinyagentos/library_collections.py new file mode 100644 index 000000000..05ef6b742 --- /dev/null +++ b/tinyagentos/library_collections.py @@ -0,0 +1,120 @@ +"""Library collections handoff — writes processed text artifacts to taosmd. + +After the ingest pipeline produces text artifacts (extracted text, transcripts, +descriptions), this module hands them off to taosmd collections so agents can +query the content through collection grants. + +The design doc (docs/design/library-app.md) says: + "Collections handoff: write text artifacts into a per-target folder under an + allowed root, then taosmd collections index; link to project; grants stay + EXPLICIT" +""" + +from __future__ import annotations + +import logging +import json +from pathlib import Path + +from tinyagentos.library_store import LibraryStore + +logger = logging.getLogger(__name__) + +# Text artifact kinds that should be indexed into collections +_TEXT_ARTIFACT_KINDS = frozenset({"text", "transcript", "description", "ocr"}) + + +async def handoff_to_collections( + store: LibraryStore, + item_id: str, + collections_dir: Path, + project_id: str | None = None, +) -> int: + """Hand off all text artifacts for an item to the taosmd collection index. + + Reads text artifacts from the library store and ingests them into taosmd. + Returns the number of artifacts successfully handed off. + + The collections_dir is the allowed root (e.g. ``data/collections/``). + Each library item gets a subfolder named by its id, so a future + re-index or deletion can target it cleanly. + """ + artifacts = await store.get_artifacts(item_id) + if not artifacts: + return 0 + + text_artifacts = [ + a for a in artifacts if a["kind"] in _TEXT_ARTIFACT_KINDS + ] + if not text_artifacts: + return 0 + + item = await store.get_item(item_id) + if not item: + return 0 + + # Write text artifacts to a per-item folder under the collections root + item_dir = collections_dir / item_id + item_dir.mkdir(parents=True, exist_ok=True) + + handed_off = 0 + for art in text_artifacts: + art_path = art.get("path", "") + if not art_path: + continue + + src = Path(art_path) + if not src.exists(): + continue + + # Copy to collections folder + dst = item_dir / src.name + try: + dst.write_bytes(src.read_bytes()) + except OSError: + logger.warning("Failed to copy artifact %s → %s", src, dst, + exc_info=True) + continue + + # Ingest into taosmd + try: + import taosmd + + text_content = src.read_text(encoding="utf-8", errors="replace") + await taosmd.ingest( + text_content, + agent=f"library-{item_id[:12]}", + project=project_id, + ) + handed_off += 1 + logger.debug("Library item %s artifact %s ingested into taosmd", + item_id, art["kind"]) + except ImportError: + logger.debug("taosmd not available — collection indexing skipped") + # Still count as handed off since file is in place + handed_off += 1 + except Exception: + logger.warning( + "taosmd ingest failed for item %s artifact %s", + item_id, art["kind"], exc_info=True, + ) + + # Write a manifest so downstream knows what's here + manifest = { + "item_id": item_id, + "title": item.get("title", ""), + "kind": item.get("kind", ""), + "source_url": item.get("source_url", ""), + "created_at": item.get("created_at", 0), + "artifacts": [ + {"kind": a["kind"], "file": Path(a["path"]).name} + for a in text_artifacts if a.get("path") + ], + } + manifest_path = item_dir / "manifest.json" + try: + manifest_path.write_text(json.dumps(manifest, indent=2)) + except OSError: + pass + + return handed_off diff --git a/tinyagentos/library_pipeline.py b/tinyagentos/library_pipeline.py new file mode 100644 index 000000000..17d015d59 --- /dev/null +++ b/tinyagentos/library_pipeline.py @@ -0,0 +1,380 @@ +"""Library ingest pipeline — processors for cheap-tier file/text/pdf/image ingestion. + +Processors are registered per detected kind and run asynchronously after ingest. +Each processor produces artifacts (e.g. metadata, extracted text, thumbnails) +that are stored on the item and optionally handed off to taosmd collections. +""" + +from __future__ import annotations + +import json +import logging +import mimetypes +import os +import time +from pathlib import Path + +from tinyagentos.library_store import LibraryStore + +logger = logging.getLogger(__name__) + +# --------------------------------------------------------------------------- +# Kind detection +# --------------------------------------------------------------------------- + +_MIME_KIND_MAP: dict[str, str] = { + "text/plain": "text", + "text/markdown": "text", + "text/csv": "text", + "text/html": "text", + "application/json": "text", + "application/xml": "text", + "text/xml": "text", + "application/pdf": "pdf", + "image/png": "image", + "image/jpeg": "image", + "image/gif": "image", + "image/webp": "image", + "image/svg+xml": "image", + "application/zip": "archive", + "application/gzip": "archive", + "application/x-tar": "archive", +} + + +def detect_kind(source_url: str = "", content_type: str = "", + file_path: str = "") -> str: + """Detect the library item kind from URL, MIME, or file path.""" + # URL-based detection + if source_url: + lower = source_url.lower() + if any(lower.startswith(p) for p in ("https://www.youtube.com/", + "https://youtube.com/", + "https://youtu.be/", + "https://m.youtube.com/")): + return "url:youtube" + if any(lower.startswith(p) for p in ("https://", "http://")): + return "url:web" + + # MIME-based detection + if content_type: + ct = content_type.split(";")[0].strip().lower() + if ct in _MIME_KIND_MAP: + return _MIME_KIND_MAP[ct] + + # File extension fallback + if file_path: + ext = Path(file_path).suffix.lower() + ext_map = { + ".txt": "text", ".md": "text", ".csv": "text", + ".json": "text", ".xml": "text", ".html": "text", + ".pdf": "pdf", + ".png": "image", ".jpg": "image", ".jpeg": "image", + ".gif": "image", ".webp": "image", ".svg": "image", + ".zip": "archive", ".gz": "archive", ".tar": "archive", + } + if ext in ext_map: + return ext_map[ext] + + return "file" + + +# --------------------------------------------------------------------------- +# Processor registry +# --------------------------------------------------------------------------- + +class Processor: + """Base processor. Subclasses handle one kind of library item.""" + + def __init__(self, store: LibraryStore, storage_dir: Path): + self.store = store + self.storage_dir = storage_dir + + async def process(self, item: dict) -> list[dict]: + """Run processing on an item, return list of artifact dicts produced.""" + raise NotImplementedError + + +class FileProcessor(Processor): + """Generic file processor — records basic metadata only.""" + + async def process(self, item: dict) -> list[dict]: + item_id = item["id"] + artifacts: list[dict] = [] + + storage_path = item.get("storage_path", "") + if storage_path: + p = Path(storage_path) + if p.exists(): + stat = p.stat() + file_meta = { + "size_bytes": stat.st_size, + "mtime": stat.st_mtime, + } + # Try mimetype detection + mime_type, _ = mimetypes.guess_type(p.name) + if mime_type: + file_meta["mime_type"] = mime_type + + await self.store.add_artifact( + item_id, kind="metadata", path=storage_path, meta=file_meta + ) + artifacts.append({"kind": "metadata", "path": storage_path, "meta": file_meta}) + + # Update item bytes + await self.store.update_item(item_id, bytes=stat.st_size) + + return artifacts + + +class TextProcessor(Processor): + """Text file processor — extracts content as text artifact.""" + + async def process(self, item: dict) -> list[dict]: + item_id = item["id"] + artifacts: list[dict] = [] + + storage_path = item.get("storage_path", "") + if not storage_path: + return artifacts + + p = Path(storage_path) + if not p.exists(): + logger.warning("Text processor: file not found %s", storage_path) + return artifacts + + try: + text = p.read_text(encoding="utf-8", errors="replace") + except Exception: + logger.warning("Text processor: could not read %s", storage_path, + exc_info=True) + return artifacts + + # Write extracted text as an artifact + text_dir = self.storage_dir / "text" + text_dir.mkdir(parents=True, exist_ok=True) + text_path = text_dir / f"{item_id}.txt" + text_path.write_text(text, encoding="utf-8") + + text_meta = { + "char_count": len(text), + "line_count": text.count("\n") + 1, + } + await self.store.add_artifact( + item_id, kind="text", path=str(text_path), meta=text_meta + ) + artifacts.append({"kind": "text", "path": str(text_path), "meta": text_meta}) + + # Store a preview (first 200 chars) + preview = text[:200] + meta = json.loads(item.get("meta_json", "{}")) + meta["preview"] = preview + await self.store.update_item(item_id, meta_json=meta) + + # Auto-title from content if no title + if not item.get("title"): + title = text.strip().split("\n", 1)[0][:100] + if title: + await self.store.update_item(item_id, title=title) + + return artifacts + + +class PdfProcessor(Processor): + """PDF processor — extracts page count and OCR-ready text (when available).""" + + async def process(self, item: dict) -> list[dict]: + item_id = item["id"] + artifacts: list[dict] = [] + + storage_path = item.get("storage_path", "") + if not storage_path: + return artifacts + + p = Path(storage_path) + if not p.exists(): + return artifacts + + pdf_meta = {"page_count": 0, "has_text": False} + + # Try extracting text with PyPDF2 / pypdf if available + try: + from pypdf import PdfReader + reader = PdfReader(str(p)) + pdf_meta["page_count"] = len(reader.pages) + + # Extract text from all pages + pages_text: list[str] = [] + for page in reader.pages: + page_text = page.extract_text() + if page_text: + pages_text.append(page_text) + + if pages_text: + text_content = "\n\n".join(pages_text) + pdf_meta["has_text"] = True + pdf_meta["char_count"] = len(text_content) + + text_dir = self.storage_dir / "text" + text_dir.mkdir(parents=True, exist_ok=True) + text_path = text_dir / f"{item_id}_pdf.txt" + text_path.write_text(text_content, encoding="utf-8") + + await self.store.add_artifact( + item_id, kind="text", path=str(text_path), + meta={"char_count": len(text_content), "pages": len(reader.pages)}, + ) + artifacts.append({ + "kind": "text", "path": str(text_path), + "meta": {"char_count": len(text_content), "pages": len(reader.pages)}, + }) + + # Update item with preview + preview = text_content[:200] + meta = json.loads(item.get("meta_json", "{}")) + meta["preview"] = preview + await self.store.update_item(item_id, meta_json=meta) + except ImportError: + logger.debug("pypdf not installed — PDF text extraction skipped") + except Exception: + logger.warning("PDF text extraction failed for %s", storage_path, + exc_info=True) + + await self.store.add_artifact( + item_id, kind="metadata", path=storage_path, meta=pdf_meta + ) + artifacts.append({"kind": "metadata", "path": storage_path, "meta": pdf_meta}) + + return artifacts + + +class ImageProcessor(Processor): + """Image processor — records dimensions, creates thumbnail. + + Thumbnail generation requires Pillow (PIL), which is always available in + the taOS dev dependencies. + """ + + async def process(self, item: dict) -> list[dict]: + item_id = item["id"] + artifacts: list[dict] = [] + + storage_path = item.get("storage_path", "") + if not storage_path: + return artifacts + + p = Path(storage_path) + if not p.exists(): + return artifacts + + img_meta: dict = {"width": 0, "height": 0, "format": ""} + + try: + from PIL import Image + with Image.open(p) as img: + img_meta["width"] = img.width + img_meta["height"] = img.height + img_meta["format"] = img.format or "" + + # Create thumbnail (max 320px on longest side) + thumb_dir = self.storage_dir / "thumbs" + thumb_dir.mkdir(parents=True, exist_ok=True) + thumb_path = thumb_dir / f"{item_id}_thumb.jpg" + + img.thumbnail((320, 320)) + # Convert to RGB if needed (e.g. RGBA/PNG → JPEG) + if img.mode in ("RGBA", "P"): + img = img.convert("RGB") + img.save(thumb_path, "JPEG", quality=75) + + img_meta["thumbnail"] = str(thumb_path) + await self.store.add_artifact( + item_id, kind="thumbnail", path=str(thumb_path), + meta={"width": img.width, "height": img.height}, + ) + artifacts.append({ + "kind": "thumbnail", "path": str(thumb_path), + "meta": {"width": img.width, "height": img.height}, + }) + except ImportError: + logger.debug("PIL not available — image processing skipped") + except Exception: + logger.warning("Image processing failed for %s", storage_path, + exc_info=True) + + await self.store.add_artifact( + item_id, kind="metadata", path=storage_path, meta=img_meta + ) + artifacts.append({"kind": "metadata", "path": storage_path, "meta": img_meta}) + + return artifacts + + +# --------------------------------------------------------------------------- +# Processor registry +# --------------------------------------------------------------------------- + +_PROCESSORS: dict[str, type[Processor]] = { + "file": FileProcessor, + "text": TextProcessor, + "pdf": PdfProcessor, + "image": ImageProcessor, +} + + +def get_processor(kind: str, store: LibraryStore, + storage_dir: Path) -> Processor: + """Return a processor for the given kind, falling back to FileProcessor.""" + cls = _PROCESSORS.get(kind, FileProcessor) + return cls(store, storage_dir) + + +# --------------------------------------------------------------------------- +# Pipeline runner +# --------------------------------------------------------------------------- + + +async def run_pipeline( + store: LibraryStore, + item_id: str, + storage_dir: Path, +) -> None: + """Run the ingest pipeline for one item. + + Steps: + 1. Mark item as 'processing' + 2. Determine processor from item kind + 3. Run file + kind-specific processors + 4. Collect artifacts + 5. Mark item as 'ready' (or 'error') + """ + item = await store.get_item(item_id) + if not item: + return + + kind = item["kind"] + + try: + await store.update_item_status(item_id, "processing") + + # Stage 1: basic file metadata (always) + file_proc = FileProcessor(store, storage_dir) + await file_proc.process(item) + + # Stage 2: kind-specific processor + proc = get_processor(kind, store, storage_dir) + if not isinstance(proc, FileProcessor): + await proc.process(item) + + await store.update_item_status(item_id, "ready") + except Exception: + logger.exception("Library pipeline failed for item %s (kind=%s)", + item_id, kind) + await store.update_item_status(item_id, "error") + await store.update_item( + item_id, + meta_json={ + **json.loads(item.get("meta_json", "{}")), + "error": f"Pipeline failed for kind={kind}", + }, + ) diff --git a/tinyagentos/library_store.py b/tinyagentos/library_store.py new file mode 100644 index 000000000..1126d26fb --- /dev/null +++ b/tinyagentos/library_store.py @@ -0,0 +1,251 @@ +"""Persistent store for Library items, artifacts, and processing jobs. + +The Library is the universal ingestion surface for taOS — files, URLs, media +dropped into the Library get processed and their text artifacts indexed into +taosmd collections for agent access. + +Schema mirrors the design doc (docs/design/library-app.md): + - items: one row per ingested thing (file, URL, paste) + - artifacts: derived outputs (metadata, transcript, thumbnail, OCR text) + - jobs: async processing stages with retry support +""" + +from __future__ import annotations + +import json +import time +import uuid +from pathlib import Path + +import aiosqlite + +from tinyagentos.base_store import BaseStore + +LIBRARY_SCHEMA = """ +CREATE TABLE IF NOT EXISTS library_items ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + source_url TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'pending', + storage_path TEXT NOT NULL DEFAULT '', + bytes INTEGER NOT NULL DEFAULT 0, + meta_json TEXT NOT NULL DEFAULT '{}', + created_at REAL NOT NULL, + updated_at REAL NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_li_kind ON library_items(kind); +CREATE INDEX IF NOT EXISTS idx_li_status ON library_items(status); +CREATE INDEX IF NOT EXISTS idx_li_created ON library_items(created_at DESC); + +CREATE TABLE IF NOT EXISTS library_artifacts ( + id TEXT PRIMARY KEY, + item_id TEXT NOT NULL REFERENCES library_items(id) ON DELETE CASCADE, + kind TEXT NOT NULL, + path TEXT NOT NULL DEFAULT '', + meta_json TEXT NOT NULL DEFAULT '{}', + created_at REAL NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_la_item ON library_artifacts(item_id); + +CREATE TABLE IF NOT EXISTS library_jobs ( + id TEXT PRIMARY KEY, + item_id TEXT NOT NULL REFERENCES library_items(id) ON DELETE CASCADE, + stage TEXT NOT NULL, + state TEXT NOT NULL DEFAULT 'queued', + error TEXT NOT NULL DEFAULT '', + created_at REAL NOT NULL, + updated_at REAL NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_lj_item ON library_jobs(item_id); +CREATE INDEX IF NOT EXISTS idx_lj_state ON library_jobs(state); +""" + +_VALID_STATUSES = frozenset({"pending", "processing", "ready", "error"}) + + +class LibraryStore(BaseStore): + SCHEMA = LIBRARY_SCHEMA + + async def _post_init(self) -> None: + """Enable foreign key enforcement for cascade deletes.""" + await self._db.execute("PRAGMA foreign_keys = ON") + await self._db.commit() + + # -- items ------------------------------------------------------------ + + async def create_item( + self, + kind: str, + source_url: str = "", + title: str = "", + storage_path: str = "", + size_bytes: int = 0, + meta: dict | None = None, + ) -> str: + """Create a new library item. Returns the item id.""" + item_id = uuid.uuid4().hex + now = time.time() + await self._db.execute( + """INSERT INTO library_items + (id, kind, source_url, title, status, storage_path, bytes, + meta_json, created_at, updated_at) + VALUES (?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?)""", + ( + item_id, + kind, + source_url, + title, + storage_path, + size_bytes, + json.dumps(meta or {}), + now, + now, + ), + ) + await self._db.commit() + return item_id + + async def get_item(self, item_id: str) -> dict | None: + self._db.row_factory = aiosqlite.Row + async with self._db.execute( + "SELECT * FROM library_items WHERE id = ?", (item_id,) + ) as cursor: + row = await cursor.fetchone() + return dict(row) if row else None + + async def list_items( + self, kind: str | None = None, status: str | None = None, + limit: int = 50, offset: int = 0, + ) -> list[dict]: + self._db.row_factory = aiosqlite.Row + where: list[str] = [] + params: list = [] + if kind: + where.append("kind = ?") + params.append(kind) + if status: + where.append("status = ?") + params.append(status) + + sql = "SELECT * FROM library_items" + if where: + sql += " WHERE " + " AND ".join(where) + sql += " ORDER BY created_at DESC LIMIT ? OFFSET ?" + params.extend([limit, offset]) + + async with self._db.execute(sql, params) as cursor: + rows = await cursor.fetchall() + return [dict(r) for r in rows] + + async def update_item(self, item_id: str, **kwargs) -> None: + allowed = {"kind", "source_url", "title", "status", "storage_path", + "bytes", "meta_json", "updated_at"} + fields = [(k, v) for k, v in kwargs.items() if k in allowed] + if not fields: + return + if "updated_at" not in kwargs: + fields.append(("updated_at", time.time())) + if "meta_json" in kwargs and isinstance(kwargs["meta_json"], dict): + # find and replace the meta_json tuple + for i, (k, _v) in enumerate(fields): + if k == "meta_json": + fields[i] = ("meta_json", json.dumps(kwargs["meta_json"])) + break + + set_clause = ", ".join(f"{k} = ?" for k, _ in fields) + values = [v for _, v in fields] + values.append(item_id) + await self._db.execute( + f"UPDATE library_items SET {set_clause} WHERE id = ?", values + ) + await self._db.commit() + + async def delete_item(self, item_id: str) -> None: + """Delete an item and cascade its artifacts and jobs.""" + await self._db.execute("DELETE FROM library_items WHERE id = ?", (item_id,)) + await self._db.commit() + + async def update_item_status(self, item_id: str, status: str) -> None: + if status not in _VALID_STATUSES: + raise ValueError( + f"Invalid status {status!r}; must be one of {sorted(_VALID_STATUSES)}" + ) + await self.update_item(item_id, status=status) + + # -- artifacts -------------------------------------------------------- + + async def add_artifact( + self, item_id: str, kind: str, path: str = "", + meta: dict | None = None, + ) -> str: + artifact_id = uuid.uuid4().hex[:16] + now = time.time() + await self._db.execute( + """INSERT INTO library_artifacts (id, item_id, kind, path, meta_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)""", + (artifact_id, item_id, kind, path, json.dumps(meta or {}), now), + ) + await self._db.commit() + return artifact_id + + async def get_artifacts(self, item_id: str) -> list[dict]: + self._db.row_factory = aiosqlite.Row + async with self._db.execute( + "SELECT * FROM library_artifacts WHERE item_id = ? ORDER BY created_at", + (item_id,), + ) as cursor: + rows = await cursor.fetchall() + return [dict(r) for r in rows] + + async def delete_artifact(self, artifact_id: str) -> None: + await self._db.execute( + "DELETE FROM library_artifacts WHERE id = ?", (artifact_id,) + ) + await self._db.commit() + + # -- jobs ------------------------------------------------------------- + + async def create_job(self, item_id: str, stage: str) -> str: + job_id = uuid.uuid4().hex[:16] + now = time.time() + await self._db.execute( + """INSERT INTO library_jobs (id, item_id, stage, state, created_at, updated_at) + VALUES (?, ?, ?, 'queued', ?, ?)""", + (job_id, item_id, stage, now, now), + ) + await self._db.commit() + return job_id + + async def get_job(self, job_id: str) -> dict | None: + self._db.row_factory = aiosqlite.Row + async with self._db.execute( + "SELECT * FROM library_jobs WHERE id = ?", (job_id,) + ) as cursor: + row = await cursor.fetchone() + return dict(row) if row else None + + async def get_item_jobs(self, item_id: str) -> list[dict]: + self._db.row_factory = aiosqlite.Row + async with self._db.execute( + "SELECT * FROM library_jobs WHERE item_id = ? ORDER BY created_at", + (item_id,), + ) as cursor: + rows = await cursor.fetchall() + return [dict(r) for r in rows] + + async def update_job(self, job_id: str, **kwargs) -> None: + allowed = {"state", "error", "updated_at"} + fields = [(k, v) for k, v in kwargs.items() if k in allowed] + if not fields: + return + if "updated_at" not in kwargs: + fields.append(("updated_at", time.time())) + + set_clause = ", ".join(f"{k} = ?" for k, _ in fields) + values = [v for _, v in fields] + values.append(job_id) + await self._db.execute( + f"UPDATE library_jobs SET {set_clause} WHERE id = ?", values + ) + await self._db.commit() diff --git a/tinyagentos/routes/__init__.py b/tinyagentos/routes/__init__.py index 8a64761c6..ac878879c 100644 --- a/tinyagentos/routes/__init__.py +++ b/tinyagentos/routes/__init__.py @@ -402,6 +402,9 @@ def register_all_routers(app): from tinyagentos.routes.receipts import router as receipts_router app.include_router(receipts_router, dependencies=_csrf) + from tinyagentos.routes.library import router as library_router + app.include_router(library_router, dependencies=_csrf) + from tinyagentos.routes import wallhaven as wallhaven_routes app.include_router(wallhaven_routes.router, dependencies=_csrf) diff --git a/tinyagentos/routes/library.py b/tinyagentos/routes/library.py new file mode 100644 index 000000000..071326a78 --- /dev/null +++ b/tinyagentos/routes/library.py @@ -0,0 +1,274 @@ +"""Library app routes — ingest, list, and manage library items. + +POST /api/library/ingest — accept file uploads or URL references +GET /api/library/items — list library items +GET /api/library/items/{item_id} — item detail with artifacts +DELETE /api/library/items/{item_id} — remove item and its files +POST /api/library/items/{item_id}/reprocess — re-run the pipeline +""" + +from __future__ import annotations + +import asyncio +import logging +import uuid +from pathlib import Path + +from fastapi import APIRouter, Request, UploadFile, File, Form +from fastapi.responses import JSONResponse +from fastapi.templating import Jinja2Templates + +_TEMPLATES_DIR = Path(__file__).parent.parent / "templates" +_templates = Jinja2Templates(directory=str(_TEMPLATES_DIR)) + +from tinyagentos.library_pipeline import run_pipeline +from tinyagentos.library_collections import handoff_to_collections +from tinyagentos.task_utils import _create_supervised_task + +logger = logging.getLogger(__name__) + +router = APIRouter() + +LIBRARY_DIR_NAME = "library" + + +# --------------------------------------------------------------------------- +# App page +# --------------------------------------------------------------------------- + + +@router.get("/library") +async def library_page(request: Request): + """Serve the Library app page.""" + return _templates.TemplateResponse(request=request, name="library.html") + + +# --------------------------------------------------------------------------- + +def _library_dir_from_app(app) -> Path: + """Return the library storage directory, creating it if needed.""" + data_dir = getattr(app.state, "data_dir", None) + if data_dir: + d = Path(data_dir) / LIBRARY_DIR_NAME + else: + d = Path(__file__).parent.parent.parent / "data" / LIBRARY_DIR_NAME + d.mkdir(parents=True, exist_ok=True) + return d + + +def _library_dir(request: Request) -> Path: + return _library_dir_from_app(request.app) + + +async def _get_library_store(request: Request): + """Get the LibraryStore from app.state (lazily initialised).""" + store = getattr(request.app.state, "library_store", None) + if store is None: + from tinyagentos.library_store import LibraryStore + + data_dir = getattr(request.app.state, "data_dir", None) + base = Path(data_dir) if data_dir else Path(__file__).parent.parent.parent / "data" + store = LibraryStore(base / "library.db") + await store.init() + request.app.state.library_store = store + return store + + +# --------------------------------------------------------------------------- +# Ingest +# --------------------------------------------------------------------------- + + +@router.post("/api/library/ingest") +async def ingest( + request: Request, + file: UploadFile | None = File(None), + url: str | None = Form(None), + title: str | None = Form(None), +): + """Ingest a file or URL into the library. + + Accepts a file upload (multipart) or a URL string form field. At least one + of ``file`` or ``url`` must be provided. + + Returns ``{item_id, status: \"pending\"}`` immediately — pipeline processing + happens asynchronously in a background task. + """ + store = await _get_library_store(request) + storage_dir = _library_dir(request) + + if file and file.filename: + # File upload + kind = _detect_kind_from_filename(file.filename, file.content_type) + file_dir = storage_dir / "files" + file_dir.mkdir(parents=True, exist_ok=True) + + # Sanitise filename + safe_name = _sanitise_filename(file.filename) + dest = file_dir / f"{uuid.uuid4().hex[:8]}_{safe_name}" + + content = await file.read() + dest.write_bytes(content) + + item_id = await store.create_item( + kind=kind, + title=title or file.filename, + storage_path=str(dest), + size_bytes=len(content), + source_url="", + ) + elif url: + # URL reference + kind = _detect_kind_from_url(url) + item_id = await store.create_item( + kind=kind, + source_url=url, + title=title or url, + ) + else: + return JSONResponse( + {"error": "Provide either 'file' (multipart upload) or 'url' (form field)."}, + status_code=400, + ) + + # Run pipeline in background + task_set = getattr(request.app.state, "_background_tasks", None) + coro = _ingest_task(request.app, item_id, store, storage_dir) + if task_set is None: + asyncio.create_task(coro) + else: + _create_supervised_task(coro, task_set) + + return JSONResponse({"item_id": item_id, "status": "pending"}, status_code=202) + + +async def _ingest_task(app, item_id: str, store, storage_dir: Path) -> None: + """Background task: run pipeline + collections handoff for an item. + + Never raises — always leaves the item in a terminal status. + """ + try: + await run_pipeline(store, item_id, storage_dir) + except Exception: + logger.exception("Library ingest pipeline crashed for item %s", item_id) + await store.update_item_status(item_id, "error") + return + + # Collections handoff after successful pipeline + try: + collections_dir = storage_dir.parent / "collections" + await handoff_to_collections(store, item_id, collections_dir) + except Exception: + logger.exception("Collections handoff failed for item %s", item_id) + + +def _sanitise_filename(name: str) -> str: + """Strip path separators and null bytes from a filename.""" + name = name.replace("/", "_").replace("\\", "_").replace("\x00", "") + # Also prevent double-dots for path traversal + name = name.replace("..", "_") + return name or "unnamed" + + +def _detect_kind_from_filename(filename: str, content_type: str | None = None) -> str: + """Detect kind from filename and optional MIME type.""" + from tinyagentos.library_pipeline import detect_kind + return detect_kind(file_path=filename, content_type=content_type or "") + + +def _detect_kind_from_url(url: str) -> str: + """Detect kind from URL pattern.""" + from tinyagentos.library_pipeline import detect_kind + return detect_kind(source_url=url) + + +# --------------------------------------------------------------------------- +# List / Get / Delete +# --------------------------------------------------------------------------- + + +@router.get("/api/library/items") +async def list_items( + request: Request, + kind: str | None = None, + status: str | None = None, + limit: int = 50, + offset: int = 0, +): + """List library items, optionally filtered by kind or status.""" + store = await _get_library_store(request) + items = await store.list_items(kind=kind, status=status, limit=limit, offset=offset) + return {"items": items, "count": len(items)} + + +@router.get("/api/library/items/{item_id}") +async def get_item(request: Request, item_id: str): + """Get a library item with its artifacts.""" + store = await _get_library_store(request) + item = await store.get_item(item_id) + if not item: + return JSONResponse({"error": f"Item {item_id!r} not found"}, status_code=404) + + artifacts = await store.get_artifacts(item_id) + jobs = await store.get_item_jobs(item_id) + return {"item": item, "artifacts": artifacts, "jobs": jobs} + + +@router.delete("/api/library/items/{item_id}") +async def delete_item(request: Request, item_id: str): + """Delete a library item and its associated files.""" + store = await _get_library_store(request) + item = await store.get_item(item_id) + if not item: + return JSONResponse({"error": f"Item {item_id!r} not found"}, status_code=404) + + # Remove on-disk files + storage_path = item.get("storage_path", "") + if storage_path and (p := Path(storage_path)).exists(): + try: + p.unlink() + except OSError: + pass + + # Remove artifacts from disk + artifacts = await store.get_artifacts(item_id) + for art in artifacts: + art_path = art.get("path", "") + if art_path and (ap := Path(art_path)).exists(): + try: + ap.unlink() + except OSError: + pass + + # Remove collections folder + storage_dir = _library_dir(request) + item_collection_dir = storage_dir.parent / "collections" / item_id + if item_collection_dir.exists(): + import shutil + try: + shutil.rmtree(item_collection_dir) + except OSError: + pass + + await store.delete_item(item_id) + return {"status": "deleted", "item_id": item_id} + + +@router.post("/api/library/items/{item_id}/reprocess") +async def reprocess_item(request: Request, item_id: str): + """Re-run the ingest pipeline for an existing item.""" + store = await _get_library_store(request) + item = await store.get_item(item_id) + if not item: + return JSONResponse({"error": f"Item {item_id!r} not found"}, status_code=404) + + storage_dir = _library_dir(request) + + task_set = getattr(request.app.state, "_background_tasks", None) + coro = _ingest_task(request.app, item_id, store, storage_dir) + if task_set is None: + asyncio.create_task(coro) + else: + _create_supervised_task(coro, task_set) + + return JSONResponse({"item_id": item_id, "status": "reprocessing"}, status_code=202) diff --git a/tinyagentos/templates/library.html b/tinyagentos/templates/library.html new file mode 100644 index 000000000..6fdcb1d44 --- /dev/null +++ b/tinyagentos/templates/library.html @@ -0,0 +1,130 @@ + + +
+ + +Drop files here or paste a URL
+ +No items yet. Drop a file or paste a URL above.
+No items yet. Drop a file or paste a URL above.
" + "