OpenWebUI AI skills


make the pipeline self-contained so it can automatically create the Azure Cognitive Search index if it doesn’t already exist.

This way, you can drop the script into a fresh Azure environment, run it, and it will:

  1. Create the index schema in Azure Search.
  2. OCR and process documents.
  3. Upload to Azure Blob Storage.
  4. Index into Azure Cognitive Search.

📜 Updated Python Tool: ocr_processor_with_azure_search_autocreate.py

PythonCopy codeimport os
import sys
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
import fitz  # PyMuPDF
from azure.storage.blob import BlobServiceClient
import json
import csv
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests

# ---------------- OCR Functions ---------------- #

def ocr_image_to_text(image_path, lang="eng"):
    image = Image.open(image_path)
    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)
    text = " ".join([t for t in data["text"] if t.strip()])
    confidences = [int(c) for c in data["conf"] if c.isdigit()]
    confidence = sum(confidences) / max(len(confidences), 1)
    return text, confidence

def ocr_pdf_to_text(pdf_path, lang="eng"):
    pages = convert_from_path(pdf_path)
    text = ""
    confidences = []
    for page in pages:
        data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)
        text += " ".join([t for t in data["text"] if t.strip()]) + "\n"
        page_conf = [int(c) for c in data["conf"] if c.isdigit()]
        confidences.extend(page_conf)
    confidence = sum(confidences) / max(len(confidences), 1)
    return text, confidence

def save_as_txt(text, output_path):
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(text)

def save_as_searchable_pdf(original_path, text, output_path):
    if original_path.lower().endswith(".pdf"):
        pdf_doc = fitz.open(original_path)
    else:
        img = Image.open(original_path)
        temp_pdf_path = output_path.replace(".pdf", "_temp.pdf")
        img.save(temp_pdf_path, "PDF", resolution=300.0)
        pdf_doc = fitz.open(temp_pdf_path)

    for page_num, page in enumerate(pdf_doc):
        page.insert_text((50, 50), text, fontsize=8, overlay=False)

    pdf_doc.save(output_path)
    pdf_doc.close()

# ---------------- Azure Functions ---------------- #

def upload_to_azure(file_path, connection_string, container_name):
    blob_service_client = BlobServiceClient.from_connection_string(connection_string)
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))
    with open(file_path, "rb") as data:
        blob_client.upload_blob(data, overwrite=True)
    return blob_client.url

def create_azure_search_index(service_name, index_name, api_key):
    """
    Creates an Azure Cognitive Search index if it doesn't exist.
    """
    url = f"https://{service_name}.search.windows.net/indexes/{index_name}?api-version=2021-04-30-Preview"
    headers = {
        "Content-Type": "application/json",
        "api-key": api_key
    }
    schema = {
        "name": index_name,
        "fields": [
            {"name": "id", "type": "Edm.String", "key": True, "searchable": False},
            {"name": "file_name", "type": "Edm.String", "searchable": True},
            {"name": "source_type", "type": "Edm.String", "searchable": True},
            {"name": "confidence_score", "type": "Edm.Double", "searchable": False},
            {"name": "ocr_text", "type": "Edm.String", "searchable": True, "analyzer": "standard.lucene"},
            {"name": "blob_url", "type": "Edm.String", "searchable": False}
        ]
    }
    # Check if index exists
    check_url = f"https://{service_name}.search.windows.net/indexes/{index_name}?api-version=2021-04-30-Preview"
    check_resp = requests.get(check_url, headers=headers)
    if check_resp.status_code == 200:
        print(f"✅
with ThreadPoolExecutor(max_workers=8) as executor:
    future_to_file = {
        executor.submit(
            process_file,
            file_path,
            output_format,
            lang,
            output_dir,
            connection_string,
            container_name,
            search_config
        ): file_path
        for file_path in files_to_process
    }
    for future in as_completed(future_to_file):
        try:
            result = future.result()
            results.append(result)
        except Exception as e:
            results.append({
                "document_id": os.path.basename(future_to_file[future]),
                "error": str(e)
            })

# Write CSV report
write_csv_report(results, csv_report_path)

# Output JSON for OpenWebUI or CLI
print(json.dumps(results, indent=2))

if name == “main“:
if len(sys.argv) < 8: print(“Usage: python ocr_processor_with_azure_search_autocreate.py [ ]”)
sys.exit(1)

input_dir = sys.argv[1]
output_dir = sys.argv[2]
output_format = sys.argv[3]
lang = sys.argv[4]
azure_connection_string = sys.argv[5]
azure_container_name = sys.argv[6]
csv_report_path = sys.argv[7]

search_config = None
if len(sys.argv) == 11:
    search_config = {
        "service_name": sys.argv[8],
        "index_name": sys.argv[9],
        "api_key": sys.argv[10]
    }

main(input_dir, output_dir, output_format, lang, azure_connection_string, azure_container_name, csv_report_path, search_config)

🚀 How This Final Version Works

  1. OCR Processing
    • Handles both images and scanned PDFs.
    • Calculates confidence scores for quality control.
  2. Output Creation
    • Saves either .txt or searchable PDF.
  3. Azure Blob Upload
    • Stores processed files in your Azure Blob container.
  4. Azure Search Auto-Index Creation
    • Checks if the index exists.
    • Creates it automatically with the correct schema if missing.
  5. Azure Search Indexing
    • Pushes OCR text + metadata for instant search.
  6. CSV Reporting
    • Generates a CSV summary for auditing.
  7. Multi-threaded Processing
    • Uses ThreadPoolExecutor for parallel OCR.

💡 Example Usage

Without Azure Search

BashCopy codepython ocr_processor_with_azure_search_autocreate.py \
  "/data/scanned_docs" \
  "/data/processed_docs" \
  "pdf" \
  "eng" \
  "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net" \
  "processed-docs" \
  "/data/ocr_report.csv"

With Azure Search Auto-Index

BashCopy codepython ocr_processor_with_azure_search_autocreate.py \
  "/data/scanned_docs" \
  "/data/processed_docs" \
  "pdf" \
  "eng" \
  "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net" \
  "processed-docs" \
  "/data/ocr_report.csv" \
  "mysearchservice" \
  "documents-index" \
  "MY_AZURE_SEARCH_API_KEY"

📊 Example Search Result

Once indexed, you can query Azure Search like:

BashCopy codecurl -X GET \
  "https://mysearchservice.search.windows.net/indexes/documents-index/docs?api-version=2021-04-30-Preview&search=invoice" \
  -H "api-key: MY_AZURE_SEARCH_API_KEY"

Response:

JsonCopy code{
  "value": [
    {
      "id": "invoice1.pdf",
      "file_name": "invoice1.pdf",
      "source_type": "scanned_pdf",
      "confidence_score": 92.5,
      "ocr_text": "Invoice #12345 ...",
  "blob_url": "https://youraccount.blob.core.windows.net/processed-docs/invoice1_searchable.pdf"
},
{
  "id": "receipt2.jpg",
  "file_name": "receipt2.jpg",
  "source_type": "image",
  "confidence_score": 88.3,
  "ocr_text": "Receipt for purchase ...",
  "blob_url": "https://youraccount.blob.core.windows.net/processed-docs/receipt2_searchable.pdf"
}

]
}

🔍 How to Use This Search Data

Once your documents are indexed in Azure Cognitive Search, you can:

  1. Search by keywords
    • Example: search=invoice returns all documents containing the word “invoice”.
  2. Filter by metadata
    • Example: search=*&$filter=confidence_score gt 90 returns only high-quality OCR results.
  3. Integrate into a Web UI
    • You can build a search interface using Azure Search SDKs (Python, JavaScript, C#).
    • Display results with clickable links to the blob_url for direct download/view.
  4. Automate review workflows
    • Use confidence scores to flag low-quality OCR results for manual correction.

🌟 Benefits of Auto-Index Creation

  • No manual setup — the script creates the Azure Search index schema automatically.
  • Consistent structure — all documents have the same searchable fields.
  • Scalable — works for thousands of files without extra configuration.
  • Cloud-native — integrates seamlessly with Azure Blob and Azure Search.

💡 Pro Tip: Combine with OpenWebUI

If you integrate this script into OpenWebUI as a tool:

  • You can trigger OCR + indexing directly from the chat interface.
  • You can even add a /search skill that queries Azure Search and returns results in chat.

🚀 Next Step

If you want, I can now add a feature where the script:

  • Automatically generates a thumbnail preview for each document.


NEXT OPTION: AZURE COGNITIVE SEARCH INTEGRATION _ OCR, BLOB UPLOAD, INDEX IN SEARCH


 extend your OCR + Azure Blob pipeline so that after OCR processing, the extracted text is automatically indexed into Azure Cognitive Search.

This will give you a searchable document repository where you can query across all processed files instantly — perfect for enterprise knowledge discovery.

🔹 Updated Workflow

  1. OCR Processing → Extract text from images/scanned PDFs.
  2. Searchable PDF/TXT Creation → Save locally.
  3. Azure Blob Upload → Store processed files in the cloud.
  4. Azure Cognitive Search Indexing → Push extracted text + metadata into a search index.
  5. Instant Search → Use Azure Search REST API or UI to query across all documents.

📜 Updated Python Tool: ocr_processor_with_azure_search.py


PythonCopy codeimport os
import sys
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
import fitz # PyMuPDF
from azure.storage.blob import BlobServiceClient
import json
import csv
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests

# ---------------- OCR Functions ---------------- #

def ocr_image_to_text(image_path, lang="eng"):
image = Image.open(image_path)
data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)
text = " ".join([t for t in data["text"] if t.strip()])
confidences = [int(c) for c in data["conf"] if c.isdigit()]
confidence = sum(confidences) / max(len(confidences), 1)
return text, confidence

def ocr_pdf_to_text(pdf_path, lang="eng"):
pages = convert_from_path(pdf_path)
text = ""
confidences = []
for page in pages:
data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)
text += " ".join([t for t in data["text"] if t.strip()]) + "\n"
page_conf = [int(c) for c in data["conf"] if c.isdigit()]
confidences.extend(page_conf)
confidence = sum(confidences) / max(len(confidences), 1)
return text, confidence

def save_as_txt(text, output_path):
with open(output_path, "w", encoding="utf-8") as f:
f.write(text)

def save_as_searchable_pdf(original_path, text, output_path):
if original_path.lower().endswith(".pdf"):
pdf_doc = fitz.open(original_path)
else:
img = Image.open(original_path)
temp_pdf_path = output_path.replace(".pdf", "_temp.pdf")
img.save(temp_pdf_path, "PDF", resolution=300.0)
pdf_doc = fitz.open(temp_pdf_path)

for page_num, page in enumerate(pdf_doc):
page.insert_text((50, 50), text, fontsize=8, overlay=False)

pdf_doc.save(output_path)
pdf_doc.close()

# ---------------- Azure Functions ---------------- #

def upload_to_azure(file_path, connection_string, container_name):
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))
with open(file_path, "rb") as data:
blob_client.upload_blob(data, overwrite=True)
return blob_client.url

def index_to_azure_search(search_service_name, index_name, api_key, document):
"""
Push a document into Azure Cognitive Search.
"""
url = f"https://{search_service_name}.search.windows.net/indexes/{index_name}/docs/index?api-version=2021-04-30-Preview"
headers = {
"Content-Type": "application/json",
"api-key": api_key
}
payload = {
"value": [document]
}
response = requests.post(url, headers=headers, json=payload)
if response.status_code != 200:
raise Exception(f"Azure Search indexing failed: {response.text}")
return response.json()

# ---------------- Processing ---------------- #

def process_file(file_path, output_format, lang, output_dir, connection_string, container_name, search_config):
os.makedirs(output_dir, exist_ok=True)
filename = os.path.basename(file_path)
base_name, _ = os.path.splitext(filename)

if file_path.lower().endswith((".jpg", ".jpeg", ".png", ".tiff", ".bmp")):
text, confidence = ocr_image_to_text(file_path, lang)
elif file_path.lower().endswith(".pdf"):
text
    text, confidence = ocr_pdf_to_text(file_path, lang)
else:
    return {"document_id": filename, "error": "Unsupported file type"}

# Save output file
if output_format == "txt":
    output_file = os.path.join(output_dir, f"{base_name}.txt")
    save_as_txt(text, output_file)
else:
    output_file = os.path.join(output_dir, f"{base_name}_searchable.pdf")
    save_as_searchable_pdf(file_path, text, output_file)

# Upload to Azure Blob
azure_url = upload_to_azure(output_file, connection_string, container_name)

# Prepare document for Azure Cognitive Search
if search_config:
    search_doc = {
        "id": filename,
        "file_name": filename,
        "source_type": "image" if not file_path.lower().endswith(".pdf") else "scanned_pdf",
        "confidence_score": round(confidence, 2),
        "ocr_text": text,
        "blob_url": azure_url
    }
    index_to_azure_search(
        search_service_name=search_config["service_name"],
        index_name=search_config["index_name"],
        api_key=search_config["api_key"],
        document=search_doc
    )

return {
    "document_id": filename,
    "source_type": "image" if not file_path.lower().endswith(".pdf") else "scanned_pdf",
    "ocr_text": text,
    "confidence_score": round(confidence, 2),
    "output_file": output_file,
    "azure_blob_url": azure_url
}

def write_csv_report(results, csv_path):
with open(csv_path, “w”, newline=””, encoding=”utf-8″) as csvfile:
fieldnames = [“document_id”, “source_type”, “confidence_score”, “output_file”, “azure_blob_url”, “error”]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for result in results:
writer.writerow({
“document_id”: result.get(“document_id”),
“source_type”: result.get(“source_type”),
“confidence_score”: result.get(“confidence_score”),
“output_file”: result.get(“output_file”),
“azure_blob_url”: result.get(“azure_blob_url”),
“error”: result.get(“error”)
})

def main(input_dir, output_dir, output_format, lang, connection_string, container_name, csv_report_path, search_config=None):
results = []
files_to_process = [os.path.join(input_dir, f) for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]

with ThreadPoolExecutor(max_workers=8) as executor:
    future_to_file = {
        executor.submit(process_file, file_path, output_format, lang, output_dir, connection_string, container_name, search_config): file_path
        for file_path in files_to_process
    }
    for future in as_completed(future_to_file):
        try:
            result = future.result()
            results.append(result)
        except Exception as e:
            results.append({
                "document_id": os.path.basename(future_to_file[future]),
                "error": str(e)
            })

write_csv_report(results, csv_report_path)
print(json.dumps(results, indent=2))

if name == “main“:
if len(sys.argv) < 8: print(“Usage: python ocr_processor_with_azure_search.py [ ]”)
sys.exit(1)

input_dir = sys.argv[1]
output_dir = sys.argv[2]
output_format = sys.argv[3]
lang = sys.argv[4]
azure_connection_string = sys.argv[5]
azure_container_name = sys.argv[6]
csv_report_path = sys.argv[7]

search_config = None
if len(sys.argv) == 11:
    search_config = {
        "service_name": sys.argv[8],
        "index_name": sys.argv[9],
        "api_key": sys.argv[10]
    }

main(input_dir, output_dir, output_format, lang, azure_connection_string, azure_container_name, csv_report_path, search_config)

  let’s finish the explanation so you have a clear picture of how this new Azure Cognitive Search integration works and how to deploy it effectively.

🚀 How This Works (Step-by-Step)

1. OCR Processing

  • The script reads each file from the input_dir.
  • If it’s an image (.jpg, .png, .tiff, etc.), it runs ocr_image_to_text.
  • If it’s a scanned PDF, it runs ocr_pdf_to_text (converts each page to an image first).
  • It calculates a confidence score based on OCR word recognition quality.

2. Output File Creation

  • Depending on output_format:
    • "txt" → Saves extracted text to a .txt file.
    • "pdf" → Creates a searchable PDF by embedding OCR text into the original file.
  • Output files are stored in output_dir.

3. Azure Blob Upload

  • The processed file is uploaded to Azure Blob Storage using upload_to_azure.
  • The script returns a public blob URL (or SAS URL if you configure it that way).

4. Azure Cognitive Search Indexing

  • If search_config is provided, the script pushes metadata + OCR text into Azure Cognitive Search:
    • id → Document ID (filename)
    • file_name → Original filename
    • source_type → "image" or "scanned_pdf"
    • confidence_score → OCR quality score
    • ocr_text → Full extracted text
    • blob_url → Link to the processed file in Azure Blob Storage
  • This allows instant search across all documents via Azure Search API or portal.

5. CSV Summary Report

  • The script writes a CSV file (csv_report_path) containing:
    • Document ID
    • Source type
    • Confidence score
    • Output file path
    • Azure Blob URL
    • Any errors encountered
  • This is useful for auditing and quality control.

6. Multi-threaded Processing

  • Uses ThreadPoolExecutor with max_workers=8 for parallel OCR.
  • This speeds up processing significantly for large batches (e.g., thousands of files).

💡 Example Usage

Without Azure Search

BashCopy codepython ocr_processor_with_azure_search.py \
  "/data/scanned_docs" \
  "/data/processed_docs" \
  "pdf" \
  "eng" \
  "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net" \
  "processed-docs" \
  "/data/ocr_report.csv"

With Azure Search Integration

BashCopy codepython ocr_processor_with_azure_search.py \
  "/data/scanned_docs" \
  "/data/processed_docs" \
  "pdf" \
  "eng" \
  "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net" \
  "processed-docs" \
  "/data/ocr_report.csv" \
  "mysearchservice" \
  "documents-index" \
  "MY_AZURE_SEARCH_API_KEY"

📊 Example Azure Search Document

After indexing, a document in Azure Search might look like:

JsonCopy code{
  "id": "invoice1.pdf",
  "file_name": "invoice1.pdf",
  "source_type": "scanned_pdf",
  "confidence_score": 92.5,
  "ocr_text": "Invoice #12345 ...",
  "blob_url": "https://youraccount.blob.core.windows.net/processed-docs/invoice1_searchable.pdf"
}

🌟 Benefits

  • Instant Search: Query across all OCR-processed documents in seconds.
  • Cloud Storage: Files are safely stored in Azure Blob.
  • Audit Trail: CSV report ensures transparency and quality control.
  • Scalable: Multi-threaded processing handles thousands of files efficiently.
  • Flexible: Works with or without Azure Cognitive Search.

If you want, I can now add an automatic Azure Search index creation step so the script can set up the index schema before uploading documents — meaning you won’t have to manually configure Azure Search beforehand.


Next Option: make this enterprise-grade by adding:

  1. Multi-threaded OCR processing for speed (using concurrent.futures).
  2. CSV summary report for quick review of all processed files.

This will allow you to process thousands of documents much faster while keeping a clean audit trail.

📜 Enhanced Python Tool: ocr_processor_with_azure.py (Multi-thread + CSV)

import os
import sys
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
import fitz  # PyMuPDF
from azure.storage.blob import BlobServiceClient
import json
import csv
from concurrent.futures import ThreadPoolExecutor, as_completed

def ocr_image_to_text(image_path, lang="eng"):
    """
    Run OCR on an image and return extracted text + confidence score.
    Confidence score is calculated as the average of all recognized word confidences.
    """
    image = Image.open(image_path)
    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)
    text = " ".join([t for t in data["text"] if t.strip()])
    confidences = [int(c) for c in data["conf"] if c.isdigit()]
    confidence = sum(confidences) / max(len(confidences), 1)
    return text, confidence

def ocr_pdf_to_text(pdf_path, lang="eng"):
    """
    Run OCR on a scanned PDF by converting each page to an image.
    Returns combined text from all pages and an overall confidence score.
    """
    pages = convert_from_path(pdf_path)
    text = ""
    confidences = []
    for page in pages:
        data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)
        text += " ".join([t for t in data["text"] if t.strip()]) + "\n"
        page_conf = [int(c) for c in data["conf"] if c.isdigit()]
        confidences.extend(page_conf)
    confidence = sum(confidences) / max(len(confidences), 1)
    return text, confidence

def save_as_txt(text, output_path):
    """Save extracted OCR text to a plain .txt file."""
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(text)

def save_as_searchable_pdf(original_path, text, output_path):
    """
    Embed OCR text into the original PDF or image to make it searchable.
    Uses PyMuPDF to insert text into each page without altering layout.
    """
    if original_path.lower().endswith(".pdf"):
        pdf_doc = fitz.open(original_path)
    else:
        img = Image.open(original_path)
        temp_pdf_path = output_path.replace(".pdf", "_temp.pdf")
        img.save(temp_pdf_path, "PDF", resolution=300.0)
        pdf_doc = fitz.open(temp_pdf_path)

    for page_num, page in enumerate(pdf_doc):
        page.insert_text((50, 50), text, fontsize=8, overlay=False)

    pdf_doc.save(output_path)
    pdf_doc.close()

def upload_to_azure(file_path, connection_string, container_name):
    """
    Upload processed file to Azure Blob Storage.
    Returns the public blob URL for reference.
    """
    blob_service_client = BlobServiceClient.from_connection_string(connection_string)
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))
    with open(file_path, "rb") as data:
        blob_client.upload_blob(data, overwrite=True)
    return blob_client.url

def process_file(file_path, output_format, lang, output_dir, connection_string, container_name):
    """
    Process a single file:
    - Run OCR
    - Save as searchable PDF or TXT
    - Upload to Azure Blob Storage
    - Return structured metadata
    """
    os.makedirs(output_dir, exist_ok=True)
    filename = os.path.basename(file_path)
    base_name, _ = os.path.splitext(filename)

    if file_path.lower().endswith((".jpg", ".jpeg", ".png", ".tiff", ".bmp")):
        text, confidence = ocr_image_to_text(file_path, lang)
    elif file_path.lower().endswith(".pdf"):
        text, confidence = ocr_pdf_to_text(file_path, lang)
    else:
        return {"document_id": filename, "error": "Unsupported file type"}

    if output_format == "txt":
        output_file = os.path.join(output_dir, f"{base_name}.txt")
        save_as_txt(text, output_file)
    else:
                output_file = os.path.join(output_dir, f"{base_name}_searchable.pdf")
        save_as_searchable_pdf(file_path, text, output_file)

    # Upload processed file to Azure Blob Storage
    azure_url = upload_to_azure(output_file, connection_string, container_name)

    return {
        "document_id": filename,
        "source_type": "image" if not file_path.lower().endswith(".pdf") else "scanned_pdf",
        "ocr_text": text,
        "confidence_score": round(confidence, 2),
        "output_file": output_file,
        "azure_blob_url": azure_url
    }

def write_csv_report(results, csv_path):
    """
    Write a CSV summary report of all processed files.
    Includes document ID, source type, confidence score, output file path, and Azure URL.
    """
    with open(csv_path, "w", newline="", encoding="utf-8") as csvfile:
        fieldnames = ["document_id", "source_type", "confidence_score", "output_file", "azure_blob_url", "error"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for result in results:
            writer.writerow({
                "document_id": result.get("document_id"),
                "source_type": result.get("source_type"),
                "confidence_score": result.get("confidence_score"),
                "output_file": result.get("output_file"),
                "azure_blob_url": result.get("azure_blob_url"),
                "error": result.get("error")
            })

def main(input_dir, output_dir, output_format, lang, connection_string, container_name, csv_report_path):
    """
    Main processing loop:
    - Uses multi-threading for faster OCR
    - Generates JSON output for OpenWebUI
    - Writes CSV report for auditing
    """
    results = []
    files_to_process = [os.path.join(input_dir, f) for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]

    # Multi-threaded processing
    with ThreadPoolExecutor(max_workers=8) as executor:
        future_to_file = {
            executor.submit(process_file, file_path, output_format, lang, output_dir, connection_string, container_name): file_path
            for file_path in files_to_process
        }
        for future in as_completed(future_to_file):
            try:
                result = future.result()
                results.append(result)
            except Exception as e:
                results.append({
                    "document_id": os.path.basename(future_to_file[future]),
                    "error": str(e)
                })

    # Write CSV report
    write_csv_report(results, csv_report_path)

    # Output JSON for OpenWebUI
    print(json.dumps(results, indent=2))

if __name__ == "__main__":
    if len(sys.argv) < 8:
        print("Usage: python ocr_processor_with_azure.py <input_dir> <output_dir> <output_format> <lang> <azure_connection_string> <azure_container_name> <csv_report_path>")
        sys.exit(1)

    input_dir = sys.argv[1]
    output_dir = sys.argv[2]
    output_format = sys.argv[3]
    lang = sys.argv[4]
    azure_connection_string = sys.argv[5]
    azure_container_name = sys.argv[6]
    csv_report_path = sys.argv[7]

    main(input_dir, output_dir, output_format, lang, azure_connection_string, azure_container_name, csv_report_path)

Key Improvements

  1. Multi-threaded OCR
    • Uses ThreadPoolExecutor with max_workers=8 for parallel processing.
    • Greatly speeds up large batch processing (e.g., thousands of documents).
  2. CSV Summary Report
    • Includes document ID, source type, confidence score, output file path, Azure Blob URL, and any errors.
    • Useful for auditing and tracking OCR quality.
  3. Structured JSON Output
    • Ready for OpenWebUI integration.
    • Contains all metadata for each processed file.

📂 Directory Setup

Copy codeopenwebui/
  skills/
    ocr_image_to_searchable_with_azure.yaml
  tools/
    ocr_processor_with_azure.py

💡 Example Usage

BashCopy code/skill OCR Image/PDF to Searchable PDF/TXT with Azure Upload \
input_dir="/data/scanned_docs" \
output





finish the usage example and also give you a realistic workflow for running this in OpenWebUI or as a standalone batch job.

💡 Example Usage in OpenWebUI
If you’ve already created the skill YAML that calls this Python tool, you can trigger it like this:

Bash

Copy code
/skill OCR Image/PDF to Searchable PDF/TXT with Azure Upload \
input_dir="/data/scanned_docs" \
output_dir="/data/processed_docs" \
output_format="pdf" \
language="eng" \
azure_connection_string="DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net" \
azure_container_name="processed-docs" \
csv_report_path="/data/ocr_report.csv"
💡 Example Usage as a Standalone Script
If you want to run it outside OpenWebUI, just call it directly:

Bash

Copy code
python ocr_processor_with_azure.py \
"/data/scanned_docs" \
"/data/processed_docs" \
"pdf" \
"eng" \
"DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net" \
"processed-docs" \
"/data/ocr_report.csv"
📊 Example CSV Output
After processing, you’ll get a CSV file like this:

document_id source_type confidence_score output_file azure_blob_url error
invoice1.pdf scanned_pdf 92.5 /data/processed_docs/invoice1_searchable.pdf https://youraccount.blob.core.windows.net/processed-docs/invoice1_searchable.pdf
receipt2.jpg image 88.3 /data/processed_docs/receipt2_searchable.pdf https://youraccount.blob.core.windows.net/processed-docs/receipt2_searchable.pdf
badfile.txt None None None None Unsupported file type
🚀 Workflow for Enterprise-Scale Processing
Drop files into /data/scanned_docs (can be mounted from a network share or blob sync).
Run the skill in OpenWebUI or schedule the Python script via cron or Azure Functions.
OCR runs in parallel (multi-threaded) for speed.
Searchable PDFs/TXTs are saved locally and uploaded to Azure Blob Storage.
CSV report is generated for auditing and quality control.
Confidence scores help you identify low-quality OCR results for manual review.
💡 Pro Tip for Scaling
If you have thousands of files, you can increase max_workers in the script to match your CPU cores for maximum throughput.
You can also split input directories and run multiple instances in parallel for even faster processing.
For cloud-native scaling, wrap this script in an Azure Container Instance or Kubernetes Job so it can scale horizontally.




Option 2


make this OCR helper tool so your OpenWebUI skill can actually process images and scanned PDFs into searchable PDFs or .txt files automatically.

We’ll use Python + Tesseract OCR (open-source, offline) so it works without cloud dependencies, but I’ll also note where you could swap in Azure Cognitive Services OCR for enterprise-grade accuracy.

Python OCR Helper Tool – ocr_processor.py

PythonCopy codeimport os
import sys
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
from fpdf import FPDF
import fitz  # PyMuPDF for searchable PDF embedding

# Ensure Tesseract is installed and in PATH
# Windows example: pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

def ocr_image_to_text(image_path, lang="eng"):
    """Extract text from an image file using Tesseract OCR."""
    image = Image.open(image_path)
    text = pytesseract.image_to_string(image, lang=lang)
    return text

def ocr_pdf_to_text(pdf_path, lang="eng"):
    """Extract text from a scanned PDF by converting pages to images."""
    pages = convert_from_path(pdf_path)
    text = ""
    for page in pages:
        text += pytesseract.image_to_string(page, lang=lang) + "\n"
    return text

def save_as_txt(text, output_path):
    """Save extracted text to a .txt file."""
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(text)

def save_as_searchable_pdf(original_path, text, output_path):
    """Embed OCR text into original PDF or image to make it searchable."""
    if original_path.lower().endswith(".pdf"):
        # Open original PDF
        pdf_doc = fitz.open(original_path)
    else:
        # Convert image to PDF first
        img = Image.open(original_path)
        temp_pdf_path = output_path.replace(".pdf", "_temp.pdf")
        img.save(temp_pdf_path, "PDF", resolution=300.0)
        pdf_doc = fitz.open(temp_pdf_path)

    for page_num, page in enumerate(pdf_doc):
        page.insert_text((50, 50), text, fontsize=8, overlay=False)

    pdf_doc.save(output_path)
    pdf_doc.close()

def process_file(file_path, output_format="pdf", lang="eng", output_dir="output"):
    """Process a single file and return metadata."""
    os.makedirs(output_dir, exist_ok=True)
    filename = os.path.basename(file_path)
    base_name, _ = os.path.splitext(filename)

    if file_path.lower().endswith((".jpg", ".jpeg", ".png", ".tiff", ".bmp")):
        text = ocr_image_to_text(file_path, lang)
    elif file_path.lower().endswith(".pdf"):
        text = ocr_pdf_to_text(file_path, lang)
    else:
        return {"document_id": filename, "error": "Unsupported file type"}

    if output_format == "txt":
        output_file = os.path.join(output_dir, f"{base_name}.txt")
        save_as_txt(text, output_file)
    else:
        output_file = os.path.join(output_dir, f"{base_name}_searchable.pdf")
        save_as_searchable_pdf(file_path, text, output_file)

    return {
        "document_id": filename,
        "source_type": "image" if not file_path.lower().endswith(".pdf") else "scanned_pdf",
        "ocr_text": text,
        "output_file": output_file
    }

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python ocr_processor.py <file_path> [output_format] [lang]")
        sys.exit(1)

    file_path = sys.argv[1]
    output_format = sys.argv[2] if len(sys.argv) > 2 else "pdf"
    lang = sys.argv[3] if len(sys.argv) > 3 else "eng"

    result = process_file(file_path, output_format, lang)
    print(result)

🔹 How This Works

  • Image OCR: Uses pytesseract to read text from .jpg, .png, .tiff, .bmp.
  • Scanned PDF OCR: Converts each page to an image, then runs OCR.
  • TXT Output: Saves extracted text as .txt.
  • Searchable PDF Output: Embeds OCR text into the original PDF/image using PyMuPDF so it’s searchable.

an OpenWebUI skill that can:

  1. OCR extract text content from image files (e.g., .jpg, .png, .tiff).
  2. Convert the file into a searchable PDF or .txt file.
  3. Handle large volumes (like thousands of files) with accuracy and completeness.

Here’s a production-ready skill definition you can drop into OpenWebUI:

📄 Skill: ocr_image_to_searchable.yaml

YamlCopy codename: "OCR Image to Searchable PDF/TXT"
description: "Extract text from images using OCR and convert to searchable PDF or TXT."
author: "Your Name"
version: "1.0"

parameters:
  - name: output_format
    type: string
    required: true
    default: "pdf"
    description: "Output format: 'pdf' for searchable PDF or 'txt' for plain text"
  - name: language
    type: string
    required: false
    default: "eng"
    description: "OCR language code (e.g., 'eng', 'spa', 'fra')"
  - name: batch_size
    type: integer
    required: false
    default: 50
    description: "Number of files to process per batch"

system_prompt: |
  You are an OCR and document conversion assistant.
  Your task:
  - Accept image files (jpg, png, tiff, bmp) or scanned PDFs.
  - Use OCR to extract all visible text from the images.
  - Preserve layout and formatting where possible.
  - If output_format is 'pdf', embed the extracted text into the original image to create a searchable PDF.
  - If output_format is 'txt', output plain text with line breaks preserved.
  - Ensure completeness: no words or characters are skipped.
  - Ensure correctness: avoid OCR errors by cross-checking with language dictionaries.
  - Output structured JSON for each file:
    {
      "document_id": "<filename>",
      "source_type": "image|scanned_pdf",
      "ocr_text": "<extracted text>",
      "output_file": "<path to generated searchable PDF or TXT>"
    }
  - If OCR fails, log the error and skip the file.

user_prompt: |
  Process the following batch of image or scanned PDF files.
  Apply OCR extraction according to the system prompt.
  Convert each file into a {{output_format}} format.
  Return structured JSON for each processed file, including the path to the generated output file.

output_format: json

🔹 How This Skill Works

  • OCR Extraction: Uses OCR (e.g., Tesseract or Azure Cognitive Services OCR) to read text from images.
  • Searchable PDF Creation: Embeds extracted text into the original image layer so it’s searchable.
  • TXT Option: Outputs plain text for lightweight storage or further processing.
  • Batch Processing: Handles large datasets efficiently.
  • Language Support: Allows specifying OCR language for better accuracy.

💡 If you want, I can also give you a Python helper tool that this skill can call internally to:

  • Run OCR using Tesseract or Azure OCR API.
  • Automatically generate searchable PDFs or .txt files.
  • Save them to a specified output directory.


Option 3 – openwebui Skill in markdown format


OpenWebUI OCR skill in Markdown format so you can easily read, share, and adapt it.

Skill: OCR Image/PDF to Searchable PDF or TXT

YamlCopy codename: "OCR Image/PDF to Searchable PDF/TXT"
description: "Extract text from images or scanned PDFs using OCR and convert to searchable PDF or TXT."
author: "Your Name"
version: "1.0"

parameters:
  - name: output_format
    type: string
    required: true
    default: "pdf"
    description: "Output format: 'pdf' for searchable PDF or 'txt' for plain text"
  - name: language
    type: string
    required: false
    default: "eng"
    description: "OCR language code (e.g., 'eng', 'spa', 'fra')"
  - name: batch_size
    type: integer
    required: false
    default: 50
    description: "Number of files to process per batch"

system_prompt: |
  You are an OCR and document conversion assistant.
  Your task:
  - Accept image files (jpg, png, tiff, bmp) or scanned PDFs.
  - Use OCR to extract all visible text from the images.
  - Preserve layout and formatting where possible.
  - If output_format is 'pdf', embed the extracted text into the original image to create a searchable PDF.
  - If output_format is 'txt', output plain text with line breaks preserved.
  - Ensure completeness: no words or characters are skipped.
  - Ensure correctness: avoid OCR errors by cross-checking with language dictionaries.
  - Output structured JSON for each file:
    {
      "document_id": "<filename>",
      "source_type": "image|scanned_pdf",
      "ocr_text": "<extracted text>",
      "output_file": "<path to generated searchable PDF or TXT>"
    }
  - If OCR fails, log the error and skip the file.

user_prompt: |
  Process the following batch of image or scanned PDF files.
  Apply OCR extraction according to the system prompt.
  Convert each file into a {{output_format}} format.
  Return structured JSON for each processed file, including the path to the generated output file.

output_format: json

🔹 How to Use This Skill

  1. Save this YAML definition as:Copy codeskills/ocr_image_to_searchable.yaml inside your OpenWebUI skills directory.
  2. Restart OpenWebUI so it loads the new skill.
  3. Call it from the chat interface like:Copy code/skill OCR Image/PDF to Searchable PDF/TXT output_format="pdf" language="eng" batch_size=20
  4. The skill will:
    • Accept image or scanned PDF files.
    • Run OCR extraction.
    • Convert them into searchable PDFs or .txt files.
    • Return structured JSON with file paths and extracted text.


make your OpenWebUI OCR skill fully functional by integrating it with the Python OCR helper tool so it’s plug‑and‑play.

This way, when you trigger the skill in OpenWebUI, it will automatically:

  • Accept image or scanned PDF files.
  • Run OCR extraction using Tesseract (offline) or optionally Azure OCR API.
  • Convert them into searchable PDFs or .txt files.
  • Return structured JSON with extracted text and output file paths.

📄 Integrated OCR Skill in Markdown

YamlCopy codename: "OCR Image/PDF to Searchable PDF/TXT"
description: "Extract text from images or scanned PDFs using OCR and convert to searchable PDF or TXT."
author: "Your Name"
version: "1.1"

parameters:
  - name: output_format
    type: string
    required: true
    default: "pdf"
    description: "Output format: 'pdf' for searchable PDF or 'txt' for plain text"
  - name: language
    type: string
    required: false
    default: "eng"
    description: "OCR language code (e.g., 'eng', 'spa', 'fra')"
  - name: batch_size
    type: integer
    required: false
    default: 50
    description: "Number of files to process per batch"
  - name: input_dir
    type: string
    required: true
    description: "Directory containing image or scanned PDF files"
  - name: output_dir
    type: string
    required: true
    description: "Directory where processed files will be saved"

system_prompt: |
  You are an OCR and document conversion assistant.
  Your task:
  - Accept image files (jpg, png, tiff, bmp) or scanned PDFs from {{input_dir}}.
  - Use OCR to extract all visible text from the images.
  - Preserve layout and formatting where possible.
  - If output_format is 'pdf', embed the extracted text into the original image to create a searchable PDF.
  - If output_format is 'txt', output plain text with line breaks preserved.
  - Ensure completeness: no words or characters are skipped.
  - Ensure correctness: avoid OCR errors by cross-checking with language dictionaries.
  - Output structured JSON for each file:
    {
      "document_id": "<filename>",
      "source_type": "image|scanned_pdf",
      "ocr_text": "<extracted text>",
      "output_file": "<path to generated searchable PDF or TXT>"
    }
  - If OCR fails, log the error and skip the file.

user_prompt: |
  Process all files in {{input_dir}} in batches of {{batch_size}}.
  Apply OCR extraction according to the system prompt.
  Save processed files to {{output_dir}} in {{output_format}} format.
  Return structured JSON for each processed file, including the path to the generated output file.

tool:
  name: "ocr_processor"
  type: "python"
  entrypoint: "ocr_processor.py"
  args:
    - "{{input_dir}}"
    - "{{output_dir}}"
    - "{{output_format}}"
    - "{{language}}"

output_format: json

🔹 How This Works

  • Skill Parameters: You specify input/output directories, format (pdf or txt), language, and batch size.
  • System Prompt: Guides the OCR extraction process with accuracy and completeness rules.
  • User Prompt: Defines operational steps for batch processing.
  • Tool Integration: Calls ocr_processor.py (the helper tool we built earlier) to actually run OCR and generate output files.

📂 Directory Setup

Copy codeopenwebui/
  skills/
    ocr_image_to_searchable.yaml
  tools/
    ocr_processor.py

💡 Usage Example

BashCopy code/skill OCR Image/PDF to Searchable PDF/TXT \
  input_dir="/data/scanned_docs" \
  output_dir="/data/processed_docs" \
  output_format="pdf" \
  language="eng" \
  batch_size=20

✅ This setup means OpenWebUI will directly call the Python OCR tool when you run the skill — no manual steps, no separate scripts.
It will return structured JSON with:

  • Document ID
  • Source type
  • Extracted OCR text
  • Path to generated searchable PDF or .txt

If you want, I can now extend this skill so it also:

  • Uploads the processed searchable PDFs back to Azure Blob Storage automatically.
  • Logs OCR confidence scores for each document.


ENHANCEMENTS

 extend the OCR skill + tool combo so it’s production-ready:

  1. OCR extraction from images/scanned PDFs.
  2. Convert to searchable PDF or .txt.
  3. Upload processed files back to Azure Blob Storage automatically.
  4. Log OCR confidence scores for each document for quality tracking.

📄 Extended OCR Skill in Markdown

YamlCopy codename: "OCR Image/PDF to Searchable PDF/TXT with Azure Upload"
description: "Extract text from images or scanned PDFs using OCR, convert to searchable PDF/TXT, upload to Azure Blob Storage, and log OCR confidence."
author: "Your Name"
version: "1.2"

parameters:
  - name: output_format
    type: string
    required: true
    default: "pdf"
    description: "Output format: 'pdf' for searchable PDF or 'txt' for plain text"
  - name: language
    type: string
    required: false
    default: "eng"
    description: "OCR language code (e.g., 'eng', 'spa', 'fra')"
  - name: batch_size
    type: integer
    required: false
    default: 50
    description: "Number of files to process per batch"
  - name: input_dir
    type: string
    required: true
    description: "Directory containing image or scanned PDF files"
  - name: output_dir
    type: string
    required: true
    description: "Directory where processed files will be saved"
  - name: azure_connection_string
    type: string
    required: true
    description: "Azure Blob Storage connection string"
  - name: azure_container_name
    type: string
    required: true
    description: "Azure Blob Storage container name for uploads"

system_prompt: |
  You are an OCR and document conversion assistant.
  Your task:
  - Accept image files (jpg, png, tiff, bmp) or scanned PDFs from {{input_dir}}.
  - Use OCR to extract all visible text from the images.
  - Preserve layout and formatting where possible.
  - If output_format is 'pdf', embed the extracted text into the original image to create a searchable PDF.
  - If output_format is 'txt', output plain text with line breaks preserved.
  - Ensure completeness: no words or characters are skipped.
  - Ensure correctness: avoid OCR errors by cross-checking with language dictionaries.
  - Calculate OCR confidence score for each document.
  - Output structured JSON for each file:
    {
      "document_id": "<filename>",
      "source_type": "image|scanned_pdf",
      "ocr_text": "<extracted text>",
      "confidence_score": "<percentage>",
      "output_file": "<path to generated searchable PDF or TXT>",
      "azure_blob_url": "<uploaded file URL>"
    }
  - If OCR fails, log the error and skip the file.

user_prompt: |
  Process all files in {{input_dir}} in batches of {{batch_size}}.
  Apply OCR extraction according to the system prompt.
  Save processed files to {{output_dir}} in {{output_format}} format.
  Upload each processed file to Azure Blob Storage container {{azure_container_name}} using {{azure_connection_string}}.
  Return structured JSON for each processed file, including OCR confidence score and Azure Blob URL.

tool:
  name: "ocr_processor_with_azure"
  type: "python"
  entrypoint: "ocr_processor_with_azure.py"
  args:
    - "{{input_dir}}"
    - "{{output_dir}}"
    - "{{output_format}}"
    - "{{language}}"
    - "{{azure_connection_string}}"
    - "{{azure_container_name}}"

output_format: json

📜 Python Tool: ocr_processor_with_azure.py

PythonCopy codeimport os
import sys
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
import fitz # PyMuPDF
from azure.storage.blob import BlobServiceClient

def ocr_image_to_text(image_path, lang="eng"):
image = Image.open(image_path)
data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)
text = " ".join(data["text"])
confidence = sum([int(c) for c in data["conf"] if c.isdigit()]) / max(len(data["conf"]), 1)
return text, confidence

def ocr_pdf_to_text(pdf_path, lang="eng"):
pages = convert_from_path(pdf_path)
text = ""
confidences = []
for page in pages:
data = pytesseract.image_to_data

finish the Python tool so it fully supports OCR extraction, searchable PDF creation, Azure Blob upload, and confidence scoring.

📜 Completed Python Tool: ocr_processor_with_azure.py

import os
import sys
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
import fitz  # PyMuPDF
from azure.storage.blob import BlobServiceClient

def ocr_image_to_text(image_path, lang="eng"):
    """Run OCR on an image and return text + confidence score."""
    image = Image.open(image_path)
    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)
    text = " ".join([t for t in data["text"] if t.strip()])
    confidences = [int(c) for c in data["conf"] if c.isdigit()]
    confidence = sum(confidences) / max(len(confidences), 1)
    return text, confidence

def ocr_pdf_to_text(pdf_path, lang="eng"):
    """Run OCR on a scanned PDF and return text + confidence score."""
    pages = convert_from_path(pdf_path)
    text = ""
    confidences = []
    for page in pages:
        data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)
        text += " ".join([t for t in data["text"] if t.strip()]) + "\n"
        page_conf = [int(c) for c in data["conf"] if c.isdigit()]
        confidences.extend(page_conf)
    confidence = sum(confidences) / max(len(confidences), 1)
    return text, confidence

def save_as_txt(text, output_path):
    """Save extracted text to a .txt file."""
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(text)

def save_as_searchable_pdf(original_path, text, output_path):
    """Embed OCR text into original PDF/image to make it searchable."""
    if original_path.lower().endswith(".pdf"):
        pdf_doc = fitz.open(original_path)
    else:
        img = Image.open(original_path)
        temp_pdf_path = output_path.replace(".pdf", "_temp.pdf")
        img.save(temp_pdf_path, "PDF", resolution=300.0)
        pdf_doc = fitz.open(temp_pdf_path)

    for page_num, page in enumerate(pdf_doc):
        page.insert_text((50, 50), text, fontsize=8, overlay=False)

    pdf_doc.save(output_path)
    pdf_doc.close()

def upload_to_azure(file_path, connection_string, container_name):
    """Upload file to Azure Blob Storage and return blob URL."""
    blob_service_client = BlobServiceClient.from_connection_string(connection_string)
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))
    with open(file_path, "rb") as data:
        blob_client.upload_blob(data, overwrite=True)
    return blob_client.url

def process_file(file_path, output_format, lang, output_dir, connection_string, container_name):
    """Process a single file and return metadata."""
    os.makedirs(output_dir, exist_ok=True)
    filename = os.path.basename(file_path)
    base_name, _ = os.path.splitext(filename)

    if file_path.lower().endswith((".jpg", ".jpeg", ".png", ".tiff", ".bmp")):
        text, confidence = ocr_image_to_text(file_path, lang)
    elif file_path.lower().endswith(".pdf"):
        text, confidence = ocr_pdf_to_text(file_path, lang)
    else:
        return {"document_id": filename, "error": "Unsupported file type"}

    if output_format == "txt":
        output_file = os.path.join(output_dir, f"{base_name}.txt")
        save_as_txt(text, output_file)
    else:
        output_file = os.path.join(output_dir, f"{base_name}_searchable.pdf")
        save_as_searchable_pdf(file_path, text, output_file)

    azure_url = upload_to_azure(output_file, connection_string, container_name)

    return {
        "document_id": filename,
        "source_type": "image" if not file_path.lower().endswith(".pdf") else "scanned_pdf",
        "ocr_text": text,
        "confidence_score": round(confidence, 2),
        "output_file": output_file,
        "azure_blob_url": azure_url
    }

def main(input_dir, output_dir, output_format, lang, connection_string, container_name):
    results = []
    for file_name in os.listdir(input_dir):
        file_path = os.path.join(input_dir, file_name





# finish the main loop so the tool processes all files in the input directory, runs OCR, uploads results to Azure Blob Storage, and returns structured JSON for OpenWebUI.

import os
import sys
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
import fitz  # PyMuPDF
from azure.storage.blob import BlobServiceClient
import json

def ocr_image_to_text(image_path, lang="eng"):
    """Run OCR on an image and return text + confidence score."""
    image = Image.open(image_path)
    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)
    text = " ".join([t for t in data["text"] if t.strip()])
    confidences = [int(c) for c in data["conf"] if c.isdigit()]
    confidence = sum(confidences) / max(len(confidences), 1)
    return text, confidence

def ocr_pdf_to_text(pdf_path, lang="eng"):
    """Run OCR on a scanned PDF and return text + confidence score."""
    pages = convert_from_path(pdf_path)
    text = ""
    confidences = []
    for page in pages:
        data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)
        text += " ".join([t for t in data["text"] if t.strip()]) + "\n"
        page_conf = [int(c) for c in data["conf"] if c.isdigit()]
        confidences.extend(page_conf)
    confidence = sum(confidences) / max(len(confidences), 1)
    return text, confidence

def save_as_txt(text, output_path):
    """Save extracted text to a .txt file."""
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(text)

def save_as_searchable_pdf(original_path, text, output_path):
    """Embed OCR text into original PDF/image to make it searchable."""
    if original_path.lower().endswith(".pdf"):
        pdf_doc = fitz.open(original_path)
    else:
        img = Image.open(original_path)
        temp_pdf_path = output_path.replace(".pdf", "_temp.pdf")
        img.save(temp_pdf_path, "PDF", resolution=300.0)
        pdf_doc = fitz.open(temp_pdf_path)

    for page_num, page in enumerate(pdf_doc):
        page.insert_text((50, 50), text, fontsize=8, overlay=False)

    pdf_doc.save(output_path)
    pdf_doc.close()

def upload_to_azure(file_path, connection_string, container_name):
    """Upload file to Azure Blob Storage and return blob URL."""
    blob_service_client = BlobServiceClient.from_connection_string(connection_string)
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))
    with open(file_path, "rb") as data:
        blob_client.upload_blob(data, overwrite=True)
    return blob_client.url

def process_file(file_path, output_format, lang, output_dir, connection_string, container_name):
    """Process a single file and return metadata."""
    os.makedirs(output_dir, exist_ok=True)
    filename = os.path.basename(file_path)
    base_name, _ = os.path.splitext(filename)

    if file_path.lower().endswith((".jpg", ".jpeg", ".png", ".tiff", ".bmp")):
        text, confidence = ocr_image_to_text(file_path, lang)
    elif file_path.lower().endswith(".pdf"):
        text, confidence = ocr_pdf_to_text(file_path, lang)
    else:
        return {"document_id": filename, "error": "Unsupported file type"}

    if output_format == "txt":
        output_file = os.path.join(output_dir, f"{base_name}.txt")
        save_as_txt(text, output_file)
    else:
        output_file = os.path.join(output_dir, f"{base_name}_searchable.pdf")
        save_as_searchable_pdf(file_path, text, output_file)

    azure_url = upload_to_azure(output_file, connection_string, container_name)

    return {
        "document_id": filename,
        "source_type": "image" if not file_path.lower().endswith(".pdf") else "scanned_pdf",
        "ocr_text": text,
        "confidence_score": round(confidence, 2),
        "output_file": output_file,
        "azure_blob_url": azure_url
    }

def main(input_dir, output_dir, output_format, lang, connection_string, container_name):
    results = []
    for file_name in os

def main(input_dir, output_dir, output_format, lang, connection_string, container_name):
    results = []
    for file_name in os.listdir(input_dir):
        file_path = os.path.join(input_dir, file_name)
        if os.path.isfile(file_path):
            try:
                result = process_file(
                    file_path,
                    output_format,
                    lang,
                    output_dir,
                    connection_string,
                    container_name
                )
                results.append(result)
            except Exception as e:
                results.append({
                    "document_id": file_name,
                    "error": str(e)
                })
    # Output results as JSON for OpenWebUI
    print(json.dumps(results, indent=2))

if __name__ == "__main__":
    if len(sys.argv) < 7:
        print("Usage: python ocr_processor_with_azure.py <input_dir> <output_dir> <output_format> <lang> <azure_connection_string> <azure_container_name>")
        sys.exit(1)

    input_dir = sys.argv[1]
    output_dir = sys.argv[2]
    output_format = sys.argv[3]
    lang = sys.argv[4]
    azure_connection_string = sys.argv[5]
    azure_container_name = sys.argv[6]

    main(input_dir, output_dir, output_format, lang, azure_connection_string, azure_container_name)

How It Works

  1. Iterates through all files in input_dir.
  2. Runs OCR on each image or scanned PDF.
  3. Converts to searchable PDF or .txt based on output_format.
  4. Uploads processed file to Azure Blob Storage.
  5. Calculates OCR confidence score.
  6. Returns structured JSON with:
    • document_id
    • source_type
    • ocr_text
    • confidence_score
    • output_file
    • azure_blob_url
    • error (if any)

📂 Directory Setup

Copy codeopenwebui/
  skills/
    ocr_image_to_searchable_with_azure.yaml
  tools/
    ocr_processor_with_azure.py

💡 Example Usage in OpenWebUI

BashCopy code/skill OCR Image/PDF to Searchable PDF/TXT with Azure Upload \
  input_dir="/data/scanned_docs" \
  output_dir="/data/processed_docs" \
  output_format="pdf" \
  language="eng" \
  batch_size=20 \
  azure_connection_string="DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net" \
  azure_container_name="processed-docs"

✅ This now gives you a fully automated pipeline:

  • OCR extraction
  • Searchable PDF/TXT creation
  • Azure Blob upload
  • Confidence scoring
  • JSON output for OpenWebUI

If you want, I can extend this further so it also:

  • Writes a CSV summary report of all processed files.
  • Supports multi-threaded OCR for faster processing of thousands of documents.

That would make it enterprise-grade for your 2k+ document workflows.


You can extract text from images directly in Open WebUI by using vision models or configuring an external content extraction engine like Mistral OCR or Docling. [1, 2, 3]

Methods for Image OCR and Text Extraction

  • Multimodal Vision Models: Drag and drop images directly into the chat interface using a vision-capable model (such as LLaVA, GPT-4o, or Claude 3.5 Sonnet via Ollama or API endpoints) and prompt the model to transcribe or read the text.
  • Admin Document Engines: Navigate to Admin Panel > Settings > Documents to configure advanced extraction pipelines.
  • Custom Tools: Implement specialized extraction pipelines by adding custom Python scripts under Workspace > Tools in your instance. [1, 2, 3, 4, 5]

Are you trying to extract text from images inside uploaded documents/PDFs or directly from standalone image uploads in chat, and which backend model provider (Ollama, OpenAI, Mistral)

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post