
{"id":129,"date":"2026-10-07T15:44:59","date_gmt":"2026-10-07T15:44:59","guid":{"rendered":"https:\/\/roboticsmaestro.com\/ai\/?p=129"},"modified":"2026-10-07T16:53:13","modified_gmt":"2026-10-07T16:53:13","slug":"openwebui-ai-skills","status":"publish","type":"post","link":"https:\/\/roboticsmaestro.com\/ai\/blog\/2026\/10\/07\/openwebui-ai-skills\/","title":{"rendered":"OpenWebUI AI skills"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\">make the pipeline <strong>self-contained<\/strong> so it can <strong>automatically create the Azure Cognitive Search index<\/strong> if it doesn\u2019t already exist.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This way, you can drop the script into a fresh Azure environment, run it, and it will:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create the index schema in Azure Search.<\/li>\n\n\n\n<li>OCR and process documents.<\/li>\n\n\n\n<li>Upload to Azure Blob Storage.<\/li>\n\n\n\n<li>Index into Azure Cognitive Search.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4dc; Updated Python Tool: <code>ocr_processor_with_azure_search_autocreate.py<\/code><\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">PythonCopy code<code>import os\nimport sys\nimport pytesseract\nfrom pdf2image import convert_from_path\nfrom PIL import Image\nimport fitz  # PyMuPDF\nfrom azure.storage.blob import BlobServiceClient\nimport json\nimport csv\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport requests\n\n# ---------------- OCR Functions ---------------- #\n\ndef ocr_image_to_text(image_path, lang=\"eng\"):\n    image = Image.open(image_path)\n    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)\n    text = \" \".join([t for t in data[\"text\"] if t.strip()])\n    confidences = [int(c) for c in data[\"conf\"] if c.isdigit()]\n    confidence = sum(confidences) \/ max(len(confidences), 1)\n    return text, confidence\n\ndef ocr_pdf_to_text(pdf_path, lang=\"eng\"):\n    pages = convert_from_path(pdf_path)\n    text = \"\"\n    confidences = []\n    for page in pages:\n        data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)\n        text += \" \".join([t for t in data[\"text\"] if t.strip()]) + \"\\n\"\n        page_conf = [int(c) for c in data[\"conf\"] if c.isdigit()]\n        confidences.extend(page_conf)\n    confidence = sum(confidences) \/ max(len(confidences), 1)\n    return text, confidence\n\ndef save_as_txt(text, output_path):\n    with open(output_path, \"w\", encoding=\"utf-8\") as f:\n        f.write(text)\n\ndef save_as_searchable_pdf(original_path, text, output_path):\n    if original_path.lower().endswith(\".pdf\"):\n        pdf_doc = fitz.open(original_path)\n    else:\n        img = Image.open(original_path)\n        temp_pdf_path = output_path.replace(\".pdf\", \"_temp.pdf\")\n        img.save(temp_pdf_path, \"PDF\", resolution=300.0)\n        pdf_doc = fitz.open(temp_pdf_path)\n\n    for page_num, page in enumerate(pdf_doc):\n        page.insert_text((50, 50), text, fontsize=8, overlay=False)\n\n    pdf_doc.save(output_path)\n    pdf_doc.close()\n\n# ---------------- Azure Functions ---------------- #\n\ndef upload_to_azure(file_path, connection_string, container_name):\n    blob_service_client = BlobServiceClient.from_connection_string(connection_string)\n    blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))\n    with open(file_path, \"rb\") as data:\n        blob_client.upload_blob(data, overwrite=True)\n    return blob_client.url\n\ndef create_azure_search_index(service_name, index_name, api_key):\n    \"\"\"\n    Creates an Azure Cognitive Search index if it doesn't exist.\n    \"\"\"\n    url = f\"https:\/\/{service_name}.search.windows.net\/indexes\/{index_name}?api-version=2021-04-30-Preview\"\n    headers = {\n        \"Content-Type\": \"application\/json\",\n        \"api-key\": api_key\n    }\n    schema = {\n        \"name\": index_name,\n        \"fields\": [\n            {\"name\": \"id\", \"type\": \"Edm.String\", \"key\": True, \"searchable\": False},\n            {\"name\": \"file_name\", \"type\": \"Edm.String\", \"searchable\": True},\n            {\"name\": \"source_type\", \"type\": \"Edm.String\", \"searchable\": True},\n            {\"name\": \"confidence_score\", \"type\": \"Edm.Double\", \"searchable\": False},\n            {\"name\": \"ocr_text\", \"type\": \"Edm.String\", \"searchable\": True, \"analyzer\": \"standard.lucene\"},\n            {\"name\": \"blob_url\", \"type\": \"Edm.String\", \"searchable\": False}\n        ]\n    }\n    # Check if index exists\n    check_url = f\"https:\/\/{service_name}.search.windows.net\/indexes\/{index_name}?api-version=2021-04-30-Preview\"\n    check_resp = requests.get(check_url, headers=headers)\n    if check_resp.status_code == 200:\n        print(f\"&#x2705;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>with ThreadPoolExecutor(max_workers=8) as executor:\n    future_to_file = {\n        executor.submit(\n            process_file,\n            file_path,\n            output_format,\n            lang,\n            output_dir,\n            connection_string,\n            container_name,\n            search_config\n        ): file_path\n        for file_path in files_to_process\n    }\n    for future in as_completed(future_to_file):\n        try:\n            result = future.result()\n            results.append(result)\n        except Exception as e:\n            results.append({\n                \"document_id\": os.path.basename(future_to_file&#91;future]),\n                \"error\": str(e)\n            })\n\n# Write CSV report\nwrite_csv_report(results, csv_report_path)\n\n# Output JSON for OpenWebUI or CLI\nprint(json.dumps(results, indent=2))<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">if <strong>name<\/strong> == &#8220;<strong>main<\/strong>&#8220;:<br>if len(sys.argv) &lt; 8: print(&#8220;Usage: python ocr_processor_with_azure_search_autocreate.py [ ]&#8221;)<br>sys.exit(1)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>input_dir = sys.argv&#91;1]\noutput_dir = sys.argv&#91;2]\noutput_format = sys.argv&#91;3]\nlang = sys.argv&#91;4]\nazure_connection_string = sys.argv&#91;5]\nazure_container_name = sys.argv&#91;6]\ncsv_report_path = sys.argv&#91;7]\n\nsearch_config = None\nif len(sys.argv) == 11:\n    search_config = {\n        \"service_name\": sys.argv&#91;8],\n        \"index_name\": sys.argv&#91;9],\n        \"api_key\": sys.argv&#91;10]\n    }\n\nmain(input_dir, output_dir, output_format, lang, azure_connection_string, azure_container_name, csv_report_path, search_config)\n\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f680; How This Final Version Works<\/strong><\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>OCR Processing<\/strong>\n<ul class=\"wp-block-list\">\n<li>Handles both images and scanned PDFs.<\/li>\n\n\n\n<li>Calculates confidence scores for quality control.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Output Creation<\/strong>\n<ul class=\"wp-block-list\">\n<li>Saves either <code>.txt<\/code> or <strong>searchable PDF<\/strong>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Azure Blob Upload<\/strong>\n<ul class=\"wp-block-list\">\n<li>Stores processed files in your Azure Blob container.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Azure Search Auto-Index Creation<\/strong>\n<ul class=\"wp-block-list\">\n<li>Checks if the index exists.<\/li>\n\n\n\n<li>Creates it automatically with the correct schema if missing.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Azure Search Indexing<\/strong>\n<ul class=\"wp-block-list\">\n<li>Pushes OCR text + metadata for instant search.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>CSV Reporting<\/strong>\n<ul class=\"wp-block-list\">\n<li>Generates a CSV summary for auditing.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Multi-threaded Processing<\/strong>\n<ul class=\"wp-block-list\">\n<li>Uses <code>ThreadPoolExecutor<\/code> for parallel OCR.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4a1; Example Usage<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Without Azure Search<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">BashCopy code<code>python ocr_processor_with_azure_search_autocreate.py \\\n  \"\/data\/scanned_docs\" \\\n  \"\/data\/processed_docs\" \\\n  \"pdf\" \\\n  \"eng\" \\\n  \"DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net\" \\\n  \"processed-docs\" \\\n  \"\/data\/ocr_report.csv\"\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>With Azure Search Auto-Index<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">BashCopy code<code>python ocr_processor_with_azure_search_autocreate.py \\\n  \"\/data\/scanned_docs\" \\\n  \"\/data\/processed_docs\" \\\n  \"pdf\" \\\n  \"eng\" \\\n  \"DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net\" \\\n  \"processed-docs\" \\\n  \"\/data\/ocr_report.csv\" \\\n  \"mysearchservice\" \\\n  \"documents-index\" \\\n  \"MY_AZURE_SEARCH_API_KEY\"\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4ca; Example Search Result<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Once indexed, you can query Azure Search like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">BashCopy code<code>curl -X GET \\\n  \"https:\/\/mysearchservice.search.windows.net\/indexes\/documents-index\/docs?api-version=2021-04-30-Preview&amp;search=invoice\" \\\n  -H \"api-key: MY_AZURE_SEARCH_API_KEY\"\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Response:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">JsonCopy code<code>{\n  \"value\": [\n    {\n      \"id\": \"invoice1.pdf\",\n      \"file_name\": \"invoice1.pdf\",\n      \"source_type\": \"scanned_pdf\",\n      \"confidence_score\": 92.5,\n      \"ocr_text\": \"Invoice #12345 ...\",<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>  \"blob_url\": \"https:\/\/youraccount.blob.core.windows.net\/processed-docs\/invoice1_searchable.pdf\"\n},\n{\n  \"id\": \"receipt2.jpg\",\n  \"file_name\": \"receipt2.jpg\",\n  \"source_type\": \"image\",\n  \"confidence_score\": 88.3,\n  \"ocr_text\": \"Receipt for purchase ...\",\n  \"blob_url\": \"https:\/\/youraccount.blob.core.windows.net\/processed-docs\/receipt2_searchable.pdf\"\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">]<br>}<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f50d; How to Use This Search Data<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Once your documents are indexed in <strong>Azure Cognitive Search<\/strong>, you can:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Search by keywords<\/strong>\n<ul class=\"wp-block-list\">\n<li>Example: <code>search=invoice<\/code> returns all documents containing the word &#8220;invoice&#8221;.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Filter by metadata<\/strong>\n<ul class=\"wp-block-list\">\n<li>Example: <code>search=*&amp;$filter=confidence_score gt 90<\/code> returns only high-quality OCR results.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Integrate into a Web UI<\/strong>\n<ul class=\"wp-block-list\">\n<li>You can build a search interface using Azure Search SDKs (Python, JavaScript, C#).<\/li>\n\n\n\n<li>Display results with clickable links to the <code>blob_url<\/code> for direct download\/view.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Automate review workflows<\/strong>\n<ul class=\"wp-block-list\">\n<li>Use confidence scores to flag low-quality OCR results for manual correction.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f31f; Benefits of Auto-Index Creation<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>No manual setup<\/strong> \u2014 the script creates the Azure Search index schema automatically.<\/li>\n\n\n\n<li><strong>Consistent structure<\/strong> \u2014 all documents have the same searchable fields.<\/li>\n\n\n\n<li><strong>Scalable<\/strong> \u2014 works for thousands of files without extra configuration.<\/li>\n\n\n\n<li><strong>Cloud-native<\/strong> \u2014 integrates seamlessly with Azure Blob and Azure Search.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4a1; Pro Tip: Combine with OpenWebUI<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If you integrate this script into <strong>OpenWebUI<\/strong> as a tool:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You can trigger OCR + indexing directly from the chat interface.<\/li>\n\n\n\n<li>You can even add a <code>\/search<\/code> skill that queries Azure Search and returns results in chat.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f680; Next Step<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If you want, I can now <strong>add a feature<\/strong> where the script:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Automatically <strong>generates a thumbnail preview<\/strong> for each document.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>NEXT OPTION:<\/strong> <strong>AZURE COGNITIVE SEARCH INTEGRATION _ OCR, BLOB UPLOAD, INDEX IN SEARCH<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;extend your <strong>OCR + Azure Blob pipeline<\/strong> so that after OCR processing, the extracted text is <strong>automatically indexed into Azure Cognitive Search<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This will give you a <strong>searchable document repository<\/strong> where you can query across all processed files instantly \u2014 perfect for enterprise knowledge discovery.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f539; Updated Workflow<\/strong><\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>OCR Processing<\/strong> \u2192 Extract text from images\/scanned PDFs.<\/li>\n\n\n\n<li><strong>Searchable PDF\/TXT Creation<\/strong> \u2192 Save locally.<\/li>\n\n\n\n<li><strong>Azure Blob Upload<\/strong> \u2192 Store processed files in the cloud.<\/li>\n\n\n\n<li><strong>Azure Cognitive Search Indexing<\/strong> \u2192 Push extracted text + metadata into a search index.<\/li>\n\n\n\n<li><strong>Instant Search<\/strong> \u2192 Use Azure Search REST API or UI to query across all documents.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4dc; Updated Python Tool: <code>ocr_processor_with_azure_search.py<\/code><\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\"><br>PythonCopy code<code>import os<br>import sys<br>import pytesseract<br>from pdf2image import convert_from_path<br>from PIL import Image<br>import fitz  # PyMuPDF<br>from azure.storage.blob import BlobServiceClient<br>import json<br>import csv<br>from concurrent.futures import ThreadPoolExecutor, as_completed<br>import requests<br><br># ---------------- OCR Functions ---------------- #<br><br>def ocr_image_to_text(image_path, lang=\"eng\"):<br>    image = Image.open(image_path)<br>    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)<br>    text = \" \".join([t for t in data[\"text\"] if t.strip()])<br>    confidences = [int(c) for c in data[\"conf\"] if c.isdigit()]<br>    confidence = sum(confidences) \/ max(len(confidences), 1)<br>    return text, confidence<br><br>def ocr_pdf_to_text(pdf_path, lang=\"eng\"):<br>    pages = convert_from_path(pdf_path)<br>    text = \"\"<br>    confidences = []<br>    for page in pages:<br>        data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)<br>        text += \" \".join([t for t in data[\"text\"] if t.strip()]) + \"\\n\"<br>        page_conf = [int(c) for c in data[\"conf\"] if c.isdigit()]<br>        confidences.extend(page_conf)<br>    confidence = sum(confidences) \/ max(len(confidences), 1)<br>    return text, confidence<br><br>def save_as_txt(text, output_path):<br>    with open(output_path, \"w\", encoding=\"utf-8\") as f:<br>        f.write(text)<br><br>def save_as_searchable_pdf(original_path, text, output_path):<br>    if original_path.lower().endswith(\".pdf\"):<br>        pdf_doc = fitz.open(original_path)<br>    else:<br>        img = Image.open(original_path)<br>        temp_pdf_path = output_path.replace(\".pdf\", \"_temp.pdf\")<br>        img.save(temp_pdf_path, \"PDF\", resolution=300.0)<br>        pdf_doc = fitz.open(temp_pdf_path)<br><br>    for page_num, page in enumerate(pdf_doc):<br>        page.insert_text((50, 50), text, fontsize=8, overlay=False)<br><br>    pdf_doc.save(output_path)<br>    pdf_doc.close()<br><br># ---------------- Azure Functions ---------------- #<br><br>def upload_to_azure(file_path, connection_string, container_name):<br>    blob_service_client = BlobServiceClient.from_connection_string(connection_string)<br>    blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))<br>    with open(file_path, \"rb\") as data:<br>        blob_client.upload_blob(data, overwrite=True)<br>    return blob_client.url<br><br>def index_to_azure_search(search_service_name, index_name, api_key, document):<br>    \"\"\"<br>    Push a document into Azure Cognitive Search.<br>    \"\"\"<br>    url = f\"https:\/\/{search_service_name}.search.windows.net\/indexes\/{index_name}\/docs\/index?api-version=2021-04-30-Preview\"<br>    headers = {<br>        \"Content-Type\": \"application\/json\",<br>        \"api-key\": api_key<br>    }<br>    payload = {<br>        \"value\": [document]<br>    }<br>    response = requests.post(url, headers=headers, json=payload)<br>    if response.status_code != 200:<br>        raise Exception(f\"Azure Search indexing failed: {response.text}\")<br>    return response.json()<br><br># ---------------- Processing ---------------- #<br><br>def process_file(file_path, output_format, lang, output_dir, connection_string, container_name, search_config):<br>    os.makedirs(output_dir, exist_ok=True)<br>    filename = os.path.basename(file_path)<br>    base_name, _ = os.path.splitext(filename)<br><br>    if file_path.lower().endswith((\".jpg\", \".jpeg\", \".png\", \".tiff\", \".bmp\")):<br>        text, confidence = ocr_image_to_text(file_path, lang)<br>    elif file_path.lower().endswith(\".pdf\"):<br>        text<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>    text, confidence = ocr_pdf_to_text(file_path, lang)\nelse:\n    return {\"document_id\": filename, \"error\": \"Unsupported file type\"}\n\n# Save output file\nif output_format == \"txt\":\n    output_file = os.path.join(output_dir, f\"{base_name}.txt\")\n    save_as_txt(text, output_file)\nelse:\n    output_file = os.path.join(output_dir, f\"{base_name}_searchable.pdf\")\n    save_as_searchable_pdf(file_path, text, output_file)\n\n# Upload to Azure Blob\nazure_url = upload_to_azure(output_file, connection_string, container_name)\n\n# Prepare document for Azure Cognitive Search\nif search_config:\n    search_doc = {\n        \"id\": filename,\n        \"file_name\": filename,\n        \"source_type\": \"image\" if not file_path.lower().endswith(\".pdf\") else \"scanned_pdf\",\n        \"confidence_score\": round(confidence, 2),\n        \"ocr_text\": text,\n        \"blob_url\": azure_url\n    }\n    index_to_azure_search(\n        search_service_name=search_config&#91;\"service_name\"],\n        index_name=search_config&#91;\"index_name\"],\n        api_key=search_config&#91;\"api_key\"],\n        document=search_doc\n    )\n\nreturn {\n    \"document_id\": filename,\n    \"source_type\": \"image\" if not file_path.lower().endswith(\".pdf\") else \"scanned_pdf\",\n    \"ocr_text\": text,\n    \"confidence_score\": round(confidence, 2),\n    \"output_file\": output_file,\n    \"azure_blob_url\": azure_url\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">def write_csv_report(results, csv_path):<br>with open(csv_path, &#8220;w&#8221;, newline=&#8221;&#8221;, encoding=&#8221;utf-8&#8243;) as csvfile:<br>fieldnames = [&#8220;document_id&#8221;, &#8220;source_type&#8221;, &#8220;confidence_score&#8221;, &#8220;output_file&#8221;, &#8220;azure_blob_url&#8221;, &#8220;error&#8221;]<br>writer = csv.DictWriter(csvfile, fieldnames=fieldnames)<br>writer.writeheader()<br>for result in results:<br>writer.writerow({<br>&#8220;document_id&#8221;: result.get(&#8220;document_id&#8221;),<br>&#8220;source_type&#8221;: result.get(&#8220;source_type&#8221;),<br>&#8220;confidence_score&#8221;: result.get(&#8220;confidence_score&#8221;),<br>&#8220;output_file&#8221;: result.get(&#8220;output_file&#8221;),<br>&#8220;azure_blob_url&#8221;: result.get(&#8220;azure_blob_url&#8221;),<br>&#8220;error&#8221;: result.get(&#8220;error&#8221;)<br>})<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">def main(input_dir, output_dir, output_format, lang, connection_string, container_name, csv_report_path, search_config=None):<br>results = []<br>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))]<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>with ThreadPoolExecutor(max_workers=8) as executor:\n    future_to_file = {\n        executor.submit(process_file, file_path, output_format, lang, output_dir, connection_string, container_name, search_config): file_path\n        for file_path in files_to_process\n    }\n    for future in as_completed(future_to_file):\n        try:\n            result = future.result()\n            results.append(result)\n        except Exception as e:\n            results.append({\n                \"document_id\": os.path.basename(future_to_file&#91;future]),\n                \"error\": str(e)\n            })\n\nwrite_csv_report(results, csv_report_path)\nprint(json.dumps(results, indent=2))<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">if <strong>name<\/strong> == &#8220;<strong>main<\/strong>&#8220;:<br>if len(sys.argv) &lt; 8: print(&#8220;Usage: python ocr_processor_with_azure_search.py [ ]&#8221;)<br>sys.exit(1)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>input_dir = sys.argv&#91;1]\noutput_dir = sys.argv&#91;2]\noutput_format = sys.argv&#91;3]\nlang = sys.argv&#91;4]\nazure_connection_string = sys.argv&#91;5]\nazure_container_name = sys.argv&#91;6]\ncsv_report_path = sys.argv&#91;7]\n\nsearch_config = None\nif len(sys.argv) == 11:\n    search_config = {\n        \"service_name\": sys.argv&#91;8],\n        \"index_name\": sys.argv&#91;9],\n        \"api_key\": sys.argv&#91;10]\n    }\n\nmain(input_dir, output_dir, output_format, lang, azure_connection_string, azure_container_name, csv_report_path, search_config)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>&nbsp;<\/strong>&nbsp;let\u2019s finish the <strong>explanation<\/strong> so you have a clear picture of how this new Azure Cognitive Search integration works and how to deploy it effectively.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f680; How This Works (Step-by-Step)<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. OCR Processing<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The script reads each file from the <code>input_dir<\/code>.<\/li>\n\n\n\n<li>If it\u2019s an <strong>image<\/strong> (<code>.jpg<\/code>, <code>.png<\/code>, <code>.tiff<\/code>, etc.), it runs <code>ocr_image_to_text<\/code>.<\/li>\n\n\n\n<li>If it\u2019s a <strong>scanned PDF<\/strong>, it runs <code>ocr_pdf_to_text<\/code> (converts each page to an image first).<\/li>\n\n\n\n<li>It calculates a <strong>confidence score<\/strong> based on OCR word recognition quality.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2. Output File Creation<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Depending on <code>output_format<\/code>:\n<ul class=\"wp-block-list\">\n<li><code>\"txt\"<\/code> \u2192 Saves extracted text to a <code>.txt<\/code> file.<\/li>\n\n\n\n<li><code>\"pdf\"<\/code> \u2192 Creates a <strong>searchable PDF<\/strong> by embedding OCR text into the original file.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Output files are stored in <code>output_dir<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3. Azure Blob Upload<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The processed file is uploaded to <strong>Azure Blob Storage<\/strong> using <code>upload_to_azure<\/code>.<\/li>\n\n\n\n<li>The script returns a <strong>public blob URL<\/strong> (or SAS URL if you configure it that way).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>4. Azure Cognitive Search Indexing<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If <code>search_config<\/code> is provided, the script pushes metadata + OCR text into <strong>Azure Cognitive Search<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>id<\/code> \u2192 Document ID (filename)<\/li>\n\n\n\n<li><code>file_name<\/code> \u2192 Original filename<\/li>\n\n\n\n<li><code>source_type<\/code> \u2192 <code>\"image\"<\/code> or <code>\"scanned_pdf\"<\/code><\/li>\n\n\n\n<li><code>confidence_score<\/code> \u2192 OCR quality score<\/li>\n\n\n\n<li><code>ocr_text<\/code> \u2192 Full extracted text<\/li>\n\n\n\n<li><code>blob_url<\/code> \u2192 Link to the processed file in Azure Blob Storage<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>This allows <strong>instant search<\/strong> across all documents via Azure Search API or portal.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>5. CSV Summary Report<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The script writes a CSV file (<code>csv_report_path<\/code>) containing:\n<ul class=\"wp-block-list\">\n<li>Document ID<\/li>\n\n\n\n<li>Source type<\/li>\n\n\n\n<li>Confidence score<\/li>\n\n\n\n<li>Output file path<\/li>\n\n\n\n<li>Azure Blob URL<\/li>\n\n\n\n<li>Any errors encountered<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>This is useful for auditing and quality control.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6. Multi-threaded Processing<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Uses <code>ThreadPoolExecutor<\/code> with <code>max_workers=8<\/code> for parallel OCR.<\/li>\n\n\n\n<li>This speeds up processing significantly for large batches (e.g., thousands of files).<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4a1; Example Usage<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Without Azure Search<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">BashCopy code<code>python ocr_processor_with_azure_search.py \\\n  \"\/data\/scanned_docs\" \\\n  \"\/data\/processed_docs\" \\\n  \"pdf\" \\\n  \"eng\" \\\n  \"DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net\" \\\n  \"processed-docs\" \\\n  \"\/data\/ocr_report.csv\"\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>With Azure Search Integration<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">BashCopy code<code>python ocr_processor_with_azure_search.py \\\n  \"\/data\/scanned_docs\" \\\n  \"\/data\/processed_docs\" \\\n  \"pdf\" \\\n  \"eng\" \\\n  \"DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net\" \\\n  \"processed-docs\" \\\n  \"\/data\/ocr_report.csv\" \\\n  \"mysearchservice\" \\\n  \"documents-index\" \\\n  \"MY_AZURE_SEARCH_API_KEY\"\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4ca; Example Azure Search Document<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">After indexing, a document in Azure Search might look like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">JsonCopy code<code>{\n  \"id\": \"invoice1.pdf\",\n  \"file_name\": \"invoice1.pdf\",\n  \"source_type\": \"scanned_pdf\",\n  \"confidence_score\": 92.5,\n  \"ocr_text\": \"Invoice #12345 ...\",\n  \"blob_url\": \"https:\/\/youraccount.blob.core.windows.net\/processed-docs\/invoice1_searchable.pdf\"\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f31f; Benefits<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Instant Search<\/strong>: Query across all OCR-processed documents in seconds.<\/li>\n\n\n\n<li><strong>Cloud Storage<\/strong>: Files are safely stored in Azure Blob.<\/li>\n\n\n\n<li><strong>Audit Trail<\/strong>: CSV report ensures transparency and quality control.<\/li>\n\n\n\n<li><strong>Scalable<\/strong>: Multi-threaded processing handles thousands of files efficiently.<\/li>\n\n\n\n<li><strong>Flexible<\/strong>: Works with or without Azure Cognitive Search.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If you want, I can now <strong>add an automatic Azure Search index creation step<\/strong> so the script can <strong>set up the index schema<\/strong> before uploading documents \u2014 meaning you won\u2019t have to manually configure Azure Search beforehand.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Next Option: <\/strong>make this <strong>enterprise-grade<\/strong> by adding:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Multi-threaded OCR processing<\/strong> for speed (using <code>concurrent.futures<\/code>).<\/li>\n\n\n\n<li><strong>CSV summary report<\/strong> for quick review of all processed files.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">This will allow you to process <strong>thousands of documents<\/strong> much faster while keeping a clean audit trail.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4dc; Enhanced Python Tool: <code>ocr_processor_with_azure.py<\/code> (Multi-thread + CSV)<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\nimport sys\nimport pytesseract\nfrom pdf2image import convert_from_path\nfrom PIL import Image\nimport fitz  # PyMuPDF\nfrom azure.storage.blob import BlobServiceClient\nimport json\nimport csv\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef ocr_image_to_text(image_path, lang=\"eng\"):\n    \"\"\"\n    Run OCR on an image and return extracted text + confidence score.\n    Confidence score is calculated as the average of all recognized word confidences.\n    \"\"\"\n    image = Image.open(image_path)\n    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)\n    text = \" \".join(&#91;t for t in data&#91;\"text\"] if t.strip()])\n    confidences = &#91;int(c) for c in data&#91;\"conf\"] if c.isdigit()]\n    confidence = sum(confidences) \/ max(len(confidences), 1)\n    return text, confidence\n\ndef ocr_pdf_to_text(pdf_path, lang=\"eng\"):\n    \"\"\"\n    Run OCR on a scanned PDF by converting each page to an image.\n    Returns combined text from all pages and an overall confidence score.\n    \"\"\"\n    pages = convert_from_path(pdf_path)\n    text = \"\"\n    confidences = &#91;]\n    for page in pages:\n        data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)\n        text += \" \".join(&#91;t for t in data&#91;\"text\"] if t.strip()]) + \"\\n\"\n        page_conf = &#91;int(c) for c in data&#91;\"conf\"] if c.isdigit()]\n        confidences.extend(page_conf)\n    confidence = sum(confidences) \/ max(len(confidences), 1)\n    return text, confidence\n\ndef save_as_txt(text, output_path):\n    \"\"\"Save extracted OCR text to a plain .txt file.\"\"\"\n    with open(output_path, \"w\", encoding=\"utf-8\") as f:\n        f.write(text)\n\ndef save_as_searchable_pdf(original_path, text, output_path):\n    \"\"\"\n    Embed OCR text into the original PDF or image to make it searchable.\n    Uses PyMuPDF to insert text into each page without altering layout.\n    \"\"\"\n    if original_path.lower().endswith(\".pdf\"):\n        pdf_doc = fitz.open(original_path)\n    else:\n        img = Image.open(original_path)\n        temp_pdf_path = output_path.replace(\".pdf\", \"_temp.pdf\")\n        img.save(temp_pdf_path, \"PDF\", resolution=300.0)\n        pdf_doc = fitz.open(temp_pdf_path)\n\n    for page_num, page in enumerate(pdf_doc):\n        page.insert_text((50, 50), text, fontsize=8, overlay=False)\n\n    pdf_doc.save(output_path)\n    pdf_doc.close()\n\ndef upload_to_azure(file_path, connection_string, container_name):\n    \"\"\"\n    Upload processed file to Azure Blob Storage.\n    Returns the public blob URL for reference.\n    \"\"\"\n    blob_service_client = BlobServiceClient.from_connection_string(connection_string)\n    blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))\n    with open(file_path, \"rb\") as data:\n        blob_client.upload_blob(data, overwrite=True)\n    return blob_client.url\n\ndef process_file(file_path, output_format, lang, output_dir, connection_string, container_name):\n    \"\"\"\n    Process a single file:\n    - Run OCR\n    - Save as searchable PDF or TXT\n    - Upload to Azure Blob Storage\n    - Return structured metadata\n    \"\"\"\n    os.makedirs(output_dir, exist_ok=True)\n    filename = os.path.basename(file_path)\n    base_name, _ = os.path.splitext(filename)\n\n    if file_path.lower().endswith((\".jpg\", \".jpeg\", \".png\", \".tiff\", \".bmp\")):\n        text, confidence = ocr_image_to_text(file_path, lang)\n    elif file_path.lower().endswith(\".pdf\"):\n        text, confidence = ocr_pdf_to_text(file_path, lang)\n    else:\n        return {\"document_id\": filename, \"error\": \"Unsupported file type\"}\n\n    if output_format == \"txt\":\n        output_file = os.path.join(output_dir, f\"{base_name}.txt\")\n        save_as_txt(text, output_file)\n    else:\n                output_file = os.path.join(output_dir, f\"{base_name}_searchable.pdf\")\n        save_as_searchable_pdf(file_path, text, output_file)\n\n    # Upload processed file to Azure Blob Storage\n    azure_url = upload_to_azure(output_file, connection_string, container_name)\n\n    return {\n        \"document_id\": filename,\n        \"source_type\": \"image\" if not file_path.lower().endswith(\".pdf\") else \"scanned_pdf\",\n        \"ocr_text\": text,\n        \"confidence_score\": round(confidence, 2),\n        \"output_file\": output_file,\n        \"azure_blob_url\": azure_url\n    }\n\ndef write_csv_report(results, csv_path):\n    \"\"\"\n    Write a CSV summary report of all processed files.\n    Includes document ID, source type, confidence score, output file path, and Azure URL.\n    \"\"\"\n    with open(csv_path, \"w\", newline=\"\", encoding=\"utf-8\") as csvfile:\n        fieldnames = &#91;\"document_id\", \"source_type\", \"confidence_score\", \"output_file\", \"azure_blob_url\", \"error\"]\n        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n        writer.writeheader()\n        for result in results:\n            writer.writerow({\n                \"document_id\": result.get(\"document_id\"),\n                \"source_type\": result.get(\"source_type\"),\n                \"confidence_score\": result.get(\"confidence_score\"),\n                \"output_file\": result.get(\"output_file\"),\n                \"azure_blob_url\": result.get(\"azure_blob_url\"),\n                \"error\": result.get(\"error\")\n            })\n\ndef main(input_dir, output_dir, output_format, lang, connection_string, container_name, csv_report_path):\n    \"\"\"\n    Main processing loop:\n    - Uses multi-threading for faster OCR\n    - Generates JSON output for OpenWebUI\n    - Writes CSV report for auditing\n    \"\"\"\n    results = &#91;]\n    files_to_process = &#91;os.path.join(input_dir, f) for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]\n\n    # Multi-threaded processing\n    with ThreadPoolExecutor(max_workers=8) as executor:\n        future_to_file = {\n            executor.submit(process_file, file_path, output_format, lang, output_dir, connection_string, container_name): file_path\n            for file_path in files_to_process\n        }\n        for future in as_completed(future_to_file):\n            try:\n                result = future.result()\n                results.append(result)\n            except Exception as e:\n                results.append({\n                    \"document_id\": os.path.basename(future_to_file&#91;future]),\n                    \"error\": str(e)\n                })\n\n    # Write CSV report\n    write_csv_report(results, csv_report_path)\n\n    # Output JSON for OpenWebUI\n    print(json.dumps(results, indent=2))\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 8:\n        print(\"Usage: python ocr_processor_with_azure.py &lt;input_dir&gt; &lt;output_dir&gt; &lt;output_format&gt; &lt;lang&gt; &lt;azure_connection_string&gt; &lt;azure_container_name&gt; &lt;csv_report_path&gt;\")\n        sys.exit(1)\n\n    input_dir = sys.argv&#91;1]\n    output_dir = sys.argv&#91;2]\n    output_format = sys.argv&#91;3]\n    lang = sys.argv&#91;4]\n    azure_connection_string = sys.argv&#91;5]\n    azure_container_name = sys.argv&#91;6]\n    csv_report_path = sys.argv&#91;7]\n\n    main(input_dir, output_dir, output_format, lang, azure_connection_string, azure_container_name, csv_report_path)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Key Improvements<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Multi-threaded OCR<\/strong>\n<ul class=\"wp-block-list\">\n<li>Uses <code>ThreadPoolExecutor<\/code> with <code>max_workers=8<\/code> for parallel processing.<\/li>\n\n\n\n<li>Greatly speeds up large batch processing (e.g., thousands of documents).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>CSV Summary Report<\/strong>\n<ul class=\"wp-block-list\">\n<li>Includes document ID, source type, confidence score, output file path, Azure Blob URL, and any errors.<\/li>\n\n\n\n<li>Useful for auditing and tracking OCR quality.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Structured JSON Output<\/strong>\n<ul class=\"wp-block-list\">\n<li>Ready for OpenWebUI integration.<\/li>\n\n\n\n<li>Contains all metadata for each processed file.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>&#x1f4c2; Directory Setup<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">Copy code<code>openwebui\/\n  skills\/\n    ocr_image_to_searchable_with_azure.yaml\n  tools\/\n    ocr_processor_with_azure.py\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>&#x1f4a1; Example Usage<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">BashCopy code<code>\/skill OCR Image\/PDF to Searchable PDF\/TXT with Azure Upload \\<br>  input_dir=\"\/data\/scanned_docs\" \\<br>  output<\/code><br><br><br><br><br>finish the usage example and also give you a realistic workflow for running this in OpenWebUI or as a standalone batch job.<br><br>&#x1f4a1; Example Usage in OpenWebUI<br>If you\u2019ve already created the skill YAML that calls this Python tool, you can trigger it like this:<br><br>Bash<br><br>Copy code<br>\/skill OCR Image\/PDF to Searchable PDF\/TXT with Azure Upload \\<br>  input_dir=\"\/data\/scanned_docs\" \\<br>  output_dir=\"\/data\/processed_docs\" \\<br>  output_format=\"pdf\" \\<br>  language=\"eng\" \\<br>  azure_connection_string=\"DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net\" \\<br>  azure_container_name=\"processed-docs\" \\<br>  csv_report_path=\"\/data\/ocr_report.csv\"<br>&#x1f4a1; Example Usage as a Standalone Script<br>If you want to run it outside OpenWebUI, just call it directly:<br><br>Bash<br><br>Copy code<br>python ocr_processor_with_azure.py \\<br>  \"\/data\/scanned_docs\" \\<br>  \"\/data\/processed_docs\" \\<br>  \"pdf\" \\<br>  \"eng\" \\<br>  \"DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net\" \\<br>  \"processed-docs\" \\<br>  \"\/data\/ocr_report.csv\"<br>&#x1f4ca; Example CSV Output<br>After processing, you\u2019ll get a CSV file like this:<br><br>document_id\tsource_type\tconfidence_score\toutput_file\tazure_blob_url\terror<br>invoice1.pdf\tscanned_pdf\t92.5\t\/data\/processed_docs\/invoice1_searchable.pdf\thttps:\/\/youraccount.blob.core.windows.net\/processed-docs\/invoice1_searchable.pdf\t<br>receipt2.jpg\timage\t88.3\t\/data\/processed_docs\/receipt2_searchable.pdf\thttps:\/\/youraccount.blob.core.windows.net\/processed-docs\/receipt2_searchable.pdf\t<br>badfile.txt\tNone\tNone\tNone\tNone\tUnsupported file type<br>&#x1f680; Workflow for Enterprise-Scale Processing<br>Drop files into \/data\/scanned_docs (can be mounted from a network share or blob sync).<br>Run the skill in OpenWebUI or schedule the Python script via cron or Azure Functions.<br>OCR runs in parallel (multi-threaded) for speed.<br>Searchable PDFs\/TXTs are saved locally and uploaded to Azure Blob Storage.<br>CSV report is generated for auditing and quality control.<br>Confidence scores help you identify low-quality OCR results for manual review.<br>&#x1f4a1; Pro Tip for Scaling<br>If you have thousands of files, you can increase max_workers in the script to match your CPU cores for maximum throughput.<br>You can also split input directories and run multiple instances in parallel for even faster processing.<br>For cloud-native scaling, wrap this script in an Azure Container Instance or Kubernetes Job so it can scale horizontally.<br><br><br><br><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Option 2<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\">make this <strong>OCR helper tool<\/strong> so your OpenWebUI skill can actually process images and scanned PDFs into <strong>searchable PDFs<\/strong> or <code>.txt<\/code> files automatically.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We\u2019ll use <strong>Python + Tesseract OCR<\/strong> (open-source, offline) so it works without cloud dependencies, but I\u2019ll also note where you could swap in <strong>Azure Cognitive Services OCR<\/strong> for enterprise-grade accuracy.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Python OCR Helper Tool \u2013 <code>ocr_processor.py<\/code><\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">PythonCopy code<code>import os\nimport sys\nimport pytesseract\nfrom pdf2image import convert_from_path\nfrom PIL import Image\nfrom fpdf import FPDF\nimport fitz  # PyMuPDF for searchable PDF embedding\n\n# Ensure Tesseract is installed and in PATH\n# Windows example: pytesseract.pytesseract.tesseract_cmd = r\"C:\\Program Files\\Tesseract-OCR\\tesseract.exe\"\n\ndef ocr_image_to_text(image_path, lang=\"eng\"):\n    \"\"\"Extract text from an image file using Tesseract OCR.\"\"\"\n    image = Image.open(image_path)\n    text = pytesseract.image_to_string(image, lang=lang)\n    return text\n\ndef ocr_pdf_to_text(pdf_path, lang=\"eng\"):\n    \"\"\"Extract text from a scanned PDF by converting pages to images.\"\"\"\n    pages = convert_from_path(pdf_path)\n    text = \"\"\n    for page in pages:\n        text += pytesseract.image_to_string(page, lang=lang) + \"\\n\"\n    return text\n\ndef save_as_txt(text, output_path):\n    \"\"\"Save extracted text to a .txt file.\"\"\"\n    with open(output_path, \"w\", encoding=\"utf-8\") as f:\n        f.write(text)\n\ndef save_as_searchable_pdf(original_path, text, output_path):\n    \"\"\"Embed OCR text into original PDF or image to make it searchable.\"\"\"\n    if original_path.lower().endswith(\".pdf\"):\n        # Open original PDF\n        pdf_doc = fitz.open(original_path)\n    else:\n        # Convert image to PDF first\n        img = Image.open(original_path)\n        temp_pdf_path = output_path.replace(\".pdf\", \"_temp.pdf\")\n        img.save(temp_pdf_path, \"PDF\", resolution=300.0)\n        pdf_doc = fitz.open(temp_pdf_path)\n\n    for page_num, page in enumerate(pdf_doc):\n        page.insert_text((50, 50), text, fontsize=8, overlay=False)\n\n    pdf_doc.save(output_path)\n    pdf_doc.close()\n\ndef process_file(file_path, output_format=\"pdf\", lang=\"eng\", output_dir=\"output\"):\n    \"\"\"Process a single file and return metadata.\"\"\"\n    os.makedirs(output_dir, exist_ok=True)\n    filename = os.path.basename(file_path)\n    base_name, _ = os.path.splitext(filename)\n\n    if file_path.lower().endswith((\".jpg\", \".jpeg\", \".png\", \".tiff\", \".bmp\")):\n        text = ocr_image_to_text(file_path, lang)\n    elif file_path.lower().endswith(\".pdf\"):\n        text = ocr_pdf_to_text(file_path, lang)\n    else:\n        return {\"document_id\": filename, \"error\": \"Unsupported file type\"}\n\n    if output_format == \"txt\":\n        output_file = os.path.join(output_dir, f\"{base_name}.txt\")\n        save_as_txt(text, output_file)\n    else:\n        output_file = os.path.join(output_dir, f\"{base_name}_searchable.pdf\")\n        save_as_searchable_pdf(file_path, text, output_file)\n\n    return {\n        \"document_id\": filename,\n        \"source_type\": \"image\" if not file_path.lower().endswith(\".pdf\") else \"scanned_pdf\",\n        \"ocr_text\": text,\n        \"output_file\": output_file\n    }\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 2:\n        print(\"Usage: python ocr_processor.py &lt;file_path&gt; [output_format] [lang]\")\n        sys.exit(1)\n\n    file_path = sys.argv[1]\n    output_format = sys.argv[2] if len(sys.argv) &gt; 2 else \"pdf\"\n    lang = sys.argv[3] if len(sys.argv) &gt; 3 else \"eng\"\n\n    result = process_file(file_path, output_format, lang)\n    print(result)\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f539; How This Works<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Image OCR<\/strong>: Uses <code>pytesseract<\/code> to read text from <code>.jpg<\/code>, <code>.png<\/code>, <code>.tiff<\/code>, <code>.bmp<\/code>.<\/li>\n\n\n\n<li><strong>Scanned PDF OCR<\/strong>: Converts each page to an image, then runs OCR.<\/li>\n\n\n\n<li><strong>TXT Output<\/strong>: Saves extracted text as <code>.txt<\/code>.<\/li>\n\n\n\n<li><strong>Searchable PDF Output<\/strong>: Embeds OCR text into the original PDF\/image using <strong>PyMuPDF<\/strong> so it\u2019s searchable.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\">an <strong>OpenWebUI skill<\/strong> that can:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>OCR extract text content<\/strong> from image files (e.g., <code>.jpg<\/code>, <code>.png<\/code>, <code>.tiff<\/code>).<\/li>\n\n\n\n<li><strong>Convert the file<\/strong> into a <strong>searchable PDF<\/strong> or <code>.txt<\/code> file.<\/li>\n\n\n\n<li>Handle large volumes (like thousands of files) with accuracy and completeness.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Here\u2019s a <strong>production-ready skill definition<\/strong> you can drop into OpenWebUI:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>&#x1f4c4; Skill: <code>ocr_image_to_searchable.yaml<\/code><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">YamlCopy code<code>name: \"OCR Image to Searchable PDF\/TXT\"\ndescription: \"Extract text from images using OCR and convert to searchable PDF or TXT.\"\nauthor: \"Your Name\"\nversion: \"1.0\"\n\nparameters:\n  - name: output_format\n    type: string\n    required: true\n    default: \"pdf\"\n    description: \"Output format: 'pdf' for searchable PDF or 'txt' for plain text\"\n  - name: language\n    type: string\n    required: false\n    default: \"eng\"\n    description: \"OCR language code (e.g., 'eng', 'spa', 'fra')\"\n  - name: batch_size\n    type: integer\n    required: false\n    default: 50\n    description: \"Number of files to process per batch\"\n\nsystem_prompt: |\n  You are an OCR and document conversion assistant.\n  Your task:\n  - Accept image files (jpg, png, tiff, bmp) or scanned PDFs.\n  - Use OCR to extract all visible text from the images.\n  - Preserve layout and formatting where possible.\n  - If output_format is 'pdf', embed the extracted text into the original image to create a searchable PDF.\n  - If output_format is 'txt', output plain text with line breaks preserved.\n  - Ensure completeness: no words or characters are skipped.\n  - Ensure correctness: avoid OCR errors by cross-checking with language dictionaries.\n  - Output structured JSON for each file:\n    {\n      \"document_id\": \"&lt;filename&gt;\",\n      \"source_type\": \"image|scanned_pdf\",\n      \"ocr_text\": \"&lt;extracted text&gt;\",\n      \"output_file\": \"&lt;path to generated searchable PDF or TXT&gt;\"\n    }\n  - If OCR fails, log the error and skip the file.\n\nuser_prompt: |\n  Process the following batch of image or scanned PDF files.\n  Apply OCR extraction according to the system prompt.\n  Convert each file into a {{output_format}} format.\n  Return structured JSON for each processed file, including the path to the generated output file.\n\noutput_format: json\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>&#x1f539; How This Skill Works<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>OCR Extraction<\/strong>: Uses OCR (e.g., Tesseract or Azure Cognitive Services OCR) to read text from images.<\/li>\n\n\n\n<li><strong>Searchable PDF Creation<\/strong>: Embeds extracted text into the original image layer so it\u2019s searchable.<\/li>\n\n\n\n<li><strong>TXT Option<\/strong>: Outputs plain text for lightweight storage or further processing.<\/li>\n\n\n\n<li><strong>Batch Processing<\/strong>: Handles large datasets efficiently.<\/li>\n\n\n\n<li><strong>Language Support<\/strong>: Allows specifying OCR language for better accuracy.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">&#x1f4a1; If you want, I can also give you a <strong>Python helper tool<\/strong> that this skill can call internally to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Run OCR using <strong>Tesseract<\/strong> or <strong>Azure OCR API<\/strong>.<\/li>\n\n\n\n<li>Automatically generate searchable PDFs or <code>.txt<\/code> files.<\/li>\n\n\n\n<li>Save them to a specified output directory.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Option 3 &#8211; openwebui Skill in markdown format<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>OpenWebUI OCR skill<\/strong> in <strong>Markdown format<\/strong> so you can easily read, share, and adapt it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Skill: OCR Image\/PDF to Searchable PDF or TXT<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">YamlCopy code<code>name: \"OCR Image\/PDF to Searchable PDF\/TXT\"\ndescription: \"Extract text from images or scanned PDFs using OCR and convert to searchable PDF or TXT.\"\nauthor: \"Your Name\"\nversion: \"1.0\"\n\nparameters:\n  - name: output_format\n    type: string\n    required: true\n    default: \"pdf\"\n    description: \"Output format: 'pdf' for searchable PDF or 'txt' for plain text\"\n  - name: language\n    type: string\n    required: false\n    default: \"eng\"\n    description: \"OCR language code (e.g., 'eng', 'spa', 'fra')\"\n  - name: batch_size\n    type: integer\n    required: false\n    default: 50\n    description: \"Number of files to process per batch\"\n\nsystem_prompt: |\n  You are an OCR and document conversion assistant.\n  Your task:\n  - Accept image files (jpg, png, tiff, bmp) or scanned PDFs.\n  - Use OCR to extract all visible text from the images.\n  - Preserve layout and formatting where possible.\n  - If output_format is 'pdf', embed the extracted text into the original image to create a searchable PDF.\n  - If output_format is 'txt', output plain text with line breaks preserved.\n  - Ensure completeness: no words or characters are skipped.\n  - Ensure correctness: avoid OCR errors by cross-checking with language dictionaries.\n  - Output structured JSON for each file:\n    {\n      \"document_id\": \"&lt;filename&gt;\",\n      \"source_type\": \"image|scanned_pdf\",\n      \"ocr_text\": \"&lt;extracted text&gt;\",\n      \"output_file\": \"&lt;path to generated searchable PDF or TXT&gt;\"\n    }\n  - If OCR fails, log the error and skip the file.\n\nuser_prompt: |\n  Process the following batch of image or scanned PDF files.\n  Apply OCR extraction according to the system prompt.\n  Convert each file into a {{output_format}} format.\n  Return structured JSON for each processed file, including the path to the generated output file.\n\noutput_format: json\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>&#x1f539; How to Use This Skill<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Save this YAML definition as:Copy code<code>skills\/ocr_image_to_searchable.yaml <\/code>inside your <strong>OpenWebUI skills directory<\/strong>.<\/li>\n\n\n\n<li>Restart OpenWebUI so it loads the new skill.<\/li>\n\n\n\n<li>Call it from the chat interface like:Copy code<code>\/skill OCR Image\/PDF to Searchable PDF\/TXT output_format=\"pdf\" language=\"eng\" batch_size=20<\/code><\/li>\n\n\n\n<li>The skill will:\n<ul class=\"wp-block-list\">\n<li>Accept image or scanned PDF files.<\/li>\n\n\n\n<li>Run OCR extraction.<\/li>\n\n\n\n<li>Convert them into <strong>searchable PDFs<\/strong> or <code>.txt<\/code> files.<\/li>\n\n\n\n<li>Return structured JSON with file paths and extracted text.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">make your <strong>OpenWebUI OCR skill<\/strong> fully functional by integrating it with the <strong>Python OCR helper tool<\/strong> so it\u2019s plug\u2011and\u2011play.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This way, when you trigger the skill in OpenWebUI, it will automatically:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Accept image or scanned PDF files.<\/li>\n\n\n\n<li>Run OCR extraction using <strong>Tesseract<\/strong> (offline) or optionally <strong>Azure OCR API<\/strong>.<\/li>\n\n\n\n<li>Convert them into <strong>searchable PDFs<\/strong> or <code>.txt<\/code> files.<\/li>\n\n\n\n<li>Return structured JSON with extracted text and output file paths.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4c4; Integrated OCR Skill in Markdown<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">YamlCopy code<code>name: \"OCR Image\/PDF to Searchable PDF\/TXT\"\ndescription: \"Extract text from images or scanned PDFs using OCR and convert to searchable PDF or TXT.\"\nauthor: \"Your Name\"\nversion: \"1.1\"\n\nparameters:\n  - name: output_format\n    type: string\n    required: true\n    default: \"pdf\"\n    description: \"Output format: 'pdf' for searchable PDF or 'txt' for plain text\"\n  - name: language\n    type: string\n    required: false\n    default: \"eng\"\n    description: \"OCR language code (e.g., 'eng', 'spa', 'fra')\"\n  - name: batch_size\n    type: integer\n    required: false\n    default: 50\n    description: \"Number of files to process per batch\"\n  - name: input_dir\n    type: string\n    required: true\n    description: \"Directory containing image or scanned PDF files\"\n  - name: output_dir\n    type: string\n    required: true\n    description: \"Directory where processed files will be saved\"\n\nsystem_prompt: |\n  You are an OCR and document conversion assistant.\n  Your task:\n  - Accept image files (jpg, png, tiff, bmp) or scanned PDFs from {{input_dir}}.\n  - Use OCR to extract all visible text from the images.\n  - Preserve layout and formatting where possible.\n  - If output_format is 'pdf', embed the extracted text into the original image to create a searchable PDF.\n  - If output_format is 'txt', output plain text with line breaks preserved.\n  - Ensure completeness: no words or characters are skipped.\n  - Ensure correctness: avoid OCR errors by cross-checking with language dictionaries.\n  - Output structured JSON for each file:\n    {\n      \"document_id\": \"&lt;filename&gt;\",\n      \"source_type\": \"image|scanned_pdf\",\n      \"ocr_text\": \"&lt;extracted text&gt;\",\n      \"output_file\": \"&lt;path to generated searchable PDF or TXT&gt;\"\n    }\n  - If OCR fails, log the error and skip the file.\n\nuser_prompt: |\n  Process all files in {{input_dir}} in batches of {{batch_size}}.\n  Apply OCR extraction according to the system prompt.\n  Save processed files to {{output_dir}} in {{output_format}} format.\n  Return structured JSON for each processed file, including the path to the generated output file.\n\ntool:\n  name: \"ocr_processor\"\n  type: \"python\"\n  entrypoint: \"ocr_processor.py\"\n  args:\n    - \"{{input_dir}}\"\n    - \"{{output_dir}}\"\n    - \"{{output_format}}\"\n    - \"{{language}}\"\n\noutput_format: json\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f539; How This Works<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Skill Parameters<\/strong>: You specify input\/output directories, format (<code>pdf<\/code> or <code>txt<\/code>), language, and batch size.<\/li>\n\n\n\n<li><strong>System Prompt<\/strong>: Guides the OCR extraction process with accuracy and completeness rules.<\/li>\n\n\n\n<li><strong>User Prompt<\/strong>: Defines operational steps for batch processing.<\/li>\n\n\n\n<li><strong>Tool Integration<\/strong>: Calls <code>ocr_processor.py<\/code> (the helper tool we built earlier) to actually run OCR and generate output files.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4c2; Directory Setup<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">Copy code<code>openwebui\/\n  skills\/\n    ocr_image_to_searchable.yaml\n  tools\/\n    ocr_processor.py\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4a1; Usage Example<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">BashCopy code<code>\/skill OCR Image\/PDF to Searchable PDF\/TXT \\\n  input_dir=\"\/data\/scanned_docs\" \\\n  output_dir=\"\/data\/processed_docs\" \\\n  output_format=\"pdf\" \\\n  language=\"eng\" \\\n  batch_size=20\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">&#x2705; This setup means <strong>OpenWebUI will directly call the Python OCR tool<\/strong> when you run the skill \u2014 no manual steps, no separate scripts.<br>It will return <strong>structured JSON<\/strong> with:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Document ID<\/li>\n\n\n\n<li>Source type<\/li>\n\n\n\n<li>Extracted OCR text<\/li>\n\n\n\n<li>Path to generated searchable PDF or <code>.txt<\/code><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If you want, I can now <strong>extend this skill<\/strong> so it also:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Uploads the processed searchable PDFs back to <strong>Azure Blob Storage<\/strong> automatically.<\/li>\n\n\n\n<li>Logs OCR confidence scores for each document.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\">ENHANCEMENTS<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;extend the <strong>OCR skill + tool combo<\/strong> so it\u2019s <strong>production-ready<\/strong>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>OCR extraction<\/strong> from images\/scanned PDFs.<\/li>\n\n\n\n<li><strong>Convert to searchable PDF or <code>.txt<\/code><\/strong>.<\/li>\n\n\n\n<li><strong>Upload processed files back to Azure Blob Storage<\/strong> automatically.<\/li>\n\n\n\n<li><strong>Log OCR confidence scores<\/strong> for each document for quality tracking.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4c4; Extended OCR Skill in Markdown<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">YamlCopy code<code>name: \"OCR Image\/PDF to Searchable PDF\/TXT with Azure Upload\"\ndescription: \"Extract text from images or scanned PDFs using OCR, convert to searchable PDF\/TXT, upload to Azure Blob Storage, and log OCR confidence.\"\nauthor: \"Your Name\"\nversion: \"1.2\"\n\nparameters:\n  - name: output_format\n    type: string\n    required: true\n    default: \"pdf\"\n    description: \"Output format: 'pdf' for searchable PDF or 'txt' for plain text\"\n  - name: language\n    type: string\n    required: false\n    default: \"eng\"\n    description: \"OCR language code (e.g., 'eng', 'spa', 'fra')\"\n  - name: batch_size\n    type: integer\n    required: false\n    default: 50\n    description: \"Number of files to process per batch\"\n  - name: input_dir\n    type: string\n    required: true\n    description: \"Directory containing image or scanned PDF files\"\n  - name: output_dir\n    type: string\n    required: true\n    description: \"Directory where processed files will be saved\"\n  - name: azure_connection_string\n    type: string\n    required: true\n    description: \"Azure Blob Storage connection string\"\n  - name: azure_container_name\n    type: string\n    required: true\n    description: \"Azure Blob Storage container name for uploads\"\n\nsystem_prompt: |\n  You are an OCR and document conversion assistant.\n  Your task:\n  - Accept image files (jpg, png, tiff, bmp) or scanned PDFs from {{input_dir}}.\n  - Use OCR to extract all visible text from the images.\n  - Preserve layout and formatting where possible.\n  - If output_format is 'pdf', embed the extracted text into the original image to create a searchable PDF.\n  - If output_format is 'txt', output plain text with line breaks preserved.\n  - Ensure completeness: no words or characters are skipped.\n  - Ensure correctness: avoid OCR errors by cross-checking with language dictionaries.\n  - Calculate OCR confidence score for each document.\n  - Output structured JSON for each file:\n    {\n      \"document_id\": \"&lt;filename&gt;\",\n      \"source_type\": \"image|scanned_pdf\",\n      \"ocr_text\": \"&lt;extracted text&gt;\",\n      \"confidence_score\": \"&lt;percentage&gt;\",\n      \"output_file\": \"&lt;path to generated searchable PDF or TXT&gt;\",\n      \"azure_blob_url\": \"&lt;uploaded file URL&gt;\"\n    }\n  - If OCR fails, log the error and skip the file.\n\nuser_prompt: |\n  Process all files in {{input_dir}} in batches of {{batch_size}}.\n  Apply OCR extraction according to the system prompt.\n  Save processed files to {{output_dir}} in {{output_format}} format.\n  Upload each processed file to Azure Blob Storage container {{azure_container_name}} using {{azure_connection_string}}.\n  Return structured JSON for each processed file, including OCR confidence score and Azure Blob URL.\n\ntool:\n  name: \"ocr_processor_with_azure\"\n  type: \"python\"\n  entrypoint: \"ocr_processor_with_azure.py\"\n  args:\n    - \"{{input_dir}}\"\n    - \"{{output_dir}}\"\n    - \"{{output_format}}\"\n    - \"{{language}}\"\n    - \"{{azure_connection_string}}\"\n    - \"{{azure_container_name}}\"\n\noutput_format: json\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4dc; Python Tool: <code>ocr_processor_with_azure.py<\/code><\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">PythonCopy code<code>import os<br>import sys<br>import pytesseract<br>from pdf2image import convert_from_path<br>from PIL import Image<br>import fitz  # PyMuPDF<br>from azure.storage.blob import BlobServiceClient<br><br>def ocr_image_to_text(image_path, lang=\"eng\"):<br>    image = Image.open(image_path)<br>    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)<br>    text = \" \".join(data[\"text\"])<br>    confidence = sum([int(c) for c in data[\"conf\"] if c.isdigit()]) \/ max(len(data[\"conf\"]), 1)<br>    return text, confidence<br><br>def ocr_pdf_to_text(pdf_path, lang=\"eng\"):<br>    pages = convert_from_path(pdf_path)<br>    text = \"\"<br>    confidences = []<br>    for page in pages:<br>        data = pytesseract.image_to_data<\/code><br><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">finish the <strong>Python tool<\/strong> so it fully supports OCR extraction, searchable PDF creation, Azure Blob upload, and confidence scoring.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>&#x1f4dc; Completed Python Tool: <code>ocr_processor_with_azure.py<\/code><\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\nimport sys\nimport pytesseract\nfrom pdf2image import convert_from_path\nfrom PIL import Image\nimport fitz  # PyMuPDF\nfrom azure.storage.blob import BlobServiceClient\n\ndef ocr_image_to_text(image_path, lang=\"eng\"):\n    \"\"\"Run OCR on an image and return text + confidence score.\"\"\"\n    image = Image.open(image_path)\n    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)\n    text = \" \".join(&#91;t for t in data&#91;\"text\"] if t.strip()])\n    confidences = &#91;int(c) for c in data&#91;\"conf\"] if c.isdigit()]\n    confidence = sum(confidences) \/ max(len(confidences), 1)\n    return text, confidence\n\ndef ocr_pdf_to_text(pdf_path, lang=\"eng\"):\n    \"\"\"Run OCR on a scanned PDF and return text + confidence score.\"\"\"\n    pages = convert_from_path(pdf_path)\n    text = \"\"\n    confidences = &#91;]\n    for page in pages:\n        data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)\n        text += \" \".join(&#91;t for t in data&#91;\"text\"] if t.strip()]) + \"\\n\"\n        page_conf = &#91;int(c) for c in data&#91;\"conf\"] if c.isdigit()]\n        confidences.extend(page_conf)\n    confidence = sum(confidences) \/ max(len(confidences), 1)\n    return text, confidence\n\ndef save_as_txt(text, output_path):\n    \"\"\"Save extracted text to a .txt file.\"\"\"\n    with open(output_path, \"w\", encoding=\"utf-8\") as f:\n        f.write(text)\n\ndef save_as_searchable_pdf(original_path, text, output_path):\n    \"\"\"Embed OCR text into original PDF\/image to make it searchable.\"\"\"\n    if original_path.lower().endswith(\".pdf\"):\n        pdf_doc = fitz.open(original_path)\n    else:\n        img = Image.open(original_path)\n        temp_pdf_path = output_path.replace(\".pdf\", \"_temp.pdf\")\n        img.save(temp_pdf_path, \"PDF\", resolution=300.0)\n        pdf_doc = fitz.open(temp_pdf_path)\n\n    for page_num, page in enumerate(pdf_doc):\n        page.insert_text((50, 50), text, fontsize=8, overlay=False)\n\n    pdf_doc.save(output_path)\n    pdf_doc.close()\n\ndef upload_to_azure(file_path, connection_string, container_name):\n    \"\"\"Upload file to Azure Blob Storage and return blob URL.\"\"\"\n    blob_service_client = BlobServiceClient.from_connection_string(connection_string)\n    blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))\n    with open(file_path, \"rb\") as data:\n        blob_client.upload_blob(data, overwrite=True)\n    return blob_client.url\n\ndef process_file(file_path, output_format, lang, output_dir, connection_string, container_name):\n    \"\"\"Process a single file and return metadata.\"\"\"\n    os.makedirs(output_dir, exist_ok=True)\n    filename = os.path.basename(file_path)\n    base_name, _ = os.path.splitext(filename)\n\n    if file_path.lower().endswith((\".jpg\", \".jpeg\", \".png\", \".tiff\", \".bmp\")):\n        text, confidence = ocr_image_to_text(file_path, lang)\n    elif file_path.lower().endswith(\".pdf\"):\n        text, confidence = ocr_pdf_to_text(file_path, lang)\n    else:\n        return {\"document_id\": filename, \"error\": \"Unsupported file type\"}\n\n    if output_format == \"txt\":\n        output_file = os.path.join(output_dir, f\"{base_name}.txt\")\n        save_as_txt(text, output_file)\n    else:\n        output_file = os.path.join(output_dir, f\"{base_name}_searchable.pdf\")\n        save_as_searchable_pdf(file_path, text, output_file)\n\n    azure_url = upload_to_azure(output_file, connection_string, container_name)\n\n    return {\n        \"document_id\": filename,\n        \"source_type\": \"image\" if not file_path.lower().endswith(\".pdf\") else \"scanned_pdf\",\n        \"ocr_text\": text,\n        \"confidence_score\": round(confidence, 2),\n        \"output_file\": output_file,\n        \"azure_blob_url\": azure_url\n    }\n\ndef main(input_dir, output_dir, output_format, lang, connection_string, container_name):\n    results = &#91;]\n    for file_name in os.listdir(input_dir):\n        file_path = os.path.join(input_dir, file_name\n\n\n\n\n\n# 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.\n\nimport os\nimport sys\nimport pytesseract\nfrom pdf2image import convert_from_path\nfrom PIL import Image\nimport fitz  # PyMuPDF\nfrom azure.storage.blob import BlobServiceClient\nimport json\n\ndef ocr_image_to_text(image_path, lang=\"eng\"):\n    \"\"\"Run OCR on an image and return text + confidence score.\"\"\"\n    image = Image.open(image_path)\n    data = pytesseract.image_to_data(image, lang=lang, output_type=pytesseract.Output.DICT)\n    text = \" \".join(&#91;t for t in data&#91;\"text\"] if t.strip()])\n    confidences = &#91;int(c) for c in data&#91;\"conf\"] if c.isdigit()]\n    confidence = sum(confidences) \/ max(len(confidences), 1)\n    return text, confidence\n\ndef ocr_pdf_to_text(pdf_path, lang=\"eng\"):\n    \"\"\"Run OCR on a scanned PDF and return text + confidence score.\"\"\"\n    pages = convert_from_path(pdf_path)\n    text = \"\"\n    confidences = &#91;]\n    for page in pages:\n        data = pytesseract.image_to_data(page, lang=lang, output_type=pytesseract.Output.DICT)\n        text += \" \".join(&#91;t for t in data&#91;\"text\"] if t.strip()]) + \"\\n\"\n        page_conf = &#91;int(c) for c in data&#91;\"conf\"] if c.isdigit()]\n        confidences.extend(page_conf)\n    confidence = sum(confidences) \/ max(len(confidences), 1)\n    return text, confidence\n\ndef save_as_txt(text, output_path):\n    \"\"\"Save extracted text to a .txt file.\"\"\"\n    with open(output_path, \"w\", encoding=\"utf-8\") as f:\n        f.write(text)\n\ndef save_as_searchable_pdf(original_path, text, output_path):\n    \"\"\"Embed OCR text into original PDF\/image to make it searchable.\"\"\"\n    if original_path.lower().endswith(\".pdf\"):\n        pdf_doc = fitz.open(original_path)\n    else:\n        img = Image.open(original_path)\n        temp_pdf_path = output_path.replace(\".pdf\", \"_temp.pdf\")\n        img.save(temp_pdf_path, \"PDF\", resolution=300.0)\n        pdf_doc = fitz.open(temp_pdf_path)\n\n    for page_num, page in enumerate(pdf_doc):\n        page.insert_text((50, 50), text, fontsize=8, overlay=False)\n\n    pdf_doc.save(output_path)\n    pdf_doc.close()\n\ndef upload_to_azure(file_path, connection_string, container_name):\n    \"\"\"Upload file to Azure Blob Storage and return blob URL.\"\"\"\n    blob_service_client = BlobServiceClient.from_connection_string(connection_string)\n    blob_client = blob_service_client.get_blob_client(container=container_name, blob=os.path.basename(file_path))\n    with open(file_path, \"rb\") as data:\n        blob_client.upload_blob(data, overwrite=True)\n    return blob_client.url\n\ndef process_file(file_path, output_format, lang, output_dir, connection_string, container_name):\n    \"\"\"Process a single file and return metadata.\"\"\"\n    os.makedirs(output_dir, exist_ok=True)\n    filename = os.path.basename(file_path)\n    base_name, _ = os.path.splitext(filename)\n\n    if file_path.lower().endswith((\".jpg\", \".jpeg\", \".png\", \".tiff\", \".bmp\")):\n        text, confidence = ocr_image_to_text(file_path, lang)\n    elif file_path.lower().endswith(\".pdf\"):\n        text, confidence = ocr_pdf_to_text(file_path, lang)\n    else:\n        return {\"document_id\": filename, \"error\": \"Unsupported file type\"}\n\n    if output_format == \"txt\":\n        output_file = os.path.join(output_dir, f\"{base_name}.txt\")\n        save_as_txt(text, output_file)\n    else:\n        output_file = os.path.join(output_dir, f\"{base_name}_searchable.pdf\")\n        save_as_searchable_pdf(file_path, text, output_file)\n\n    azure_url = upload_to_azure(output_file, connection_string, container_name)\n\n    return {\n        \"document_id\": filename,\n        \"source_type\": \"image\" if not file_path.lower().endswith(\".pdf\") else \"scanned_pdf\",\n        \"ocr_text\": text,\n        \"confidence_score\": round(confidence, 2),\n        \"output_file\": output_file,\n        \"azure_blob_url\": azure_url\n    }\n\ndef main(input_dir, output_dir, output_format, lang, connection_string, container_name):\n    results = &#91;]\n    for file_name in os\n\ndef main(input_dir, output_dir, output_format, lang, connection_string, container_name):\n    results = &#91;]\n    for file_name in os.listdir(input_dir):\n        file_path = os.path.join(input_dir, file_name)\n        if os.path.isfile(file_path):\n            try:\n                result = process_file(\n                    file_path,\n                    output_format,\n                    lang,\n                    output_dir,\n                    connection_string,\n                    container_name\n                )\n                results.append(result)\n            except Exception as e:\n                results.append({\n                    \"document_id\": file_name,\n                    \"error\": str(e)\n                })\n    # Output results as JSON for OpenWebUI\n    print(json.dumps(results, indent=2))\n\nif __name__ == \"__main__\":\n    if len(sys.argv) &lt; 7:\n        print(\"Usage: python ocr_processor_with_azure.py &lt;input_dir&gt; &lt;output_dir&gt; &lt;output_format&gt; &lt;lang&gt; &lt;azure_connection_string&gt; &lt;azure_container_name&gt;\")\n        sys.exit(1)\n\n    input_dir = sys.argv&#91;1]\n    output_dir = sys.argv&#91;2]\n    output_format = sys.argv&#91;3]\n    lang = sys.argv&#91;4]\n    azure_connection_string = sys.argv&#91;5]\n    azure_container_name = sys.argv&#91;6]\n\n    main(input_dir, output_dir, output_format, lang, azure_connection_string, azure_container_name)\n\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>How It Works<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Iterates through all files<\/strong> in <code>input_dir<\/code>.<\/li>\n\n\n\n<li>Runs OCR on each image or scanned PDF.<\/li>\n\n\n\n<li>Converts to <strong>searchable PDF<\/strong> or <code>.txt<\/code> based on <code>output_format<\/code>.<\/li>\n\n\n\n<li>Uploads processed file to <strong>Azure Blob Storage<\/strong>.<\/li>\n\n\n\n<li>Calculates <strong>OCR confidence score<\/strong>.<\/li>\n\n\n\n<li>Returns structured JSON with:\n<ul class=\"wp-block-list\">\n<li><code>document_id<\/code><\/li>\n\n\n\n<li><code>source_type<\/code><\/li>\n\n\n\n<li><code>ocr_text<\/code><\/li>\n\n\n\n<li><code>confidence_score<\/code><\/li>\n\n\n\n<li><code>output_file<\/code><\/li>\n\n\n\n<li><code>azure_blob_url<\/code><\/li>\n\n\n\n<li><code>error<\/code> (if any)<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>&#x1f4c2; Directory Setup<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">Copy code<code>openwebui\/\n  skills\/\n    ocr_image_to_searchable_with_azure.yaml\n  tools\/\n    ocr_processor_with_azure.py\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>&#x1f4a1; Example Usage in OpenWebUI<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">BashCopy code<code>\/skill OCR Image\/PDF to Searchable PDF\/TXT with Azure Upload \\\n  input_dir=\"\/data\/scanned_docs\" \\\n  output_dir=\"\/data\/processed_docs\" \\\n  output_format=\"pdf\" \\\n  language=\"eng\" \\\n  batch_size=20 \\\n  azure_connection_string=\"DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net\" \\\n  azure_container_name=\"processed-docs\"\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">&#x2705; This now gives you a <strong>fully automated pipeline<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>OCR extraction<\/li>\n\n\n\n<li>Searchable PDF\/TXT creation<\/li>\n\n\n\n<li>Azure Blob upload<\/li>\n\n\n\n<li>Confidence scoring<\/li>\n\n\n\n<li>JSON output for OpenWebUI<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If you want, I can <strong>extend this further<\/strong> so it also:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Writes a <strong>CSV summary report<\/strong> of all processed files.<\/li>\n\n\n\n<li>Supports <strong>multi-threaded OCR<\/strong> for faster processing of thousands of documents.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">That would make it <strong>enterprise-grade<\/strong> for your 2k+ document workflows.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\">You can extract text from images directly in <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/www.google.com\/url?sa=i&amp;source=web&amp;rct=j&amp;url=https:\/\/docs.openwebui.com\/features\/chat-conversations\/rag\/document-extraction\/&amp;ved=2ahUKEwjjkprNraiXAxXikokEHTeKBiMQy_kOegoIAggACAAIChAB&amp;opi=89978449&amp;cd&amp;psig=AOvVaw2doX23sB5VDKO2vzB7KOLd&amp;ust=1791477961058000\">Open WebUI<\/a> by <mark>using vision models or configuring an external content extraction engine like Mistral OCR or Docling<\/mark>. [<a href=\"https:\/\/docs.openwebui.com\/features\/chat-conversations\/rag\/document-extraction\/\">1<\/a>, <a href=\"https:\/\/docs.openwebui.com\/features\/chat-conversations\/rag\/document-extraction\/mistral-ocr\/\">2<\/a>, <a href=\"https:\/\/docs.openwebui.com\/features\/chat-conversations\/rag\/document-extraction\/docling\/\">3<\/a>]<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Methods for Image OCR and Text Extraction<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Multimodal Vision Models<\/strong>: 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.<\/li>\n\n\n\n<li><strong>Admin Document Engines<\/strong>: Navigate to <strong>Admin Panel > Settings > Documents<\/strong> to configure advanced extraction pipelines.<\/li>\n\n\n\n<li><strong>Custom Tools<\/strong>: Implement specialized extraction pipelines by adding custom Python scripts under <strong>Workspace > Tools<\/strong> in your instance. [<a href=\"https:\/\/www.youtube.com\/watch?v=s-I04KS6hmo\">1<\/a>, <a href=\"https:\/\/github.com\/TrueLipstick\/TrueLipstick-pdf-image-ocr-extractor\">2<\/a>, <a href=\"https:\/\/www.reddit.com\/r\/OpenWebUI\/comments\/1keeeyd\/some_help_creating_a_basic_tool_for_ocr\/\">3<\/a>, <a href=\"https:\/\/docs.openwebui.com\/features\/chat-conversations\/rag\/document-extraction\/mistral-ocr\/\">4<\/a>, <a href=\"https:\/\/docs.openwebui.com\/features\/chat-conversations\/rag\/document-extraction\/docling\/\">5<\/a>]<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Are you trying to extract text from images <strong>inside uploaded documents\/PDFs<\/strong> or directly from <strong>standalone image uploads in chat<\/strong>, and which backend model provider (Ollama, OpenAI, Mistral)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>make the pipeline self-contained so it can automatically create the Azure Cognitive Search index if it doesn\u2019t already exist. This way, you can drop the script into a fresh Azure environment, run it, and it will: &#x1f4dc; 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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_regular_price":[],"currency_symbol":[],"pagelayer_contact_templates":[],"_pagelayer_content":"","footnotes":""},"categories":[1],"tags":[],"class_list":["post-129","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"post_slider_layout_featured_media_urls":{"thumbnail":"","post_slider_layout_landscape_large":"","post_slider_layout_portrait_large":"","post_slider_layout_square_large":"","post_slider_layout_landscape":"","post_slider_layout_portrait":"","post_slider_layout_square":"","full":""},"_links":{"self":[{"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/posts\/129","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/comments?post=129"}],"version-history":[{"count":8,"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/posts\/129\/revisions"}],"predecessor-version":[{"id":141,"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/posts\/129\/revisions\/141"}],"wp:attachment":[{"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/media?parent=129"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/categories?post=129"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/roboticsmaestro.com\/ai\/wp-json\/wp\/v2\/tags?post=129"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}