79 lines
2.5 KiB
Python
79 lines
2.5 KiB
Python
from typing import Any
|
|
|
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.auth.deps import get_current_user
|
|
from app.config import get_settings
|
|
from app.db.base import get_db
|
|
from app.db.models import User
|
|
from app.db.models import Document
|
|
from app.rag.ingest import (
|
|
delete_document_vectors,
|
|
ingest_document_file,
|
|
reindex_document,
|
|
serialize_document,
|
|
)
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/documents")
|
|
def list_documents(db: Session = Depends(get_db), user: User = Depends(get_current_user)) -> list[dict[str, Any]]:
|
|
docs = db.scalars(select(Document).where(Document.user_id == user.id).order_by(Document.created_at.desc())).all()
|
|
return [serialize_document(d) for d in docs]
|
|
|
|
|
|
@router.post("/documents/upload")
|
|
async def upload_document(
|
|
file: UploadFile = File(...),
|
|
title: str = Form(""),
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
) -> dict[str, Any]:
|
|
raw = await file.read()
|
|
if not raw:
|
|
raise HTTPException(status_code=400, detail="Empty file")
|
|
try:
|
|
doc = await ingest_document_file(
|
|
db,
|
|
user_id=user.id,
|
|
title=title.strip() or (file.filename or "document"),
|
|
filename=file.filename or "upload.txt",
|
|
raw_bytes=raw,
|
|
)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
return {"ok": True, "document": doc}
|
|
|
|
|
|
@router.post("/documents/{document_id}/reindex")
|
|
async def reindex_document_route(
|
|
document_id: int,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
) -> dict[str, Any]:
|
|
doc = db.get(Document, document_id)
|
|
if not doc or doc.user_id != user.id:
|
|
raise HTTPException(status_code=404, detail="Document not found")
|
|
result = await reindex_document(db, doc)
|
|
return {"ok": True, "document": result}
|
|
|
|
|
|
@router.delete("/documents/{document_id}")
|
|
def delete_document_route(
|
|
document_id: int,
|
|
db: Session = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
) -> dict[str, Any]:
|
|
doc = db.get(Document, document_id)
|
|
if not doc or doc.user_id != user.id:
|
|
raise HTTPException(status_code=404, detail="Document not found")
|
|
|
|
if get_settings().rag_enabled:
|
|
delete_document_vectors(doc.id)
|
|
db.delete(doc)
|
|
db.commit()
|
|
return {"ok": True}
|