diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fec1e5ffc1eb3e1277efa98292567a3b6035f96c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM python:3.11-slim + +WORKDIR /app + +# Install system dependencies for PostgreSQL and other libraries +RUN apt-get update && apt-get install -y \ + build-essential \ + libpq-dev \ + && rm -rf /var/lib/apt/lists/* + +# Copy requirements and install dependencies +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy the rest of the application code +COPY . . + +# Set environment variables for Cloud Run compatibility +ENV PORT=8080 +EXPOSE 8080 + +# Run the application using uvicorn +CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT}"] diff --git a/app/__pycache__/main.cpython-312.pyc b/app/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f718d452fcfa84362c7b50b68359b35720a8f3ec Binary files /dev/null and b/app/__pycache__/main.cpython-312.pyc differ diff --git a/app/api/__pycache__/auth.cpython-312.pyc b/app/api/__pycache__/auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24b35246a86c320814fde0935b21366198b002d3 Binary files /dev/null and b/app/api/__pycache__/auth.cpython-312.pyc differ diff --git a/app/api/__pycache__/chat.cpython-312.pyc b/app/api/__pycache__/chat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04f0b1ad9893cb37e55708890749b82b62a36883 Binary files /dev/null and b/app/api/__pycache__/chat.cpython-312.pyc differ diff --git a/app/api/__pycache__/documents.cpython-312.pyc b/app/api/__pycache__/documents.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc9df71bde6c218505e42ad6fef979cc9e0a7810 Binary files /dev/null and b/app/api/__pycache__/documents.cpython-312.pyc differ diff --git a/app/api/__pycache__/upload.cpython-312.pyc b/app/api/__pycache__/upload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f121c40b293482d435193a0f67e64809a6c80b4 Binary files /dev/null and b/app/api/__pycache__/upload.cpython-312.pyc differ diff --git a/app/api/auth.py b/app/api/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..ed4ca28024fbb6f4309581f47997caa9eb1daa34 --- /dev/null +++ b/app/api/auth.py @@ -0,0 +1,72 @@ +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.db.database import get_db +from app.models.user import User +from app.core.security import hash_password, verify_password, create_access_token +from fastapi.security import OAuth2PasswordRequestForm + +router = APIRouter() + + +class RegisterRequest(BaseModel): + username: str + password: str + + +class LoginRequest(BaseModel): + username: str + password: str + + +@router.post("/register") +def register(request: RegisterRequest, db: Session = Depends(get_db)): + existing_user = db.query(User).filter(User.username == request.username).first() + + if existing_user: + raise HTTPException(status_code=400, detail="Username already exists") + + new_user = User( + username=request.username, + hashed_password=hash_password(request.password) + ) + + db.add(new_user) + db.commit() + db.refresh(new_user) + + return { + "message": "User registered successfully", + "user_id": new_user.id, + "username": new_user.username + } + + +@router.post("/login") +def login( + form_data: OAuth2PasswordRequestForm = Depends(), + db: Session = Depends(get_db) +): + user = db.query(User).filter(User.username == form_data.username).first() + + if not user: + raise HTTPException(status_code=401, detail="Invalid username or password") + + if not verify_password(form_data.password, user.hashed_password): + raise HTTPException(status_code=401, detail="Invalid username or password") + + token = create_access_token( + data={"sub": str(user.id), "username": user.username} + ) + + return { + "access_token": token, + "token_type": "bearer" + } + +@router.post("/logout") +def logout(): + return { + "message": "Logout successful. Please remove token from client." + } \ No newline at end of file diff --git a/app/api/chat.py b/app/api/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..7ba6aa38b309c3bc0e4c3d632fb4a25864e4ff70 --- /dev/null +++ b/app/api/chat.py @@ -0,0 +1,363 @@ +import json +import logging + +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.services.rag_service import ask_question +from app.core.dependencies import get_current_user +from app.db.database import get_db +from app.models.user import User +from app.models.document import Document +from app.models.chat_message import ChatMessage +from fastapi.responses import StreamingResponse +from app.services.rag_service import stream_answer_events + +router = APIRouter() +logger = logging.getLogger("uvicorn.error") + + +def serialize_sse_event(payload: dict) -> str: + return f"data: {json.dumps(payload)}\n\n" + + +class ChatRequest(BaseModel): + query: str + document_id: int + + +def serialize_chat_message(message: ChatMessage): + return { + "id": message.id, + "role": message.role, + "content": message.content, + "document_id": message.document_id, + "sources": json.loads(message.sources) if message.sources else [], + "created_at": message.created_at, + } + + +@router.get("/history/{document_id}") +def get_chat_history( + document_id: int, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + document = db.query(Document).filter( + Document.id == document_id, + Document.user_id == current_user.id + ).first() + + if document is None: + raise HTTPException(status_code=404, detail="Document not found") + + messages = db.query(ChatMessage).filter( + ChatMessage.document_id == document_id, + ChatMessage.user_id == current_user.id + ).order_by(ChatMessage.created_at.asc(), ChatMessage.id.asc()).all() + + return { + "document_id": document_id, + "messages": [serialize_chat_message(message) for message in messages], + } + + +@router.get("/activity") +def get_recent_activity( + limit: int = 20, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + """Get recent chat messages across all user documents.""" + messages = ( + db.query(ChatMessage) + .join(Document, ChatMessage.document_id == Document.id) + .filter(Document.user_id == current_user.id) + .order_by(ChatMessage.created_at.desc(), ChatMessage.id.desc()) + .limit(limit) + .all() + ) + return [serialize_chat_message(msg) for msg in messages] + + +@router.get("/stats") +def get_usage_stats( + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + """Get usage statistics for the user.""" + total_docs = db.query(Document).filter(Document.user_id == current_user.id).count() + total_messages = db.query(ChatMessage).filter(ChatMessage.user_id == current_user.id).count() + + # Get count of processing docs + processing_docs = db.query(Document).filter( + Document.user_id == current_user.id, + Document.status == "processing" + ).count() + + # Get daily message stats for the last 7 days + from datetime import datetime, timedelta + from sqlalchemy import func, cast, Date + + seven_days_ago = datetime.utcnow().date() - timedelta(days=6) + + daily_messages = ( + db.query( + cast(ChatMessage.created_at, Date).label("date"), + func.count(ChatMessage.id).label("count") + ) + .filter( + ChatMessage.user_id == current_user.id, + cast(ChatMessage.created_at, Date) >= seven_days_ago + ) + .group_by(cast(ChatMessage.created_at, Date)) + .order_by(cast(ChatMessage.created_at, Date).asc()) + .all() + ) + + # Fill in gaps for days with zero messages + stats_map = {row.date.strftime("%Y-%m-%d"): row.count for row in daily_messages} + chart_data = [] + for i in range(7): + day = seven_days_ago + timedelta(days=i) + day_str = day.strftime("%Y-%m-%d") + chart_data.append({ + "date": day.strftime("%b %d"), + "messages": stats_map.get(day_str, 0) + }) + + return { + "total_documents": total_docs, + "total_messages": total_messages, + "processing_documents": processing_docs, + "chart_data": chart_data + } + + +@router.post("/") +def chat( + request: ChatRequest, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + document: Document | None = db.query(Document).filter( + Document.id == request.document_id, + Document.user_id == current_user.id + ).first() + + if document is None: + raise HTTPException(status_code=404, detail="Document not found") + + document_status = str(document.status) + + if document_status == "processing": + raise HTTPException(status_code=400, detail="Document is still processing") + + if document_status == "failed": + raise HTTPException( + status_code=400, + detail=f"Document indexing failed: {document.error_message}" + ) + + history_messages = db.query(ChatMessage).filter( + ChatMessage.document_id == request.document_id, + ChatMessage.user_id == current_user.id + ).order_by(ChatMessage.created_at.desc(), ChatMessage.id.desc()).limit(10).all() + history_messages.reverse() + chat_history = [{"role": msg.role, "content": msg.content} for msg in history_messages] + + user_message = ChatMessage( + user_id=current_user.id, + document_id=request.document_id, + role="user", + content=request.query, + sources=None, + ) + + assistant_content = "" + assistant_sources: list[dict] = [] + fallback_response = False + + try: + response = ask_question( + query=request.query, + user_id=str(current_user.id), + document_id=str(request.document_id), + chat_history=chat_history + ) + assistant_content = response["answer"] + assistant_sources = response.get("sources", []) + except Exception as exc: + logger.warning( + "Chat answer generation failed for document %s (user %s): %s", + request.document_id, + current_user.id, + exc, + ) + assistant_content = ( + "I couldn't generate an answer right now. Please try again in a moment." + ) + assistant_sources = [] + fallback_response = True + + assistant_message = ChatMessage( + user_id=current_user.id, + document_id=request.document_id, + role="assistant", + content=assistant_content, + sources=json.dumps(assistant_sources), + ) + + db.add(user_message) + db.add(assistant_message) + db.commit() + + return { + "answer": assistant_content, + "sources": assistant_sources, + "fallback": fallback_response, + } + + +@router.delete("/history/{document_id}", status_code=204) +def clear_chat_history( + document_id: int, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + document = db.query(Document).filter( + Document.id == document_id, + Document.user_id == current_user.id + ).first() + + if document is None: + raise HTTPException(status_code=404, detail="Document not found") + + db.query(ChatMessage).filter( + ChatMessage.document_id == document_id, + ChatMessage.user_id == current_user.id + ).delete(synchronize_session=False) + db.commit() + + +@router.post("/stream") +def chat_stream( + request: ChatRequest, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + document = db.query(Document).filter( + Document.id == request.document_id, + Document.user_id == current_user.id + ).first() + + if not document: + raise HTTPException(status_code=404, detail="Document not found") + + if document.status == "processing": + raise HTTPException(status_code=400, detail="Document is still processing") + + if document.status == "failed": + raise HTTPException( + status_code=400, + detail=f"Document indexing failed: {document.error_message}" + ) + + history_messages = db.query(ChatMessage).filter( + ChatMessage.document_id == request.document_id, + ChatMessage.user_id == current_user.id + ).order_by(ChatMessage.created_at.desc(), ChatMessage.id.desc()).limit(10).all() + history_messages.reverse() + chat_history = [{"role": msg.role, "content": msg.content} for msg in history_messages] + + user_message = ChatMessage( + user_id=current_user.id, + document_id=request.document_id, + role="user", + content=request.query, + sources=None, + ) + db.add(user_message) + db.commit() + db.refresh(user_message) + + def event_stream(): + assistant_parts: list[str] = [] + assistant_sources: list[dict] = [] + fallback_response = False + + try: + yield serialize_sse_event({ + "type": "start", + "messageId": user_message.id, + }) + + for event in stream_answer_events( + query=request.query, + user_id=str(current_user.id), + document_id=str(request.document_id), + chat_history=chat_history + ): + if event["type"] == "sources": + assistant_sources = event.get("sources", []) + yield serialize_sse_event(event) + continue + + if event["type"] == "delta": + token = event.get("content", "") + assistant_parts.append(token) + yield serialize_sse_event(event) + except Exception as exc: + logger.warning( + "Chat stream generation failed for document %s (user %s): %s", + request.document_id, + current_user.id, + exc, + ) + fallback_response = True + fallback_text = ( + "I couldn't generate an answer right now. Please try again in a moment." + ) + assistant_parts = [fallback_text] + assistant_sources = [] + yield serialize_sse_event({ + "type": "delta", + "content": fallback_text, + }) + finally: + assistant_content = "".join(assistant_parts).strip() + + if not assistant_content: + assistant_content = ( + "I couldn't generate an answer right now. Please try again in a moment." + ) + fallback_response = True + + assistant_message = ChatMessage( + user_id=current_user.id, + document_id=request.document_id, + role="assistant", + content=assistant_content, + sources=json.dumps(assistant_sources), + ) + db.add(assistant_message) + db.commit() + db.refresh(assistant_message) + + yield serialize_sse_event({ + "type": "done", + "messageId": assistant_message.id, + "sources": assistant_sources, + "fallback": fallback_response, + }) + + return StreamingResponse( + event_stream(), + media_type="text/event-stream", + headers={ + "Cache-Control": "no-cache", + "Connection": "keep-alive", + "X-Accel-Buffering": "no", + }, + ) diff --git a/app/api/documents.py b/app/api/documents.py new file mode 100644 index 0000000000000000000000000000000000000000..f252c731422da2c67b177e49620133fe1cf12fc0 --- /dev/null +++ b/app/api/documents.py @@ -0,0 +1,121 @@ +import os +import io +from fastapi import APIRouter, Depends, HTTPException +from fastapi.responses import FileResponse, StreamingResponse +from sqlalchemy.orm import Session + +from app.db.database import get_db +from app.core.dependencies import get_current_user +from app.models.user import User +from app.models.document import Document +from app.services.vector_service import delete_document_vectors +from app.services.storage_service import storage_service + +router = APIRouter() + + +@router.get("/") +def list_documents( + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + documents = db.query(Document).filter( + Document.user_id == current_user.id + ).order_by(Document.created_at.desc()).all() + + return { + "documents": [ + { + "document_id": doc.id, + "filename": doc.filename, + "status": doc.status, + "error_message": doc.error_message, + "uploaded_at": doc.created_at + } + for doc in documents + ] + } + + +@router.get("/{document_id}/file") +def get_document_file( + document_id: int, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + document = db.query(Document).filter( + Document.id == document_id, + Document.user_id == current_user.id + ).first() + + if document is None: + raise HTTPException(status_code=404, detail="Document not found") + + # Check if it's GCS path + if document.file_path.startswith("uploads/"): + content = storage_service.download_file(document.file_path) + if not content: + raise HTTPException(status_code=404, detail="File not found in cloud storage") + + return StreamingResponse( + io.BytesIO(content), + media_type="application/pdf", + headers={"Content-Disposition": f"inline; filename={document.filename}"} + ) + + # Fallback to local + if not document.file_path or not os.path.exists(document.file_path): + raise HTTPException(status_code=404, detail="File not found") + + return FileResponse( + path=document.file_path, + media_type="application/pdf", + filename=document.filename + ) + + +@router.delete("/{document_id}") +def delete_document( + document_id: int, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + document_query = db.query(Document).filter( + Document.id == document_id, + Document.user_id == current_user.id + ) + document = document_query.first() + + if document is None: + raise HTTPException(status_code=404, detail="Document not found") + + # Delete from GCS if applicable + if document.file_path.startswith("uploads/"): + storage_service.delete_file(document.file_path) + elif document.file_path and os.path.exists(document.file_path): + os.remove(document.file_path) + + vectors_deleted = delete_document_vectors( + user_id=str(current_user.id), + document_id=str(document.id) + ) + + rows_deleted = document_query.delete(synchronize_session=False) + db.commit() + + response = { + "message": "Document deleted successfully", + "document_id": document_id + } + + if rows_deleted == 0: + response["warning"] = ( + "Document metadata was already removed before delete confirmation." + ) + + if not vectors_deleted: + response["warning"] = ( + "Document was removed from the app, but vector cleanup could not be completed." + ) + + return response diff --git a/app/api/upload.py b/app/api/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..b50f8afedccc54a2c95815cdf901f4709d243981 --- /dev/null +++ b/app/api/upload.py @@ -0,0 +1,99 @@ +import os +import uuid +import tempfile +from fastapi import APIRouter, UploadFile, File, HTTPException, Depends, BackgroundTasks +from sqlalchemy.orm import Session + +from app.db.database import get_db +from app.core.dependencies import get_current_user +from app.models.user import User +from app.models.document import Document +from app.services.indexing_service import index_document +from app.utils.hash import generate_file_hash +from app.services.storage_service import storage_service + +router = APIRouter() + + +@router.post("/") +async def upload_pdf( + background_tasks: BackgroundTasks, + file: UploadFile = File(...), + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + filename = file.filename + + if not filename: + raise HTTPException(status_code=400, detail="Filename is missing") + + if not filename.lower().endswith(".pdf"): + raise HTTPException(status_code=400, detail="Only PDF files are allowed") + + # Read file content + content = await file.read() + + # Save to a temporary file to generate hash + with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp: + tmp.write(content) + temp_path = tmp.name + + try: + file_hash = generate_file_hash(temp_path) + + existing_doc = db.query(Document).filter( + Document.user_id == current_user.id, + Document.file_hash == file_hash + ).first() + + if existing_doc: + os.remove(temp_path) + return { + "message": "File already uploaded", + "document_id": existing_doc.id, + "filename": existing_doc.filename, + "status": existing_doc.status + } + + # Create document entry first to get ID + new_document = Document( + filename=filename, + file_path="pending", # Will update after GCS upload + user_id=current_user.id, + file_hash=file_hash, + status="processing" + ) + db.add(new_document) + db.commit() + db.refresh(new_document) + + # Upload to GCS: storage/user_id/doc_id_filename.pdf + gcs_blob_name = f"uploads/user_{current_user.id}/{new_document.id}_{filename}" + + upload_success = storage_service.upload_file(content, gcs_blob_name) + + if not upload_success: + db.delete(new_document) + db.commit() + raise HTTPException(status_code=500, detail="Failed to upload file to cloud storage") + + new_document.file_path = gcs_blob_name + db.commit() + + background_tasks.add_task( + index_document, + new_document.id, + gcs_blob_name, + filename, + current_user.id + ) + + return { + "message": "PDF uploaded successfully. Indexing started.", + "document_id": new_document.id, + "filename": filename, + "status": new_document.status + } + finally: + if os.path.exists(temp_path): + os.remove(temp_path) \ No newline at end of file diff --git a/app/core/__pycache__/dependencies.cpython-312.pyc b/app/core/__pycache__/dependencies.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ec0c1e2d0f1a60a6a7f99bd47c4d719bd50d30b Binary files /dev/null and b/app/core/__pycache__/dependencies.cpython-312.pyc differ diff --git a/app/core/__pycache__/security.cpython-312.pyc b/app/core/__pycache__/security.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d16213588e8f36660310a0b2cb1196136570d3c Binary files /dev/null and b/app/core/__pycache__/security.cpython-312.pyc differ diff --git a/app/core/dependencies.py b/app/core/dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..ce45b0a60ad2a1f3cba383f0b88f6dd2c7428208 --- /dev/null +++ b/app/core/dependencies.py @@ -0,0 +1,40 @@ +import os +from dotenv import load_dotenv +from fastapi import Depends, HTTPException +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from jose import jwt, JWTError +from sqlalchemy.orm import Session + +from app.db.database import get_db +from app.models.user import User + +load_dotenv() + +SECRET_KEY = os.getenv("SECRET_KEY") +ALGORITHM = os.getenv("ALGORITHM", "HS256") + +bearer_scheme = HTTPBearer() + + +def get_current_user( + credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme), + db: Session = Depends(get_db) +): + token = credentials.credentials + + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + user_id = payload.get("sub") + + if user_id is None: + raise HTTPException(status_code=401, detail="Invalid token") + + except JWTError: + raise HTTPException(status_code=401, detail="Invalid token") + + user = db.query(User).filter(User.id == int(user_id)).first() + + if not user: + raise HTTPException(status_code=401, detail="User not found") + + return user \ No newline at end of file diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000000000000000000000000000000000000..a040924a9292072d9cb26729f1fd0764061a6db3 --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,41 @@ +import os +from datetime import datetime, timedelta, timezone +from dotenv import load_dotenv +from passlib.context import CryptContext +from jose import jwt + +load_dotenv() + +# ENV VARIABLES +SECRET_KEY = os.getenv("SECRET_KEY") +if not SECRET_KEY: + raise ValueError("SECRET_KEY is missing in .env file") + +ALGORITHM = os.getenv("ALGORITHM", "HS256") +ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", 60)) + +# PASSWORD HASHING +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + + +def hash_password(password: str): + return pwd_context.hash(password) + + +def verify_password(plain_password: str, hashed_password: str): + return pwd_context.verify(plain_password, hashed_password) + + +# JWT TOKEN +def create_access_token(data: dict): + to_encode = data.copy() + + expire = datetime.now(timezone.utc) + timedelta( + minutes=ACCESS_TOKEN_EXPIRE_MINUTES + ) + + to_encode.update({"exp": expire}) + + encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) + + return encoded_jwt \ No newline at end of file diff --git a/app/db/__pycache__/database.cpython-312.pyc b/app/db/__pycache__/database.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18ee0b56b5bf13df0bce888f77844ffc9f1417c8 Binary files /dev/null and b/app/db/__pycache__/database.cpython-312.pyc differ diff --git a/app/db/database.py b/app/db/database.py new file mode 100644 index 0000000000000000000000000000000000000000..ddc10e3db854c8e80ede1e46612b63af092cdb05 --- /dev/null +++ b/app/db/database.py @@ -0,0 +1,29 @@ +import os +from dotenv import load_dotenv +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker, declarative_base + +load_dotenv() + +DATABASE_URL = os.getenv("DATABASE_URL") + +if not DATABASE_URL: + raise ValueError("DATABASE_URL is missing in .env file") + +engine = create_engine(DATABASE_URL) + +SessionLocal = sessionmaker( + autocommit=False, + autoflush=False, + bind=engine +) + +Base = declarative_base() + + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..81966ace62155c4a37a3cdad31aa170ce0d508c4 --- /dev/null +++ b/app/main.py @@ -0,0 +1,27 @@ +from fastapi import FastAPI +from app.api import chat, upload, documents, auth +from app.db.database import Base, engine +from app.models import user, document, chat_message +from fastapi.middleware.cors import CORSMiddleware + +Base.metadata.create_all(bind=engine) + +app = FastAPI(title="DocBrain API") + +app.include_router(auth.router, prefix="/api/v1/auth", tags=["Auth"]) +app.include_router(upload.router, prefix="/api/v1/upload", tags=["Upload"]) +app.include_router(chat.router, prefix="/api/v1/chat", tags=["Chat"]) +app.include_router(documents.router, prefix="/api/v1/documents", tags=["Documents"]) + +@app.get("/") +def home(): + return {"message": "DocBrain backend running"} + + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) diff --git a/app/models/__pycache__/chat_message.cpython-312.pyc b/app/models/__pycache__/chat_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c86363a507be89f7615608e9d934c59fd6e31406 Binary files /dev/null and b/app/models/__pycache__/chat_message.cpython-312.pyc differ diff --git a/app/models/__pycache__/document.cpython-312.pyc b/app/models/__pycache__/document.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00d1f65a30918be03907e6fdaeac98188f9323bf Binary files /dev/null and b/app/models/__pycache__/document.cpython-312.pyc differ diff --git a/app/models/__pycache__/user.cpython-312.pyc b/app/models/__pycache__/user.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24da85877eb481cb00fa06a1f53a1feecc00a84a Binary files /dev/null and b/app/models/__pycache__/user.cpython-312.pyc differ diff --git a/app/models/chat_message.py b/app/models/chat_message.py new file mode 100644 index 0000000000000000000000000000000000000000..538353371c5bce82b519a29d702979747e08c73f --- /dev/null +++ b/app/models/chat_message.py @@ -0,0 +1,19 @@ +from datetime import datetime + +from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text + +from app.db.database import Base + + +class ChatMessage(Base): + __tablename__ = "chat_messages" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True) + document_id = Column( + Integer, ForeignKey("documents.id"), nullable=False, index=True + ) + role = Column(String, nullable=False) + content = Column(Text, nullable=False) + sources = Column(Text, nullable=True) + created_at = Column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/app/models/document.py b/app/models/document.py new file mode 100644 index 0000000000000000000000000000000000000000..0abffd2a98c863c82b9ef8f969d19eebccc8a203 --- /dev/null +++ b/app/models/document.py @@ -0,0 +1,16 @@ +from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text +from datetime import datetime +from app.db.database import Base + + +class Document(Base): + __tablename__ = "documents" + + id = Column(Integer, primary_key=True, index=True) + filename = Column(String, nullable=False) + file_path = Column(String, nullable=False) + file_hash = Column(String, nullable=False) + user_id = Column(Integer, ForeignKey("users.id"), nullable=False) + status = Column(String, default="processing") + error_message = Column(Text, nullable=True) + created_at = Column(DateTime, default=datetime.utcnow) \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000000000000000000000000000000000000..6e3c8a038a9f37c540b5b41a6c1e6fbb6aea2380 --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,11 @@ +from sqlalchemy import Column, Integer, String, DateTime +from datetime import datetime +from app.db.database import Base + +class User(Base): + __tablename__ = "users" + + id = Column(Integer, primary_key=True, index=True) + username = Column(String, unique=True, index=True, nullable=False) + hashed_password = Column(String, nullable=False) + created_at = Column(DateTime, default=datetime.utcnow) \ No newline at end of file diff --git a/app/services/__pycache__/indexing_service.cpython-312.pyc b/app/services/__pycache__/indexing_service.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b6022c97b39fcccc07ae04c3282ac2bf64a1608 Binary files /dev/null and b/app/services/__pycache__/indexing_service.cpython-312.pyc differ diff --git a/app/services/__pycache__/rag_service.cpython-312.pyc b/app/services/__pycache__/rag_service.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d68e54cbe799f4e76fe38fcbd825023a8eea3a3 Binary files /dev/null and b/app/services/__pycache__/rag_service.cpython-312.pyc differ diff --git a/app/services/__pycache__/vector_service.cpython-312.pyc b/app/services/__pycache__/vector_service.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b25424ef1858c4e199f9f42f6412ede9c72a93e7 Binary files /dev/null and b/app/services/__pycache__/vector_service.cpython-312.pyc differ diff --git a/app/services/indexing_service.py b/app/services/indexing_service.py new file mode 100644 index 0000000000000000000000000000000000000000..ad0b4304daf1ca3d66ef6c44223a81622f6f22f3 --- /dev/null +++ b/app/services/indexing_service.py @@ -0,0 +1,78 @@ +import asyncio +import os +import tempfile +from app.db.database import SessionLocal +from app.models.document import Document +from app.utils.pdf_loader import extract_text +from app.utils.chunking import chunk_text +from app.services.vector_service import store_chunks +from app.services.storage_service import storage_service + + +async def index_document(document_id: int, file_path: str, filename: str, user_id: int): + db = SessionLocal() + temp_local_path = None + + try: + document = db.query(Document).filter(Document.id == document_id).first() + + if document is None: + return + + document.status = "processing" + document.error_message = None + db.commit() + + # Check if file_path is a GCS path or local path + if file_path.startswith("uploads/"): + # Download from GCS to a temporary file + with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp: + content = storage_service.download_file(file_path) + if not content: + raise Exception("Failed to download file from Google Cloud Storage") + tmp.write(content) + temp_local_path = tmp.name + processing_path = temp_local_path + else: + processing_path = file_path + + text = await asyncio.to_thread(extract_text, processing_path) + + if not text.strip(): + document.status = "failed" + document.error_message = "No text found in PDF" + db.commit() + return + + chunks = await asyncio.to_thread(chunk_text, text) + + if not chunks: + document.status = "failed" + document.error_message = "No chunks created from PDF" + db.commit() + return + + await asyncio.to_thread( + store_chunks, + chunks, + filename, + str(user_id), + str(document_id) + ) + + document.status = "indexed" + document.error_message = None + db.commit() + + except Exception as e: + document = db.query(Document).filter(Document.id == document_id).first() + + if document is not None: + document.status = "failed" + document.error_message = str(e) + db.commit() + + finally: + if temp_local_path and os.path.exists(temp_local_path): + os.remove(temp_local_path) + db.close() \ No newline at end of file diff --git a/app/services/rag_service.py b/app/services/rag_service.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc91ac7b08fe234caef98257de5db251f58d508 --- /dev/null +++ b/app/services/rag_service.py @@ -0,0 +1,259 @@ +import os +import json +import httpx +from dotenv import load_dotenv +from app.services.vector_service import get_document_chunks, search_chunks + +load_dotenv() + +GROQ_API_KEY = os.getenv("GROQ_API_KEY") + +if not GROQ_API_KEY: + raise ValueError("GROQ_API_KEY is missing in .env file") + + +BROAD_QUERY_HINTS = ( + "what is this pdf about", + "what is this document about", + "summarize this document", + "summary of this document", + "give me an overview", + "document overview", + "what does this pdf say", + "what is in this pdf", + "is this a resume", + "is this resume", + "what kind of document is this", + "what are the projects", + "list the projects", + "what projects are mentioned", +) + + +def is_broad_overview_query(query: str) -> bool: + lowered_query = query.strip().lower() + return any(hint in lowered_query for hint in BROAD_QUERY_HINTS) + + +def merge_context_docs(primary_docs, additional_docs): + merged_docs = [] + seen_keys = set() + + for doc in [*primary_docs, *additional_docs]: + metadata = doc.get("metadata", {}) + key = ( + metadata.get("document_id"), + metadata.get("chunk_index"), + doc.get("page_content", ""), + ) + + if key in seen_keys: + continue + + seen_keys.add(key) + merged_docs.append(doc) + + return merged_docs + + +def retrieve_context(query: str, user_id: str, document_id: str): + semantic_docs = search_chunks( + query=query, + k=10, + user_id=user_id, + document_id=document_id, + ) + + if is_broad_overview_query(query): + leading_docs = get_document_chunks( + user_id=user_id, + document_id=document_id, + limit=10, + ) + return merge_context_docs(leading_docs, semantic_docs) + + return semantic_docs + + +def build_prompt(query: str, docs): + context_blocks = [] + + for doc in docs: + metadata = doc.get("metadata", {}) + chunk_number = metadata.get("chunk_index") + chunk_label = ( + f"Chunk {int(chunk_number) + 1}" + if isinstance(chunk_number, int) + else "Chunk" + ) + context_blocks.append(f"[{chunk_label}]\n{doc['page_content']}") + + context = "\n\n".join(context_blocks) + + system_message = f"""You are DocBrain, a document-grounded assistant. + +Rules: +- Answer using ONLY the document excerpts below. +- For broad questions, synthesize the overall document purpose from multiple excerpts. +- If the document appears to be a resume, CV, report, proposal, or similar, say that clearly. +- Do not invent facts, names, titles, dates, or project details. +- If the answer is not supported by the excerpts, say "I don't know based on the provided document excerpts." +- Keep the answer concise, factual, and directly relevant to the question. + +Document excerpts: +{context}""" + + return query, system_message + + +def build_messages(query: str, system_message: str, chat_history: list): + messages = [ + { + "role": "system", + "content": system_message, + } + ] + for msg in chat_history: + # Groq expects strictly 'user' or 'assistant' + messages.append({ + "role": msg["role"], + "content": msg["content"] + }) + messages.append({ + "role": "user", + "content": query, + }) + return messages + + +def call_groq(query: str, system_message: str, chat_history: list) -> str: + try: + messages = build_messages(query, system_message, chat_history) + response = httpx.post( + "https://api.groq.com/openai/v1/chat/completions", + headers={ + "Authorization": f"Bearer {GROQ_API_KEY}", + "Content-Type": "application/json", + }, + json={ + "model": "llama-3.3-70b-versatile", + "messages": messages, + "temperature": 0.1, + }, + timeout=30, + ) + + response.raise_for_status() + return response.json()["choices"][0]["message"]["content"] + + except httpx.TimeoutException: + raise Exception("Groq API timeout. Please try again.") + + except httpx.HTTPStatusError as e: + raise Exception(f"Groq API error: {e.response.text}") + + except httpx.HTTPError as e: + raise Exception(f"Groq request failed: {str(e)}") + + +def stream_groq(query: str, system_message: str, chat_history: list): + try: + messages = build_messages(query, system_message, chat_history) + with httpx.stream( + "POST", + "https://api.groq.com/openai/v1/chat/completions", + headers={ + "Authorization": f"Bearer {GROQ_API_KEY}", + "Content-Type": "application/json", + }, + json={ + "model": "llama-3.3-70b-versatile", + "messages": messages, + "temperature": 0.1, + "stream": True, + }, + timeout=60, + ) as response: + + response.raise_for_status() + + for line in response.iter_lines(): + if not line: + continue + + if line.startswith("data: "): + data = line.replace("data: ", "") + + if data == "[DONE]": + break + + chunk = json.loads(data) + delta = chunk["choices"][0]["delta"].get("content") + + if delta: + yield delta + + except httpx.TimeoutException: + raise Exception("Groq API timeout. Please try again.") + + except httpx.HTTPStatusError as e: + raise Exception(f"Groq API error: {e.response.text}") + + except httpx.HTTPError as e: + raise Exception(f"Groq request failed: {str(e)}") + + +def ask_question(query: str, user_id: str, document_id: str, chat_history: list = None): + if chat_history is None: + chat_history = [] + + docs = retrieve_context( + query=query, + user_id=user_id, + document_id=document_id, + ) + + if not docs: + return { + "answer": "No relevant information found in this document.", + "sources": [], + } + + q, system_message = build_prompt(query, docs) + answer = call_groq(q, system_message, chat_history) + + return { + "answer": answer, + "sources": [doc["metadata"] for doc in docs], + } + + +def stream_answer_events(query: str, user_id: str, document_id: str, chat_history: list = None): + if chat_history is None: + chat_history = [] + + docs = retrieve_context( + query=query, + user_id=user_id, + document_id=document_id, + ) + + yield { + "type": "sources", + "sources": [doc["metadata"] for doc in docs], + } + + if not docs: + yield { + "type": "delta", + "content": "No relevant information found in this document.", + } + return + + q, system_message = build_prompt(query, docs) + + for token in stream_groq(q, system_message, chat_history): + yield { + "type": "delta", + "content": token, + } diff --git a/app/services/storage_service.py b/app/services/storage_service.py new file mode 100644 index 0000000000000000000000000000000000000000..77229111bc02b09def05d8a5a059a4c5b1cac31b --- /dev/null +++ b/app/services/storage_service.py @@ -0,0 +1,74 @@ +import os +import logging +from google.cloud import storage +from google.api_core import exceptions +from dotenv import load_dotenv + +load_dotenv() + +logger = logging.getLogger("uvicorn.error") + +# GCS Configuration +BUCKET_NAME = os.getenv("GCP_BUCKET_NAME") +# For local dev, we might not have GCS credentials, so we can fallback or mock +# In Cloud Run, credentials are automatically picked up from the service account + +class CloudStorageService: + def __init__(self): + try: + self.client = storage.Client() + self.bucket = self.client.bucket(BUCKET_NAME) if BUCKET_NAME else None + except Exception as e: + logger.warning(f"GCS Client initialization failed: {e}. Falling back to local storage if needed.") + self.client = None + self.bucket = None + + def upload_file(self, file_content: bytes, destination_blob_name: str): + """Uploads a file to the bucket.""" + if not self.bucket: + logger.error("GCS Bucket not configured. Upload failed.") + return False + + try: + blob = self.bucket.blob(destination_blob_name) + blob.upload_from_string(file_content, content_type='application/pdf') + logger.info(f"File {destination_blob_name} uploaded to {BUCKET_NAME}.") + return True + except exceptions.GoogleCloudError as e: + logger.error(f"Failed to upload {destination_blob_name} to GCS: {e}") + return False + + def download_file(self, blob_name: str) -> bytes: + """Downloads a file from the bucket as bytes.""" + if not self.bucket: + logger.error("GCS Bucket not configured. Download failed.") + return None + + try: + blob = self.bucket.blob(blob_name) + content = blob.download_as_bytes() + return content + except exceptions.GoogleCloudError as e: + logger.error(f"Failed to download {blob_name} from GCS: {e}") + return None + + def delete_file(self, blob_name: str): + """Deletes a file from the bucket.""" + if not self.bucket: + logger.error("GCS Bucket not configured. Delete failed.") + return False + + try: + blob = self.bucket.blob(blob_name) + blob.delete() + logger.info(f"File {blob_name} deleted from {BUCKET_NAME}.") + return True + except exceptions.NotFound: + logger.warning(f"File {blob_name} not found in {BUCKET_NAME}.") + return True + except exceptions.GoogleCloudError as e: + logger.error(f"Failed to delete {blob_name} from GCS: {e}") + return False + +# Singleton instance +storage_service = CloudStorageService() diff --git a/app/services/vector_service.py b/app/services/vector_service.py new file mode 100644 index 0000000000000000000000000000000000000000..d509382a69a53cb457b5fdbaa35994b4b28aa2cb --- /dev/null +++ b/app/services/vector_service.py @@ -0,0 +1,207 @@ +import os +import uuid +import httpx +import logging +from dotenv import load_dotenv +from qdrant_client import QdrantClient +from qdrant_client.models import PointStruct, Filter, FieldCondition, MatchValue + +load_dotenv() + +logger = logging.getLogger("uvicorn.error") + +COLLECTION_NAME = "docbrain_documents" + +JINA_API_KEY = os.getenv("JINA_API_KEY") +QDRANT_URL = os.getenv("QDRANT_URL") +QDRANT_API_KEY = os.getenv("QDRANT_API_KEY") + +if not JINA_API_KEY: + raise ValueError("JINA_API_KEY is missing in .env file") + +if not QDRANT_URL: + raise ValueError("QDRANT_URL is missing in .env file") + +if not QDRANT_API_KEY: + raise ValueError("QDRANT_API_KEY is missing in .env file") + +client = QdrantClient( + url=QDRANT_URL, + api_key=QDRANT_API_KEY, + check_compatibility=False +) + + +def get_embedding(text: str, task: str = "retrieval.query") -> list[float]: + response = httpx.post( + "https://api.jina.ai/v1/embeddings", + headers={ + "Authorization": f"Bearer {JINA_API_KEY}", + "Content-Type": "application/json", + }, + json={ + "model": "jina-embeddings-v3", + "task": task, + "input": [text], + }, + timeout=30, + ) + + response.raise_for_status() + return response.json()["data"][0]["embedding"] + + +def get_embeddings_batch(texts: list[str], task: str = "retrieval.passage"): + response = httpx.post( + "https://api.jina.ai/v1/embeddings", + headers={ + "Authorization": f"Bearer {JINA_API_KEY}", + "Content-Type": "application/json", + }, + json={ + "model": "jina-embeddings-v3", + "task": task, + "input": texts, + }, + timeout=30, + ) + + response.raise_for_status() + + return [item["embedding"] for item in response.json()["data"]] + + +def store_chunks(chunks, filename, user_id, document_id): + points = [] + + embeddings = get_embeddings_batch( + chunks, + task="retrieval.passage" + ) + + for index, chunk in enumerate(chunks): + points.append( + PointStruct( + id=str(uuid.uuid4()), + vector=embeddings[index], + payload={ + "text": chunk, + "source": filename, + "user_id": user_id, + "document_id": document_id, + "chunk_index": index, + }, + ) + ) + + client.upsert( + collection_name=COLLECTION_NAME, + points=points + ) + + return { + "message": "Chunks stored successfully", + "total_chunks": len(chunks) + } + + +def search_chunks(query: str, k: int = 3, user_id: str | None = None, document_id: str | None = None): + query_vector = get_embedding(query, task="retrieval.query") + + q_filter = Filter( + must=[ + FieldCondition(key="user_id", match=MatchValue(value=user_id)), + FieldCondition(key="document_id", match=MatchValue(value=document_id)), + ] + ) + + results = client.query_points( + collection_name=COLLECTION_NAME, + query=query_vector, + query_filter=q_filter, + limit=k + ) + + return [ + { + "page_content": point.payload.get("text", ""), + "metadata": { + "source": point.payload.get("source"), + "user_id": point.payload.get("user_id"), + "document_id": point.payload.get("document_id"), + "chunk_index": point.payload.get("chunk_index"), + "score": point.score, + } + } + for point in results.points + ] + + +def get_document_chunks( + user_id: str, + document_id: str, + limit: int = 6, + fetch_limit: int = 128, +): + q_filter = Filter( + must=[ + FieldCondition(key="user_id", match=MatchValue(value=user_id)), + FieldCondition(key="document_id", match=MatchValue(value=document_id)), + ] + ) + + points, _ = client.scroll( + collection_name=COLLECTION_NAME, + scroll_filter=q_filter, + with_payload=True, + with_vectors=False, + limit=fetch_limit, + ) + + sorted_points = sorted( + points, + key=lambda point: point.payload.get("chunk_index", 0), + ) + + return [ + { + "page_content": point.payload.get("text", ""), + "metadata": { + "source": point.payload.get("source"), + "user_id": point.payload.get("user_id"), + "document_id": point.payload.get("document_id"), + "chunk_index": point.payload.get("chunk_index"), + "score": None, + }, + } + for point in sorted_points[:limit] + ] + + +def delete_document_vectors(user_id: str, document_id: str): + q_filter = Filter( + must=[ + FieldCondition(key="user_id", match=MatchValue(value=user_id)), + FieldCondition(key="document_id", match=MatchValue(value=document_id)), + ] + ) + + try: + client.delete( + collection_name=COLLECTION_NAME, + points_selector=q_filter + ) + logger.info( + "Vectors deleted successfully for document %s (user %s)", + document_id, + user_id, + ) + return True + except Exception as exc: + logger.warning( + "Failed to delete vectors for document %s (user %s): %s", + document_id, + user_id, + exc, + ) + return False diff --git a/app/utils/__pycache__/chunking.cpython-312.pyc b/app/utils/__pycache__/chunking.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15b2ff90228fa338bf344a825de615363c3bba46 Binary files /dev/null and b/app/utils/__pycache__/chunking.cpython-312.pyc differ diff --git a/app/utils/__pycache__/hash.cpython-312.pyc b/app/utils/__pycache__/hash.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..356e275bd898a31ecc06add624e276d6e601929e Binary files /dev/null and b/app/utils/__pycache__/hash.cpython-312.pyc differ diff --git a/app/utils/__pycache__/pdf_loader.cpython-312.pyc b/app/utils/__pycache__/pdf_loader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50635e6bcceaa7397c039279bc1684d6582a0089 Binary files /dev/null and b/app/utils/__pycache__/pdf_loader.cpython-312.pyc differ diff --git a/app/utils/chunking.py b/app/utils/chunking.py new file mode 100644 index 0000000000000000000000000000000000000000..e024a21c67689b18ed36ca2b34605637473d0e7f --- /dev/null +++ b/app/utils/chunking.py @@ -0,0 +1,10 @@ +from langchain_text_splitters import RecursiveCharacterTextSplitter + + +def chunk_text(text): + splitter = RecursiveCharacterTextSplitter( + chunk_size=800, + chunk_overlap=150 + ) + + return splitter.split_text(text) \ No newline at end of file diff --git a/app/utils/hash.py b/app/utils/hash.py new file mode 100644 index 0000000000000000000000000000000000000000..8a21f0cc98ff10cb3417deeb7f25ebd1eb1f224b --- /dev/null +++ b/app/utils/hash.py @@ -0,0 +1,11 @@ +import hashlib + + +def generate_file_hash(file_path: str) -> str: + hash_sha256 = hashlib.sha256() + + with open(file_path, "rb") as f: + for chunk in iter(lambda: f.read(4096), b""): + hash_sha256.update(chunk) + + return hash_sha256.hexdigest() \ No newline at end of file diff --git a/app/utils/pdf_loader.py b/app/utils/pdf_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..bf34368d900fee751d6e21d9e96d301184fb5fbf --- /dev/null +++ b/app/utils/pdf_loader.py @@ -0,0 +1,12 @@ +import pdfplumber + +def extract_text(file_path): + text = "" + + with pdfplumber.open(file_path) as pdf: + for page in pdf.pages: + page_text = page.extract_text() + if page_text: + text += page_text + "\n" + + return text \ No newline at end of file diff --git a/create_qdrant_collection.py b/create_qdrant_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..ba1a4670c9f34af31c3b3c3df08b28f98f8d6f62 --- /dev/null +++ b/create_qdrant_collection.py @@ -0,0 +1,58 @@ +import os +from dotenv import load_dotenv +from qdrant_client import QdrantClient +from qdrant_client.models import VectorParams, Distance, PayloadSchemaType + +load_dotenv() + +QDRANT_URL = os.getenv("QDRANT_URL") +QDRANT_API_KEY = os.getenv("QDRANT_API_KEY") + +COLLECTION_NAME = "docbrain_documents" +VECTOR_SIZE = 1024 # Jina embedding size + + +def main(): + client = QdrantClient( + url=QDRANT_URL, + api_key=QDRANT_API_KEY, + check_compatibility=False + ) + + # Create collection if not exists + if not client.collection_exists(COLLECTION_NAME): + client.create_collection( + collection_name=COLLECTION_NAME, + vectors_config=VectorParams( + size=VECTOR_SIZE, + distance=Distance.COSINE + ) + ) + print(f"✅ Collection '{COLLECTION_NAME}' created with vector size: {VECTOR_SIZE}") + else: + print(f"â„šī¸ Collection '{COLLECTION_NAME}' already exists") + + # Create indexes for filtering + try: + client.create_payload_index( + collection_name=COLLECTION_NAME, + field_name="user_id", + field_schema=PayloadSchemaType.KEYWORD + ) + print("Index created for user_id") + except Exception: + print("Index already exists for user_id") + + try: + client.create_payload_index( + collection_name=COLLECTION_NAME, + field_name="document_id", + field_schema=PayloadSchemaType.KEYWORD + ) + print("Index created for document_id") + except Exception: + print("Index already exists for document_id") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..086f9dc5fb5538624d5d04352c964d794e40b278 Binary files /dev/null and b/requirements.txt differ diff --git a/test_jina.py b/test_jina.py new file mode 100644 index 0000000000000000000000000000000000000000..2269bdd7156f17c0119558c7e91dacd1dd50f66b --- /dev/null +++ b/test_jina.py @@ -0,0 +1,19 @@ +import httpx +import os +from dotenv import load_dotenv + +load_dotenv() + +response = httpx.post( + "https://api.jina.ai/v1/embeddings", + headers={ + "Authorization": f"Bearer {os.getenv('JINA_API_KEY')}", + "Content-Type": "application/json", + }, + json={ + "model": "jina-embeddings-v3", + "input": ["Hello world"], + }, +) + +print(response.json()) \ No newline at end of file diff --git a/test_qdrant.py b/test_qdrant.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e79d7caacf9ac2eba51002a9bdce26d81c702e --- /dev/null +++ b/test_qdrant.py @@ -0,0 +1,13 @@ +from qdrant_client import QdrantClient +import os +from dotenv import load_dotenv + +load_dotenv() + +client = QdrantClient( + url=os.getenv("QDRANT_URL"), + api_key=os.getenv("QDRANT_API_KEY"), + check_compatibility=False +) + +print(client.get_collections()) \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/__pycache__/__init__.cpython-312.pyc b/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cbc74fb158c19116cd4737d0798fe0c63852a94 Binary files /dev/null and b/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/tests/__pycache__/test_auth.cpython-312-pytest-9.0.3.pyc b/tests/__pycache__/test_auth.cpython-312-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48279065432f42d954dff5f99c13354e510d9cfa Binary files /dev/null and b/tests/__pycache__/test_auth.cpython-312-pytest-9.0.3.pyc differ diff --git a/tests/__pycache__/test_chunking.cpython-312-pytest-9.0.3.pyc b/tests/__pycache__/test_chunking.cpython-312-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..615597abe59e71aaef06458e07cd9ad6cf2b149f Binary files /dev/null and b/tests/__pycache__/test_chunking.cpython-312-pytest-9.0.3.pyc differ diff --git a/tests/__pycache__/test_documents.cpython-312-pytest-9.0.3.pyc b/tests/__pycache__/test_documents.cpython-312-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d50260bdcfe157ff354cfa4c21773301942cb672 Binary files /dev/null and b/tests/__pycache__/test_documents.cpython-312-pytest-9.0.3.pyc differ diff --git a/tests/__pycache__/test_hash.cpython-312-pytest-9.0.3.pyc b/tests/__pycache__/test_hash.cpython-312-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19efb1c2d1f89447a64794a493e75695ebd193a9 Binary files /dev/null and b/tests/__pycache__/test_hash.cpython-312-pytest-9.0.3.pyc differ diff --git a/tests/__pycache__/test_pdf_loader.cpython-312-pytest-9.0.3.pyc b/tests/__pycache__/test_pdf_loader.cpython-312-pytest-9.0.3.pyc new file mode 100644 index 0000000000000000000000000000000000000000..455b78550d67d9fa1caa4b47fa30ca01148c8573 Binary files /dev/null and b/tests/__pycache__/test_pdf_loader.cpython-312-pytest-9.0.3.pyc differ diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..ec5737942533b59973bc684e76720594bead1cd1 --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,17 @@ +from app.core.security import hash_password, verify_password, create_access_token + + +def test_hash_password(): + password = "Test@1234" + + hashed = hash_password(password) + + assert hashed != password + assert verify_password(password, hashed) is True + + +def test_create_access_token(): + token = create_access_token({"sub": "1", "username": "testuser"}) + + assert isinstance(token, str) + assert len(token) > 20 \ No newline at end of file diff --git a/tests/test_chunking.py b/tests/test_chunking.py new file mode 100644 index 0000000000000000000000000000000000000000..85478c07b1cbda9cb9a5eeb55a1ecb85fc37d8fe --- /dev/null +++ b/tests/test_chunking.py @@ -0,0 +1,11 @@ +from app.utils.chunking import chunk_text + + +def test_chunk_text_returns_chunks(): + text = "This is a sample text. " * 100 + + chunks = chunk_text(text) + + assert isinstance(chunks, list) + assert len(chunks) > 0 + assert isinstance(chunks[0], str) \ No newline at end of file diff --git a/tests/test_documents.py b/tests/test_documents.py new file mode 100644 index 0000000000000000000000000000000000000000..a784d2c89cbcdab4123af2f80c83edfa30e1fa56 --- /dev/null +++ b/tests/test_documents.py @@ -0,0 +1,16 @@ +from app.models.document import Document + + +def test_document_model_creation(): + document = Document( + filename="sample.pdf", + file_path="uploads/user_1/1_sample.pdf", + user_id=1, + file_hash="a" * 64, + status="processing" + ) + + assert document.filename == "sample.pdf" + assert document.user_id == 1 + assert document.status == "processing" + assert len(document.file_hash) == 64 \ No newline at end of file diff --git a/tests/test_hash.py b/tests/test_hash.py new file mode 100644 index 0000000000000000000000000000000000000000..1dda44ca92fccdf37e8c638c3ce3482b13b2cc93 --- /dev/null +++ b/tests/test_hash.py @@ -0,0 +1,11 @@ +from app.utils.hash import generate_file_hash + + +def test_generate_file_hash(tmp_path): + file_path = tmp_path / "sample.txt" + file_path.write_text("hello world") + + file_hash = generate_file_hash(str(file_path)) + + assert isinstance(file_hash, str) + assert len(file_hash) == 64 \ No newline at end of file diff --git a/tests/test_pdf_loader.py b/tests/test_pdf_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..d3b069e12adc0b3ca9330ea23109cd02286473fd --- /dev/null +++ b/tests/test_pdf_loader.py @@ -0,0 +1,8 @@ +from app.utils.pdf_loader import extract_text + + +def test_extract_text_from_pdf(): + text = extract_text("uploads/Local Creator Marketplace – Project Proposal.pdf") + + assert isinstance(text, str) + assert len(text) > 0 \ No newline at end of file