turn your RAG-enabled OCR pipeline into a local web app so you can:
- Upload images & PDFs through a browser.
- Run OCR automatically.
- Store embeddings + metadata.
- Ask questions and get grounded answers from your processed documents.
We’ll use FastAPI for the backend and Streamlit for the UI — this keeps it lightweight, easy to run locally, and interactive.
RAG OCR Web App — FastAPI + Streamlit
Backend (FastAPI) — rag_backend.py
PythonCopy codeimport os
import uuid
from datetime import datetime
from fastapi import FastAPI, UploadFile, Form
from PIL import Image
import pytesseract
import fitz
import nltk
import json
import sqlite3
import faiss
from nltk.corpus import stopwords
from sentence_transformers import SentenceTransformer
import spacy
from transformers import pipeline
# ===== CONFIG =====
DOC_FOLDER = "uploaded_docs"
VECTOR_DB_PATH = "vector_index.faiss"
SQLITE_DB_PATH = "metadata.db"
MODEL_NAME = "all-MiniLM-L6-v2"
CHUNK_SIZE = 300
STOPWORDS = set(stopwords.words('english'))
# ===== Setup =====
nltk.download('punkt')
nltk.download('stopwords')
nlp = spacy.load("en_core_web_sm")
qa_pipeline = pipeline("question-answering", model="deepset/roberta-base-squad2")
model = SentenceTransformer(MODEL_NAME)
app = FastAPI()
# ===== DB Init =====
def init_sqlite():
conn = sqlite3.connect(SQLITE_DB_PATH)
c = conn.cursor()
c.execute("""
CREATE TABLE IF NOT EXISTS metadata (
id TEXT PRIMARY KEY,
timestamp TEXT,
source_file TEXT,
chunk_text TEXT,
tokens TEXT,
tags TEXT
)
""")
conn.commit()
conn.close()
init_sqlite()
# ===== OCR Functions =====
def extract_text_from_image(image_path):
image = Image.open(image_path)
return pytesseract.image_to_string(image).strip()
def extract_text_from_pdf(pdf_path):
doc = fitz.open(pdf_path)
text = ""
for page in doc:
text += page.get_text("text") + "\n"
return text.strip()
def chunk_text(text, chunk_size=CHUNK_SIZE):
return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
def tokenize_and_clean(text):
tokens = nltk.word_tokenize(text)
return [t for t in tokens if t.lower() not in STOPWORDS and t.isalpha()]
def auto_tag(text):
doc = nlp(text)
return list(set([ent.text for ent in doc.ents]))
def vectorize_text(text):
return model.encode([text], convert_to_numpy=True)
def store_vector(embedding, metadata_json):
dim = embedding.shape[1]
try:
index = faiss.read_index(VECTOR_DB_PATH)
except:
index = faiss.IndexFlatL2(dim)
index.add(embedding)
faiss.write_index(index, VECTOR_DB_PATH)
conn = sqlite3.connect(SQLITE_DB_PATH)
c = conn.cursor()
c.execute("""
INSERT INTO metadata (id, timestamp, source_file, chunk_text, tokens, tags)
VALUES (?, ?, ?, ?, ?, ?)
""", (
metadata_json["id"],
metadata_json["timestamp"],
metadata_json["source_file"],
metadata_json["chunk_text"],
json.dumps(metadata_json["tokens"]),
json.dumps(metadata_json["tags"])
))
conn.commit()
conn.close()
def search_vector(query_text, top_k=3):
index = faiss.read_index(VECTOR_DB_PATH)
query_vec = model.encode([query_text], convert_to_numpy=True)
distances, ids = index.search(query_vec, top_k)
conn = sqlite3.connect(SQLITE_DB_PATH)
c = conn.cursor()
results = []
for i, idx in enumerate(ids[0]):
c.execute("SELECT * FROM metadata WHERE rowid=?", (idx+1,))
row = c.fetchone()
if row:
results.append({
"metadata": {
"id": row[0],
"timestamp": row[1],
"source_file": row[2],
"chunk_text": row[3],
"tokens": json.loads(row[4]),
"tags": json.loads(row[5])
},
"distance": float(distances[0][i])
})
conn.close()
return results
def rag_answer(query_text, top_k=3):
retrieved_chunks = search_vector(query_text, top
#finish the FastAPI backend so it can handle both document uploads and RAG queries, then we’ll move on to the Streamlit frontend. Continuing rag_backend.py
# Step 2: Concatenate retrieved text for context
context_text = " ".join([chunk["metadata"]["chunk_text"] for chunk in retrieved_chunks])
# Step 3: Run QA pipeline
answer = qa_pipeline(question=query_text, context=context_text)
return {
"query": query_text,
"answer": answer["answer"],
"score": answer["score"],
"sources": [chunk["metadata"]["source_file"] for chunk in retrieved_chunks]
}
# ===== API Endpoints =====
@app.post("/upload")
async def upload_file(file: UploadFile):
os.makedirs(DOC_FOLDER, exist_ok=True)
file_path = os.path.join(DOC_FOLDER, file.filename)
# Save uploaded file
with open(file_path, "wb") as f:
f.write(await file.read())
# OCR based on file type
if file.filename.lower().endswith((".png", ".jpg", ".jpeg", ".tiff")):
extracted_text = extract_text_from_image(file_path)
elif file.filename.lower().endswith(".pdf"):
extracted_text = extract_text_from_pdf(file_path)
else:
return {"error": "Unsupported file type"}
# Chunk text
chunks = chunk_text(extracted_text)
for chunk in chunks:
tokens = tokenize_and_clean(chunk)
tags = auto_tag(chunk)
embedding = vectorize_text(" ".join(tokens))
metadata_json = {
"id": str(uuid.uuid4()),
"timestamp": datetime.utcnow().isoformat(),
"source_file": file.filename,
"chunk_text": chunk,
"tokens": tokens,
"tags": tags
}
store_vector(embedding, metadata_json)
return {"status": "File processed successfully", "chunks": len(chunks)}
@app.get("/search")
def search(query: str, top_k: int = 3):
results = search_vector(query, top_k=top_k)
return {"query": query, "results": results}
@app.get("/rag")
def rag(query: str, top_k: int = 3):
result = rag_answer(query, top_k=top_k)
return result
Frontend (Streamlit) — rag_frontend.py
import requests
import streamlit as st
BACKEND_URL = "http://localhost:8000"
st.title("📄 OCR + RAG Document Search")
# ===== Upload Section =====
st.header("Upload Document")
uploaded_file = st.file_uploader("Choose an image or PDF", type=["png", "jpg", "jpeg", "tiff", "pdf"])
if uploaded_file is not None:
if st.button("Upload & Process"):
files = {"file": uploaded_file.getvalue()}
response = requests.post(f"{BACKEND_URL}/upload", files={"file": uploaded_file})
st.write(response.json())
# ===== Search Section =====
st.header("Search Documents")
query = st.text_input("Enter search query")
if st.button("Search"):
response = requests.get(f"{BACKEND_URL}/search", params={"query": query, "top_k": 5})
results = response.json()["results"]
for r in results:
st.write(f"📄 {r['metadata']['source_file']} — Distance: {r['distance']:.4f}")
st.write(f"Chunk: {r['metadata']['chunk_text'][:200]}...")
st.write(f"Tags: {', '.join(r['metadata']['tags'])}")
# ===== RAG Q&A Section =====
st.header("Ask a Question (RAG)")
question = st.text_input("Enter your question")
if st.button("Get Answer"):
response = requests.get(f"{BACKEND_URL}/rag", params={"query": question, "top_k": 5})
rag_result = response.json()
st.subheader("Answer")
st.write(rag_result["answer"])
st.write(f"Confidence Score: {rag_result['score']:.4f}")
st.write("Sources:", ", ".join(rag_result["sources"]))
How to Run the Web App
- Install dependencies:
Bash: pip install fastapi uvicorn pillow pytesseract nltk sentence-transformers faiss-cpu spacy transformers pymupdf streamlit requests
python -m spacy download en_core_web_sm
- Install Tesseract OCR:
- Linux:
sudo apt install tesseract-ocr - Mac: `brew install t