File size: 9,670 Bytes
792ad00 | 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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import List, Optional
import logging
import PyPDF2
import io
import uuid
from core.database import get_db
from models import db_models
from services.rag_service import rag_service
from services.s3_service import s3_service
from api.auth import get_current_user
from core.config import settings
from openai import OpenAI
router = APIRouter(prefix="/api/rag", tags=["RAG Document Management"])
logger = logging.getLogger(__name__)
# Request/Response Models
class RAGIndexRequest(BaseModel):
file_key: str # S3 key of source file to index
class RAGIndexResponse(BaseModel):
id: int
filename: str
azure_doc_id: str
chunk_count: int
message: str
class RAGDocumentResponse(BaseModel):
id: int
filename: str
azure_doc_id: str
chunk_count: int
source_id: Optional[int]
created_at: str
class Config:
from_attributes = True
def extract_text_from_pdf(file_content: bytes) -> str:
"""Extract text from PDF file."""
try:
pdf_reader = PyPDF2.PdfReader(io.BytesIO(file_content))
text = ""
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
return text.strip()
except Exception as e:
logger.error(f"Error extracting PDF text: {e}")
raise HTTPException(status_code=400, detail=f"Failed to extract text: {str(e)}")
def chunk_text(text: str, chunk_size: int = 1000, overlap: int = 200) -> List[str]:
"""Split text into overlapping chunks."""
chunks = []
start = 0
while start < len(text):
end = start + chunk_size
chunks.append(text[start:end])
start += (chunk_size - overlap)
return chunks
@router.post("/index", response_model=RAGIndexResponse)
async def index_document(
request: RAGIndexRequest,
current_user: db_models.User = Depends(get_current_user),
db: Session = Depends(get_db)):
"""
Index a document for AI search (one-time operation).
Downloads from S3, extracts text, generates embeddings, stores in Azure Search.
"""
try:
# 1. Verify file ownership
source = db.query(db_models.Source).filter(
db_models.Source.s3_key == request.file_key,
db_models.Source.user_id == current_user.id
).first()
if not source:
raise HTTPException(status_code=404, detail="File not found")
# 2. Check if already indexed
existing = db.query(db_models.RAGDocument).filter(
db_models.RAGDocument.source_id == source.id,
db_models.RAGDocument.user_id == current_user.id
).first()
if existing:
return RAGIndexResponse(
id=existing.id,
filename=existing.filename,
azure_doc_id=existing.azure_doc_id,
chunk_count=existing.chunk_count,
message="Document already indexed"
)
# 3. Download from S3
logger.info(f"Downloading {request.file_key}...")
# Create temp local path
import tempfile
import os
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(source.filename)[1]) as tmp:
temp_file = tmp.name
s3_service.s3_client.download_file(
settings.AWS_S3_BUCKET,
request.file_key,
temp_file
)
# 4. Extract text
try:
with open(temp_file, "rb") as f:
file_content = f.read()
if source.filename.lower().endswith('.pdf'):
text = extract_text_from_pdf(file_content)
elif source.filename.lower().endswith('.txt'):
text = file_content.decode('utf-8')
else:
raise HTTPException(status_code=400, detail="Only PDF and TXT supported")
if len(text) < 10:
raise HTTPException(status_code=400, detail="No readable text content found in file")
# 5. Chunk text
chunks = chunk_text(text)
logger.info(f"Created {len(chunks)} chunks")
# 6. Generate doc ID and index in Azure Search
doc_id = str(uuid.uuid4())
chunk_count = rag_service.index_document(
chunks=chunks,
filename=source.filename,
user_id=current_user.id,
doc_id=doc_id
)
# 7. Save to database
rag_doc = db_models.RAGDocument(
filename=source.filename,
azure_doc_id=doc_id,
chunk_count=chunk_count,
user_id=current_user.id,
source_id=source.id
)
db.add(rag_doc)
db.commit()
db.refresh(rag_doc)
logger.info(f"Successfully indexed {source.filename}")
return RAGIndexResponse(
id=rag_doc.id,
filename=rag_doc.filename,
azure_doc_id=rag_doc.azure_doc_id,
chunk_count=rag_doc.chunk_count,
message="Document indexed successfully for AI conversation"
)
finally:
if os.path.exists(temp_file):
os.remove(temp_file)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error indexing document: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Indexing failed: {str(e)}")
@router.get("/documents", response_model=List[RAGDocumentResponse])
async def list_indexed_documents(
current_user: db_models.User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""List all documents that have been processed and are ready for chatting."""
documents = db.query(db_models.RAGDocument).filter(
db_models.RAGDocument.user_id == current_user.id
).order_by(db_models.RAGDocument.created_at.desc()).all()
return [
RAGDocumentResponse(
id=doc.id,
filename=doc.filename,
azure_doc_id=doc.azure_doc_id,
chunk_count=doc.chunk_count,
source_id=doc.source_id,
created_at=doc.created_at.isoformat()
)
for doc in documents
]
@router.delete("/documents/{doc_id}")
async def delete_indexed_document(
doc_id: str, # Azure doc ID
current_user: db_models.User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""Remove a document from the AI search index."""
# Find document
rag_doc = db.query(db_models.RAGDocument).filter(
db_models.RAGDocument.azure_doc_id == doc_id,
db_models.RAGDocument.user_id == current_user.id
).first()
if not rag_doc:
raise HTTPException(status_code=404, detail="Document index entry not found")
try:
# Delete from Azure Search
rag_service.delete_document(doc_id)
# Delete from database
db.delete(rag_doc)
db.commit()
return {"message": "AI index for document deleted successfully"}
except Exception as e:
logger.error(f"Error deleting document index: {e}")
raise HTTPException(status_code=500, detail=f"Deletion failed: {str(e)}")
class RAGSummaryRequest(BaseModel):
rag_doc_id: int
@router.post("/summary")
async def generate_document_summary(
request: RAGSummaryRequest,
current_user: db_models.User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""
Generate an on-the-fly summary for an indexed document.
No data is stored in the database.
"""
try:
# 1. Verify existence and ownership
rag_doc = db.query(db_models.RAGDocument).filter(
db_models.RAGDocument.id == request.rag_doc_id,
db_models.RAGDocument.user_id == current_user.id
).first()
if not rag_doc:
raise HTTPException(status_code=404, detail="Document not found")
# 2. Fetch top chunks to build a summary
# We search with a generic prompt to get a representative spread of content
results = rag_service.search_document(
query="Give me a general overview and executive summary of this document.",
doc_id=rag_doc.azure_doc_id,
user_id=current_user.id,
top_k=8 # Fetch more context for a better summary
)
if not results:
return {"summary": "No content found to summarize."}
context = "\n\n".join([r["content"] for r in results])
# 3. Generate summary using OpenAI
openai_client = OpenAI(api_key=settings.OPENAI_API_KEY)
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "You are a professional document analyst. Provide a concise, high-level summary (3-5 sentences) of the document based on the provided context."
},
{"role": "user", "content": f"Context from '{rag_doc.filename}':\n\n{context}"}
],
temperature=0.5
)
return {"summary": response.choices[0].message.content}
except Exception as e:
logger.error(f"Summary generation failed: {e}")
raise HTTPException(status_code=500, detail=f"Failed to generate summary: {str(e)}")
|