Spaces:
Sleeping

MUHAMMED THABSHEER P commited on
Commit
45e7ae0
·
0 Parent(s):

Files added

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +23 -0
  2. app/__pycache__/main.cpython-312.pyc +0 -0
  3. app/api/__pycache__/auth.cpython-312.pyc +0 -0
  4. app/api/__pycache__/chat.cpython-312.pyc +0 -0
  5. app/api/__pycache__/documents.cpython-312.pyc +0 -0
  6. app/api/__pycache__/upload.cpython-312.pyc +0 -0
  7. app/api/auth.py +72 -0
  8. app/api/chat.py +363 -0
  9. app/api/documents.py +121 -0
  10. app/api/upload.py +99 -0
  11. app/core/__pycache__/dependencies.cpython-312.pyc +0 -0
  12. app/core/__pycache__/security.cpython-312.pyc +0 -0
  13. app/core/dependencies.py +40 -0
  14. app/core/security.py +41 -0
  15. app/db/__pycache__/database.cpython-312.pyc +0 -0
  16. app/db/database.py +29 -0
  17. app/main.py +27 -0
  18. app/models/__pycache__/chat_message.cpython-312.pyc +0 -0
  19. app/models/__pycache__/document.cpython-312.pyc +0 -0
  20. app/models/__pycache__/user.cpython-312.pyc +0 -0
  21. app/models/chat_message.py +19 -0
  22. app/models/document.py +16 -0
  23. app/models/user.py +11 -0
  24. app/services/__pycache__/indexing_service.cpython-312.pyc +0 -0
  25. app/services/__pycache__/rag_service.cpython-312.pyc +0 -0
  26. app/services/__pycache__/vector_service.cpython-312.pyc +0 -0
  27. app/services/indexing_service.py +78 -0
  28. app/services/rag_service.py +259 -0
  29. app/services/storage_service.py +74 -0
  30. app/services/vector_service.py +207 -0
  31. app/utils/__pycache__/chunking.cpython-312.pyc +0 -0
  32. app/utils/__pycache__/hash.cpython-312.pyc +0 -0
  33. app/utils/__pycache__/pdf_loader.cpython-312.pyc +0 -0
  34. app/utils/chunking.py +10 -0
  35. app/utils/hash.py +11 -0
  36. app/utils/pdf_loader.py +12 -0
  37. create_qdrant_collection.py +58 -0
  38. requirements.txt +0 -0
  39. test_jina.py +19 -0
  40. test_qdrant.py +13 -0
  41. tests/__init__.py +0 -0
  42. tests/__pycache__/__init__.cpython-312.pyc +0 -0
  43. tests/__pycache__/test_auth.cpython-312-pytest-9.0.3.pyc +0 -0
  44. tests/__pycache__/test_chunking.cpython-312-pytest-9.0.3.pyc +0 -0
  45. tests/__pycache__/test_documents.cpython-312-pytest-9.0.3.pyc +0 -0
  46. tests/__pycache__/test_hash.cpython-312-pytest-9.0.3.pyc +0 -0
  47. tests/__pycache__/test_pdf_loader.cpython-312-pytest-9.0.3.pyc +0 -0
  48. tests/test_auth.py +17 -0
  49. tests/test_chunking.py +11 -0
  50. tests/test_documents.py +16 -0
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install system dependencies for PostgreSQL and other libraries
6
+ RUN apt-get update && apt-get install -y \
7
+ build-essential \
8
+ libpq-dev \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # Copy requirements and install dependencies
12
+ COPY requirements.txt .
13
+ RUN pip install --no-cache-dir -r requirements.txt
14
+
15
+ # Copy the rest of the application code
16
+ COPY . .
17
+
18
+ # Set environment variables for Cloud Run compatibility
19
+ ENV PORT=8080
20
+ EXPOSE 8080
21
+
22
+ # Run the application using uvicorn
23
+ CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT}"]
app/__pycache__/main.cpython-312.pyc ADDED
Binary file (1.53 kB). View file
 
app/api/__pycache__/auth.cpython-312.pyc ADDED
Binary file (3.3 kB). View file
 
app/api/__pycache__/chat.cpython-312.pyc ADDED
Binary file (16.1 kB). View file
 
app/api/__pycache__/documents.cpython-312.pyc ADDED
Binary file (4.34 kB). View file
 
app/api/__pycache__/upload.cpython-312.pyc ADDED
Binary file (3.66 kB). View file
 
app/api/auth.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, HTTPException
2
+ from pydantic import BaseModel
3
+ from sqlalchemy.orm import Session
4
+
5
+ from app.db.database import get_db
6
+ from app.models.user import User
7
+ from app.core.security import hash_password, verify_password, create_access_token
8
+ from fastapi.security import OAuth2PasswordRequestForm
9
+
10
+ router = APIRouter()
11
+
12
+
13
+ class RegisterRequest(BaseModel):
14
+ username: str
15
+ password: str
16
+
17
+
18
+ class LoginRequest(BaseModel):
19
+ username: str
20
+ password: str
21
+
22
+
23
+ @router.post("/register")
24
+ def register(request: RegisterRequest, db: Session = Depends(get_db)):
25
+ existing_user = db.query(User).filter(User.username == request.username).first()
26
+
27
+ if existing_user:
28
+ raise HTTPException(status_code=400, detail="Username already exists")
29
+
30
+ new_user = User(
31
+ username=request.username,
32
+ hashed_password=hash_password(request.password)
33
+ )
34
+
35
+ db.add(new_user)
36
+ db.commit()
37
+ db.refresh(new_user)
38
+
39
+ return {
40
+ "message": "User registered successfully",
41
+ "user_id": new_user.id,
42
+ "username": new_user.username
43
+ }
44
+
45
+
46
+ @router.post("/login")
47
+ def login(
48
+ form_data: OAuth2PasswordRequestForm = Depends(),
49
+ db: Session = Depends(get_db)
50
+ ):
51
+ user = db.query(User).filter(User.username == form_data.username).first()
52
+
53
+ if not user:
54
+ raise HTTPException(status_code=401, detail="Invalid username or password")
55
+
56
+ if not verify_password(form_data.password, user.hashed_password):
57
+ raise HTTPException(status_code=401, detail="Invalid username or password")
58
+
59
+ token = create_access_token(
60
+ data={"sub": str(user.id), "username": user.username}
61
+ )
62
+
63
+ return {
64
+ "access_token": token,
65
+ "token_type": "bearer"
66
+ }
67
+
68
+ @router.post("/logout")
69
+ def logout():
70
+ return {
71
+ "message": "Logout successful. Please remove token from client."
72
+ }
app/api/chat.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+
4
+ from fastapi import APIRouter, Depends, HTTPException
5
+ from pydantic import BaseModel
6
+ from sqlalchemy.orm import Session
7
+
8
+ from app.services.rag_service import ask_question
9
+ from app.core.dependencies import get_current_user
10
+ from app.db.database import get_db
11
+ from app.models.user import User
12
+ from app.models.document import Document
13
+ from app.models.chat_message import ChatMessage
14
+ from fastapi.responses import StreamingResponse
15
+ from app.services.rag_service import stream_answer_events
16
+
17
+ router = APIRouter()
18
+ logger = logging.getLogger("uvicorn.error")
19
+
20
+
21
+ def serialize_sse_event(payload: dict) -> str:
22
+ return f"data: {json.dumps(payload)}\n\n"
23
+
24
+
25
+ class ChatRequest(BaseModel):
26
+ query: str
27
+ document_id: int
28
+
29
+
30
+ def serialize_chat_message(message: ChatMessage):
31
+ return {
32
+ "id": message.id,
33
+ "role": message.role,
34
+ "content": message.content,
35
+ "document_id": message.document_id,
36
+ "sources": json.loads(message.sources) if message.sources else [],
37
+ "created_at": message.created_at,
38
+ }
39
+
40
+
41
+ @router.get("/history/{document_id}")
42
+ def get_chat_history(
43
+ document_id: int,
44
+ current_user: User = Depends(get_current_user),
45
+ db: Session = Depends(get_db)
46
+ ):
47
+ document = db.query(Document).filter(
48
+ Document.id == document_id,
49
+ Document.user_id == current_user.id
50
+ ).first()
51
+
52
+ if document is None:
53
+ raise HTTPException(status_code=404, detail="Document not found")
54
+
55
+ messages = db.query(ChatMessage).filter(
56
+ ChatMessage.document_id == document_id,
57
+ ChatMessage.user_id == current_user.id
58
+ ).order_by(ChatMessage.created_at.asc(), ChatMessage.id.asc()).all()
59
+
60
+ return {
61
+ "document_id": document_id,
62
+ "messages": [serialize_chat_message(message) for message in messages],
63
+ }
64
+
65
+
66
+ @router.get("/activity")
67
+ def get_recent_activity(
68
+ limit: int = 20,
69
+ current_user: User = Depends(get_current_user),
70
+ db: Session = Depends(get_db)
71
+ ):
72
+ """Get recent chat messages across all user documents."""
73
+ messages = (
74
+ db.query(ChatMessage)
75
+ .join(Document, ChatMessage.document_id == Document.id)
76
+ .filter(Document.user_id == current_user.id)
77
+ .order_by(ChatMessage.created_at.desc(), ChatMessage.id.desc())
78
+ .limit(limit)
79
+ .all()
80
+ )
81
+ return [serialize_chat_message(msg) for msg in messages]
82
+
83
+
84
+ @router.get("/stats")
85
+ def get_usage_stats(
86
+ current_user: User = Depends(get_current_user),
87
+ db: Session = Depends(get_db)
88
+ ):
89
+ """Get usage statistics for the user."""
90
+ total_docs = db.query(Document).filter(Document.user_id == current_user.id).count()
91
+ total_messages = db.query(ChatMessage).filter(ChatMessage.user_id == current_user.id).count()
92
+
93
+ # Get count of processing docs
94
+ processing_docs = db.query(Document).filter(
95
+ Document.user_id == current_user.id,
96
+ Document.status == "processing"
97
+ ).count()
98
+
99
+ # Get daily message stats for the last 7 days
100
+ from datetime import datetime, timedelta
101
+ from sqlalchemy import func, cast, Date
102
+
103
+ seven_days_ago = datetime.utcnow().date() - timedelta(days=6)
104
+
105
+ daily_messages = (
106
+ db.query(
107
+ cast(ChatMessage.created_at, Date).label("date"),
108
+ func.count(ChatMessage.id).label("count")
109
+ )
110
+ .filter(
111
+ ChatMessage.user_id == current_user.id,
112
+ cast(ChatMessage.created_at, Date) >= seven_days_ago
113
+ )
114
+ .group_by(cast(ChatMessage.created_at, Date))
115
+ .order_by(cast(ChatMessage.created_at, Date).asc())
116
+ .all()
117
+ )
118
+
119
+ # Fill in gaps for days with zero messages
120
+ stats_map = {row.date.strftime("%Y-%m-%d"): row.count for row in daily_messages}
121
+ chart_data = []
122
+ for i in range(7):
123
+ day = seven_days_ago + timedelta(days=i)
124
+ day_str = day.strftime("%Y-%m-%d")
125
+ chart_data.append({
126
+ "date": day.strftime("%b %d"),
127
+ "messages": stats_map.get(day_str, 0)
128
+ })
129
+
130
+ return {
131
+ "total_documents": total_docs,
132
+ "total_messages": total_messages,
133
+ "processing_documents": processing_docs,
134
+ "chart_data": chart_data
135
+ }
136
+
137
+
138
+ @router.post("/")
139
+ def chat(
140
+ request: ChatRequest,
141
+ current_user: User = Depends(get_current_user),
142
+ db: Session = Depends(get_db)
143
+ ):
144
+ document: Document | None = db.query(Document).filter(
145
+ Document.id == request.document_id,
146
+ Document.user_id == current_user.id
147
+ ).first()
148
+
149
+ if document is None:
150
+ raise HTTPException(status_code=404, detail="Document not found")
151
+
152
+ document_status = str(document.status)
153
+
154
+ if document_status == "processing":
155
+ raise HTTPException(status_code=400, detail="Document is still processing")
156
+
157
+ if document_status == "failed":
158
+ raise HTTPException(
159
+ status_code=400,
160
+ detail=f"Document indexing failed: {document.error_message}"
161
+ )
162
+
163
+ history_messages = db.query(ChatMessage).filter(
164
+ ChatMessage.document_id == request.document_id,
165
+ ChatMessage.user_id == current_user.id
166
+ ).order_by(ChatMessage.created_at.desc(), ChatMessage.id.desc()).limit(10).all()
167
+ history_messages.reverse()
168
+ chat_history = [{"role": msg.role, "content": msg.content} for msg in history_messages]
169
+
170
+ user_message = ChatMessage(
171
+ user_id=current_user.id,
172
+ document_id=request.document_id,
173
+ role="user",
174
+ content=request.query,
175
+ sources=None,
176
+ )
177
+
178
+ assistant_content = ""
179
+ assistant_sources: list[dict] = []
180
+ fallback_response = False
181
+
182
+ try:
183
+ response = ask_question(
184
+ query=request.query,
185
+ user_id=str(current_user.id),
186
+ document_id=str(request.document_id),
187
+ chat_history=chat_history
188
+ )
189
+ assistant_content = response["answer"]
190
+ assistant_sources = response.get("sources", [])
191
+ except Exception as exc:
192
+ logger.warning(
193
+ "Chat answer generation failed for document %s (user %s): %s",
194
+ request.document_id,
195
+ current_user.id,
196
+ exc,
197
+ )
198
+ assistant_content = (
199
+ "I couldn't generate an answer right now. Please try again in a moment."
200
+ )
201
+ assistant_sources = []
202
+ fallback_response = True
203
+
204
+ assistant_message = ChatMessage(
205
+ user_id=current_user.id,
206
+ document_id=request.document_id,
207
+ role="assistant",
208
+ content=assistant_content,
209
+ sources=json.dumps(assistant_sources),
210
+ )
211
+
212
+ db.add(user_message)
213
+ db.add(assistant_message)
214
+ db.commit()
215
+
216
+ return {
217
+ "answer": assistant_content,
218
+ "sources": assistant_sources,
219
+ "fallback": fallback_response,
220
+ }
221
+
222
+
223
+ @router.delete("/history/{document_id}", status_code=204)
224
+ def clear_chat_history(
225
+ document_id: int,
226
+ current_user: User = Depends(get_current_user),
227
+ db: Session = Depends(get_db)
228
+ ):
229
+ document = db.query(Document).filter(
230
+ Document.id == document_id,
231
+ Document.user_id == current_user.id
232
+ ).first()
233
+
234
+ if document is None:
235
+ raise HTTPException(status_code=404, detail="Document not found")
236
+
237
+ db.query(ChatMessage).filter(
238
+ ChatMessage.document_id == document_id,
239
+ ChatMessage.user_id == current_user.id
240
+ ).delete(synchronize_session=False)
241
+ db.commit()
242
+
243
+
244
+ @router.post("/stream")
245
+ def chat_stream(
246
+ request: ChatRequest,
247
+ current_user: User = Depends(get_current_user),
248
+ db: Session = Depends(get_db)
249
+ ):
250
+ document = db.query(Document).filter(
251
+ Document.id == request.document_id,
252
+ Document.user_id == current_user.id
253
+ ).first()
254
+
255
+ if not document:
256
+ raise HTTPException(status_code=404, detail="Document not found")
257
+
258
+ if document.status == "processing":
259
+ raise HTTPException(status_code=400, detail="Document is still processing")
260
+
261
+ if document.status == "failed":
262
+ raise HTTPException(
263
+ status_code=400,
264
+ detail=f"Document indexing failed: {document.error_message}"
265
+ )
266
+
267
+ history_messages = db.query(ChatMessage).filter(
268
+ ChatMessage.document_id == request.document_id,
269
+ ChatMessage.user_id == current_user.id
270
+ ).order_by(ChatMessage.created_at.desc(), ChatMessage.id.desc()).limit(10).all()
271
+ history_messages.reverse()
272
+ chat_history = [{"role": msg.role, "content": msg.content} for msg in history_messages]
273
+
274
+ user_message = ChatMessage(
275
+ user_id=current_user.id,
276
+ document_id=request.document_id,
277
+ role="user",
278
+ content=request.query,
279
+ sources=None,
280
+ )
281
+ db.add(user_message)
282
+ db.commit()
283
+ db.refresh(user_message)
284
+
285
+ def event_stream():
286
+ assistant_parts: list[str] = []
287
+ assistant_sources: list[dict] = []
288
+ fallback_response = False
289
+
290
+ try:
291
+ yield serialize_sse_event({
292
+ "type": "start",
293
+ "messageId": user_message.id,
294
+ })
295
+
296
+ for event in stream_answer_events(
297
+ query=request.query,
298
+ user_id=str(current_user.id),
299
+ document_id=str(request.document_id),
300
+ chat_history=chat_history
301
+ ):
302
+ if event["type"] == "sources":
303
+ assistant_sources = event.get("sources", [])
304
+ yield serialize_sse_event(event)
305
+ continue
306
+
307
+ if event["type"] == "delta":
308
+ token = event.get("content", "")
309
+ assistant_parts.append(token)
310
+ yield serialize_sse_event(event)
311
+ except Exception as exc:
312
+ logger.warning(
313
+ "Chat stream generation failed for document %s (user %s): %s",
314
+ request.document_id,
315
+ current_user.id,
316
+ exc,
317
+ )
318
+ fallback_response = True
319
+ fallback_text = (
320
+ "I couldn't generate an answer right now. Please try again in a moment."
321
+ )
322
+ assistant_parts = [fallback_text]
323
+ assistant_sources = []
324
+ yield serialize_sse_event({
325
+ "type": "delta",
326
+ "content": fallback_text,
327
+ })
328
+ finally:
329
+ assistant_content = "".join(assistant_parts).strip()
330
+
331
+ if not assistant_content:
332
+ assistant_content = (
333
+ "I couldn't generate an answer right now. Please try again in a moment."
334
+ )
335
+ fallback_response = True
336
+
337
+ assistant_message = ChatMessage(
338
+ user_id=current_user.id,
339
+ document_id=request.document_id,
340
+ role="assistant",
341
+ content=assistant_content,
342
+ sources=json.dumps(assistant_sources),
343
+ )
344
+ db.add(assistant_message)
345
+ db.commit()
346
+ db.refresh(assistant_message)
347
+
348
+ yield serialize_sse_event({
349
+ "type": "done",
350
+ "messageId": assistant_message.id,
351
+ "sources": assistant_sources,
352
+ "fallback": fallback_response,
353
+ })
354
+
355
+ return StreamingResponse(
356
+ event_stream(),
357
+ media_type="text/event-stream",
358
+ headers={
359
+ "Cache-Control": "no-cache",
360
+ "Connection": "keep-alive",
361
+ "X-Accel-Buffering": "no",
362
+ },
363
+ )
app/api/documents.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ from fastapi import APIRouter, Depends, HTTPException
4
+ from fastapi.responses import FileResponse, StreamingResponse
5
+ from sqlalchemy.orm import Session
6
+
7
+ from app.db.database import get_db
8
+ from app.core.dependencies import get_current_user
9
+ from app.models.user import User
10
+ from app.models.document import Document
11
+ from app.services.vector_service import delete_document_vectors
12
+ from app.services.storage_service import storage_service
13
+
14
+ router = APIRouter()
15
+
16
+
17
+ @router.get("/")
18
+ def list_documents(
19
+ current_user: User = Depends(get_current_user),
20
+ db: Session = Depends(get_db)
21
+ ):
22
+ documents = db.query(Document).filter(
23
+ Document.user_id == current_user.id
24
+ ).order_by(Document.created_at.desc()).all()
25
+
26
+ return {
27
+ "documents": [
28
+ {
29
+ "document_id": doc.id,
30
+ "filename": doc.filename,
31
+ "status": doc.status,
32
+ "error_message": doc.error_message,
33
+ "uploaded_at": doc.created_at
34
+ }
35
+ for doc in documents
36
+ ]
37
+ }
38
+
39
+
40
+ @router.get("/{document_id}/file")
41
+ def get_document_file(
42
+ document_id: int,
43
+ current_user: User = Depends(get_current_user),
44
+ db: Session = Depends(get_db)
45
+ ):
46
+ document = db.query(Document).filter(
47
+ Document.id == document_id,
48
+ Document.user_id == current_user.id
49
+ ).first()
50
+
51
+ if document is None:
52
+ raise HTTPException(status_code=404, detail="Document not found")
53
+
54
+ # Check if it's GCS path
55
+ if document.file_path.startswith("uploads/"):
56
+ content = storage_service.download_file(document.file_path)
57
+ if not content:
58
+ raise HTTPException(status_code=404, detail="File not found in cloud storage")
59
+
60
+ return StreamingResponse(
61
+ io.BytesIO(content),
62
+ media_type="application/pdf",
63
+ headers={"Content-Disposition": f"inline; filename={document.filename}"}
64
+ )
65
+
66
+ # Fallback to local
67
+ if not document.file_path or not os.path.exists(document.file_path):
68
+ raise HTTPException(status_code=404, detail="File not found")
69
+
70
+ return FileResponse(
71
+ path=document.file_path,
72
+ media_type="application/pdf",
73
+ filename=document.filename
74
+ )
75
+
76
+
77
+ @router.delete("/{document_id}")
78
+ def delete_document(
79
+ document_id: int,
80
+ current_user: User = Depends(get_current_user),
81
+ db: Session = Depends(get_db)
82
+ ):
83
+ document_query = db.query(Document).filter(
84
+ Document.id == document_id,
85
+ Document.user_id == current_user.id
86
+ )
87
+ document = document_query.first()
88
+
89
+ if document is None:
90
+ raise HTTPException(status_code=404, detail="Document not found")
91
+
92
+ # Delete from GCS if applicable
93
+ if document.file_path.startswith("uploads/"):
94
+ storage_service.delete_file(document.file_path)
95
+ elif document.file_path and os.path.exists(document.file_path):
96
+ os.remove(document.file_path)
97
+
98
+ vectors_deleted = delete_document_vectors(
99
+ user_id=str(current_user.id),
100
+ document_id=str(document.id)
101
+ )
102
+
103
+ rows_deleted = document_query.delete(synchronize_session=False)
104
+ db.commit()
105
+
106
+ response = {
107
+ "message": "Document deleted successfully",
108
+ "document_id": document_id
109
+ }
110
+
111
+ if rows_deleted == 0:
112
+ response["warning"] = (
113
+ "Document metadata was already removed before delete confirmation."
114
+ )
115
+
116
+ if not vectors_deleted:
117
+ response["warning"] = (
118
+ "Document was removed from the app, but vector cleanup could not be completed."
119
+ )
120
+
121
+ return response
app/api/upload.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ import tempfile
4
+ from fastapi import APIRouter, UploadFile, File, HTTPException, Depends, BackgroundTasks
5
+ from sqlalchemy.orm import Session
6
+
7
+ from app.db.database import get_db
8
+ from app.core.dependencies import get_current_user
9
+ from app.models.user import User
10
+ from app.models.document import Document
11
+ from app.services.indexing_service import index_document
12
+ from app.utils.hash import generate_file_hash
13
+ from app.services.storage_service import storage_service
14
+
15
+ router = APIRouter()
16
+
17
+
18
+ @router.post("/")
19
+ async def upload_pdf(
20
+ background_tasks: BackgroundTasks,
21
+ file: UploadFile = File(...),
22
+ current_user: User = Depends(get_current_user),
23
+ db: Session = Depends(get_db)
24
+ ):
25
+ filename = file.filename
26
+
27
+ if not filename:
28
+ raise HTTPException(status_code=400, detail="Filename is missing")
29
+
30
+ if not filename.lower().endswith(".pdf"):
31
+ raise HTTPException(status_code=400, detail="Only PDF files are allowed")
32
+
33
+ # Read file content
34
+ content = await file.read()
35
+
36
+ # Save to a temporary file to generate hash
37
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
38
+ tmp.write(content)
39
+ temp_path = tmp.name
40
+
41
+ try:
42
+ file_hash = generate_file_hash(temp_path)
43
+
44
+ existing_doc = db.query(Document).filter(
45
+ Document.user_id == current_user.id,
46
+ Document.file_hash == file_hash
47
+ ).first()
48
+
49
+ if existing_doc:
50
+ os.remove(temp_path)
51
+ return {
52
+ "message": "File already uploaded",
53
+ "document_id": existing_doc.id,
54
+ "filename": existing_doc.filename,
55
+ "status": existing_doc.status
56
+ }
57
+
58
+ # Create document entry first to get ID
59
+ new_document = Document(
60
+ filename=filename,
61
+ file_path="pending", # Will update after GCS upload
62
+ user_id=current_user.id,
63
+ file_hash=file_hash,
64
+ status="processing"
65
+ )
66
+ db.add(new_document)
67
+ db.commit()
68
+ db.refresh(new_document)
69
+
70
+ # Upload to GCS: storage/user_id/doc_id_filename.pdf
71
+ gcs_blob_name = f"uploads/user_{current_user.id}/{new_document.id}_{filename}"
72
+
73
+ upload_success = storage_service.upload_file(content, gcs_blob_name)
74
+
75
+ if not upload_success:
76
+ db.delete(new_document)
77
+ db.commit()
78
+ raise HTTPException(status_code=500, detail="Failed to upload file to cloud storage")
79
+
80
+ new_document.file_path = gcs_blob_name
81
+ db.commit()
82
+
83
+ background_tasks.add_task(
84
+ index_document,
85
+ new_document.id,
86
+ gcs_blob_name,
87
+ filename,
88
+ current_user.id
89
+ )
90
+
91
+ return {
92
+ "message": "PDF uploaded successfully. Indexing started.",
93
+ "document_id": new_document.id,
94
+ "filename": filename,
95
+ "status": new_document.status
96
+ }
97
+ finally:
98
+ if os.path.exists(temp_path):
99
+ os.remove(temp_path)
app/core/__pycache__/dependencies.cpython-312.pyc ADDED
Binary file (1.74 kB). View file
 
app/core/__pycache__/security.cpython-312.pyc ADDED
Binary file (1.87 kB). View file
 
app/core/dependencies.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from fastapi import Depends, HTTPException
4
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
5
+ from jose import jwt, JWTError
6
+ from sqlalchemy.orm import Session
7
+
8
+ from app.db.database import get_db
9
+ from app.models.user import User
10
+
11
+ load_dotenv()
12
+
13
+ SECRET_KEY = os.getenv("SECRET_KEY")
14
+ ALGORITHM = os.getenv("ALGORITHM", "HS256")
15
+
16
+ bearer_scheme = HTTPBearer()
17
+
18
+
19
+ def get_current_user(
20
+ credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
21
+ db: Session = Depends(get_db)
22
+ ):
23
+ token = credentials.credentials
24
+
25
+ try:
26
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
27
+ user_id = payload.get("sub")
28
+
29
+ if user_id is None:
30
+ raise HTTPException(status_code=401, detail="Invalid token")
31
+
32
+ except JWTError:
33
+ raise HTTPException(status_code=401, detail="Invalid token")
34
+
35
+ user = db.query(User).filter(User.id == int(user_id)).first()
36
+
37
+ if not user:
38
+ raise HTTPException(status_code=401, detail="User not found")
39
+
40
+ return user
app/core/security.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from datetime import datetime, timedelta, timezone
3
+ from dotenv import load_dotenv
4
+ from passlib.context import CryptContext
5
+ from jose import jwt
6
+
7
+ load_dotenv()
8
+
9
+ # ENV VARIABLES
10
+ SECRET_KEY = os.getenv("SECRET_KEY")
11
+ if not SECRET_KEY:
12
+ raise ValueError("SECRET_KEY is missing in .env file")
13
+
14
+ ALGORITHM = os.getenv("ALGORITHM", "HS256")
15
+ ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", 60))
16
+
17
+ # PASSWORD HASHING
18
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
19
+
20
+
21
+ def hash_password(password: str):
22
+ return pwd_context.hash(password)
23
+
24
+
25
+ def verify_password(plain_password: str, hashed_password: str):
26
+ return pwd_context.verify(plain_password, hashed_password)
27
+
28
+
29
+ # JWT TOKEN
30
+ def create_access_token(data: dict):
31
+ to_encode = data.copy()
32
+
33
+ expire = datetime.now(timezone.utc) + timedelta(
34
+ minutes=ACCESS_TOKEN_EXPIRE_MINUTES
35
+ )
36
+
37
+ to_encode.update({"exp": expire})
38
+
39
+ encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
40
+
41
+ return encoded_jwt
app/db/__pycache__/database.cpython-312.pyc ADDED
Binary file (937 Bytes). View file
 
app/db/database.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from sqlalchemy import create_engine
4
+ from sqlalchemy.orm import sessionmaker, declarative_base
5
+
6
+ load_dotenv()
7
+
8
+ DATABASE_URL = os.getenv("DATABASE_URL")
9
+
10
+ if not DATABASE_URL:
11
+ raise ValueError("DATABASE_URL is missing in .env file")
12
+
13
+ engine = create_engine(DATABASE_URL)
14
+
15
+ SessionLocal = sessionmaker(
16
+ autocommit=False,
17
+ autoflush=False,
18
+ bind=engine
19
+ )
20
+
21
+ Base = declarative_base()
22
+
23
+
24
+ def get_db():
25
+ db = SessionLocal()
26
+ try:
27
+ yield db
28
+ finally:
29
+ db.close()
app/main.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from app.api import chat, upload, documents, auth
3
+ from app.db.database import Base, engine
4
+ from app.models import user, document, chat_message
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+
7
+ Base.metadata.create_all(bind=engine)
8
+
9
+ app = FastAPI(title="DocBrain API")
10
+
11
+ app.include_router(auth.router, prefix="/api/v1/auth", tags=["Auth"])
12
+ app.include_router(upload.router, prefix="/api/v1/upload", tags=["Upload"])
13
+ app.include_router(chat.router, prefix="/api/v1/chat", tags=["Chat"])
14
+ app.include_router(documents.router, prefix="/api/v1/documents", tags=["Documents"])
15
+
16
+ @app.get("/")
17
+ def home():
18
+ return {"message": "DocBrain backend running"}
19
+
20
+
21
+ app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"],
24
+ allow_credentials=True,
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
app/models/__pycache__/chat_message.cpython-312.pyc ADDED
Binary file (1.08 kB). View file
 
app/models/__pycache__/document.cpython-312.pyc ADDED
Binary file (1.06 kB). View file
 
app/models/__pycache__/user.cpython-312.pyc ADDED
Binary file (821 Bytes). View file
 
app/models/chat_message.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text
4
+
5
+ from app.db.database import Base
6
+
7
+
8
+ class ChatMessage(Base):
9
+ __tablename__ = "chat_messages"
10
+
11
+ id = Column(Integer, primary_key=True, index=True)
12
+ user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
13
+ document_id = Column(
14
+ Integer, ForeignKey("documents.id"), nullable=False, index=True
15
+ )
16
+ role = Column(String, nullable=False)
17
+ content = Column(Text, nullable=False)
18
+ sources = Column(Text, nullable=True)
19
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
app/models/document.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text
2
+ from datetime import datetime
3
+ from app.db.database import Base
4
+
5
+
6
+ class Document(Base):
7
+ __tablename__ = "documents"
8
+
9
+ id = Column(Integer, primary_key=True, index=True)
10
+ filename = Column(String, nullable=False)
11
+ file_path = Column(String, nullable=False)
12
+ file_hash = Column(String, nullable=False)
13
+ user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
14
+ status = Column(String, default="processing")
15
+ error_message = Column(Text, nullable=True)
16
+ created_at = Column(DateTime, default=datetime.utcnow)
app/models/user.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import Column, Integer, String, DateTime
2
+ from datetime import datetime
3
+ from app.db.database import Base
4
+
5
+ class User(Base):
6
+ __tablename__ = "users"
7
+
8
+ id = Column(Integer, primary_key=True, index=True)
9
+ username = Column(String, unique=True, index=True, nullable=False)
10
+ hashed_password = Column(String, nullable=False)
11
+ created_at = Column(DateTime, default=datetime.utcnow)
app/services/__pycache__/indexing_service.cpython-312.pyc ADDED
Binary file (2.67 kB). View file
 
app/services/__pycache__/rag_service.cpython-312.pyc ADDED
Binary file (8.45 kB). View file
 
app/services/__pycache__/vector_service.cpython-312.pyc ADDED
Binary file (6.8 kB). View file
 
app/services/indexing_service.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import os
3
+ import tempfile
4
+ from app.db.database import SessionLocal
5
+ from app.models.document import Document
6
+ from app.utils.pdf_loader import extract_text
7
+ from app.utils.chunking import chunk_text
8
+ from app.services.vector_service import store_chunks
9
+ from app.services.storage_service import storage_service
10
+
11
+
12
+ async def index_document(document_id: int, file_path: str, filename: str, user_id: int):
13
+ db = SessionLocal()
14
+ temp_local_path = None
15
+
16
+ try:
17
+ document = db.query(Document).filter(Document.id == document_id).first()
18
+
19
+ if document is None:
20
+ return
21
+
22
+ document.status = "processing"
23
+ document.error_message = None
24
+ db.commit()
25
+
26
+ # Check if file_path is a GCS path or local path
27
+ if file_path.startswith("uploads/"):
28
+ # Download from GCS to a temporary file
29
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
30
+ content = storage_service.download_file(file_path)
31
+ if not content:
32
+ raise Exception("Failed to download file from Google Cloud Storage")
33
+ tmp.write(content)
34
+ temp_local_path = tmp.name
35
+ processing_path = temp_local_path
36
+ else:
37
+ processing_path = file_path
38
+
39
+ text = await asyncio.to_thread(extract_text, processing_path)
40
+
41
+ if not text.strip():
42
+ document.status = "failed"
43
+ document.error_message = "No text found in PDF"
44
+ db.commit()
45
+ return
46
+
47
+ chunks = await asyncio.to_thread(chunk_text, text)
48
+
49
+ if not chunks:
50
+ document.status = "failed"
51
+ document.error_message = "No chunks created from PDF"
52
+ db.commit()
53
+ return
54
+
55
+ await asyncio.to_thread(
56
+ store_chunks,
57
+ chunks,
58
+ filename,
59
+ str(user_id),
60
+ str(document_id)
61
+ )
62
+
63
+ document.status = "indexed"
64
+ document.error_message = None
65
+ db.commit()
66
+
67
+ except Exception as e:
68
+ document = db.query(Document).filter(Document.id == document_id).first()
69
+
70
+ if document is not None:
71
+ document.status = "failed"
72
+ document.error_message = str(e)
73
+ db.commit()
74
+
75
+ finally:
76
+ if temp_local_path and os.path.exists(temp_local_path):
77
+ os.remove(temp_local_path)
78
+ db.close()
app/services/rag_service.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import httpx
4
+ from dotenv import load_dotenv
5
+ from app.services.vector_service import get_document_chunks, search_chunks
6
+
7
+ load_dotenv()
8
+
9
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
10
+
11
+ if not GROQ_API_KEY:
12
+ raise ValueError("GROQ_API_KEY is missing in .env file")
13
+
14
+
15
+ BROAD_QUERY_HINTS = (
16
+ "what is this pdf about",
17
+ "what is this document about",
18
+ "summarize this document",
19
+ "summary of this document",
20
+ "give me an overview",
21
+ "document overview",
22
+ "what does this pdf say",
23
+ "what is in this pdf",
24
+ "is this a resume",
25
+ "is this resume",
26
+ "what kind of document is this",
27
+ "what are the projects",
28
+ "list the projects",
29
+ "what projects are mentioned",
30
+ )
31
+
32
+
33
+ def is_broad_overview_query(query: str) -> bool:
34
+ lowered_query = query.strip().lower()
35
+ return any(hint in lowered_query for hint in BROAD_QUERY_HINTS)
36
+
37
+
38
+ def merge_context_docs(primary_docs, additional_docs):
39
+ merged_docs = []
40
+ seen_keys = set()
41
+
42
+ for doc in [*primary_docs, *additional_docs]:
43
+ metadata = doc.get("metadata", {})
44
+ key = (
45
+ metadata.get("document_id"),
46
+ metadata.get("chunk_index"),
47
+ doc.get("page_content", ""),
48
+ )
49
+
50
+ if key in seen_keys:
51
+ continue
52
+
53
+ seen_keys.add(key)
54
+ merged_docs.append(doc)
55
+
56
+ return merged_docs
57
+
58
+
59
+ def retrieve_context(query: str, user_id: str, document_id: str):
60
+ semantic_docs = search_chunks(
61
+ query=query,
62
+ k=10,
63
+ user_id=user_id,
64
+ document_id=document_id,
65
+ )
66
+
67
+ if is_broad_overview_query(query):
68
+ leading_docs = get_document_chunks(
69
+ user_id=user_id,
70
+ document_id=document_id,
71
+ limit=10,
72
+ )
73
+ return merge_context_docs(leading_docs, semantic_docs)
74
+
75
+ return semantic_docs
76
+
77
+
78
+ def build_prompt(query: str, docs):
79
+ context_blocks = []
80
+
81
+ for doc in docs:
82
+ metadata = doc.get("metadata", {})
83
+ chunk_number = metadata.get("chunk_index")
84
+ chunk_label = (
85
+ f"Chunk {int(chunk_number) + 1}"
86
+ if isinstance(chunk_number, int)
87
+ else "Chunk"
88
+ )
89
+ context_blocks.append(f"[{chunk_label}]\n{doc['page_content']}")
90
+
91
+ context = "\n\n".join(context_blocks)
92
+
93
+ system_message = f"""You are DocBrain, a document-grounded assistant.
94
+
95
+ Rules:
96
+ - Answer using ONLY the document excerpts below.
97
+ - For broad questions, synthesize the overall document purpose from multiple excerpts.
98
+ - If the document appears to be a resume, CV, report, proposal, or similar, say that clearly.
99
+ - Do not invent facts, names, titles, dates, or project details.
100
+ - If the answer is not supported by the excerpts, say "I don't know based on the provided document excerpts."
101
+ - Keep the answer concise, factual, and directly relevant to the question.
102
+
103
+ Document excerpts:
104
+ {context}"""
105
+
106
+ return query, system_message
107
+
108
+
109
+ def build_messages(query: str, system_message: str, chat_history: list):
110
+ messages = [
111
+ {
112
+ "role": "system",
113
+ "content": system_message,
114
+ }
115
+ ]
116
+ for msg in chat_history:
117
+ # Groq expects strictly 'user' or 'assistant'
118
+ messages.append({
119
+ "role": msg["role"],
120
+ "content": msg["content"]
121
+ })
122
+ messages.append({
123
+ "role": "user",
124
+ "content": query,
125
+ })
126
+ return messages
127
+
128
+
129
+ def call_groq(query: str, system_message: str, chat_history: list) -> str:
130
+ try:
131
+ messages = build_messages(query, system_message, chat_history)
132
+ response = httpx.post(
133
+ "https://api.groq.com/openai/v1/chat/completions",
134
+ headers={
135
+ "Authorization": f"Bearer {GROQ_API_KEY}",
136
+ "Content-Type": "application/json",
137
+ },
138
+ json={
139
+ "model": "llama-3.3-70b-versatile",
140
+ "messages": messages,
141
+ "temperature": 0.1,
142
+ },
143
+ timeout=30,
144
+ )
145
+
146
+ response.raise_for_status()
147
+ return response.json()["choices"][0]["message"]["content"]
148
+
149
+ except httpx.TimeoutException:
150
+ raise Exception("Groq API timeout. Please try again.")
151
+
152
+ except httpx.HTTPStatusError as e:
153
+ raise Exception(f"Groq API error: {e.response.text}")
154
+
155
+ except httpx.HTTPError as e:
156
+ raise Exception(f"Groq request failed: {str(e)}")
157
+
158
+
159
+ def stream_groq(query: str, system_message: str, chat_history: list):
160
+ try:
161
+ messages = build_messages(query, system_message, chat_history)
162
+ with httpx.stream(
163
+ "POST",
164
+ "https://api.groq.com/openai/v1/chat/completions",
165
+ headers={
166
+ "Authorization": f"Bearer {GROQ_API_KEY}",
167
+ "Content-Type": "application/json",
168
+ },
169
+ json={
170
+ "model": "llama-3.3-70b-versatile",
171
+ "messages": messages,
172
+ "temperature": 0.1,
173
+ "stream": True,
174
+ },
175
+ timeout=60,
176
+ ) as response:
177
+
178
+ response.raise_for_status()
179
+
180
+ for line in response.iter_lines():
181
+ if not line:
182
+ continue
183
+
184
+ if line.startswith("data: "):
185
+ data = line.replace("data: ", "")
186
+
187
+ if data == "[DONE]":
188
+ break
189
+
190
+ chunk = json.loads(data)
191
+ delta = chunk["choices"][0]["delta"].get("content")
192
+
193
+ if delta:
194
+ yield delta
195
+
196
+ except httpx.TimeoutException:
197
+ raise Exception("Groq API timeout. Please try again.")
198
+
199
+ except httpx.HTTPStatusError as e:
200
+ raise Exception(f"Groq API error: {e.response.text}")
201
+
202
+ except httpx.HTTPError as e:
203
+ raise Exception(f"Groq request failed: {str(e)}")
204
+
205
+
206
+ def ask_question(query: str, user_id: str, document_id: str, chat_history: list = None):
207
+ if chat_history is None:
208
+ chat_history = []
209
+
210
+ docs = retrieve_context(
211
+ query=query,
212
+ user_id=user_id,
213
+ document_id=document_id,
214
+ )
215
+
216
+ if not docs:
217
+ return {
218
+ "answer": "No relevant information found in this document.",
219
+ "sources": [],
220
+ }
221
+
222
+ q, system_message = build_prompt(query, docs)
223
+ answer = call_groq(q, system_message, chat_history)
224
+
225
+ return {
226
+ "answer": answer,
227
+ "sources": [doc["metadata"] for doc in docs],
228
+ }
229
+
230
+
231
+ def stream_answer_events(query: str, user_id: str, document_id: str, chat_history: list = None):
232
+ if chat_history is None:
233
+ chat_history = []
234
+
235
+ docs = retrieve_context(
236
+ query=query,
237
+ user_id=user_id,
238
+ document_id=document_id,
239
+ )
240
+
241
+ yield {
242
+ "type": "sources",
243
+ "sources": [doc["metadata"] for doc in docs],
244
+ }
245
+
246
+ if not docs:
247
+ yield {
248
+ "type": "delta",
249
+ "content": "No relevant information found in this document.",
250
+ }
251
+ return
252
+
253
+ q, system_message = build_prompt(query, docs)
254
+
255
+ for token in stream_groq(q, system_message, chat_history):
256
+ yield {
257
+ "type": "delta",
258
+ "content": token,
259
+ }
app/services/storage_service.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from google.cloud import storage
4
+ from google.api_core import exceptions
5
+ from dotenv import load_dotenv
6
+
7
+ load_dotenv()
8
+
9
+ logger = logging.getLogger("uvicorn.error")
10
+
11
+ # GCS Configuration
12
+ BUCKET_NAME = os.getenv("GCP_BUCKET_NAME")
13
+ # For local dev, we might not have GCS credentials, so we can fallback or mock
14
+ # In Cloud Run, credentials are automatically picked up from the service account
15
+
16
+ class CloudStorageService:
17
+ def __init__(self):
18
+ try:
19
+ self.client = storage.Client()
20
+ self.bucket = self.client.bucket(BUCKET_NAME) if BUCKET_NAME else None
21
+ except Exception as e:
22
+ logger.warning(f"GCS Client initialization failed: {e}. Falling back to local storage if needed.")
23
+ self.client = None
24
+ self.bucket = None
25
+
26
+ def upload_file(self, file_content: bytes, destination_blob_name: str):
27
+ """Uploads a file to the bucket."""
28
+ if not self.bucket:
29
+ logger.error("GCS Bucket not configured. Upload failed.")
30
+ return False
31
+
32
+ try:
33
+ blob = self.bucket.blob(destination_blob_name)
34
+ blob.upload_from_string(file_content, content_type='application/pdf')
35
+ logger.info(f"File {destination_blob_name} uploaded to {BUCKET_NAME}.")
36
+ return True
37
+ except exceptions.GoogleCloudError as e:
38
+ logger.error(f"Failed to upload {destination_blob_name} to GCS: {e}")
39
+ return False
40
+
41
+ def download_file(self, blob_name: str) -> bytes:
42
+ """Downloads a file from the bucket as bytes."""
43
+ if not self.bucket:
44
+ logger.error("GCS Bucket not configured. Download failed.")
45
+ return None
46
+
47
+ try:
48
+ blob = self.bucket.blob(blob_name)
49
+ content = blob.download_as_bytes()
50
+ return content
51
+ except exceptions.GoogleCloudError as e:
52
+ logger.error(f"Failed to download {blob_name} from GCS: {e}")
53
+ return None
54
+
55
+ def delete_file(self, blob_name: str):
56
+ """Deletes a file from the bucket."""
57
+ if not self.bucket:
58
+ logger.error("GCS Bucket not configured. Delete failed.")
59
+ return False
60
+
61
+ try:
62
+ blob = self.bucket.blob(blob_name)
63
+ blob.delete()
64
+ logger.info(f"File {blob_name} deleted from {BUCKET_NAME}.")
65
+ return True
66
+ except exceptions.NotFound:
67
+ logger.warning(f"File {blob_name} not found in {BUCKET_NAME}.")
68
+ return True
69
+ except exceptions.GoogleCloudError as e:
70
+ logger.error(f"Failed to delete {blob_name} from GCS: {e}")
71
+ return False
72
+
73
+ # Singleton instance
74
+ storage_service = CloudStorageService()
app/services/vector_service.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ import httpx
4
+ import logging
5
+ from dotenv import load_dotenv
6
+ from qdrant_client import QdrantClient
7
+ from qdrant_client.models import PointStruct, Filter, FieldCondition, MatchValue
8
+
9
+ load_dotenv()
10
+
11
+ logger = logging.getLogger("uvicorn.error")
12
+
13
+ COLLECTION_NAME = "docbrain_documents"
14
+
15
+ JINA_API_KEY = os.getenv("JINA_API_KEY")
16
+ QDRANT_URL = os.getenv("QDRANT_URL")
17
+ QDRANT_API_KEY = os.getenv("QDRANT_API_KEY")
18
+
19
+ if not JINA_API_KEY:
20
+ raise ValueError("JINA_API_KEY is missing in .env file")
21
+
22
+ if not QDRANT_URL:
23
+ raise ValueError("QDRANT_URL is missing in .env file")
24
+
25
+ if not QDRANT_API_KEY:
26
+ raise ValueError("QDRANT_API_KEY is missing in .env file")
27
+
28
+ client = QdrantClient(
29
+ url=QDRANT_URL,
30
+ api_key=QDRANT_API_KEY,
31
+ check_compatibility=False
32
+ )
33
+
34
+
35
+ def get_embedding(text: str, task: str = "retrieval.query") -> list[float]:
36
+ response = httpx.post(
37
+ "https://api.jina.ai/v1/embeddings",
38
+ headers={
39
+ "Authorization": f"Bearer {JINA_API_KEY}",
40
+ "Content-Type": "application/json",
41
+ },
42
+ json={
43
+ "model": "jina-embeddings-v3",
44
+ "task": task,
45
+ "input": [text],
46
+ },
47
+ timeout=30,
48
+ )
49
+
50
+ response.raise_for_status()
51
+ return response.json()["data"][0]["embedding"]
52
+
53
+
54
+ def get_embeddings_batch(texts: list[str], task: str = "retrieval.passage"):
55
+ response = httpx.post(
56
+ "https://api.jina.ai/v1/embeddings",
57
+ headers={
58
+ "Authorization": f"Bearer {JINA_API_KEY}",
59
+ "Content-Type": "application/json",
60
+ },
61
+ json={
62
+ "model": "jina-embeddings-v3",
63
+ "task": task,
64
+ "input": texts,
65
+ },
66
+ timeout=30,
67
+ )
68
+
69
+ response.raise_for_status()
70
+
71
+ return [item["embedding"] for item in response.json()["data"]]
72
+
73
+
74
+ def store_chunks(chunks, filename, user_id, document_id):
75
+ points = []
76
+
77
+ embeddings = get_embeddings_batch(
78
+ chunks,
79
+ task="retrieval.passage"
80
+ )
81
+
82
+ for index, chunk in enumerate(chunks):
83
+ points.append(
84
+ PointStruct(
85
+ id=str(uuid.uuid4()),
86
+ vector=embeddings[index],
87
+ payload={
88
+ "text": chunk,
89
+ "source": filename,
90
+ "user_id": user_id,
91
+ "document_id": document_id,
92
+ "chunk_index": index,
93
+ },
94
+ )
95
+ )
96
+
97
+ client.upsert(
98
+ collection_name=COLLECTION_NAME,
99
+ points=points
100
+ )
101
+
102
+ return {
103
+ "message": "Chunks stored successfully",
104
+ "total_chunks": len(chunks)
105
+ }
106
+
107
+
108
+ def search_chunks(query: str, k: int = 3, user_id: str | None = None, document_id: str | None = None):
109
+ query_vector = get_embedding(query, task="retrieval.query")
110
+
111
+ q_filter = Filter(
112
+ must=[
113
+ FieldCondition(key="user_id", match=MatchValue(value=user_id)),
114
+ FieldCondition(key="document_id", match=MatchValue(value=document_id)),
115
+ ]
116
+ )
117
+
118
+ results = client.query_points(
119
+ collection_name=COLLECTION_NAME,
120
+ query=query_vector,
121
+ query_filter=q_filter,
122
+ limit=k
123
+ )
124
+
125
+ return [
126
+ {
127
+ "page_content": point.payload.get("text", ""),
128
+ "metadata": {
129
+ "source": point.payload.get("source"),
130
+ "user_id": point.payload.get("user_id"),
131
+ "document_id": point.payload.get("document_id"),
132
+ "chunk_index": point.payload.get("chunk_index"),
133
+ "score": point.score,
134
+ }
135
+ }
136
+ for point in results.points
137
+ ]
138
+
139
+
140
+ def get_document_chunks(
141
+ user_id: str,
142
+ document_id: str,
143
+ limit: int = 6,
144
+ fetch_limit: int = 128,
145
+ ):
146
+ q_filter = Filter(
147
+ must=[
148
+ FieldCondition(key="user_id", match=MatchValue(value=user_id)),
149
+ FieldCondition(key="document_id", match=MatchValue(value=document_id)),
150
+ ]
151
+ )
152
+
153
+ points, _ = client.scroll(
154
+ collection_name=COLLECTION_NAME,
155
+ scroll_filter=q_filter,
156
+ with_payload=True,
157
+ with_vectors=False,
158
+ limit=fetch_limit,
159
+ )
160
+
161
+ sorted_points = sorted(
162
+ points,
163
+ key=lambda point: point.payload.get("chunk_index", 0),
164
+ )
165
+
166
+ return [
167
+ {
168
+ "page_content": point.payload.get("text", ""),
169
+ "metadata": {
170
+ "source": point.payload.get("source"),
171
+ "user_id": point.payload.get("user_id"),
172
+ "document_id": point.payload.get("document_id"),
173
+ "chunk_index": point.payload.get("chunk_index"),
174
+ "score": None,
175
+ },
176
+ }
177
+ for point in sorted_points[:limit]
178
+ ]
179
+
180
+
181
+ def delete_document_vectors(user_id: str, document_id: str):
182
+ q_filter = Filter(
183
+ must=[
184
+ FieldCondition(key="user_id", match=MatchValue(value=user_id)),
185
+ FieldCondition(key="document_id", match=MatchValue(value=document_id)),
186
+ ]
187
+ )
188
+
189
+ try:
190
+ client.delete(
191
+ collection_name=COLLECTION_NAME,
192
+ points_selector=q_filter
193
+ )
194
+ logger.info(
195
+ "Vectors deleted successfully for document %s (user %s)",
196
+ document_id,
197
+ user_id,
198
+ )
199
+ return True
200
+ except Exception as exc:
201
+ logger.warning(
202
+ "Failed to delete vectors for document %s (user %s): %s",
203
+ document_id,
204
+ user_id,
205
+ exc,
206
+ )
207
+ return False
app/utils/__pycache__/chunking.cpython-312.pyc ADDED
Binary file (483 Bytes). View file
 
app/utils/__pycache__/hash.cpython-312.pyc ADDED
Binary file (935 Bytes). View file
 
app/utils/__pycache__/pdf_loader.cpython-312.pyc ADDED
Binary file (633 Bytes). View file
 
app/utils/chunking.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
2
+
3
+
4
+ def chunk_text(text):
5
+ splitter = RecursiveCharacterTextSplitter(
6
+ chunk_size=800,
7
+ chunk_overlap=150
8
+ )
9
+
10
+ return splitter.split_text(text)
app/utils/hash.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+
3
+
4
+ def generate_file_hash(file_path: str) -> str:
5
+ hash_sha256 = hashlib.sha256()
6
+
7
+ with open(file_path, "rb") as f:
8
+ for chunk in iter(lambda: f.read(4096), b""):
9
+ hash_sha256.update(chunk)
10
+
11
+ return hash_sha256.hexdigest()
app/utils/pdf_loader.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdfplumber
2
+
3
+ def extract_text(file_path):
4
+ text = ""
5
+
6
+ with pdfplumber.open(file_path) as pdf:
7
+ for page in pdf.pages:
8
+ page_text = page.extract_text()
9
+ if page_text:
10
+ text += page_text + "\n"
11
+
12
+ return text
create_qdrant_collection.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from qdrant_client import QdrantClient
4
+ from qdrant_client.models import VectorParams, Distance, PayloadSchemaType
5
+
6
+ load_dotenv()
7
+
8
+ QDRANT_URL = os.getenv("QDRANT_URL")
9
+ QDRANT_API_KEY = os.getenv("QDRANT_API_KEY")
10
+
11
+ COLLECTION_NAME = "docbrain_documents"
12
+ VECTOR_SIZE = 1024 # Jina embedding size
13
+
14
+
15
+ def main():
16
+ client = QdrantClient(
17
+ url=QDRANT_URL,
18
+ api_key=QDRANT_API_KEY,
19
+ check_compatibility=False
20
+ )
21
+
22
+ # Create collection if not exists
23
+ if not client.collection_exists(COLLECTION_NAME):
24
+ client.create_collection(
25
+ collection_name=COLLECTION_NAME,
26
+ vectors_config=VectorParams(
27
+ size=VECTOR_SIZE,
28
+ distance=Distance.COSINE
29
+ )
30
+ )
31
+ print(f"✅ Collection '{COLLECTION_NAME}' created with vector size: {VECTOR_SIZE}")
32
+ else:
33
+ print(f"ℹ️ Collection '{COLLECTION_NAME}' already exists")
34
+
35
+ # Create indexes for filtering
36
+ try:
37
+ client.create_payload_index(
38
+ collection_name=COLLECTION_NAME,
39
+ field_name="user_id",
40
+ field_schema=PayloadSchemaType.KEYWORD
41
+ )
42
+ print("Index created for user_id")
43
+ except Exception:
44
+ print("Index already exists for user_id")
45
+
46
+ try:
47
+ client.create_payload_index(
48
+ collection_name=COLLECTION_NAME,
49
+ field_name="document_id",
50
+ field_schema=PayloadSchemaType.KEYWORD
51
+ )
52
+ print("Index created for document_id")
53
+ except Exception:
54
+ print("Index already exists for document_id")
55
+
56
+
57
+ if __name__ == "__main__":
58
+ main()
requirements.txt ADDED
Binary file (5.48 kB). View file
 
test_jina.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import httpx
2
+ import os
3
+ from dotenv import load_dotenv
4
+
5
+ load_dotenv()
6
+
7
+ response = httpx.post(
8
+ "https://api.jina.ai/v1/embeddings",
9
+ headers={
10
+ "Authorization": f"Bearer {os.getenv('JINA_API_KEY')}",
11
+ "Content-Type": "application/json",
12
+ },
13
+ json={
14
+ "model": "jina-embeddings-v3",
15
+ "input": ["Hello world"],
16
+ },
17
+ )
18
+
19
+ print(response.json())
test_qdrant.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from qdrant_client import QdrantClient
2
+ import os
3
+ from dotenv import load_dotenv
4
+
5
+ load_dotenv()
6
+
7
+ client = QdrantClient(
8
+ url=os.getenv("QDRANT_URL"),
9
+ api_key=os.getenv("QDRANT_API_KEY"),
10
+ check_compatibility=False
11
+ )
12
+
13
+ print(client.get_collections())
tests/__init__.py ADDED
File without changes
tests/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (134 Bytes). View file
 
tests/__pycache__/test_auth.cpython-312-pytest-9.0.3.pyc ADDED
Binary file (4.27 kB). View file
 
tests/__pycache__/test_chunking.cpython-312-pytest-9.0.3.pyc ADDED
Binary file (5.36 kB). View file
 
tests/__pycache__/test_documents.cpython-312-pytest-9.0.3.pyc ADDED
Binary file (3.61 kB). View file
 
tests/__pycache__/test_hash.cpython-312-pytest-9.0.3.pyc ADDED
Binary file (2.45 kB). View file
 
tests/__pycache__/test_pdf_loader.cpython-312-pytest-9.0.3.pyc ADDED
Binary file (2.36 kB). View file
 
tests/test_auth.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.core.security import hash_password, verify_password, create_access_token
2
+
3
+
4
+ def test_hash_password():
5
+ password = "Test@1234"
6
+
7
+ hashed = hash_password(password)
8
+
9
+ assert hashed != password
10
+ assert verify_password(password, hashed) is True
11
+
12
+
13
+ def test_create_access_token():
14
+ token = create_access_token({"sub": "1", "username": "testuser"})
15
+
16
+ assert isinstance(token, str)
17
+ assert len(token) > 20
tests/test_chunking.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.utils.chunking import chunk_text
2
+
3
+
4
+ def test_chunk_text_returns_chunks():
5
+ text = "This is a sample text. " * 100
6
+
7
+ chunks = chunk_text(text)
8
+
9
+ assert isinstance(chunks, list)
10
+ assert len(chunks) > 0
11
+ assert isinstance(chunks[0], str)
tests/test_documents.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.models.document import Document
2
+
3
+
4
+ def test_document_model_creation():
5
+ document = Document(
6
+ filename="sample.pdf",
7
+ file_path="uploads/user_1/1_sample.pdf",
8
+ user_id=1,
9
+ file_hash="a" * 64,
10
+ status="processing"
11
+ )
12
+
13
+ assert document.filename == "sample.pdf"
14
+ assert document.user_id == 1
15
+ assert document.status == "processing"
16
+ assert len(document.file_hash) == 64