|
| 1 | +from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile |
| 2 | +from sqlalchemy import select |
| 3 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 4 | + |
| 5 | +from app.api.v1.schemas.documents import ( |
| 6 | + DocumentCreate, |
| 7 | + DocumentResponse, |
| 8 | + DocumentUploadResponse, |
| 9 | +) |
| 10 | +from app.db.config.database import get_async_session |
| 11 | +from app.db.models import FAQEmbedding |
| 12 | +from app.security.auth import AuthUser, require_admin_user |
| 13 | +from app.services.document_ingestion_service import document_ingestion_service |
| 14 | +from app.services.embedding_service import embedding_service |
| 15 | + |
| 16 | +router = APIRouter() |
| 17 | + |
| 18 | + |
| 19 | +@router.post("/documents", response_model=DocumentResponse, status_code=201) |
| 20 | +async def create_document( |
| 21 | + document: DocumentCreate, |
| 22 | + _current_user: AuthUser = Depends(require_admin_user), |
| 23 | + session: AsyncSession = Depends(get_async_session) |
| 24 | +) -> DocumentResponse: |
| 25 | + try: |
| 26 | + created = await embedding_service.add_faq_embedding( |
| 27 | + question=document.question, |
| 28 | + answer=document.answer, |
| 29 | + session=session |
| 30 | + ) |
| 31 | + |
| 32 | + if created is None: |
| 33 | + raise HTTPException( |
| 34 | + status_code=500, |
| 35 | + detail="No se pudo crear el documento y su embedding" |
| 36 | + ) |
| 37 | + |
| 38 | + return DocumentResponse( |
| 39 | + id=created.id, |
| 40 | + question=created.question, |
| 41 | + answer=created.answer, |
| 42 | + created_at=created.created_at |
| 43 | + ) |
| 44 | + except HTTPException: |
| 45 | + raise |
| 46 | + except Exception: |
| 47 | + raise HTTPException(status_code=500, detail="Error creando documento") |
| 48 | + |
| 49 | + |
| 50 | +@router.post("/documents/upload", response_model=DocumentUploadResponse, status_code=201) |
| 51 | +async def upload_document( |
| 52 | + file: UploadFile = File(...), |
| 53 | + chunk_size: int = Query(1200, ge=200, le=4000), |
| 54 | + chunk_overlap: int = Query(150, ge=0, le=1000), |
| 55 | + _current_user: AuthUser = Depends(require_admin_user), |
| 56 | + session: AsyncSession = Depends(get_async_session) |
| 57 | +) -> DocumentUploadResponse: |
| 58 | + if not file.filename: |
| 59 | + raise HTTPException(status_code=400, detail="Archivo sin nombre") |
| 60 | + |
| 61 | + if chunk_overlap >= chunk_size: |
| 62 | + raise HTTPException( |
| 63 | + status_code=400, |
| 64 | + detail="chunk_overlap debe ser menor que chunk_size" |
| 65 | + ) |
| 66 | + if chunk_overlap * 2 >= chunk_size: |
| 67 | + raise HTTPException( |
| 68 | + status_code=400, |
| 69 | + detail="chunk_overlap debe ser menor al 50% de chunk_size" |
| 70 | + ) |
| 71 | + |
| 72 | + content = await file.read() |
| 73 | + if not content: |
| 74 | + raise HTTPException(status_code=400, detail="Archivo vacio") |
| 75 | + |
| 76 | + if len(content) > document_ingestion_service.max_file_size_bytes: |
| 77 | + raise HTTPException(status_code=400, detail="Archivo demasiado grande (max 20MB)") |
| 78 | + |
| 79 | + file_type, text = document_ingestion_service.extract_file_text(file.filename, content) |
| 80 | + chunks = document_ingestion_service.split_text( |
| 81 | + text, |
| 82 | + chunk_size=chunk_size, |
| 83 | + chunk_overlap=chunk_overlap, |
| 84 | + ) |
| 85 | + |
| 86 | + if not chunks: |
| 87 | + raise HTTPException(status_code=400, detail="No se encontro texto util en el archivo") |
| 88 | + |
| 89 | + created_ids: list[int] = [] |
| 90 | + total = len(chunks) |
| 91 | + |
| 92 | + try: |
| 93 | + for index, chunk in enumerate(chunks, start=1): |
| 94 | + title = f"{file.filename} - fragmento {index}/{total}" |
| 95 | + combined_text = f"Pregunta: {title}\nRespuesta: {chunk}" |
| 96 | + vector = await embedding_service.generate_embedding(combined_text) |
| 97 | + item = FAQEmbedding(question=title, answer=chunk, embedding=vector) |
| 98 | + session.add(item) |
| 99 | + await session.flush() |
| 100 | + created_ids.append(item.id) |
| 101 | + |
| 102 | + await session.commit() |
| 103 | + except Exception: |
| 104 | + await session.rollback() |
| 105 | + raise HTTPException(status_code=500, detail="Error procesando el archivo") |
| 106 | + |
| 107 | + return DocumentUploadResponse( |
| 108 | + filename=file.filename, |
| 109 | + file_type=file_type, |
| 110 | + chunks_created=len(created_ids), |
| 111 | + document_ids=created_ids |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +@router.get("/documents", response_model=list[DocumentResponse]) |
| 116 | +async def list_documents( |
| 117 | + limit: int = Query(50, ge=1, le=200), |
| 118 | + offset: int = Query(0, ge=0), |
| 119 | + session: AsyncSession = Depends(get_async_session) |
| 120 | +) -> list[DocumentResponse]: |
| 121 | + try: |
| 122 | + stmt = ( |
| 123 | + select(FAQEmbedding) |
| 124 | + .order_by(FAQEmbedding.created_at.desc()) |
| 125 | + .limit(limit) |
| 126 | + .offset(offset) |
| 127 | + ) |
| 128 | + |
| 129 | + result = await session.execute(stmt) |
| 130 | + documents = result.scalars().all() |
| 131 | + |
| 132 | + return [ |
| 133 | + DocumentResponse( |
| 134 | + id=document.id, |
| 135 | + question=document.question, |
| 136 | + answer=document.answer, |
| 137 | + created_at=document.created_at |
| 138 | + ) for document in documents |
| 139 | + ] |
| 140 | + except Exception: |
| 141 | + raise HTTPException(status_code=500, detail="Error listando documentos") |
| 142 | + |
| 143 | + |
| 144 | +@router.delete("/documents/{document_id}") |
| 145 | +async def delete_document( |
| 146 | + document_id: int, |
| 147 | + _current_user: AuthUser = Depends(require_admin_user), |
| 148 | + session: AsyncSession = Depends(get_async_session) |
| 149 | +) -> dict: |
| 150 | + try: |
| 151 | + result = await session.execute( |
| 152 | + select(FAQEmbedding).where(FAQEmbedding.id == document_id) |
| 153 | + ) |
| 154 | + document = result.scalar_one_or_none() |
| 155 | + |
| 156 | + if document is None: |
| 157 | + raise HTTPException(status_code=404, detail="Documento no encontrado") |
| 158 | + |
| 159 | + await session.delete(document) |
| 160 | + await session.commit() |
| 161 | + |
| 162 | + return {"message": f"Documento {document_id} eliminado correctamente"} |
| 163 | + except HTTPException: |
| 164 | + raise |
| 165 | + except Exception: |
| 166 | + await session.rollback() |
| 167 | + raise HTTPException(status_code=500, detail="Error eliminando documento") |
0 commit comments