Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

Update: vision RAG project

Tiioluwanifb79419298ca
diff --git a/vision_rag/.env.example b/vision_rag/.env.example
new file mode 100644
index 0000000..ca327ce
--- /dev/null
+++ b/vision_rag/.env.example
@@ -0,0 +1,2 @@
+OPENAI_API_KEY=your_openai_api_key_here
+COHERE_API_KEY=your_cohere_api_key_here
diff --git a/vision_rag/.gitignore b/vision_rag/.gitignore
new file mode 100644
index 0000000..6b17d32
--- /dev/null
+++ b/vision_rag/.gitignore
@@ -0,0 +1,7 @@
+.env
+__pycache__/
+venv/
+.DS_Store
+*.pyc
+lancedb_data/
+vision_rag_data/
diff --git a/vision_rag/README.md b/vision_rag/README.md
index e2ec88a..ce61811 100644
--- a/vision_rag/README.md
+++ b/vision_rag/README.md
@@ -1,78 +1,35 @@
-# VisionRAG: Multimodal Search & Visual Question Answering
+# VisionRAG (Multimodal Search & VQA)
-A powerful Streamlit application that combines multimodal search with visual question answering to analyze images and PDF documents using AI.
+A visual-first search engine that allows you to "talk" to your images and PDF documents. It combines visual similarity search with advanced Visual Question Answering (VQA).
-## Features
+## Principal Functionalities
+- **Visual Retrieval Augmented Generation (VisionRAG)**: Unlike text-only RAG, this system breaks down PDFs and images into visual segments and uses **Cohere Embed-v3** to find the most relevant visual context for your question.
+- **Multimodal Question Answering**: Powered by **OpenAI Vision**, the system "looks" at the retrieved image or PDF page to answer specific questions about charts, diagrams, or photos.
+- **PDF-to-Visual Indexing**: High-fidelity conversion of PDF pages into searchable visual chunks using **PyMuPDF**.
+- **Interactive Visual Chat**: A dashboard that shows you exactly which part of the document the AI is looking at when it gives its answer.
-- **Multimodal Search**: Uses Cohere Embed-4 to find semantically relevant images for text questions
-- **Visual Question Answering**: Employs Google Gemini 2.5 Flash to analyze images and generate context-aware answers
-- **Flexible Content Sources**:
- - Upload custom images (PNG, JPG, JPEG)
- - Upload PDF documents (automatically extracts pages as images)
- - Load sample financial charts and infographics
-- **No OCR Required**: Directly processes complex visual elements without text extraction
+## Technical Context
+- **Intelligence**: OpenAI `gpt-4o-mini` (Vision-enabled) for multimodal understanding.
+- **Embeddings**: Cohere `embed-english-v3.0` for high-accuracy visual search.
+- **Processing**: PyMuPDF and Pillow for document-to-image pipeline.
-## 🚀 Quick Start
+## Setup & Execution
-### Prerequisites
+### 1. Requirements
+This project runs within the shared repository environment. Ensure dependencies are installed:
+```bash
+pip install -r requirements.txt
+```
-- Python 3.8+
-- Cohere API key
-- Google Gemini API key
+### 2. Environment
+The application pulls your `OPENAI_API_KEY` and `COHERE_API_KEY` from the root `.env` file.
-### Installation
-
-1. **Clone the repository**
- ```bash
- git clone <repository-url>
- cd vision-rag
- ```
-
-2. **Create and activate virtual environment**
- ```bash
- python -m venv venv
- # On Windows
- .\venv\Scripts\activate
- # On macOS/Linux
- source venv/bin/activate
- ```
-
-3. **Install dependencies**
- ```bash
- pip install -r requirements.txt
- ```
-
-4. **Set up API keys**
- - Get your [Cohere API key](https://cohere.ai/)
- - Get your [Google Gemini API key](https://makersuite.google.com/app/apikey)
- - Create a `.env` file in the project root
- - Add your API keys to the `.env` file:
- ```
- COHERE_API_KEY=your_cohere_api_key_here
- GEMINI_API_KEY=your_gemini_api_key_here
- ```
-
-5. **Run the application**
- ```bash
- streamlit run app.py
- ```
-
-## Dependencies
-
-- **streamlit**: Web application framework
-- **cohere**: Embedding generation
-- **requests**: HTTP requests for Gemini API
-- **PyMuPDF**: PDF processing
-- **Pillow**: Image processing
-- **numpy**: Numerical operations
-- **scikit-learn**: Cosine similarity calculations
-
-
-## Contributing
-
-Contributions, issues, and feature requests are welcome. Please feel free to submit a Pull Request or open an issue.
-
-## License
-
-This project is licensed under the MIT License - see the LICENSE file for details.
+### 3. Launch
+```bash
+streamlit run app.py
+```
+## How to Use
+1. **Upload**: Load any image (PNG/JPG) or a multi-page PDF document.
+2. **Interact**: Ask a question like "What does the growth chart on page 3 indicate?" or "Describe the logo in this image."
+3. **Verify**: The system will display the most relevant visual segment side-by-side with its AI-generated answer.
diff --git a/vision_rag/app.py b/vision_rag/app.py
index 36de46b..6ed301f 100644
--- a/vision_rag/app.py
+++ b/vision_rag/app.py
@@ -3,19 +3,18 @@ import os
import datetime
from PIL import Image
import numpy as np
-from dotenv import load_dotenv
-from utils import get_cohere_embedding, gemini_vqa, pdf_to_images, image_to_bytes, find_most_similar
+from dotenv import load_dotenv, find_dotenv
+from utils import get_cohere_embedding, openai_vqa, pdf_to_images, image_to_bytes, find_most_similar
# Load environment variables
-load_dotenv()
+load_dotenv(find_dotenv())
# Page configuration
st.set_page_config(page_title="VisionRAG: Multimodal Search & VQA", layout="wide")
st.title("VisionRAG: Multimodal Search & Visual Question Answering")
-# API Keys from environment variables
cohere_api = os.getenv("COHERE_API_KEY")
-gemini_api = os.getenv("GEMINI_API_KEY")
+openai_api = os.getenv("OPENAI_API_KEY")
# Initialize session state
if 'items' not in st.session_state:
@@ -103,8 +102,8 @@ with st.form("question_form"):
# Process question submission
if submit_button:
- if not cohere_api or not gemini_api:
- st.error("Please provide both Cohere and Gemini API keys.")
+ if not cohere_api or not openai_api:
+ st.error("Please provide both Cohere and OpenAI API keys.")
elif not question:
st.error("Please enter a question.")
elif not st.session_state['items']:
@@ -125,10 +124,10 @@ if submit_button:
idx, sim = find_most_similar(q_emb, emb_list)
best_item = st.session_state['items'][idx]
- # Generate answer using Gemini
- st.info("Generating answer with Gemini...")
+ # Generate answer using OpenAI
+ st.info("Generating answer with OpenAI Vision...")
img_bytes = image_to_bytes(best_item['img'])
- answer = gemini_vqa(gemini_api, img_bytes, question)
+ answer = openai_vqa(openai_api, img_bytes, question)
# Add to conversation history
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
diff --git a/vision_rag/requirements.txt b/vision_rag/requirements.txt
index a031eb8..c3d06e6 100644
--- a/vision_rag/requirements.txt
+++ b/vision_rag/requirements.txt
@@ -1,8 +1,9 @@
streamlit
cohere
-requests
+openai==1.83.0
+python-dotenv
PyMuPDF
Pillow
numpy
scikit-learn
-python-dotenv
\ No newline at end of file
+requests
\ No newline at end of file
diff --git a/vision_rag/utils.py b/vision_rag/utils.py
index eba83c2..ee6e3c4 100644
--- a/vision_rag/utils.py
+++ b/vision_rag/utils.py
@@ -40,40 +40,46 @@ def get_cohere_embedding(api_key, input_data, input_type='text'):
else:
raise ValueError("input_type must be 'text' or 'image'")
-# --- Google Gemini 2.5 Flash VQA ---
-def gemini_vqa(api_key, image_bytes, question):
+# --- OpenAI GPT-4o-mini VQA ---
+def openai_vqa(api_key, image_bytes, question):
"""
- Send image and question to Gemini 2.5 Flash for Visual Question Answering.
+ Send image and question to GPT-4o-mini for Visual Question Answering.
Args:
- api_key (str): Google Gemini API key
+ api_key (str): OpenAI API key
image_bytes (bytes): Image data
question (str): Question about the image
Returns:
str: Generated answer
"""
- endpoint = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={api_key}"
- headers = {"Content-Type": "application/json"}
-
- image_b64 = base64.b64encode(image_bytes).decode()
- data = {
- "contents": [
- {
- "parts": [
- {"inline_data": {"mime_type": "image/png", "data": image_b64}},
- {"text": question}
- ]
- }
- ]
- }
-
- response = requests.post(endpoint, headers=headers, json=data)
-
- if response.status_code == 200:
- return response.json()['candidates'][0]['content']['parts'][0]['text']
- else:
- return f"Error: {response.status_code} {response.text}"
+ try:
+ from openai import OpenAI
+ client = OpenAI(api_key=api_key)
+
+ image_b64 = base64.b64encode(image_bytes).decode('utf-8')
+
+ response = client.chat.completions.create(
+ model="gpt-4o-mini",
+ messages=[
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": question},
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": f"data:image/png;base64,{image_b64}"
+ }
+ },
+ ],
+ }
+ ],
+ max_tokens=500,
+ )
+ return response.choices[0].message.content
+ except Exception as e:
+ return f"Error with OpenAI Vision: {e}"
# --- PDF to Images ---
def pdf_to_images(pdf_bytes):