A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
added merged project to the readme
cyberholics0a3ca0b5ebe8
diff --git a/OCR/glm_ocr_pro/.gitignore b/OCR/glm_ocr_pro/.gitignoredeleted file mode 100644index 3cebe7d..0000000--- a/OCR/glm_ocr_pro/.gitignore+++ /dev/null@@ -1,4 +0,0 @@-.idea/-*.iml-__pycache__/-*.pyc\ No newline at end of filediff --git a/OCR/glm_ocr_pro/README.md b/OCR/glm_ocr_pro/README.mddeleted file mode 100644index 31cf982..0000000--- a/OCR/glm_ocr_pro/README.md+++ /dev/null@@ -1,112 +0,0 @@-# GLM-OCR Pro π§Ύ--**GLM-OCR Pro** is a high-performance, local-first Streamlit application designed for structured document extraction. It leverages the **GLM-OCR** model via Ollama to transform images and PDFs into cleanly formatted Markdown in real-time.--## Demo---------## Overview--GLM-OCR Pro solves the problem of extracting structured text from documents without sending sensitive data to external APIs. It runs entirely on your local machine using the GLM-OCR model via Ollama, making it ideal for confidential documents. The app streams results in real-time and outputs clean, structured Markdown that preserves headings, tables, and lists.--## Prerequisites--Before you begin, ensure you have:-- Python 3.8 or higher-- [Ollama](https://ollama.com) installed and running-- The GLM-OCR model pulled: `ollama pull glm-ocr`-- A GPU with at least 4GB VRAM (recommended)--## Features--- **100% Private & Local:** No data ever leaves your machine. Perfect for sensitive documents.-- **Real-time Streaming:** Watch text populate your screen as the model identifies it.-- **Premium UI:** A modern, glassmorphism-inspired dashboard with support for complex tables.-- **Hardware Optimized:** Pre-configured performance profiles tailored for laptop and desktop GPUs.-- **Multi-Format Support:** Seamlessly handles PNG, JPG, JPEG, and multi-page PDFs.-------## Quick Start--### 1. Clone the Repository--```bash-git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git-cd Hands-On-AI-Engineering/OCR/glm_ocr_pro-```--### 2. Install Ollama--Download and install Ollama from [ollama.com](https://ollama.com).--### 3. Pull the GLM-OCR Model--Open your terminal and run:--```bash-ollama pull glm-ocr-```--### 4. Setup the Python Environment--```bash-# Optional: Create a virtual environment-python -m venv .venv-source .venv/bin/activate # Or `.venv\Scripts\activate` on Windows--# Install dependencies-pip install -r requirements.txt-```--### 5. Run the App--```bash-streamlit run app.py-```-------## Usage--Once the app is running at `http://localhost:8501`:--1. Check the **Ollama Status** indicator in the Settings panel. If the model is not loaded, click **Warm Up Model**.-2. Upload a document (PNG, JPG, JPEG, or PDF) using the file uploader.-3. Select a **Performance Profile** to match your GPU: Balanced, Fast, or Ultra Fast.-4. Click **Extract Knowledge** to run OCR. Results stream in real time on the right panel.-5. Download the extracted Markdown with the **Download .md** button or copy it from the raw source viewer.-------## Performance Tuning--GLM-OCR Pro includes three "Performance Profiles" to help you balance speed and accuracy based on your hardware:--| Profile | Image Res. | Grayscale | Use Case |-| :--- | :--- | :--- | :--- |-| **Balanced** | 1300px | No | High-accuracy scanning on desktop GPUs. |-| **Fast** | 1000px | Yes | Optimal for mid-range GPUs (e.g., 4GB VRAM). |-| **Ultra Fast** | 800px | Yes | Lightning-fast extractions for simple text. |-------## Tech Stack--- **UI Framework:** Streamlit-- **PDF Engine:** PyPDFium2-- **Image Processing:** Pillow-- **Inference:** Ollama (`glm-ocr`)-------## License--This project is intended for personal and professional use. Ensure compliance with the GLM-OCR and Ollama licensing terms.-------[Back to top](#glm-ocr-pro)diff --git a/OCR/glm_ocr_pro/app.py b/OCR/glm_ocr_pro/app.pydeleted file mode 100644index 7770d4b..0000000--- a/OCR/glm_ocr_pro/app.py+++ /dev/null@@ -1,149 +0,0 @@-"""Streamlit application that uses GLM-OCR via Ollama to extract structured Markdown from uploaded images and PDFs."""-import streamlit as st-import os--# Only importing local mode now-from ocr_local import check_ollama_status, extract_markdown_local_stream, warmup_local_model--# Design System Injection-_here = os.path.dirname(os.path.abspath(__file__))-_css_path = os.path.join(_here, "style.css")-if os.path.exists(_css_path):- with open(_css_path) as f:- st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)--def _looks_like_html_table(text: str) -> bool:- """Returns True if the text appears to contain an HTML table."""- lowered = text.lower()- return "<table" in lowered and ("<tr" in lowered or "<td" in lowered)--st.set_page_config(- page_title="GLM-OCR Pro",- page_icon="π§Ύ",- layout="wide",-)--# Header Section-st.title("GLM-OCR Pro")-st.markdown("##### Modern Intelligence for Structured Document Extraction")-st.divider()--if "ocr_output" not in st.session_state:- st.session_state["ocr_output"] = ""--# Layout-col1, col2 = st.columns([1, 1.2], gap="large")--with col1:- with st.container(border=True):- st.subheader("βοΈ Settings")-- @st.cache_data(ttl=30)- def _cached_ollama_status():- return check_ollama_status()- ok, status = _cached_ollama_status()- status_color = "green" if ok else "red"- st.markdown(f"**Ollama Status:** <span style='color:{status_color}'>{'β' if ok else 'β'} {status}</span>", unsafe_allow_html=True)-- if st.button("Warm Up Model", use_container_width=True, type="primary"):- with st.spinner("Loading GLM-OCR weights..."):- result = warmup_local_model()- if result.lower().startswith("warm-up completed"):- st.toast("Model warmed up on GPU!")- else:- st.error(result)-- st.divider()-- uploaded_file = st.file_uploader(- "Drop your document here",- type=["png", "jpg", "jpeg", "pdf"],- help="Supported: PNG, JPG, JPEG, PDF",- )-- with st.expander("Advanced Tuning", expanded=True):- speed_profile = st.selectbox(- "Performance Profile",- ["Balanced", "Fast", "Ultra Fast"],- index=2,- help="Profiles adjust resolution and grayscale for optimal VRAM usage.",- )-- if speed_profile == "Balanced":- default_side, default_render, default_gray = 1300, 1.8, False- elif speed_profile == "Fast":- default_side, default_render, default_gray = 1000, 1.5, True- else: # Ultra Fast- default_side, default_render, default_gray = 800, 1.2, True-- max_pdf_pages = st.slider("Max PDF Pages", 1, 20, 3)- use_grayscale = st.checkbox("Enable Grayscale (Recommended)", value=default_gray)- max_side = st.number_input("Max Side (px)", 400, 2400, default_side, step=100)- pdf_render_scale = st.number_input("PDF Rendering Scale", 1.0, 3.0, float(default_render), step=0.1)- num_predict = st.number_input("Max Output Tokens", 256, 8192, 2048, step=256)--- if st.button("π Extract Knowledge", type="primary", use_container_width=True):- if uploaded_file is None:- st.error("Please provide an image or PDF to start.")- else:- file_bytes = uploaded_file.getvalue()- mime_type = uploaded_file.type or "application/octet-stream"-- st.session_state["ocr_output"] = ""- # Placeholder for streaming output- output_placeholder = st.empty()- full_text = ""-- try:- for chunk in extract_markdown_local_stream(- file_bytes=file_bytes,- mime_type=mime_type,- max_pdf_pages=max_pdf_pages,- optimize_images=True,- max_side=max_side,- grayscale=use_grayscale,- pdf_render_scale=pdf_render_scale,- num_predict=int(num_predict),- ):- full_text += chunk- # Prettify rendering during stream- output_placeholder.markdown(full_text)-- st.session_state["ocr_output"] = full_text- st.balloons()- except Exception as exc:- st.error(f"Extraction Pipeline Error: {exc}")--with col2:- if st.session_state["ocr_output"]:- with st.container(border=True):- st.subheader("π§Ύ Extracted Results")-- # Action Row- btn_col1, btn_col2 = st.columns(2)- with btn_col1:- st.download_button(- label="πΎ Download .md",- data=st.session_state["ocr_output"],- file_name="extraction.md",- mime="text/markdown",- use_container_width=True- )- with btn_col2:- # Built-in Copy strategy via st.code- st.info("π‘ Copy button is built into the viewer below.")-- st.divider()-- # The Viewer- if _looks_like_html_table(st.session_state["ocr_output"]):- st.html(st.session_state["ocr_output"])- else:- st.markdown(st.session_state["ocr_output"])-- st.divider()- st.caption("Raw Markdown Source (Safe Copying)")- st.code(st.session_state["ocr_output"], language="markdown")- else:- st.info("Upload a document and initiate extraction to see structured data here.")diff --git a/OCR/glm_ocr_pro/assets/demo.gif b/OCR/glm_ocr_pro/assets/demo.gifdeleted file mode 100644index 4df9c86..0000000Binary files a/OCR/glm_ocr_pro/assets/demo.gif and /dev/null differdiff --git a/OCR/glm_ocr_pro/ocr_local.py b/OCR/glm_ocr_pro/ocr_local.pydeleted file mode 100644index ef9479b..0000000--- a/OCR/glm_ocr_pro/ocr_local.py+++ /dev/null@@ -1,151 +0,0 @@-import json-from io import BytesIO-import urllib.request-from typing import Generator--import pypdfium2 as pdfium-from PIL import Image--from utils import image_bytes_to_base64---OLLAMA_BASE_URL = "http://localhost:11434"---def check_ollama_status() -> tuple[bool, str]:- """Probes the Ollama API to check whether it is reachable and returns a status message."""- try:- req = urllib.request.Request(f"{OLLAMA_BASE_URL}/api/tags", method="GET")- with urllib.request.urlopen(req, timeout=5) as resp:- if resp.status == 200:- return True, "Ollama is running."- return False, "Ollama is not responding as expected."- except Exception as exc:- return False, f"Ollama not reachable: {exc}"---def _iter_pdf_image_bytes(pdf_bytes: bytes, max_pages: int, render_scale: float = 2.0) -> Generator[bytes, None, None]:- """Renders each page of a PDF to a PNG byte string, up to max_pages."""- doc = pdfium.PdfDocument(pdf_bytes)- page_count = min(len(doc), max_pages)- for i in range(page_count):- page = doc[i]- bitmap = page.render(scale=render_scale)- pil_image = bitmap.to_pil()- if pil_image.mode not in ("RGB", "L"):- pil_image = pil_image.convert("RGB")- buf = BytesIO()- pil_image.save(buf, format="PNG")- yield buf.getvalue()---def _optimize_image_bytes(image_bytes: bytes, max_side: int = 1400, quality: int = 75, grayscale: bool = False) -> bytes:- """Optimize image for local LLM consumption."""- image = Image.open(BytesIO(image_bytes))-- # Convert to RGB if needed, or Grayscale (L) for speed/memory savings- if grayscale:- image = image.convert("L")- elif image.mode not in ("RGB", "L"):- image = image.convert("RGB")-- w, h = image.size- longest = max(w, h)- if longest > max_side:- scale = max_side / float(longest)- image = image.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.Resampling.LANCZOS)-- buf = BytesIO()- # JPEG format for smaller size, or PNG if quality is paramount- image.save(buf, format="JPEG", quality=quality, optimize=True)- return buf.getvalue()---def warmup_local_model(timeout_seconds: int = 120) -> str:- """Sends a no-op prompt to Ollama to pre-load the GLM-OCR model weights into GPU memory."""- payload = {"model": "glm-ocr", "prompt": "ready", "stream": False, "keep_alive": "10m"}- req = urllib.request.Request(- f"{OLLAMA_BASE_URL}/api/generate",- method="POST",- headers={"Content-Type": "application/json"},- data=json.dumps(payload).encode("utf-8"),- )- try:- with urllib.request.urlopen(req, timeout=timeout_seconds) as resp:- _ = resp.read()- return "Warm-up completed. Model is loaded."- except Exception as exc:- return f"Warm-up failed: {exc}"---def _run_single_image_local_stream(image_bytes: bytes, timeout_seconds: int, num_predict: int = 2048) -> Generator[str, None, None]:- """Calls Ollama chat endpoint with streaming enabled."""- prompt = (- "Extract all readable text from this image and return structured Markdown. "- "Maintain layout accuracy: preserve headings, lists, tables, and formulas. "- "Do not apologize or explain. Just return the extraction."- )- payload = {- "model": "glm-ocr",- "prompt": prompt,- "images": [image_bytes_to_base64(image_bytes)],- "stream": True,- "keep_alive": "10m",- "options": {- "temperature": 0.0,- "num_predict": num_predict,- },- }-- req = urllib.request.Request(- f"{OLLAMA_BASE_URL}/api/generate",- method="POST",- headers={"Content-Type": "application/json"},- data=json.dumps(payload).encode("utf-8"),- )-- try:- # We manually iterate over response lines for streaming- with urllib.request.urlopen(req, timeout=timeout_seconds) as resp:- for line in resp:- if not line:- continue- try:- chunk = json.loads(line.decode("utf-8"))- content = chunk.get("response", "")- if content:- yield content- if chunk.get("done"):- break- except json.JSONDecodeError:- continue- except Exception as exc:- raise RuntimeError(f"Ollama request failed: {exc}") from exc---def extract_markdown_local_stream(- file_bytes: bytes,- mime_type: str,- max_pdf_pages: int = 5,- timeout_seconds: int = 600,- optimize_images: bool = True,- max_side: int = 1400,- grayscale: bool = False,- pdf_render_scale: float = 2.0,- num_predict: int = 2048,-) -> Generator[str, None, None]:- """Main entry point for local extraction, yielding chunks of text."""- if mime_type == "application/pdf":- for idx, page_bytes in enumerate(- _iter_pdf_image_bytes(file_bytes, max_pages=max_pdf_pages, render_scale=pdf_render_scale),- start=1,- ):- yield f"## Page {idx}\n\n"- if optimize_images:- page_bytes = _optimize_image_bytes(page_bytes, max_side=max_side, grayscale=grayscale)- yield from _run_single_image_local_stream(page_bytes, timeout_seconds=timeout_seconds, num_predict=num_predict)- yield "\n\n---\n\n"- else:- if optimize_images:- file_bytes = _optimize_image_bytes(file_bytes, max_side=max_side, grayscale=grayscale)- yield from _run_single_image_local_stream(file_bytes, timeout_seconds=timeout_seconds, num_predict=num_predict)diff --git a/OCR/glm_ocr_pro/requirements.txt b/OCR/glm_ocr_pro/requirements.txtdeleted file mode 100644index 215dbdd..0000000--- a/OCR/glm_ocr_pro/requirements.txt+++ /dev/null@@ -1,3 +0,0 @@-streamlit>=1.33.0-pypdfium2>=4.30.0-pillow>=10.0.0\ No newline at end of filediff --git a/OCR/glm_ocr_pro/style.css b/OCR/glm_ocr_pro/style.cssdeleted file mode 100644index 5583922..0000000--- a/OCR/glm_ocr_pro/style.css+++ /dev/null@@ -1,81 +0,0 @@-/*- GLM-OCR Pro - Premium Design System- Indigo / Slate / Neon Accents-*/--/* Main Sidebar Styling */-[data-testid="stSidebar"] {- background-color: #0c0e14;- border-right: 1px solid rgba(255, 255, 255, 0.1);-}--/* Header Text */-h1 {- font-weight: 800 !important;- background: linear-gradient(90deg, #6366f1 0%, #a855f7 100%);- -webkit-background-clip: text;- background-clip: text;- -webkit-text-fill-color: transparent;- letter-spacing: -0.02em;-}--h2, h3 {- font-weight: 700 !important;- letter-spacing: -0.01em;-}--/* Custom Card Wrapper (used with st.markdown) */-.st-emotion-cache-1kyx7g3 {- background: rgba(255, 255, 255, 0.03);- border: 1px solid rgba(255, 255, 255, 0.1);- border-radius: 16px;- padding: 24px;- box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);- backdrop-filter: blur(5px);-}--/* Button Styling Overrides */-.stButton > button {- border-radius: 12px !important;- font-weight: 600 !important;- transition: all 0.2s ease !important;- text-transform: uppercase;- letter-spacing: 0.05em;- font-size: 0.75rem !important;-}--.stButton > button:hover {- transform: translateY(-2px);- box-shadow: 0 10px 15px -3px rgba(99, 102, 241, 0.3);- border-color: #6366f1 !important;-}--/* Primary Button Accent */-div.stButton > button:first-child[kind="primary"] {- background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%) !important;- border: none !important;-}--/* Code area custom design */-.stCode {- border-radius: 12px !important;- border: 1px solid rgba(255, 255, 255, 0.05) !important;-}--/* Spinner & Status colors */-.st-emotion-cache-16idsys p {- color: #a5b4fc !important;-}--/* Info/Success/Warning bubbles */-.stAlert {- border-radius: 12px !important;- border: none !important;-}--/* Divider colors */-hr {- margin: 2em 0 !important;- border: 0;- border-top: 1px solid rgba(255, 255, 255, 0.1) !important;-}diff --git a/OCR/glm_ocr_pro/utils.py b/OCR/glm_ocr_pro/utils.pydeleted file mode 100644index c5698d9..0000000--- a/OCR/glm_ocr_pro/utils.py+++ /dev/null@@ -1,6 +0,0 @@-import base64---def image_bytes_to_base64(file_bytes: bytes) -> str:- """Encodes image bytes to base64 string for Ollama consumption."""- return base64.b64encode(file_bytes).decode("utf-8")diff --git a/README.md b/README.mdindex feb61b2..b0dc850 100644--- a/README.md+++ b/README.md@@ -72,6 +72,8 @@ Intelligent ai agents for various automation tasks.- [**Personal Finance Agent**](./ai_agents/personal_finance_agent) - Upload a bank statement CSV, auto-categorize transactions, and ask natural language questions about your spending. Powered by a LangChain tool-calling agent backed by Orq.ai with SQLite persistence.- [**Offline Medical Agent**](./ai_agents/offline_medical_agent) - Fully offline agentic RAG system for clinical protocol lookup at remote clinics and field hospitals.- [**Customer Query Routing and Resolution Agent**](./ai_agents/customer_query_routing_agent) - Routes incoming support queries to the right department and generates grounded responses using [Actian VectorAI DB](https://www.actian.com/databases/vectorai-db/) as a local persistent memory and retrieval layer.+- [**Email Auto Responder**](./ai_agents/email_auto_responder). Reads unread Gmail messages over IMAP, classifies intent with CrewAI agents on GLM-5.1, and drafts professional replies in a Streamlit dashboard.+- [**LLM Agri Bot**](./ai_agents/llm_agri_bot). Farming assistant that answers questions on crop health, weather, pests, and planting seasons using a LangChain tool-calling agent powered by Mistral.### πΈ OCR@@ -118,6 +120,12 @@ Retrieval-Augmented Generation systems for knowledge-enhanced AI applications.- [**RAG Agent with Database Routing**](./rag_apps/rag_agent_with_database_routing) β Routes queries across three specialized Qdrant databases (products, support, financial) using an Agno router agent. Falls back to a LangGraph ReAct web search agent when no relevant documents are found.- [**Reasoning RAG**](./rag_apps/reasoning_rag) - Ask questions against any web source and get cited answers with a live, step-by-step reasoning trace via Gradio.+### ποΈ Fine-Tuning++Projects for training and fine-tuning models on specialized tasks.++- [**Text-to-SQL Inventory Specialist**](./fine_tuning/text_to_sql_inventory). Natural language interface for retail inventory databases using a fine-tuned Qwen3.5-2B model. Ask questions in plain English and get SQL-backed answers via Gradio.+---## π€ Contributing