CoolFace
Apppublic

omravalccc/rag_final_optimized

sourceHugging Faceupdated 8mo agoView on Hugging Face
0likes
App README

Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference


๐Ÿ“š RAG Final Optimized - Knowledge Assistant

A production-ready Retrieval-Augmented Generation (RAG) system built for efficient document processing, semantic search, and intelligent question answering. Optimized for Hugging Face Spaces deployment with Docker.

๐ŸŽฏ Project Overview

This system allows users to:

  • โ€”Upload documents (PDF, DOCX, TXT, Images)
  • โ€”Automatically extract text with OCR support
  • โ€”Create semantic chunks using embedding similarity
  • โ€”Store vectors in FAISS for fast retrieval
  • โ€”Answer questions using Gemini LLM with retrieved context

๐Ÿ—๏ธ Architecture Choices & Justifications

1. Embedding Model Selection

ModelSizeSpeedQualityHF DeploymentOur Choice
intfloat/e5-base-v2438MBโšก Fast๐ŸŸข Excellentโœ… Easyโœ… Selected
sentence-transformers/all-MiniLM-L6-v280MBโšกโšก Fastest๐ŸŸก Goodโœ… EasyโŒ
text-embedding-ada-002 (OpenAI)API๐ŸŸก Network๐ŸŸข ExcellentโŒ API Key RequiredโŒ
BAAI/bge-large-en-v1.51.3GB๐Ÿ”ด Slow๐ŸŸข Excellentโš ๏ธ Memory IssuesโŒ
google/flan-t5-large3GB๐Ÿ”ด Very Slow๐ŸŸข ExcellentโŒ Load Time 5min+โŒ

Why E5-base-v2?

  • โ€”Perfect balance of size (438MB) and quality
  • โ€”Supports asymmetric retrieval with query: and passage: prefixes
  • โ€”Loads in under 30 seconds on HF Spaces
  • โ€”MTEB benchmark top performer in its size category
  • โ€”No API key required - runs fully locally

2. Vector Database Selection

Vector DBSpeedMemoryPersistenceSetup ComplexityOur Choice
FAISS (CPU)โšกโšก Fastest๐ŸŸข Lowโœ… File-based๐ŸŸข Simpleโœ… Selected
ChromaDBโšก Fast๐ŸŸก Mediumโœ… SQLite๐ŸŸก MediumโŒ
Pineconeโšก Fastโ˜๏ธ Cloudโœ… Managed๐Ÿ”ด API Key + SetupโŒ
Weaviateโšก Fast๐Ÿ”ด Highโœ… Yes๐Ÿ”ด Complex DockerโŒ
Milvusโšก Fast๐Ÿ”ด Highโœ… Yes๐Ÿ”ด Very ComplexโŒ
PostgreSQL + pgvector๐ŸŸก Medium๐ŸŸก Mediumโœ… Yes๐Ÿ”ด DB Setup RequiredโŒ

Why FAISS?

  • โ€”Zero external dependencies - just pip install
  • โ€”File-based persistence - simple save/load
  • โ€”Inner Product similarity for normalized embeddings
  • โ€”Battle-tested by Meta AI for billion-scale search
  • โ€”Works perfectly in Docker/HF Spaces environment

3. LLM Selection for Answer Generation

LLMResponse QualitySpeedCostHF DeploymentOur Choice
Gemini 2.5 Flash๐ŸŸข Excellentโšกโšก Very Fast๐Ÿ’š Free Tierโœ… API Key Onlyโœ… Selected
Gemini 2.5 Pro๐ŸŸข Excellentโšก Fast๐Ÿ’› Paidโœ… API Key Onlyโœ… Fallback
GPT-4o๐ŸŸข Excellentโšก Fast๐Ÿ”ด Expensiveโœ… API Key OnlyโŒ
GPT-3.5 Turbo๐ŸŸก Goodโšกโšก Very Fast๐Ÿ’› Cheapโœ… API Key OnlyโŒ
Llama 3.1 70B (Local)๐ŸŸข Excellent๐Ÿ”ด Very Slow๐Ÿ’š FreeโŒ 140GB+ RAMโŒ
Mistral 7B (Local)๐ŸŸก Good๐Ÿ”ด Slow๐Ÿ’š FreeโŒ 16GB+ RAMโŒ
google/flan-t5-large๐ŸŸก Medium๐Ÿ”ด Very Slow๐Ÿ’š Freeโš ๏ธ 5min+ LoadโŒ

Why Gemini 2.5 Flash?

  • โ€”Free tier with generous quota
  • โ€”Extremely fast response times
  • โ€”High quality outputs for RAG tasks
  • โ€”No model download required - API based
  • โ€”Automatic fallback to Pro and older versions
  • โ€”Easy HF Spaces deployment with just API key in secrets

4. Chunking Strategy Comparison

StrategyContext PreservationSpeedComplexityOur Choice
Semantic Chunking๐ŸŸข Excellent๐ŸŸก Medium๐ŸŸก Mediumโœ… Selected
Fixed Size (500 tokens)๐Ÿ”ด Poorโšกโšก Fastest๐ŸŸข SimpleโŒ
Sentence-based๐ŸŸก Goodโšก Fast๐ŸŸข SimpleโŒ
Paragraph-based๐ŸŸก Goodโšก Fast๐ŸŸข SimpleโŒ
Recursive Character๐ŸŸก Goodโšก Fast๐ŸŸก MediumโŒ

Why Semantic Chunking?

  • โ€”Groups semantically similar sentences together
  • โ€”Uses embedding similarity threshold (0.75)
  • โ€”Preserves topic coherence within chunks
  • โ€”Better retrieval accuracy than fixed-size chunking
  • โ€”Respects natural content boundaries

5. OCR and Document Processing

ToolPDF SupportImage OCRDOCXSpeedOur Choice
pdfplumber + pytesseractโœ… Fullโœ… Fullโœ… Full๐ŸŸก Mediumโœ… Selected
PyMuPDF (fitz)โœ… Fullโš ๏ธ LimitedโŒโšก FastโŒ
Unstructured.ioโœ… Fullโœ… Fullโœ… Full๐Ÿ”ด SlowโŒ
Azure Document Intelligenceโœ… Fullโœ… Fullโœ… Fullโšก FastโŒ API Cost
AWS Textractโœ… Fullโœ… Fullโš ๏ธ Limitedโšก FastโŒ API Cost

Why pdfplumber + pytesseract?

  • โ€”Open source and free
  • โ€”Excellent PDF text extraction
  • โ€”Tesseract OCR for scanned pages and images
  • โ€”Works in Docker with apt packages
  • โ€”Handles mixed documents (text + images)

๐Ÿ“Š Performance Benchmarks

Model Loading Times (HF Spaces - 2 vCPU, 16GB RAM)

ComponentLoad TimeMemory
E5-base-v2 Embedding~25 seconds~900MB
FAISS Index (10K chunks)< 1 second~50MB
Streamlit App~5 seconds~200MB
Total Cold Start~35 seconds~1.2GB

Query Performance

OperationTime
Embed Query~50ms
FAISS Search (10K vectors)~5ms
Gemini API Response~1-3 seconds
Total Query Time~2-4 seconds

๐Ÿ”„ Why NOT These Alternatives?

Local LLMs (Llama, Mistral, etc.)

IssueImpact
Model Size7B+ models = 14GB+ download
RAM Requirements16-32GB minimum
HF Spaces LimitsFree tier has 16GB RAM
Cold Start5-10 minutes to load
Inference Speed10-60 seconds per response

OpenAI Embeddings

IssueImpact
API Costs$0.0001 per 1K tokens
Network DependencyLatency + potential failures
Rate LimitsCan hit limits on batch processing
Data PrivacyData sent to OpenAI servers

Google Flan-T5 Models

IssueImpact
Load Time3-8 minutes on HF Spaces
Memory Usage3-6GB for large variants
Response QualityGood but not as detailed as Gemini
HF DeploymentOften times out during loading

Heavy Vector DBs (Milvus, Weaviate)

IssueImpact
Setup ComplexityRequires separate containers
Memory Usage2-4GB minimum
Docker ComposeNot supported on HF Spaces
OverkillOur scale doesn't need distributed DB

๐Ÿ› ๏ธ Technical Implementation Details

Embedding Strategy

Documents โ†’ "passage: {text}" โ†’ E5-base-v2 โ†’ Normalized Vectors
Queries   โ†’ "query: {text}"   โ†’ E5-base-v2 โ†’ Normalized Vectors

Similarity Metric

  • โ€”Using Inner Product (IP) instead of L2 distance
  • โ€”Vectors are normalized โ†’ IP equals cosine similarity
  • โ€”Faster computation for normalized vectors

Chunking Algorithm

1. Split text into sentences
2. Embed each sentence
3. For each sentence:
   - If similarity with current chunk โ‰ฅ 0.75 AND size < max_size:
     โ†’ Add to current chunk
   - Else:
     โ†’ Start new chunk
4. Merge small chunks (< 100 chars) with neighbors

๐Ÿ“ Project Structure

rag_final_optimized/
โ”œโ”€โ”€ utils/
โ”‚   โ”œโ”€โ”€ docs_reciever.py     # Document ingestion + chunking + embedding
โ”‚   โ””โ”€โ”€ ans_retrieval.py     # Vector search + Gemini answer generation
โ”œโ”€โ”€ streamlit.py             # Web UI with tabs
โ”œโ”€โ”€ requirements.txt         # Python dependencies
โ”œโ”€โ”€ packages.txt             # System packages (apt)
โ”œโ”€โ”€ Dockerfile               # HF Spaces deployment
โ”œโ”€โ”€ .env                     # API keys (local only)
โ””โ”€โ”€ README.md                # This file

๐Ÿš€ Deployment

Hugging Face Spaces

  1. 1.Push to HF Space repository
  2. 2.Add GEMINI_API_KEY to Space secrets
  3. 3.Wait for Docker build (~5 minutes)
  4. 4.App is live!

Local Development

bash
pip install -r requirements.txt
streamlit run streamlit.py

๐Ÿ”‘ Environment Variables

VariableRequiredDescription
GEMINI_API_KEYโœ… YesPrimary Gemini API key
GEMINI_API_KEY_2โŒ OptionalFallback API key for rate limits

๐Ÿ“ˆ Future Improvements

  • โ€”[ ] Add reranking with cross-encoder
  • โ€”[ ] Implement hybrid search (BM25 + vector)
  • โ€”[ ] Add conversation history/memory
  • โ€”[ ] Support more file formats (Excel, PPT)
  • โ€”[ ] Add multi-language support

๐Ÿ“ License

MIT License - Feel free to use and modify!


Built with โค๏ธ using Streamlit, FAISS, E5 Embeddings, and Gemini