Production ready: mobile responsive UI, ChromaDB persistence, Excel export, and Filing Deadlines
This commit is contained in:
@@ -12,8 +12,28 @@ from app import models
|
||||
from app.db import engine
|
||||
|
||||
log = logging.getLogger("uvicorn.error")
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
app = FastAPI(title="BookKeepPro API", docs_url=None, redoc_url=None) # hide docs in production
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
# Startup
|
||||
try:
|
||||
from app.utils.scheduler import start_scheduler
|
||||
start_scheduler()
|
||||
log.info("Scheduler started via lifespan.")
|
||||
except Exception as exc:
|
||||
log.exception("Failed to start scheduler: %s", exc)
|
||||
yield
|
||||
# Shutdown
|
||||
try:
|
||||
from app.utils.scheduler import stop_scheduler
|
||||
stop_scheduler()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
app = FastAPI(title="BookKeepPro API", docs_url=None, redoc_url=None, lifespan=lifespan) # hide docs in production
|
||||
|
||||
# Rate limiter
|
||||
app.state.limiter = limiter
|
||||
@@ -37,6 +57,13 @@ try:
|
||||
except Exception as exc:
|
||||
log.exception("Failed to load upload router: %s", exc)
|
||||
|
||||
try:
|
||||
from app.routers import search
|
||||
app.include_router(search.router)
|
||||
except Exception as exc:
|
||||
log.exception("Failed to load search router: %s", exc)
|
||||
|
||||
|
||||
try:
|
||||
from app.routers import contact # type: ignore
|
||||
app.include_router(contact.router)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
Column,
|
||||
Date,
|
||||
DateTime,
|
||||
Enum,
|
||||
ForeignKey,
|
||||
@@ -222,3 +223,28 @@ class ChatMessage(Base):
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
session = relationship("ChatSession", back_populates="messages")
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Filing Deadlines — set by admin when sending review email
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
class FilingDeadline(Base):
|
||||
__tablename__ = "filing_deadlines"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
doc_type = Column(String(20), nullable=False) # "personal" or "business"
|
||||
deadline_date = Column(Date, nullable=False)
|
||||
days_given = Column(Integer, nullable=False)
|
||||
notified_7d = Column(Boolean, default=False, nullable=False)
|
||||
notified_1d = Column(Boolean, default=False, nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
user = relationship("User")
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_filing_deadlines_user_id", "user_id"),
|
||||
Index("ix_filing_deadlines_deadline_date", "deadline_date"),
|
||||
)
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import os
|
||||
from datetime import date, timedelta
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models import AdminDocument, User, UserRole
|
||||
from app.models import AdminDocument, User, UserRole, FilingDeadline
|
||||
from app.db import get_db
|
||||
from app.utils.emailer import send_email
|
||||
from app import crud
|
||||
@@ -92,6 +93,30 @@ async def notify_user_review(
|
||||
|
||||
await send_email(to=user.email, subject="Document Review Update — BookKeepro", body=body)
|
||||
logger.info(f"Admin {current_user.id} sent review notification to user {payload.user_id}")
|
||||
|
||||
# Save / reset filing deadlines if timelines were provided
|
||||
today = date.today()
|
||||
for doc_type, days in [("personal", payload.personal_timeline), ("business", payload.business_timeline)]:
|
||||
if days and days > 0:
|
||||
existing = db.query(FilingDeadline).filter(
|
||||
FilingDeadline.user_id == payload.user_id,
|
||||
FilingDeadline.doc_type == doc_type,
|
||||
).first()
|
||||
if existing:
|
||||
# Reset the deadline and clear reminder flags
|
||||
existing.deadline_date = today + timedelta(days=days)
|
||||
existing.days_given = days
|
||||
existing.notified_7d = False
|
||||
existing.notified_1d = False
|
||||
else:
|
||||
db.add(FilingDeadline(
|
||||
user_id=payload.user_id,
|
||||
doc_type=doc_type,
|
||||
deadline_date=today + timedelta(days=days),
|
||||
days_given=days,
|
||||
))
|
||||
db.commit()
|
||||
|
||||
return {"status": "notified"}
|
||||
|
||||
|
||||
@@ -143,3 +168,30 @@ async def admin_doc_response(
|
||||
|
||||
logger.info(f"User {current_user.id} {payload.status} admin doc {payload.doc_id}")
|
||||
return {"status": "notified"}
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Get filing deadlines for a user
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
@router.get("/deadlines/{user_id}")
|
||||
def get_filing_deadlines(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
from app.models import FilingDeadline
|
||||
deadlines = db.query(FilingDeadline).filter(FilingDeadline.user_id == user_id).all()
|
||||
today = date.today()
|
||||
result = []
|
||||
for dl in deadlines:
|
||||
days_left = (dl.deadline_date - today).days
|
||||
result.append({
|
||||
"doc_type": dl.doc_type,
|
||||
"deadline_date": dl.deadline_date.isoformat(),
|
||||
"days_given": dl.days_given,
|
||||
"days_left": days_left,
|
||||
"is_overdue": days_left < 0,
|
||||
})
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from app.db import get_db
|
||||
from app.models import PersonalDocument, BusinessDocument, User
|
||||
from app.auth.security import get_current_user
|
||||
from app.utils.vector_store import search_documents
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/search",
|
||||
tags=["Search"]
|
||||
)
|
||||
|
||||
@router.get("/semantic")
|
||||
def semantic_search(
|
||||
q: str = Query(..., description="The semantic search query"),
|
||||
limit: int = Query(5, description="Maximum number of results to return"),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""
|
||||
Searches for documents matching the query semantics.
|
||||
Returns matched documents across both personal and business tables.
|
||||
"""
|
||||
if not q.strip():
|
||||
raise HTTPException(status_code=400, detail="Query string cannot be empty")
|
||||
|
||||
# Search the vector database
|
||||
results = search_documents(q, current_user.id, limit=limit)
|
||||
|
||||
if not results:
|
||||
return []
|
||||
|
||||
# Fetch full document metadata from DB
|
||||
enriched_results = []
|
||||
|
||||
for res in results:
|
||||
doc_id = res['doc_id']
|
||||
doc_type = res['doc_type']
|
||||
|
||||
doc = None
|
||||
if doc_type == "personal":
|
||||
doc = db.query(PersonalDocument).filter(
|
||||
PersonalDocument.id == doc_id,
|
||||
PersonalDocument.user_id == current_user.id,
|
||||
PersonalDocument.deleted_at == None
|
||||
).first()
|
||||
elif doc_type == "business":
|
||||
doc = db.query(BusinessDocument).filter(
|
||||
BusinessDocument.id == doc_id,
|
||||
BusinessDocument.user_id == current_user.id,
|
||||
BusinessDocument.deleted_at == None
|
||||
).first()
|
||||
|
||||
if doc:
|
||||
doc_data = {
|
||||
"id": doc.id,
|
||||
"table": doc_type,
|
||||
"original_filename": doc.original_filename,
|
||||
"document_type": doc.document_type,
|
||||
"uploaded_at": doc.uploaded_at,
|
||||
"relevance_score": res['distance']
|
||||
}
|
||||
enriched_results.append(doc_data)
|
||||
|
||||
return enriched_results
|
||||
@@ -5,18 +5,19 @@ import logging
|
||||
from datetime import datetime
|
||||
import filetype
|
||||
from fastapi import APIRouter, BackgroundTasks, UploadFile, File, HTTPException, Depends, Form, Query
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from jose import jwt, JWTError
|
||||
from datetime import timedelta
|
||||
|
||||
from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole
|
||||
from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole, ChatSession, ChatMessage
|
||||
from app.db import get_db, SessionLocal
|
||||
import app.crud as crud
|
||||
from app.auth.security import get_current_user, require_admin, SECRET_KEY, ALGORITHM
|
||||
from app.utils.emailer import send_email
|
||||
from app.utils.ai import extract_document_data, summarize_admin_document
|
||||
from app.utils.ai import extract_document_data, summarize_admin_document, extract_raw_text
|
||||
from app.utils.vector_store import add_document_embedding, delete_document_embeddings, delete_user_embeddings
|
||||
from app.schemas import UploadCompleteNotify, ReviewStatusUpdate, ExtractedDataUpdate
|
||||
from app.limiter import limiter
|
||||
from fastapi import Request
|
||||
@@ -72,6 +73,12 @@ def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str
|
||||
doc.extracted_data = cached.extracted_data
|
||||
doc.file_hash = file_hash
|
||||
db.commit()
|
||||
try:
|
||||
raw_text = extract_raw_text(file_path)
|
||||
if raw_text:
|
||||
add_document_embedding(doc.id, table, doc.user_id, raw_text)
|
||||
except Exception as ve:
|
||||
logger.error(f"VectorStore Failed to embed {file_path}: {ve}")
|
||||
return
|
||||
|
||||
# No cache — run full extraction
|
||||
@@ -90,6 +97,12 @@ def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str
|
||||
doc.extracted_data = extracted
|
||||
doc.file_hash = file_hash
|
||||
db.commit()
|
||||
try:
|
||||
raw_text = extract_raw_text(file_path)
|
||||
if raw_text:
|
||||
add_document_embedding(doc.id, table, doc.user_id, raw_text)
|
||||
except Exception as ve:
|
||||
logger.error(f"VectorStore Failed to embed {file_path}: {ve}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update DB with AI extraction: {e}")
|
||||
@@ -1087,3 +1100,142 @@ def delete_template(
|
||||
db.delete(record)
|
||||
db.commit()
|
||||
return {"deleted": True}
|
||||
|
||||
from fastapi.responses import StreamingResponse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
|
||||
@router.get("/admin/users/{user_id}/export")
|
||||
def export_user_documents_excel(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
"""Export all documents for a user as a formatted Excel (.xlsx) workbook."""
|
||||
import io
|
||||
import json as _json
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
if current_user.role == UserRole.admin and user.role != UserRole.user:
|
||||
raise HTTPException(status_code=403, detail="Admins can only export documents for regular user accounts")
|
||||
|
||||
personal_docs = db.query(PersonalDocument).filter(
|
||||
PersonalDocument.user_id == user_id, PersonalDocument.deleted_at == None
|
||||
).all()
|
||||
business_docs = db.query(BusinessDocument).filter(
|
||||
BusinessDocument.user_id == user_id, BusinessDocument.deleted_at == None
|
||||
).all()
|
||||
|
||||
# Collect all extracted_data keys to build dynamic columns
|
||||
extracted_keys = set()
|
||||
all_docs = []
|
||||
|
||||
for d in personal_docs:
|
||||
row = {
|
||||
"ID": f"P-{d.id}",
|
||||
"Table": "Personal",
|
||||
"Doc Type": d.doc_type,
|
||||
"Filename": d.filename,
|
||||
"Uploaded At": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "",
|
||||
"Tax Year": d.tax_year or "",
|
||||
"Review Status": (d.review_status or "").capitalize(),
|
||||
"Review Note": d.review_note or "",
|
||||
}
|
||||
if d.extracted_data:
|
||||
try:
|
||||
data = _json.loads(d.extracted_data) if isinstance(d.extracted_data, str) else d.extracted_data
|
||||
if isinstance(data, dict):
|
||||
for k, v in data.items():
|
||||
col = f"AI: {k}"
|
||||
extracted_keys.add(col)
|
||||
row[col] = str(v)
|
||||
except Exception:
|
||||
pass
|
||||
all_docs.append(row)
|
||||
|
||||
for d in business_docs:
|
||||
row = {
|
||||
"ID": f"B-{d.id}",
|
||||
"Table": "Business",
|
||||
"Doc Type": d.business_type,
|
||||
"Filename": d.filename,
|
||||
"Uploaded At": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "",
|
||||
"Tax Year": d.tax_year or "",
|
||||
"Review Status": (d.review_status or "").capitalize(),
|
||||
"Review Note": d.review_note or "",
|
||||
}
|
||||
if d.extracted_data:
|
||||
try:
|
||||
data = _json.loads(d.extracted_data) if isinstance(d.extracted_data, str) else d.extracted_data
|
||||
if isinstance(data, dict):
|
||||
for k, v in data.items():
|
||||
col = f"AI: {k}"
|
||||
extracted_keys.add(col)
|
||||
row[col] = str(v)
|
||||
except Exception:
|
||||
pass
|
||||
all_docs.append(row)
|
||||
|
||||
base_cols = ["ID", "Table", "Doc Type", "Filename", "Uploaded At", "Tax Year", "Review Status", "Review Note"]
|
||||
all_cols = base_cols + sorted(list(extracted_keys))
|
||||
|
||||
# ── Build workbook ────────────────────────────────────────────────────────
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Documents"
|
||||
|
||||
# Header style
|
||||
header_fill = PatternFill(fill_type="solid", fgColor="2C7A5B")
|
||||
header_font = Font(bold=True, color="FFFFFF", size=11)
|
||||
center_align = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
thin_border = Border(
|
||||
left=Side(style="thin"), right=Side(style="thin"),
|
||||
top=Side(style="thin"), bottom=Side(style="thin"),
|
||||
)
|
||||
|
||||
# Write headers
|
||||
for col_idx, col_name in enumerate(all_cols, 1):
|
||||
cell = ws.cell(row=1, column=col_idx, value=col_name)
|
||||
cell.fill = header_fill
|
||||
cell.font = header_font
|
||||
cell.alignment = center_align
|
||||
cell.border = thin_border
|
||||
|
||||
ws.row_dimensions[1].height = 30
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
# Alternate row fill
|
||||
alt_fill = PatternFill(fill_type="solid", fgColor="EAF4EF")
|
||||
|
||||
# Write data
|
||||
for row_idx, doc in enumerate(all_docs, 2):
|
||||
fill = alt_fill if row_idx % 2 == 0 else None
|
||||
for col_idx, col_name in enumerate(all_cols, 1):
|
||||
cell = ws.cell(row=row_idx, column=col_idx, value=doc.get(col_name, ""))
|
||||
cell.alignment = Alignment(vertical="center", wrap_text=False)
|
||||
cell.border = thin_border
|
||||
if fill:
|
||||
cell.fill = fill
|
||||
|
||||
# Auto-fit column widths (capped at 40)
|
||||
for col_idx, col_name in enumerate(all_cols, 1):
|
||||
max_len = max(len(col_name), *(len(str(doc.get(col_name, ""))) for doc in all_docs)) if all_docs else len(col_name)
|
||||
ws.column_dimensions[get_column_letter(col_idx)].width = min(max_len + 3, 40)
|
||||
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
|
||||
headers = {
|
||||
"Content-Disposition": f'attachment; filename="user_{user_id}_documents.xlsx"',
|
||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
}
|
||||
return StreamingResponse(buf, headers=headers)
|
||||
|
||||
|
||||
@@ -435,7 +435,7 @@ _SUMMARY_SYSTEM_PROMPT = (
|
||||
)
|
||||
|
||||
|
||||
def _extract_text_from_file(file_path: str) -> str:
|
||||
def extract_raw_text(file_path: str) -> str:
|
||||
"""Extract raw text from a PDF or image file. Returns empty string on failure."""
|
||||
try:
|
||||
if file_path.lower().endswith(".pdf"):
|
||||
@@ -492,7 +492,7 @@ def summarize_admin_document(file_path: str, doc_label: str) -> str | None:
|
||||
logger.warning("[Summary] OPENROUTER_API_KEY not set — skipping summary")
|
||||
return None
|
||||
|
||||
text = _extract_text_from_file(file_path)
|
||||
text = extract_raw_text(file_path)
|
||||
|
||||
if not text:
|
||||
logger.info(f"[Summary] No extractable text from {file_path} — skipping")
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
scheduler.py — Daily background job to send filing deadline reminders.
|
||||
|
||||
Checks for deadlines that are 7 days or 1 day away and sends reminder emails
|
||||
to both the user and all admins/super-admins.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import date, timedelta
|
||||
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_scheduler = BackgroundScheduler(timezone="UTC")
|
||||
|
||||
|
||||
def _run_deadline_reminders():
|
||||
"""Check all upcoming deadlines and dispatch reminder emails."""
|
||||
# Import inside to avoid circular imports at module load
|
||||
from app.db import SessionLocal
|
||||
from app.models import FilingDeadline, User, UserRole
|
||||
from app.utils.emailer import send_email
|
||||
import asyncio
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
today = date.today()
|
||||
thresholds = [
|
||||
(7, "notified_7d", "7 days"),
|
||||
(1, "notified_1d", "1 day"),
|
||||
]
|
||||
|
||||
# Fetch all admins/super-admins to CC on reminders
|
||||
admins = db.query(User).filter(
|
||||
User.role.in_([UserRole.admin, UserRole.super_admin])
|
||||
).all()
|
||||
admin_emails = [a.email for a in admins]
|
||||
|
||||
for days_out, flag_col, label in thresholds:
|
||||
target_date = today + timedelta(days=days_out)
|
||||
deadlines = (
|
||||
db.query(FilingDeadline)
|
||||
.filter(
|
||||
FilingDeadline.deadline_date == target_date,
|
||||
getattr(FilingDeadline, flag_col) == False,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
for dl in deadlines:
|
||||
user = db.query(User).filter(User.id == dl.user_id).first()
|
||||
if not user:
|
||||
continue
|
||||
|
||||
doc_label = dl.doc_type.capitalize()
|
||||
|
||||
# Email to user
|
||||
user_body = f"""
|
||||
<p>Dear {user.name or "Sir/Ma'am"},</p>
|
||||
<p>This is a reminder that your <strong>{doc_label} document filing deadline</strong>
|
||||
is in <strong>{label}</strong> ({dl.deadline_date.strftime('%B %d, %Y')}).</p>
|
||||
<p>Please ensure all outstanding actions are completed before the deadline.</p>
|
||||
<p>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
||||
"""
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
send_email(
|
||||
to=user.email,
|
||||
subject=f"Reminder: {doc_label} Filing Deadline in {label} — BookKeepro",
|
||||
body=user_body,
|
||||
)
|
||||
)
|
||||
|
||||
# Email to all admins
|
||||
admin_body = f"""
|
||||
<p>Admin Notice:</p>
|
||||
<p>The <strong>{doc_label} filing deadline</strong> for client
|
||||
<strong>{user.name or user.email}</strong> ({user.email}) is in
|
||||
<strong>{label}</strong> ({dl.deadline_date.strftime('%B %d, %Y')}).</p>
|
||||
<p>Please review the client's status and take any necessary action.</p>
|
||||
<p><strong>BookKeepro System</strong></p>
|
||||
"""
|
||||
for admin_email in admin_emails:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
send_email(
|
||||
to=admin_email,
|
||||
subject=f"Admin Reminder: {user.email} — {doc_label} Deadline in {label}",
|
||||
body=admin_body,
|
||||
)
|
||||
)
|
||||
|
||||
# Mark as notified
|
||||
setattr(dl, flag_col, True)
|
||||
db.commit()
|
||||
|
||||
logger.info(
|
||||
"Sent %s deadline reminder for user %s (%s)",
|
||||
label, dl.user_id, dl.doc_type,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Deadline reminder job failed: %s", exc)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def start_scheduler():
|
||||
"""Start the APScheduler. Called once at application startup."""
|
||||
if _scheduler.running:
|
||||
return
|
||||
|
||||
# Run every day at 08:00 UTC
|
||||
_scheduler.add_job(
|
||||
_run_deadline_reminders,
|
||||
trigger=CronTrigger(hour=8, minute=0, timezone="UTC"),
|
||||
id="filing_deadline_reminders",
|
||||
replace_existing=True,
|
||||
misfire_grace_time=3600, # If the server was down, run if missed by < 1 hr
|
||||
)
|
||||
_scheduler.start()
|
||||
logger.info("APScheduler started — filing deadline reminders active.")
|
||||
|
||||
|
||||
def stop_scheduler():
|
||||
"""Gracefully stop the scheduler at application shutdown."""
|
||||
if _scheduler.running:
|
||||
_scheduler.shutdown(wait=False)
|
||||
logger.info("APScheduler stopped.")
|
||||
@@ -0,0 +1,105 @@
|
||||
import chromadb
|
||||
from chromadb.config import Settings
|
||||
import os
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Ensure the database directory exists
|
||||
DB_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'chroma_db'))
|
||||
os.makedirs(DB_PATH, exist_ok=True)
|
||||
|
||||
# Initialize ChromaDB client with persistent storage
|
||||
client = chromadb.PersistentClient(path=DB_PATH)
|
||||
|
||||
# We'll use a single collection for all documents, using metadata to differentiate
|
||||
collection = client.get_or_create_collection(
|
||||
name='documents',
|
||||
metadata={'hnsw:space': 'cosine'}
|
||||
)
|
||||
|
||||
|
||||
def add_document_embedding(doc_id: int, doc_type: str, user_id: int, text: str):
|
||||
"""
|
||||
Adds a document's text to the vector database.
|
||||
We chunk the text into roughly 1000 character segments to improve search relevance.
|
||||
"""
|
||||
if not text or not text.strip():
|
||||
logger.info(f"[VectorStore] Skipping empty text for doc {doc_id}")
|
||||
return
|
||||
|
||||
logger.info(f"[VectorStore] Adding embeddings for doc {doc_id} (user {user_id})")
|
||||
|
||||
# Simple chunking by fixed length (1000 chars)
|
||||
chunk_size = 1000
|
||||
chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
|
||||
|
||||
ids = [f"doc_{doc_type}_{doc_id}_chunk_{i}" for i in range(len(chunks))]
|
||||
metadatas = [{"doc_id": doc_id, "doc_type": doc_type, "user_id": user_id, "chunk_index": i} for i in range(len(chunks))]
|
||||
|
||||
collection.upsert(
|
||||
documents=chunks,
|
||||
metadatas=metadatas,
|
||||
ids=ids
|
||||
)
|
||||
logger.info(f"[VectorStore] Added {len(chunks)} chunks for doc {doc_id}")
|
||||
|
||||
|
||||
def search_documents(query: str, user_id: int, limit: int = 5):
|
||||
"""
|
||||
Searches for documents matching the query for a specific user.
|
||||
Returns a list of dicts: {'doc_id': int, 'doc_type': str, 'distance': float}
|
||||
"""
|
||||
logger.info(f'[VectorStore] Searching for: "{query}" (user {user_id})')
|
||||
|
||||
try:
|
||||
results = collection.query(
|
||||
query_texts=[query],
|
||||
n_results=limit * 2, # Fetch more to account for duplicates
|
||||
where={"user_id": user_id}
|
||||
)
|
||||
|
||||
if not results or not results['documents'] or len(results['documents'][0]) == 0:
|
||||
return []
|
||||
|
||||
metadatas = results['metadatas'][0]
|
||||
distances = results['distances'][0]
|
||||
|
||||
# We want to return unique documents, keeping the best score for each
|
||||
doc_scores = {}
|
||||
for meta, dist in zip(metadatas, distances):
|
||||
key = f"{meta['doc_type']}_{meta['doc_id']}"
|
||||
if key not in doc_scores or dist < doc_scores[key]['distance']:
|
||||
doc_scores[key] = {
|
||||
'doc_id': meta['doc_id'],
|
||||
'doc_type': meta['doc_type'],
|
||||
'distance': dist
|
||||
}
|
||||
|
||||
# Sort by distance
|
||||
sorted_docs = sorted(doc_scores.values(), key=lambda x: x['distance'])
|
||||
return sorted_docs[:limit]
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[VectorStore] Search failed: {e}")
|
||||
return []
|
||||
|
||||
def delete_document_embeddings(doc_id: int, doc_type: str):
|
||||
"""
|
||||
Deletes all vector chunks associated with a specific document.
|
||||
"""
|
||||
try:
|
||||
collection.delete(where={"$and": [{"doc_id": doc_id}, {"doc_type": doc_type}]})
|
||||
logger.info(f"[VectorStore] Deleted embeddings for {doc_type} document {doc_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"[VectorStore] Failed to delete embeddings for doc {doc_id}: {e}")
|
||||
|
||||
def delete_user_embeddings(user_id: int):
|
||||
"""
|
||||
Deletes all vector chunks associated with a specific user.
|
||||
"""
|
||||
try:
|
||||
collection.delete(where={"user_id": user_id})
|
||||
logger.info(f"[VectorStore] Deleted all embeddings for user {user_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"[VectorStore] Failed to delete embeddings for user {user_id}: {e}")
|
||||
@@ -39,3 +39,8 @@ pymupdf==1.24.1
|
||||
Pillow==12.0.0
|
||||
pytesseract==0.3.13
|
||||
pypdf==4.3.1
|
||||
|
||||
chromadb==0.5.5
|
||||
|
||||
openpyxl
|
||||
APScheduler
|
||||
|
||||
Reference in New Issue
Block a user