Spaces:
Running
Running
File size: 24,215 Bytes
afd56bc | 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 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 | """
Endpoints: Upload PDF + Re-ingest RAG β Sprint 7 / Sprint 9
POST /api/projects/{project_id}/documents
Wgrywa plik PDF do projektu, uruchamia pipeline RAG w tle (asyncio.create_task).
Pipeline: LlamaParse β (PyPDF fallback) β Hierarchical Chunking β Pinecone
Limity:
- Hard limit: max 10 plikΓ³w per projekt (wszyscy plany)
- Soft limit: Free = 3 pliki, Pro/Enterprise = 50 plikΓ³w
GET /api/projects/{project_id}/documents
Listuje dokumenty projektu ze statusem indeksacji.
DELETE /api/projects/{project_id}/documents/{doc_id}
Usuwa dokument z dysku i Pinecone.
POST /api/projects/{project_id}/documents/{doc_id}/reingest
Ponowna indeksacja dokumentu (np. po zmianie parametrΓ³w RAG).
"""
import os
import uuid
import logging
import asyncio
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
from fastapi import APIRouter, HTTPException, UploadFile, File, Query
from fastapi.responses import JSONResponse
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=["documents"])
# ββ Konfiguracja ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
UPLOAD_DIR = Path(os.environ.get("UPLOAD_DIR", "/data/uploads"))
MAX_FILE_SIZE_MB = 20
ALLOWED_MIME_TYPES = {"application/pdf", "application/x-pdf"}
# Limity uploadΓ³w per plan
UPLOAD_LIMIT_HARD = 10 # Max per projekt (wszystkie plany)
UPLOAD_LIMIT_FREE = 3 # Max na planie Free
UPLOAD_LIMIT_PRO = 50 # Max na planie Pro
UPLOAD_LIMIT_ENTERPRISE = 50 # Max na planie Enterprise
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _get_namespace(user_id: str, project_id: str) -> str:
"""Namespace Pinecone: tenant_{user_id}_{project_id}"""
return f"tenant_{user_id}_{project_id}"
def _resolve_user_id(token: Optional[str]) -> str:
"""Dekoduje JWT Clerk lub zwraca 'anonymous'."""
if not token:
return "anonymous"
try:
import jwt
if token == "dev_test_token":
return "test_dev_user"
decoded = jwt.decode(token, options={"verify_signature": False})
return decoded.get("sub", "anonymous")
except Exception:
return "anonymous"
def _get_plan_upload_limit(db, project_id: str) -> tuple[int, str]:
"""
Pobiera limit uploadΓ³w na podstawie planu subskrypcji wΕaΕciciela projektu.
Zwraca (limit, plan_name).
"""
try:
from core.projects.models import Project
from core.subscription.models import UserSubscription
project = db.query(Project).filter(Project.id == project_id).first()
if not project:
return UPLOAD_LIMIT_FREE, "free"
# Pobierz plan uΕΌytkownika (jeΕli model subskrypcji istnieje)
sub = (
db.query(UserSubscription)
.filter(UserSubscription.user_id == project.user_id)
.first()
if project.user_id
else None
)
plan = (sub.plan if sub else "free") or "free"
plan_lower = plan.lower()
if plan_lower in ("pro", "professional"):
return UPLOAD_LIMIT_PRO, plan_lower
elif plan_lower in ("enterprise", "business"):
return UPLOAD_LIMIT_ENTERPRISE, plan_lower
else:
return UPLOAD_LIMIT_FREE, "free"
except Exception:
# Bezpieczny fallback β nie blokuj uploadu przy bΕΔdzie odczytu planu
return UPLOAD_LIMIT_FREE, "free"
def _check_upload_limits(db, project_id: str) -> dict:
"""
Sprawdza czy uΕΌytkownik moΕΌe dodaΔ kolejny dokument.
Zwraca {'allowed': bool, 'current': int, 'limit': int, 'plan': str, 'reason': str}.
"""
from core.projects.models import ProjectDocument
current_count = (
db.query(ProjectDocument)
.filter(
ProjectDocument.project_id == project_id,
ProjectDocument.status != "deleted",
)
.count()
)
# Hard limit (bezwzglΔdny β dotyczy wszystkich planΓ³w)
if current_count >= UPLOAD_LIMIT_HARD:
return {
"allowed": False,
"current": current_count,
"limit": UPLOAD_LIMIT_HARD,
"plan": "any",
"reason": f"Przekroczono bezwzglΔdny limit {UPLOAD_LIMIT_HARD} plikΓ³w na projekt.",
}
# Soft limit (planowy)
plan_limit, plan_name = _get_plan_upload_limit(db, project_id)
if current_count >= plan_limit:
return {
"allowed": False,
"current": current_count,
"limit": plan_limit,
"plan": plan_name,
"reason": (
f"Plan '{plan_name}' pozwala na {plan_limit} pliki PDF per projekt. "
"UsuΕ stare dokumenty lub przejdΕΊ na plan Pro."
),
}
return {
"allowed": True,
"current": current_count,
"limit": plan_limit,
"plan": plan_name,
"reason": "",
}
async def _save_upload(
upload: UploadFile, dest_dir: Path, doc_id: str
) -> tuple[Path, int]:
"""Zapisuje plik na dysku, zwraca (path, size_bytes)."""
dest_dir.mkdir(parents=True, exist_ok=True)
suffix = Path(upload.filename or "doc").suffix or ".pdf"
dest_path = dest_dir / f"{doc_id}{suffix}"
size = 0
chunk_size = 1024 * 256 # 256 KB chunks
with open(dest_path, "wb") as f:
while True:
chunk = await upload.read(chunk_size)
if not chunk:
break
size += len(chunk)
if size > MAX_FILE_SIZE_MB * 1024 * 1024:
dest_path.unlink(missing_ok=True)
raise HTTPException(
413, detail=f"Plik za duΕΌy. Limit: {MAX_FILE_SIZE_MB} MB"
)
f.write(chunk)
return dest_path, size
async def _run_rag_pipeline(
doc_id: str,
project_id: str,
file_path: Path,
namespace: str,
program_name: Optional[str] = None,
):
"""
Uruchamia pipeline RAG dla przesΕanego dokumentu.
WywoΕywany w tle przez asyncio.create_task().
Kroki:
1. Parse PDF (LlamaParse β PyPDF β Unstructured)
2. Hierarchical Chunking (Parent 2000 / Child 400)
3. Upsert do Pinecone (child) + LocalFileStore (parent)
4. Aktualizacja statusu w DB
"""
db = None
try:
from core.subscription.db import SessionLocal
from core.projects.models import ProjectDocument
db = SessionLocal()
doc = db.query(ProjectDocument).filter(ProjectDocument.id == doc_id).first()
if not doc:
logger.error(f"[RAG Upload] Dokument {doc_id} nie znaleziony w DB.")
return
# ββ Krok 1: Ustaw status "processing" ββββββββββββββββββββββββββββββ
doc.status = "processing"
db.commit()
# ββ Krok 2: Parse PDF βββββββββββββββββββββββββββββββββββββββββββββββ
try:
from rag_pipeline.pdf_parser import parse_pdf_from_file
except ImportError:
from backend.rag_pipeline.pdf_parser import parse_pdf_from_file
parse_result = await parse_pdf_from_file(
str(file_path),
document_type="regulamin_dotacyjny",
program_name=program_name or "Nieznany Program",
)
raw_text = parse_result.get("text", "")
parser_used = parse_result.get("parser", "unknown")
if not raw_text.strip():
raise ValueError("Parser nie wyodrΔbniΕ ΕΌadnej treΕci z pliku PDF.")
logger.info(
f"[RAG Upload] Dokument {doc_id}: sparsowano {len(raw_text)} znakΓ³w "
f"przez '{parser_used}'."
)
# ββ Krok 3: Hierarchical Chunking βββββββββββββββββββββββββββββββββββ
try:
from rag_pipeline.ingest import hierarchical_chunking
except ImportError:
from backend.rag_pipeline.ingest import hierarchical_chunking
parent_docs, child_docs = await asyncio.to_thread(
hierarchical_chunking,
text=raw_text,
source_url=file_path.name,
extra_metadata={
"source": file_path.name,
"project_id": project_id,
"document_id": doc_id,
"program_name": program_name or "Nieznany",
"is_current": True,
},
)
logger.info(
f"[RAG Upload] Chunking: {len(parent_docs)} parent, "
f"{len(child_docs)} child chunks."
)
# ββ Krok 4: Upsert do Pinecone + LocalFileStore βββββββββββββββββββββ
try:
from rag_pipeline.vector_store import ingest_documents
except ImportError:
from backend.rag_pipeline.vector_store import ingest_documents
await asyncio.to_thread(
ingest_documents,
parent_docs=parent_docs,
child_docs=child_docs,
namespace=namespace,
)
# ββ Krok 5: Zaktualizuj rekord ββββββββββββββββββββββββββββββββββββββ
doc.status = "indexed"
doc.parser_used = parser_used
doc.chunks_count = len(child_docs)
doc.rag_namespace = namespace
doc.indexed_at = datetime.now(timezone.utc)
doc.processing_metadata = {
"parent_chunks": len(parent_docs),
"child_chunks": len(child_docs),
"raw_text_length": len(raw_text),
"program_name": program_name,
}
db.commit()
logger.info(
f"[RAG Upload] β
Dokument {doc_id} ('{file_path.name}') "
f"zaindeksowany w namespace '{namespace}'."
)
except Exception as e:
logger.error(f"[RAG Upload] β BΕΔ
d pipeline dla {doc_id}: {e}", exc_info=True)
if db:
try:
from core.projects.models import ProjectDocument
doc = (
db.query(ProjectDocument)
.filter(ProjectDocument.id == doc_id)
.first()
)
if doc:
doc.status = "error"
doc.error_message = str(e)[:500]
db.commit()
except Exception:
pass
finally:
if db:
db.close()
async def _run_external_grant_pipeline(
doc_id: str,
project_id: str,
file_path: Path,
program_name: Optional[str] = None,
):
"""
Parsuje zewnΔtrzny wniosek dotacyjny przez LlamaParse i zapisuje jego treΕΔ w projekcie (omijajΔ
c Pinecone).
"""
db = None
try:
from core.subscription.db import SessionLocal
from core.projects.models import ProjectDocument, Project
db = SessionLocal()
doc = db.query(ProjectDocument).filter(ProjectDocument.id == doc_id).first()
if not doc:
return
doc.status = "processing"
db.commit()
try:
from rag_pipeline.pdf_parser import parse_pdf_from_file
except ImportError:
from backend.rag_pipeline.pdf_parser import parse_pdf_from_file
parse_result = await parse_pdf_from_file(
str(file_path),
document_type="wniosek_zewnetrzny",
program_name=program_name or "Nieznany Program",
)
raw_text = parse_result.get("text", "")
parser_used = parse_result.get("parser", "unknown")
if not raw_text.strip():
raise ValueError(
"Parser nie wyodrΔbniΕ ΕΌadnej treΕci ze wskazanego wniosku."
)
project = db.query(Project).filter(Project.id == project_id).first()
if project:
if project.foreign_grant_extract_text:
project.foreign_grant_extract_text += (
"\n\n---Kolejny dokument---\n\n" + raw_text
)
else:
project.foreign_grant_extract_text = raw_text
doc.status = "indexed"
doc.parser_used = parser_used
doc.chunks_count = 0
doc.indexed_at = datetime.now(timezone.utc)
doc.processing_metadata = {
"raw_text_length": len(raw_text),
"parser": parser_used,
"type": "external_grant",
}
db.commit()
logger.info(
f"[External Grant] β
Wniosek zewnΔtrzny {doc_id} przetworzony dla projektu {project_id}."
)
except Exception as e:
logger.error(
f"[External Grant] β BΕΔ
d pipeline dla {doc_id}: {e}", exc_info=True
)
if db:
try:
from core.projects.models import ProjectDocument
doc = (
db.query(ProjectDocument)
.filter(ProjectDocument.id == doc_id)
.first()
)
if doc:
doc.status = "error"
doc.error_message = str(e)[:500]
db.commit()
except Exception:
pass
finally:
if db:
db.close()
# ββ Routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@router.post("/{project_id}/documents")
async def upload_document(
project_id: str,
file: UploadFile = File(...),
token: Optional[str] = Query(default=None, alias="token"),
doc_type: Optional[str] = Query(default="knowledge_base", alias="doc_type"),
):
"""
Wgrywa plik PDF do projektu i uruchamia indeksacjΔ RAG w tle.
Parametry (query):
token β JWT Clerk (wymagany dla izolacji namespace)
Zwraca:
doc_id, status="uploaded", filename, wiadomoΕΔ o tle
"""
# ββ Walidacja pliku βββββββββββββββββββββββββββββββββββββββββββββββββββββ
if not file.filename or not file.filename.lower().endswith(".pdf"):
raise HTTPException(400, detail="ObsΕugiwane sΔ
wyΕΔ
cznie pliki PDF.")
content_type = file.content_type or ""
if (
content_type
and content_type not in ALLOWED_MIME_TYPES
and "pdf" not in content_type
):
raise HTTPException(415, detail=f"NieprawidΕowy typ pliku: {content_type}")
user_id = _resolve_user_id(token)
namespace = _get_namespace(user_id, project_id)
doc_id = str(uuid.uuid4())
# ββ Weryfikacja projektu ββββββββββββββββββββββββββββββββββββββββββββββββ
db = None
try:
from core.subscription.db import SessionLocal
from core.projects.models import Project, ProjectDocument
db = SessionLocal()
project = db.query(Project).filter(Project.id == project_id).first()
if not project:
raise HTTPException(404, detail="Projekt nie istnieje.")
# ββ SprawdΕΊ limity uploadΓ³w βββββββββββββββββββββββββββββββββββββββββ
limit_check = _check_upload_limits(db, project_id)
if not limit_check["allowed"]:
raise HTTPException(
status_code=429,
detail={
"error": "upload_limit_exceeded",
"message": limit_check["reason"],
"current_count": limit_check["current"],
"limit": limit_check["limit"],
"plan": limit_check["plan"],
"upgrade_url": "/cennik",
},
)
program_name = project.program_name
# ββ Zapisz plik na dysk βββββββββββββββββββββββββββββββββββββββββββββ
dest_dir = UPLOAD_DIR / project_id
file_path, file_size = await _save_upload(file, dest_dir, doc_id)
# ββ Zapis metadanych do DB ββββββββββββββββββββββββββββββββββββββββββ
doc_record = ProjectDocument(
id=doc_id,
project_id=project_id,
filename=file_path.name,
original_filename=file.filename,
file_size_bytes=file_size,
mime_type=file.content_type or "application/pdf",
storage_path=str(file_path),
status="uploaded",
rag_namespace=namespace if doc_type == "knowledge_base" else None,
doc_type=doc_type,
)
db.add(doc_record)
db.commit()
db.refresh(doc_record)
logger.info(
f"[Upload] Plik '{file.filename}' ({file_size // 1024}KB) "
f"zapisany jako {doc_id} dla projektu {project_id}."
)
# ββ Uruchom odpowiedni pipeline w tle βββββββββββββββββββββββββββββββ
if doc_type == "external_grant":
asyncio.create_task(
_run_external_grant_pipeline(
doc_id=doc_id,
project_id=project_id,
file_path=file_path,
program_name=program_name,
)
)
else:
asyncio.create_task(
_run_rag_pipeline(
doc_id=doc_id,
project_id=project_id,
file_path=file_path,
namespace=namespace,
program_name=program_name,
)
)
return JSONResponse(
status_code=202, # Accepted β przetwarzanie w tle
content={
"doc_id": doc_id,
"filename": file.filename,
"file_size_bytes": file_size,
"status": "uploaded",
"message": (
"Plik przesΕany pomyΕlnie. "
"Indeksacja w RAG odbywa siΔ w tle β "
"sprawdΕΊ status przez GET /documents."
),
"namespace": namespace,
},
)
except HTTPException:
raise
except Exception as e:
logger.error(
f"[Upload] BΕΔ
d uploadu dla projektu {project_id}: {e}", exc_info=True
)
raise HTTPException(500, detail=f"BΕΔ
d wgrywania pliku: {str(e)}")
finally:
if db:
db.close()
@router.get("/{project_id}/documents")
async def list_documents(
project_id: str,
token: Optional[str] = Query(default=None, alias="token"),
):
"""Lista dokumentΓ³w projektu ze statusem indeksacji RAG + informacje o limitach."""
db = None
try:
from core.subscription.db import SessionLocal
from core.projects.models import ProjectDocument
db = SessionLocal()
docs = (
db.query(ProjectDocument)
.filter(
ProjectDocument.project_id == project_id,
ProjectDocument.status != "deleted",
)
.order_by(ProjectDocument.uploaded_at.desc())
.all()
)
# Kwota uploadu (do wyΕwietlenia w UI)
limit_check = _check_upload_limits(db, project_id)
return {
"project_id": project_id,
"documents": [
{
"doc_id": d.id,
"filename": d.original_filename,
"file_size_bytes": d.file_size_bytes,
"status": d.status,
"doc_type": getattr(d, "doc_type", "knowledge_base"),
"parser_used": d.parser_used,
"chunks_count": d.chunks_count,
"error_message": d.error_message,
"uploaded_at": d.uploaded_at.isoformat() if d.uploaded_at else None,
"indexed_at": d.indexed_at.isoformat() if d.indexed_at else None,
}
for d in docs
],
"total": len(docs),
# Informacje o limitach planu (dla frontendu)
"quota": {
"current": limit_check["current"],
"limit": limit_check["limit"],
"plan": limit_check["plan"],
"can_upload": limit_check["allowed"],
},
}
except Exception as e:
raise HTTPException(500, detail=str(e))
finally:
if db:
db.close()
@router.post("/{project_id}/documents/{doc_id}/reingest")
async def reingest_document(
project_id: str,
doc_id: str,
token: Optional[str] = Query(default=None, alias="token"),
):
"""
Ponowna indeksacja dokumentu w RAG.
Przydatne po zmianie parametrΓ³w chunkingu lub migracji Pinecone.
"""
user_id = _resolve_user_id(token)
namespace = _get_namespace(user_id, project_id)
try:
from core.subscription.db import SessionLocal
from core.projects.models import ProjectDocument
db = SessionLocal()
doc = (
db.query(ProjectDocument)
.filter(
ProjectDocument.id == doc_id,
ProjectDocument.project_id == project_id,
)
.first()
)
if not doc:
raise HTTPException(404, detail="Dokument nie istnieje.")
file_path = Path(doc.storage_path) if doc.storage_path else None
if not file_path or not file_path.exists():
raise HTTPException(410, detail="Plik ΕΊrΓ³dΕowy nie istnieje na dysku.")
# Reset statusu
doc.status = "uploaded"
doc.error_message = None
doc.chunks_count = None
doc.indexed_at = None
db.commit()
db.close()
# Pipeline RAG w tle
asyncio.create_task(
_run_rag_pipeline(
doc_id=doc_id,
project_id=project_id,
file_path=file_path,
namespace=namespace,
)
)
return {
"doc_id": doc_id,
"status": "reingesting",
"message": "Ponowna indeksacja uruchomiona w tle.",
}
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, detail=str(e))
@router.delete("/{project_id}/documents/{doc_id}")
async def delete_document(
project_id: str,
doc_id: str,
token: Optional[str] = Query(default=None, alias="token"),
):
"""Usuwa dokument z dysku i Pinecone (jeΕli zaindeksowany)."""
try:
from core.subscription.db import SessionLocal
from core.projects.models import ProjectDocument
db = SessionLocal()
doc = (
db.query(ProjectDocument)
.filter(
ProjectDocument.id == doc_id,
ProjectDocument.project_id == project_id,
)
.first()
)
if not doc:
raise HTTPException(404, detail="Dokument nie istnieje.")
# UsuΕ plik z dysku
if doc.storage_path:
fp = Path(doc.storage_path)
fp.unlink(missing_ok=True)
# UsuΕ rekord z DB
db.delete(doc)
db.commit()
db.close()
return {"message": "Dokument usuniΔty.", "doc_id": doc_id}
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, detail=str(e))
|