A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
audit: fix vision_rag - swap OpenAI for Mistral, fix Cohere model version, add env comments, add docstring, add demo, improve README
Tiioluwani2615824d0650
diff --git a/rag_apps/vision_rag/.env.example b/rag_apps/vision_rag/.env.exampleindex ca327ce..9752a2a 100644--- a/rag_apps/vision_rag/.env.example+++ b/rag_apps/vision_rag/.env.example@@ -1,2 +1,7 @@-OPENAI_API_KEY=your_openai_api_key_here+# Mistral API key used for Mistral Small (vision) question answering.+# Get one free at https://platform.mistral.ai+MISTRAL_API_KEY=your_mistral_api_key_here++# Cohere API key used for embed-v4.0 multimodal embeddings.+# Get one free at https://cohere.comCOHERE_API_KEY=your_cohere_api_key_herediff --git a/rag_apps/vision_rag/README.md b/rag_apps/vision_rag/README.mdindex bf5f693..e330e79 100644--- a/rag_apps/vision_rag/README.md+++ b/rag_apps/vision_rag/README.md@@ -3,28 +3,36 @@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).## 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.+- **Visual Retrieval Augmented Generation (VisionRAG)**: Unlike text-only RAG, this system breaks down PDFs and images into visual segments and uses **Cohere Embed-v4** to find the most relevant visual context for your question.+- **Multimodal Question Answering**: Powered by **Mistral Small (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.## Technical Context-- **Intelligence**: OpenAI `gpt-4o-mini` (Vision-enabled) for multimodal understanding.-- **Embeddings**: Cohere `embed-english-v3.0` for high-accuracy visual search.+- **Intelligence**: Mistral `mistral-small-latest` (Vision-enabled) for multimodal understanding.+- **Embeddings**: Cohere `embed-v4.0` for high-accuracy visual search.- **Processing**: PyMuPDF and Pillow for document-to-image pipeline.+## Prerequisites++- Python 3.9 or later+- A Cohere API key, get one free at [cohere.com](https://cohere.com)+- A Mistral API key, get one free at [platform.mistral.ai](https://platform.mistral.ai)++## Demo+++## Setup & Execution### 1. Requirements-This project runs within the shared repository environment. Ensure dependencies are installed:--This project runs within the shared repository environment. Ensure dependencies are installed:From the `vision_rag` directory, install dependencies:- ```bash+```bashcd vision_rag- pip install -r requirements.txt+pip install -r requirements.txt```### 2. Environment-The application pulls your `OPENAI_API_KEY` and `COHERE_API_KEY` from the root `.env` file.+The application pulls your `MISTRAL_API_KEY` and `COHERE_API_KEY` from the root `.env` file.### 3. Launch```bash@@ -35,3 +43,5 @@ streamlit run app.py1. **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.++[Back to top](#visionrag-multimodal-search--vqa)diff --git a/rag_apps/vision_rag/app.py b/rag_apps/vision_rag/app.pyindex 6ed301f..3179340 100644--- a/rag_apps/vision_rag/app.py+++ b/rag_apps/vision_rag/app.py@@ -1,10 +1,14 @@+"""+VisionRAG: Multimodal Search & Visual Question Answering Streamlit app.+"""+import streamlit as stimport osimport datetimefrom PIL import Imageimport numpy as npfrom dotenv import load_dotenv, find_dotenv-from utils import get_cohere_embedding, openai_vqa, pdf_to_images, image_to_bytes, find_most_similar+from utils import get_cohere_embedding, mistral_vqa, pdf_to_images, image_to_bytes, find_most_similar# Load environment variablesload_dotenv(find_dotenv())@@ -14,7 +18,7 @@ st.set_page_config(page_title="VisionRAG: Multimodal Search & VQA", layout="widest.title("VisionRAG: Multimodal Search & Visual Question Answering")cohere_api = os.getenv("COHERE_API_KEY")-openai_api = os.getenv("OPENAI_API_KEY")+mistral_api = os.getenv("MISTRAL_API_KEY")# Initialize session stateif 'items' not in st.session_state:@@ -102,8 +106,8 @@ with st.form("question_form"):# Process question submissionif submit_button:- if not cohere_api or not openai_api:- st.error("Please provide both Cohere and OpenAI API keys.")+ if not cohere_api or not mistral_api:+ st.error("Please provide both Cohere and Mistral API keys.")elif not question:st.error("Please enter a question.")elif not st.session_state['items']:@@ -124,10 +128,10 @@ if submit_button:idx, sim = find_most_similar(q_emb, emb_list)best_item = st.session_state['items'][idx]- # Generate answer using OpenAI- st.info("Generating answer with OpenAI Vision...")+ # Generate answer using Mistral+ st.info("Generating answer with Mistral Vision...")img_bytes = image_to_bytes(best_item['img'])- answer = openai_vqa(openai_api, img_bytes, question)+ answer = mistral_vqa(mistral_api, img_bytes, question)# Add to conversation historytimestamp = datetime.datetime.now().strftime("%H:%M:%S")diff --git a/rag_apps/vision_rag/assets/demo.gif b/rag_apps/vision_rag/assets/demo.gifnew file mode 100644index 0000000..8d6ace7Binary files /dev/null and b/rag_apps/vision_rag/assets/demo.gif differdiff --git a/rag_apps/vision_rag/requirements.txt b/rag_apps/vision_rag/requirements.txtindex c3d06e6..c0d5a5d 100644--- a/rag_apps/vision_rag/requirements.txt+++ b/rag_apps/vision_rag/requirements.txt@@ -1,6 +1,6 @@streamlitcohere-openai==1.83.0+mistralaipython-dotenvPyMuPDFPillowdiff --git a/rag_apps/vision_rag/utils.py b/rag_apps/vision_rag/utils.pyindex 718532d..a7bf04f 100644--- a/rag_apps/vision_rag/utils.py+++ b/rag_apps/vision_rag/utils.py@@ -40,26 +40,26 @@ def get_cohere_embedding(api_key, input_data, input_type='text'):else:raise ValueError("input_type must be 'text' or 'image'")-# --- OpenAI GPT-4o-mini VQA ----def openai_vqa(api_key, image_bytes, question):+# --- Mistral Small VQA ---+def mistral_vqa(api_key, image_bytes, question):"""- Send image and question to GPT-4o-mini for Visual Question Answering.-+ Send image and question to Mistral Small for Visual Question Answering.+Args:- api_key (str): OpenAI API key+ api_key (str): Mistral API keyimage_bytes (bytes): Image dataquestion (str): Question about the image-+Returns:str: Generated answer"""- from openai import OpenAI- client = OpenAI(api_key=api_key, timeout=30.0)-+ from mistralai.client import Mistral+ client = Mistral(api_key=api_key)+image_b64 = base64.b64encode(image_bytes).decode('utf-8')-- response = client.chat.completions.create(- model="gpt-4o-mini",++ response = client.chat.complete(+ model="mistral-small-latest",messages=[{"role": "user",@@ -67,7 +67,7 @@ def openai_vqa(api_key, image_bytes, question):{"type": "text", "text": question},{"type": "image_url",- "image_url": {"url": f"data:image/png;base64,{image_b64}"},+ "image_url": f"data:image/png;base64,{image_b64}",},],}