import os
import tempfile
from typing import List, Dict
import faiss
import numpy as np
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import HuggingFaceBgeEmbeddings
from langchain.docstore.document import Document
from langchain.vectorstores import FAISS
from langchain.chains.question_answering import load_qa_chain
from langchain.llms import Ollama
from paddleocr import PaddleOCR
from pdf2image import convert_from_path
try:
images = convert_from_path(pdf_path)
except Exception as e:
print(f"Error converting {pdf_path} to images: {e}")
return ""
full_text = ''
for i, image in enumerate(images):
with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as temp_image:
image.save(temp_image.name, 'JPEG')
code
try:
result = ocr.ocr(temp_image.name, cls=True)
if result is None or len(result) == 0:
print(f"Warning: OCR returned no results for page {i+1} of {pdf_path}")
continue
page_text = ''
for line in result:
if line is None:
print(f"Warning: Empty line in OCR result for page {i+1} of {pdf_path}")
continue
for word_info in line:
if word_info is None or len(word_info) < 2:
print(f"Warning: Invalid word_info in OCR result for page {i+1} of {pdf_path}")
continue
page_text += word_info[1][0] + ' '
page_text += '\n'
full_text += f'--- Page {i+1} ---\n'
full_text += page_text + '\n'
except Exception as e:
print(f"Error processing page {i+1} of {pdf_path}: {e}")
os.unlink(temp_image.name)
print(f'Processed page {i+1} of {pdf_path}')
Assistant
if not full_text:
print(f"Warning: No text extracted from {pdf_path}")
for filename in os.listdir(pdf_directory):
if filename.lower().endswith('.pdf'):
pdf_path = os.path.join(pdf_directory, filename)
print(f"Processing {filename}")
code
# Perform OCR on the PDF
extracted_text = perform_ocr_on_pdf(pdf_path)
if extracted_text:
# Create a text file for the extracted content
output_file = os.path.join(output_directory, f"{os.path.splitext(filename)[0]}.txt")
with open(output_file, 'w', encoding='utf-8') as f:
f.write(extracted_text)
print(f"Saved extracted text to {output_file}")
# Create a Document object with the extracted text
doc = Document(page_content=extracted_text, metadata={"source": filename})
documents.append(doc)
else:
print(f"Warning: No text extracted from {filename}")
try:
db = FAISS.from_documents(texts, embeddings)
print("FAISS index created successfully.")
except Exception as e:
print(f"Error creating FAISS index: {e}")
return
Ensure the directory exists
if not os.path.exists(index_path):
os.makedirs(index_path)
Save the FAISS index
try:
db.save_local(index_path)
print(f"FAISS index saved to {index_path}.")
except Exception as e:
print(f"Error saving FAISS index: {e}")
db = load_faiss_index(index_path)
if db is None:
print("Failed to load FAISS index. Exiting.")
return
while True:
query = input("Enter your query (or 'quit' to exit): ")
if query.lower() == 'quit':
break
code
result = query_documents(query, db)
print("Answer:", result)
print()
if name == "main":
Uncomment the following line to process documents and create index
process_documents_and_create_index()
Run the main query script
main_query_script()
which perform ocr can you modify this code to fastapi code please but make sure that fast api has two endpoints one to upload multiple files and another to just query and make sure when i query it does not process file again from zero
Yes, of course! Let's refactor your code into a FastAPI application with two endpoints:
/upload: To upload multiple PDF files, perform OCR, and update the FAISS index.
/query: To query the existing FAISS index without reprocessing the files.
We'll ensure that when you query, it doesn't reprocess the files from scratch. Here's the modified code:
python
# main.py
import os
import tempfile
import threading
from typing import List
import faiss
import numpy as np
import uvicorn
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.responses import JSONResponse
from langchain.chains.question_answering import load_qa_chain
from langchain.docstore.document import Document
from langchain.embeddings import HuggingFaceBgeEmbeddings
from langchain.llms import Ollama
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import FAISS
from paddleocr import PaddleOCR
from pdf2image import convert_from_path
from pydantic import BaseModel
# Initialize FastAPI app
app = FastAPI()
# Global variables and locks
INDEX_PATH = "/home/ec2-user/lisa/api/apps/pdfs/faiss_index"
UPLOAD_DIRECTORY = "/home/ec2-user/lisa/api/apps/pdfs/uploaded"
OUTPUT_DIRECTORY = "/home/ec2-user/lisa/api/apps/pdfs/output"
db_lock = threading.Lock()
ocr_lock = threading.Lock()
# Initialize PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=False)
# Initialize embeddings globally
embeddings = HuggingFaceBgeEmbeddings()
# Load or initialize the FAISS index
db = None
if os.path.exists(INDEX_PATH):
try:
db = FAISS.load_local(INDEX_PATH, embeddings, allow_dangerous_deserialization=True)
print("FAISS index loaded successfully.")
except Exception as e:
print(f"Error loading FAISS index: {e}")
db = None
else:
print("No FAISS index found. It will be created after uploading documents.")
# Pydantic model for query input
class QueryRequest(BaseModel):
query: str
# Helper function to perform OCR on a PDF
def perform_ocr_on_pdf(pdf_path):
print(f"Processing PDF: {pdf_path}")
try:
images = convert_from_path(pdf_path)
except Exception as e:
print(f"Error converting {pdf_path} to images: {e}")
return ""
full_text = ''
for i, image in enumerate(images):
with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as temp_image:
image.save(temp_image.name, 'JPEG')
try:
with ocr_lock:
result = ocr.ocr(temp_image.name, cls=True)
if result is None or len(result) == 0:
print(f"Warning: OCR returned no results for page {i+1} of {pdf_path}")
continue
page_text = ''
for line in result:
if line is None:
print(f"Warning: Empty line in OCR result for page {i+1} of {pdf_path}")
continue
for word_info in line:
if word_info is None or len(word_info) < 2:
print(f"Warning: Invalid word_info in OCR result for page {i+1} of {pdf_path}")
continue
page_text += word_info[1][0] + ' '
page_text += '\n'
full_text += f'--- Page {i+1} ---\n'
full_text += page_text + '\n'
except Exception as e:
print(f"Error processing page {i+1} of {pdf_path}: {e}")
os.unlink(temp_image.name)
print(f'Processed page {i+1} of {pdf_path}')
if not full_text:
print(f"Warning: No text extracted from {pdf_path}")
return full_text
# Endpoint to upload and process PDF files
@app.post("/upload")
def upload_files(files: List[UploadFile] = File(...)):
try:
os.makedirs(UPLOAD_DIRECTORY, exist_ok=True)
os.makedirs(OUTPUT_DIRECTORY, exist_ok=True)
# Save uploaded files
uploaded_file_paths = []
for file in files:
if not file.filename.lower().endswith('.pdf'):
raise HTTPException(status_code=400, detail=f"File {file.filename} is not a PDF.")
file_location = os.path.join(UPLOAD_DIRECTORY, file.filename)
with open(file_location, "wb") as f:
f.write(file.file.read())
uploaded_file_paths.append(file_location)
# Process PDFs
new_documents = []
for pdf_path in uploaded_file_paths:
extracted_text = perform_ocr_on_pdf(pdf_path)
if extracted_text:
# Save extracted text to file
output_file = os.path.join(OUTPUT_DIRECTORY, f"{os.path.splitext(os.path.basename(pdf_path))[0]}.txt")
with open(output_file, 'w', encoding='utf-8') as f:
f.write(extracted_text)
# Create a Document object with the extracted text
doc = Document(page_content=extracted_text, metadata={"source": os.path.basename(pdf_path)})
new_documents.append(doc)
# Update the FAISS index
if new_documents:
# Split documents into chunks
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
texts = text_splitter.split_documents(new_documents)
# Update the FAISS index with threading lock
global db
with db_lock:
if db is None:
# Create a new FAISS index
db = FAISS.from_documents(texts, embeddings)
else:
# Add new documents to existing index
db.add_documents(texts)
# Save the FAISS index
db.save_local(INDEX_PATH)
return {"message": "Files uploaded and processed successfully."}
else:
return {"message": "No text extracted from uploaded files."}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Endpoint to query the FAISS index
@app.post("/query")
def query_documents(request: QueryRequest):
global db
if db is None:
raise HTTPException(status_code=400, detail="No FAISS index found. Please upload documents first.")
try:
with db_lock:
# Retrieve relevant documents
docs = db.similarity_search(request.query, k=20)
# Use Ollama for question answering
llm = Ollama(base_url="https://artglobal-lisa.hf.space", model="phi3.5:latest")
chain = load_qa_chain(llm, chain_type="stuff")
# Run the chain
result = chain({"input_documents": docs, "question": request.query}, return_only_outputs=True)
return {"answer": result['output_text']}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Run the app using Uvicorn
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
Note:
Thread Safety: We've used threading locks (db_lock and ocr_lock) to ensure that the FAISS index and OCR operations are thread-safe. This prevents race conditions when multiple users are uploading files or querying at the same time.
Global Variables: The FAISS index (db) and embeddings are initialized globally to avoid reloading them on every request.
Directories: Ensure that the directories for uploaded files and processed texts (UPLOAD_DIRECTORY and OUTPUT_DIRECTORY) exist or are created.
Error Handling: Proper exception handling is added to inform the user if something goes wrong.
Dependency Management: Make sure all the required packages are installed and compatible with FastAPI.
Testing the Endpoints:
Upload Endpoint:
URL: POST http://localhost:8000/upload
Body: Form data with multiple PDF files.
Response: A JSON message indicating the files have been uploaded and processed.
Query Endpoint:
URL: POST http://localhost:8000/query
Body:
json
{
"query": "Your question here"
}
Response: A JSON object containing the answer.
Example Usage:
bash
# Uploading files using curl
curl -X POST "http://localhost:8000/upload" \
-F "files=@/path/to/file1.pdf" \
-F "files=@/path/to/file2.pdf"
# Querying using curl
curl -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{"query": "What is the capital of France?"}'
Important:
Asynchronous vs. Synchronous: Since PaddleOCR and FAISS operations are CPU-bound and not async-friendly, we've used synchronous endpoints (def instead of async def). FastAPI will handle these in separate threads, so the event loop isn't blocked.
Concurrency Considerations: For production, you might want to consider more robust concurrency control or use background tasks for long-running operations.
Security: Ensure that file uploads are secure and authenticated if needed.
Validation: Add more validation as required, e.g., file size limits, allowed file types, etc.
PaddleOCR: If you encounter issues with PaddleOCR not being thread-safe, you might need to initialize it inside each function or ensure that it is used in a thread-safe manner.
Ollama and LangChain: Ensure that the LLM service you're using (Ollama) is accessible and that the langchain library is properly configured.
Conclusion:
This refactored code turns your script into a FastAPI application with two endpoints, handling file uploads and queries without reprocessing the files when querying. It maintains the same functionality while leveraging FastAPI's capabilities.