-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdigest.txt
More file actions
2557 lines (2154 loc) · 79 KB
/
Copy pathdigest.txt
File metadata and controls
2557 lines (2154 loc) · 79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Directory structure:
└── pdf_reader_project/
├── README.md
├── Project Documentation.docx
├── Backend/
│ ├── gunicorn.conf.py
│ ├── pyproject.toml
│ ├── render.yaml
│ ├── requirements.txt
│ ├── runtime.txt
│ ├── app/
│ │ ├── __init__.py
│ │ ├── auth.py
│ │ ├── auth_config.py
│ │ ├── auth_models.py
│ │ ├── chat_manager.py
│ │ ├── file_processor.py
│ │ ├── ingest.py
│ │ ├── main.py
│ │ ├── models.py
│ │ ├── mongo_db.py
│ │ ├── query.py
│ │ ├── test_imports.py
│ │ └── vector_search.py
│ └── db/
│ ├── index.faiss
│ └── index.pkl
└── Frontend/
├── README.md
├── eslint.config.js
├── index.html
├── package.json
├── postcss.config.mjs
├── vite.config.js
└── src/
├── App.css
├── App.jsx
├── index.css
├── main.jsx
├── api/
│ ├── api.js
│ ├── ask.js
│ ├── chat.js
│ └── upload.js
├── components/
│ ├── Navbar.jsx
│ └── ProtectedRoute.jsx
├── context/
│ └── AuthContext.jsx
└── pages/
├── Login.jsx
└── Signup.jsx
================================================
FILE: README.md
================================================
AI Document Chat
A RAG based application where users upload documents and ask questions.
Tech Stack:
Python
LangChain
FAISS
OpenAI
React
Node.js
Features:
• Document upload
• Semantic search
• AI answer generation
• Chat history
================================================
FILE: Project Documentation.docx
================================================
[Binary file]
================================================
FILE: Backend/gunicorn.conf.py
================================================
workers = 4
worker_class = "uvicorn.workers.UvicornWorker"
bind = "0.0.0.0:8000"
timeout = 120
================================================
FILE: Backend/pyproject.toml
================================================
# pyproject.toml
[build-system]
requires = ["setuptools", "wheel", "cython"]
build-backend = "setuptools.build_meta"
================================================
FILE: Backend/render.yaml
================================================
services:
- type: web
name: pdf-ai-assistant-backend
runtime: python3
rootDir: Backend
buildCommand: pip install -r requirements.txt
startCommand: uvicorn app.main:app --host 0.0.0.0 --port $PORT
envVars:
- key: MONGO_URI
sync: false
- key: GOOGLE_API_KEY
sync: false
- key: SECRET_KEY
generateValue: true
- key: ALGORITHM
value: HS256
- key: ACCESS_TOKEN_EXPIRE_MINUTES
value: 30
================================================
FILE: Backend/requirements.txt
================================================
fastapi
uvicorn
gunicorn
python-multipart
langchain
langchain-community
langchain-google-genai
langchain-huggingface
google-generativeai
tiktoken
sentence-transformers
faiss-cpu
pypdf
pandas
python-dotenv
passlib[argon2]
email-validator
python-jose[cryptography]
argon2-cffi
pymongo
python-docx
openpyxl
python-pptx
pillow
pytesseract
torch --index-url https://download.pytorch.org/whl/cpu
================================================
FILE: Backend/runtime.txt
================================================
python-3.10.16
================================================
FILE: Backend/app/__init__.py
================================================
[Empty file]
================================================
FILE: Backend/app/auth.py
================================================
from fastapi import APIRouter, HTTPException, Depends, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from app.auth_models import UserCreate, UserLogin, TokenResponse, UserResponse
from app.auth_config import verify_password, get_password_hash, create_access_token, verify_token
from app.mongo_db import db
from datetime import datetime, timedelta
from bson import ObjectId
import logging
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/auth", tags=["authentication"])
# OAuth2 scheme for token authentication
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
# Users collection
users_collection = db["users"]
@router.post("/signup", response_model=TokenResponse)
async def signup(user_data: UserCreate):
"""Register a new user"""
# Check if user already exists
existing_user = users_collection.find_one({"email": user_data.email})
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already registered"
)
# Hash password and create user
hashed_password = get_password_hash(user_data.password)
user = {
"email": user_data.email,
"password": hashed_password,
"created_at": datetime.utcnow()
}
result = users_collection.insert_one(user)
user_id = str(result.inserted_id)
# Create access token
access_token = create_access_token(
data={"sub": user_data.email, "user_id": user_id}
)
return TokenResponse(
access_token=access_token,
token_type="bearer",
user=UserResponse(id=user_id, email=user_data.email)
)
@router.post("/login", response_model=TokenResponse)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
"""Login with email and password (OAuth2 compatible)"""
# Find user
user = users_collection.find_one({"email": form_data.username})
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
# Verify password
if not verify_password(form_data.password, user["password"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
# Create access token
access_token = create_access_token(
data={"sub": user["email"], "user_id": str(user["_id"])}
)
return TokenResponse(
access_token=access_token,
token_type="bearer",
user=UserResponse(id=str(user["_id"]), email=user["email"])
)
@router.post("/login/json")
async def login_json(user_data: UserLogin):
"""Login with JSON body (alternative to form)"""
# Find user
user = users_collection.find_one({"email": user_data.email})
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password"
)
# Verify password
if not verify_password(user_data.password, user["password"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password"
)
# Create access token
access_token = create_access_token(
data={"sub": user["email"], "user_id": str(user["_id"])}
)
return {
"access_token": access_token,
"token_type": "bearer",
"user": {
"id": str(user["_id"]),
"email": user["email"]
}
}
@router.get("/me", response_model=UserResponse)
async def get_current_user(token: str = Depends(oauth2_scheme)):
"""Get current user info"""
payload = verify_token(token)
if not payload:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
email = payload.get("sub")
user_id = payload.get("user_id")
if not email or not user_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token payload"
)
user = users_collection.find_one({"_id": ObjectId(user_id), "email": email})
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found"
)
return UserResponse(id=str(user["_id"]), email=user["email"])
# Dependency to get current user for protected routes
async def get_current_user_id(token: str = Depends(oauth2_scheme)) -> str:
"""Get current user ID from token"""
payload = verify_token(token)
if not payload:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
user_id = payload.get("user_id")
if not user_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token"
)
return user_id
================================================
FILE: Backend/app/auth_config.py
================================================
from passlib.context import CryptContext
from datetime import datetime, timedelta
from jose import JWTError, jwt
import os
from dotenv import load_dotenv
load_dotenv()
# JWT Configuration
SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-change-in-production")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Password hashing - using argon2 which doesn't have the 72-byte limit
pwd_context = CryptContext(
schemes=["argon2"],
deprecated="auto",
argon2__memory_cost=65536, # 64MB
argon2__time_cost=3,
argon2__parallelism=4
)
def verify_password(plain_password, hashed_password):
"""Verify a plain password against a hashed password"""
try:
return pwd_context.verify(plain_password, hashed_password)
except Exception as e:
print(f"Password verification error: {e}")
return False
def get_password_hash(password):
"""Hash a password"""
try:
return pwd_context.hash(password)
except Exception as e:
print(f"Password hashing error: {e}")
raise
def create_access_token(data: dict, expires_delta: timedelta = None):
"""Create a JWT access token"""
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_token(token: str):
"""Verify a JWT token and return the payload"""
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except JWTError:
return None
================================================
FILE: Backend/app/auth_models.py
================================================
from pydantic import BaseModel, EmailStr, Field
from typing import Optional
class UserCreate(BaseModel):
"""User registration model"""
email: EmailStr
password: str = Field(..., min_length=6)
class UserLogin(BaseModel):
"""User login model"""
email: EmailStr
password: str
class UserResponse(BaseModel):
"""User response model"""
id: str
email: str
class TokenResponse(BaseModel):
"""Token response model"""
access_token: str
token_type: str
user: UserResponse
class TokenData(BaseModel):
"""Token data model"""
email: Optional[str] = None
user_id: Optional[str] = None
================================================
FILE: Backend/app/chat_manager.py
================================================
from app.mongo_db import db
from app.models import ChatSession, Message, MessageRole, ChatSessionResponse
from datetime import datetime
from typing import List, Optional, Dict, Any
import uuid
import logging
from bson import ObjectId
logger = logging.getLogger(__name__)
sessions_collection = db["chat_sessions"]
messages_collection = db["messages"]
class ChatSessionManager:
@staticmethod
async def create_session(user_id: str, title: str = None) -> Dict[str, Any]:
"""Create a new chat session"""
if not title:
title = f"Chat Session {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"
session_id = str(uuid.uuid4())
session = {
"session_id": session_id,
"user_id": user_id,
"title": title,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
"files": [],
"message_count": 0
}
sessions_collection.insert_one(session)
return {
"session_id": session_id,
"title": title,
"created_at": session["created_at"],
"updated_at": session["updated_at"],
"message_count": 0,
"file_count": 0
}
@staticmethod
async def get_user_sessions(user_id: str) -> List[Dict[str, Any]]:
"""Get all sessions for a user"""
cursor = sessions_collection.find(
{"user_id": user_id}
).sort("updated_at", -1)
sessions = []
for doc in cursor:
sessions.append({
"session_id": doc["session_id"],
"title": doc["title"],
"created_at": doc["created_at"],
"updated_at": doc["updated_at"],
"message_count": doc.get("message_count", 0),
"file_count": len(doc.get("files", []))
})
return sessions
@staticmethod
async def get_session(session_id: str, user_id: str) -> Optional[Dict[str, Any]]:
"""Get a specific session"""
session = sessions_collection.find_one({
"session_id": session_id,
"user_id": user_id
})
if not session:
return None
# Get messages for this session
messages = list(messages_collection.find(
{"session_id": session_id}
).sort("timestamp", 1))
return {
"session_id": session["session_id"],
"title": session["title"],
"created_at": session["created_at"],
"updated_at": session["updated_at"],
"files": session.get("files", []),
"messages": [
{
"role": msg["role"],
"content": msg["content"],
"timestamp": msg["timestamp"],
"sources": msg.get("sources", [])
}
for msg in messages
]
}
@staticmethod
async def add_message(
session_id: str,
user_id: str,
role: MessageRole,
content: str,
sources: List[Dict[str, Any]] = None
) -> None:
"""Add a message to a session"""
# Verify session belongs to user
session = sessions_collection.find_one({
"session_id": session_id,
"user_id": user_id
})
if not session:
raise ValueError("Session not found")
# Add message
message = {
"session_id": session_id,
"role": role.value if isinstance(role, MessageRole) else role,
"content": content,
"timestamp": datetime.utcnow(),
"sources": sources or []
}
messages_collection.insert_one(message)
# Update session
sessions_collection.update_one(
{"session_id": session_id},
{
"$set": {"updated_at": datetime.utcnow()},
"$inc": {"message_count": 1}
}
)
@staticmethod
async def add_file_to_session(session_id: str, user_id: str, filename: str) -> None:
"""Add a file reference to a session"""
sessions_collection.update_one(
{
"session_id": session_id,
"user_id": user_id
},
{
"$addToSet": {"files": filename},
"$set": {"updated_at": datetime.utcnow()}
}
)
@staticmethod
async def delete_session(session_id: str, user_id: str) -> bool:
"""Delete a session and its messages"""
result = sessions_collection.delete_one({
"session_id": session_id,
"user_id": user_id
})
if result.deleted_count > 0:
# Delete messages
messages_collection.delete_many({"session_id": session_id})
# Note: Files are not deleted, just disassociated
return True
return False
@staticmethod
async def get_session_files(session_id: str, user_id: str) -> List[str]:
"""Get all files associated with a session"""
session = sessions_collection.find_one({
"session_id": session_id,
"user_id": user_id
})
return session.get("files", []) if session else []
================================================
FILE: Backend/app/file_processor.py
================================================
import os
import logging
import tempfile
import uuid
from typing import List, Dict, Any, Optional
from datetime import datetime
from langchain_community.document_loaders import (
PyPDFLoader,
TextLoader,
Docx2txtLoader,
UnstructuredExcelLoader,
UnstructuredPowerPointLoader,
)
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_core.documents import Document # Updated import
from app.mongo_db import collection, fs, files_collection
import pandas as pd
import pytesseract
from PIL import Image
import io
logger = logging.getLogger(__name__)
# Initialize embeddings
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
class FileProcessor:
SUPPORTED_EXTENSIONS = {
'.pdf': 'pdf',
'.docx': 'docx',
'.doc': 'docx',
'.txt': 'txt',
'.csv': 'xlsx',
'.xlsx': 'xlsx',
'.xls': 'xlsx',
'.pptx': 'pptx',
'.ppt': 'pptx',
'.jpg': 'image',
'.jpeg': 'image',
'.png': 'image',
'.gif': 'image'
}
@classmethod
def get_file_type(cls, filename: str) -> str:
ext = os.path.splitext(filename)[1].lower()
return cls.SUPPORTED_EXTENSIONS.get(ext, 'txt')
@classmethod
async def process_file(cls, file_bytes: bytes, filename: str, user_id: str, session_id: Optional[str] = None) -> Dict[str, Any]:
"""Process any supported file type and store in MongoDB"""
temp_file_path = None
file_type = cls.get_file_type(filename)
try:
# Create temp file
unique_filename = f"{uuid.uuid4()}_{filename}"
temp_dir = os.path.join(tempfile.gettempdir(), "file_processor")
os.makedirs(temp_dir, exist_ok=True)
temp_file_path = os.path.join(temp_dir, unique_filename)
with open(temp_file_path, 'wb') as f:
f.write(file_bytes)
# Load documents based on file type
documents = await cls._load_documents(temp_file_path, filename, file_type)
if not documents:
raise ValueError(f"No content extracted from {filename}")
# Split documents into chunks
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
splits = splitter.split_documents(documents)
# Store in MongoDB with embeddings
success_count = 0
for i, doc in enumerate(splits):
try:
embedding = embeddings.embed_query(doc.page_content)
collection.insert_one({
"text": doc.page_content,
"embedding": embedding,
"metadata": doc.metadata,
"file": filename,
"file_type": file_type,
"user_id": user_id,
"session_id": session_id,
"chunk_id": i,
"timestamp": datetime.utcnow()
})
success_count += 1
except Exception as e:
logger.error(f"Failed to store chunk {i}: {e}")
continue
# Store file in GridFS
file_id = fs.put(
file_bytes,
filename=filename,
uploadDate=datetime.utcnow(),
contentType=cls._get_mime_type(file_type),
metadata={
"user_id": user_id,
"file_type": file_type,
"session_id": session_id
}
)
# Store file metadata
files_collection.insert_one({
"file_id": file_id,
"filename": filename,
"file_type": file_type,
"user_id": user_id,
"session_id": session_id,
"upload_date": datetime.utcnow(),
"size": len(file_bytes),
"chunks": success_count
})
return {
"success": True,
"filename": filename,
"file_type": file_type,
"chunks_stored": success_count,
"file_id": str(file_id)
}
except Exception as e:
logger.error(f"File processing failed: {e}")
raise
finally:
if temp_file_path and os.path.exists(temp_file_path):
try:
os.remove(temp_file_path)
except:
pass
@classmethod
async def _load_documents(cls, file_path: str, filename: str, file_type: str) -> List[Document]:
"""Load documents based on file type"""
try:
if file_type == 'pdf':
loader = PyPDFLoader(file_path)
return loader.load()
elif file_type == 'docx':
loader = Docx2txtLoader(file_path)
return loader.load()
elif file_type == 'txt':
loader = TextLoader(file_path, encoding='utf-8')
return loader.load()
elif file_type == 'xlsx':
# Handle Excel files
try:
df_dict = pd.read_excel(file_path, sheet_name=None)
documents = []
for sheet_name, df in df_dict.items():
content = f"Sheet: {sheet_name}\n"
content += df.to_string()
doc = Document(
page_content=content,
metadata={"source": filename, "sheet": sheet_name, "page": 0}
)
documents.append(doc)
return documents
except Exception as e:
logger.error(f"Excel processing error: {e}")
loader = UnstructuredExcelLoader(file_path)
return loader.load()
elif file_type == 'pptx':
loader = UnstructuredPowerPointLoader(file_path)
return loader.load()
elif file_type == 'image':
# Handle images with OCR
try:
image = Image.open(file_path)
text = pytesseract.image_to_string(image)
doc = Document(
page_content=text,
metadata={"source": filename, "page": 0}
)
return [doc]
except Exception as e:
logger.error(f"OCR failed: {e}")
return []
else:
# Default to text loader
loader = TextLoader(file_path, encoding='utf-8')
return loader.load()
except Exception as e:
logger.error(f"Error loading documents: {e}")
return []
@staticmethod
def _get_mime_type(file_type: str) -> str:
mime_types = {
'pdf': 'application/pdf',
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'txt': 'text/plain',
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'image': 'image/jpeg'
}
return mime_types.get(file_type, 'application/octet-stream')
================================================
FILE: Backend/app/ingest.py
================================================
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_huggingface import HuggingFaceEmbeddings
from pymongo import MongoClient
import os
import logging
from dotenv import load_dotenv
import io
from datetime import datetime
import tempfile
import uuid
load_dotenv()
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# MongoDB connection
try:
client = MongoClient(os.getenv("MONGO_URI"))
db = client["pdf_ai"]
collection = db["documents"]
logger.info("Connected to MongoDB")
except Exception as e:
logger.error(f"MongoDB connection failed: {e}")
raise
# Initialize embeddings
try:
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
logger.info("Embeddings model loaded successfully")
except Exception as e:
logger.error(f"Failed to load embeddings model: {e}")
raise
def ingest_pdf_from_bytes(pdf_bytes, filename, user_id):
"""Process PDF from bytes and store in MongoDB with vector embeddings"""
temp_file_path = None
try:
# Create a unique filename to avoid conflicts
unique_filename = f"{uuid.uuid4()}_{filename}"
# Create temp directory if it doesn't exist
temp_dir = os.path.join(tempfile.gettempdir(), "pdf_processor")
os.makedirs(temp_dir, exist_ok=True)
# Create temp file path
temp_file_path = os.path.join(temp_dir, unique_filename)
# Write bytes to temp file with proper permissions
logger.info(f"Creating temp file: {temp_file_path}")
with open(temp_file_path, 'wb') as f:
f.write(pdf_bytes)
# Verify file was written
if not os.path.exists(temp_file_path):
raise Exception("Failed to create temp file")
logger.info(f"Temp file created successfully, size: {os.path.getsize(temp_file_path)} bytes")
# Load PDF using the temp file
loader = PyPDFLoader(temp_file_path)
documents = loader.load()
if not documents:
raise ValueError("No content extracted from PDF")
logger.info(f"Loaded {len(documents)} pages from PDF")
# Split documents into chunks
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
splits = splitter.split_documents(documents)
logger.info(f"Created {len(splits)} text chunks")
# Store in MongoDB with embeddings and user_id
success_count = 0
for i, doc in enumerate(splits):
try:
# Generate embedding
embedding = embeddings.embed_query(doc.page_content)
# Store in MongoDB with user_id
collection.insert_one({
"text": doc.page_content,
"embedding": embedding,
"page": doc.metadata.get("page", 0),
"file": filename,
"user_id": user_id,
"chunk_id": i,
"timestamp": datetime.utcnow()
})
success_count += 1
except Exception as e:
logger.error(f"Failed to store chunk {i}: {e}")
continue
logger.info(f"Successfully stored {success_count}/{len(splits)} chunks in MongoDB")
return {"success": True, "chunks_stored": success_count}
except Exception as e:
logger.error(f"PDF ingestion failed: {e}")
raise
finally:
# Clean up temp file
if temp_file_path and os.path.exists(temp_file_path):
try:
# Make sure file is not locked before deleting
import time
time.sleep(0.1) # Small delay to ensure file is released
os.remove(temp_file_path)
logger.info(f"Temp file deleted: {temp_file_path}")
except Exception as e:
logger.warning(f"Could not delete temp file {temp_file_path}: {e}")
================================================
FILE: Backend/app/main.py
================================================
Error reading file with 'cp1252': 'charmap' codec can't decode byte 0x9d in position 1398: character maps to <undefined>
================================================
FILE: Backend/app/models.py
================================================
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
from datetime import datetime
from enum import Enum
class FileType(str, Enum):
PDF = "pdf"
DOCX = "docx"
TXT = "txt"
XLSX = "xlsx"
PPTX = "pptx"
IMAGE = "image"
class MessageRole(str, Enum):
USER = "user"
ASSISTANT = "assistant"