-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_processor.py
More file actions
64 lines (54 loc) · 2.04 KB
/
document_processor.py
File metadata and controls
64 lines (54 loc) · 2.04 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
from fastapi import UploadFile
import os
from typing import Optional
import PyPDF2
from docx import Document
from rag_engine import RAGEngine
from pdf2image import convert_from_path
import pytesseract
from PIL import Image
import io
async def process_document(file: UploadFile, doc_type: Optional[str]):
# Create uploads directory if it doesn't exist
os.makedirs("uploads", exist_ok=True)
# Save the uploaded file
file_path = f"uploads/{file.filename}"
with open(file_path, "wb") as buffer:
content = await file.read()
buffer.write(content)
# Extract text based on file type
text = extract_text(file_path, doc_type)
# Create a new RAG instance for this upload
rag_engine = RAGEngine()
await rag_engine.add_documents([text])
return {
"rag_engine": rag_engine,
"doc_type": doc_type,
"file_name": file.filename
}
def extract_text(file_path: str, doc_type: Optional[str]) -> str:
if doc_type == "pdf" or file_path.lower().endswith('.pdf'):
return extract_text_from_pdf(file_path)
elif doc_type == "docx" or file_path.lower().endswith('.docx'):
return extract_text_from_docx(file_path)
else:
# Assume it's a plain text file
with open(file_path, 'r', encoding='utf-8') as file:
return file.read()
def extract_text_from_pdf(file_path: str) -> str:
text = ""
# First, try to extract text directly from the PDF
with open(file_path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
text = " ".join(page.extract_text() for page in reader.pages)
# If no text was extracted, assume the PDF contains images
if not text.strip():
# Convert PDF to images
images = convert_from_path(file_path)
# Perform OCR on each image
for image in images:
text += pytesseract.image_to_string(image) + " "
return text
def extract_text_from_docx(file_path: str) -> str:
doc = Document(file_path)
return " ".join(paragraph.text for paragraph in doc.paragraphs)